diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index 7c668174a0f..ce62681e4a6 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -254,6 +254,7 @@ RUN if [ -n "${NEMOCLAW_CORPORATE_CA_B64}" ]; then \ # Cross-stage root copies are accepted by Docker's legacy builder and create # one final-image layer while preserving metadata on existing parent paths. +# hadolint ignore=DL3067 COPY --from=hermes-npm-patch-payload / / # The immutable selected base owns the reviewed Hindsight and agent-browser @@ -447,6 +448,7 @@ RUN _hermes_certifi=$(/opt/hermes/.venv/bin/python -c 'import certifi; print(cer ENV HERMES_TELEGRAM_DISABLE_FALLBACK_IPS=1 ENV HERMES_TUI_DIR="/opt/hermes/ui-tui" +# hadolint ignore=DL3067 COPY --from=hermes-agent-payload / / # Managed MCP and ACP require their packaged Hermes client surfaces. A @@ -494,6 +496,7 @@ RUN printf '%s %s\n' \ /opt/nemoclaw-hermes-config/hindsight-lazy-integrity.patch \ && rm /opt/nemoclaw-hermes-config/hindsight-lazy-integrity.patch +# hadolint ignore=DL3067 COPY --from=hermes-runtime-payload / / # Keep the root-owned managed-startup handoff in this image-only layer. The @@ -825,6 +828,7 @@ RUN printf '%s %s\n' \ # The wrapper's shebang pins `/usr/bin/python3 -I` (isolated mode); fail the # build if that absolute path is missing or non-executable so a base-image # upgrade that drops it cannot ship a wrapper that ENOEXECs at runtime. +# hadolint ignore=DL3067 COPY --from=hermes-wrapper-payload / / RUN test -x /usr/bin/python3 \ @@ -958,6 +962,7 @@ RUN if [ "$NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION" = "1" ]; then \ WORKDIR /sandbox RUN test "$(id -u sandbox):$(id -g sandbox):$(pwd)" = "998:999:/sandbox" \ && rm -rf /sandbox/.cache +# hadolint ignore=DL3066 USER sandbox # Set up blueprint for local resolution @@ -979,6 +984,7 @@ RUN /opt/hermes/.venv/bin/python -I \ fi \ && rm -rf /sandbox/.cache +# hadolint ignore=DL3066 USER root # Install the generated policy manifest outside the mutable Hermes home. Python @@ -1070,6 +1076,7 @@ RUN set -eu; \ /opt/hermes/.venv/bin/python -I \ /opt/nemoclaw-hermes-config/image-build-probes.py profile-policy +# hadolint ignore=DL3066 USER sandbox # Prove that the installed dashboard seeder carries every reviewed policy value @@ -1091,6 +1098,7 @@ RUN dashboard_probe=/tmp/nemoclaw-dashboard-policy-probe.yaml \ # Hermes home. Custom images use this same image-owned tree for reviewed # plugins. /sandbox/.hermes/plugins remains mutable state for Hermes' same-UID # topology and is ignored by the identity-proven separated gateway. +# hadolint ignore=DL3066 USER root # hadolint ignore=DL3059 RUN rm -rf /opt/hermes/plugins/nemoclaw \ @@ -1100,6 +1108,7 @@ RUN rm -rf /opt/hermes/plugins/nemoclaw \ && find /opt/hermes/plugins/nemoclaw -type d -exec chmod 0755 {} + \ && find /opt/hermes/plugins/nemoclaw -type f -exec chmod 0444 {} + +# hadolint ignore=DL3066 USER sandbox # Apply messaging render and post-agent-install build-file hooks after agent/plugin installation. @@ -1127,7 +1136,7 @@ ENV HERMES_ENVIRONMENT_HINT="You are running inside an NVIDIA OpenShell sandbox, # The sandbox user can write config; the gateway user can read it via # supplementary sandbox-group membership and create Hermes v0.14 runtime dirs # without being able to remove sticky-protected config files. -# hadolint ignore=DL3002 +# hadolint ignore=DL3002,DL3066 USER root # Flatten stale published base images that still contain the old .hermes-data diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index de144e2f12d..a86fd006194 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -7,10 +7,11 @@ "src/lib/actions/sandbox/mcp-bridge-contracts.ts": 25, "src/lib/actions/sandbox/process-recovery.ts": 26, "src/lib/adapters/docker/index.ts": 42, - "src/lib/adapters/openshell/client.ts": 18, + "src/lib/adapters/openshell/client.ts": 19, "src/lib/adapters/openshell/command-argv.ts": 22, "src/lib/adapters/openshell/resolve.ts": 25, - "src/lib/adapters/openshell/runtime.ts": 52, + "src/lib/adapters/openshell/runtime.ts": 48, + "src/lib/adapters/openshell/sandbox-observer.ts": 35, "src/lib/adapters/openshell/timeouts.ts": 32, "src/lib/agent/defs.ts": 32, "src/lib/cli/branding.ts": 80, @@ -31,7 +32,7 @@ "src/lib/state/onboard-session.ts": 35, "src/lib/state/registry.ts": 96, "src/lib/state/state-root.ts": 21, - "src/lib/subprocess-env.ts": 23, + "src/lib/subprocess-env.ts": 25, "src/lib/validation.ts": 24 } }, @@ -39,24 +40,26 @@ "defaultMax": 20, "maxByFile": { "src/lib/actions/inference-set.ts": 31, - "src/lib/actions/sandbox/connect.ts": 42, + "src/lib/actions/sandbox/connect.ts": 43, "src/lib/actions/sandbox/destroy.ts": 28, - "src/lib/actions/sandbox/doctor.ts": 27, + "src/lib/actions/sandbox/doctor.ts": 28, "src/lib/actions/sandbox/gateway-state.ts": 21, "src/lib/actions/sandbox/status-snapshot.ts": 20, "src/lib/actions/sandbox/policy-channel.ts": 30, - "src/lib/actions/sandbox/process-recovery.ts": 19, + "src/lib/actions/sandbox/process-recovery.ts": 21, "src/lib/actions/sandbox/rebuild-pipeline.ts": 30, "src/lib/actions/sandbox/snapshot.ts": 37, "src/lib/actions/uninstall/run-plan.ts": 25, "src/lib/inference/local.ts": 22, "src/lib/inference/onboard-probes.ts": 21, "src/lib/inference/vllm.ts": 20, - "src/lib/onboard.ts": 191, + "src/lib/onboard.ts": 192, + "src/lib/onboard/sandbox-gpu-create-run-attempt.ts": 21, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/policy/index.ts": 22, "src/lib/sandbox/config.ts": 19, - "src/lib/state/sandbox.ts": 21 + "src/lib/state/sandbox.ts": 21, + "scripts/checks/run-managed-image-openshell-e2e.ts": 21 } }, "allowedCycles": [], diff --git a/docs/manage-sandboxes/manage-messaging-channels.mdx b/docs/manage-sandboxes/manage-messaging-channels.mdx index 298b219a133..472a4133e64 100644 --- a/docs/manage-sandboxes/manage-messaging-channels.mdx +++ b/docs/manage-sandboxes/manage-messaging-channels.mdx @@ -76,13 +76,17 @@ The cleanup targets `/sandbox/.openclaw//`. The cleanup targets `/sandbox/.hermes/platforms//`. -It tries `openshell sandbox exec` and falls back to SSH if the first transport does not produce the success sentinel. +NemoClaw runs the cleanup through `openshell sandbox exec` first. +If OpenShell is unavailable or its outcome is inconclusive, NemoClaw retries the same cleanup through the sandbox's registered local runtime provider unless OpenShell reports cancellation. +NemoClaw permits this retry only because removing the declared paths is idempotent and the success sentinel verifies completion. +A runtime validation or identity refusal stops removal instead of falling through to SSH. +If the sentinel remains absent after any permitted local retry, NemoClaw tries SSH. -For OpenClaw WeChat only, if neither transport succeeds, NemoClaw tries the stopped Docker fallback. -It confirms that the container belongs to the registered sandbox and has one writable Docker volume at `/sandbox`. +For OpenClaw WeChat only, if the sentinel remains absent after those attempts, NemoClaw asks the registered runtime provider to run its distinct stopped-state cleanup. +The provider confirms that the runtime resource belongs to the registered sandbox, is stopped, and has one writable state resource that contains the declared paths. The helper removes only the WeChat state paths declared by the channel manifest. -Only when WeChat appears in neither the messaging plan nor the current OpenShell policy does NemoClaw treat state cleanup as complete without inspecting a volume if the registry entry is missing, the driver is not Docker, or no eligible stopped container exists. +Only when WeChat appears in neither the messaging plan nor the current OpenShell policy does NemoClaw treat state cleanup as complete without inspecting the state resource if the registry entry is missing, the provider does not support stopped-state cleanup, or no eligible stopped runtime resource exists. If the messaging plan or current OpenShell policy still records the channel and NemoClaw cannot confirm cleanup, the command exits nonzero with recovery guidance. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index c0cf6f18812..228825373bc 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2262,7 +2262,15 @@ For QR-paired channels (today: WhatsApp), NemoClaw destructively clears the in-s - OpenClaw: `/sandbox/.openclaw//` (for example `/sandbox/.openclaw/whatsapp/`). - Hermes: `/sandbox/.hermes/platforms//` (for example `/sandbox/.hermes/platforms/whatsapp/`). For WhatsApp, NemoClaw also clears the current Dashboard profile at `/sandbox/.hermes/profiles/dashboard-home/platforms/whatsapp/session/` and the legacy migration source at `/sandbox/.hermes/dashboard-home/platforms/whatsapp/session/`. -The cleanup tries `openshell sandbox exec` first and falls back to SSH if the exec wrapper does not return the success sentinel. If both transports fail (the sandbox is stopped, the gateway is down, or SSH cannot reach it) the command refuses to proceed to the rebuild and asks you to start the sandbox and re-run, so a half-removed state cannot leave stale Baileys auth files behind for the next rebuild to restore. +NemoClaw runs the cleanup through `openshell sandbox exec` first. +If OpenShell is unavailable or its outcome is inconclusive, NemoClaw retries the same cleanup through the sandbox's registered local runtime provider unless OpenShell reports cancellation. +NemoClaw permits this retry only because removing the declared paths is idempotent and the success sentinel verifies completion. +A runtime validation or identity refusal stops removal instead of falling through to SSH. +If the sentinel remains absent after any permitted local retry, NemoClaw tries SSH. +For OpenClaw WeChat only, if the sentinel remains absent after those attempts, NemoClaw asks the registered runtime provider to run its distinct stopped-state cleanup. +If cleanup still fails, the command refuses to rebuild and prints recovery guidance for the reported condition. +Fix that condition, then rerun the command. +This failure prevents the next rebuild from restoring stale channel authentication files. ```bash $$nemoclaw my-assistant channels remove telegram diff --git a/scripts/checks/layer-import-boundaries.mts b/scripts/checks/layer-import-boundaries.mts index 6eec902ba50..58377ca128e 100644 --- a/scripts/checks/layer-import-boundaries.mts +++ b/scripts/checks/layer-import-boundaries.mts @@ -57,6 +57,12 @@ const MANAGED_STATE_ROOT_PROVIDER_MODULES = [ "src/lib/onboard/managed-bootstrap/docker.ts", "src/lib/onboard/managed-bootstrap/podman-runtime.ts", ] as const; +const LEGACY_BUFFERED_EXEC_HELPER = "src/lib/actions/sandbox/exec.ts"; +const INTERACTIVE_EXEC_HELPER_IMPORTERS = new Set([ + "src/lib/actions/sandbox/agent/passthrough-json.ts", + "src/lib/actions/sandbox/agent/passthrough.ts", + "src/lib/actions/sandbox/launch.ts", +]); const MANAGED_AGENT_IDS = new Set(["openclaw", "hermes", "langchain-deepagents-code", "pi"]); function toRepoPath(absPath: string): string { @@ -164,6 +170,25 @@ function collectPreprocessedImportRefs(source: string): ImportRef[] { }); } +function mayContainNamespaceExport(source: string): boolean { + return ( + source.includes("export") && + source.includes("*") && + source.includes("as") && + source.includes("from") + ); +} + +function containsNamespaceExport(sourceFile: ts.SourceFile): boolean { + return sourceFile.statements.some( + (statement) => + ts.isExportDeclaration(statement) && + !statement.isTypeOnly && + statement.exportClause !== undefined && + ts.isNamespaceExport(statement.exportClause), + ); +} + function resolveInternalImport(fromAbsPath: string, specifier: string): string | null { if (!specifier.startsWith(".")) return null; const base = path.resolve(path.dirname(fromAbsPath), specifier); @@ -379,6 +404,165 @@ function checkNoBinLibShimImport( } } +function checkBufferedExecHelperImport( + absPath: string, + repoPath: string, + sourceFile: ts.SourceFile, + violations: Violation[], +): void { + if (repoPath === LEGACY_BUFFERED_EXEC_HELPER || INTERACTIVE_EXEC_HELPER_IMPORTERS.has(repoPath)) { + return; + } + const namespaceImports = new Set(); + const addNamedBindingViolation = (node: ts.Node): void => { + const pos = position(sourceFile, node); + addViolation( + violations, + repoPath, + pos.line, + pos.column, + "buffered-exec-uses-async-executor", + "buffered sandbox execution must use the async command executor instead of buildOpenshellExecArgs", + ); + }; + const isLegacyModuleLoaderCall = (node: ts.Node): node is ts.CallExpression => + ts.isCallExpression(node) && + ((ts.isIdentifier(node.expression) && node.expression.text === "require") || + node.expression.kind === ts.SyntaxKind.ImportKeyword) && + node.arguments.length === 1 && + ts.isStringLiteralLike(node.arguments[0]) && + resolveInternalImport(absPath, node.arguments[0].text) === LEGACY_BUFFERED_EXEC_HELPER; + const unwrapModuleExpression = (node: ts.Expression): ts.Expression => { + let current = node; + while (ts.isParenthesizedExpression(current) || ts.isAwaitExpression(current)) { + current = current.expression; + } + return current; + }; + const staticPropertyName = (node: ts.Node): string | null => { + if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) return node.text; + if (ts.isComputedPropertyName(node) && ts.isStringLiteralLike(node.expression)) { + return node.expression.text; + } + return null; + }; + for (const statement of sourceFile.statements) { + if (ts.isImportDeclaration(statement) && ts.isStringLiteralLike(statement.moduleSpecifier)) { + if ( + resolveInternalImport(absPath, statement.moduleSpecifier.text) !== + LEGACY_BUFFERED_EXEC_HELPER + ) { + continue; + } + const bindings = statement.importClause?.namedBindings; + if (bindings && ts.isNamedImports(bindings)) { + for (const binding of bindings.elements) { + if ((binding.propertyName?.text ?? binding.name.text) !== "buildOpenshellExecArgs") + continue; + addNamedBindingViolation(binding); + } + } else if (bindings && ts.isNamespaceImport(bindings)) { + namespaceImports.add(bindings.name.text); + } + continue; + } + + if ( + ts.isExportDeclaration(statement) && + !statement.isTypeOnly && + statement.moduleSpecifier && + ts.isStringLiteralLike(statement.moduleSpecifier) && + resolveInternalImport(absPath, statement.moduleSpecifier.text) === LEGACY_BUFFERED_EXEC_HELPER + ) { + const bindings = statement.exportClause; + if (!bindings || ts.isNamespaceExport(bindings)) { + addNamedBindingViolation(bindings ?? statement); + continue; + } + for (const binding of bindings.elements) { + if (binding.isTypeOnly) continue; + if ((binding.propertyName?.text ?? binding.name.text) === "buildOpenshellExecArgs") { + addNamedBindingViolation(binding); + } + } + continue; + } + + if ( + ts.isImportEqualsDeclaration(statement) && + ts.isExternalModuleReference(statement.moduleReference) && + statement.moduleReference.expression && + ts.isStringLiteralLike(statement.moduleReference.expression) && + resolveInternalImport(absPath, statement.moduleReference.expression.text) === + LEGACY_BUFFERED_EXEC_HELPER + ) { + namespaceImports.add(statement.name.text); + continue; + } + } + const collectRequireBindings = (node: ts.Node): void => { + if (ts.isVariableDeclaration(node)) { + const initializer = node.initializer; + if (initializer && isLegacyModuleLoaderCall(unwrapModuleExpression(initializer))) { + if (ts.isIdentifier(node.name)) { + namespaceImports.add(node.name.text); + } else if (ts.isObjectBindingPattern(node.name)) { + for (const binding of node.name.elements) { + const importedName = binding.propertyName + ? staticPropertyName(binding.propertyName) + : staticPropertyName(binding.name); + if (importedName === "buildOpenshellExecArgs") { + addNamedBindingViolation(binding); + } + } + } + } + } + ts.forEachChild(node, collectRequireBindings); + }; + collectRequireBindings(sourceFile); + const isLegacyHelperAccess = ( + node: ts.PropertyAccessExpression | ts.ElementAccessExpression, + ): boolean => { + const accessedName = ts.isPropertyAccessExpression(node) + ? node.name.text + : staticPropertyName(node.argumentExpression); + if (accessedName !== "buildOpenshellExecArgs") return false; + const moduleExpression = unwrapModuleExpression(node.expression); + return ( + (ts.isIdentifier(moduleExpression) && namespaceImports.has(moduleExpression.text)) || + isLegacyModuleLoaderCall(moduleExpression) + ); + }; + const visit = (node: ts.Node): void => { + if (ts.isExportAssignment(node)) { + const exported = unwrapModuleExpression(node.expression); + if ( + (ts.isIdentifier(exported) && namespaceImports.has(exported.text)) || + isLegacyModuleLoaderCall(exported) + ) { + addNamedBindingViolation(node); + } + } + if ( + (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + isLegacyHelperAccess(node) + ) { + const pos = position(sourceFile, node); + addViolation( + violations, + repoPath, + pos.line, + pos.column, + "buffered-exec-uses-async-executor", + "buffered sandbox execution must use the async command executor instead of buildOpenshellExecArgs", + ); + } + ts.forEachChild(node, visit); + }; + visit(sourceFile); +} + function checkMessagingManifestFile( absPath: string, repoPath: string, @@ -506,12 +690,35 @@ export function findLayerImportBoundaryViolations(root = SRC_ROOT): Violation[] const messagingManifestFile = isMessagingManifestFile(repoPath); const commandFile = isCommandFile(repoPath); const source = readFileSync(absPath, "utf8"); - if (!domainFile && !actionFile && !adapterFile && !messagingManifestFile && !commandFile) { - checkNoBinLibShimImport(absPath, repoPath, collectPreprocessedImportRefs(source), violations); + const preprocessedImports = collectPreprocessedImportRefs(source); + let parsedImports: ImportRef[] | null = null; + let parsedSourceFile: ts.SourceFile | null = null; + const getParsedSourceFile = (): ts.SourceFile => + (parsedSourceFile ??= sourceFileFor(absPath, source)); + const getParsedImports = (): ImportRef[] => + (parsedImports ??= collectImportRefs(getParsedSourceFile())); + const importsBufferedExecHelper = + repoPath !== LEGACY_BUFFERED_EXEC_HELPER && + !INTERACTIVE_EXEC_HELPER_IMPORTERS.has(repoPath) && + (preprocessedImports.some( + (ref) => resolveInternalImport(absPath, ref.specifier) === LEGACY_BUFFERED_EXEC_HELPER, + ) || + (mayContainNamespaceExport(source) && + containsNamespaceExport(getParsedSourceFile()) && + getParsedImports().some( + (ref) => resolveInternalImport(absPath, ref.specifier) === LEGACY_BUFFERED_EXEC_HELPER, + ))); + const layerFile = + domainFile || actionFile || adapterFile || messagingManifestFile || commandFile; + if (!layerFile && !importsBufferedExecHelper) { + checkNoBinLibShimImport(absPath, repoPath, preprocessedImports, violations); continue; } - const sourceFile = sourceFileFor(absPath, source); - const imports = collectImportRefs(sourceFile); + const sourceFile = getParsedSourceFile(); + if (importsBufferedExecHelper) { + checkBufferedExecHelperImport(absPath, repoPath, sourceFile, violations); + } + const imports = getParsedImports(); checkNoBinLibShimImport(absPath, repoPath, imports, violations); if (domainFile) { checkDomainFile(absPath, repoPath, sourceFile, imports, violations); diff --git a/scripts/checks/run-managed-image-openshell-e2e.ts b/scripts/checks/run-managed-image-openshell-e2e.ts index e9bc66d920a..b25981043ee 100644 --- a/scripts/checks/run-managed-image-openshell-e2e.ts +++ b/scripts/checks/run-managed-image-openshell-e2e.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { resolveAgent } from "../../src/lib/agent/onboard.ts"; import { parseOpenShellSandboxId } from "../../src/lib/adapters/openshell/sandbox-identity.ts"; +import { createCliOpenShellSandboxCommandExecutor } from "../../src/lib/adapters/openshell/sandbox-command-cli.ts"; import { createCliOpenShellSandboxObserverFromRunner } from "../../src/lib/adapters/openshell/sandbox-observer-cli.ts"; import { isValidName, NAME_ALLOWED_FORMAT } from "../../src/lib/name-validation.ts"; import { @@ -67,6 +68,7 @@ import { // and profile policy remains in managed-image-protected-runtime-contract.ts. const MANAGED_AGENTS = new Set(SHIPPED_MANAGED_IMAGE_AGENTS); +const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const MODEL = "nvidia/nemotron-3-ultra-550b-a55b"; const GATEWAY_NAME = "nemoclaw"; const GATEWAY_PORT = 8080; @@ -367,12 +369,7 @@ export function parseManagedImageOpenShellE2eInputs(argv: readonly string[]): In } export function managedImageOpenShellBasePolicyPath(agent: ShippedManagedImageAgent): string { - return path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - "..", - "..", - ...MANAGED_AGENT_BASE_POLICIES[agent], - ); + return path.resolve(REPOSITORY_ROOT, ...MANAGED_AGENT_BASE_POLICIES[agent]); } export interface ManagedImageCommandResult { @@ -784,8 +781,10 @@ function assertProtectedLocalInference( export function failureInjectingAdapter( onboard: OnboardModule, stateRoot: string, + commandExecutor = createCliOpenShellSandboxCommandExecutor({ hostCwd: REPOSITORY_ROOT }), ): ManagedBootstrapAdapter { const adapter = createDockerManagedBootstrapAdapter({ + commandExecutor, runCaptureOpenshell: onboard.runCaptureOpenshell, runOpenshell: onboard.runOpenshell, sleep: onboard.sleepSeconds, @@ -1139,6 +1138,9 @@ async function run> | null = null; try { flow = await runSandboxGpuCreateFlow( @@ -1179,6 +1181,7 @@ async function run - failureInjectingAdapter(onboard!, stateRoot), + failureInjectingAdapter(onboard!, stateRoot, commandExecutor), } : {}), }, diff --git a/src/commands/sandbox/gateway/restart.ts b/src/commands/sandbox/gateway/restart.ts index 44e3c895134..1752ad2d41e 100644 --- a/src/commands/sandbox/gateway/restart.ts +++ b/src/commands/sandbox/gateway/restart.ts @@ -31,7 +31,7 @@ export default class GatewayRestartCliCommand extends NemoClawCommand { public async run(): Promise { const { args, flags } = await this.parse(GatewayRestartCliCommand); - const result = restartSandboxGateway(args.sandboxName, { quiet: flags.quiet === true }); + const result = await restartSandboxGateway(args.sandboxName, { quiet: flags.quiet === true }); if (!result.ok) { this.setExitCode(1); } diff --git a/src/commands/sandbox/sessions.ts b/src/commands/sandbox/sessions.ts index 49cacb183b9..606790caa88 100644 --- a/src/commands/sandbox/sessions.ts +++ b/src/commands/sandbox/sessions.ts @@ -2,11 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { + createSessionsPassthrough, hasSessionsPassthroughHelpToken, printSessionsPassthroughHelp, - runSessionsPassthrough, } from "../../lib/actions/sandbox/sessions/passthrough"; +import { createCliOpenShellSandboxCommandExecutor } from "../../lib/adapters/openshell/sandbox-command-cli"; import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; +import { REPOSITORY_ROOT } from "../../lib/core/repository-root"; + +const runSessionsPassthrough = createSessionsPassthrough({ + sandboxCommandExecutor: createCliOpenShellSandboxCommandExecutor({ hostCwd: REPOSITORY_ROOT }), +}); export default class SandboxSessionsCommand extends NemoClawCommand { static id = "sandbox:sessions"; diff --git a/src/commands/sandbox/sessions/list.ts b/src/commands/sandbox/sessions/list.ts index 7e89c4018ec..496c3a81df8 100644 --- a/src/commands/sandbox/sessions/list.ts +++ b/src/commands/sandbox/sessions/list.ts @@ -2,11 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { + createSessionsPassthrough, hasSessionsPassthroughHelpToken, printSessionsPassthroughHelp, - runSessionsPassthrough, } from "../../../lib/actions/sandbox/sessions/passthrough"; +import { createCliOpenShellSandboxCommandExecutor } from "../../../lib/adapters/openshell/sandbox-command-cli"; import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; +import { REPOSITORY_ROOT } from "../../../lib/core/repository-root"; + +const runSessionsPassthrough = createSessionsPassthrough({ + sandboxCommandExecutor: createCliOpenShellSandboxCommandExecutor({ hostCwd: REPOSITORY_ROOT }), +}); export default class SandboxSessionsListCommand extends NemoClawCommand { static id = "sandbox:sessions:list"; diff --git a/src/lib/actions/inference-set-compatible-provider.test.ts b/src/lib/actions/inference-set-compatible-provider.test.ts index ffba409eee9..456d2d7b7fb 100644 --- a/src/lib/actions/inference-set-compatible-provider.test.ts +++ b/src/lib/actions/inference-set-compatible-provider.test.ts @@ -11,9 +11,7 @@ import { createDeps, } from "./inference-set.test-support"; -type ProbeSandboxRoute = NonNullable< - Parameters[0]["probeSandboxRoute"] ->; +type ProbeSandboxRoute = NonNullable[0]["probeSandboxRoute"]>; const OPENAI_PROFILE_OUTPUT = JSON.stringify({ id: "openai", @@ -305,119 +303,122 @@ describe("runInferenceSet compatible providers", () => { it.each([ ["an HTTPS IP-literal", "https://198.51.100.10/v1", "https://198.51.100.10/v1"], ["a DNS-pinned HTTP", "http://compatible.example/v1", "http://198.51.100.10/v1"], - ])("creates an absent direct compatible provider for %s endpoint (#7725)", async (_kind, endpointUrl, validatedEndpointUrl) => { - let providerCreated = false; - const captureOpenshell = vi.fn((args: string[]) => { - switch (`${args[0]}:${args[1]}`) { - case "provider:profile": - return OPENAI_PROFILE_RESULT; - case "inference:set": - return providerCreated - ? { status: 0, output: "", stdout: "", stderr: "" } - : { - status: 1, - output: "Error: provider 'compatible-endpoint' not found", - stdout: "", - stderr: "Error: provider 'compatible-endpoint' not found", - }; - case "provider:get": { - const output = [ - "Name: compatible-endpoint", - "Id: 11111111-2222-4333-8444-555555555555", - "Type: openai", - "Resource version: 1", - "Credential keys: COMPATIBLE_API_KEY", - "Config keys: OPENAI_BASE_URL", - ].join("\n"); - return providerCreated - ? { status: 0, output, stdout: output, stderr: "" } - : { - status: 1, - output: - "Error: code: 'Some requested entity was not found', message: \"provider not found\"", - stdout: "", - stderr: - "Error: code: 'Some requested entity was not found', message: \"provider not found\"", - }; + ])( + "creates an absent direct compatible provider for %s endpoint (#7725)", + async (_kind, endpointUrl, validatedEndpointUrl) => { + let providerCreated = false; + const captureOpenshell = vi.fn((args: string[]) => { + switch (`${args[0]}:${args[1]}`) { + case "provider:profile": + return OPENAI_PROFILE_RESULT; + case "inference:set": + return providerCreated + ? { status: 0, output: "", stdout: "", stderr: "" } + : { + status: 1, + output: "Error: provider 'compatible-endpoint' not found", + stdout: "", + stderr: "Error: provider 'compatible-endpoint' not found", + }; + case "provider:get": { + const output = [ + "Name: compatible-endpoint", + "Id: 11111111-2222-4333-8444-555555555555", + "Type: openai", + "Resource version: 1", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + ].join("\n"); + return providerCreated + ? { status: 0, output, stdout: output, stderr: "" } + : { + status: 1, + output: + "Error: code: 'Some requested entity was not found', message: \"provider not found\"", + stdout: "", + stderr: + "Error: code: 'Some requested entity was not found', message: \"provider not found\"", + }; + } + case "provider:create": + providerCreated = true; + return { status: 0, output: "", stdout: "", stderr: "" }; + default: + return { status: 0, output: "", stdout: "", stderr: "" }; } - case "provider:create": - providerCreated = true; - return { status: 0, output: "", stdout: "", stderr: "" }; - default: - return { status: 0, output: "", stdout: "", stderr: "" }; - } - }); - const deps = createDeps({ - config: { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } } }, - entry: { - name: "alpha", - agent: "openclaw", - provider: "nvidia-prod", - model: "nvidia/model-a", - }, - session: baseSession({ - provider: "nvidia-prod", - model: "nvidia/model-a", - }), - captureOpenshell, - rewriteConfigUrlsWithDnsPinning: async () => validatedEndpointUrl, - resolveCredentialValue: () => "real-upstream-secret", - }); - - await expect( - runInferenceSet( - { - provider: "compatible-endpoint", - model: "mock-model", - endpointUrl, - credentialEnv: "COMPATIBLE_API_KEY", - inferenceApi: "openai-completions", + }); + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/model-a", }, - deps, - ), - ).resolves.toMatchObject({ - sandboxName: "alpha", - provider: "compatible-endpoint", - model: "mock-model", - }); + session: baseSession({ + provider: "nvidia-prod", + model: "nvidia/model-a", + }), + captureOpenshell, + rewriteConfigUrlsWithDnsPinning: async () => validatedEndpointUrl, + resolveCredentialValue: () => "real-upstream-secret", + }); - const providerCreateIndex = captureOpenshell.mock.calls.findIndex( - ([args]) => args[0] === "provider" && args[1] === "create", - ); - const successfulSetIndex = captureOpenshell.mock.calls.findIndex( - ([args], index) => - index > providerCreateIndex && args[0] === "inference" && args[1] === "set", - ); - expect(providerCreateIndex).toBeGreaterThanOrEqual(0); - expect(successfulSetIndex).toBeGreaterThan(providerCreateIndex); - expect(captureOpenshell.mock.calls[successfulSetIndex][0]).not.toContain("--no-verify"); - expect(captureOpenshell.mock.calls[providerCreateIndex]).toEqual([ - [ - "provider", - "create", - "-g", - "nemoclaw", - "--name", - "compatible-endpoint", - "--type", - "openai", - "--credential", - "COMPATIBLE_API_KEY", - "--config", - `OPENAI_BASE_URL=${validatedEndpointUrl}`, - ], - expect.objectContaining({ - env: { COMPATIBLE_API_KEY: "real-upstream-secret" }, - }), - ]); - expect(deps.calls.updateSandbox.mock.calls.at(-1)).toEqual([ - "alpha", - expect.objectContaining({ + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "mock-model", + endpointUrl, + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + }, + deps, + ), + ).resolves.toMatchObject({ + sandboxName: "alpha", provider: "compatible-endpoint", - endpointUrl: validatedEndpointUrl, - }), - ]); - }); + model: "mock-model", + }); + + const providerCreateIndex = captureOpenshell.mock.calls.findIndex( + ([args]) => args[0] === "provider" && args[1] === "create", + ); + const successfulSetIndex = captureOpenshell.mock.calls.findIndex( + ([args], index) => + index > providerCreateIndex && args[0] === "inference" && args[1] === "set", + ); + expect(providerCreateIndex).toBeGreaterThanOrEqual(0); + expect(successfulSetIndex).toBeGreaterThan(providerCreateIndex); + expect(captureOpenshell.mock.calls[successfulSetIndex][0]).not.toContain("--no-verify"); + expect(captureOpenshell.mock.calls[providerCreateIndex]).toEqual([ + [ + "provider", + "create", + "-g", + "nemoclaw", + "--name", + "compatible-endpoint", + "--type", + "openai", + "--credential", + "COMPATIBLE_API_KEY", + "--config", + `OPENAI_BASE_URL=${validatedEndpointUrl}`, + ], + expect.objectContaining({ + env: { COMPATIBLE_API_KEY: "real-upstream-secret" }, + }), + ]); + expect(deps.calls.updateSandbox.mock.calls.at(-1)).toEqual([ + "alpha", + expect.objectContaining({ + provider: "compatible-endpoint", + endpointUrl: validatedEndpointUrl, + }), + ]); + }, + ); it("stops before route mutation when a newly created provider revision changes (#9806)", async () => { let providerCreated = false; @@ -627,65 +628,64 @@ describe("runInferenceSet compatible providers", () => { recordedEndpointUrl: "http://198.51.100.10/v1", recordedCredentialEnv: "LEGACY_COMPATIBLE_API_KEY", }, - ])("rejects $bindingPart replacement for an existing direct provider (#7725)", async ({ - bindingPart, - recordedEndpointUrl, - recordedCredentialEnv, - }) => { - const captureOpenshell = createCompatibleProviderCapture({ - name: "compatible-endpoint", - type: "openai", - credentialEnv: "COMPATIBLE_API_KEY", - configKey: "OPENAI_BASE_URL", - }); - const deps = createDeps({ - config: { agents: { defaults: { model: { primary: "inference/old-model" } } } }, - entry: { - name: "alpha", - agent: "openclaw", - provider: "compatible-endpoint", - model: "old-model", - endpointUrl: recordedEndpointUrl, - endpointSource: "inference-set", - credentialEnv: recordedCredentialEnv, - preferredInferenceApi: "openai-completions", - }, - session: baseSession({ - provider: "compatible-endpoint", - model: "old-model", - endpointUrl: recordedEndpointUrl, - credentialEnv: recordedCredentialEnv, - preferredInferenceApi: "openai-completions", - }), - captureOpenshell, - rewriteConfigUrlsWithDnsPinning: async () => "http://198.51.100.10/v1", - resolveCredentialValue: () => "replacement-upstream-secret", - }); - - await expect( - runInferenceSet( - { + ])( + "rejects $bindingPart replacement for an existing direct provider (#7725)", + async ({ bindingPart, recordedEndpointUrl, recordedCredentialEnv }) => { + const captureOpenshell = createCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + }); + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/old-model" } } } }, + entry: { + name: "alpha", + agent: "openclaw", provider: "compatible-endpoint", - model: "new-model", - endpointUrl: "http://compatible.example/v1", - credentialEnv: "COMPATIBLE_API_KEY", - inferenceApi: "openai-completions", + model: "old-model", + endpointUrl: recordedEndpointUrl, + endpointSource: "inference-set", + credentialEnv: recordedCredentialEnv, + preferredInferenceApi: "openai-completions", }, - deps, - ), - ).rejects.toThrow( - new RegExp(`Cannot replace existing provider.*binding differs in: ${bindingPart}`), - ); - expect( - captureOpenshell.mock.calls.some( - ([args]) => - (args[0] === "inference" && args[1] === "set") || - (args[0] === "provider" && args[1] === "update"), - ), - ).toBe(false); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); - }); + session: baseSession({ + provider: "compatible-endpoint", + model: "old-model", + endpointUrl: recordedEndpointUrl, + credentialEnv: recordedCredentialEnv, + preferredInferenceApi: "openai-completions", + }), + captureOpenshell, + rewriteConfigUrlsWithDnsPinning: async () => "http://198.51.100.10/v1", + resolveCredentialValue: () => "replacement-upstream-secret", + }); + + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "new-model", + endpointUrl: "http://compatible.example/v1", + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + }, + deps, + ), + ).rejects.toThrow( + new RegExp(`Cannot replace existing provider.*binding differs in: ${bindingPart}`), + ); + expect( + captureOpenshell.mock.calls.some( + ([args]) => + (args[0] === "inference" && args[1] === "set") || + (args[0] === "provider" && args[1] === "update"), + ), + ).toBe(false); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); + }, + ); it("reuses an existing direct provider when its recorded endpoint matches", async () => { const captureOpenshell = createCompatibleProviderCapture({ @@ -1014,7 +1014,7 @@ describe("runInferenceSet compatible providers", () => { ])("does not retry a changed-family %s failure (#9467)", async (_failureClass, httpStatus) => { const { deps, probeSandboxRoute } = await runRejectedCompatibleSwitchScenario({ targetFamily: "anthropic", - probeSandboxRoute: () => ({ + probeSandboxRoute: async () => ({ ok: false as const, detail: `sandbox inference invocation probe returned HTTP ${httpStatus}`, httpStatus, @@ -1031,7 +1031,7 @@ describe("runInferenceSet compatible providers", () => { it("does not retry a target rejection when the API family did not change", async () => { const { deps, probeSandboxRoute } = await runRejectedCompatibleSwitchScenario({ targetFamily: "openai", - probeSandboxRoute: () => ({ + probeSandboxRoute: async () => ({ ok: false as const, detail: "sandbox inference invocation probe returned HTTP 400", httpStatus: 400, @@ -1046,7 +1046,7 @@ describe("runInferenceSet compatible providers", () => { it.each([ [ "returns a rejection", - () => ({ + async () => ({ ok: false, detail: "sandbox inference invocation probe exited with status 7", httpStatus: null, @@ -1055,81 +1055,84 @@ describe("runInferenceSet compatible providers", () => { ], [ "throws", - () => { + async () => { throw new Error("sandbox dial failed"); }, /sandbox inference invocation probe was unavailable: sandbox dial failed.*previous OpenShell inference selection was restored/s, ], - ])("restores the prior route when sandbox-only provider verification %s", async (_failureMode, probeSandboxRoute, expectedError) => { - const captureOpenshell = createCompatibleProviderCapture({ - name: "compatible-anthropic-endpoint", - type: "anthropic", - credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", - configKey: "ANTHROPIC_BASE_URL", - initiallyPresent: false, - }); - const deps = createDeps({ - config: { agents: { defaults: { model: { primary: "inference/old-model" } } } }, - entry: { - name: "alpha", - agent: "openclaw", - provider: "nvidia-prod", - model: "old-model", - }, - session: baseSession({ provider: "nvidia-prod", model: "old-model" }), - captureOpenshell, - probeSandboxRoute, - }); - - await expect( - runInferenceSet( - { - provider: "compatible-anthropic-endpoint", - model: "mock-anthropic-model", - endpointUrl: "http://host.openshell.internal:18767/", - credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", - inferenceApi: "anthropic-messages", + ])( + "restores the prior route when sandbox-only provider verification %s", + async (_failureMode, probeSandboxRoute, expectedError) => { + const captureOpenshell = createCompatibleProviderCapture({ + name: "compatible-anthropic-endpoint", + type: "anthropic", + credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", + configKey: "ANTHROPIC_BASE_URL", + initiallyPresent: false, + }); + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/old-model" } } } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "old-model", }, - deps, - ), - ).rejects.toThrow(expectedError); + session: baseSession({ provider: "nvidia-prod", model: "old-model" }), + captureOpenshell, + probeSandboxRoute, + }); - expect( - captureOpenshell.mock.calls - .filter(([args]) => args[0] === "inference" && args[1] === "set") - .map(([args]) => args), - ).toEqual([ - [ - "inference", - "set", - "-g", - "nemoclaw", - "--provider", - "compatible-anthropic-endpoint", - "--model", - "mock-anthropic-model", - "--no-verify", - ], - [ - "inference", - "set", - "-g", - "nemoclaw", - "--provider", - "nvidia-prod", - "--model", - "old-model", - "--no-verify", - ], - ]); - expect( - captureOpenshell.mock.calls.some( - ([args]) => args[0] === "provider" && args[1] === "delete", - ), - ).toBe(true); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); - }); + await expect( + runInferenceSet( + { + provider: "compatible-anthropic-endpoint", + model: "mock-anthropic-model", + endpointUrl: "http://host.openshell.internal:18767/", + credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", + inferenceApi: "anthropic-messages", + }, + deps, + ), + ).rejects.toThrow(expectedError); + + expect( + captureOpenshell.mock.calls + .filter(([args]) => args[0] === "inference" && args[1] === "set") + .map(([args]) => args), + ).toEqual([ + [ + "inference", + "set", + "-g", + "nemoclaw", + "--provider", + "compatible-anthropic-endpoint", + "--model", + "mock-anthropic-model", + "--no-verify", + ], + [ + "inference", + "set", + "-g", + "nemoclaw", + "--provider", + "nvidia-prod", + "--model", + "old-model", + "--no-verify", + ], + ]); + expect( + captureOpenshell.mock.calls.some( + ([args]) => args[0] === "provider" && args[1] === "delete", + ), + ).toBe(true); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); + }, + ); it("preserves redacted probe diagnostics when restoring the prior route fails", async () => { const providerCapture = createCompatibleProviderCapture({ diff --git a/src/lib/actions/inference-set-gateway-restart.ts b/src/lib/actions/inference-set-gateway-restart.ts index e5e743aa485..10c4499fdfd 100644 --- a/src/lib/actions/inference-set-gateway-restart.ts +++ b/src/lib/actions/inference-set-gateway-restart.ts @@ -112,7 +112,7 @@ export function settleInferenceSetOpenClawPairing( export interface InferenceGatewayRestartDeps { appendAuditEntry: (entry: OperationalAuditEntry) => void; log: (message: string) => void; - restartSandboxGateway: (sandboxName: string) => GatewayRestartResult; + restartSandboxGateway: (sandboxName: string) => Promise; settleOpenClawPairing: ( target: InferenceSetOpenClawPairingTarget, ) => InferenceSetOpenClawPairingResult; @@ -160,7 +160,9 @@ export interface InferenceMutation { // Remove pairing settlement when OpenClaw no longer requires a separate // allowlisted device-scope upgrade after a route change. -export function defaultInferenceGatewayRestart(sandboxName: string): GatewayRestartResult { +export async function defaultInferenceGatewayRestart( + sandboxName: string, +): Promise { const recovery: typeof import("./sandbox/process-recovery") = require("./sandbox/process-recovery"); return recovery.restartSandboxGateway(sandboxName, { quiet: true }); } @@ -256,10 +258,10 @@ export function finalizeInferenceMutation( }; } -export function completeInferencePostCommit( +export async function completeInferencePostCommit( mutation: InferenceMutation, deps: InferenceGatewayRestartDeps, -): void { +): Promise { const { result } = mutation; if (mutation.openClawGatewayRestartRequired) { deps.log( @@ -267,7 +269,7 @@ export function completeInferencePostCommit ); let restartFailure: string | null = null; try { - const restart = deps.restartSandboxGateway(result.sandboxName); + const restart = await deps.restartSandboxGateway(result.sandboxName); if (!restart.ok) restartFailure = restart.failureLayer; } catch { restartFailure = "restart exception"; diff --git a/src/lib/actions/inference-set-https-pin-runtime.test.ts b/src/lib/actions/inference-set-https-pin-runtime.test.ts index 31c7320f69e..c1eeaed3927 100644 --- a/src/lib/actions/inference-set-https-pin-runtime.test.ts +++ b/src/lib/actions/inference-set-https-pin-runtime.test.ts @@ -457,7 +457,7 @@ describe("runInferenceSet HTTPS-pin route credential handoff (#6141)", () => { }), ensureHttpsPinRuntimeAdapter: adapter, captureOpenshell: capture, - probeSandboxRoute: () => ({ + probeSandboxRoute: async () => ({ ok: false, detail: "sandbox inference invocation probe returned HTTP 500", httpStatus: 500, diff --git a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts index e91432bfe64..4542138588e 100644 --- a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts +++ b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts @@ -164,7 +164,7 @@ describe("runInferenceSet OpenClaw gateway restart", () => { credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: "anthropic-messages", }), - restartSandboxGateway: () => ({ + restartSandboxGateway: async () => ({ ok: false, failureLayer: "health timeout", detail: "replacement gateway did not become healthy", diff --git a/src/lib/actions/inference-set-openclaw-pairing.test.ts b/src/lib/actions/inference-set-openclaw-pairing.test.ts index 401bf8fa65d..0cb27f98760 100644 --- a/src/lib/actions/inference-set-openclaw-pairing.test.ts +++ b/src/lib/actions/inference-set-openclaw-pairing.test.ts @@ -171,7 +171,7 @@ describe("settleInferenceSetOpenClawPairing", () => { expect(deps.approveScopeRequest).toHaveBeenCalledOnce(); }); - it("fails closed when required convergence has no pairing target (#9527)", () => { + it("fails closed when required convergence has no pairing target (#9527)", async () => { const appendAuditEntry = vi.fn(); const log = vi.fn(); const settleOpenClawPairing = vi.fn(() => ({ ok: true }) as const); @@ -192,12 +192,12 @@ describe("settleInferenceSetOpenClawPairing", () => { { appendAuditEntry, log }, ); - expect(() => + await expect( completeInferencePostCommit(mutation, { appendAuditEntry, log, restartSandboxGateway: vi.fn( - () => + async () => ({ ok: true, restarted: true, @@ -207,7 +207,7 @@ describe("settleInferenceSetOpenClawPairing", () => { ), settleOpenClawPairing, }), - ).toThrow("OpenClaw gateway pairing did not converge (pairing-target-unavailable)"); + ).rejects.toThrow("OpenClaw gateway pairing did not converge (pairing-target-unavailable)"); expect(settleOpenClawPairing).not.toHaveBeenCalled(); expect(log.mock.calls.flat().join("\n")).not.toContain("Inference route synced"); expect(appendAuditEntry).toHaveBeenCalledWith( diff --git a/src/lib/actions/inference-set-provider.ts b/src/lib/actions/inference-set-provider.ts index 77e30875a48..ced2cbcff24 100644 --- a/src/lib/actions/inference-set-provider.ts +++ b/src/lib/actions/inference-set-provider.ts @@ -43,7 +43,7 @@ export function createDefaultInferenceSetProviderAdapter(): OpenShellProviderAda export type InferenceSetSandboxRouteProbe = ( input: SandboxInferenceInvocationInput, -) => SandboxInferenceInvocationResult; +) => Promise; // OpenShell 0.0.106 refreshes the sandbox route cache every five seconds. // A stale route can still return a valid 2xx response, so wait one complete @@ -55,11 +55,11 @@ export function sleepInferenceSetRouteConvergence(milliseconds: number): Promise return new Promise((resolve) => setTimeout(resolve, milliseconds)); } -export function probeInferenceSetSandboxRoute( +export async function probeInferenceSetSandboxRoute( input: SandboxInferenceInvocationInput, -): SandboxInferenceInvocationResult { +): Promise { const probe: typeof import("./sandbox/inference-invocation-probe") = require("./sandbox/inference-invocation-probe"); - return probe.probeSandboxInferenceInvocation( + return await probe.probeSandboxInferenceInvocation( input, {}, probe.READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index d4331f30bce..5da91ab86a7 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -260,11 +260,11 @@ export function createDeps(options: { revokeHttpsPinRuntimeAdapterRoute: vi.fn( options.revokeHttpsPinRuntimeAdapterRoute ?? (async () => true), ), - probeSandboxRoute: vi.fn(options.probeSandboxRoute ?? (() => ({ ok: true }) as const)), + probeSandboxRoute: vi.fn(options.probeSandboxRoute ?? (async () => ({ ok: true }) as const)), sleep: vi.fn(async () => {}), restartSandboxGateway: vi.fn( options.restartSandboxGateway ?? - ((): ReturnType => ({ + (async (): ReturnType => ({ ok: true, restarted: true, healthPassed: true, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 59512b8a8af..ac65a15aafa 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1226,7 +1226,7 @@ async function runInferenceSetWithoutHostLock( } if (probeDirectSandboxBridge) { - let probe: ReturnType; + let probe: Awaited>; try { probe = await probeInferenceSetSandboxRouteUntilConverged( { @@ -1594,7 +1594,7 @@ export async function runInferenceSet( // Retain the outer sandbox lifecycle lock so another process cannot replace // this sandbox between the committed write, an optional restart, and // device-scope convergence. - completeInferencePostCommit(mutation, deps); + await completeInferencePostCommit(mutation, deps); if (mutation.result.dashboardConverged === false) { throw new InferenceSetError( `Inference route and main Hermes config were updated for '${mutation.result.sandboxName}', ` + diff --git a/src/lib/actions/sandbox/agents/apply.test.ts b/src/lib/actions/sandbox/agents/apply.test.ts index 166b7b5e627..8c148d8142a 100644 --- a/src/lib/actions/sandbox/agents/apply.test.ts +++ b/src/lib/actions/sandbox/agents/apply.test.ts @@ -237,6 +237,70 @@ describe("validateAgentsManifestForApply", () => { }); describe("runAgentsApply", () => { + const getSandboxAgent = () => "openclaw"; + + it("uses typed buffered commands for list, delete, and add", async () => { + const manifestPath = manifestFile( + "typed-roster.yaml", + ["agents:", " - id: alpha", ""].join("\n"), + ); + const runBuffered = vi + .fn() + .mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: '[{"id":"main"},{"id":"obsolete"}]', + stderr: "", + }) + .mockResolvedValue({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: "", + stderr: "", + }); + const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + + try { + await runAgentsApply( + { sandboxName: "my-assistant", manifestPath, yes: true }, + { + ensureLive: async () => undefined, + getSandboxAgent, + commandExecutor: { runBuffered }, + log: () => {}, + }, + ); + } finally { + stdout.mockRestore(); + stderr.mockRestore(); + } + + expect(runBuffered.mock.calls.map(([request]) => request)).toEqual([ + { + sandboxName: "my-assistant", + target: { kind: "selected" }, + command: ["openclaw", "agents", "list", "--json"], + }, + { + sandboxName: "my-assistant", + target: { kind: "selected" }, + command: ["openclaw", "agents", "delete", "obsolete", "--force"], + }, + { + sandboxName: "my-assistant", + target: { kind: "selected" }, + command: [ + "openclaw", + "agents", + "add", + "alpha", + "--non-interactive", + "--workspace", + "/sandbox/.openclaw/workspace-alpha", + ], + }, + ]); + }); + it("invokes add for missing manifest agents and delete for orphans", async () => { const manifestPath = manifestFile( "roster.yaml", @@ -253,12 +317,12 @@ describe("runAgentsApply", () => { ); const log = vi.fn(); const ensureLive = vi.fn(async () => undefined); - const listAgents = vi.fn(() => [{ id: "main" }, { id: "obsolete" }]); - const addAgent = vi.fn(); - const deleteAgent = vi.fn(); + const listAgents = vi.fn(async () => [{ id: "main" }, { id: "obsolete" }]); + const addAgent = vi.fn(async (_sandboxName: string, _id: string) => undefined); + const deleteAgent = vi.fn(async () => undefined); await runAgentsApply( { sandboxName: "my-assistant", manifestPath, yes: true }, - { ensureLive, listAgents, addAgent, deleteAgent, log }, + { ensureLive, getSandboxAgent, listAgents, addAgent, deleteAgent, log }, ); expect(ensureLive).toHaveBeenCalledWith("my-assistant", { allowNonReadyPhase: false }); expect(deleteAgent.mock.calls).toEqual([["my-assistant", "obsolete"]]); @@ -281,13 +345,14 @@ describe("runAgentsApply", () => { ].join("\n"), ); const messages: string[] = []; - const addAgent = vi.fn(); - const deleteAgent = vi.fn(); + const addAgent = vi.fn(async (_sandboxName: string, _id: string) => undefined); + const deleteAgent = vi.fn(async () => undefined); await runAgentsApply( { sandboxName: "my-assistant", manifestPath, yes: true }, { ensureLive: async () => undefined, - listAgents: () => [{ id: "main" }, { id: "alpha" }], + getSandboxAgent, + listAgents: async () => [{ id: "main" }, { id: "alpha" }], addAgent, deleteAgent, log: (message) => messages.push(message), @@ -308,15 +373,16 @@ describe("runAgentsApply", () => { const exit = vi.fn((code: number) => { throw new Error(`exit:${code}`); }); - const addAgent = vi.fn(); + const addAgent = vi.fn(async (_sandboxName: string, _id: string) => undefined); await expect( runAgentsApply( { sandboxName: "my-assistant", manifestPath, nonInteractive: true }, { ensureLive: async () => undefined, - listAgents: () => [{ id: "main" }], + getSandboxAgent, + listAgents: async () => [{ id: "main" }], addAgent, - deleteAgent: vi.fn(), + deleteAgent: vi.fn(async () => undefined), log: () => {}, exit: exit as unknown as (code: number) => never, }, @@ -333,13 +399,14 @@ describe("runAgentsApply", () => { ), ); const messages: string[] = []; - const addAgent = vi.fn(); - const deleteAgent = vi.fn(); + const addAgent = vi.fn(async (_sandboxName: string, _id: string) => undefined); + const deleteAgent = vi.fn(async () => undefined); await runAgentsApply( { sandboxName: "my-assistant", manifestPath, yes: true }, { ensureLive: async () => undefined, - listAgents: () => [{ id: "main" }], + getSandboxAgent, + listAgents: async () => [{ id: "main" }], addAgent, deleteAgent, log: (message) => messages.push(message), @@ -373,14 +440,15 @@ describe("runAgentsApply", () => { throw new Error(`exit:${code}`); }); const messages: string[] = []; - const addAgent = vi.fn(); - const deleteAgent = vi.fn(); + const addAgent = vi.fn(async () => undefined); + const deleteAgent = vi.fn(async () => undefined); await expect( runAgentsApply( { sandboxName: "my-assistant", manifestPath, yes: true }, { ensureLive: async () => undefined, - listAgents: () => [{ id: "main" }], + getSandboxAgent, + listAgents: async () => [{ id: "main" }], addAgent, deleteAgent, log: (message) => messages.push(message), @@ -402,9 +470,9 @@ describe("runAgentsApply", () => { throw new Error(`exit:${code}`); }); const messages: string[] = []; - const addAgent = vi.fn(); - const deleteAgent = vi.fn(); - const listAgents = vi.fn(); + const addAgent = vi.fn(async () => undefined); + const deleteAgent = vi.fn(async () => undefined); + const listAgents = vi.fn(async () => []); await expect( runAgentsApply( { sandboxName: "hermes-sandbox", manifestPath, yes: true }, @@ -431,13 +499,14 @@ describe("runAgentsApply", () => { ["agents:", " - id: alpha", " tools:", " allow: [read]", ""].join("\n"), ); const messages: string[] = []; - const addAgent = vi.fn(); - const deleteAgent = vi.fn(); + const addAgent = vi.fn(async () => undefined); + const deleteAgent = vi.fn(async () => undefined); await runAgentsApply( { sandboxName: "my-assistant", manifestPath }, { ensureLive: async () => undefined, - listAgents: () => [{ id: "main" }, { id: "alpha" }], + getSandboxAgent, + listAgents: async () => [{ id: "main" }, { id: "alpha" }], addAgent, deleteAgent, log: (message) => messages.push(message), diff --git a/src/lib/actions/sandbox/agents/apply.ts b/src/lib/actions/sandbox/agents/apply.ts index 3b5f06f4725..abf8b3bec7b 100644 --- a/src/lib/actions/sandbox/agents/apply.ts +++ b/src/lib/actions/sandbox/agents/apply.ts @@ -1,12 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; - +import { createCliOpenShellSandboxCommandExecutor } from "../../../adapters/openshell/sandbox-command-cli"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../../../adapters/openshell/sandbox-observer"; import { loadAgentsManifest } from "../../../onboard/agents-manifest"; import { isOpenclawAgent } from "../../../onboard/openclaw-otel-policy-presets"; import * as registry from "../../../state/registry"; -import { buildOpenshellExecArgs } from "../exec"; // Lazy-require `ensureLiveSandboxOrExit` because its import chain pulls in // `runner`/`./platform`, which the Vitest TS loader cannot resolve at module @@ -218,9 +218,10 @@ export interface RunAgentsApplyOptions { export interface RunAgentsApplyDeps { ensureLive?: EnsureLive; getSandboxAgent?: (sandboxName: string) => string | null; - listAgents?: (sandboxName: string) => OpenClawAgentEntry[]; - addAgent?: (sandboxName: string, id: string, workspace: string | undefined) => void; - deleteAgent?: (sandboxName: string, id: string) => void; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; + listAgents?: (sandboxName: string) => Promise; + addAgent?: (sandboxName: string, id: string, workspace: string | undefined) => Promise; + deleteAgent?: (sandboxName: string, id: string) => Promise; log?: (message: string) => void; exit?: (code: number) => never; } @@ -272,21 +273,38 @@ export function parseOpenClawAgentsList(output: string): OpenClawAgentEntry[] { }); } -function defaultListAgents(sandboxName: string): OpenClawAgentEntry[] { - const { getOpenshellBinary } = - require("../../../adapters/openshell/runtime") as typeof import("../../../adapters/openshell/runtime"); - const result = spawnSync( - getOpenshellBinary(), - buildOpenshellExecArgs(sandboxName, ["openclaw", "agents", "list", "--json"]), - { stdio: ["ignore", "pipe", "pipe"], encoding: "utf-8" }, - ); - if (result.status !== 0) { - const stderr = String(result.stderr || "").trim(); +async function executeAgentCommand( + executor: OpenShellSandboxBufferedCommandExecutor, + sandboxName: string, + command: readonly string[], +) { + return executor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command, + }); +} + +async function defaultListAgents( + executor: OpenShellSandboxBufferedCommandExecutor, + sandboxName: string, +): Promise { + const result = await executeAgentCommand(executor, sandboxName, [ + "openclaw", + "agents", + "list", + "--json", + ]); + if (result.outcome.kind === "failed") { + throw new Error(`openclaw agents list --json failed: ${result.outcome.error.message}`); + } + if (result.outcome.exitCode !== 0) { + const stderr = result.stderr.trim(); throw new Error( - `openclaw agents list --json failed (exit ${result.status ?? "?"})${stderr ? `: ${stderr}` : ""}`, + `openclaw agents list --json failed (exit ${result.outcome.exitCode})${stderr ? `: ${stderr}` : ""}`, ); } - return parseOpenClawAgentsList(String(result.stdout || "[]")); + return parseOpenClawAgentsList(result.stdout || "[]"); } // OpenClaw flag contract differs by agents verb: @@ -307,29 +325,40 @@ export function buildOpenclawAgentDeleteArgs(id: string): string[] { return ["openclaw", "agents", "delete", id, "--force"]; } -function defaultAddAgent(sandboxName: string, id: string, workspace: string | undefined): void { - const { getOpenshellBinary } = - require("../../../adapters/openshell/runtime") as typeof import("../../../adapters/openshell/runtime"); - const result = spawnSync( - getOpenshellBinary(), - buildOpenshellExecArgs(sandboxName, buildOpenclawAgentAddArgs(id, workspace)), - { stdio: "inherit" }, +async function defaultAddAgent( + executor: OpenShellSandboxBufferedCommandExecutor, + sandboxName: string, + id: string, + workspace: string | undefined, +): Promise { + const result = await executeAgentCommand( + executor, + sandboxName, + buildOpenclawAgentAddArgs(id, workspace), ); - if (result.status !== 0) { - throw new Error(`openclaw agents add ${id} failed (exit ${result.status ?? "?"})`); + process.stdout.write(result.stdout); + process.stderr.write(result.stderr); + if (result.outcome.kind === "failed") { + throw new Error(`openclaw agents add ${id} failed: ${result.outcome.error.message}`); + } + if (result.outcome.exitCode !== 0) { + throw new Error(`openclaw agents add ${id} failed (exit ${result.outcome.exitCode})`); } } -function defaultDeleteAgent(sandboxName: string, id: string): void { - const { getOpenshellBinary } = - require("../../../adapters/openshell/runtime") as typeof import("../../../adapters/openshell/runtime"); - const result = spawnSync( - getOpenshellBinary(), - buildOpenshellExecArgs(sandboxName, buildOpenclawAgentDeleteArgs(id)), - { stdio: "inherit" }, - ); - if (result.status !== 0) { - throw new Error(`openclaw agents delete ${id} failed (exit ${result.status ?? "?"})`); +async function defaultDeleteAgent( + executor: OpenShellSandboxBufferedCommandExecutor, + sandboxName: string, + id: string, +): Promise { + const result = await executeAgentCommand(executor, sandboxName, buildOpenclawAgentDeleteArgs(id)); + process.stdout.write(result.stdout); + process.stderr.write(result.stderr); + if (result.outcome.kind === "failed") { + throw new Error(`openclaw agents delete ${id} failed: ${result.outcome.error.message}`); + } + if (result.outcome.exitCode !== 0) { + throw new Error(`openclaw agents delete ${id} failed (exit ${result.outcome.exitCode})`); } } @@ -341,9 +370,13 @@ export async function runAgentsApply( const exit = deps.exit ?? ((code: number) => process.exit(code)); const ensureLive = deps.ensureLive ?? lazyEnsureLive(); const getSandboxAgent = deps.getSandboxAgent ?? defaultGetSandboxAgent; - const listAgents = deps.listAgents ?? defaultListAgents; - const addAgent = deps.addAgent ?? defaultAddAgent; - const deleteAgent = deps.deleteAgent ?? defaultDeleteAgent; + const commandExecutor = deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor(); + const listAgents = deps.listAgents ?? ((name) => defaultListAgents(commandExecutor, name)); + const addAgent = + deps.addAgent ?? + ((name, id, workspace) => defaultAddAgent(commandExecutor, name, id, workspace)); + const deleteAgent = + deps.deleteAgent ?? ((name, id) => defaultDeleteAgent(commandExecutor, name, id)); await ensureLive(options.sandboxName, { allowNonReadyPhase: false }); @@ -363,7 +396,7 @@ export async function runAgentsApply( log(` Manifest rejected before mutation: ${reason}`); exit(1); } - const currentList = listAgents(options.sandboxName); + const currentList = await listAgents(options.sandboxName); const diff = buildAgentsApplyDiff(currentList, manifest); log(` Sandbox: ${options.sandboxName}`); @@ -401,7 +434,7 @@ export async function runAgentsApply( const toolsAgentIds = findManifestToolsByAgentId(manifest.agents); for (const id of diff.toDelete) { log(` Deleting agent: ${id}`); - deleteAgent(options.sandboxName, id); + await deleteAgent(options.sandboxName, id); } for (const entry of diff.toAdd) { if (toolsAgentIds.has(entry.id)) { @@ -410,7 +443,7 @@ export async function runAgentsApply( ); } log(` Adding agent: ${entry.id}`); - addAgent(options.sandboxName, entry.id, entry.workspace); + await addAgent(options.sandboxName, entry.id, entry.workspace); } log(" Apply complete."); } diff --git a/src/lib/actions/sandbox/channel-status-config-channels.test.ts b/src/lib/actions/sandbox/channel-status-config-channels.test.ts index d05ccb3f73b..1bcc0a495aa 100644 --- a/src/lib/actions/sandbox/channel-status-config-channels.test.ts +++ b/src/lib/actions/sandbox/channel-status-config-channels.test.ts @@ -6,10 +6,22 @@ import type { DiagnosticSignal } from "../../messaging/channels/channel-health"; import { type ExecResult, entry, - makeDeps, + makeDeps as makeSyncDeps, showSandboxChannelStatus, } from "./channel-status.test-helpers"; +function makeDeps(options: Parameters[0]) { + const result = makeSyncDeps(options); + const execSandbox = result.deps.execSandbox; + return { + ...result, + deps: { + ...result.deps, + execSandbox: async (...args: Parameters) => execSandbox(...args), + }, + }; +} + function wrappedSignalsOf(result: unknown): DiagnosticSignal[] { expect(result).toHaveProperty("report"); return (result as { report: { signals: DiagnosticSignal[] } }).report.signals; @@ -340,53 +352,50 @@ describe("showSandboxChannelStatus channel config parsers", () => { ).toBeUndefined(); }); - it.each([ - "../x", - "a/b", - "bad'quote", - 'bad"quote', - "bad\nline", - ])("does not read derived WeChat account files for unsafe accountId %j", async (accountId) => { - const commands: string[] = []; - const { deps } = makeDeps({ - exec: (_sandbox, command) => { - commands.push(command); - return command.includes("/sandbox/.openclaw/openclaw.json") - ? { - status: 0, - stdout: JSON.stringify({ - channels: { - "openclaw-weixin": { - accounts: {}, + it.each(["../x", "a/b", "bad'quote", 'bad"quote', "bad\nline"])( + "does not read derived WeChat account files for unsafe accountId %j", + async (accountId) => { + const commands: string[] = []; + const { deps } = makeDeps({ + exec: (_sandbox, command) => { + commands.push(command); + return command.includes("/sandbox/.openclaw/openclaw.json") + ? { + status: 0, + stdout: JSON.stringify({ + channels: { + "openclaw-weixin": { + accounts: {}, + }, }, - }, - }), - stderr: "", - } - : { status: 1, stdout: "", stderr: "" }; - }, - sandbox: entry(["wechat"], [], { - wechat: [ - { - channelId: "wechat", - inputId: "accountId", - kind: "config", - required: true, - sourceEnv: "WECHAT_ACCOUNT_ID", - statePath: "wechatConfig.accountId", - value: accountId, - }, - ], - }), - appliedPresets: ["wechat"], - }); - await showSandboxChannelStatus("alpha", { - deps, - channel: "wechat", - }); + }), + stderr: "", + } + : { status: 1, stdout: "", stderr: "" }; + }, + sandbox: entry(["wechat"], [], { + wechat: [ + { + channelId: "wechat", + inputId: "accountId", + kind: "config", + required: true, + sourceEnv: "WECHAT_ACCOUNT_ID", + statePath: "wechatConfig.accountId", + value: accountId, + }, + ], + }), + appliedPresets: ["wechat"], + }); + await showSandboxChannelStatus("alpha", { + deps, + channel: "wechat", + }); - expect(commands).toEqual(["head -c 65537 '/sandbox/.openclaw/openclaw.json'"]); - }); + expect(commands).toEqual(["head -c 65537 '/sandbox/.openclaw/openclaw.json'"]); + }, + ); it("compares Hermes WeChat values through rendered WEIXIN env keys", async () => { const { deps } = makeDeps({ diff --git a/src/lib/actions/sandbox/channel-status-config-core.test.ts b/src/lib/actions/sandbox/channel-status-config-core.test.ts index 7bdc5184cfd..44e55c3215b 100644 --- a/src/lib/actions/sandbox/channel-status-config-core.test.ts +++ b/src/lib/actions/sandbox/channel-status-config-core.test.ts @@ -4,12 +4,24 @@ import { describe, expect, it } from "vitest"; import { entry, - makeDeps, + makeDeps as makeSyncDeps, reportSignals, showSandboxChannelStatus, withTelegramProbe, } from "./channel-status.test-helpers"; +function makeDeps(options: Parameters[0]) { + const result = makeSyncDeps(options); + const execSandbox = result.deps.execSandbox; + return { + ...result, + deps: { + ...result.deps, + execSandbox: async (...args: Parameters) => execSandbox(...args), + }, + }; +} + describe("showSandboxChannelStatus config comparison", () => { it("marks rendered config ok when the sandbox config matches the sandbox entry", async () => { const { deps, out_lines } = makeDeps({ diff --git a/src/lib/actions/sandbox/channel-status-config.ts b/src/lib/actions/sandbox/channel-status-config.ts index ef6af42f432..f89d4c9bf2c 100644 --- a/src/lib/actions/sandbox/channel-status-config.ts +++ b/src/lib/actions/sandbox/channel-status-config.ts @@ -38,23 +38,19 @@ type ExecRunner = ( sandboxName: string, command: string, timeoutMs?: number, -) => { - status: number; - stdout: string; - stderr: string; -} | null; +) => Promise<{ status: number; stdout: string; stderr: string } | null>; export type ChannelStatusConfigDeps = { execSandbox: ExecRunner; }; -export function buildConfigStatusSignals( +export async function buildConfigStatusSignals( sandboxName: string, channelName: string, entry: ReturnType, agent: AgentDefinition, deps: ChannelStatusConfigDeps, -): DiagnosticSignal[] { +): Promise { const plan = registry.getMessagingPlanFromEntry(entry); const channelPlan = plan?.channels.find((channel) => channel.channelId === channelName); if (!channelPlan?.configured) return []; @@ -80,7 +76,7 @@ export function buildConfigStatusSignals( ) : []; const sourceReads = parser - ? readConfigSourceValues(sandboxName, renderSources, parser, deps) + ? await readConfigSourceValues(sandboxName, renderSources, parser, deps) : emptyConfigSourceReads(); const configInputs = new Map( channelPlan.inputs @@ -294,17 +290,17 @@ function resolveConfigTarget( return null; } -function readConfigSourceValues( +async function readConfigSourceValues( sandboxName: string, sources: readonly ConfigRenderSource[], parser: RenderedChannelConfigParser, deps: ChannelStatusConfigDeps, -): ConfigSourceReads { +): Promise { const targetReads = new Map(); for (const target of new Set(sources.map((source) => source.resolvedTarget))) { // Targets are resolved only from built-in channel manifests via resolveConfigTarget. // Keep this command path closed to user-provided targets before broadening shellQuote use. - const result = deps.execSandbox( + const result = await deps.execSandbox( sandboxName, `head -c ${CONFIG_STATUS_MAX_SOURCE_BYTES + 1} ${shellQuote(target)}`, CONFIG_STATUS_TIMEOUT_MS, diff --git a/src/lib/actions/sandbox/channel-status-summary.test.ts b/src/lib/actions/sandbox/channel-status-summary.test.ts index 2586839da51..685517b6ecc 100644 --- a/src/lib/actions/sandbox/channel-status-summary.test.ts +++ b/src/lib/actions/sandbox/channel-status-summary.test.ts @@ -4,11 +4,23 @@ import { describe, expect, it, vi } from "vitest"; import { entry, - makeDeps, + makeDeps as makeSyncDeps, showSandboxChannelStatus, withTelegramProbe, } from "./channel-status.test-helpers"; +function makeDeps(options: Parameters[0]) { + const result = makeSyncDeps(options); + const execSandbox = result.deps.execSandbox; + return { + ...result, + deps: { + ...result.deps, + execSandbox: async (...args: Parameters) => execSandbox(...args), + }, + }; +} + describe("showSandboxChannelStatus summary", () => { it("emits a compact all-channel report when no channel is selected", async () => { const commands: string[] = []; diff --git a/src/lib/actions/sandbox/channel-status-telegram-policy.test.ts b/src/lib/actions/sandbox/channel-status-telegram-policy.test.ts index 106b753cb01..25cf6068293 100644 --- a/src/lib/actions/sandbox/channel-status-telegram-policy.test.ts +++ b/src/lib/actions/sandbox/channel-status-telegram-policy.test.ts @@ -4,12 +4,24 @@ import { describe, expect, it, vi } from "vitest"; import { entry, - makeDeps, + makeDeps as makeSyncDeps, reportSignals, showSandboxChannelStatus, withTelegramProbe, } from "./channel-status.test-helpers"; +function makeDeps(options: Parameters[0]) { + const result = makeSyncDeps(options); + const execSandbox = result.deps.execSandbox; + return { + ...result, + deps: { + ...result.deps, + execSandbox: async (...args: Parameters) => execSandbox(...args), + }, + }; +} + describe("showSandboxChannelStatus Telegram group policy", () => { it("uses manifest defaults when no stored config value exists", async () => { const { deps, out_lines } = makeDeps({ @@ -114,6 +126,28 @@ describe("showSandboxChannelStatus Telegram group policy", () => { }); describe("showSandboxChannelStatus Telegram health exit propagation", () => { + it("classifies a rejected sandbox exec as probe_failed", async () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code})`); + }) as never); + const { deps, out_lines } = makeDeps({ + exec: () => ({ status: 0, stdout: "{}", stderr: "" }), + sandbox: entry(["telegram"]), + appliedPresets: ["telegram"], + gatewayPresets: ["telegram"], + }); + deps.execSandbox = vi + .fn() + .mockRejectedValueOnce(new Error("sandbox exec unavailable")) + .mockResolvedValue({ status: 0, stdout: "{}", stderr: "" }); + + await expect(showSandboxChannelStatus("alpha", { deps, channel: "telegram" })).rejects.toThrow( + "process.exit(1)", + ); + exitSpy.mockRestore(); + expect(out_lines.join("\n")).toMatch(/Verdict:.*probe_failed/); + }); + it("exits non-zero in text mode for an unhealthy (unreachable) telegram probe (#6743)", async () => { // The whole point of the probe is a non-zero exit on an unhealthy channel so // automation cannot treat a failed health check as success. Drive an diff --git a/src/lib/actions/sandbox/channel-status.test.ts b/src/lib/actions/sandbox/channel-status.test.ts index aed49b0d89f..654222963db 100644 --- a/src/lib/actions/sandbox/channel-status.test.ts +++ b/src/lib/actions/sandbox/channel-status.test.ts @@ -4,11 +4,23 @@ import { describe, expect, it, vi } from "vitest"; import { entry, - makeDeps, + makeDeps as makeSyncDeps, showSandboxChannelStatus, TELEGRAM_PROBE_UNKNOWN_STDOUT, } from "./channel-status.test-helpers"; +function makeDeps(options: Parameters[0]) { + const result = makeSyncDeps(options); + const execSandbox = result.deps.execSandbox; + return { + ...result, + deps: { + ...result.deps, + execSandbox: async (...args: Parameters) => execSandbox(...args), + }, + }; +} + // The whatsapp status hook now reads OpenClaw's authoritative live status JSON // (`openclaw channels status --channel whatsapp --json`) instead of scraping // shell markers, so these integration tests feed that JSON shape through the @@ -374,7 +386,7 @@ describe("showSandboxChannelStatus (whatsapp)", () => { // bridge and preset until the operator runs `channels start`. The // status command should reflect that rather than probing a torn-down // bridge and reporting failures. - const execSpy = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + const execSpy = vi.fn(async () => ({ status: 0, stdout: "", stderr: "" })); const { deps, out_lines } = makeDeps({ exec: () => ({ status: 0, stdout: "", stderr: "" }), sandbox: entry(["whatsapp"], ["whatsapp"]), @@ -399,7 +411,7 @@ describe("showSandboxChannelStatus (whatsapp)", () => { it("labels a paused telegram channel as paused rather than summary view under --channel (#6887)", async () => { // A probe-capable channel that is paused skips the live probe but keeps the // detailed envelope. The Runtime health signal must reflect the paused state. - const execSpy = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + const execSpy = vi.fn(async () => ({ status: 0, stdout: "", stderr: "" })); const { deps } = makeDeps({ exec: () => ({ status: 0, stdout: "", stderr: "" }), sandbox: entry(["telegram"], ["telegram"]), @@ -541,23 +553,26 @@ describe("showSandboxChannelStatus Slack readiness wait", () => { it.each([ ["openclaw", "channel_paused"], ["hermes", "readiness_not_supported"], - ] as const)("returns the agent-appropriate terminal result for paused %s Slack (#7383)", async (agentName, reason) => { - const { deps, probe, sleep } = slackWaitHarness([{}], { paused: true, agentName }); - - const result = await waitForSlack(deps); - - expect(result && "readiness" in result ? result.readiness : null).toMatchObject({ - state: "terminal", - category: "runtime", - reason, - retryable: false, - attempts: 1, - elapsedMs: 0, - }); - expect(result && (await import("./channel-status")).exitCodeFor(result)).toBe(1); - expect(probe).not.toHaveBeenCalled(); - expect(sleep).not.toHaveBeenCalled(); - }); + ] as const)( + "returns the agent-appropriate terminal result for paused %s Slack (#7383)", + async (agentName, reason) => { + const { deps, probe, sleep } = slackWaitHarness([{}], { paused: true, agentName }); + + const result = await waitForSlack(deps); + + expect(result && "readiness" in result ? result.readiness : null).toMatchObject({ + state: "terminal", + category: "runtime", + reason, + retryable: false, + attempts: 1, + elapsedMs: 0, + }); + expect(result && (await import("./channel-status")).exitCodeFor(result)).toBe(1); + expect(probe).not.toHaveBeenCalled(); + expect(sleep).not.toHaveBeenCalled(); + }, + ); it("bounds every readiness dependency by one wait deadline (#7383)", async () => { const { deps, gatewayPolicy, probe, configRead, sleep } = slackWaitHarness( diff --git a/src/lib/actions/sandbox/channel-status.ts b/src/lib/actions/sandbox/channel-status.ts index f665e6112c4..3a84cd5d94f 100644 --- a/src/lib/actions/sandbox/channel-status.ts +++ b/src/lib/actions/sandbox/channel-status.ts @@ -34,7 +34,7 @@ import { import { createBuiltInMessagingHookRegistry } from "../../messaging/hooks"; import { readChannelHealthOutputs, - runMessagingStatusHooks, + runMessagingStatusHooksAsync, } from "../../messaging/hooks/status-runner"; import * as policies from "../../policy"; import * as registry from "../../state/registry"; @@ -53,11 +53,7 @@ type ExecRunner = ( sandboxName: string, command: string, timeoutMs?: number, -) => { - status: number; - stdout: string; - stderr: string; -} | null; +) => Promise<{ status: number; stdout: string; stderr: string } | null>; type StatusDeps = { loadAgent?: (name: string) => AgentDefinition; @@ -153,12 +149,14 @@ function severityLabel(severity: DiagnosticSeverity): string { } } -function defaultExec( +async function defaultExec( sandboxName: string, command: string, timeoutMs?: number, -): { status: number; stdout: string; stderr: string } | null { - return loadProcessRecovery().executeSandboxExecCommand(sandboxName, command, timeoutMs); +): Promise<{ status: number; stdout: string; stderr: string } | null> { + return loadProcessRecovery().executeSandboxExecCommand(sandboxName, command, timeoutMs, { + localDockerFallbackPolicy: "read-only", + }); } function defaultDeps(deps: StatusDeps | undefined): Required { @@ -293,14 +291,14 @@ export function exitCodeFor(report: ChannelStatusReport): number { return 0; } -function buildBasicChannelReport( +async function buildBasicChannelReport( sandboxName: string, channelName: string, agent: AgentDefinition, deps: Required, diagnostic: MessagingChannelDiagnosticSpec, options: { readonly includeDeepDiagnostics?: boolean; readonly channelPaused?: boolean } = {}, -): ChannelStatusBasicReport { +): Promise { const entry = deps.getSandbox(sandboxName); const enabled = registry.getConfiguredMessagingChannelsFromEntry(entry).includes(channelName); const disabled = registry.getDisabledMessagingChannelsFromEntry(entry).includes(channelName); @@ -331,7 +329,7 @@ function buildBasicChannelReport( : `run \`${CLI_NAME} ${sandboxName} policy add ${policyPresets[0]}\``, }); if (enabled) { - signals.push(...buildConfigStatusSignals(sandboxName, channelName, entry, agent, deps)); + signals.push(...(await buildConfigStatusSignals(sandboxName, channelName, entry, agent, deps))); } if (diagnostic.deepProbe !== undefined) { // Channel has a deep probe this path does not run: the summary view never @@ -418,14 +416,14 @@ function channelHealthStatusHook(channelName: string, agent: AgentDefinition) { // with no breadcrumb producer for the requested agent (e.g. Hermes // telegram), so the caller falls back to the basic report when no health // output is returned. -function runChannelHealthHook( +async function runChannelHealthHook( sandboxName: string, channelName: string, agent: AgentDefinition, deps: Required, diagnostic: MessagingChannelDiagnosticSpec, probeTimeoutMs?: number, -): ChannelHealthReport | undefined { +): Promise { const entry = deps.getSandbox(sandboxName); const channelEnabledInRegistry = registry .getConfiguredMessagingChannelsFromEntry(entry) @@ -445,13 +443,19 @@ function runChannelHealthHook( presetOnGateway = null; } - const results = runMessagingStatusHooks({ + const results = await runMessagingStatusHooksAsync({ agent: agent.name === "hermes" ? "hermes" : "openclaw", channels: new Set([channelName]), currentSandbox: sandboxName, hookRegistry: createBuiltInMessagingHookRegistry({ statusHealth: { - executeSandboxCommand: deps.execSandbox, + executeSandboxCommand: async (...args) => { + try { + return await deps.execSandbox(...args); + } catch { + return null; + } + }, timeoutMs: probeTimeoutMs, }, }), @@ -467,7 +471,7 @@ function runChannelHealthHook( return results.flatMap(readChannelHealthOutputs)[0]; } -function collectChannelReport( +async function collectChannelReport( sandboxName: string, channelName: string, agent: AgentDefinition, @@ -475,7 +479,7 @@ function collectChannelReport( diagnostic: MessagingChannelDiagnosticSpec, hasHealthHook: boolean, deadlineMs?: number, -): ChannelStatusSingleReport { +): Promise { const collectionDeps = deadlineMs === undefined ? deps : withStatusDeadline(deps, deadlineMs); const probeTimeoutMs = deadlineMs === undefined @@ -487,7 +491,7 @@ function collectChannelReport( const channelIsPaused = disabledChannels.has(channelName); const healthReport = hasHealthHook && !channelIsPaused - ? runChannelHealthHook( + ? await runChannelHealthHook( sandboxName, channelName, agent, @@ -497,7 +501,7 @@ function collectChannelReport( ) : undefined; if (!healthReport) { - const basicReport = buildBasicChannelReport( + const basicReport = await buildBasicChannelReport( sandboxName, channelName, agent, @@ -521,7 +525,7 @@ function collectChannelReport( }, }; } - const configSignals = buildConfigStatusSignals( + const configSignals = await buildConfigStatusSignals( sandboxName, channelName, collectionDeps.getSandbox(sandboxName), @@ -548,9 +552,9 @@ function withStatusDeadline(deps: Required, deadlineMs: number): Req const timeoutMs = boundedTimeoutMs(requestedTimeoutMs); return timeoutMs === null ? null : deps.getGatewayPresets(sandboxName, timeoutMs); }, - execSandbox: (sandboxName, command, requestedTimeoutMs) => { + execSandbox: async (sandboxName, command, requestedTimeoutMs) => { const timeoutMs = boundedTimeoutMs(requestedTimeoutMs); - return timeoutMs === null ? null : deps.execSandbox(sandboxName, command, timeoutMs); + return timeoutMs === null ? null : await deps.execSandbox(sandboxName, command, timeoutMs); }, }; } @@ -559,7 +563,7 @@ async function waitForChannelReadiness( sandboxName: string, channelName: string, readinessSupported: boolean, - collect: (deadlineMs?: number) => ChannelStatusSingleReport, + collect: (deadlineMs?: number) => Promise, options: ChannelStatusOptions, deps: Required, ): Promise { @@ -591,7 +595,7 @@ async function waitForChannelReadiness( }; let attempts = 1; - let status = collect(deadlineMs); + let status = await collect(deadlineMs); let lastObserved = readReadiness(status); let elapsedMs = Math.max(0, deps.nowMs() - startedAt); while (lastObserved.state === "waiting" && elapsedMs < timeoutMs) { @@ -599,7 +603,7 @@ async function waitForChannelReadiness( elapsedMs = Math.max(0, deps.nowMs() - startedAt); if (elapsedMs >= timeoutMs) break; attempts += 1; - status = collect(deadlineMs); + status = await collect(deadlineMs); lastObserved = readReadiness(status); elapsedMs = Math.max(0, deps.nowMs() - startedAt); } @@ -657,18 +661,21 @@ export async function showSandboxChannelStatus( const agent = deps.loadAgent(entry.agent || "openclaw"); if (!channelArg) { - const configuredChannels = registry.getConfiguredMessagingChannelsFromEntry(entry); + const channels: ChannelStatusSingleReport[] = []; + for (const channelName of registry.getConfiguredMessagingChannelsFromEntry(entry)) { + const diagnostic = getChannelStatusDiagnostic(channelName); + channels.push( + diagnostic + ? await buildBasicChannelReport(sandboxName, channelName, agent, deps, diagnostic, { + includeDeepDiagnostics: false, + }) + : buildUnknownConfiguredChannelReport(sandboxName, channelName), + ); + } const report: ChannelStatusReport = { schemaVersion: 1, sandbox: sandboxName, - channels: configuredChannels.map((channelName) => { - const diagnostic = getChannelStatusDiagnostic(channelName); - return diagnostic - ? buildBasicChannelReport(sandboxName, channelName, agent, deps, diagnostic, { - includeDeepDiagnostics: false, - }) - : buildUnknownConfiguredChannelReport(sandboxName, channelName); - }), + channels, }; if (!(asJson && quietJson)) { renderReport(report, asJson, deps); @@ -714,7 +721,7 @@ export async function showSandboxChannelStatus( options, deps, ) - : collect(); + : await collect(); if (!(asJson && quietJson)) { renderReport(report, asJson, deps); diff --git a/src/lib/actions/sandbox/connect-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index 586a9079a69..fc73ebf4a7e 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -8,47 +8,71 @@ import { createConnectHarness, requireDist, } from "../../../../test/support/connect-flow-test-harness"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandRequest, +} from "../../adapters/openshell/sandbox-command"; + +function completedBufferedCommand( + stdout: string, + exitCode = 0, +): OpenShellSandboxBufferedCommandCompletion { + return { + outcome: { kind: "completed", exitCode }, + stdout, + stderr: "", + }; +} -function captureInferenceRouteThenDrift( +function runInferenceRouteThenDrift( harness: ReturnType, -): (args: unknown) => { status: number; output: string; stderr?: string } { - return (args: unknown) => { - const argv = Array.isArray(args) ? args : []; - switch (argv.slice(0, 2).join("\0")) { - case "inference\0get": - harness.registryEntries[0]!.model = "changed-model"; - return { - status: 0, - output: "Gateway inference:\n Provider: ollama-local\n Model: qwen3-vl:4b\n", - }; - case "sandbox\0exec": - return { status: 0, output: "OK 200", stderr: "" }; - default: - return { status: 0, output: "alpha Ready" }; - } +): ( + request: OpenShellSandboxBufferedCommandRequest, +) => Promise { + return async (request) => { + expect(request.command.join(" ")).toContain("inference.local/v1/models"); + harness.registryEntries[0]!.model = "changed-model"; + return completedBufferedCommand("OK 200"); }; } -function captureInferenceRouteThenDriftLiveIdentity( +function runInferenceRouteThenDriftLiveIdentity( harness: ReturnType, -): (args: unknown) => { status: number; output: string; stderr?: string } { - return (args: unknown) => { - const argv = Array.isArray(args) ? args : []; - switch (argv.slice(0, 2).join("\0")) { - case "inference\0get": - harness.registryEntries[0]!.lifecycleLiveIdentityFingerprint = "0".repeat(64); - return { - status: 0, - output: "Gateway inference:\n Provider: ollama-local\n Model: qwen3-vl:4b\n", - }; - case "sandbox\0exec": - return { status: 0, output: "OK 200", stderr: "" }; - default: - return { status: 0, output: "alpha Ready" }; - } +): ( + request: OpenShellSandboxBufferedCommandRequest, +) => Promise { + return async (request) => { + expect(request.command.join(" ")).toContain("inference.local/v1/models"); + harness.registryEntries[0]!.lifecycleLiveIdentityFingerprint = "0".repeat(64); + return completedBufferedCommand("OK 200"); }; } +function awaitHermesRouteVerification(harness: ReturnType): void { + harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation((async (input: { + verifyRoute: () => Promise; + prepareProbeDependency?: () => { release: () => void }; + }) => { + await input.verifyRoute(); + input.prepareProbeDependency?.().release(); + return "reused"; + }) as never); +} + +function configureAlignedInferenceGet(harness: ReturnType): void { + const capture = harness.captureOpenshellSpy.getMockImplementation()!; + harness.captureOpenshellSpy.mockImplementation(((args: unknown, options: unknown) => { + const argv = Array.isArray(args) ? args.map(String) : []; + return argv[0] === "inference" && argv[1] === "get" + ? { + status: 0, + output: + "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + } + : capture(args, options); + }) as never); +} + describe("connectSandbox flow", () => { let exitSpy: MockInstance; const originalStdinIsTty = process.stdin.isTTY; @@ -368,27 +392,23 @@ describe("connectSandbox flow", () => { await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(0)"); - expect(harness.captureOpenshellSpy).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "--name", - "alpha", - "--no-tty", - "--env", - "HOME=/usr/local/lib/nemoclaw", - "--env", - "BASH_ENV=", - "--env", - "ENV=", - "--", + expect(harness.sandboxRunBufferedSpy).toHaveBeenCalledWith({ + command: [ "/usr/local/lib/nemoclaw/dcode-managed-exec", "/bin/sh", "-c", expect.stringContaining("/usr/bin/curl"), ], - expect.objectContaining({ ignoreError: true }), - ); + sandboxEnvironment: { + BASH_ENV: "", + ENV: "", + HOME: "/usr/local/lib/nemoclaw", + }, + sandboxName: "alpha", + target: { kind: "selected" }, + timeoutMilliseconds: expect.any(Number), + tty: false, + }); }); it.each([401, 403, 404])( @@ -469,20 +489,12 @@ describe("connectSandbox flow", () => { model: "nvidia/nemotron-3-super-120b-a12b", }, }); - harness.captureOpenshellSpy - .mockReturnValueOnce({ status: 0, output: "alpha Ready" }) - .mockReturnValueOnce({ - status: 0, - output: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", - }) - .mockImplementationOnce(() => { - throw new Error("sandbox exec transport failed"); - }); + configureAlignedInferenceGet(harness); + harness.sandboxRunBufferedSpy.mockRejectedValueOnce(new Error("sandbox exec transport failed")); await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(1)"); - expect(JSON.stringify(harness.captureOpenshellSpy.mock.calls[2]?.[0])).toContain( + expect(JSON.stringify(harness.sandboxRunBufferedSpy.mock.calls[0]?.[0])).toContain( "inference.local/v1/models", ); expect(harness.applyVmDnsMonkeypatchSpy).not.toHaveBeenCalled(); @@ -493,35 +505,29 @@ describe("connectSandbox flow", () => { ["sandbox", "connect", "alpha"], expect.any(Object), ); - const errorOutput = harness.errorSpy.mock.calls.flat().join("\n"); - expect(errorOutput).toContain("did not return a trusted result"); - expect(errorOutput).toContain("Last probe: sandbox exec transport failed"); - expect(errorOutput).not.toContain("after DNS and route repair"); expect(exitSpy).toHaveBeenCalledWith(1); }); it("fails closed without repair when the route probe transport times out (#6192)", async () => { - const timeoutError = Object.assign(new Error("sandbox exec timed out"), { - code: "ETIMEDOUT", - }); const harness = createConnectHarness({ registryEntry: { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }, }); - harness.captureOpenshellSpy - .mockReturnValueOnce({ status: 0, output: "alpha Ready" }) - .mockReturnValueOnce({ - status: 0, - output: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", - }) - .mockReturnValueOnce({ status: null, output: "", error: timeoutError }); + configureAlignedInferenceGet(harness); + harness.sandboxRunBufferedSpy.mockResolvedValueOnce({ + outcome: { + kind: "failed", + error: { kind: "timeout", message: "sandbox exec timed out" }, + }, + stdout: "", + stderr: "", + }); await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(1)"); - expect(JSON.stringify(harness.captureOpenshellSpy.mock.calls[2]?.[0])).toContain( + expect(JSON.stringify(harness.sandboxRunBufferedSpy.mock.calls[0]?.[0])).toContain( "inference.local/v1/models", ); expect(harness.applyVmDnsMonkeypatchSpy).not.toHaveBeenCalled(); @@ -546,17 +552,10 @@ describe("connectSandbox flow", () => { model: "nvidia/nemotron-3-super-120b-a12b", }, }); - harness.captureOpenshellSpy - .mockReturnValueOnce({ status: 0, output: "alpha Ready" }) - .mockReturnValueOnce({ - status: 0, - output: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", - }) - .mockReturnValueOnce({ - status: 0, - output: "UNAVAILABLE OpenShell CA bundle missing or unreadable", - }); + configureAlignedInferenceGet(harness); + harness.sandboxRunBufferedSpy.mockResolvedValueOnce( + completedBufferedCommand("UNAVAILABLE OpenShell CA bundle missing or unreadable", 1), + ); await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(1)"); @@ -1058,6 +1057,7 @@ describe("connectSandbox flow", () => { portableReceiptDisposition: { kind: "hermes", phase: "active" }, portableRecoveryResult: { kind: "recovered" }, }); + awaitHermesRouteVerification(harness); await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); @@ -1142,6 +1142,7 @@ describe("connectSandbox flow", () => { ? { inferenceProbeResponses: [...routeOptions.inferenceProbeResponses] } : {}), }); + awaitHermesRouteVerification(harness); await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( "process.exit(1)", @@ -1166,7 +1167,8 @@ describe("connectSandbox flow", () => { portableReceiptDisposition: { kind: "hermes", phase: "active" }, portableRecoveryResult: { kind: "already-running" }, }); - harness.captureResolvedOpenshellSpy.mockImplementation(captureInferenceRouteThenDrift(harness)); + awaitHermesRouteVerification(harness); + harness.sandboxRunBufferedSpy.mockImplementation(runInferenceRouteThenDrift(harness)); await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( "process.exit(1)", @@ -1182,8 +1184,9 @@ describe("connectSandbox flow", () => { portableReceiptDisposition: { kind: "hermes", phase: "active" }, portableRecoveryResult: { kind: "already-running" }, }); - harness.captureResolvedOpenshellSpy.mockImplementation( - captureInferenceRouteThenDriftLiveIdentity(harness), + awaitHermesRouteVerification(harness); + harness.sandboxRunBufferedSpy.mockImplementation( + runInferenceRouteThenDriftLiveIdentity(harness), ); await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( @@ -1459,7 +1462,7 @@ describe("connectSandbox flow", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it("keeps a direct recovery failure detail separate from an earlier callback layer", () => { + it("keeps a direct recovery failure detail separate from an earlier callback layer", async () => { const harness = createConnectHarness(); harness.checkAndRecoverSpy.mockImplementation( ( @@ -1480,7 +1483,7 @@ describe("connectSandbox flow", () => { }, ); - expect(harness.restoreSandboxStartupState("alpha")).toMatchObject({ + await expect(harness.restoreSandboxStartupState("alpha")).resolves.toMatchObject({ recoveryFailureDetail: "the managed supervisor health check for the recreated sandbox did not pass", recoveryFailureLayer: null, diff --git a/src/lib/actions/sandbox/connect-hermes-accepted-readiness.test.ts b/src/lib/actions/sandbox/connect-hermes-accepted-readiness.test.ts index 9d236aa9d4d..c2d454a760a 100644 --- a/src/lib/actions/sandbox/connect-hermes-accepted-readiness.test.ts +++ b/src/lib/actions/sandbox/connect-hermes-accepted-readiness.test.ts @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; import { createConnectHarness } from "../../../../test/support/connect-flow-test-harness"; +import type { OpenShellSandboxBufferedCommandRequest } from "../../adapters/openshell/sandbox-command"; import { HermesPortableForwardRecoveryError } from "./probe/hermes-portable-forward-recovery"; const originalStdoutIsTty = process.stdout.isTTY; @@ -73,7 +74,7 @@ function missingHermesHarness( lifecycleLiveIdentityFingerprint: "f".repeat(64), hostLocalInferenceReceipt: "exact-receipt\n", } as never; - return createConnectHarness({ + const harness = createConnectHarness({ agentName: "hermes", sessionAgent: { name: "hermes" }, registryEntry: entry, @@ -90,6 +91,15 @@ function missingHermesHarness( recoveryBlocked: false, }, }); + harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation((async (input: { + verifyRoute: () => Promise; + prepareProbeDependency?: () => { release: () => void }; + }) => { + await input.verifyRoute(); + input.prepareProbeDependency?.().release(); + return "reused"; + }) as never); + return harness; } describe("Hermes accepted launch-readiness probe", () => { @@ -693,34 +703,50 @@ describe("Hermes accepted launch-readiness probe", () => { status: 0, output: "Name: alpha\nId: sandbox-generation-1\nPhase: Ready\n", } as never) - .mockImplementationOnce(((args: unknown) => { - const argv = Array.isArray(args) ? args.map(String) : []; - const marker = argv.join(" ").match(/__NEMOCLAW_SANDBOX_EXEC_STARTED___[0-9a-f]{32}/u)?.[0]; - return { status: 0, output: `${marker ?? "missing-marker"}\nRUNNING` }; - }) as never) - .mockReturnValueOnce({ status: 0, output: "OK 200" } as never) .mockReturnValueOnce({ status: 0, output: "SANDBOX BIND PORT PID STATUS\nalpha 127.0.0.1 18789 12345 running", } as never); + const captureAuthorityDeltas: number[] = []; + const bufferedAuthorityDeltas: number[] = []; + const bufferedObservationRequests: OpenShellSandboxBufferedCommandRequest[] = []; + let boundRunBufferedSpy: MockInstance | null = null; harness.inspectLaunchReadinessSpy.mockImplementationOnce(async (_sandboxName, deps) => { + const commandExecutor = deps.commandExecutor!; + const runBuffered = commandExecutor.runBuffered.bind(commandExecutor); + boundRunBufferedSpy = vi + .spyOn(commandExecutor, "runBuffered") + .mockImplementation((request) => runBuffered(request)); const authorityCalls = () => harness.assertHermesPortableOperatingCommandCurrentSpy.mock.calls.length; - const assertBoundObservation = async (observe: () => unknown | Promise) => { + const assertBoundCaptureObservation = async (observe: () => unknown | Promise) => { const before = authorityCalls(); await observe(); - expect(authorityCalls() - before).toBe(2); + captureAuthorityDeltas.push(authorityCalls() - before); }; - await assertBoundObservation(() => deps.capture?.(["policy", "get", "-g", "nemoclaw"])); - await assertBoundObservation(() => + const assertBoundBufferedObservation = async (observe: () => unknown | Promise) => { + const authorityBefore = authorityCalls(); + const before = boundRunBufferedSpy!.mock.calls.length; + await observe(); + bufferedAuthorityDeltas.push(authorityCalls() - authorityBefore); + bufferedObservationRequests.push( + ...boundRunBufferedSpy!.mock.calls + .slice(before) + .map(([request]) => request as OpenShellSandboxBufferedCommandRequest), + ); + }; + await assertBoundCaptureObservation(() => + deps.capture?.(["policy", "get", "-g", "nemoclaw"]), + ); + await assertBoundCaptureObservation(() => deps.observeSandbox?.({ sandboxName: "alpha", gatewayName: "nemoclaw", gatewayPort: 18789, }), ); - await assertBoundObservation(() => deps.gatewayHealth?.("alpha", "nemoclaw")); - await assertBoundObservation(() => + await assertBoundBufferedObservation(() => deps.gatewayHealth?.("alpha", "nemoclaw")); + await assertBoundBufferedObservation(() => deps.inferenceProbe?.("alpha", { name: "hermes" } as never, "nemoclaw"), ); return { @@ -734,7 +760,23 @@ describe("Hermes accepted launch-readiness probe", () => { await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); expect(harness.captureOpenshellSpy).not.toHaveBeenCalled(); - expect(harness.captureResolvedOpenshellSpy).toHaveBeenCalledTimes(5); + expect(captureAuthorityDeltas).toEqual([2, 2]); + expect(bufferedAuthorityDeltas).toEqual([2, 2]); + expect(bufferedObservationRequests).toHaveLength(2); + expect(bufferedObservationRequests).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw" }, + }), + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw" }, + }), + ]), + ); + expect(harness.captureResolvedOpenshellSpy).toHaveBeenCalledTimes(3); + expect(boundRunBufferedSpy).toHaveBeenCalledTimes(2); const exactOptions = { env: { HOME: "/home/test", @@ -747,8 +789,6 @@ describe("Hermes accepted launch-readiness probe", () => { expect(harness.captureResolvedOpenshellSpy.mock.calls[0]?.[1]).toMatchObject(exactOptions); expect(harness.captureResolvedOpenshellSpy.mock.calls[1]?.[1]).toMatchObject(exactOptions); expect(harness.captureResolvedOpenshellSpy.mock.calls[2]?.[1]).toMatchObject(exactOptions); - expect(harness.captureResolvedOpenshellSpy.mock.calls[3]?.[1]).toMatchObject(exactOptions); - expect(harness.captureResolvedOpenshellSpy.mock.calls[4]?.[1]).toMatchObject(exactOptions); }); it.each(["executable", "socket"])( diff --git a/src/lib/actions/sandbox/connect-hermes-portable-inference-recovery-errors.test.ts b/src/lib/actions/sandbox/connect-hermes-portable-inference-recovery-errors.test.ts index e0da03809d7..ea30eff69c7 100644 --- a/src/lib/actions/sandbox/connect-hermes-portable-inference-recovery-errors.test.ts +++ b/src/lib/actions/sandbox/connect-hermes-portable-inference-recovery-errors.test.ts @@ -89,11 +89,12 @@ describe("Hermes Portable connect recovery errors", () => { ["inference", "get", "-g", "nemoclaw"], expect.objectContaining({ openshellBinary: "/usr/bin/openshell" }), ); - expect( - harness.captureResolvedOpenshellSpy.mock.calls.some( - ([args]) => Array.isArray(args) && args[0] === "sandbox" && args[1] === "exec", - ), - ).toBe(true); + expect(harness.sandboxRunBufferedSpy).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw" }, + }), + ); expect(harness.publishLaunchReadinessSpy).toHaveBeenCalledOnce(); }); diff --git a/src/lib/actions/sandbox/connect-inference-route-probe.test.ts b/src/lib/actions/sandbox/connect-inference-route-probe.test.ts index 55fedf1c3d3..be5b150ebcd 100644 --- a/src/lib/actions/sandbox/connect-inference-route-probe.test.ts +++ b/src/lib/actions/sandbox/connect-inference-route-probe.test.ts @@ -8,7 +8,7 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { - buildSandboxInferenceRouteProbeArgs, + buildSandboxInferenceRouteProbeRequest, classifyInferenceRouteFailureLabel, DCODE_MANAGED_EXEC_LAUNCHER, DCODE_MANAGED_EXEC_MISSING_DETAIL, @@ -17,66 +17,66 @@ import { parseSandboxInferenceRouteProbeResult, } from "./connect-inference-route-probe"; -describe("sandbox connect inference route probe argv", () => { +describe("sandbox connect inference route probe request", () => { it("uses the managed DCode proxy boundary without adding a login shell (#6191)", () => { - const args = buildSandboxInferenceRouteProbeArgs("deep-code", { - name: "langchain-deepagents-code", - }); - - expect(args.slice(0, 15)).toEqual([ - "sandbox", - "exec", - "--name", + const request = buildSandboxInferenceRouteProbeRequest( "deep-code", - "--no-tty", - "--env", - "HOME=/usr/local/lib/nemoclaw", - "--env", - "BASH_ENV=", - "--env", - "ENV=", - "--", + { name: "langchain-deepagents-code" }, + undefined, + 9000, + ); + + expect(request).toMatchObject({ + sandboxName: "deep-code", + target: { kind: "selected" }, + tty: false, + timeoutMilliseconds: 9000, + sandboxEnvironment: { BASH_ENV: "", ENV: "", HOME: "/usr/local/lib/nemoclaw" }, + }); + expect(request.command).toEqual([ "/usr/local/lib/nemoclaw/dcode-managed-exec", "/bin/sh", "-c", - ]); - expect(args.at(-1)).toContain("https://inference.local/v1/models"); - expect(args).not.toContain("bash"); - expect(args.join(" ")).not.toContain("3>&1"); - expect(args.join(" ")).not.toContain("/tmp/nemoclaw-proxy-env.sh"); - expect(args.every((arg) => !/[\r\n]/.test(arg))).toBe(true); - }); - - it.each([ - null, - { name: "openclaw" }, - { name: "hermes" }, - ])("preserves the plain sh probe for non-dcode agents (%j)", (agent) => { - expect(buildSandboxInferenceRouteProbeArgs("alpha", agent)).toEqual([ - "sandbox", - "exec", - "--name", - "alpha", - "--", - "sh", - "-c", INFERENCE_ROUTE_PROBE_SCRIPT, ]); + expect(request.command.at(-1)).toContain("https://inference.local/v1/models"); + expect(request.command).not.toContain("bash"); + expect(request.command.join(" ")).not.toContain("3>&1"); + expect(request.command.join(" ")).not.toContain("/tmp/nemoclaw-proxy-env.sh"); }); - it.each([ - null, - { name: "hermes" }, - { name: "langchain-deepagents-code" }, - ])("pins the probe to the owning OpenShell gateway for agent %j (#8942)", (agent) => { - expect( - buildSandboxInferenceRouteProbeArgs("alpha", agent, "nemoclaw-8091").slice(0, 7), - ).toEqual(["sandbox", "exec", "--name", "alpha", "-g", "nemoclaw-8091", expect.any(String)]); - }); + it.each([null, { name: "openclaw" }, { name: "hermes" }])( + "preserves the plain sh probe for non-dcode agents (%j)", + (agent) => { + expect(buildSandboxInferenceRouteProbeRequest("alpha", agent, undefined, 9000)).toEqual({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["sh", "-c", INFERENCE_ROUTE_PROBE_SCRIPT], + timeoutMilliseconds: 9000, + }); + }, + ); + + it.each([null, { name: "hermes" }, { name: "langchain-deepagents-code" }])( + "pins the probe to the owning OpenShell gateway for agent %j (#8942)", + (agent) => { + expect( + buildSandboxInferenceRouteProbeRequest("alpha", agent, "nemoclaw-8091", 9000), + ).toMatchObject({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw-8091" }, + }); + }, + ); it("verifies the route with OpenShell's CA and discards the response (#6192)", () => { - const args = buildSandboxInferenceRouteProbeArgs("alpha", { name: "openclaw" }); - const script = args.at(-1) ?? ""; + const request = buildSandboxInferenceRouteProbeRequest( + "alpha", + { name: "openclaw" }, + undefined, + 9000, + ); + const script = request.command.at(-1) ?? ""; expect(script).toContain("/usr/bin/curl -q -s -o /dev/null"); expect(script).toContain('CA_BUNDLE="${CURL_CA_BUNDLE:-${SSL_CERT_FILE:-}}"'); @@ -106,66 +106,67 @@ describe("sandbox connect inference route probe argv", () => { ).toMatchObject({ healthy: false, broken: false, httpStatus: 0 }); }); - it.each([ - "OK 200", - "BROKEN 503", - ])("managed launcher does not run hostile DCode startup or curl config for a %s spoof (#6192)", (spoof) => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-probe-")); - const profileMarker = path.join(home, "profile-ran"); - try { - const caBundle = path.join(home, "openshell-ca.pem"); - const profile = path.join(home, ".bash_profile"); - const launcher = path.join(home, "nemoclaw-start"); - const curlConfigMarker = path.join(home, "curl-config-ran"); - fs.writeFileSync(caBundle, "test CA boundary", "utf8"); - fs.writeFileSync( - profile, - `printf '%s' ${JSON.stringify(spoof)} >&3; printf ran > ${JSON.stringify(profileMarker)}; exit 0`, - ); - fs.writeFileSync( - path.join(home, ".curlrc"), - `trace-ascii = ${JSON.stringify(curlConfigMarker)}\n`, - ); - fs.writeFileSync(launcher, '#!/bin/bash -p\nset -eu\nunset BASH_ENV ENV\nexec "$@"\n', { - mode: 0o755, - }); - const args = buildSandboxInferenceRouteProbeArgs("deep-code", { - name: "langchain-deepagents-code", - }); - const delimiter = args.indexOf("--"); - expect(delimiter).toBeGreaterThan(0); - const command = args.slice(delimiter + 1); - command[0] = launcher; + it.each(["OK 200", "BROKEN 503"])( + "managed launcher does not run hostile DCode startup or curl config for a %s spoof (#6192)", + (spoof) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-probe-")); + const profileMarker = path.join(home, "profile-ran"); + try { + const caBundle = path.join(home, "openshell-ca.pem"); + const profile = path.join(home, ".bash_profile"); + const launcher = path.join(home, "nemoclaw-start"); + const curlConfigMarker = path.join(home, "curl-config-ran"); + fs.writeFileSync(caBundle, "test CA boundary", "utf8"); + fs.writeFileSync( + profile, + `printf '%s' ${JSON.stringify(spoof)} >&3; printf ran > ${JSON.stringify(profileMarker)}; exit 0`, + ); + fs.writeFileSync( + path.join(home, ".curlrc"), + `trace-ascii = ${JSON.stringify(curlConfigMarker)}\n`, + ); + fs.writeFileSync(launcher, '#!/bin/bash -p\nset -eu\nunset BASH_ENV ENV\nexec "$@"\n', { + mode: 0o755, + }); + const request = buildSandboxInferenceRouteProbeRequest( + "deep-code", + { name: "langchain-deepagents-code" }, + undefined, + 9000, + ); + const command = [...request.command]; + command[0] = launcher; - const result = spawnSync(command[0], command.slice(1), { - encoding: "utf8", - env: { - ...process.env, - ALL_PROXY: "", - BASH_ENV: profile, - CURL_CA_BUNDLE: caBundle, - ENV: profile, - HOME: home, - HTTP_PROXY: "http://127.0.0.1:9", - HTTPS_PROXY: "http://127.0.0.1:9", - NO_PROXY: "", - SSL_CERT_FILE: "", - all_proxy: "", - http_proxy: "http://127.0.0.1:9", - https_proxy: "http://127.0.0.1:9", - no_proxy: "", - }, - }); + const result = spawnSync(command[0], command.slice(1), { + encoding: "utf8", + env: { + ...process.env, + ALL_PROXY: "", + BASH_ENV: profile, + CURL_CA_BUNDLE: caBundle, + ENV: profile, + HOME: home, + HTTP_PROXY: "http://127.0.0.1:9", + HTTPS_PROXY: "http://127.0.0.1:9", + NO_PROXY: "", + SSL_CERT_FILE: "", + all_proxy: "", + http_proxy: "http://127.0.0.1:9", + https_proxy: "http://127.0.0.1:9", + no_proxy: "", + }, + }); - expect(result.status).toBe(0); - expect(result.stdout).toBe("BROKEN 000"); - expect(result.stdout).not.toContain(spoof); - expect(fs.existsSync(profileMarker)).toBe(false); - expect(fs.existsSync(curlConfigMarker)).toBe(false); - } finally { - fs.rmSync(home, { force: true, recursive: true }); - } - }); + expect(result.status).toBe(0); + expect(result.stdout).toBe("BROKEN 000"); + expect(result.stdout).not.toContain(spoof); + expect(fs.existsSync(profileMarker)).toBe(false); + expect(fs.existsSync(curlConfigMarker)).toBe(false); + } finally { + fs.rmSync(home, { force: true, recursive: true }); + } + }, + ); }); describe("sandbox inference route probe result", () => { @@ -180,30 +181,23 @@ describe("sandbox inference route probe result", () => { expect(classifyInferenceRouteFailureLabel(httpStatus)).toBe(expected); }); - it.each([ - "200", - "401", - "403", - "499", - ])("accepts HTTP %s as a reachable route (#6192)", (httpStatus) => { - expect( - parseSandboxInferenceRouteProbeResult({ status: 0, output: `OK ${httpStatus}` }), - ).toMatchObject({ healthy: true, broken: false, httpStatus: Number(httpStatus) }); - }); + it.each(["200", "401", "403", "499"])( + "accepts HTTP %s as a reachable route (#6192)", + (httpStatus) => { + expect( + parseSandboxInferenceRouteProbeResult({ status: 0, output: `OK ${httpStatus}` }), + ).toMatchObject({ healthy: true, broken: false, httpStatus: Number(httpStatus) }); + }, + ); - it.each([ - "000", - "100", - "199", - "500", - "503", - "599", - "600", - ])("rejects HTTP %s as a broken route (#6192)", (httpStatus) => { - expect( - parseSandboxInferenceRouteProbeResult({ status: 0, output: `BROKEN ${httpStatus}` }), - ).toMatchObject({ healthy: false, broken: true, httpStatus: Number(httpStatus) }); - }); + it.each(["000", "100", "199", "500", "503", "599", "600"])( + "rejects HTTP %s as a broken route (#6192)", + (httpStatus) => { + expect( + parseSandboxInferenceRouteProbeResult({ status: 0, output: `BROKEN ${httpStatus}` }), + ).toMatchObject({ healthy: false, broken: true, httpStatus: Number(httpStatus) }); + }, + ); it("does not classify an unavailable probe as healthy or broken (#6192)", () => { expect( @@ -306,23 +300,23 @@ describe("sandbox inference route probe result", () => { }); }); - it.each([ - "[stdout] OK 200", - "stdout: OK 401", - ])("accepts framed healthy output from OpenShell (%s) (#6192)", (output) => { - expect(parseSandboxInferenceRouteProbeResult({ status: 0, output })).toMatchObject({ - healthy: true, - broken: false, - }); - }); + it.each(["[stdout] OK 200", "stdout: OK 401"])( + "accepts framed healthy output from OpenShell (%s) (#6192)", + (output) => { + expect(parseSandboxInferenceRouteProbeResult({ status: 0, output })).toMatchObject({ + healthy: true, + broken: false, + }); + }, + ); - it.each([ - "[stdout] BROKEN 503 service unavailable", - "stdout: BROKEN 000", - ])("accepts framed broken output from OpenShell (%s) (#6192)", (output) => { - expect(parseSandboxInferenceRouteProbeResult({ status: 0, output })).toMatchObject({ - healthy: false, - broken: true, - }); - }); + it.each(["[stdout] BROKEN 503 service unavailable", "stdout: BROKEN 000"])( + "accepts framed broken output from OpenShell (%s) (#6192)", + (output) => { + expect(parseSandboxInferenceRouteProbeResult({ status: 0, output })).toMatchObject({ + healthy: false, + broken: true, + }); + }, + ); }); diff --git a/src/lib/actions/sandbox/connect-inference-route-probe.ts b/src/lib/actions/sandbox/connect-inference-route-probe.ts index 2ebaff48fe5..e47a9e5dca7 100644 --- a/src/lib/actions/sandbox/connect-inference-route-probe.ts +++ b/src/lib/actions/sandbox/connect-inference-route-probe.ts @@ -2,6 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import { redactSensitiveText } from "../../security/redact"; +import type { OpenShellSandboxBufferedCommandRequest } from "../../adapters/openshell/sandbox-command"; +import { + namedOpenShellGateway, + selectedOpenShellGateway, +} from "../../adapters/openshell/sandbox-observer"; export type InferenceRouteProbeAgent = { name: string } | null; @@ -80,40 +85,32 @@ export function classifyInferenceRouteFailureLabel(httpStatus: number): Inferenc return httpStatus >= 500 && httpStatus < 600 ? "unhealthy" : "unreachable"; } -export function buildSandboxInferenceRouteProbeArgs( +/** Build the transport-neutral buffered request for an inference route probe. */ +export function buildSandboxInferenceRouteProbeRequest( sandboxName: string, agent: InferenceRouteProbeAgent, - gatewayName?: string, -): string[] { - const targetArgs = [ - "sandbox", - "exec", - "--name", + gatewayName: string | undefined, + timeoutMilliseconds: number, +): OpenShellSandboxBufferedCommandRequest { + const dcode = agent?.name === "langchain-deepagents-code"; + return { sandboxName, - ...(gatewayName ? ["-g", gatewayName] : []), - ]; - if (agent?.name === "langchain-deepagents-code") { - return [ - ...targetArgs, - "--no-tty", - "--env", - "HOME=/usr/local/lib/nemoclaw", - "--env", - "BASH_ENV=", - "--env", - "ENV=", - "--", - // The trusted launcher ignores ambient proxy overrides and does not add - // another startup-file read or rewrite persistent runtime state. The - // OpenShell transport-level login shell remains tracked in OpenShell#2668. - DCODE_MANAGED_EXEC_LAUNCHER, - "/bin/sh", - "-c", - INFERENCE_ROUTE_PROBE_SCRIPT, - ]; - } - - return [...targetArgs, "--", "sh", "-c", INFERENCE_ROUTE_PROBE_SCRIPT]; + target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), + command: dcode + ? [DCODE_MANAGED_EXEC_LAUNCHER, "/bin/sh", "-c", INFERENCE_ROUTE_PROBE_SCRIPT] + : ["sh", "-c", INFERENCE_ROUTE_PROBE_SCRIPT], + ...(dcode + ? { + sandboxEnvironment: { + BASH_ENV: "", + ENV: "", + HOME: "/usr/local/lib/nemoclaw", + }, + } + : {}), + ...(dcode ? { tty: false } : {}), + timeoutMilliseconds, + }; } /** Parse the shared route-probe output used by connect, status, and doctor. */ diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index 9e9b12ba07e..8c756c35bf3 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -37,14 +37,14 @@ describe("connect route containment", () => { delete require.cache[requireDist.resolve(connectModulePath)]; }); - it("stops before the initial endpoint probe or repair mutation when routes conflict (#6315)", () => { + it("stops before the initial endpoint probe or repair mutation when routes conflict (#6315)", async () => { const conflict = new Error("shared gateway route conflict"); const assertRouteCompatible = vi.fn(() => { throw conflict; }); - const probe = vi.fn(() => ({ healthy: false, broken: true, detail: "BROKEN 503" })); + const probe = vi.fn(async () => ({ healthy: false, broken: true, detail: "BROKEN 503" })); const applyVmDnsMonkeypatch = vi.fn(() => ({ ok: false })); - const reapplyVmInferenceRoute = vi.fn(() => null); + const reapplyVmInferenceRoute = vi.fn(async () => null); const repairLegacyDnsProxy = vi.fn(() => ({ exitCode: 0 })); const deps: SandboxInferenceRouteRepairDeps = { probe, @@ -62,7 +62,7 @@ describe("connect route containment", () => { gpuEnabled: false, }; - expect(() => repairSandboxInferenceRouteWithDeps("vm-box", sandbox, {}, deps)).toThrow( + await expect(repairSandboxInferenceRouteWithDeps("vm-box", sandbox, {}, deps)).rejects.toBe( conflict, ); @@ -407,7 +407,7 @@ describe("connect route containment", () => { await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); - const routeProbeCalls = harness.captureOpenshellSpy.mock.calls.filter((call) => + const routeProbeCalls = harness.sandboxRunBufferedSpy.mock.calls.filter((call) => JSON.stringify(call[0]).includes("inference.local/v1/models"), ); expect(routeProbeCalls).toHaveLength(1); diff --git a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts index 5b91ecbc2e0..e10383d417f 100644 --- a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts +++ b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts @@ -171,7 +171,7 @@ describe("connectSandbox route lifecycle", () => { ); expect(harness.runSetupDnsProxySpy).not.toHaveBeenCalled(); expect(harness.runOpenshellSpy).not.toHaveBeenCalled(); - const routeProbeCalls = harness.captureOpenshellSpy.mock.calls.filter((call) => + const routeProbeCalls = harness.sandboxRunBufferedSpy.mock.calls.filter((call) => JSON.stringify(call[0]).includes("inference.local/v1/models"), ); expect(routeProbeCalls).toHaveLength(2); @@ -186,17 +186,20 @@ describe("connectSandbox route lifecycle", () => { ["model-only", null, "nvidia/test"], ["blank-provider", " ", "nvidia/test"], ["blank-model", "nvidia-prod", " "], - ] as const)("skips inference reconciliation for %s registry entries (#5937)", async (_description, provider, model) => { - const harness = createConnectHarness({ registryEntry: { model, provider } }); + ] as const)( + "skips inference reconciliation for %s registry entries (#5937)", + async (_description, provider, model) => { + const harness = createConnectHarness({ registryEntry: { model, provider } }); - await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); + await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); - expect(harness.captureOpenshellSpy).not.toHaveBeenCalledWith( - ["inference", "get", "-g", "nemoclaw"], - expect.any(Object), - ); - expect(harness.runOpenshellSpy).not.toHaveBeenCalled(); - }); + expect(harness.captureOpenshellSpy).not.toHaveBeenCalledWith( + ["inference", "get", "-g", "nemoclaw"], + expect.any(Object), + ); + expect(harness.runOpenshellSpy).not.toHaveBeenCalled(); + }, + ); it("does not reset an inference route that already matches the sandbox", async () => { const harness = createConnectHarness({ diff --git a/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts b/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts index 68e6aa6b3f1..96984f50121 100644 --- a/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts +++ b/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts @@ -66,10 +66,10 @@ function makeRepairDeps(probes: SandboxInferenceRouteProbe[]) { }; const queue = [...probes]; const deps: SandboxInferenceRouteRepairDeps = { - probe: vi.fn(() => queue.shift() ?? broken()), + probe: vi.fn(async () => queue.shift() ?? broken()), shouldApplyVmDnsMonkeypatch: vi.fn(() => false), applyVmDnsMonkeypatch: vi.fn(() => ({ ok: false })), - reapplyVmInferenceRoute: vi.fn((sandboxName) => { + reapplyVmInferenceRoute: vi.fn(async (sandboxName) => { calls.reapplications.push(sandboxName); return queue.shift() ?? broken(); }), @@ -84,10 +84,10 @@ function makeRepairDeps(probes: SandboxInferenceRouteProbe[]) { } describe("sandbox connect inconclusive route repair", () => { - it("fails closed without repair when the initial probe is inconclusive (#6192)", () => { + it("fails closed without repair when the initial probe is inconclusive (#6192)", async () => { const { calls, deps } = makeRepairDeps([inconclusive()]); - const result = repairSandboxInferenceRouteWithDeps("demo", sandbox(), {}, deps); + const result = await repairSandboxInferenceRouteWithDeps("demo", sandbox(), {}, deps); expect(result).toEqual({ healthy: false, @@ -98,10 +98,10 @@ describe("sandbox connect inconclusive route repair", () => { expect(calls.reapplications).toEqual([]); }); - it("fails closed when non-legacy route reapply remains inconclusive (#6192)", () => { + it("fails closed when non-legacy route reapply remains inconclusive (#6192)", async () => { const { calls, deps } = makeRepairDeps([broken(), inconclusive()]); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "vm-box", sandbox({ openshellDriver: "vm" }), {}, @@ -116,10 +116,10 @@ describe("sandbox connect inconclusive route repair", () => { expect(calls.reapplications).toEqual(["vm-box"]); }); - it("fails closed when a legacy repair probe remains inconclusive (#6192)", () => { + it("fails closed when a legacy repair probe remains inconclusive (#6192)", async () => { const { calls, deps } = makeRepairDeps([broken(), inconclusive()]); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "legacy-box", sandbox({ openshellDriver: "kubernetes" }), {}, diff --git a/src/lib/actions/sandbox/connect-route-repair.test.ts b/src/lib/actions/sandbox/connect-route-repair.test.ts index e424327c077..35c4f4f0fd2 100644 --- a/src/lib/actions/sandbox/connect-route-repair.test.ts +++ b/src/lib/actions/sandbox/connect-route-repair.test.ts @@ -1,10 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandExecutor, +} from "../../adapters/openshell/sandbox-command"; import type { SandboxEntry } from "../../state/registry"; -import { captureOpenshell } from "../../adapters/openshell/runtime"; +const runBuffered = vi.hoisted(() => + vi.fn(), +); + +vi.mock("../../adapters/openshell/sandbox-command-cli", () => ({ + createCliOpenShellSandboxCommandExecutor: vi.fn(() => ({ runBuffered })), +})); vi.mock("../../adapters/openshell/runtime", () => ({ captureOpenshell: vi.fn(() => ({ status: 0, output: "" })), @@ -48,6 +58,10 @@ import { type SandboxInferenceRouteRepairDeps, } from "./connect"; +function completed(output: string): OpenShellSandboxBufferedCommandCompletion { + return { outcome: { kind: "completed", exitCode: 0 }, stdout: output, stderr: "" }; +} + const healthy = (detail = "OK 200"): SandboxInferenceRouteProbe => ({ healthy: true, broken: false, @@ -84,7 +98,7 @@ function makeRepairDeps( }; const queue = [...probes]; const deps: SandboxInferenceRouteRepairDeps = { - probe: vi.fn((_sandboxName, options) => { + probe: vi.fn(async (_sandboxName, options) => { calls.probeOptions.push(options); return queue.shift() ?? broken("missing mocked probe"); }), @@ -93,7 +107,7 @@ function makeRepairDeps( calls.monkeypatches.push(sandboxName); return { ok: false, reason: "not mocked" }; }), - reapplyVmInferenceRoute: vi.fn((sandboxName) => { + reapplyVmInferenceRoute: vi.fn(async (sandboxName) => { calls.reapplications.push(sandboxName); return queue.shift() ?? broken("missing mocked reapply probe"); }), @@ -109,12 +123,12 @@ function makeRepairDeps( } describe("sandbox connect route repair unit flow", () => { - it("still probes and fails closed when route repair is disabled (#8502)", () => { + it("still probes and fails closed when route repair is disabled (#8502)", async () => { const { calls, deps } = makeRepairDeps([broken()], { isRepairDisabled: () => true, }); - const result = repairSandboxInferenceRouteWithDeps("demo", sandbox(), {}, deps); + const result = await repairSandboxInferenceRouteWithDeps("demo", sandbox(), {}, deps); expect(result).toEqual({ healthy: false, @@ -125,10 +139,10 @@ describe("sandbox connect route repair unit flow", () => { expect(calls.legacyRepairs).toEqual([]); }); - it("does not repair a healthy initial probe", () => { + it("does not repair a healthy initial probe", async () => { const { calls, deps } = makeRepairDeps([healthy()]); - const result = repairSandboxInferenceRouteWithDeps("demo", sandbox(), {}, deps); + const result = await repairSandboxInferenceRouteWithDeps("demo", sandbox(), {}, deps); expect(result).toEqual({ healthy: true, @@ -139,10 +153,10 @@ describe("sandbox connect route repair unit flow", () => { expect(calls.reapplications).toEqual([]); }); - it("repairs legacy kubernetes routes through the DNS proxy path", () => { + it("repairs legacy kubernetes routes through the DNS proxy path", async () => { const { calls, deps } = makeRepairDeps([broken(), healthy()]); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "legacy-box", sandbox({ openshellDriver: "kubernetes" }), {}, @@ -163,7 +177,7 @@ describe("sandbox connect route repair unit flow", () => { expect(calls.logs).toContain(" inference.local route repaired."); }); - it("returns the DNS repair failure detail without route reapply on legacy sandboxes", () => { + it("returns the DNS repair failure detail without route reapply on legacy sandboxes", async () => { const { calls, deps } = makeRepairDeps([broken()], { repairLegacyDnsProxy: vi.fn((sandboxName, quiet) => { calls.legacyRepairs.push({ sandboxName, quiet }); @@ -171,7 +185,7 @@ describe("sandbox connect route repair unit flow", () => { }), }); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "legacy-box", sandbox({ openshellDriver: "kubernetes" }), {}, @@ -189,10 +203,10 @@ describe("sandbox connect route repair unit flow", () => { it.each(["docker", "podman"])( "uses inference route reapply instead of legacy DNS repair for %s sandboxes", - (driver) => { + async (driver) => { const { calls, deps } = makeRepairDeps([broken(), healthy()]); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( `${driver}-box`, sandbox({ openshellDriver: driver }), {}, @@ -207,7 +221,7 @@ describe("sandbox connect route repair unit flow", () => { }, ); - it("lets the VM monkeypatch satisfy the route before inference reapply", () => { + it("lets the VM monkeypatch satisfy the route before inference reapply", async () => { const { calls, deps } = makeRepairDeps([broken(), healthy()], { shouldApplyVmDnsMonkeypatch: vi.fn(() => true), applyVmDnsMonkeypatch: vi.fn((sandboxName) => { @@ -216,7 +230,7 @@ describe("sandbox connect route repair unit flow", () => { }), }); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "vm-box", sandbox({ openshellDriver: "vm" }), {}, @@ -236,7 +250,7 @@ describe("sandbox connect route repair unit flow", () => { ); }); - it("falls back to inference reapply when the VM monkeypatch leaves the route broken", () => { + it("falls back to inference reapply when the VM monkeypatch leaves the route broken", async () => { const { calls, deps } = makeRepairDeps([broken(), broken(), healthy()], { shouldApplyVmDnsMonkeypatch: vi.fn(() => true), applyVmDnsMonkeypatch: vi.fn((sandboxName) => { @@ -245,7 +259,7 @@ describe("sandbox connect route repair unit flow", () => { }), }); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "vm-box", sandbox({ openshellDriver: "vm" }), {}, @@ -260,10 +274,10 @@ describe("sandbox connect route repair unit flow", () => { ); }); - it("reports broken non-legacy routes after inference reapply cannot repair them", () => { + it("reports broken non-legacy routes after inference reapply cannot repair them", async () => { const { calls, deps } = makeRepairDeps([broken(), broken()]); - const result = repairSandboxInferenceRouteWithDeps( + const result = await repairSandboxInferenceRouteWithDeps( "vm-box", sandbox({ openshellDriver: "vm" }), {}, @@ -303,7 +317,7 @@ function makeResetDeps( calls.inferenceSets.push({ provider, model }); return { status: 0 }; }), - probe: vi.fn((_sandboxName, options) => { + probe: vi.fn(async (_sandboxName, options) => { calls.probeOptions.push(options); return queue.shift() ?? broken("missing mocked reset probe"); }), @@ -318,10 +332,10 @@ function makeResetDeps( } describe("managed inference route reset unit flow", () => { - it("verifies local dependencies before and after a successful route reset", () => { + it("verifies local dependencies before and after a successful route reset", async () => { const { calls, deps } = makeResetDeps([healthy()]); - const result = resetManagedInferenceRouteWithDeps( + const result = await resetManagedInferenceRouteWithDeps( "demo", sandbox({ provider: "ollama-local", model: "qwen3:0.6b" }), { detail: "BROKEN 503" }, @@ -337,7 +351,7 @@ describe("managed inference route reset unit flow", () => { expect(calls.logs).toContain(" inference.local route repaired."); }); - it("probes route health after a non-zero inference set and accepts a healthy route", () => { + it("probes route health after a non-zero inference set and accepts a healthy route", async () => { const { calls, deps } = makeResetDeps([healthy()], { runInferenceSet: vi.fn((provider, model) => { calls.inferenceSets.push({ provider, model }); @@ -345,7 +359,7 @@ describe("managed inference route reset unit flow", () => { }), }); - const result = resetManagedInferenceRouteWithDeps( + const result = await resetManagedInferenceRouteWithDeps( "demo", sandbox(), { detail: "BROKEN 503" }, @@ -358,7 +372,7 @@ describe("managed inference route reset unit flow", () => { expect(calls.errors).toEqual([]); }); - it("stops before inference set when local dependency checks fail", () => { + it("stops before inference set when local dependency checks fail", async () => { const { calls, deps } = makeResetDeps([], { verifyLocalInferenceRouteDependencies: vi.fn((provider, options) => { calls.localChecks.push({ provider, quiet: options.quiet }); @@ -366,7 +380,7 @@ describe("managed inference route reset unit flow", () => { }), }); - const result = resetManagedInferenceRouteWithDeps( + const result = await resetManagedInferenceRouteWithDeps( "demo", sandbox({ provider: "ollama-local", model: "qwen3:0.6b" }), { detail: "BROKEN 503" }, @@ -378,7 +392,7 @@ describe("managed inference route reset unit flow", () => { expect(calls.unrecoverable).toEqual([{ sandboxName: "demo", detail: "BROKEN 503" }]); }); - it("fails closed when route reset and the follow-up probe are both unhealthy", () => { + it("fails closed when route reset and the follow-up probe are both unhealthy", async () => { const { calls, deps } = makeResetDeps([broken("BROKEN 503 still down")], { runInferenceSet: vi.fn((provider, model) => { calls.inferenceSets.push({ provider, model }); @@ -386,7 +400,7 @@ describe("managed inference route reset unit flow", () => { }), }); - const result = resetManagedInferenceRouteWithDeps( + const result = await resetManagedInferenceRouteWithDeps( "demo", sandbox(), { detail: "BROKEN 503" }, @@ -400,32 +414,43 @@ describe("managed inference route reset unit flow", () => { }); describe("connect inference route retries", () => { - it("returns the third healthy probe result after two unhealthy probe results (#9218)", () => { - vi.mocked(captureOpenshell) - .mockReturnValueOnce({ status: 0, output: "BROKEN 503", stderr: "" }) - .mockReturnValueOnce({ status: 0, output: "BROKEN 503", stderr: "" }) - .mockReturnValueOnce({ status: 0, output: "OK 200", stderr: "" }); + beforeEach(() => { + runBuffered.mockReset(); + }); + + it("returns the third healthy probe result after two unhealthy probe results (#9218)", async () => { + runBuffered + .mockResolvedValueOnce(completed("BROKEN 503")) + .mockResolvedValueOnce(completed("BROKEN 503")) + .mockResolvedValueOnce(completed("OK 200")); - const result = probeSandboxInferenceRoute( + const result = await probeSandboxInferenceRoute( "alpha", { name: "hermes" }, { attempts: 3, delayMs: 2_000 }, ); expect(result).toMatchObject({ healthy: true, broken: false, httpStatus: 200 }); - expect(captureOpenshell).toHaveBeenCalledTimes(3); + expect(runBuffered).toHaveBeenCalledTimes(3); + expect(runBuffered).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["sh", "-c", expect.any(String)], + }), + ); }); - it("returns the final unhealthy probe result after exhausting attempts (#9218)", () => { - vi.mocked(captureOpenshell).mockReturnValue({ status: 0, output: "BROKEN 503", stderr: "" }); + it("returns the final unhealthy probe result after exhausting attempts (#9218)", async () => { + runBuffered.mockResolvedValue(completed("BROKEN 503")); - const result = probeSandboxInferenceRoute( + const result = await probeSandboxInferenceRoute( "alpha", { name: "hermes" }, { attempts: 2, delayMs: 500 }, ); expect(result).toMatchObject({ healthy: false, broken: true, httpStatus: 503 }); - expect(captureOpenshell).toHaveBeenCalledTimes(2); + expect(runBuffered).toHaveBeenCalledTimes(2); }); }); diff --git a/src/lib/actions/sandbox/connect-wedge-diagnostics.test.ts b/src/lib/actions/sandbox/connect-wedge-diagnostics.test.ts new file mode 100644 index 00000000000..aac363d0bdd --- /dev/null +++ b/src/lib/actions/sandbox/connect-wedge-diagnostics.test.ts @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; + +import { + connectModulePath, + createConnectHarness, + requireDist, +} from "../../../../test/support/connect-flow-test-harness"; + +describe("connectSandbox wedge diagnostic failures", () => { + let exitSpy: MockInstance; + + beforeEach(() => { + vi.stubEnv("NEMOCLAW_TEST_NO_SLEEP", "1"); + exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + delete require.cache[requireDist.resolve(connectModulePath)]; + }); + + it("preserves the classified recovery exit when wedge diagnostics reject", async () => { + const harness = createConnectHarness({ + processCheck: { + checked: true, + wasRunning: false, + recovered: false, + forwardRecovered: false, + recoveryFailureDetail: "the recovered gateway did not become responsive", + }, + }); + harness.sandboxRunBufferedSpy.mockRejectedValueOnce(new Error("untrusted diagnostic failure")); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( + "process.exit(1)", + ); + + const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(errorOutput).toContain( + "Recovery detail: the recovered gateway did not become responsive.", + ); + expect(errorOutput).toContain("Check /tmp/gateway.log inside the sandbox for details."); + expect(errorOutput).not.toContain("untrusted diagnostic failure"); + expect(harness.sandboxRunBufferedSpy).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("preserves the automatic-recovery failure exit when wedge diagnostics reject", async () => { + const harness = createConnectHarness({ + processCheck: { + checked: true, + wasRunning: false, + recovered: false, + }, + }); + harness.sandboxRunBufferedSpy.mockRejectedValueOnce(new Error("untrusted diagnostic failure")); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( + "process.exit(1)", + ); + + const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(errorOutput).toContain( + "Probe failed: OpenClaw gateway is not running in 'alpha' and automatic recovery failed.", + ); + expect(errorOutput).toContain("Check /tmp/gateway.log inside the sandbox for details."); + expect(errorOutput).not.toContain("untrusted diagnostic failure"); + expect(harness.sandboxRunBufferedSpy).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(1); + }); +}); diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 2c0426e23c9..15075a044bc 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -4,6 +4,10 @@ import { spawnSync } from "node:child_process"; import { isDeepStrictEqual } from "node:util"; import { createCliOpenShellSandboxObserver } from "../../adapters/openshell/sandbox-observer-cli"; +import { + createCliOpenShellSandboxCommandExecutor, + createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor, +} from "../../adapters/openshell/sandbox-command-cli"; import { namedOpenShellGateway, type OpenShellSandboxError, @@ -26,7 +30,7 @@ import type { AgentDefinition } from "../../agent/defs"; import * as agentRuntime from "../../agent/runtime"; import { CLI_NAME } from "../../cli/branding"; import { D, G, R, YW } from "../../cli/terminal-style"; -import { retryUntil, retryUntilAsync } from "../../core/retry"; +import { retryUntilAsync } from "../../core/retry"; import { spawnExitCode } from "../../core/process-exit"; import { shellQuote } from "../../core/shell-quote"; @@ -74,7 +78,7 @@ import { sandboxUsesLegacyClusterGateway, } from "./connect-inference-gateway"; import { - buildSandboxInferenceRouteProbeArgs, + buildSandboxInferenceRouteProbeRequest, type InferenceRouteProbeAgent, parseSandboxInferenceRouteProbeResult, } from "./connect-inference-route-probe"; @@ -145,6 +149,7 @@ import { applyOpenShellVmDnsMonkeypatch, shouldApplyVmDnsMonkeypatch } from "./v export { runConnectAutoPairApprovalPass, waitForManagedGatewaySupervisor }; const HERMES_READINESS_PUBLICATION_SETTLE_DELAYS_MS = [100, 250] as const; +const sandboxCommandExecutor = createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); async function publishHermesLaunchReadinessWithSettlement( publication: Parameters[0], @@ -162,7 +167,9 @@ export type SandboxConnectOptions = { requireLaunchReadinessPublication?: boolean; }; -export type SandboxStartupRecoveryResult = ReturnType & { +export type SandboxStartupRecoveryResult = Awaited< + ReturnType +> & { recoveryFailureDetail?: string | null; recoveryFailureLayer?: GatewayRestartFailureLayer | null; }; @@ -205,7 +212,10 @@ export type SandboxInferenceRouteRepairResult = { export type SandboxInferenceRouteRepairDeps = { isRepairDisabled?: () => boolean; - probe: (sandboxName: string, options?: InferenceRouteProbeOptions) => SandboxInferenceRouteProbe; + probe: ( + sandboxName: string, + options?: InferenceRouteProbeOptions, + ) => Promise; shouldApplyVmDnsMonkeypatch: (sb: SandboxEntry | null) => boolean; applyVmDnsMonkeypatch: ( sandboxName: string, @@ -214,7 +224,7 @@ export type SandboxInferenceRouteRepairDeps = { reapplyVmInferenceRoute: ( sandboxName: string, sb: SandboxEntry | null, - ) => SandboxInferenceRouteProbe | null; + ) => Promise; repairLegacyDnsProxy: ( sandboxName: string, quiet: boolean, @@ -230,7 +240,10 @@ export type ManagedInferenceRouteResetDeps = { options: { quiet?: boolean }, ) => boolean; runInferenceSet: (provider: string, model: string) => { status: number | null }; - probe: (sandboxName: string, options?: InferenceRouteProbeOptions) => SandboxInferenceRouteProbe; + probe: ( + sandboxName: string, + options?: InferenceRouteProbeOptions, + ) => Promise; printUnrecoverableInferenceRoute: (sandboxName: string, route: string, detail: string) => void; log?: (message: string) => void; error?: (message: string) => void; @@ -308,13 +321,13 @@ function exitOnForwardRecoveryFailure( process.exit(1); } -function exitOnGatewayRecoveryFailure( +async function exitOnGatewayRecoveryFailure( sandboxName: string, agentName: string, detail: string, operation: "Probe" | "Recovery" = "Probe", showWedgeDiagnostics = false, -): never { +): Promise { const safeDetail = sanitizeSandboxStartupRecoveryDetail(detail); const terminalPunctuation = /[.!?]$/u.test(safeDetail) ? "" : "."; console.error(""); @@ -323,7 +336,11 @@ function exitOnGatewayRecoveryFailure( ); console.error(` Recovery detail: ${safeDetail}${terminalPunctuation}`); if (showWedgeDiagnostics) { - printGatewayWedgeDiagnostics(sandboxName, executeSandboxExecCommand); + await printGatewayWedgeDiagnostics(sandboxName, (name, command) => + executeSandboxExecCommand(name, command, undefined, { + localDockerFallbackPolicy: "read-only", + }), + ); console.error(" Check /tmp/gateway.log inside the sandbox for details."); } process.exit(1); @@ -363,7 +380,7 @@ async function runSandboxConnectProbe( const agentName = agentRuntime.getAgentDisplayName(agent); if (hermesPortable) { if (probeOnly !== true) throw new Error("Hermes inference recovery requires probe-only mode"); - const route = measure("inference", () => + const route = await measureAsync("inference", () => verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit(sandboxName, agent, undefined, { commandAuthority: hermesPortableCommandAuthority, probeTiming, @@ -398,11 +415,11 @@ async function runSandboxConnectProbe( const routeResult = await measureAsync("inference", () => ensureSandboxInferenceRoute(sandboxName, agent, { quiet: true }), ); - measure("inference", () => + await measureAsync("inference", () => runTerminalAgentConnectProbe({ agent, agentName, - capture: captureOpenshell, + commandExecutor: sandboxCommandExecutor, ensureInferenceRoute: () => routeResult, sandboxName, }), @@ -414,7 +431,7 @@ async function runSandboxConnectProbe( // only way this path can tell a retryable wedge apart from a deterministic // integrity refusal that no restart, recover, or connect can clear (#7801). let recoveryFailureLayer: GatewayRestartFailureLayer | null = null; - const processCheck = checkAndRecoverSandboxProcesses(sandboxName, { + const processCheck = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, probeTiming, onRecoveryFailureLayer: (layer) => { @@ -447,7 +464,7 @@ async function runSandboxConnectProbe( } if ("recoveryFailureDetail" in processCheck && processCheck.recoveryFailureDetail) { probeTiming?.markFailureStage("processes"); - exitOnGatewayRecoveryFailure( + await exitOnGatewayRecoveryFailure( sandboxName, agentName, String(processCheck.recoveryFailureDetail), @@ -500,7 +517,11 @@ async function runSandboxConnectProbe( // Surface the #4710 wedge signature: recovery ran with quiet=true, so this // is the operator's only window into a gateway that served briefly and // then dropped its listener. - printGatewayWedgeDiagnostics(sandboxName, executeSandboxExecCommand); + await printGatewayWedgeDiagnostics(sandboxName, (name, command) => + executeSandboxExecCommand(name, command, undefined, { + localDockerFallbackPolicy: "read-only", + }), + ); console.error(" Check /tmp/gateway.log inside the sandbox for details."); process.exit(1); } @@ -628,6 +649,15 @@ function probeTimingLaunchReadinessDeps( : {}; } +function ordinaryLaunchReadinessDeps( + probeTiming?: ProbeTimingRecorder, +): NonNullable[1]> { + return { + commandExecutor: sandboxCommandExecutor, + ...probeTimingLaunchReadinessDeps(probeTiming), + }; +} + function captureHermesPortableReadinessObservation( authority: HermesPortableReadinessCommandAuthority, args: string[], @@ -656,8 +686,16 @@ function hermesPortableLaunchReadinessDeps( args: string[], options: NonNullable[1]> = {}, ) => captureHermesPortableReadinessObservation(authority, args, options, assertCurrent); + const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( + { + resolveBinary: () => authority.executablePath, + hostCwd: ROOT, + hostEnv: authority.env, + }, + assertCurrent, + ); return { - ...createBoundLaunchReadinessDeps(capture), + ...createBoundLaunchReadinessDeps(capture, commandExecutor), ...probeTimingLaunchReadinessDeps(probeTiming), }; } @@ -844,12 +882,12 @@ function refuseHermesPortableInferenceRoute(reason: string): never { } /** Verify the recorded Hermes route without invoking repair or process exit. */ -function verifyHermesPortableInferenceRoute( +async function verifyHermesPortableInferenceRoute( sandboxName: string, agent: InferenceRouteProbeAgent, expectedAuthority?: HermesPortableActiveLifecycleAuthority, commandAuthority?: HermesPortableReadinessCommandAuthority, -): SandboxEntry { +): Promise { let authority: ReturnType; try { authority = requireHermesPortableActiveLifecycleAuthority( @@ -889,12 +927,32 @@ function verifyHermesPortableInferenceRoute( if (planInferenceRouteReconcile(live, inference).kind !== "aligned") { refuseHermesPortableInferenceRoute("different from its recorded provider or model"); } - const probe = parseSandboxInferenceRouteProbeResult( - capture(buildSandboxInferenceRouteProbeArgs(sandboxName, agent, authority.gatewayName), { - includeStreams: true, - timeout: OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, - }), - ); + const portableCommandAuthority = + commandAuthority ?? buildHermesPortableCommandAuthority(sandboxName); + const commandExecutor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => portableCommandAuthority.executablePath, + hostCwd: ROOT, + hostEnv: portableCommandAuthority.env, + }); + commandAuthority?.assertCurrent(); + let completion: Awaited>; + try { + completion = await commandExecutor.runBuffered( + buildSandboxInferenceRouteProbeRequest( + sandboxName, + agent, + authority.gatewayName, + OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, + ), + ); + } finally { + commandAuthority?.assertCurrent(); + } + const probe = parseSandboxInferenceRouteProbeResult({ + status: completion.outcome.kind === "completed" ? completion.outcome.exitCode : null, + output: completion.stdout, + stderr: completion.stderr, + }); if ( !probe.healthy || (inference.provider === "ollama-local" && @@ -924,14 +982,14 @@ function verifyHermesPortableInferenceRoute( } /** Verify the recorded Hermes route without invoking any inference repair. */ -function verifyHermesPortableInferenceRouteOrExit( +async function verifyHermesPortableInferenceRouteOrExit( sandboxName: string, agent: InferenceRouteProbeAgent, expectedAuthority?: HermesPortableActiveLifecycleAuthority, commandAuthority?: HermesPortableReadinessCommandAuthority, -): SandboxEntry { +): Promise { try { - return verifyHermesPortableInferenceRoute( + return await verifyHermesPortableInferenceRoute( sandboxName, agent, expectedAuthority, @@ -956,12 +1014,12 @@ type HermesPortableProbeRouteOptions = { }; /** Verify the recorded route and resume published Ollama only for probe-only recovery. */ -function verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit( +async function verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit( sandboxName: string, agent: InferenceRouteProbeAgent, expectedAuthority?: HermesPortableActiveLifecycleAuthority, options: HermesPortableProbeRouteOptions = {}, -): HermesPortableProbeRouteResult { +): Promise { let authority: HermesPortableActiveLifecycleAuthority; try { authority = requireHermesPortableActiveLifecycleAuthority( @@ -973,7 +1031,7 @@ function verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit( failHermesPortableInferenceRoute(sandboxName, "missing or incomplete"); } if (authority.entry.provider !== "ollama-local") { - const entry = verifyHermesPortableInferenceRouteOrExit( + const entry = await verifyHermesPortableInferenceRouteOrExit( sandboxName, agent, authority, @@ -989,7 +1047,7 @@ function verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit( let verified: SandboxEntry | null = null; let preparedForwards: PreparedHermesPortableForwardRecovery | null = null; try { - recoverHermesPortableInferenceForConnectProbe({ + await recoverHermesPortableInferenceForConnectProbe({ sandboxName, authority, readRegistry: registry.getSandbox, @@ -1015,8 +1073,8 @@ function verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit( }, } : {}), - verifyRoute: () => { - verified = verifyHermesPortableInferenceRoute( + verifyRoute: async () => { + verified = await verifyHermesPortableInferenceRoute( sandboxName, agent, authority, @@ -1142,45 +1200,45 @@ function failIfGatewayBlocksConnectReadiness(sandboxName: string): void { } } -function sleepSync(milliseconds: number): void { - if (milliseconds <= 0) return; - if (process.env.VITEST === "true" || process.env.NEMOCLAW_TEST_NO_SLEEP === "1") return; - spawnSync(process.execPath, ["-e", `setTimeout(() => {}, ${milliseconds})`], { - stdio: "ignore", - timeout: milliseconds + 1_000, +async function runSandboxInferenceRouteProbe( + sandboxName: string, + agent: InferenceRouteProbeAgent, +): Promise { + const completion = await sandboxCommandExecutor.runBuffered( + buildSandboxInferenceRouteProbeRequest( + sandboxName, + agent, + undefined, + OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, + ), + ); + const parsed = parseSandboxInferenceRouteProbeResult({ + status: completion.outcome.kind === "completed" ? completion.outcome.exitCode : null, + output: completion.stdout, + stderr: completion.stderr, }); + return { + healthy: parsed.healthy, + broken: parsed.broken, + httpStatus: parsed.httpStatus, + detail: parsed.detail, + }; } -export function probeSandboxInferenceRoute( +export async function probeSandboxInferenceRoute( sandboxName: string, agent: InferenceRouteProbeAgent, { attempts = 1, delayMs = 0 }: InferenceRouteProbeOptions = {}, -): SandboxInferenceRouteProbe { +): Promise { const attemptCount = Math.max(1, Math.floor(attempts)); - return retryUntil( - () => { - // Keep the shell string inside the sandbox: curl write-out, body capture, - // and status classification must run as one bounded probe. sandboxName - // remains an argv value, so no user input is interpolated into the script. - const probe = captureOpenshell(buildSandboxInferenceRouteProbeArgs(sandboxName, agent), { - ignoreError: true, - includeStreams: true, - timeout: OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, - }); - const parsed = parseSandboxInferenceRouteProbeResult(probe); - return { - healthy: parsed.healthy, - broken: parsed.broken, - httpStatus: parsed.httpStatus, - detail: parsed.detail, - }; - }, - { - accept: (result) => result.healthy, - retryDelaysMs: Array.from({ length: attemptCount - 1 }, () => delayMs), - sleep: sleepSync, - }, - ); + return retryUntilAsync(() => runSandboxInferenceRouteProbe(sandboxName, agent), { + accept: (result) => result.healthy, + retryDelaysMs: Array.from({ length: attemptCount - 1 }, () => delayMs), + sleep: (milliseconds) => + process.env.VITEST === "true" || process.env.NEMOCLAW_TEST_NO_SLEEP === "1" + ? Promise.resolve() + : new Promise((resolve) => setTimeout(resolve, milliseconds)), + }); } function shouldUseLegacyDnsProxyRepair(sb: SandboxEntry | null): boolean { @@ -1193,12 +1251,12 @@ function shouldUseLegacyDnsProxyRepair(sb: SandboxEntry | null): boolean { return sandboxUsesLegacyClusterGateway(sb); } -function reapplyVmInferenceRoute( +async function reapplyVmInferenceRoute( sandboxName: string, sb: SandboxEntry | null, agent: InferenceRouteProbeAgent, gatewayName: string, -): SandboxInferenceRouteProbe | null { +): Promise { const inference = sb ? registry.getSandboxEntryInference(sb) : null; if (inference?.kind !== "configured") return null; runOpenshell(buildGatewayInferenceSetArgs(gatewayName, inference.provider, inference.model), { @@ -1208,16 +1266,16 @@ function reapplyVmInferenceRoute( return probeSandboxInferenceRoute(sandboxName, agent); } -export function repairSandboxInferenceRouteWithDeps( +export async function repairSandboxInferenceRouteWithDeps( sandboxName: string, sb: SandboxEntry | null, { quiet = false }: { quiet?: boolean } = {}, deps: SandboxInferenceRouteRepairDeps, -): SandboxInferenceRouteRepairResult { +): Promise { const log = deps.log ?? console.log; const error = deps.error ?? console.error; deps.assertRouteCompatible?.(sandboxName, sb); - const initialProbe = deps.probe(sandboxName); + const initialProbe = await deps.probe(sandboxName); if (initialProbe.healthy) { return { healthy: true, repairAttempted: false, detail: initialProbe.detail }; } @@ -1241,7 +1299,7 @@ export function repairSandboxInferenceRouteWithDeps( } const patch = deps.applyVmDnsMonkeypatch(sandboxName, sb); const patchedProbe = patch.ok - ? deps.probe(sandboxName, { + ? await deps.probe(sandboxName, { attempts: INFERENCE_ROUTE_POST_REPAIR_PROBE_ATTEMPTS, delayMs: INFERENCE_ROUTE_POST_REPAIR_PROBE_DELAY_MS, }) @@ -1273,7 +1331,7 @@ export function repairSandboxInferenceRouteWithDeps( ` inference.local is unavailable inside '${sandboxName}'. Reapplying OpenShell inference route...`, ); } - const finalProbe = deps.reapplyVmInferenceRoute(sandboxName, sb); + const finalProbe = await deps.reapplyVmInferenceRoute(sandboxName, sb); if (!quiet) { if (finalProbe?.healthy) { log(" inference.local route repaired."); @@ -1314,7 +1372,7 @@ export function repairSandboxInferenceRouteWithDeps( }; } - const repairedProbe = deps.probe(sandboxName, { + const repairedProbe = await deps.probe(sandboxName, { attempts: INFERENCE_ROUTE_POST_REPAIR_PROBE_ATTEMPTS, delayMs: INFERENCE_ROUTE_POST_REPAIR_PROBE_DELAY_MS, }); @@ -1332,14 +1390,14 @@ export function repairSandboxInferenceRouteWithDeps( }; } -function repairSandboxInferenceRouteIfNeeded( +async function repairSandboxInferenceRouteIfNeeded( sandboxName: string, sb: SandboxEntry | null, agent: InferenceRouteProbeAgent, gatewayName: string, { quiet = false }: { quiet?: boolean } = {}, -): SandboxInferenceRouteRepairResult { - return repairSandboxInferenceRouteWithDeps( +): Promise { + return await repairSandboxInferenceRouteWithDeps( sandboxName, sb, { quiet }, @@ -1422,12 +1480,12 @@ function printUnrecoverableInferenceRoute( ); } -export function resetManagedInferenceRouteWithDeps( +export async function resetManagedInferenceRouteWithDeps( sandboxName: string, sb: SandboxEntry, { detail, quiet = false }: { detail: string; quiet?: boolean }, deps: ManagedInferenceRouteResetDeps, -): boolean { +): Promise { const log = deps.log ?? console.log; const inference = registry.getSandboxEntryInference(sb); if (inference.kind !== "configured") return false; @@ -1452,7 +1510,7 @@ export function resetManagedInferenceRouteWithDeps( return fail(detail); } - const finalProbe = deps.probe(sandboxName, { + const finalProbe = await deps.probe(sandboxName, { attempts: INFERENCE_ROUTE_POST_REPAIR_PROBE_ATTEMPTS, delayMs: INFERENCE_ROUTE_POST_REPAIR_PROBE_DELAY_MS, }); @@ -1467,14 +1525,14 @@ export function resetManagedInferenceRouteWithDeps( ); } -function resetManagedInferenceRoute( +async function resetManagedInferenceRoute( sandboxName: string, sb: SandboxEntry, agent: InferenceRouteProbeAgent, gatewayName: string, { detail, quiet = false }: { detail: string; quiet?: boolean }, -): boolean { - return resetManagedInferenceRouteWithDeps( +): Promise { + return await resetManagedInferenceRouteWithDeps( sandboxName, sb, { detail, quiet }, @@ -1491,11 +1549,11 @@ function resetManagedInferenceRoute( ); } -function ensureSandboxInferenceRouteUnlocked( +async function ensureSandboxInferenceRouteUnlocked( sandboxName: string, agent: InferenceRouteProbeAgent, { quiet = false }: { quiet?: boolean } = {}, -): SandboxInferenceRouteEnsureResult { +): Promise { let sb: SandboxEntry | null = null; let inference: ReturnType | null = null; try { @@ -1550,9 +1608,13 @@ function ensureSandboxInferenceRouteUnlocked( ); } } - const repairResult = repairSandboxInferenceRouteIfNeeded(sandboxName, sb, agent, gatewayName, { - quiet, - }); + const repairResult = await repairSandboxInferenceRouteIfNeeded( + sandboxName, + sb, + agent, + gatewayName, + { quiet }, + ); if (!repairResult.healthy && !repairResult.repairAttempted) { // Unavailable or malformed probe output is a permanent fail-closed // classification at the OpenShell exec/DNS/TLS/proxy boundary. There is @@ -1570,7 +1632,7 @@ function ensureSandboxInferenceRouteUnlocked( } let routeReady = repairResult.healthy; if (!routeReady && repairResult.repairAttempted) { - routeReady = resetManagedInferenceRoute(sandboxName, sb, agent, gatewayName, { + routeReady = await resetManagedInferenceRoute(sandboxName, sb, agent, gatewayName, { detail: repairResult.detail, quiet, }); @@ -1580,7 +1642,7 @@ function ensureSandboxInferenceRouteUnlocked( if (!verifyLocalInferenceRouteDependencies(provider, { quiet })) { return { sandbox: sb, routeHealthy: false }; } - const finalProbe = probeSandboxInferenceRoute(sandboxName, agent); + const finalProbe = await probeSandboxInferenceRoute(sandboxName, agent); const strictRouteHealthy = finalProbe.healthy && finalProbe.httpStatus !== undefined && @@ -1678,10 +1740,12 @@ function maybeEnsureHermesToolGatewayBroker(sb: SandboxEntry | null): void { } } -export function restoreSandboxStartupState(sandboxName: string): SandboxStartupRecoveryResult { +export async function restoreSandboxStartupState( + sandboxName: string, +): Promise { let reportedRecoveryFailureDetail: string | null = null; let reportedRecoveryFailureLayer: GatewayRestartFailureLayer | null = null; - const processCheck = checkAndRecoverSandboxProcesses(sandboxName, { + const processCheck = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, onRecoveryFailureLayer: (layer, detail) => { reportedRecoveryFailureLayer = layer; @@ -2205,7 +2269,7 @@ export async function prepareInteractiveSession(sandboxName: string): Promise<{ withinLifecycleFence: async ({ hermesPortable, requalify }) => { if (!hermesPortable) { printInteractiveSessionHints(sandboxName); - const processCheck = checkAndRecoverSandboxProcesses(sandboxName); + const processCheck = await checkAndRecoverSandboxProcesses(sandboxName); if ("secretBoundaryRefused" in processCheck && processCheck.secretBoundaryRefused) { const agentName = agentRuntime.getAgentDisplayName( agentRuntime.getSessionAgent(sandboxName), @@ -2224,7 +2288,12 @@ export async function prepareInteractiveSession(sandboxName: string): Promise<{ const agentName = agentRuntime.getAgentDisplayName( agentRuntime.getSessionAgent(sandboxName), ); - exitOnGatewayRecoveryFailure(sandboxName, agentName, recoveryFailureDetail, "Recovery"); + await exitOnGatewayRecoveryFailure( + sandboxName, + agentName, + recoveryFailureDetail, + "Recovery", + ); } } // Ensure Ollama auth proxy is running (recovers from host reboots) @@ -2244,7 +2313,7 @@ export async function prepareInteractiveSession(sandboxName: string): Promise<{ // ── Inference route swap (#1248, #3390) ─────────────────────── const agent = agentRuntime.getSessionAgent(sandboxName); const sb = hermesPortable - ? verifyHermesPortableInferenceRouteOrExit(sandboxName, agent) + ? await verifyHermesPortableInferenceRouteOrExit(sandboxName, agent) : await ensureSandboxInferenceRouteOrExit(sandboxName, agent); requalify(); if (!hermesPortable && !(await settlePortablePairingOrExit(sandboxName))) { @@ -2478,7 +2547,7 @@ async function prepareConnectSandboxWithinLifecycleFence( sandboxName, hermesReadinessAuthority ? hermesPortableLaunchReadinessDeps(hermesReadinessAuthority.command, probeTiming) - : probeTimingLaunchReadinessDeps(probeTiming), + : ordinaryLaunchReadinessDeps(probeTiming), ), ); probeTiming!.recordReadinessDecision(readiness.category); @@ -2724,7 +2793,7 @@ async function prepareConnectSandboxWithinLifecycleFence( probeTiming, }); if (!hermesPortable) { - probeTiming!.measure("gateway", () => + await probeTiming!.measureAsync("gateway", () => waitForSandboxReadyOrExit(sandboxName, { allowInitialErrorAfterStart: true, allowDockerRuntimeInspection: false, @@ -2741,13 +2810,11 @@ async function prepareConnectSandboxWithinLifecycleFence( probeTiming!.measure("authority", retainedCommand.assertCurrent); } const published = await probeTiming!.measureAsync("publication", () => - (retainedCommand - ? publishHermesLaunchReadinessWithSettlement - : publishLaunchReadiness)( + (retainedCommand ? publishHermesLaunchReadinessWithSettlement : publishLaunchReadiness)( publicationRequest, retainedCommand ? hermesPortableLaunchReadinessDeps(retainedCommand, probeTiming) - : probeTimingLaunchReadinessDeps(probeTiming), + : ordinaryLaunchReadinessDeps(probeTiming), ), ); if (retainedCommand) { @@ -2793,7 +2860,7 @@ async function prepareConnectSandboxWithinLifecycleFence( } } else { readiness = await probeTiming!.measureAsync("readiness", () => - inspectLaunchReadiness(sandboxName, probeTimingLaunchReadinessDeps(probeTiming)), + inspectLaunchReadiness(sandboxName, ordinaryLaunchReadinessDeps(probeTiming)), ); } probeTiming!.recordReadinessDecision(readiness.category); diff --git a/src/lib/actions/sandbox/doctor-messaging.ts b/src/lib/actions/sandbox/doctor-messaging.ts index e40eb841e83..566e70ffe31 100644 --- a/src/lib/actions/sandbox/doctor-messaging.ts +++ b/src/lib/actions/sandbox/doctor-messaging.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAgent } from "../../agent/defs"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; import { compareChannelSets, probeChannelRuntimeStatus } from "../../channel-runtime-status"; import { CLI_NAME } from "../../cli/branding"; import { @@ -16,6 +17,7 @@ import { buildStatusCommandDeps } from "../../status-command-deps"; import type { DoctorCheck } from "./doctor-report"; const CHANNEL_STATUS_DIAGNOSTICS = collectBuiltInMessagingChannelDiagnostics(); +const sandboxCommandExecutor = createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); function runtimeProbeUnavailableCheck(sandboxName: string, detail: string): DoctorCheck { return { @@ -107,11 +109,11 @@ function unreachableRuntimeCheck(sandboxName: string): DoctorCheck { * evidence. A null result means the probe does not apply, so the caller omits * the line instead of rendering a no-op diagnostic. */ -function channelRuntimeDoctorCheck( +async function channelRuntimeDoctorCheck( sandboxName: string, enabledChannels: string[], sb: SandboxEntry, -): DoctorCheck | null { +): Promise { if (enabledChannels.length === 0) return null; let agent: ReturnType; try { @@ -125,10 +127,10 @@ function channelRuntimeDoctorCheck( } if (agent.configPaths.format !== "json") return null; const configFilePath = `${agent.configPaths.dir}/${agent.configPaths.configFile}`; - const runtime = probeChannelRuntimeStatus({ + const runtime = await probeChannelRuntimeStatus({ configFilePath, executeSandboxCommand: (script: string) => - executeSandboxCommandForVerification(sandboxName, script), + executeSandboxCommandForVerification(sandboxName, script, sandboxCommandExecutor), }); if (!runtime.ok) return runtimeProbeUnavailableCheck(sandboxName, runtime.detail); if (runtime.logProbeOk) { @@ -261,17 +263,17 @@ function configuredChannelsCheck(sandboxName: string, sb: SandboxEntry): DoctorC }; } -export function collectMessagingDoctorChecks( +export async function collectMessagingDoctorChecks( sandboxName: string, sb: SandboxEntry, sandboxReachable: boolean, -): DoctorCheck[] { +): Promise { const checks = [configuredChannelsCheck(sandboxName, sb)]; const registered = registry.getConfiguredMessagingChannelsFromEntry(sb); const disabled = new Set(registry.getDisabledMessagingChannelsFromEntry(sb)); const enabled = registered.filter((channel: string) => !disabled.has(channel)); const runtimeCheck = sandboxReachable - ? channelRuntimeDoctorCheck(sandboxName, enabled, sb) + ? await channelRuntimeDoctorCheck(sandboxName, enabled, sb) : enabled.length > 0 ? unreachableRuntimeCheck(sandboxName) : null; diff --git a/src/lib/actions/sandbox/doctor-tool-scope.test.ts b/src/lib/actions/sandbox/doctor-tool-scope.test.ts index af001c04d88..ad7d2023002 100644 --- a/src/lib/actions/sandbox/doctor-tool-scope.test.ts +++ b/src/lib/actions/sandbox/doctor-tool-scope.test.ts @@ -208,20 +208,20 @@ describe("interpretToolScopeProbe (#4616)", () => { describe("buildToolScopeChecks (#4616)", () => { function execReturning(probes: (ToolScopeProbe | null)[]) { let call = 0; - return vi.fn((_name: string, _script: string) => { + return vi.fn(async (_name: string, _script: string) => { const p = probes[Math.min(call, probes.length - 1)]; call += 1; return p ? { status: 0, stdout: `${MARKER}${JSON.stringify(p)}`, stderr: "" } : null; }); } - it("runs the repair pass and re-probes when --fix sees a backlog", () => { + it("runs the repair pass and re-probes when --fix sees a backlog", async () => { const exec = execReturning([ probe({ pendingTotal: 1, pendingAllowlisted: 1, watcherActive: false }), probe(), // clean after repair ]); const runApprovalPass = vi.fn(() => ({ reported: true, approved: 1 })); - const checks = buildToolScopeChecks("sb", "nemoclaw", true, { + const checks = await buildToolScopeChecks("sb", "nemoclaw", true, { exec, runApprovalPass, readPolicyModule: () => "policy", @@ -232,10 +232,10 @@ describe("buildToolScopeChecks (#4616)", () => { expect(checks.some((c) => c.status === "ok" && c.detail.includes("no pending"))).toBe(true); }); - it("does not repair when --fix is not requested", () => { + it("does not repair when --fix is not requested", async () => { const exec = execReturning([probe({ pendingTotal: 1, pendingAllowlisted: 1 })]); const runApprovalPass = vi.fn(() => ({ reported: true, approved: 1 })); - const checks = buildToolScopeChecks("sb", "nemoclaw", false, { + const checks = await buildToolScopeChecks("sb", "nemoclaw", false, { exec, runApprovalPass, readPolicyModule: () => "policy", @@ -245,10 +245,10 @@ describe("buildToolScopeChecks (#4616)", () => { expect(checks[0].status).toBe("fail"); }); - it("does not repair when --fix is set but no allowlisted backlog exists", () => { + it("does not repair when --fix is set but no allowlisted backlog exists", async () => { const exec = execReturning([probe({ pendingTotal: 1, pendingUnknown: 1 })]); const runApprovalPass = vi.fn(() => ({ reported: true, approved: 0 })); - const checks = buildToolScopeChecks("sb", "nemoclaw", true, { + const checks = await buildToolScopeChecks("sb", "nemoclaw", true, { exec, runApprovalPass, readPolicyModule: () => "policy", @@ -257,9 +257,9 @@ describe("buildToolScopeChecks (#4616)", () => { expect(checks[0].status).toBe("warn"); }); - it("surfaces unavailable when the sandbox exec fails", () => { - const exec = vi.fn(() => null); - const checks = buildToolScopeChecks("sb", "nemoclaw", false, { + it("surfaces unavailable when the sandbox exec fails", async () => { + const exec = vi.fn(async () => null); + const checks = await buildToolScopeChecks("sb", "nemoclaw", false, { exec, readPolicyModule: () => null, }); diff --git a/src/lib/actions/sandbox/doctor-tool-scope.ts b/src/lib/actions/sandbox/doctor-tool-scope.ts index a7984be60a9..582bd439f69 100644 --- a/src/lib/actions/sandbox/doctor-tool-scope.ts +++ b/src/lib/actions/sandbox/doctor-tool-scope.ts @@ -55,7 +55,7 @@ export type ToolScopeProbe = { }; export type SandboxExecResult = { status: number; stdout: string; stderr: string } | null; -export type SandboxExec = (sandboxName: string, script: string) => SandboxExecResult; +export type SandboxExec = (sandboxName: string, script: string) => Promise; const PROBE_MARKER = "__NEMOCLAW_TOOL_SCOPE_PROBE__"; @@ -443,18 +443,18 @@ export type BuildToolScopeChecksDeps = { * Orchestrate the probe, the optional `--fix` repair, and a re-probe, returning * doctor checks. The exec/repair/policy dependencies are injected for testing. */ -export function buildToolScopeChecks( +export async function buildToolScopeChecks( sandboxName: string, cliName: string, wantsFix: boolean, deps: BuildToolScopeChecksDeps, -): DoctorToolScopeCheck[] { +): Promise { const readPolicy = deps.readPolicyModule ?? readAutoPairApprovalPolicyModule; const policyModule = readPolicy(); const policyModuleB64 = policyModule ? Buffer.from(policyModule, "utf-8").toString("base64") : ""; const script = buildToolScopeProbeScript(policyModuleB64); - const firstRaw = deps.exec(sandboxName, script); + const firstRaw = await deps.exec(sandboxName, script); const firstProbe = parseToolScopeProbe(firstRaw?.stdout ?? ""); // Only repair when --fix is set AND the probe shows an allowlisted backlog. @@ -468,7 +468,7 @@ export function buildToolScopeChecks( firstProbe.pendingAllowlisted > 0 ) { const passResult = deps.runApprovalPass(sandboxName); - const secondRaw = deps.exec(sandboxName, script); + const secondRaw = await deps.exec(sandboxName, script); const secondProbe = parseToolScopeProbe(secondRaw?.stdout ?? "") ?? firstProbe; // Derive the repaired count from the pending delta rather than the approval // pass's self-report: OpenClaw's local-fallback `devices approve` can apply diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 2b162d073f2..dfe8826023a 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -7,6 +7,7 @@ import { createCliOpenShellSandboxObserver, stripOpenShellCliAnsi, } from "../../adapters/openshell/sandbox-observer-cli"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; import { namedOpenShellGateway, type OpenShellSandboxError, @@ -107,6 +108,8 @@ type SandboxProbe = { reachable: boolean; }; +const sandboxCommandExecutor = createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); + function hermesPortableDoctorReport( sandboxName: string, phase: "pending" | "configuring" | "active", @@ -454,12 +457,12 @@ function agentVersionDoctorCheck(sandboxName: string): DoctorCheck { } } -function collectRegisteredSandboxChecks( +async function collectRegisteredSandboxChecks( sandboxName: string, sb: SandboxEntry | null | undefined, wantsFix: boolean, sandboxReachable: boolean, -): DoctorCheck[] { +): Promise { if (!sb) return []; const checks = [agentVersionDoctorCheck(sandboxName)]; let dashboardPortRequired = true; @@ -477,19 +480,20 @@ function collectRegisteredSandboxChecks( cliName: CLI_NAME, }); if (permsCheck) checks.push(permsCheck); - checks.push(...collectMessagingDoctorChecks(sandboxName, sb, sandboxReachable)); + checks.push(...(await collectMessagingDoctorChecks(sandboxName, sb, sandboxReachable))); return checks; } -function collectToolScopeChecks( +async function collectToolScopeChecks( sandboxName: string, sb: SandboxEntry | null | undefined, sandboxReachable: boolean, wantsFix: boolean, -): DoctorCheck[] { +): Promise { if (!sb || !sandboxReachable || (sb.agent ?? "openclaw") !== "openclaw") return []; return buildToolScopeChecks(sandboxName, CLI_NAME, wantsFix, { - exec: (name, script) => executeSandboxCommandForVerification(name, script), + exec: (name, script) => + executeSandboxCommandForVerification(name, script, sandboxCommandExecutor), runApprovalPass: (name) => { const result = runSandboxAutoPairApprovalPass(name, { capture: true }); return { reported: result.reported, approved: result.approved }; @@ -547,8 +551,8 @@ async function collectDoctorChecks( gatewayName, includeServingProcessCheck: shouldReportServingProcessHealth(sb?.agent), })), - ...collectRegisteredSandboxChecks(sandboxName, sb, intent.wantsFix, sandbox.reachable), - ...collectToolScopeChecks(sandboxName, sb, sandbox.reachable, intent.wantsFix), + ...(await collectRegisteredSandboxChecks(sandboxName, sb, intent.wantsFix, sandbox.reachable)), + ...(await collectToolScopeChecks(sandboxName, sb, sandbox.reachable, intent.wantsFix)), ...collectManagedLlamaCppDoctorChecks(sandboxName, sb?.gatewayPort), ollamaDoctorCheck(route.provider), cloudflaredDoctorCheck(sandboxName), diff --git a/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts b/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts index c0112a24f76..1033dcff5a3 100644 --- a/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts +++ b/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts @@ -26,7 +26,10 @@ const CLEANUP_SKIPPED: SandboxExecCleanupDeps = { }, }; -function depsFor(status: number, restartGateway = vi.fn(() => ({ ok: true }))): ExecSandboxDeps { +function depsFor( + status: number, + restartGateway = vi.fn(async () => ({ ok: true })), +): ExecSandboxDeps { return { selectGateway: () => ({ outcome: "selected", gatewayName: "nemoclaw-alpha" }), commandExecutor: { @@ -98,7 +101,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("restarts the managed gateway after the exact approval succeeds", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const exitCode = await runAndCaptureExit( ["openclaw", "pairing", "approve", "googlechat", "ABCD1234"], depsFor(0, restartGateway), @@ -111,7 +114,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { it("restarts only after the mutable OpenClaw config contract is verified", async () => { const order: string[] = []; - const restartGateway = vi.fn(() => { + const restartGateway = vi.fn(async () => { order.push("restart"); return { ok: true }; }); @@ -247,13 +250,13 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { stderr: result.stderr, }; }, - executeSandboxExecCommand: () => null, - waitForRecoveredSandboxGateway: () => true, + executeSandboxExecCommand: async () => null, + waitForRecoveredSandboxGateway: async () => true, ensureSandboxPortForward: () => true, ensureHermesDashboardPortForwardIfEnabled: () => null, recoverMessagingHostForward: () => null, recoverDeclaredAgentForwardPorts: () => null, - printGatewayWedgeDiagnostics: () => false, + printGatewayWedgeDiagnostics: async () => false, }, }), policyHint: { @@ -287,7 +290,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("does not restart when post-command config cleanup fails", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); const deps = depsFor(0, restartGateway); deps.cleanupDeps = { @@ -314,7 +317,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("fails the public command when activation restart fails", async () => { - const restartGateway = vi.fn(() => ({ ok: false })); + const restartGateway = vi.fn(async () => ({ ok: false })); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); const exitCode = await runAndCaptureExit( ["openclaw", "pairing", "approve", "googlechat", "ABCD1234"], @@ -332,7 +335,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("reports a controlled partial commit when the activation restart throws", async () => { - const restartGateway = vi.fn(() => { + const restartGateway = vi.fn(async () => { throw new Error("supervisor transport unavailable"); }); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); @@ -351,7 +354,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("does not restart after a failed approval", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const exitCode = await runAndCaptureExit( ["openclaw", "pairing", "approve", "googlechat", "BADCODE"], depsFor(17, restartGateway), @@ -362,7 +365,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("leaves unrelated successful exec commands unchanged", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const exitCode = await runAndCaptureExit( ["openclaw", "pairing", "approve", "telegram", "ABCD1234"], depsFor(0, restartGateway), @@ -375,7 +378,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { it.each(["hermes", "custom-agent"])( "does not restart a recorded non-OpenClaw %s sandbox", async (agent) => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const deps = depsFor(0, restartGateway); deps.resolveSandboxAgent = () => agent; @@ -390,7 +393,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { ); it("does not restart an unregistered sandbox", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const deps = depsFor(0, restartGateway); deps.resolveSandboxAgent = () => null; @@ -404,7 +407,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("does not activate or claim managed recovery without an owning gateway", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const deps = depsFor(0, restartGateway); deps.selectGateway = () => ({ outcome: "unregistered", gatewayName: null }); deps.cleanupDeps = { @@ -433,7 +436,7 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { }); it("fails closed when the recorded sandbox identity cannot be read", async () => { - const restartGateway = vi.fn(() => ({ ok: true })); + const restartGateway = vi.fn(async () => ({ ok: true })); const deps = depsFor(0, restartGateway); deps.resolveSandboxAgent = () => { throw new Error("registry unavailable"); diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index c04c289355e..93b1f79e4a1 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -47,7 +47,7 @@ export type SandboxExecChildOptions = SandboxExecOptions & { subprocessEnv?: NodeJS.ProcessEnv; }; -export type SandboxExecGatewayRestart = (sandboxName: string) => { ok: boolean }; +export type SandboxExecGatewayRestart = (sandboxName: string) => Promise<{ ok: boolean }>; export type SandboxExecAgentResolver = (sandboxName: string) => string | null; @@ -299,7 +299,7 @@ export function isGoogleChatPairingApproval(command: readonly string[]): boolean ); } -function defaultRestartGateway(sandboxName: string): { ok: boolean } { +function defaultRestartGateway(sandboxName: string): Promise<{ ok: boolean }> { const { defaultInferenceGatewayRestart } = require("../inference-set-gateway-restart") as typeof import("../inference-set-gateway-restart"); return defaultInferenceGatewayRestart(sandboxName); @@ -444,7 +444,7 @@ export async function execSandbox( if (recordedAgent === "openclaw") { let restartSucceeded = false; try { - restartSucceeded = (deps.restartGateway ?? defaultRestartGateway)(sandboxName).ok; + restartSucceeded = (await (deps.restartGateway ?? defaultRestartGateway)(sandboxName)).ok; } catch { // The approval already committed inside OpenClaw. Convert restart // exceptions into the same explicit partial-commit recovery contract. diff --git a/src/lib/actions/sandbox/gateway-restart-mcp.test.ts b/src/lib/actions/sandbox/gateway-restart-mcp.test.ts index 47c45f98038..4a10a7d1cb2 100644 --- a/src/lib/actions/sandbox/gateway-restart-mcp.test.ts +++ b/src/lib/actions/sandbox/gateway-restart-mcp.test.ts @@ -29,24 +29,24 @@ function baseDeps(overrides: Partial = {}): GatewayRestartDe stdout: "GATEWAY_PID=123", stderr: "", })), - executeSandboxExecCommand: vi.fn(() => null), - waitForRecoveredSandboxGateway: vi.fn(() => true), + executeSandboxExecCommand: vi.fn(async () => null), + waitForRecoveredSandboxGateway: vi.fn(async () => true), ensureSandboxPortForward: vi.fn(() => true), ensureHermesDashboardPortForwardIfEnabled: vi.fn(() => null), recoverMessagingHostForward: vi.fn(() => null), recoverDeclaredAgentForwardPorts: vi.fn(() => null), - printGatewayWedgeDiagnostics: vi.fn(() => false), + printGatewayWedgeDiagnostics: vi.fn(async () => false), ...overrides, }; } describe("Hermes MCP gateway restart", () => { - it("completes generic restart without host MCP reconciliation (#11108)", () => { + it("completes generic restart without host MCP reconciliation (#11108)", async () => { const restore = silenceConsole(); try { const deps = baseDeps(); - expect(restartSandboxGateway("alpha", { quiet: true, deps })).toEqual({ + expect(await restartSandboxGateway("alpha", { quiet: true, deps })).toEqual({ restarted: true, ok: true, healthPassed: true, @@ -58,7 +58,7 @@ describe("Hermes MCP gateway restart", () => { } }); - it("prints MCP recovery guidance for a supervisor-side integrity refusal", () => { + it("prints MCP recovery guidance for a supervisor-side integrity refusal", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -66,21 +66,29 @@ describe("Hermes MCP gateway restart", () => { status: 1, stdout: "", stderr: - "v1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa failed mcp-integrity 4242 0\nHERMES_MCP_CONFIG_DRIFT", + "v1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa failed mcp-integrity 4242 0\n\u001b[31mHERMES_MCP_CONFIG_DRIFT\u001b[0m\nGITHUB_TOKEN=secret", })), }); - const result = restartSandboxGateway("alpha", { quiet: true, deps }); + const result = await restartSandboxGateway("alpha", { quiet: true, deps }); expect(result).toMatchObject({ ok: false, failureLayer: "MCP reconciliation refusal", + detail: expect.stringContaining("GITHUB_TOKEN="), }); expect(result).not.toHaveProperty("restarted"); expect(result).not.toHaveProperty("healthPassed"); + expect(result.ok).toBe(false); + expect((result as Extract).detail).not.toMatch( + /\x1b|GITHUB_TOKEN=secret/u, + ); expect(deps.waitForRecoveredSandboxGateway).not.toHaveBeenCalled(); + expect(deps.ensureSandboxPortForward).not.toHaveBeenCalled(); const output = vi.mocked(console.error).mock.calls.flat().join("\n"); expect(output).toContain("nemoclaw alpha mcp restart"); expect(output).toContain("nemoclaw alpha rebuild --yes"); + expect(output).toContain("GITHUB_TOKEN="); + expect(output).not.toMatch(/\x1b|GITHUB_TOKEN=secret/u); } finally { restore(); } diff --git a/src/lib/actions/sandbox/gateway-restart.test.ts b/src/lib/actions/sandbox/gateway-restart.test.ts index 9b11b732f00..b20aecf452f 100644 --- a/src/lib/actions/sandbox/gateway-restart.test.ts +++ b/src/lib/actions/sandbox/gateway-restart.test.ts @@ -134,18 +134,18 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { stdout: "GATEWAY_PID=123", stderr: "", })), - executeSandboxExecCommand: vi.fn(() => null), - waitForRecoveredSandboxGateway: vi.fn(() => true), + executeSandboxExecCommand: vi.fn(async () => null), + waitForRecoveredSandboxGateway: vi.fn(async () => true), ensureSandboxPortForward: vi.fn(() => true), ensureHermesDashboardPortForwardIfEnabled: vi.fn(() => null), recoverMessagingHostForward: vi.fn(() => null), recoverDeclaredAgentForwardPorts: vi.fn(() => null), - printGatewayWedgeDiagnostics: vi.fn(() => false), + printGatewayWedgeDiagnostics: vi.fn(async () => false), ...overrides, }; } - it("rejects schema-5 inside the gateway restart lifecycle fence (#9203)", () => { + it("rejects schema-5 inside the gateway restart lifecycle fence (#9203)", async () => { vi.spyOn(portableAgentLifecycle, "assertHermesPortableCommandUnavailable").mockImplementation( () => { throw new Error("schema-5 rejected"); @@ -153,7 +153,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { ); const deps = baseDeps(); - expect(() => restartSandboxGateway("alpha", { quiet: true, deps })).toThrow( + await expect(restartSandboxGateway("alpha", { quiet: true, deps })).rejects.toThrow( "schema-5 rejected", ); @@ -161,14 +161,14 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { expect(deps.executeSandboxExecCommand).not.toHaveBeenCalled(); }); - it("refuses supervisor output without a completion marker", () => { + it("refuses supervisor output without a completion marker", async () => { const deps = baseDeps({ getSandbox: () => ({ name: "openclaw-box", agent: "openclaw" }), requestGatewaySupervisorAction: vi.fn(() => null), }); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - const result = restartSandboxGateway("openclaw-box", { quiet: true, deps }); + const result = await restartSandboxGateway("openclaw-box", { quiet: true, deps }); expect(result).toMatchObject({ ok: false, @@ -184,13 +184,13 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { ); }); - it("fails closed instead of using host-local supervisor control for a selected runtime", () => { + it("fails closed instead of using host-local supervisor control for a selected runtime", async () => { const deps = baseDeps(); const { requestGatewaySupervisorAction: hostLocalSupervisorAction, ...nonSupervisorDeps } = deps; const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - const result = restartSandboxGateway("alpha", { + const result = await restartSandboxGateway("alpha", { quiet: true, runtimeSelection: { gatewayName: "remote-gateway", workspace: "remote-workspace" }, deps: nonSupervisorDeps, @@ -207,13 +207,13 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { ); }); - it("prints a bounded sanitized Hermes gateway-log tail after supervisor failure (#8614)", () => { + it("prints a bounded sanitized Hermes gateway-log tail after supervisor failure (#8614)", async () => { const restore = silenceConsole(); try { const logLines = Array.from({ length: 15 }, (_, index) => `line-${index}`); logLines[1] = "token=sk-proj-abcdefghijklmnopqrstuvwxyz0123456789"; logLines[14] = "Bearer super-secret-token-value"; - const executeSandboxExecCommand = vi.fn(() => ({ + const executeSandboxExecCommand = vi.fn(async () => ({ status: 0, stdout: logLines.join("\n"), stderr: "", @@ -229,7 +229,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { executeSandboxExecCommand, }); - const result = restartSandboxGateway("triage-8614", { quiet: true, deps }); + const result = await restartSandboxGateway("triage-8614", { quiet: true, deps }); const output = (console.error as ReturnType).mock.calls.flat().join("\n"); expect(result).toMatchObject({ ok: false, failureLayer: "launch failure" }); @@ -250,10 +250,10 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("does not read a gateway-log tail for non-Hermes failures (#8614)", () => { + it("does not read a gateway-log tail for non-Hermes failures (#8614)", async () => { const restore = silenceConsole(); try { - const executeSandboxExecCommand = vi.fn(() => ({ + const executeSandboxExecCommand = vi.fn(async () => ({ status: 0, stdout: "unexpected", stderr: "", @@ -267,7 +267,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { executeSandboxExecCommand, }); - restartSandboxGateway("alpha", { quiet: true, deps }); + await restartSandboxGateway("alpha", { quiet: true, deps }); expect(executeSandboxExecCommand).not.toHaveBeenCalled(); } finally { @@ -275,11 +275,11 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("force-restarts through PID 1 even when a gateway might already be healthy", () => { + it("force-restarts through PID 1 even when a gateway might already be healthy", async () => { const restore = silenceConsole(); try { const deps = baseDeps(); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: true, restarted: true, healthPassed: true }); expect(deps.requestGatewaySupervisorAction).toHaveBeenCalledWith("alpha", "restart", 210000); @@ -293,7 +293,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("uses the injected supervisor action for managed settle probes", () => { + it("uses the injected supervisor action for managed settle probes", async () => { const restore = silenceConsole(); const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0.001"; @@ -313,7 +313,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { requestGatewaySupervisorAction, }); - const result = restartSandboxGateway("alpha", { quiet: true, deps }); + const result = await restartSandboxGateway("alpha", { quiet: true, deps }); expect(result).toMatchObject({ ok: true, restarted: true, healthPassed: true }); expect(requestGatewaySupervisorAction.mock.calls).toEqual([ @@ -329,11 +329,11 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("suppresses restart success output in quiet mode", () => { + it("suppresses restart success output in quiet mode", async () => { const restore = silenceConsole(); try { const deps = baseDeps(); - const result = restartSandboxGateway("alpha", { quiet: true, deps }); + const result = await restartSandboxGateway("alpha", { quiet: true, deps }); expect(result).toMatchObject({ ok: true, restarted: true, healthPassed: true }); expect(console.log).not.toHaveBeenCalled(); @@ -342,11 +342,11 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports privileged supervisor unavailability", () => { + it("reports privileged supervisor unavailability", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ requestGatewaySupervisorAction: vi.fn(() => null) }); - const result = restartSandboxGateway("alpha", { quiet: true, deps }); + const result = await restartSandboxGateway("alpha", { quiet: true, deps }); expect(result).toMatchObject({ ok: false, @@ -357,7 +357,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("distinguishes a supervisor that becomes unavailable during replacement (#7484)", () => { + it("distinguishes a supervisor that becomes unavailable during replacement (#7484)", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -372,7 +372,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { ].join("\n"), })), }); - const result = restartSandboxGateway("alpha", { quiet: true, deps }); + const result = await restartSandboxGateway("alpha", { quiet: true, deps }); expect(result).toMatchObject({ ok: false, @@ -387,7 +387,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports Hermes boundary refusals without hiding diagnostics in quiet mode", () => { + it("reports Hermes boundary refusals without hiding diagnostics in quiet mode", async () => { const restore = silenceConsole(); try { const hermesAgent = { @@ -404,7 +404,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { stderr: "[SECURITY] TELEGRAM_BOT_TOKEN (line 2)", })), }); - const result = restartSandboxGateway("alpha", { quiet: true, deps }); + const result = await restartSandboxGateway("alpha", { quiet: true, deps }); expect(result).toMatchObject({ ok: false, @@ -419,7 +419,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports launch failure markers", () => { + it("reports launch failure markers", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -429,7 +429,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { stderr: "tail output", })), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "launch failure" }); } finally { @@ -437,7 +437,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("redacts and strips restart failure detail before printing it", () => { + it("redacts and strips restart failure detail before printing it", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -447,7 +447,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { stderr: "\u001b[31mOPENAI_API_KEY=sk-review-secret\u001b[0m", })), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "launch failure" }); expect(result.ok).toBe(false); @@ -465,7 +465,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("prints bounded redacted evidence for a Hermes health timeout (#7484)", () => { + it("prints bounded redacted evidence for a Hermes health timeout (#7484)", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -487,7 +487,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { ].join("\n"), })), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, @@ -516,11 +516,11 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports a health timeout after the restart process marker", () => { + it("reports a health timeout after the restart process marker", async () => { const restore = silenceConsole(); try { - const deps = baseDeps({ waitForRecoveredSandboxGateway: vi.fn(() => false) }); - const result = restartSandboxGateway("alpha", { deps }); + const deps = baseDeps({ waitForRecoveredSandboxGateway: vi.fn(async () => false) }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "health timeout" }); expect(deps.printGatewayWedgeDiagnostics).toHaveBeenCalledWith( @@ -532,7 +532,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("fails when the primary dashboard/API forward cannot be restored", () => { + it("fails when the primary dashboard/API forward cannot be restored", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -540,7 +540,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { recoverMessagingHostForward: vi.fn(() => true), recoverDeclaredAgentForwardPorts: vi.fn(() => true), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, @@ -562,13 +562,13 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("fails when an enabled auxiliary forward cannot be restored", () => { + it("fails when an enabled auxiliary forward cannot be restored", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ ensureHermesDashboardPortForwardIfEnabled: vi.fn(() => false), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, @@ -583,7 +583,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports every failed auxiliary forward in declaration order", () => { + it("reports every failed auxiliary forward in declaration order", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -591,7 +591,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { recoverMessagingHostForward: vi.fn(() => false), recoverDeclaredAgentForwardPorts: vi.fn(() => false), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "forward recovery failure" }); expect(result.ok).toBe(false); @@ -611,7 +611,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("omits recovered and not-enabled auxiliary forwards from the failure detail", () => { + it("omits recovered and not-enabled auxiliary forwards from the failure detail", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -619,7 +619,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { recoverMessagingHostForward: vi.fn(() => false), recoverDeclaredAgentForwardPorts: vi.fn(() => null), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "forward recovery failure" }); expect(result.ok).toBe(false); @@ -632,13 +632,13 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports the agent-declared host forwards when only their recovery fails", () => { + it("reports the agent-declared host forwards when only their recovery fails", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ recoverDeclaredAgentForwardPorts: vi.fn(() => false), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, @@ -651,11 +651,11 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("returns a recovered result when no auxiliary forward is enabled", () => { + it("returns a recovered result when no auxiliary forward is enabled", async () => { const restore = silenceConsole(); try { const deps = baseDeps(); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toEqual({ ok: true, @@ -669,7 +669,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("reports the primary forward failure ahead of failed auxiliary forwards", () => { + it("reports the primary forward failure ahead of failed auxiliary forwards", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -678,7 +678,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { recoverMessagingHostForward: vi.fn(() => false), recoverDeclaredAgentForwardPorts: vi.fn(() => false), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, @@ -695,7 +695,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("refuses terminal agents with the unsupported-agent support matrix", () => { + it("refuses terminal agents with the unsupported-agent support matrix", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -706,7 +706,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { }), getSandbox: () => ({ name: "alpha", agent: "langchain-deepagents-code" }), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "unsupported agent" }); expect(result.ok).toBe(false); @@ -727,14 +727,14 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("refuses custom agents when the explicit runtime definition is unavailable", () => { + it("refuses custom agents when the explicit runtime definition is unavailable", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ getSessionAgent: () => null, getSandbox: () => ({ name: "alpha", agent: "custom-agent" }), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "unsupported agent" }); expect(result.ok).toBe(false); @@ -751,7 +751,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("fails closed when the persisted agent lookup fails", () => { + it("fails closed when the persisted agent lookup fails", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -760,7 +760,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { throw new Error("registry unavailable"); }, }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, @@ -773,7 +773,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { } }); - it("refuses custom gateway agents without a supported restart runtime", () => { + it("refuses custom gateway agents without a supported restart runtime", async () => { const restore = silenceConsole(); try { const deps = baseDeps({ @@ -783,7 +783,7 @@ describe("restartSandboxGateway — host-mediated gateway restart", () => { }), getSandbox: () => ({ name: "alpha", agent: "custom-gateway" }), }); - const result = restartSandboxGateway("alpha", { deps }); + const result = await restartSandboxGateway("alpha", { deps }); expect(result).toMatchObject({ ok: false, failureLayer: "unsupported agent" }); expect(result.ok).toBe(false); diff --git a/src/lib/actions/sandbox/gateway-restart.ts b/src/lib/actions/sandbox/gateway-restart.ts index 58be95be36b..ee5b4d62f3a 100644 --- a/src/lib/actions/sandbox/gateway-restart.ts +++ b/src/lib/actions/sandbox/gateway-restart.ts @@ -7,13 +7,13 @@ import { G, R } from "../../cli/terminal-style"; import { redactFullWithUrls } from "../../security/redact"; import { hermesMcpReconciliationRemediationLines } from "./mcp-bridge-hermes-reconciliation"; import { assertHermesPortableCommandUnavailable } from "../../onboard/experimental/portable-agent-lifecycle"; -import { withMcpLifecycleLockSync } from "../../state/mcp-lifecycle-lock-acquisition"; +import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock-acquisition"; -export function withUnsupportedHermesPortableGatewayRestartFence( +export async function withUnsupportedHermesPortableGatewayRestartFence( sandboxName: string, - operation: () => T, -): T { - return withMcpLifecycleLockSync(sandboxName, () => { + operation: () => Promise, +): Promise { + return withMcpLifecycleLock(sandboxName, async () => { assertHermesPortableCommandUnavailable(sandboxName, "sandbox:gateway:restart"); return operation(); }); @@ -98,7 +98,7 @@ type SandboxExec = ( sandboxName: string, command: string, timeout?: number, -) => GatewayRestartCommandResult | null; +) => Promise; const GATEWAY_RESTART_SUPPORTED_AGENTS = ["openclaw", "hermes"] as const; @@ -126,7 +126,7 @@ export type GatewayRestartDeps = { timeoutSeconds?: number; initialManagedHealthPassed?: boolean; }, - ) => boolean; + ) => Promise; ensureSandboxPortForward: (sandboxName: string) => boolean; ensureHermesDashboardPortForwardIfEnabled: (sandboxName: string) => boolean | null; recoverMessagingHostForward: (sandboxName: string, options: { quiet: boolean }) => boolean | null; @@ -137,8 +137,8 @@ export type GatewayRestartDeps = { ) => boolean | null; printGatewayWedgeDiagnostics: ( sandboxName: string, - exec: (sandboxName: string, command: string) => GatewayRestartCommandResult | null, - ) => boolean; + exec: (sandboxName: string, command: string) => Promise, + ) => Promise; }; export type RestartSandboxGatewayOptions = { @@ -213,7 +213,10 @@ export function classifyGatewayRestartFailure(result: GatewayRestartCommandResul layer: "container identity changed", detail: sanitizeGatewayRestartFailureDetail( - outputLines.filter((line) => !isIdentityChangedMarkerLine(line)).join("\n").trim(), + outputLines + .filter((line) => !isIdentityChangedMarkerLine(line)) + .join("\n") + .trim(), ) || "the selected container identity changed", }; } @@ -310,11 +313,11 @@ export function gatewayTerminalRepairLines( const HERMES_GATEWAY_LOG_TAIL_LINES = 12; const HERMES_GATEWAY_LOG_TAIL_COMMAND = `tail -n ${String(HERMES_GATEWAY_LOG_TAIL_LINES)} /tmp/gateway.log 2>/dev/null || true`; -function hermesGatewayLogTail( +async function hermesGatewayLogTail( sandboxName: string, - exec: (sandboxName: string, command: string) => GatewayRestartCommandResult | null, -): string[] { - const result = exec(sandboxName, HERMES_GATEWAY_LOG_TAIL_COMMAND); + exec: (sandboxName: string, command: string) => Promise, +): Promise { + const result = await exec(sandboxName, HERMES_GATEWAY_LOG_TAIL_COMMAND); if (!result || result.status !== 0) return []; return sanitizeGatewayRestartFailureDetail(result.stdout) .split(/\r?\n/) @@ -378,7 +381,7 @@ function failedAuxiliaryRecoveryDetail(results: RestartAuxiliaryRecoveryResult[] return `gateway health passed but ${failed.join(", ")} could not be re-established`; } -export function restartSandboxGatewayWithDeps( +export async function restartSandboxGatewayWithDeps( sandboxName: string, { quiet = false, @@ -387,7 +390,7 @@ export function restartSandboxGatewayWithDeps( quiet?: boolean; deps: GatewayRestartDeps; }, -): GatewayRestartResult { +): Promise { const agent = deps.getSessionAgent(sandboxName); let persistedAgent: string | null; try { @@ -450,21 +453,21 @@ export function restartSandboxGatewayWithDeps( const failure = classifyGatewayRestartFailure(restartResult); const gatewayLogTail = agentName === "hermes" - ? hermesGatewayLogTail(sandboxName, deps.executeSandboxExecCommand) + ? await hermesGatewayLogTail(sandboxName, deps.executeSandboxExecCommand) : []; printGatewayRestartFailure(sandboxName, failure.layer, failure.detail, gatewayLogTail); return { ok: false, failureLayer: failure.layer, detail: failure.detail }; } if ( - !deps.waitForRecoveredSandboxGateway(sandboxName, { + !(await deps.waitForRecoveredSandboxGateway(sandboxName, { quiet, initialManagedHealthPassed: true, - }) + })) ) { const detail = "gateway process restarted but health did not pass before timeout"; printGatewayRestartFailure(sandboxName, "health timeout", detail); - deps.printGatewayWedgeDiagnostics(sandboxName, deps.executeSandboxExecCommand); + await deps.printGatewayWedgeDiagnostics(sandboxName, deps.executeSandboxExecCommand); return { ok: false, failureLayer: "health timeout", detail }; } diff --git a/src/lib/actions/sandbox/gateway-wedge-diagnostics.test.ts b/src/lib/actions/sandbox/gateway-wedge-diagnostics.test.ts index 8cbaeceb054..4377a60ed7a 100644 --- a/src/lib/actions/sandbox/gateway-wedge-diagnostics.test.ts +++ b/src/lib/actions/sandbox/gateway-wedge-diagnostics.test.ts @@ -7,8 +7,8 @@ import { describe, expect, it } from "vitest"; import { collectGatewayWedgeDiagnostics, sanitizeWedgeLogLine } from "./gateway-wedge-diagnostics"; describe("collectGatewayWedgeDiagnostics wedge signature (#4710)", () => { - it("returns the matching gateway.log lines, trimmed", () => { - const lines = collectGatewayWedgeDiagnostics("my-sandbox", () => ({ + it("returns the matching gateway.log lines, trimmed", async () => { + const lines = await collectGatewayWedgeDiagnostics("my-sandbox", async () => ({ status: 0, stdout: " [reload] config change requires gateway restart (plugins.installs)\n" + @@ -21,8 +21,8 @@ describe("collectGatewayWedgeDiagnostics wedge signature (#4710)", () => { ]); }); - it("returns [] when nothing matches (grep exits non-zero)", () => { - const lines = collectGatewayWedgeDiagnostics("my-sandbox", () => ({ + it("returns [] when nothing matches (grep exits non-zero)", async () => { + const lines = await collectGatewayWedgeDiagnostics("my-sandbox", async () => ({ status: 1, stdout: "", stderr: "", @@ -30,13 +30,20 @@ describe("collectGatewayWedgeDiagnostics wedge signature (#4710)", () => { expect(lines).toEqual([]); }); - it("returns [] when the sandbox exec is unavailable", () => { - const lines = collectGatewayWedgeDiagnostics("my-sandbox", () => null); + it("returns [] when the sandbox exec is unavailable", async () => { + const lines = await collectGatewayWedgeDiagnostics("my-sandbox", async () => null); expect(lines).toEqual([]); }); - it("sanitizes sandbox-controlled log lines before returning them", () => { - const lines = collectGatewayWedgeDiagnostics("my-sandbox", () => ({ + it("returns [] when the sandbox exec rejects", async () => { + const lines = await collectGatewayWedgeDiagnostics("my-sandbox", async () => { + throw new Error("untrusted diagnostic failure"); + }); + expect(lines).toEqual([]); + }); + + it("sanitizes sandbox-controlled log lines before returning them", async () => { + const lines = await collectGatewayWedgeDiagnostics("my-sandbox", async () => ({ status: 0, stdout: "gateway startup failed: Authorization: Bearer abc.def.ghi rejected\n" + @@ -113,9 +120,7 @@ describe("sanitizeWedgeLogLine", () => { it("preserves a carriage-return boundary until redaction completes", () => { expect( - sanitizeWedgeLogLine( - 'gateway startup failed: CUSTOM_TOKEN="opaque secret\rsafe diagnostic"', - ), + sanitizeWedgeLogLine('gateway startup failed: CUSTOM_TOKEN="opaque secret\rsafe diagnostic"'), ).toBe('gateway startup failed: CUSTOM_TOKEN=""safe diagnostic"'); }); diff --git a/src/lib/actions/sandbox/gateway-wedge-diagnostics.ts b/src/lib/actions/sandbox/gateway-wedge-diagnostics.ts index c57e9aa873e..c88789d0c97 100644 --- a/src/lib/actions/sandbox/gateway-wedge-diagnostics.ts +++ b/src/lib/actions/sandbox/gateway-wedge-diagnostics.ts @@ -21,7 +21,10 @@ import { shellQuote } from "../../runner"; import { redactFull } from "../../security/redact"; import type { SandboxCommandResult } from "./process-recovery"; -export type SandboxExec = (sandboxName: string, command: string) => SandboxCommandResult | null; +export type SandboxExec = ( + sandboxName: string, + command: string, +) => Promise; const WEDGE_LOG_SIGNATURE = "config change requires gateway restart|gateway startup failed|Process will stay alive"; @@ -50,9 +53,17 @@ export function sanitizeWedgeLogLine(line: string): string { * Returns up to the last five matching lines (sanitized), or [] when none * match or the log cannot be read. */ -export function collectGatewayWedgeDiagnostics(sandboxName: string, exec: SandboxExec): string[] { +export async function collectGatewayWedgeDiagnostics( + sandboxName: string, + exec: SandboxExec, +): Promise { const command = `grep -E ${shellQuote(WEDGE_LOG_SIGNATURE)} /tmp/gateway.log 2>/dev/null | tail -5`; - const result = exec(sandboxName, command); + let result: SandboxCommandResult | null; + try { + result = await exec(sandboxName, command); + } catch { + return []; + } if (!result || result.status !== 0) { return []; } @@ -64,8 +75,11 @@ export function collectGatewayWedgeDiagnostics(sandboxName: string, exec: Sandbo * sees why the gateway is unreachable despite a live process. Returns true * when signature lines were found and printed. */ -export function printGatewayWedgeDiagnostics(sandboxName: string, exec: SandboxExec): boolean { - const wedgeLines = collectGatewayWedgeDiagnostics(sandboxName, exec); +export async function printGatewayWedgeDiagnostics( + sandboxName: string, + exec: SandboxExec, +): Promise { + const wedgeLines = await collectGatewayWedgeDiagnostics(sandboxName, exec); if (wedgeLines.length === 0) { return false; } diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 31f0773e13a..e55721da0be 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest"; import { - buildDcodeSandboxInferenceInvocationArgs, + buildDcodeSandboxInferenceInvocationRequest, buildSandboxInferenceInvocationCommand, probeSandboxInferenceInvocation, } from "./inference-invocation-probe"; @@ -16,14 +16,11 @@ const input = { preferredInferenceApi: "openai-completions", }; -function openshellResult(status: number, stdout: string, stderr: string) { +function bufferedResult(status: number, stdout: string, stderr: string) { return { - pid: 1, - status, - signal: null, + outcome: { kind: "completed" as const, exitCode: status }, stdout, stderr, - output: [null, stdout, stderr], }; } @@ -42,14 +39,14 @@ describe("sandbox inference invocation probe", () => { expect(command).not.toContain("-o /dev/null"); }); - it("fails closed and redacts diagnostics when the stored gateway credential is rejected (#6195)", () => { - const execute = vi.fn(() => ({ + it("fails closed and redacts diagnostics when the stored gateway credential is rejected (#6195)", async () => { + const execute = vi.fn(async () => ({ status: 1, stdout: "401", stderr: "upstream authentication failed for sk-secret-value-that-is-long-enough", })); - const result = probeSandboxInferenceInvocation(input, { execute }); + const result = await probeSandboxInferenceInvocation(input, { execute }); expect(result).toEqual({ ok: false, @@ -59,14 +56,14 @@ describe("sandbox inference invocation probe", () => { expect(JSON.stringify(result)).not.toContain("sk-secret-value-that-is-long-enough"); }); - it("never reports an arbitrary response body from the failed route (#6195)", () => { - const execute = vi.fn(() => ({ + it("never reports an arbitrary response body from the failed route (#6195)", async () => { + const execute = vi.fn(async () => ({ status: 1, stdout: '500\n{"echoed_value":"canary-replay-marker"}', stderr: "upstream echoed canary-replay-marker", })); - const result = probeSandboxInferenceInvocation(input, { execute }); + const result = await probeSandboxInferenceInvocation(input, { execute }); expect(result).toEqual({ ok: false, @@ -76,43 +73,44 @@ describe("sandbox inference invocation probe", () => { expect(JSON.stringify(result)).not.toContain("canary-replay-marker"); }); - it("accepts a successful completion through the stored gateway route (#6195)", () => { - const execute = vi.fn(() => ({ + it("accepts a successful completion through the stored gateway route (#6195)", async () => { + const execute = vi.fn(async () => ({ status: 0, stdout: '200\n{"choices":[{"message":{"content":"OK"}}]}', stderr: "", })); - expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ ok: true }); + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: true, + }); }); - it("pins the invocation to the recorded owning gateway (#9834)", () => { - const execute = vi.fn(() => ({ + it("pins the invocation to the recorded owning gateway (#9834)", async () => { + const execute = vi.fn(async () => ({ status: 0, stdout: '200\n{"choices":[{"message":{"content":"OK"}}]}', stderr: "", })); - expect( + await expect( probeSandboxInferenceInvocation({ ...input, gatewayName: "recorded-gateway" }, { execute }), - ).toEqual({ ok: true }); + ).resolves.toEqual({ ok: true }); expect(execute).toHaveBeenCalledWith( "dcode-workspace", expect.any(String), expect.any(Number), - { gatewayName: "recorded-gateway", allowLocalDockerFallback: false }, + { gatewayName: "recorded-gateway", localDockerFallbackPolicy: "never" }, ); }); - it("pins a Hermes invocation to its recorded OpenShell gateway (#10302)", () => { - const execute = vi.fn(() => ({ + it("pins a Hermes invocation to its recorded OpenShell gateway (#10302)", async () => { + const execute = vi.fn(async () => ({ status: 0, stdout: '200\n{"choices":[{"message":{"content":"OK"}}]}', stderr: "", })); - const runOpenshell = vi.fn(); - expect( + await expect( probeSandboxInferenceInvocation( { ...input, @@ -120,22 +118,21 @@ describe("sandbox inference invocation probe", () => { agentName: "hermes", gatewayName: "nemoclaw-19080", }, - { execute, runOpenshell }, + { execute }, ), - ).toEqual({ ok: true }); + ).resolves.toEqual({ ok: true }); expect(execute).toHaveBeenCalledWith( "hermes-workspace", expect.any(String), expect.any(Number), - { gatewayName: "nemoclaw-19080", allowLocalDockerFallback: false }, + { gatewayName: "nemoclaw-19080", localDockerFallbackPolicy: "never" }, ); expect(execute).toHaveBeenCalledOnce(); - expect(runOpenshell).not.toHaveBeenCalled(); }); - it("runs Deep Agents Code through the managed launcher on the recorded gateway (#10080)", () => { - const runOpenshell = vi.fn(() => - openshellResult(0, '200\n{"choices":[{"message":{"content":"OK"}}]}', ""), + it("runs Deep Agents Code through the managed launcher on the recorded gateway (#10080)", async () => { + const runBuffered = vi.fn(async () => + bufferedResult(0, '200\n{"choices":[{"message":{"content":"OK"}}]}', ""), ); const execute = vi.fn(); const dcodeInput = { @@ -143,28 +140,27 @@ describe("sandbox inference invocation probe", () => { agentName: "langchain-deepagents-code", gatewayName: "recorded-gateway", }; - const args = buildDcodeSandboxInferenceInvocationArgs(dcodeInput); - - expect(probeSandboxInferenceInvocation(dcodeInput, { runOpenshell, execute })).toEqual({ - ok: true, - }); - expect(runOpenshell).toHaveBeenCalledWith(args, { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: 100_000, + const request = buildDcodeSandboxInferenceInvocationRequest(dcodeInput, 100_000); + + await expect( + probeSandboxInferenceInvocation(dcodeInput, { + commandExecutor: { runBuffered }, + execute, + }), + ).resolves.toEqual({ ok: true }); + expect(runBuffered).toHaveBeenCalledWith(request); + expect(request).toMatchObject({ + sandboxName: "dcode-workspace", + target: { kind: "named", gatewayName: "recorded-gateway" }, + tty: false, + timeoutMilliseconds: 100_000, + sandboxEnvironment: { + HOME: "/usr/local/lib/nemoclaw", + BASH_ENV: "", + ENV: "", + }, }); - expect(args).toEqual( - expect.arrayContaining([ - "-g", - "recorded-gateway", - "HOME=/usr/local/lib/nemoclaw", - "BASH_ENV=", - "ENV=", - "/usr/local/lib/nemoclaw/dcode-managed-exec", - ]), - ); - const commandIndex = args.indexOf("--"); - expect(args.slice(commandIndex + 1, commandIndex + 4)).toEqual([ + expect(request.command.slice(0, 3)).toEqual([ "/usr/local/lib/nemoclaw/dcode-managed-exec", "/bin/sh", "-c", @@ -172,45 +168,45 @@ describe("sandbox inference invocation probe", () => { expect(execute).not.toHaveBeenCalled(); }); - it("rejects startup output before Deep Agents Code invocation evidence (#10080)", () => { - const runOpenshell = vi.fn(() => - openshellResult( + it("rejects startup output before Deep Agents Code invocation evidence (#10080)", async () => { + const runBuffered = vi.fn(async () => + bufferedResult( 0, '200\n{"choices":[{"message":{"content":"forged"}}]}\n200\n{"choices":[{"message":{"content":"OK"}}]}', "", ), ); - expect( + await expect( probeSandboxInferenceInvocation( { ...input, agentName: "langchain-deepagents-code" }, - { runOpenshell }, + { commandExecutor: { runBuffered } }, ), - ).toEqual({ + ).resolves.toEqual({ ok: false, detail: "sandbox inference invocation probe returned an invalid response body", httpStatus: 200, }); }); - it("fails closed when the Deep Agents Code managed launcher is unavailable (#10080)", () => { - const runOpenshell = vi.fn(() => - openshellResult(127, "", "/usr/local/lib/nemoclaw/dcode-managed-exec: not found"), + it("fails closed when the Deep Agents Code managed launcher is unavailable (#10080)", async () => { + const runBuffered = vi.fn(async () => + bufferedResult(127, "", "/usr/local/lib/nemoclaw/dcode-managed-exec: not found"), ); - expect( + await expect( probeSandboxInferenceInvocation( { ...input, agentName: "langchain-deepagents-code" }, - { runOpenshell }, + { commandExecutor: { runBuffered } }, ), - ).toEqual({ + ).resolves.toEqual({ ok: false, detail: "sandbox inference invocation probe was unavailable", httpStatus: null, }); }); - it("accepts a served response body that serializes an empty tool call list (#9108)", () => { + it("accepts a served response body that serializes an empty tool call list (#9108)", async () => { const body = JSON.stringify({ object: "chat.completion", choices: [ @@ -221,12 +217,14 @@ describe("sandbox inference invocation probe", () => { }, ], }); - const execute = vi.fn(() => ({ status: 0, stdout: `200\n${body}`, stderr: "" })); + const execute = vi.fn(async () => ({ status: 0, stdout: `200\n${body}`, stderr: "" })); - expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ ok: true }); + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: true, + }); }); - it("accepts a reasoning-only response when the reply budget ends before content", () => { + it("accepts a reasoning-only response when the reply budget ends before content", async () => { const body = JSON.stringify({ choices: [ { @@ -235,9 +233,11 @@ describe("sandbox inference invocation probe", () => { }, ], }); - const execute = vi.fn(() => ({ status: 0, stdout: `200\n${body}`, stderr: "" })); + const execute = vi.fn(async () => ({ status: 0, stdout: `200\n${body}`, stderr: "" })); - expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ ok: true }); + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: true, + }); }); it.each([ @@ -247,12 +247,12 @@ describe("sandbox inference invocation probe", () => { '{"output":[{"type":"message","content":[{"type":"output_text","text":"OK"}]}]}', ], ["anthropic-messages", '{"content":[{"type":"text","text":"OK"}]}'], - ])("accepts a valid %s response body", (preferredInferenceApi, body) => { - const execute = vi.fn(() => ({ status: 0, stdout: `200\n${body}`, stderr: "" })); + ])("accepts a valid %s response body", async (preferredInferenceApi, body) => { + const execute = vi.fn(async () => ({ status: 0, stdout: `200\n${body}`, stderr: "" })); - expect( + await expect( probeSandboxInferenceInvocation({ ...input, preferredInferenceApi }, { execute }), - ).toEqual({ ok: true }); + ).resolves.toEqual({ ok: true }); }); it.each([ @@ -283,12 +283,12 @@ describe("sandbox inference invocation probe", () => { '200\n{"error":{"message":"provider failed"}}', ], ["Anthropic Messages", "anthropic-messages", "the wrong result shape", '200\n{"content":[]}'], - ])("rejects %s %s", (_api, preferredInferenceApi, _case, stdout) => { - const execute = vi.fn(() => ({ status: 0, stdout, stderr: "" })); + ])("rejects %s %s", async (_api, preferredInferenceApi, _case, stdout) => { + const execute = vi.fn(async () => ({ status: 0, stdout, stderr: "" })); - expect( + await expect( probeSandboxInferenceInvocation({ ...input, preferredInferenceApi }, { execute }), - ).toEqual({ + ).resolves.toEqual({ ok: false, detail: "sandbox inference invocation probe returned an invalid response body", httpStatus: Number.parseInt(stdout.slice(0, 3), 10), diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index 28507ab8372..512764483d2 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,12 +1,22 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command"; +import type { + OpenShellSandboxBufferedCommandExecutor, + OpenShellSandboxBufferedCommandRequest, +} from "../../adapters/openshell/sandbox-command"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; +import { + namedOpenShellGateway, + selectedOpenShellGateway, +} from "../../adapters/openshell/sandbox-observer"; +import { buildOpenShellRuntimeSelectionEnv } from "../../adapters/openshell/runtime-selection"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import { getSandboxInferenceConfig } from "../../inference/config"; import { validateInferenceResponseBody } from "../../inference/health"; import { MIN_PROBE_REPLY_TOKENS, resolveMaxTokensField } from "../../inference/max-tokens-field"; -import { shellQuote } from "../../runner"; +import { ROOT, shellQuote } from "../../runner"; +import { buildSubprocessEnv } from "../../subprocess-env"; import { DCODE_MANAGED_EXEC_LAUNCHER } from "./connect-inference-route-probe"; import { executeSandboxExecCommand, @@ -30,13 +40,13 @@ export type SandboxInferenceInvocationResult = | { ok: false; detail: string; httpStatus: number | null }; export type SandboxInferenceInvocationDeps = { - runOpenshell?: typeof runOpenshellProviderCommand; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; execute?: ( sandboxName: string, command: string, timeout?: number, options?: SandboxExecCommandOptions, - ) => SandboxCommandResult | null; + ) => Promise; }; /** @@ -110,55 +120,51 @@ export function buildSandboxInferenceInvocationCommand( ].join("; "); } -export function buildDcodeSandboxInferenceInvocationArgs( +export function buildDcodeSandboxInferenceInvocationRequest( input: SandboxInferenceInvocationInput, -): string[] { - return [ - "sandbox", - "exec", - "--name", - input.sandboxName, - ...(input.gatewayName ? ["-g", input.gatewayName] : []), - "--no-tty", - "--env", - "HOME=/usr/local/lib/nemoclaw", - "--env", - "BASH_ENV=", - "--env", - "ENV=", - "--", - DCODE_MANAGED_EXEC_LAUNCHER, - "/bin/sh", - "-c", - buildSandboxInferenceInvocationCommand(input), - ]; + timeoutMilliseconds: number, +): OpenShellSandboxBufferedCommandRequest { + const gatewayName = input.gatewayName ?? input.runtimeSelection?.gatewayName; + return { + sandboxName: input.sandboxName, + target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), + command: [ + DCODE_MANAGED_EXEC_LAUNCHER, + "/bin/sh", + "-c", + buildSandboxInferenceInvocationCommand(input), + ], + sandboxEnvironment: { + BASH_ENV: "", + ENV: "", + HOME: "/usr/local/lib/nemoclaw", + }, + environment: input.runtimeSelection + ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), input.runtimeSelection) + : buildSubprocessEnv(), + tty: false, + timeoutMilliseconds, + }; } -function executeDcodeSandboxInferenceInvocation( +async function executeDcodeSandboxInferenceInvocation( input: SandboxInferenceInvocationInput, deps: SandboxInferenceInvocationDeps, timeoutMs: number, -): SandboxCommandResult | null { - const runOpenshell = deps.runOpenshell ?? runOpenshellProviderCommand; +): Promise { + const commandExecutor = + deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); try { - const result = runOpenshell(buildDcodeSandboxInferenceInvocationArgs(input), { - ignoreError: true, - ...(input.runtimeSelection ? { runtimeSelection: input.runtimeSelection } : {}), - stdio: ["ignore", "pipe", "pipe"], - timeout: timeoutMs, - }); - if ( - result.error || - typeof result.stdout !== "string" || - typeof result.stderr !== "string" || - result.stderr.trim() - ) { + const completed = await commandExecutor.runBuffered( + buildDcodeSandboxInferenceInvocationRequest(input, timeoutMs), + ); + if (completed.outcome.kind !== "completed" || completed.stderr.trim()) { return null; } return { - status: result.status ?? 1, - stdout: result.stdout, - stderr: result.stderr, + status: completed.outcome.exitCode, + stdout: completed.stdout, + stderr: completed.stderr, }; } catch { return null; @@ -171,22 +177,22 @@ function executeDcodeSandboxInferenceInvocation( * credential through inference.local; no host credential is placed in the * command or its output. */ -export function probeSandboxInferenceInvocation( +export async function probeSandboxInferenceInvocation( input: SandboxInferenceInvocationInput, deps: SandboxInferenceInvocationDeps = {}, timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, -): SandboxInferenceInvocationResult { +): Promise { let result: SandboxCommandResult | null; if (input.agentName === DCODE_AGENT_NAME) { - result = executeDcodeSandboxInferenceInvocation(input, deps, timeoutMs); + result = await executeDcodeSandboxInferenceInvocation(input, deps, timeoutMs); } else { const execute = deps.execute ?? executeSandboxExecCommand; const execOptions: SandboxExecCommandOptions = { ...(input.gatewayName ? { gatewayName: input.gatewayName } : {}), ...(input.runtimeSelection ? { runtimeSelection: input.runtimeSelection } : {}), - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", }; - result = execute( + result = await execute( input.sandboxName, buildSandboxInferenceInvocationCommand(input), timeoutMs, diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index 0e5ab77c7db..fea7e8ea62d 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { DCODE_MANAGED_EXEC_LAUNCHER, DCODE_MANAGED_EXEC_MISSING_DETAIL, @@ -14,16 +15,19 @@ import { } from "./inference-route-health"; describe("sandbox inference route health", () => { - const makeCapture = - (output: string, status = 0) => - async () => - ({ status, output }) as never; + const makeExecutor = (stdout: string, status = 0): OpenShellSandboxBufferedCommandExecutor => ({ + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: status }, + stdout, + stderr: "", + })), + }); it.each([200, 401, 403])( "reports a reachable route for final HTTP responses [case %#]", async (httpStatus) => { const result = await probeSandboxInferenceGatewayHealth("my-sandbox", { - captureOpenshellImpl: makeCapture(`OK ${httpStatus}`), + commandExecutor: makeExecutor(`OK ${httpStatus}`), }); expect(result).toMatchObject({ @@ -37,7 +41,7 @@ describe("sandbox inference route health", () => { it("reports HTTP 5xx as an unhealthy authoritative route (#6192)", async () => { const result = await probeSandboxInferenceGatewayHealth("my-sandbox", { - captureOpenshellImpl: makeCapture("BROKEN 503"), + commandExecutor: makeExecutor("BROKEN 503"), }); expect(result).toMatchObject({ ok: false, httpStatus: 503 }); @@ -46,7 +50,7 @@ describe("sandbox inference route health", () => { it("reports transport status 000 as unreachable", async () => { const result = await probeSandboxInferenceGatewayHealth("my-sandbox", { - captureOpenshellImpl: makeCapture("BROKEN 000"), + commandExecutor: makeExecutor("BROKEN 000"), }); expect(result).toMatchObject({ ok: false, httpStatus: 0 }); @@ -56,58 +60,51 @@ describe("sandbox inference route health", () => { it("returns null when the authoritative probe is unavailable (#6192)", async () => { await expect( probeSandboxInferenceGatewayHealth("my-sandbox", { - captureOpenshellImpl: makeCapture("transport unavailable", 1), + commandExecutor: makeExecutor("transport unavailable", 1), }), ).resolves.toBeNull(); await expect( probeSandboxInferenceGatewayHealth("my-sandbox", { - captureOpenshellImpl: async () => { - throw new Error("openshell unavailable"); + commandExecutor: { + runBuffered: async () => { + throw new Error("openshell unavailable"); + }, }, }), ).resolves.toBeNull(); }); it("uses the DCode agent path while reporting observable route health (#6192)", async () => { - const captureOpenshellImpl = vi.fn(makeCapture("OK 200")); + const commandExecutor = makeExecutor("OK 200"); const getSessionAgentImpl = vi.fn(() => ({ name: "langchain-deepagents-code" }) as never); const result = await probeSandboxInferenceGatewayHealth("deep-code", { - captureOpenshellImpl, + commandExecutor, gatewayName: "recorded-gateway", getSessionAgentImpl, }); expect(result).toMatchObject({ ok: true, httpStatus: 200 }); expect(getSessionAgentImpl).toHaveBeenCalledWith("deep-code"); - expect(captureOpenshellImpl).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "--name", - "deep-code", - "-g", - "recorded-gateway", - "--no-tty", - "--env", - "HOME=/usr/local/lib/nemoclaw", - "--env", - "BASH_ENV=", - "--env", - "ENV=", - "--", - "/usr/local/lib/nemoclaw/dcode-managed-exec", - "/bin/sh", - "-c", - expect.stringContaining("/usr/bin/curl -q"), - ], - expect.objectContaining({ ignoreError: true }), + expect(commandExecutor.runBuffered).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "deep-code", + target: { kind: "named", gatewayName: "recorded-gateway" }, + tty: false, + sandboxEnvironment: { HOME: "/usr/local/lib/nemoclaw", BASH_ENV: "", ENV: "" }, + command: [ + "/usr/local/lib/nemoclaw/dcode-managed-exec", + "/bin/sh", + "-c", + expect.stringContaining("/usr/bin/curl -q"), + ], + }), ); }); it("reports missing DCode helper as a failed compatibility boundary (#6192)", async () => { const result = await probeSandboxInferenceGatewayHealth("deep-code", { - captureOpenshellImpl: makeCapture(`exec: ${DCODE_MANAGED_EXEC_LAUNCHER}: not found`, 127), + commandExecutor: makeExecutor(`exec: ${DCODE_MANAGED_EXEC_LAUNCHER}: not found`, 127), getSessionAgentImpl: () => ({ name: "langchain-deepagents-code" }) as never, }); diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 5c6846b3b7c..26ee37721b8 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -1,13 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { captureOpenshellForStatus, isCommandTimeout } from "../../adapters/openshell/runtime"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; import { OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import * as agentRuntime from "../../agent/runtime"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { ProviderHealthStatus } from "../../inference/health"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; import { - buildSandboxInferenceRouteProbeArgs, + buildSandboxInferenceRouteProbeRequest, classifyInferenceRouteFailureLabel, isDcodeManagedExecMissingDetail, parseSandboxInferenceRouteProbeResult, @@ -41,32 +43,35 @@ export type SandboxInferenceRouteHealth = { export async function probeSandboxInferenceGatewayHealth( sandboxName: string, options: { - captureOpenshellImpl?: typeof captureOpenshellForStatus; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; gatewayName?: string; getSessionAgentImpl?: typeof agentRuntime.getSessionAgent; } = {}, ): Promise { const endpoint = "https://inference.local/v1/models"; - const capture = options.captureOpenshellImpl ?? captureOpenshellForStatus; + const commandExecutor = + options.commandExecutor ?? + createCliOpenShellSandboxCommandExecutor({ hostCwd: REPOSITORY_ROOT }); const getSessionAgent = options.getSessionAgentImpl ?? agentRuntime.getSessionAgent; - let result: Awaited>; + let result: { status: number; output: string; stderr: string }; try { - result = await capture( - buildSandboxInferenceRouteProbeArgs( + const completed = await commandExecutor.runBuffered( + buildSandboxInferenceRouteProbeRequest( sandboxName, getSessionAgent(sandboxName), options.gatewayName, + OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, ), - { - ignoreError: true, - includeStreams: true, - timeout: OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, - }, ); + if (completed.outcome.kind !== "completed") return null; + result = { + status: completed.outcome.exitCode, + output: completed.stdout, + stderr: completed.stderr, + }; } catch { return null; } - if (isCommandTimeout(result) || result.error) return null; const parsed = parseSandboxInferenceRouteProbeResult(result); if (!parsed.healthy && !parsed.broken) { return isDcodeManagedExecMissingDetail(parsed.detail) @@ -331,13 +336,13 @@ export function buildSandboxInferenceRouteHealth( return subprobes.length > 0 ? { ...routeHealth, subprobes } : routeHealth; } -export function runSandboxInferenceInvocationProbe( +export async function runSandboxInferenceInvocationProbe( input: SandboxInferenceInvocationInput, probe: ProbeSandboxInferenceInvocation = probeSandboxInferenceInvocation, onProbeError: (error: unknown) => void = () => {}, -): SandboxInferenceInvocationResult { +): Promise { try { - return probe(input, {}, READINESS_INFERENCE_INVOCATION_TIMEOUT_MS); + return await probe(input, {}, READINESS_INFERENCE_INVOCATION_TIMEOUT_MS); } catch (error) { onProbeError(error); return { diff --git a/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts b/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts index d1a940ba2ab..e94746589b3 100644 --- a/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { loadAgent } from "../../agent/defs"; import type { SandboxEntry } from "../../state/registry"; import { @@ -14,9 +15,8 @@ import { isSandboxGatewayRunningForStatus } from "./process-recovery"; describe("launch-readiness gateway health scope", () => { it("pins the semantic gateway probe to the owning OpenShell gateway (#8942)", async () => { - const capture = vi.fn(async (_args: string[]) => ({ - status: 0, - output: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + const runBuffered = vi.fn(async () => ({ + outcome: { kind: "completed", exitCode: 0 }, stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", stderr: "", })); @@ -25,26 +25,24 @@ describe("launch-readiness gateway health scope", () => { isSandboxGatewayRunningForStatus("alpha", "nemoclaw-8091", { getSessionAgent: () => null, getHealthProbeUrl: () => "http://127.0.0.1:18789/health", - capture: capture as never, + commandExecutor: { runBuffered }, }), ).resolves.toBe(true); - expect(capture).toHaveBeenCalledTimes(1); - expect(capture.mock.calls[0]?.[0]?.slice(0, 7)).toEqual([ - "sandbox", - "exec", - "--name", - "alpha", - "-g", - "nemoclaw-8091", - "--", - ]); + expect(runBuffered).toHaveBeenCalledTimes(1); + expect(runBuffered).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw-8091" }, + command: ["sh", "-c", expect.stringContaining("http://127.0.0.1:18789/health")], + }), + ); }); it("pins Hermes readiness checks to its recorded OpenShell gateway (#10302)", async () => { const gatewayHealth = vi.fn(async () => true); const forwardsHealthy = vi.fn(() => true); - const inferenceProbe = vi.fn(() => ({ + const inferenceProbe = vi.fn(async () => ({ healthy: true, broken: false, httpStatus: 200, @@ -91,21 +89,41 @@ function dcodeEntry(): SandboxEntry { } function dcodeHealthDeps( - invocation: ReturnType>, + invocation: Awaited< + ReturnType> + >, ): LaunchReadinessHealthDeps { return { - smoke: vi.fn(() => ({ ok: true }) as const), - inferenceProbe: vi.fn(() => ({ + smoke: vi.fn(async () => ({ ok: true }) as const), + inferenceProbe: vi.fn(async () => ({ healthy: true, broken: false, httpStatus: 404, detail: "OK 404", })), - inferenceInvocationProbe: vi.fn(() => invocation), + inferenceInvocationProbe: vi.fn(async () => invocation), }; } describe("Deep Agents Code OpenRouter launch readiness", () => { + it("accepts an injected terminal smoke without constructing a command executor", async () => { + const smoke = vi.fn(async () => ({ ok: true }) as const); + + await expect( + requireLaunchSemanticHealth( + SANDBOX, + GATEWAY, + "langchain-deepagents-code", + dcodeEntry(), + dcodeAgent, + false, + { smoke }, + ), + ).resolves.toBeUndefined(); + + expect(smoke).toHaveBeenCalledWith(SANDBOX, dcodeAgent); + }); + it("accepts readiness after an inference request succeeds (#9834)", async () => { const currentDeps = dcodeHealthDeps({ ok: true }); diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index f29b93e7cf4..73528472dee 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -132,7 +132,12 @@ function publicationDeps( }, gatewayHealth: async () => true, forwardsHealthy: () => true, - inferenceProbe: () => ({ healthy: true, broken: false, httpStatus: 200, detail: "OK 200" }), + inferenceProbe: async () => ({ + healthy: true, + broken: false, + httpStatus: 200, + detail: "OK 200", + }), classifyPortableLifecycleReceipt: () => ({ kind: "absent" }), readLease: () => ({ kind: "missing" }), fenceLease: fence, @@ -260,7 +265,7 @@ describe("launch readiness observation timing", () => { }, gatewayHealth: async () => true, forwardsHealthy: () => true, - inferenceProbe: () => ({ + inferenceProbe: async () => ({ healthy: inferenceHealthy, broken: false, httpStatus: inferenceHealthy ? 200 : 503, diff --git a/src/lib/actions/sandbox/launch-readiness.test.ts b/src/lib/actions/sandbox/launch-readiness.test.ts index f6e6c4de489..9e68e6615ef 100644 --- a/src/lib/actions/sandbox/launch-readiness.test.ts +++ b/src/lib/actions/sandbox/launch-readiness.test.ts @@ -236,6 +236,13 @@ describe("launch readiness validation", () => { stderr: "", } as ReturnType>; }, + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }, gatewayHealth: async (sandboxName, gatewayName) => { externalEvents.push("gateway-health"); gatewayHealthRequests.push([sandboxName, gatewayName]); @@ -246,8 +253,8 @@ describe("launch readiness validation", () => { forwardRequests.push([sandboxName, gatewayName]); return forwardsHealthy; }, - smoke: () => ({ ok: true }), - inferenceProbe: (sandboxName, _agent, gatewayName) => { + smoke: async () => ({ ok: true }), + inferenceProbe: async (sandboxName, _agent, gatewayName) => { externalEvents.push("inference-health"); inferenceHealthRequests.push([sandboxName, gatewayName]); return { healthy: true, broken: false, httpStatus: 200, detail: "OK 200" }; @@ -733,7 +740,7 @@ describe("launch readiness validation", () => { }); routeOutput = "Gateway Inference:\n\n Provider: nvidia\n Model: model-a\n"; - currentDeps.inferenceProbe = () => ({ + currentDeps.inferenceProbe = async () => ({ healthy: false, broken: true, httpStatus: 503, @@ -756,7 +763,7 @@ describe("launch readiness validation", () => { }; routeOutput = "Gateway Inference:\n\n Provider: nvidia\n Model: model-a\n"; const currentDeps = await createAcceptedLease(); - currentDeps.inferenceProbe = vi.fn((_sandboxName, _agent, _gatewayName) => ({ + currentDeps.inferenceProbe = vi.fn(async (_sandboxName, _agent, _gatewayName) => ({ healthy: httpStatus < 500, broken: httpStatus >= 500, httpStatus, @@ -795,7 +802,7 @@ describe("launch readiness validation", () => { }; routeOutput = "Gateway Inference:\n\n Provider: nvidia\n Model: model-a\n"; const currentDeps = await createAcceptedLease(); - currentDeps.inferenceProbe = vi.fn((_sandboxName, _agent, gatewayName) => ({ + currentDeps.inferenceProbe = vi.fn(async (_sandboxName, _agent, gatewayName) => ({ healthy: true, broken: false, httpStatus: 299, @@ -838,7 +845,7 @@ describe("launch readiness validation", () => { sandbox = entry("langchain-deepagents-code"); const currentDeps = deps(); const gatewayHealth = vi.fn(async () => true); - const smoke = vi.fn(() => ({ ok: true }) as const); + const smoke = vi.fn(async () => ({ ok: true }) as const); currentDeps.gatewayHealth = gatewayHealth; currentDeps.smoke = smoke; await createAcceptedLease(currentDeps); @@ -847,8 +854,6 @@ describe("launch readiness validation", () => { expect(smoke).toHaveBeenCalledWith( SANDBOX, expect.objectContaining({ name: "langchain-deepagents-code" }), - expect.any(Function), - GATEWAY_NAME, ); expect(gatewayHealth).not.toHaveBeenCalled(); expect(externalEvents).not.toContain("pairing-qualification"); @@ -859,7 +864,7 @@ describe("launch readiness validation", () => { sandbox = entry(" nemocua "); const currentDeps = deps(); const gatewayHealth = vi.fn(async () => true); - const smoke = vi.fn(() => ({ ok: true }) as const); + const smoke = vi.fn(async () => ({ ok: true }) as const); const cuaAgent = { ...loadAgent("hermes"), name: "nemocua", diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index 01b33b96354..b0030f4c25a 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { captureOpenshell } from "../../../adapters/openshell/runtime"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../../adapters/openshell/sandbox-command"; import { OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, OPENSHELL_PROBE_TIMEOUT_MS, @@ -16,7 +17,7 @@ import { } from "../../../onboard/sandbox-recreate-probe"; import type { SandboxEntry } from "../../../state/registry"; import { - buildSandboxInferenceRouteProbeArgs, + buildSandboxInferenceRouteProbeRequest, type InferenceRouteProbeAgent, parseSandboxInferenceRouteProbeResult, } from "../connect-inference-route-probe"; @@ -53,14 +54,15 @@ export interface LaunchReadinessHealthDeps { listAgents?: typeof listAgents; loadAgent?: typeof loadAgent; capture?: LaunchReadinessBoundCapture; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; gatewayHealth?: (sandboxName: string, gatewayName: string) => Promise; forwardsHealthy?: (sandboxName: string, gatewayName: string) => boolean | null; - smoke?: typeof runAgentSmokeCommands; + smoke?: (sandboxName: string, agent: AgentDefinition) => ReturnType; inferenceProbe?: ( sandboxName: string, agent: InferenceRouteProbeAgent, gatewayName: string, - ) => ReturnType; + ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; recordObservationTiming?: (stage: LaunchReadinessObservationStage, elapsedMs: number) => void; recordObservationFailure?: (stage: LaunchReadinessObservationStage) => void; @@ -74,6 +76,7 @@ export type LaunchReadinessBoundCapture = ( /** Route every OpenShell-backed readiness observation through one bound capture owner. */ export function createBoundLaunchReadinessDeps( capture: LaunchReadinessBoundCapture, + commandExecutor: OpenShellSandboxBufferedCommandExecutor, ): LaunchReadinessHealthDeps & { observeSandbox: SandboxRecreateObserver } { return { capture: (args, options) => @@ -85,22 +88,13 @@ export function createBoundLaunchReadinessDeps( observeSandbox: (target) => observeSandboxOnGateway(target, capture), gatewayHealth: (sandboxName, gatewayName) => isSandboxGatewayRunningForStatus(sandboxName, gatewayName, { - capture: async (args, options) => - capture(args, { - ...options, - timeout: options?.timeout ?? OPENSHELL_PROBE_TIMEOUT_MS, - }), + commandExecutor, }), forwardsHealthy: (sandboxName, gatewayName) => areSandboxLaunchForwardsHealthy(sandboxName, gatewayName, capture), inferenceProbe: (sandboxName, agent, gatewayName) => - parseSandboxInferenceRouteProbeResult( - capture(buildSandboxInferenceRouteProbeArgs(sandboxName, agent, gatewayName), { - ignoreError: true, - includeStreams: true, - timeout: OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, - }), - ), + probeInferenceRoute(sandboxName, agent, gatewayName, commandExecutor), + commandExecutor, }; } @@ -185,16 +179,28 @@ export function resolveTrustedLaunchAgent( return agent; } -function probeInferenceRoute( +async function probeInferenceRoute( sandboxName: string, agent: InferenceRouteProbeAgent, gatewayName: string, -): ReturnType { - return parseSandboxInferenceRouteProbeResult( - captureLaunchReadiness(buildSandboxInferenceRouteProbeArgs(sandboxName, agent, gatewayName), { - includeStreams: true, - }), + commandExecutor: OpenShellSandboxBufferedCommandExecutor, +): Promise> { + const completed = await commandExecutor.runBuffered( + buildSandboxInferenceRouteProbeRequest( + sandboxName, + agent, + gatewayName, + OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, + ), ); + return parseSandboxInferenceRouteProbeResult({ + status: completed.outcome.kind === "completed" ? completed.outcome.exitCode : null, + output: completed.stdout, + stderr: + completed.outcome.kind === "completed" + ? completed.stderr + : completed.stderr || completed.outcome.error.message, + }); } export async function requireLaunchSemanticHealth( @@ -207,14 +213,12 @@ export async function requireLaunchSemanticHealth( deps: LaunchReadinessHealthDeps, ): Promise { if (isTerminalAgent(agent)) { - const smoke = (deps.smoke ?? runAgentSmokeCommands)( - sandboxName, - agent, - (args, options) => - (deps.capture ?? ((captureArgs, captureOptions) => - captureLaunchReadiness(captureArgs, captureOptions)))(args, options), - gatewayName, - ); + const smoke = deps.smoke + ? await deps.smoke(sandboxName, agent) + : deps.commandExecutor + ? await runAgentSmokeCommands(sandboxName, agent, deps.commandExecutor, gatewayName) + : null; + if (!smoke) throw new LaunchReadinessEvidenceError(); if (!smoke.ok) { const trustedExit = smoke.output?.match(/(?:^|\n)NEMOCLAW_AGENT_SMOKE_EXIT:(\d+)(?:\n|$)/); if (!trustedExit) throw new LaunchReadinessEvidenceError(); @@ -268,7 +272,13 @@ export async function requireLaunchSemanticHealth( const inferenceStartedAt = performance.now(); let inference: ReturnType; try { - inference = (deps.inferenceProbe ?? probeInferenceRoute)(sandboxName, agent, gatewayName); + const inferenceProbe = + deps.inferenceProbe ?? + ((name: string, targetAgent: InferenceRouteProbeAgent, targetGateway: string) => { + if (!deps.commandExecutor) throw new LaunchReadinessEvidenceError(); + return probeInferenceRoute(name, targetAgent, targetGateway, deps.commandExecutor); + }); + inference = await inferenceProbe(sandboxName, agent, gatewayName); } catch (error) { recordLaunchReadinessObservationFailure(deps, "inference-route"); throw error; @@ -291,9 +301,9 @@ export async function requireLaunchSemanticHealth( recordLaunchReadinessObservationFailure(deps, "inference-route"); throw new LaunchReadinessEvidenceError(); } - let invocation: ReturnType; + let invocation: Awaited>; try { - invocation = (deps.inferenceInvocationProbe ?? runSandboxInferenceInvocationProbe)({ + invocation = await (deps.inferenceInvocationProbe ?? runSandboxInferenceInvocationProbe)({ sandboxName, gatewayName, agentName, diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index 3385082f004..8a37f0f4096 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({ requireActiveLifecycleAuthority: vi.fn(), requalifyPortableAuthority: vi.fn(), assertCommandCurrent: vi.fn(), + captureAcceptedReadinessObservation: vi.fn(), })); vi.mock("./connect", () => ({ @@ -63,7 +64,11 @@ vi.mock("./connect-hermes-light-skin", () => ({ prepareHermesLightTerminalSkin: mocks.prepareHermesLightTerminalSkin, })); vi.mock("./launch-readiness", () => ({ - createBoundLaunchReadinessDeps: () => ({ boundReadinessCapture: true }), + createBoundLaunchReadinessDeps: (capture: unknown, commandExecutor: unknown) => ({ + boundReadinessCapture: true, + capture, + commandExecutor, + }), inspectLaunchReadiness: mocks.inspectLaunchReadiness, publishLaunchReadiness: mocks.publishLaunchReadiness, withLaunchReadinessMutationGate: mocks.withLaunchReadinessMutationGate, @@ -79,7 +84,7 @@ vi.mock("./gateway-state", async () => { typeof import("../../onboard/experimental/hermes-portable-lifecycle") >("../../onboard/experimental/hermes-portable-lifecycle"); return { - captureHermesPortableAcceptedReadinessObservation: vi.fn(), + captureHermesPortableAcceptedReadinessObservation: mocks.captureAcceptedReadinessObservation, policyObservationRecoveryAction: ( error: { kind: string }, sandboxName: string, @@ -921,6 +926,105 @@ describe("launchSandbox", () => { expect(mocks.prepareInteractiveSession).toHaveBeenCalledBefore(mocks.publishLaunchReadiness); expect(mocks.publishLaunchReadiness).toHaveBeenCalledBefore(mocks.execSandbox); + expect(mocks.publishLaunchReadiness).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ + commandExecutor: expect.objectContaining({ runBuffered: expect.any(Function) }), + }), + ); + }); + + it("keeps fenced Hermes fallback publication on retained command authority", async () => { + const hermes = loadAgent("hermes"); + const entry = sandboxEntry("hermes"); + prepareSession("hermes", hermes, true); + mocks.inspectPortableReceiptDisposition.mockReturnValue(activeHermesDisposition()); + mocks.qualifyAcceptedReadinessAuthority.mockReturnValueOnce({ + kind: "current", + commandAuthority: { + env: { HERMES_AUTHORITY_ENV: "retained" }, + executablePath: "/usr/bin/openshell", + assertCurrent: mocks.assertCommandCurrent, + }, + }); + mocks.inspectLaunchReadiness.mockResolvedValue({ + kind: "fallback", + category: "expired", + fence: { epochId: "a".repeat(64) }, + gatewayName: "gateway-alpha", + gatewayPort: 8080, + fenceFailed: false, + recoveryBlocked: false, + }); + mocks.publishLaunchReadiness.mockImplementation(async (_publication, publicationDeps) => { + publicationDeps.capture?.(["sandbox", "get", "alpha"]); + return { kind: "published" }; + }); + + await launchSandbox("alpha", { + getSandbox: () => entry, + resolveSandboxGatewayName: () => "gateway-alpha", + withSandboxMutationLock: async (_name, operation) => await operation(), + }); + + expect(mocks.publishLaunchReadiness).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ + assertPublicationCurrent: expect.any(Function), + boundReadinessCapture: true, + commandExecutor: expect.objectContaining({ runBuffered: expect.any(Function) }), + }), + ); + expect(mocks.captureAcceptedReadinessObservation).toHaveBeenCalledWith( + expect.objectContaining({ + executablePath: "/usr/bin/openshell", + env: { HERMES_AUTHORITY_ENV: "retained" }, + }), + ["sandbox", "get", "alpha"], + {}, + ); + expect(mocks.assertCommandCurrent).toHaveBeenCalled(); + }); + + it("rejects Hermes authority drift after async fallback publication", async () => { + const hermes = loadAgent("hermes"); + const entry = sandboxEntry("hermes"); + const publicationStarted = deferred(); + const publicationRelease = deferred(); + prepareSession("hermes", hermes, true); + mocks.inspectPortableReceiptDisposition.mockReturnValue(activeHermesDisposition()); + mocks.inspectLaunchReadiness.mockResolvedValue({ + kind: "fallback", + category: "expired", + fence: { epochId: "a".repeat(64) }, + gatewayName: "gateway-alpha", + gatewayPort: 8080, + fenceFailed: false, + recoveryBlocked: false, + }); + mocks.publishLaunchReadiness.mockImplementation(async () => { + publicationStarted.resolve(); + await publicationRelease.promise; + return { kind: "published" }; + }); + + const launch = launchSandbox("alpha", { + getSandbox: () => entry, + resolveSandboxGatewayName: () => "gateway-alpha", + withSandboxMutationLock: async (_name, operation) => await operation(), + }); + const rejection = expect(launch).rejects.toThrow( + "Hermes portable command authority changed during fallback publication", + ); + await publicationStarted.promise; + mocks.assertCommandCurrent.mockImplementation(() => { + throw new Error("Hermes portable command authority changed during fallback publication"); + }); + publicationRelease.resolve(); + + await rejection; + expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.runSandboxExecChild).not.toHaveBeenCalled(); }); it("stops before readiness publication and agent execution when recovery rejects launch (#9364)", async () => { @@ -1050,36 +1154,36 @@ describe("launchSandbox", () => { }); it("does not launch after final live-policy validation fails", async () => { - const error = { - kind: "transport" as const, - reason: "unreachable" as const, - message: "OpenShell could not reach the selected gateway.", - }; - mocks.inspectLaunchReadiness.mockResolvedValue({ - kind: "fallback", - category: "unsafe", - fence: { epochId: "a".repeat(64) }, - gatewayName: "nemoclaw", - gatewayPort: 8080, - fenceFailed: false, - recoveryBlocked: false, - }); - mocks.publishLaunchReadiness.mockResolvedValue({ - kind: "policy-observation-failed", - error, - }); + const error = { + kind: "transport" as const, + reason: "unreachable" as const, + message: "OpenShell could not reach the selected gateway.", + }; + mocks.inspectLaunchReadiness.mockResolvedValue({ + kind: "fallback", + category: "unsafe", + fence: { epochId: "a".repeat(64) }, + gatewayName: "nemoclaw", + gatewayPort: 8080, + fenceFailed: false, + recoveryBlocked: false, + }); + mocks.publishLaunchReadiness.mockResolvedValue({ + kind: "policy-observation-failed", + error, + }); - await expect(launchSandbox("alpha")).rejects.toThrow( - [ - `Launch readiness final policy validation failed for sandbox 'alpha' on gateway 'nemoclaw': ${error.message}`, - `recovery:${error.kind}:alpha:nemoclaw:launch`, - ].join("\n"), - ); - - expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); - expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); - expect(mocks.runSandboxExecChild).not.toHaveBeenCalled(); + await expect(launchSandbox("alpha")).rejects.toThrow( + [ + `Launch readiness final policy validation failed for sandbox 'alpha' on gateway 'nemoclaw': ${error.message}`, + `recovery:${error.kind}:alpha:nemoclaw:launch`, + ].join("\n"), + ); + + expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); + expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled(); + expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.runSandboxExecChild).not.toHaveBeenCalled(); }); it("does not print connect's in-sandbox command hint (#6006)", async () => { diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index bc6f32874f3..283498705a2 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -6,6 +6,11 @@ import { isDeepStrictEqual } from "node:util"; import * as agentRuntime from "../../agent/runtime"; import type { AgentDefinition } from "../../agent/definition-types"; import { spawnExitCode } from "../../core/process-exit"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; +import { + createCliOpenShellSandboxCommandExecutor, + createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor, +} from "../../adapters/openshell/sandbox-command-cli"; import { resolveSandboxGatewayName } from "../../gateway-runtime-action"; import type { SandboxEntry } from "../../state/registry"; import { @@ -43,6 +48,9 @@ import { const LAUNCH_READINESS_FENCE_REPAIR = "Launch readiness evidence could not be safely invalidated. Repair the current user's secure OS runtime authority and NemoClaw state permissions, then retry."; +const sandboxCommandExecutor = createCliOpenShellSandboxCommandExecutor({ + hostCwd: REPOSITORY_ROOT, +}); /** * Connect to a sandbox and start its agent in one host-side step (#6006). @@ -102,22 +110,75 @@ type HermesPortableReadinessCommandAuthority = ReturnType< typeof qualifyHermesPortableOperatingCommandAuthority >; -type HermesPortableAcceptedLaunchAuthority = { +type HermesPortableLaunchAuthority = { readonly active: HermesPortableActiveLifecycleAuthority; readonly command: HermesPortableReadinessCommandAuthority; }; +function requireHermesPortableLaunchAuthorityCurrent( + sandboxName: string, + authority: HermesPortableLaunchAuthority, + readSandbox: typeof getKnownSandboxTarget, +): void { + authority.command.assertCurrent(); + const current = requireHermesPortableActiveLifecycleAuthority(sandboxName, authority.active, { + readRegistry: readSandbox, + }); + if (!isDeepStrictEqual(current.entry, authority.active.entry)) { + throw new Error("Hermes portable registry authority changed during launch readiness."); + } +} + +function createHermesPortableLaunchReadinessDeps( + sandboxName: string, + authority: HermesPortableLaunchAuthority, + readSandbox: typeof getKnownSandboxTarget, +): { + readonly deps: NonNullable[1]>; + readonly assertCurrent: () => void; +} { + const assertCurrent = () => + requireHermesPortableLaunchAuthorityCurrent(sandboxName, authority, readSandbox); + const capture = (args: string[], options = {}) => { + assertCurrent(); + try { + return captureHermesPortableAcceptedReadinessObservation(authority.command, args, options); + } finally { + assertCurrent(); + } + }; + const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( + { + resolveBinary: () => authority.command.executablePath, + hostCwd: REPOSITORY_ROOT, + hostEnv: authority.command.env, + }, + assertCurrent, + ); + return { + assertCurrent, + deps: { + ...createBoundLaunchReadinessDeps(capture, commandExecutor), + getSandbox: readSandbox, + assertPublicationCurrent: assertCurrent, + }, + }; +} + async function inspectLaunchReadinessForLaunch( sandboxName: string, deps: LaunchSandboxDeps, ): Promise<{ readonly decision: Awaited>; - readonly hermesAuthority: HermesPortableAcceptedLaunchAuthority | null; + readonly hermesAuthority: HermesPortableLaunchAuthority | null; }> { const inspect = deps.inspectLaunchReadiness ?? inspectLaunchReadiness; const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; if (inspectPortableAgentReceiptDisposition(sandboxName).kind !== "hermes") { - return { decision: await inspect(sandboxName), hermesAuthority: null }; + return { + decision: await inspect(sandboxName, { commandExecutor: sandboxCommandExecutor }), + hermesAuthority: null, + }; } if (readSandbox(sandboxName)?.agent !== "hermes") { throw new Error("Hermes portable registry authority changed before launch readiness."); @@ -148,9 +209,17 @@ async function inspectLaunchReadinessForLaunch( const command = qualified.commandAuthority; const capture = (args: string[], options = {}) => captureHermesPortableAcceptedReadinessObservation(command, args, options); + const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( + { + resolveBinary: () => command.executablePath, + hostCwd: REPOSITORY_ROOT, + hostEnv: command.env, + }, + command.assertCurrent, + ); command.assertCurrent(); const decision = await inspect(sandboxName, { - ...createBoundLaunchReadinessDeps(capture), + ...createBoundLaunchReadinessDeps(capture, commandExecutor), getSandbox: readSandbox, withSandboxLock: async (_name, operation) => operation(), }); @@ -165,7 +234,7 @@ async function inspectLaunchReadinessForLaunch( } return { decision, - hermesAuthority: decision.kind === "accepted" ? { active: current, command } : null, + hermesAuthority: { active: current, command }, }; }); } @@ -177,7 +246,7 @@ async function launchAgentWithPortableAuthority( hermesPortableSnapshot: boolean, command: readonly string[], deps: LaunchSandboxDeps, - acceptedHermesAuthority: HermesPortableAcceptedLaunchAuthority | null, + acceptedHermesAuthority: HermesPortableLaunchAuthority | null, beforeOrdinaryLaunch?: () => void, beforeAgentExec?: () => void, ): Promise { @@ -302,7 +371,7 @@ export async function launchSandbox( const enterMutationGate = deps.withLaunchReadinessMutationGate ?? withLaunchReadinessMutationGate; let inspection = await inspectLaunchReadinessForLaunch(sandboxName, deps); let decision = inspection.decision; - let acceptedHermesAuthority = inspection.hermesAuthority; + let acceptedHermesAuthority = decision.kind === "accepted" ? inspection.hermesAuthority : null; let session: Awaited>; let acceptedReadinessSetup: (() => void) | undefined; let readinessAction: LaunchReadinessAction = "prepared"; @@ -337,17 +406,32 @@ export async function launchSandbox( if (decision.recoveryBlocked) throw new Error(LAUNCH_READINESS_FENCE_REPAIR); const fallbackDecision = decision; const publicationRequest = publicationFromDecision(sandboxName, fallbackDecision); + const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; + const hermesPublication = + fallbackDecision.fence && inspection.hermesAuthority + ? createHermesPortableLaunchReadinessDeps( + sandboxName, + inspection.hermesAuthority, + readSandbox, + ) + : null; const gated = await enterMutationGate(publicationRequest, async () => { + hermesPublication?.assertCurrent(); const prepared = await prepareInteractiveSession(sandboxName); + hermesPublication?.assertCurrent(); const publication = fallbackDecision.fence - ? await (deps.publishLaunchReadiness ?? publishLaunchReadiness)(publicationRequest) + ? await (deps.publishLaunchReadiness ?? publishLaunchReadiness)( + publicationRequest, + hermesPublication?.deps ?? { commandExecutor: sandboxCommandExecutor }, + ) : null; + hermesPublication?.assertCurrent(); return { prepared, publication }; }); if (gated.kind === "changed") { inspection = await inspectLaunchReadinessForLaunch(sandboxName, deps); decision = inspection.decision; - acceptedHermesAuthority = inspection.hermesAuthority; + acceptedHermesAuthority = decision.kind === "accepted" ? inspection.hermesAuthority : null; continue; } if (gated.kind === "unsafe") throw new Error(LAUNCH_READINESS_FENCE_REPAIR); diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts index 470097cf3ed..81ca6d9be65 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts @@ -16,6 +16,11 @@ const mocks = vi.hoisted(() => ({ waitForMcpBridgeCondition: vi.fn((condition: () => boolean) => Array.from({ length: 12 }).some(() => condition()), ), + waitForMcpBridgeConditionAsync: vi.fn(async (condition: () => Promise) => { + const attempt = async (remaining: number): Promise => + remaining === 0 ? false : (await condition()) || attempt(remaining - 1); + return attempt(12); + }), })); vi.mock("./process-recovery", () => ({ @@ -41,6 +46,7 @@ vi.mock("./mcp-bridge-provider-readiness", async (importOriginal) => ({ vi.mock("./mcp-bridge/timing", () => ({ waitForMcpBridgeCondition: mocks.waitForMcpBridgeCondition, + waitForMcpBridgeConditionAsync: mocks.waitForMcpBridgeConditionAsync, })); import { @@ -325,37 +331,40 @@ describe("Hermes MCP adapter credential revision", () => { }); }); -describe.each(reconciliationCases)("$name MCP credential revision reconciliation", (adapterCase) => { - beforeEach(() => { - mocks.executeSandboxCommand.mockReset(); - mocks.runOpenshellProviderCommand.mockReset(); - mocks.getSandbox.mockReset(); - mocks.getSandbox.mockReturnValue(sandbox); - mocks.observeMcpCredentialRevision.mockReset(); - mocks.observeMcpCredentialRevision.mockReturnValue("v12"); - }); +describe.each(reconciliationCases)( + "$name MCP credential revision reconciliation", + (adapterCase) => { + beforeEach(() => { + mocks.executeSandboxCommand.mockReset(); + mocks.runOpenshellProviderCommand.mockReset(); + mocks.getSandbox.mockReset(); + mocks.getSandbox.mockReturnValue(sandbox); + mocks.observeMcpCredentialRevision.mockReset(); + mocks.observeMcpCredentialRevision.mockResolvedValue("v12"); + }); - it("reconciles registration to a later stable revision", () => { - mocks.observeMcpCredentialRevision.mockReturnValueOnce("v11"); - adapterCase.arrange(); + it("reconciles registration to a later stable revision", async () => { + mocks.observeMcpCredentialRevision.mockResolvedValueOnce("v11"); + adapterCase.arrange(); - expect( - registerAgentAdapterAtCurrentCredentialRevision( - "alpha", - adapterCase.adapter, - adapterCase.entry, - runtimeSelection, - { GITHUB_TOKEN: "host-only-secret" }, - "v11", - ), - ).toBe("v12"); + await expect( + registerAgentAdapterAtCurrentCredentialRevision( + "alpha", + adapterCase.adapter, + adapterCase.entry, + runtimeSelection, + { GITHUB_TOKEN: "host-only-secret" }, + "v11", + ), + ).resolves.toBe("v12"); - const mutationCalls = adapterCase.mutationCalls(); - expect(mutationCalls).toContain("openshell:resolve:env:v11_GITHUB_TOKEN"); - expect(mutationCalls).toContain("openshell:resolve:env:v12_GITHUB_TOKEN"); - expect(mutationCalls).not.toContain("host-only-secret"); - }); -}); + const mutationCalls = adapterCase.mutationCalls(); + expect(mutationCalls).toContain("openshell:resolve:env:v11_GITHUB_TOKEN"); + expect(mutationCalls).toContain("openshell:resolve:env:v12_GITHUB_TOKEN"); + expect(mutationCalls).not.toContain("host-only-secret"); + }); + }, +); describe("MCP adapter credential revision reconciliation failures", () => { beforeEach(() => { @@ -365,7 +374,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { mocks.observeMcpCredentialRevision.mockReset(); }); - it("keeps one operation target after the registry target changes (#10514)", () => { + it("keeps one operation target after the registry target changes (#10514)", async () => { const operationSelection = { gatewayName: "nemoclaw-8091", localTlsDir: "/authority/gateway-8091/tls", @@ -383,7 +392,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { ? commandSuccess : registered, ); - mocks.observeMcpCredentialRevision.mockImplementation(() => { + mocks.observeMcpCredentialRevision.mockImplementation(async () => { mocks.getSandbox.mockReturnValue({ agent: "openclaw", gatewayName: "foreign-gateway", @@ -392,7 +401,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { return "v11"; }); - expect( + await expect( registerAgentAdapterAtCurrentCredentialRevision( "alpha", "mcporter", @@ -401,11 +410,11 @@ describe("MCP adapter credential revision reconciliation failures", () => { {}, "v11", ), - ).toBe("v11"); + ).resolves.toBe("v11"); expect(mocks.getSandbox()).toMatchObject({ gatewayName: "foreign-gateway" }); - expect( - mocks.executeSandboxCommand.mock.calls.map((call) => call[2]?.runtimeSelection), - ).toEqual(Array(mocks.executeSandboxCommand.mock.calls.length).fill(operationSelection)); + expect(mocks.executeSandboxCommand.mock.calls.map((call) => call[2]?.runtimeSelection)).toEqual( + Array(mocks.executeSandboxCommand.mock.calls.length).fill(operationSelection), + ); expect(mocks.observeMcpCredentialRevision.mock.calls.map((call) => call[2])).toEqual( Array(mocks.observeMcpCredentialRevision.mock.calls.length).fill(operationSelection), ); @@ -413,8 +422,8 @@ describe("MCP adapter credential revision reconciliation failures", () => { it.each(["absent", "canonical"] as const)( "fails closed when reconciliation observes %s credential authority", - (observation) => { - mocks.observeMcpCredentialRevision.mockReturnValue(observation); + async (observation) => { + mocks.observeMcpCredentialRevision.mockResolvedValue(observation); mocks.executeSandboxCommand.mockImplementation((_sandbox, command: string) => command === "command -v mcporter" ? { status: 0, stdout: "/usr/bin/mcporter\n", stderr: "" } @@ -423,7 +432,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { : registered, ); - expect(() => + await expect( registerAgentAdapterAtCurrentCredentialRevision( "alpha", "mcporter", @@ -432,13 +441,13 @@ describe("MCP adapter credential revision reconciliation failures", () => { {}, "v11", ), - ).toThrow("did not expose a revision-scoped credential"); + ).rejects.toThrow("did not expose a revision-scoped credential"); }, ); - it("fails closed when the credential revision never stabilizes", () => { + it("fails closed when the credential revision never stabilizes", async () => { let revision = 10; - mocks.observeMcpCredentialRevision.mockImplementation(() => `v${(revision += 1)}`); + mocks.observeMcpCredentialRevision.mockImplementation(async () => `v${(revision += 1)}`); mocks.executeSandboxCommand.mockImplementation((_sandbox, command: string) => command === "command -v mcporter" ? { status: 0, stdout: "/usr/bin/mcporter\n", stderr: "" } @@ -447,7 +456,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { : registered, ); - expect(() => + await expect( registerAgentAdapterAtCurrentCredentialRevision( "alpha", "mcporter", @@ -456,15 +465,15 @@ describe("MCP adapter credential revision reconciliation failures", () => { {}, "v10", ), - ).toThrow("credential revision did not stabilize"); + ).rejects.toThrow("credential revision did not stabilize"); }); - it("fails closed when both bounded registrations advance the revision", () => { + it("fails closed when both bounded registrations advance the revision", async () => { mocks.observeMcpCredentialRevision - .mockReturnValueOnce("v11") - .mockReturnValueOnce("v11") - .mockReturnValueOnce("v11") - .mockReturnValue("v12"); + .mockResolvedValueOnce("v11") + .mockResolvedValueOnce("v11") + .mockResolvedValueOnce("v11") + .mockResolvedValue("v12"); mocks.executeSandboxCommand.mockImplementation((_sandbox, command: string) => command === "command -v mcporter" ? { status: 0, stdout: "/usr/bin/mcporter\n", stderr: "" } @@ -473,7 +482,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { : registered, ); - expect(() => + await expect( registerAgentAdapterAtCurrentCredentialRevision( "alpha", "mcporter", @@ -482,7 +491,7 @@ describe("MCP adapter credential revision reconciliation failures", () => { {}, "v10", ), - ).toThrow("credential revision did not stabilize"); + ).rejects.toThrow("credential revision did not stabilize"); expect( mocks.executeSandboxCommand.mock.calls.filter(([, command]) => String(command).includes("config' 'add"), diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts index 0377f082f1c..b83400ced24 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts @@ -149,14 +149,14 @@ describe("MCP adapter teardown rollback", () => { type: "nemoclaw-mcp-v1", }); mocks.inspectMcpProvider.mockReset().mockReturnValue({ exists: false }); - mocks.observeMcpCredentialRevision.mockReset().mockReturnValue("v12"); + mocks.observeMcpCredentialRevision.mockReset().mockResolvedValue("v12"); mocks.preflightMcpEntryTargets .mockReset() .mockResolvedValue(new Map([[entry.server, { addresses: ["8.8.8.8"] }]])); mocks.removeGeneratedPolicy.mockReset().mockImplementation(() => { throw new Error("forced lifecycle failure after adapter scrub"); }); - mocks.registerAgentAdapterAtCurrentCredentialRevision.mockReset(); + mocks.registerAgentAdapterAtCurrentCredentialRevision.mockReset().mockResolvedValue("v12"); mocks.restoreExistingMcpBridgeRuntime.mockReset(); mocks.setBridgeState.mockReset(); mocks.unregisterAgentAdapter.mockReset().mockReturnValue("removed"); @@ -170,9 +170,9 @@ describe("MCP adapter teardown rollback", () => { async (_lifecycle, prepare) => { mocks.observeMcpCredentialRevision .mockReset() - .mockReturnValueOnce("v12") - .mockReturnValueOnce("v13") - .mockReturnValue("v13"); + .mockResolvedValueOnce("v12") + .mockResolvedValueOnce("v13") + .mockResolvedValue("v13"); await expect(prepare("alpha")).rejects.toThrow( "forced lifecycle failure after adapter scrub", @@ -194,8 +194,8 @@ describe("MCP adapter teardown rollback", () => { }, ); - it("does not derive a Hermes credential revision from an exact provider resource version", () => { - mocks.observeMcpCredentialRevision.mockReturnValue("absent"); + it("does not derive a Hermes credential revision from an exact provider resource version", async () => { + mocks.observeMcpCredentialRevision.mockResolvedValue("absent"); mocks.inspectMcpProvider.mockReturnValue({ credentialKeys: ["GITHUB_TOKEN"], exists: true, @@ -204,7 +204,9 @@ describe("MCP adapter teardown rollback", () => { type: "nemoclaw-mcp-v1", }); - expect(() => scrubManagedMcpAdapterOrThrow("alpha", sandbox, entry, runtimeSelection)).toThrow( + await expect( + scrubManagedMcpAdapterOrThrow("alpha", sandbox, entry, runtimeSelection), + ).rejects.toThrow( "Could not prove a revision-scoped credential before removing the managed adapter entry for MCP server 'github'.", ); expect(mocks.inspectMcpProvider).not.toHaveBeenCalled(); @@ -317,16 +319,19 @@ describe("MCP adapter teardown rollback", () => { { ...entry, allowedIps: undefined }, /legacy public registration without recorded address pins.*mcp restart github/, ], - ] as const)("rejects exec-unavailable rebuild for %s (#11115)", async (_case, candidate, error) => { - mocks.bridgeState.mockReturnValue({ github: candidate }); - mocks.getSandboxAgent.mockReturnValue({ name: "hermes" }); - mocks.getBridgeAdapter.mockReturnValue("hermes-config"); + ] as const)( + "rejects exec-unavailable rebuild for %s (#11115)", + async (_case, candidate, error) => { + mocks.bridgeState.mockReturnValue({ github: candidate }); + mocks.getSandboxAgent.mockReturnValue({ name: "hermes" }); + mocks.getBridgeAdapter.mockReturnValue("hermes-config"); - await expect(prepareMcpBridgesForExecUnavailableRebuild("alpha")).rejects.toThrow(error); + await expect(prepareMcpBridgesForExecUnavailableRebuild("alpha")).rejects.toThrow(error); - expect(mocks.ensureSandboxGatewaySelected).not.toHaveBeenCalled(); - expect(mocks.preflightMcpEntryTargets).not.toHaveBeenCalled(); - }); + expect(mocks.ensureSandboxGatewaySelected).not.toHaveBeenCalled(); + expect(mocks.preflightMcpEntryTargets).not.toHaveBeenCalled(); + }, + ); const expectLegacyPublicPinsPersisted = async ( prepare: (sandboxName: string) => Promise<{ entries: McpBridgeEntry[] }>, diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts index 4a5cd0d3a63..3a0a270a1ee 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts @@ -30,13 +30,13 @@ export function resolveManagedMcpAdapter( } /** Scrub one registry-owned adapter entry, failing closed when ownership is unproved. */ -export function scrubManagedMcpAdapterOrThrow( +export async function scrubManagedMcpAdapterOrThrow( sandboxName: string, sandbox: SandboxEntry, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, -): McpScrubbedAdapterEntry { - const observation = observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); +): Promise { + const observation = await observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); if (observation === "absent" || observation === "canonical") { throw new McpBridgeError( `Could not prove a revision-scoped credential before removing the managed adapter entry for MCP server '${entry.server}'.`, @@ -60,17 +60,17 @@ export function scrubManagedMcpAdapterOrThrow( } /** Restore scrubbed adapter entries without hiding failures from provider rollback. */ -export function rollbackScrubbedMcpAdapters( +export async function rollbackScrubbedMcpAdapters( sandboxName: string, sandbox: SandboxEntry, entries: readonly McpScrubbedAdapterEntry[], runtimeSelection: McpProviderInspectionRuntimeSelection, -): string[] { +): Promise { const failures: string[] = []; for (const entry of entries) { let credentialRevision: McpAttachedCredentialRevision | undefined; try { - const current = observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); + const current = await observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); if (current !== "absent" && current !== "canonical") credentialRevision = current; } catch (error) { failures.push(error instanceof Error ? error.message : String(error)); @@ -83,7 +83,7 @@ export function rollbackScrubbedMcpAdapters( continue; } try { - registerAgentAdapterAtCurrentCredentialRevision( + await registerAgentAdapterAtCurrentCredentialRevision( sandboxName, resolveManagedMcpAdapter(sandbox, entry), entry, diff --git a/src/lib/actions/sandbox/mcp-bridge-adapters.ts b/src/lib/actions/sandbox/mcp-bridge-adapters.ts index 1cbc1f7b69c..1b0b4825fae 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapters.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapters.ts @@ -31,10 +31,8 @@ import { type McpAttachedCredentialRevision, observeMcpCredentialRevision, } from "./mcp-bridge-provider-readiness"; -import { - type McpProviderInspectionRuntimeSelection, -} from "./mcp-bridge-provider-inspection"; -import { waitForMcpBridgeCondition } from "./mcp-bridge/timing"; +import { type McpProviderInspectionRuntimeSelection } from "./mcp-bridge-provider-inspection"; +import { waitForMcpBridgeConditionAsync } from "./mcp-bridge/timing"; const STABLE_CREDENTIAL_REVISION_OBSERVATIONS = 3; const MAX_CREDENTIAL_REVISION_REGISTRATIONS = 2; @@ -165,7 +163,7 @@ export function registerAgentAdapter( } /** Register one adapter and converge it on the credential revision exposed by fresh execs. */ -export function registerAgentAdapterAtCurrentCredentialRevision( +export async function registerAgentAdapterAtCurrentCredentialRevision( sandboxName: string, adapter: AgentMcpAdapter, entry: McpBridgeEntry, @@ -173,7 +171,7 @@ export function registerAgentAdapterAtCurrentCredentialRevision( envValues: Record, initialCredentialRevision: McpAttachedCredentialRevision, options: { replaceExisting?: boolean; teardownRollback?: boolean } = {}, -): McpAttachedCredentialRevision { +): Promise { const timeoutSeconds = Number.parseInt( process.env.NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS ?? "30", 10, @@ -193,9 +191,13 @@ export function registerAgentAdapterAtCurrentCredentialRevision( let candidateRevision: McpAttachedCredentialRevision | undefined; let stableObservations = 0; let observedRevision: McpAttachedCredentialRevision | undefined; - const stable = waitForMcpBridgeCondition( - () => { - const observation = observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); + const stable = await waitForMcpBridgeConditionAsync( + async () => { + const observation = await observeMcpCredentialRevision( + sandboxName, + entry, + runtimeSelection, + ); if (observation === "absent" || observation === "canonical") { throw mcpAdapterCredentialRevisionUnavailableError(entry.server); } diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 44d231aca95..339b8c4e7f0 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -469,7 +469,7 @@ async function addMcpBridgeUnlocked( } assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, providerRuntimeSelection); if (detachedMissingProviderReference) { - waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); + await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); } if (resumingPreflightedAdd && !Object.hasOwn(adapterEnvValues, entry.env[0])) { try { @@ -539,12 +539,12 @@ async function addMcpBridgeUnlocked( allowExisting: resumingPreflightedAdd, expectedProviderId: entry.providerId, runtimeSelection: providerRuntimeSelection, - prepareMutation: (action) => { + prepareMutation: async (action) => { // A fresh create has no prior revision to compare. Observe only the // bounded placeholder classification for an actual update, after the // running supervisor has accepted the authenticated MCP policy. if (action === "update") { - previousCredentialRevision = observeMcpCredentialRevision( + previousCredentialRevision = await observeMcpCredentialRevision( sandboxName, entry, providerRuntimeSelection, @@ -685,7 +685,7 @@ async function addMcpBridgeUnlocked( let reservationCleanupProved = !providerAttachAttempted; if (providerAttachAttempted && detachOutcome !== "unknown") { try { - waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); + await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); reservationCleanupProved = true; } catch { reservationCleanupProved = false; diff --git a/src/lib/actions/sandbox/mcp-bridge-destroy.ts b/src/lib/actions/sandbox/mcp-bridge-destroy.ts index f6aea15cc5c..3f7e07c665c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-destroy.ts +++ b/src/lib/actions/sandbox/mcp-bridge-destroy.ts @@ -138,7 +138,7 @@ export async function prepareMcpBridgesForDestroy( try { for (const entry of entries) { scrubbedAdapters.push( - scrubManagedMcpAdapterOrThrow(sandboxName, sandbox, entry, providerRuntimeSelection), + await scrubManagedMcpAdapterOrThrow(sandboxName, sandbox, entry, providerRuntimeSelection), ); } for (const entry of entries) { @@ -161,7 +161,7 @@ export async function prepareMcpBridgesForDestroy( `Could not prove provider detach for MCP server '${entry.server}'.`, ); } - waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); + await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); // Both an acknowledged detach and a freshly-proven absent binding are // rollback responsibilities until destroyPreparedAt is durable. This // closes retry-after-process-death gaps where an earlier attempt already @@ -202,12 +202,12 @@ export async function prepareMcpBridgesForDestroy( } if (!runtimeRestored) { rollbackFailures.push( - ...rollbackScrubbedMcpAdapters( + ...(await rollbackScrubbedMcpAdapters( sandboxName, sandbox, scrubbedAdapters, providerRuntimeSelection, - ), + )), ); } const current = registry.getSandbox(sandboxName); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts b/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts index 750d22965c4..e45ae4df637 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts @@ -114,7 +114,7 @@ export async function upsertMcpProvider( allowExisting: boolean; expectedProviderId?: string; requireExisting?: boolean; - prepareMutation?: (action: "create" | "update") => void; + prepareMutation?: (action: "create" | "update") => void | Promise; runtimeSelection: McpProviderInspectionRuntimeSelection; providerAdapter?: OpenShellProviderAdapter; }, @@ -184,7 +184,7 @@ export async function upsertMcpProvider( // Let callers establish policy and revision proofs only after the actual // mutation kind is known. The immediate reinspection below closes races // that occur while those fail-closed prerequisites are being prepared. - options.prepareMutation?.(action); + await options.prepareMutation?.(action); // invalidState: another OpenShell client replaces a mutable provider name // between inspection and mutation. sourceBoundary: OpenShell owns provider // compare-and-swap; v0.0.99 uses the version read inside the server but its @@ -396,8 +396,7 @@ export async function deleteProvider( return; if (options.bestEffort) return; throw new McpBridgeError( - result.error.message || - `Failed to delete MCP provider '${entry.providerName}'.`, + result.error.message || `Failed to delete MCP provider '${entry.providerName}'.`, ); } const after = await inspectMcpProvider( diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts index c676987e20a..af3ea306719 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts @@ -5,7 +5,7 @@ import { shellQuote } from "../../runner"; import type { McpBridgeEntry } from "../../state/registry"; import { McpBridgeError } from "./mcp-bridge-contracts"; import type { McpProviderInspectionRuntimeSelection } from "./mcp-bridge-provider-inspection"; -import { waitForMcpBridgeCondition, waitForMcpBridgeConditionAsync } from "./mcp-bridge/timing"; +import { waitForMcpBridgeConditionAsync } from "./mcp-bridge/timing"; import { assertAuthenticatedBridgeEntry, assertPersistedAuthenticatedBridgeEntry, @@ -53,7 +53,7 @@ function executeMcpCredentialProofCommand( // script classifies placeholder shape/revision only and never prints a raw // credential value or writes sandbox state. return executeSandboxExecCommand(sandboxName, command, undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); } @@ -115,12 +115,12 @@ function parseMcpCredentialRevisionObservation( : null; } -function tryObserveMcpCredentialRevision( +async function tryObserveMcpCredentialRevision( sandboxName: string, envName: string, runtimeSelection: McpProviderInspectionRuntimeSelection, -): McpCredentialRevisionAttempt { - const result = executeMcpCredentialProofCommand( +): Promise { + const result = await executeMcpCredentialProofCommand( sandboxName, buildMcpCredentialRevisionObservationCommand(envName), runtimeSelection, @@ -144,13 +144,17 @@ function describeMcpCredentialRevisionAttempt(attempt: McpCredentialRevisionAtte } } -export function observeMcpCredentialRevision( +export async function observeMcpCredentialRevision( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, -): McpCredentialRevisionObservation { +): Promise { assertAuthenticatedBridgeEntry(entry); - const attempt = tryObserveMcpCredentialRevision(sandboxName, entry.env[0], runtimeSelection); + const attempt = await tryObserveMcpCredentialRevision( + sandboxName, + entry.env[0], + runtimeSelection, + ); if (attempt.kind !== "observation") { throw new McpBridgeError( `Could not observe the current OpenShell credential revision for sandbox '${sandboxName}'.`, @@ -189,7 +193,7 @@ export async function waitForAttachedMcpCredential( // Each exec is a fresh OpenShell process. Only the bounded placeholder // classification crosses back to the host, where the comparison cannot // be influenced by a same-UID sandbox process rewriting a snapshot file. - let attempt = tryObserveMcpCredentialRevision(sandboxName, envName, runtimeSelection); + let attempt = await tryObserveMcpCredentialRevision(sandboxName, envName, runtimeSelection); lastAttempt = attempt; if ( attempt.kind === "observation" && @@ -199,7 +203,7 @@ export async function waitForAttachedMcpCredential( ) { refreshedAfterObservedAbsence = true; await options.refreshAfterObservedAbsence(); - attempt = tryObserveMcpCredentialRevision(sandboxName, envName, runtimeSelection); + attempt = await tryObserveMcpCredentialRevision(sandboxName, envName, runtimeSelection); lastAttempt = attempt; } const observation = attempt.kind === "observation" ? attempt.observation : null; @@ -248,11 +252,11 @@ export function buildMcpCredentialDetachedCommand(envName: string): string { return `[ -z "\${${envName}+x}" ]`; } -export function waitForDetachedMcpCredential( +export async function waitForDetachedMcpCredential( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { +): Promise { assertPersistedAuthenticatedBridgeEntry(entry); const envName = entry.env[0]; try { @@ -267,12 +271,14 @@ export function waitForDetachedMcpCredential( process.env.NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS ?? "30", 10, ); - const revoked = waitForMcpBridgeCondition( - () => - executeMcpCredentialProofCommand( - sandboxName, - buildMcpCredentialDetachedCommand(envName), - runtimeSelection, + const revoked = await waitForMcpBridgeConditionAsync( + async () => + ( + await executeMcpCredentialProofCommand( + sandboxName, + buildMcpCredentialDetachedCommand(envName), + runtimeSelection, + ) )?.status === 0, Number.isFinite(timeoutSeconds) && timeoutSeconds > 0 ? timeoutSeconds : 30, 1_000, diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts index 2c1bafa6a0b..28344b2e703 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts @@ -627,14 +627,14 @@ describe("OpenShell MCP provider state", () => { expect(command).not.toMatch(/\/tmp|snapshot|cat\s|exec\s+[0-9]*>/); }); - it("uses an OpenShell-only exec for provider credential proofs", () => { - const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + it("uses an OpenShell-only exec for provider credential proofs", async () => { + const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "v11", stderr: "", }); - expect( + await expect( observeMcpCredentialRevision( "alpha", { @@ -650,19 +650,19 @@ describe("OpenShell MCP provider state", () => { }, runtimeSelection, ), - ).toBe("v11"); + ).resolves.toBe("v11"); const proofCommand = exec.mock.calls[0]?.[1] ?? ""; expect(proofCommand).toContain("\n"); expect(proofCommand).toContain("GITHUB_TOKEN"); expect(proofCommand).not.toMatch(/\/tmp|snapshot/); expect(proofCommand).not.toContain("base64 -d"); expect(exec).toHaveBeenCalledWith("alpha", proofCommand, undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); - exec.mockReturnValue({ status: 0, stdout: "raw-secret", stderr: "" }); - expect(() => + exec.mockResolvedValue({ status: 0, stdout: "raw-secret", stderr: "" }); + await expect( observeMcpCredentialRevision( "alpha", { @@ -678,14 +678,14 @@ describe("OpenShell MCP provider state", () => { }, runtimeSelection, ), - ).toThrow(/Could not observe the current OpenShell credential revision/); + ).rejects.toThrow(/Could not observe the current OpenShell credential revision/); }); it("waits for native multiline OpenShell exec to expose an attached revision", async () => { const exec = vi .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "canonical", stderr: "" }) - .mockReturnValue({ status: 0, stdout: "v11", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "canonical", stderr: "" }) + .mockResolvedValue({ status: 0, stdout: "v11", stderr: "" }); const refreshAfterObservedAbsence = vi.fn(); const revision = await waitForAttachedMcpCredential( @@ -729,8 +729,8 @@ describe("OpenShell MCP provider state", () => { }; const exec = vi .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" }) - .mockReturnValue({ status: 0, stdout: "v12", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "v11", stderr: "" }) + .mockResolvedValue({ status: 0, stdout: "v12", stderr: "" }); await expect(waitForAttachedMcpCredential("alpha", entry, runtimeSelection)).resolves.toBe( "v12", @@ -752,10 +752,10 @@ describe("OpenShell MCP provider state", () => { }; const exec = vi .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "v15566468742889590075", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "v15566468742889590075", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "v7480654703696766813", stderr: "" }) - .mockReturnValue({ status: 0, stdout: "v7480654703696766813", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "v15566468742889590075", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "v15566468742889590075", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "v7480654703696766813", stderr: "" }) + .mockResolvedValue({ status: 0, stdout: "v7480654703696766813", stderr: "" }); await expect( waitForAttachedMcpCredential("alpha", entry, runtimeSelection, { @@ -767,7 +767,7 @@ describe("OpenShell MCP provider state", () => { it("does not accept an identityless placeholder as attachment readiness", async () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "canonical", stderr: "", @@ -795,7 +795,7 @@ describe("OpenShell MCP provider state", () => { it("reports an absent attached credential without attempting policy recovery", async () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); - const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "absent", stderr: "", @@ -836,8 +836,8 @@ describe("OpenShell MCP provider state", () => { }; const exec = vi .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "absent", stderr: "" }) - .mockReturnValue({ status: 0, stdout: "v12", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "absent", stderr: "" }) + .mockResolvedValue({ status: 0, stdout: "v12", stderr: "" }); const refreshAfterObservedAbsence = vi.fn(); await expect( @@ -851,7 +851,7 @@ describe("OpenShell MCP provider state", () => { it("does not repeat the provider refresh when the credential remains absent", async () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); - const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "absent", stderr: "", @@ -887,7 +887,7 @@ describe("OpenShell MCP provider state", () => { ["rejected", { status: 1, stdout: "", stderr: "" }, "proof-command-exit-1"], ])("does not refresh when a credential observation is %s", async (_case, result, diagnostic) => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue(result); + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue(result); vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(1_000); const refreshAfterObservedAbsence = vi.fn(); @@ -919,7 +919,7 @@ describe("OpenShell MCP provider state", () => { }); it("propagates a provider refresh failure after observed absence", async () => { - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "absent", stderr: "", @@ -953,8 +953,8 @@ describe("OpenShell MCP provider state", () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); const exec = vi .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "absent", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "absent", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "v11", stderr: "" }); vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(1_000); const refreshAfterObservedAbsence = vi.fn(); @@ -982,12 +982,12 @@ describe("OpenShell MCP provider state", () => { expect(exec).toHaveBeenCalledTimes(2); }); - it("fails detach verification when the strict OpenShell exec is unavailable", () => { + it("fails detach verification when the strict OpenShell exec is unavailable", async () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); - const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue(null); + const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue(null); vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(1_000); - expect(() => + await expect( waitForDetachedMcpCredential( "alpha", { @@ -1003,13 +1003,13 @@ describe("OpenShell MCP provider state", () => { }, runtimeSelection, ), - ).toThrow(/did not confirm credential 'GITHUB_TOKEN' was revoked/); + ).rejects.toThrow(/did not confirm credential 'GITHUB_TOKEN' was revoked/); const proofCommand = exec.mock.calls[0]?.[1] ?? ""; expect(proofCommand).toContain("GITHUB_TOKEN+x"); expect(proofCommand).not.toContain("base64 -d"); expect(exec).toHaveBeenCalledWith("alpha", proofCommand, undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); }); @@ -1026,7 +1026,7 @@ describe("OpenShell MCP provider state", () => { policyName: "mcp-bridge-github", addedAt: "2026-06-01T00:00:00.000Z", }; - const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "v12", stderr: "", @@ -1041,7 +1041,7 @@ describe("OpenShell MCP provider state", () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); exec.mockClear(); - exec.mockReturnValue({ status: 0, stdout: "v11", stderr: "" }); + exec.mockResolvedValue({ status: 0, stdout: "v11", stderr: "" }); vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(1_000); await expect( waitForAttachedMcpCredential("alpha", entry, runtimeSelection, { diff --git a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts index e392c393419..f7b043da093 100644 --- a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts @@ -294,7 +294,7 @@ export async function prepareMcpBridgesForRebuild( // Hermes/agent cannot boot with a stale placeholder while its provider // is intentionally detached during recreate. scrubbedAdapters.push( - scrubManagedMcpAdapterOrThrow(sandboxName, sandbox, entry, providerRuntimeSelection), + await scrubManagedMcpAdapterOrThrow(sandboxName, sandbox, entry, providerRuntimeSelection), ); } for (const entry of entries) { @@ -321,7 +321,7 @@ export async function prepareMcpBridgesForRebuild( `Could not prove provider detach for MCP server '${entry.server}'.`, ); } - waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); + await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); // A binding already absent on retry was still detached by this rebuild // transaction (possibly before a prior process died), so it must be // reattached if sandbox deletion later aborts. @@ -346,12 +346,12 @@ export async function prepareMcpBridgesForRebuild( } if (!runtimeRestored) { rollbackFailures.push( - ...rollbackScrubbedMcpAdapters( + ...(await rollbackScrubbedMcpAdapters( sandboxName, sandbox, scrubbedAdapters, providerRuntimeSelection, - ), + )), ); } const detail = error instanceof Error ? error.message : String(error); @@ -410,12 +410,12 @@ export async function reattachMcpProvidersAfterRebuildAbort( } if (!runtimeRestored) { failures.push( - ...rollbackScrubbedMcpAdapters( + ...(await rollbackScrubbedMcpAdapters( sandboxName, sandbox, scrubbedAdapterEntries, providerRuntimeSelection, - ), + )), ); } if (failures.length > 0) { diff --git a/src/lib/actions/sandbox/mcp-bridge-remove.ts b/src/lib/actions/sandbox/mcp-bridge-remove.ts index d6ef7237812..2b17fd5c407 100644 --- a/src/lib/actions/sandbox/mcp-bridge-remove.ts +++ b/src/lib/actions/sandbox/mcp-bridge-remove.ts @@ -391,7 +391,7 @@ async function removeMcpBridgeUnlocked( // skipping a fresh-exec probe lets cleanup proceed even if another // unrelated provider reference is also dangling. if (!providerWasMissing && !providerDetachedBeforeAdapterCleanup) { - waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); + await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); } reservationCleanupProved = true; } diff --git a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.test.ts b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.test.ts index 324aac09758..c0d282532d9 100644 --- a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.test.ts @@ -295,8 +295,8 @@ describe("MCP credential-resolution probe execution gates", () => { [{ ...readyProbe, providerCredentialReady: false }, "does not match"], ] as const)( "fails closed before sandbox traffic unless policy and provider readiness are all true [case %#] (#6379)", - (readiness, expectedDetail) => { - const probe = probeCredentialResolution( + async (readiness, expectedDetail) => { + const probe = await probeCredentialResolution( "alpha", baseEntry, "mcporter", @@ -309,8 +309,8 @@ describe("MCP credential-resolution probe execution gates", () => { }, ); - it("skips without contacting the sandbox when the adapter is not declared (#6379)", () => { - const probe = probeCredentialResolution( + it("skips without contacting the sandbox when the adapter is not declared (#6379)", async () => { + const probe = await probeCredentialResolution( "alpha", baseEntry, undefined, @@ -321,8 +321,8 @@ describe("MCP credential-resolution probe execution gates", () => { expect(mocks.executeSandboxCommand).not.toHaveBeenCalled(); }); - it("skips without contacting the sandbox while an add transaction is incomplete (#6379)", () => { - const probe = probeCredentialResolution( + it("skips without contacting the sandbox while an add transaction is incomplete (#6379)", async () => { + const probe = await probeCredentialResolution( "alpha", { ...baseEntry, addState: "preflighted" }, "mcporter", @@ -333,8 +333,8 @@ describe("MCP credential-resolution probe execution gates", () => { expect(mocks.executeSandboxCommand).not.toHaveBeenCalled(); }); - it("skips without contacting the sandbox when the stored URL is unsafe (#6379)", () => { - const probe = probeCredentialResolution( + it("skips without contacting the sandbox when the stored URL is unsafe (#6379)", async () => { + const probe = await probeCredentialResolution( "alpha", { ...baseEntry, url: "http://api.githubcopilot.com/mcp/" }, "mcporter", @@ -345,7 +345,7 @@ describe("MCP credential-resolution probe execution gates", () => { expect(mocks.executeSandboxCommand).not.toHaveBeenCalled(); }); - it("executes the probe in the sandbox and classifies the outcome (#6379)", () => { + it("executes the probe in the sandbox and classifies the outcome (#6379)", async () => { mocks.executeSandboxCommand.mockImplementation((_sandboxName: string, command: string) => { const resultMarker = command.match(/__NEMOCLAW_SANDBOX_EXEC_STARTED___[0-9a-f]{32}/)?.[0]; return { @@ -360,7 +360,7 @@ describe("MCP credential-resolution probe execution gates", () => { stderr: "", }; }); - const probe = probeCredentialResolution( + const probe = await probeCredentialResolution( "alpha", baseEntry, "mcporter", @@ -376,7 +376,7 @@ describe("MCP credential-resolution probe execution gates", () => { expect(mocks.executeSandboxCommand.mock.calls[0]?.[2]).toEqual({ runtimeSelection }); }); - it("reuses a status observation instead of starting a second revision check (#10079)", () => { + it("reuses a status observation instead of starting a second revision check (#10079)", async () => { mocks.executeSandboxCommand.mockImplementation((_sandboxName: string, command: string) => { const resultMarker = command.match(/__NEMOCLAW_SANDBOX_EXEC_STARTED___[0-9a-f]{32}/)?.[0]; return { @@ -392,7 +392,7 @@ describe("MCP credential-resolution probe execution gates", () => { }; }); - const probe = probeCredentialResolution( + const probe = await probeCredentialResolution( "alpha", baseEntry, "mcporter", @@ -408,10 +408,10 @@ describe("MCP credential-resolution probe execution gates", () => { ); }); - it("does not probe with an identityless canonical placeholder (#10079)", () => { + it("does not probe with an identityless canonical placeholder (#10079)", async () => { mocks.observeMcpCredentialRevision.mockReturnValue("canonical"); - const probe = probeCredentialResolution( + const probe = await probeCredentialResolution( "alpha", baseEntry, "mcporter", diff --git a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts index dbc58f100e8..44b78115bbc 100644 --- a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts +++ b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts @@ -384,14 +384,14 @@ export function credentialResolutionWarning( return `Credential resolution could not be verified: a placeholder-bearing MCP initialize probe and a deliberately-unresolvable control probe were rejected identically (HTTP ${probe.httpStatus}). If the stored credential is confirmed valid, the OpenShell host is not rewriting the '${placeholder}' placeholder on egress and agent runtimes will hit the same auth failure and skip this MCP server (see NVIDIA/OpenShell issue 2161). Otherwise, rotate the credential with mcp restart and re-run mcp status.`; } -export function probeCredentialResolution( +export async function probeCredentialResolution( sandboxName: string, entry: McpBridgeEntry, adapter: AgentMcpAdapter | undefined, readiness: CredentialResolutionProbeReadiness, runtimeSelection: McpProviderInspectionRuntimeSelection, observedCredentialRevision?: McpCredentialRevisionObservation, -): CredentialResolutionProbe { +): Promise { if (!adapter) return { ok: null, detail: "MCP adapter is not declared" }; if (entry.addState) return { ok: null, detail: "add transaction incomplete" }; const readinessSkipDetail = credentialResolutionReadinessSkipDetail(readiness); @@ -408,7 +408,7 @@ export function probeCredentialResolution( let credentialRevision = observedCredentialRevision; if (credentialRevision === undefined) { try { - credentialRevision = observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); + credentialRevision = await observeMcpCredentialRevision(sandboxName, entry, runtimeSelection); } catch { return { ok: null, diff --git a/src/lib/actions/sandbox/mcp-bridge-restart.ts b/src/lib/actions/sandbox/mcp-bridge-restart.ts index 772abe07004..b7a3aab4216 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart.ts @@ -207,7 +207,7 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P providerRuntimeSelection, ); for (const entry of missingProviderEntries) { - waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); + await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); } // Inspect registered providers once before the first mutation. Per-entry // checks below inspect only attached providers at each mutation edge. @@ -241,9 +241,9 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P allowExisting: true, expectedProviderId: entry.providerId, runtimeSelection: providerRuntimeSelection, - prepareMutation: (action) => { + prepareMutation: async (action) => { if (action === "update") { - previousCredentialRevision = observeMcpCredentialRevision( + previousCredentialRevision = await observeMcpCredentialRevision( sandboxName, entry, providerRuntimeSelection, @@ -291,7 +291,7 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P : {}), }, ); - registerAgentAdapterAtCurrentCredentialRevision( + await registerAgentAdapterAtCurrentCredentialRevision( sandboxName, entryAdapter, entry, @@ -394,7 +394,7 @@ export async function restoreExistingMcpBridgeRuntime( entry, providerRuntimeSelection, ); - registerAgentAdapterAtCurrentCredentialRevision( + await registerAgentAdapterAtCurrentCredentialRevision( sandboxName, adapter, entry, diff --git a/src/lib/actions/sandbox/mcp-bridge-status.ts b/src/lib/actions/sandbox/mcp-bridge-status.ts index 754b816d481..22b8095e49f 100644 --- a/src/lib/actions/sandbox/mcp-bridge-status.ts +++ b/src/lib/actions/sandbox/mcp-bridge-status.ts @@ -268,7 +268,7 @@ export async function statusMcpBridge( try { credentialObservations.set( name, - observeMcpCredentialRevision(sandboxName, entry, providerRuntimeSelection), + await observeMcpCredentialRevision(sandboxName, entry, providerRuntimeSelection), ); } catch { credentialObservations.set(name, null); @@ -433,7 +433,7 @@ export async function statusMcpBridge( detail: "probe skipped: the managed agent adapter does not match the current credential revision", } - : probeCredentialResolution( + : await probeCredentialResolution( sandboxName, entry, support.adapter, @@ -452,7 +452,7 @@ export async function statusMcpBridge( ? mcpToolDiscoveryPreconditionFailure( `tool discovery skipped: ${UNSUPPORTED_ATTACHED_CREDENTIAL_DETAIL}`, ) - : discoverMcpTools( + : await discoverMcpTools( sandboxName, entry, support.adapter, diff --git a/src/lib/actions/sandbox/policy-channel-conflict.test.ts b/src/lib/actions/sandbox/policy-channel-conflict.test.ts index c366c6c4960..c4a839e54ef 100644 --- a/src/lib/actions/sandbox/policy-channel-conflict.test.ts +++ b/src/lib/actions/sandbox/policy-channel-conflict.test.ts @@ -408,7 +408,7 @@ beforeEach(() => { // unit-test runner; locally it is installed, so this only bites in CI). Stub // the exec path so the post-add verification never shells out and never trips // the exit spy unless a test explicitly overrides it. - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue(null); + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue(null); vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue(null); process.env.NEMOCLAW_SKIP_TELEGRAM_REACHABILITY = "1"; @@ -1228,6 +1228,11 @@ describe("addSandboxChannel cross-sandbox conflict check (#4305)", () => { const execCommands = vi .mocked(processRecovery.executeSandboxExecCommand) .mock.calls.map((call: unknown[]) => String(call[1])); + expect( + vi + .mocked(processRecovery.executeSandboxExecCommand) + .mock.calls.every((call) => call[3]?.localDockerFallbackPolicy === "read-only"), + ).toBe(true); expect(execCommands.some((cmd: string) => cmd.includes("grep"))).toBe(false); expect( execCommands.some( @@ -1396,7 +1401,7 @@ describe("Teams host-forward lifecycle (PRA-2)", () => { function mockBridgeHealthExec(options: { config: unknown; log: string }): void { vi.mocked(processRecovery.executeSandboxExecCommand).mockImplementation( - (_sandboxName: string, command: string) => { + async (_sandboxName: string, command: string) => { if (command.includes("cat") && command.includes("openclaw.json")) { return { status: 0, stdout: JSON.stringify(options.config), stderr: "" }; } diff --git a/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts b/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts index 24caf98d835..d8e9dc2e0c8 100644 --- a/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts +++ b/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts @@ -28,7 +28,7 @@ describe("policy channel remove/enable flows", () => { }) as never); logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "NEMOCLAW_CHANNEL_CLEAR_OK\n", stderr: "", @@ -163,6 +163,10 @@ describe("policy channel remove/enable flows", () => { "/sandbox/.hermes/profiles/dashboard-home/platforms/whatsapp/session", ); expect(clearCommand).toContain("/sandbox/.hermes/dashboard-home/platforms/whatsapp/session"); + expect(vi.mocked(processRecovery.executeSandboxExecCommand).mock.calls[0]?.slice(2)).toEqual([ + undefined, + { localDockerFallbackPolicy: "reconciled" }, + ]); expect(updateSandbox).toHaveBeenCalled(); expect( vi.mocked(processRecovery.executeSandboxExecCommand).mock.invocationCallOrder[0], @@ -176,7 +180,7 @@ describe("policy channel remove/enable flows", () => { "clears every Hermes WhatsApp session path through $scenario", async ({ execStatus, usesSsh }) => { const { updateSandbox } = await arrangeHermesWhatsappRemoval(); - vi.mocked(processRecovery.executeSandboxExecCommand).mockReturnValue({ + vi.mocked(processRecovery.executeSandboxExecCommand).mockResolvedValue({ status: execStatus, stdout: execStatus === 0 ? "NEMOCLAW_CHANNEL_CLEAR_OK\n" : "", stderr: execStatus === 0 ? "" : "exec unavailable", @@ -210,7 +214,7 @@ describe("policy channel remove/enable flows", () => { it("keeps channel state unchanged when both Hermes cleanup transports fail", async () => { const { rebuildSandbox, removePreset, updateSandbox } = await arrangeHermesWhatsappRemoval(); const runOpenshell = vi.spyOn(openshellRuntime, "runOpenshell"); - vi.mocked(processRecovery.executeSandboxExecCommand).mockReturnValue({ + vi.mocked(processRecovery.executeSandboxExecCommand).mockResolvedValue({ status: 1, stdout: "", stderr: "exec unavailable", diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index cddd33a1c3b..f3d3f3e152b 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -933,7 +933,8 @@ async function applyChannelAddToGatewayAndRegistry( () => revalidateMessagingProviderAttachmentTarget(sandboxName, gatewayName), ); const updatedProviderNames = err.mutatedProviderNames.filter( - (providerName) => !createdProviders.has(providerName) || replacedProviders.has(providerName), + (providerName) => + !createdProviders.has(providerName) || replacedProviders.has(providerName), ); const originalFailure = redactFullWithUrls(err instanceof Error ? err.message : String(err)) .replace(/\s+/gu, " ") @@ -1109,7 +1110,9 @@ async function runMessagingHealthChecksAfterRebuild( openclawBridgeHealth: { sandboxName, executeSandboxCommand: (command, timeoutMs) => - executeSandboxExecCommand(sandboxName, command, timeoutMs), + executeSandboxExecCommand(sandboxName, command, timeoutMs, { + localDockerFallbackPolicy: "read-only", + }), }, }); try { @@ -1765,14 +1768,15 @@ function stoppedWechatCleanupFailureGuidance( /** * Wipe durable channel state before rebuild can preserve an obsolete auth blob. - * OpenShell exec runs first, followed by SSH and the selected provider's stopped-state fallback. + * OpenShell exec runs first. A permitted reconciled runtime-provider retry runs before SSH. + * OpenClaw WeChat stopped-state cleanup runs last. * Fixes #3998. */ -function clearSandboxChannelDurableState( +async function clearSandboxChannelDurableState( sandboxName: string, channelName: string, options: { readonly allowAbsentStoppedState?: boolean } = {}, -): boolean { +): Promise { const agent = resolveAgentForSandbox(sandboxName); const paths = getSandboxChannelStatePaths(agent, channelName); if (!paths.every(isSafeChannelStatePath)) { @@ -1786,7 +1790,9 @@ function clearSandboxChannelDurableState( const sentinelSeen = (result: { stdout?: string | null } | null): boolean => !!result && typeof result.stdout === "string" && result.stdout.includes(CHANNEL_CLEAR_SENTINEL); - let result = executeSandboxExecCommand(sandboxName, cmd); + let result = await executeSandboxExecCommand(sandboxName, cmd, undefined, { + localDockerFallbackPolicy: "reconciled", + }); if (!sentinelSeen(result)) { result = executeSandboxCommand(sandboxName, cmd); } @@ -1933,9 +1939,9 @@ async function removeSandboxChannelUnlocked( if ( requiresStateCleanupBeforeTeardown && (hasChannelResidue || recoverPhysicalWechatResidue) && - !clearSandboxChannelDurableState(sandboxName, canonical, { + !(await clearSandboxChannelDurableState(sandboxName, canonical, { allowAbsentStoppedState: !hasChannelResidue, - }) + })) ) { console.error( ` Refusing to proceed: '${canonical}' session state is still inside the sandbox.`, @@ -2014,7 +2020,7 @@ async function removeSandboxChannelUnlocked( // revocation already prevents the bot from authenticating, so a // failure here is a warning, not a bail. if (!requiresStateCleanupBeforeTeardown) { - clearSandboxChannelDurableState(sandboxName, canonical); + await clearSandboxChannelDurableState(sandboxName, canonical); } const rebuilt = await promptAndRebuild(sandboxName, `remove '${canonical}'`); diff --git a/src/lib/actions/sandbox/probe/hermes-portable-forward-recovery.test.ts b/src/lib/actions/sandbox/probe/hermes-portable-forward-recovery.test.ts index 58c3f579cb0..ba62ca833f2 100644 --- a/src/lib/actions/sandbox/probe/hermes-portable-forward-recovery.test.ts +++ b/src/lib/actions/sandbox/probe/hermes-portable-forward-recovery.test.ts @@ -1008,13 +1008,13 @@ describe("Hermes Portable connect composition", () => { portableRecoveryResult: { kind: "already-running" }, }); let ollamaRunning = false; - harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation(((input: { - verifyRoute: () => unknown; + harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation((async (input: { + verifyRoute: () => Promise; prepareProbeDependency?: () => { release: () => void; rollback: () => void }; }) => { ollamaRunning = true; try { - input.verifyRoute(); + await input.verifyRoute(); input.prepareProbeDependency?.().release(); return "recovered"; } catch (error) { @@ -1053,12 +1053,12 @@ describe("Hermes Portable connect composition", () => { portableRecoveryResult: { kind: "already-running" }, }); let ollamaRunning = false; - harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation(((input: { - verifyRoute: () => unknown; + harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation((async (input: { + verifyRoute: () => Promise; prepareProbeDependency?: () => { rollback: () => void }; }) => { ollamaRunning = true; - input.verifyRoute(); + await input.verifyRoute(); const dependency = input.prepareProbeDependency?.(); try { dependency?.rollback(); @@ -1087,12 +1087,12 @@ describe("Hermes Portable connect composition", () => { portableRecoveryResult: { kind: "already-running" }, }); let ollamaRunning = false; - harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation(((input: { - verifyRoute: () => unknown; + harness.recoverHermesPortableOllamaInferenceSpy.mockImplementation((async (input: { + verifyRoute: () => Promise; prepareProbeDependency?: () => { rollback: () => void }; }) => { ollamaRunning = true; - input.verifyRoute(); + await input.verifyRoute(); const dependency = input.prepareProbeDependency?.(); harness.assertHermesPortableOperatingCommandCurrentSpy.mockImplementation(() => { throw new Error("rollback authority canary"); diff --git a/src/lib/actions/sandbox/probe/hermes-portable-inference-recovery.ts b/src/lib/actions/sandbox/probe/hermes-portable-inference-recovery.ts index 08eaa9d68b1..a1c67a4cced 100644 --- a/src/lib/actions/sandbox/probe/hermes-portable-inference-recovery.ts +++ b/src/lib/actions/sandbox/probe/hermes-portable-inference-recovery.ts @@ -20,7 +20,7 @@ export interface HermesPortableInferenceConnectRecoveryInput { readonly sandboxName: string; readonly authority: HermesPortableActiveLifecycleAuthority; readonly readRegistry: (sandboxName: string) => SandboxEntry | null; - readonly verifyRoute: () => SandboxEntry; + readonly verifyRoute: () => Promise; readonly prepareProbeDependency?: () => HermesPortableOllamaPreparedProbeDependency; readonly assertCallerTransactionCurrent?: () => void; readonly assertCallerCurrent?: () => void; @@ -49,10 +49,10 @@ export function inspectHermesPortableInferenceReadinessRuntimeForConnectProbe( } /** Resume exact published Ollama authority for one probe-only connect operation. */ -export function recoverHermesPortableInferenceForConnectProbe( +export async function recoverHermesPortableInferenceForConnectProbe( input: HermesPortableInferenceConnectRecoveryInput, ) { - return recoverHermesPortableOllamaInference({ + return await recoverHermesPortableOllamaInference({ intent: "connect-probe-only", sandboxName: input.sandboxName, entry: input.authority.entry, diff --git a/src/lib/actions/sandbox/process-recovery-managed-startup.test.ts b/src/lib/actions/sandbox/process-recovery-managed-startup.test.ts index 73acc2761ff..601ec318eb2 100644 --- a/src/lib/actions/sandbox/process-recovery-managed-startup.test.ts +++ b/src/lib/actions/sandbox/process-recovery-managed-startup.test.ts @@ -71,7 +71,7 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { ["GATEWAY_HEALTH_TIMEOUT", false], ] as const)( "waits through the exact %s startup transition (#9466)", - (startupMarker, discovery) => { + async (startupMarker, discovery) => { const sandboxName = "startup-box"; mockGatewaySandbox(sandboxName); mockRecoveredForward(sandboxName); @@ -88,12 +88,12 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { .mockReturnValueOnce(ACCEPTED_MANAGED_RECOVERY); const relaunchManagedSupervisorSessionImpl = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses(sandboxName, { + const result = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, - waitForRecreatedSandboxOpenShellReadyImpl: () => true, + waitForRecreatedSandboxOpenShellReadyImpl: async () => true, }); expect(result).toMatchObject({ @@ -107,7 +107,7 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { }, ); - it("does not retry a diagnostic-bearing supervisor-discovery result", () => { + it("does not retry a diagnostic-bearing supervisor-discovery result", async () => { const sandboxName = "diagnostic-start"; mockGatewaySandbox(sandboxName); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "0"); @@ -118,9 +118,9 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses(sandboxName, { + const result = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, }); @@ -135,7 +135,7 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { expect(relaunchManagedSupervisorSessionImpl).not.toHaveBeenCalled(); }); - it("does not retry a managed-container identity mismatch (#9466)", () => { + it("does not retry a managed-container identity mismatch (#9466)", async () => { const sandboxName = "identity-box"; mockGatewaySandbox(sandboxName); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "0"); @@ -148,9 +148,9 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses(sandboxName, { + const result = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, }); @@ -165,7 +165,7 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { expect(relaunchManagedSupervisorSessionImpl).not.toHaveBeenCalled(); }); - it("shares one deadline across managed recovery controller calls (#11107)", () => { + it("shares one deadline across managed recovery controller calls (#11107)", async () => { const sandboxName = "deadline-box"; mockGatewaySandbox(sandboxName); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "3"); @@ -183,9 +183,9 @@ describe("checkAndRecoverSandboxProcesses managed startup", () => { ); const onRecoveryFailureLayer = vi.fn(); - const result = checkAndRecoverSandboxProcesses(sandboxName, { + const result = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, managedControlNowImpl: () => now, managedControlTimeoutMs: 20_000, onRecoveryFailureLayer, @@ -327,7 +327,7 @@ describe("managed container discovery settlement", () => { expect({ calls, seconds }).toEqual({ calls: 31, seconds: 90 }); }); - it("waits through supervisor startup before recreation after delayed discovery (#11107)", () => { + it("waits through supervisor startup before recreation after delayed discovery (#11107)", async () => { const sandboxName = "hermes-discovery"; mockGatewaySandbox(sandboxName, "hermes"); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "3"); @@ -339,9 +339,9 @@ describe("managed container discovery settlement", () => { expect(seconds).toBe(66); return null; }); - const result = checkAndRecoverSandboxProcesses(sandboxName, { + const result = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction: () => ({ status: 1, stdout: "", @@ -374,7 +374,7 @@ describe("managed container discovery settlement", () => { { readyAt: 63, recovered: false, elapsed: 60 }, ])( "ends Hermes recovery at $elapsed seconds when discovery needs $readyAt seconds (#11107)", - ({ readyAt, recovered, elapsed }) => { + async ({ readyAt, recovered, elapsed }) => { const sandboxName = "hermes-discovery"; mockGatewaySandbox(sandboxName, "hermes"); mockRecoveredForward(sandboxName); @@ -385,13 +385,13 @@ describe("managed container discovery settlement", () => { seconds += duration; }); const relaunch = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses(sandboxName, { + const result = await checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction: () => seconds >= readyAt ? ACCEPTED_MANAGED_RECOVERY : PENDING_MANAGED_CONTAINER_DISCOVERY, relaunchManagedSupervisorSessionImpl: relaunch, - waitForRecreatedSandboxOpenShellReadyImpl: () => true, + waitForRecreatedSandboxOpenShellReadyImpl: async () => true, }); expect({ recovered: result.recovered, elapsed: seconds }).toEqual({ recovered, elapsed }); expect(relaunch).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts index fad669039b4..7b7a2be6a0d 100644 --- a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts +++ b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts @@ -9,6 +9,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const captureSandboxSshConfig = vi.hoisted(() => vi.fn()); const executePrivilegedSandboxCommand = vi.hoisted(() => vi.fn()); +const runBuffered = vi.hoisted(() => vi.fn()); + +vi.mock("../../adapters/openshell/sandbox-command-cli", () => ({ + createCliOpenShellSandboxCommandExecutor: vi.fn(() => ({ runBuffered })), +})); vi.mock("node:child_process", async (importOriginal) => { const actual = await importOriginal(); @@ -40,6 +45,11 @@ import { executeSandboxCommand, executeSandboxExecCommand } from "./process-reco describe("executeSandboxCommand temp SSH config", () => { beforeEach(() => { vi.clearAllMocks(); + runBuffered.mockResolvedValue({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: "", + stderr: "", + }); }); afterEach(() => { @@ -119,23 +129,20 @@ describe("executeSandboxCommand temp SSH config", () => { ); }); - it("pins strict OpenShell exec to the same authority-derived target (#10514)", () => { + it("pins strict OpenShell exec to the same authority-derived target (#10514)", async () => { vi.stubEnv("OPENSHELL_GATEWAY", "ambient-gateway"); vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://ambient.invalid"); vi.stubEnv("OPENSHELL_GATEWAY_INSECURE", "true"); vi.stubEnv("OPENSHELL_LOCAL_TLS_DIR", "/ambient/tls"); vi.stubEnv("OPENSHELL_TOKEN", "ambient-token"); vi.stubEnv("OPENSHELL_WORKSPACE", "ambient-workspace"); - vi.mocked(spawnSync).mockReturnValue({ - status: 0, + runBuffered.mockResolvedValue({ + outcome: { kind: "completed", exitCode: 0 }, stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nrevision-1\n", stderr: "", - pid: 1234, - output: [], - signal: null, }); - expect( + await expect( executeSandboxExecCommand("alpha", "printf revision-1", undefined, { runtimeSelection: { gatewayName: "nemoclaw-8091", @@ -143,32 +150,30 @@ describe("executeSandboxCommand temp SSH config", () => { workspace: "default", }, }), - ).toEqual({ status: 0, stdout: "revision-1", stderr: "" }); + ).resolves.toEqual({ status: 0, stdout: "revision-1", stderr: "" }); - const [command, args, options] = vi.mocked(spawnSync).mock.calls[0] ?? []; - expect(command).toBe("openshell"); - expect(args).toEqual( - expect.arrayContaining(["sandbox", "exec", "--name", "alpha", "-g", "nemoclaw-8091"]), - ); - expect(options?.env).toMatchObject({ + const request = runBuffered.mock.calls[0]?.[0]; + expect(request).toMatchObject({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw-8091" }, + command: ["sh", "-c", expect.stringContaining("printf revision-1")], + }); + expect(request?.environment).toMatchObject({ OPENSHELL_GATEWAY: "nemoclaw-8091", OPENSHELL_LOCAL_TLS_DIR: "/authority/tls", OPENSHELL_WORKSPACE: "default", }); - expect(options?.env).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); - expect(options?.env).not.toHaveProperty("OPENSHELL_GATEWAY_INSECURE"); - expect(options?.env).not.toHaveProperty("OPENSHELL_TOKEN"); + expect(request?.environment).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); + expect(request?.environment).not.toHaveProperty("OPENSHELL_GATEWAY_INSECURE"); + expect(request?.environment).not.toHaveProperty("OPENSHELL_TOKEN"); expect(executePrivilegedSandboxCommand).not.toHaveBeenCalled(); }); - it("fails closed instead of using a same-name local sandbox for selected exec (#10514)", () => { - vi.mocked(spawnSync).mockReturnValue({ - status: 1, + it("fails closed instead of using a same-name local sandbox for selected exec (#10514)", async () => { + runBuffered.mockResolvedValue({ + outcome: { kind: "completed", exitCode: 1 }, stdout: "selected gateway unavailable\n", stderr: "", - pid: 1234, - output: [], - signal: null, }); executePrivilegedSandboxCommand.mockReturnValue({ status: 0, @@ -176,16 +181,16 @@ describe("executeSandboxCommand temp SSH config", () => { stderr: "", }); - expect( + await expect( executeSandboxExecCommand("alpha", "printf selected", undefined, { - allowLocalDockerFallback: true, + localDockerFallbackPolicy: "read-only", runtimeSelection: { gatewayName: "recorded-gateway", localTlsDir: "/authority/tls", workspace: "default", }, }), - ).toBeNull(); + ).resolves.toBeNull(); expect(executePrivilegedSandboxCommand).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/process-recovery.test.ts b/src/lib/actions/sandbox/process-recovery.test.ts index aa42b171cc0..698e4c3c1b0 100644 --- a/src/lib/actions/sandbox/process-recovery.test.ts +++ b/src/lib/actions/sandbox/process-recovery.test.ts @@ -3,6 +3,10 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandExecutor, +} from "../../adapters/openshell/sandbox-command"; import { parseManagedGatewayControlCompletion } from "./gateway-restart"; // Import source directly so this test cannot pass against a stale build. import { @@ -41,6 +45,36 @@ const OPENSHELL_RELAY_TARGET_REFUSED_STDERR = `Error: × code: 'The service is const OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR = "Error: sandbox 'recreated-box' is not ready (phase: Error); wait for it to reach Ready state.\n"; +function completed( + exitCode: number, + stderr = "", + stdout = "", +): OpenShellSandboxBufferedCommandCompletion { + return { outcome: { kind: "completed", exitCode }, stdout, stderr }; +} + +function timedOut(): OpenShellSandboxBufferedCommandCompletion { + return { + outcome: { kind: "failed", error: { kind: "timeout", message: "timed out" } }, + stdout: "", + stderr: "", + }; +} + +function sequencedExecutor( + first: OpenShellSandboxBufferedCommandCompletion, + ...remaining: OpenShellSandboxBufferedCommandCompletion[] +): OpenShellSandboxBufferedCommandExecutor & { runBuffered: ReturnType } { + const results = [first, ...remaining]; + let index = 0; + const runBuffered = vi.fn(async () => { + const result = results[Math.min(index, results.length - 1)] ?? first; + index += 1; + return result; + }); + return { runBuffered }; +} + describe("managed gateway control completion", () => { const nonce = "a".repeat(64); @@ -49,15 +83,18 @@ describe("managed gateway control completion", () => { ["ok", 4242, 4242], ["already-running", 4242, 4242], ["already-running", 4242, 5252], - ] as const)("preserves the exact %s controller disposition (#7919)", (disposition, oldPid, newPid) => { - expect( - parseManagedGatewayControlCompletion({ - status: 0, - stdout: `v1 ${nonce} complete ${disposition} ${oldPid} ${newPid}\nGATEWAY_PID=${newPid}`, - stderr: "", - }), - ).toEqual({ disposition, oldPid, newPid }); - }); + ] as const)( + "preserves the exact %s controller disposition (#7919)", + (disposition, oldPid, newPid) => { + expect( + parseManagedGatewayControlCompletion({ + status: 0, + stdout: `v1 ${nonce} complete ${disposition} ${oldPid} ${newPid}\nGATEWAY_PID=${newPid}`, + stderr: "", + }), + ).toEqual({ disposition, oldPid, newPid }); + }, + ); it.each([ [`v1 ${nonce} complete already-running 4242 4242\nGATEWAY_PID=5252`, ""], @@ -76,211 +113,162 @@ describe("recreated sandbox OpenShell readiness", () => { vi.unstubAllEnvs(); }); - it("retries the structured not-ready state until OpenShell accepts the sandbox", () => { - const notReady = { - status: 1, - output: OPENSHELL_SANDBOX_NOT_READY_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_SANDBOX_NOT_READY_STDERR, - }; - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce(notReady) - .mockReturnValueOnce(notReady) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + it("retries the structured not-ready state until OpenShell accepts the sandbox", async () => { + const notReady = completed(1, OPENSHELL_SANDBOX_NOT_READY_STDERR); + const commandExecutor = sequencedExecutor(notReady, notReady, completed(0)); const beforeProbe = vi.fn(() => true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(true); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(3); - expect(captureOpenshellImpl).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "recreated-box", "--", "true"], + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(3); + expect(commandExecutor.runBuffered).toHaveBeenCalledWith( expect.objectContaining({ - ignoreError: true, - includeStderr: true, - includeStreams: true, + sandboxName: "recreated-box", + target: { kind: "selected" }, + command: ["true"], + timeoutMilliseconds: expect.any(Number), }), ); expect(beforeProbe).toHaveBeenCalledTimes(3); expect(sleeps).toEqual([3, 3]); }); - it("retries the same-sandbox Error phase until OpenShell accepts the sandbox", () => { - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: 1, - output: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR, - }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + it("retries the same-sandbox Error phase until OpenShell accepts the sandbox", async () => { + const commandExecutor = sequencedExecutor( + completed(1, OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR), + completed(0), + ); const beforeProbe = vi.fn(() => true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(true); expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(2); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(2); expect(sleeps).toEqual([3]); }); - it("retries the exact same-sandbox Error phase when OpenShell also emits informational stdout", () => { - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: 1, - output: - `Waiting for sandbox registration\n${OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR}`.trim(), - stdout: "Waiting for sandbox registration\n", - stderr: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR, - }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + it("retries the exact same-sandbox Error phase when OpenShell also emits informational stdout", async () => { + const commandExecutor = sequencedExecutor( + completed(1, OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR, "Waiting for sandbox registration\n"), + completed(0), + ); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe: () => true, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(true); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(2); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(2); expect(sleeps).toEqual([3]); }); - it("keeps an empty read-only probe inconclusive after exact replacement re-registration", () => { - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: 1, - output: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR, - }) - .mockReturnValueOnce({ status: 1, output: "", stdout: "", stderr: "" }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + it("keeps an empty read-only probe inconclusive after exact replacement re-registration", async () => { + const commandExecutor = sequencedExecutor( + completed(1, OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR), + completed(1), + completed(0), + ); const beforeProbe = vi.fn(() => true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(true); expect(beforeProbe).toHaveBeenCalledTimes(3); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(3); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(3); expect(sleeps).toEqual([3, 3]); }); - it("keeps an empty first OpenShell failure terminal", () => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 1, - output: "", - stdout: "", - stderr: "", - })); + it("keeps an empty first OpenShell failure terminal", async () => { + const commandExecutor = sequencedExecutor(completed(1)); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe: () => true, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(false); - expect(captureOpenshellImpl).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(sleeps).toEqual([]); }); - it("rides out a transient Error phase past the old 30s budget by default (#7227)", () => { + it("rides out a transient Error phase past the old 30s budget by default (#7227)", async () => { // No timeoutSeconds option and no env override: the default recovery budget // must be large enough (120s, aligned with connect's readiness wait) to keep // retrying a cold-start phase:Error settling window that exceeds the old // 30s / 11-attempt budget. The 12th probe (past the old 11-attempt cap) must // still be reached, so the primary dashboard/API forward is not abandoned. delete process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; - const errorPhase = { - status: 1, - output: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR, - }; - const captureOpenshellImpl = vi.fn(); - for (let attempt = 0; attempt < 11; attempt += 1) { - captureOpenshellImpl.mockReturnValueOnce(errorPhase); - } - captureOpenshellImpl.mockReturnValueOnce({ - status: 0, - output: "", - stdout: "", - stderr: "", - }); + const errorPhase = completed(1, OPENSHELL_TRANSIENT_ERROR_PHASE_STDERR); + const commandExecutor = sequencedExecutor( + errorPhase, + ...Array.from({ length: 10 }, () => errorPhase), + completed(0), + ); expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe: () => true, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: () => {}, // no timeoutSeconds -> exercise the default budget; the old 30s default // capped at 11 attempts and would have given up before the 12th probe. }), ).toBe(true); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(12); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(12); }); - it("retries the exact supervisor reconnect states exposed during direct recreation", () => { + it("retries the exact supervisor reconnect states exposed during direct recreation", async () => { const reconnecting = [ OPENSHELL_SUPERVISOR_NOT_CONNECTED_STDERR, OPENSHELL_SUPERVISOR_DISCONNECTED_STDERR, - ].map((stderr) => ({ - status: 1, - output: stderr.trim(), - stdout: "", - stderr, - })); - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce(reconnecting[0]) - .mockReturnValueOnce(reconnecting[1]) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + ].map((stderr) => completed(1, stderr)); + const commandExecutor = sequencedExecutor(reconnecting[0], reconnecting[1], completed(0)); const beforeProbe = vi.fn(() => true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(true); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(3); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(3); expect(beforeProbe).toHaveBeenCalledTimes(3); expect(sleeps).toEqual([3, 3]); }); @@ -288,89 +276,71 @@ describe("recreated sandbox OpenShell readiness", () => { it.each([ OPENSHELL_RELAY_OPEN_TIMED_OUT_STDERR, OPENSHELL_SUPERVISOR_RELAY_CHANNEL_TIMED_OUT_STDERR, - ])("retries when the connected supervisor misses OpenShell's relay deadline (#7227)", (stderr) => { - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: 1, - output: stderr.trim(), - stdout: "", - stderr, - }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); - const beforeProbe = vi.fn(() => true); - const sleeps: number[] = []; - - expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { - beforeProbe, - captureOpenshellImpl, - intervalSeconds: 3, - sleepImpl: (seconds) => sleeps.push(seconds), - timeoutSeconds: 30, - }), - ).toBe(true); - expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(2); - expect(sleeps).toEqual([3]); - }); - - it("retries when OpenShell drops the replacement supervisor's reverse relay", () => { - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: 1, - output: OPENSHELL_RELAY_CHANNEL_DROPPED_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_RELAY_CHANNEL_DROPPED_STDERR, - }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + ])( + "retries when the connected supervisor misses OpenShell's relay deadline (#7227)", + async (stderr) => { + const commandExecutor = sequencedExecutor(completed(1, stderr), completed(0)); + const beforeProbe = vi.fn(() => true); + const sleeps: number[] = []; + + expect( + await waitForRecreatedSandboxOpenShellReady("recreated-box", { + beforeProbe, + commandExecutor, + intervalSeconds: 3, + sleepImpl: (seconds) => sleeps.push(seconds), + timeoutSeconds: 30, + }), + ).toBe(true); + expect(beforeProbe).toHaveBeenCalledTimes(2); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(2); + expect(sleeps).toEqual([3]); + }, + ); + + it("retries when OpenShell drops the replacement supervisor's reverse relay", async () => { + const commandExecutor = sequencedExecutor( + completed(1, OPENSHELL_RELAY_CHANNEL_DROPPED_STDERR), + completed(0), + ); const beforeProbe = vi.fn(() => true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(true); expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(2); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(2); expect(sleeps).toEqual([3]); }); - it.each([ - OPENSHELL_RELAY_TARGET_NOT_FOUND_STDERR, - OPENSHELL_RELAY_TARGET_REFUSED_STDERR, - ])("retries while the replacement supervisor's local relay target starts (#7273)", (stderr) => { - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: 1, - output: stderr.trim(), - stdout: "", - stderr, - }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); - const beforeProbe = vi.fn(() => true); - const sleeps: number[] = []; - - expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { - beforeProbe, - captureOpenshellImpl, - intervalSeconds: 3, - sleepImpl: (seconds) => sleeps.push(seconds), - timeoutSeconds: 30, - }), - ).toBe(true); - expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(2); - expect(sleeps).toEqual([3]); - }); + it.each([OPENSHELL_RELAY_TARGET_NOT_FOUND_STDERR, OPENSHELL_RELAY_TARGET_REFUSED_STDERR])( + "retries while the replacement supervisor's local relay target starts (#7273)", + async (stderr) => { + const commandExecutor = sequencedExecutor(completed(1, stderr), completed(0)); + const beforeProbe = vi.fn(() => true); + const sleeps: number[] = []; + + expect( + await waitForRecreatedSandboxOpenShellReady("recreated-box", { + beforeProbe, + commandExecutor, + intervalSeconds: 3, + sleepImpl: (seconds) => sleeps.push(seconds), + timeoutSeconds: 30, + }), + ).toBe(true); + expect(beforeProbe).toHaveBeenCalledTimes(2); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(2); + expect(sleeps).toEqual([3]); + }, + ); it.each([ `Error: × status: DeadlineExceeded, message: "policy update timed out"`, @@ -380,193 +350,148 @@ describe("recreated sandbox OpenShell readiness", () => { `Error: × code: 'The service is currently unavailable', message: "permission denied"`, "Error: sandbox 'other-box' is not ready (phase: Error); wait for it to reach Ready state.", "Error: sandbox 'recreated-box' is not ready (phase: Failed); wait for it to reach Ready state.", - ])("does not retry an unrelated OpenShell error", (stderr) => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 1, - output: stderr, - stdout: "", - stderr, - })); + ])("does not retry an unrelated OpenShell error", async (stderr) => { + const commandExecutor = sequencedExecutor(completed(1, stderr)); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { - captureOpenshellImpl, + await waitForRecreatedSandboxOpenShellReady("recreated-box", { + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(false); - expect(captureOpenshellImpl).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(sleeps).toEqual([]); }); - it("fails immediately on an unknown OpenShell error", () => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 1, - output: "permission denied", - stdout: "", - stderr: "permission denied", - })); + it("fails immediately on an unknown OpenShell error", async () => { + const commandExecutor = sequencedExecutor(completed(1, "permission denied")); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { - captureOpenshellImpl, + await waitForRecreatedSandboxOpenShellReady("recreated-box", { + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(false); - expect(captureOpenshellImpl).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(sleeps).toEqual([]); }); - it("retries the no-op OpenShell readiness probe after a command timeout (#7273)", () => { - const timeoutError = Object.assign(new Error("timed out"), { code: "ETIMEDOUT" }); - const captureOpenshellImpl = vi - .fn() - .mockReturnValueOnce({ - status: null, - output: "", - stdout: "", - stderr: "", - error: timeoutError, - }) - .mockReturnValueOnce({ status: 0, output: "", stdout: "", stderr: "" }); + it("retries the no-op OpenShell readiness probe after a command timeout (#7273)", async () => { + const commandExecutor = sequencedExecutor(timedOut(), completed(0)); const beforeProbe = vi.fn(() => true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 30, }), ).toBe(true); expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledTimes(2); + expect(commandExecutor.runBuffered).toHaveBeenCalledTimes(2); expect(sleeps).toEqual([3]); }); - it("rechecks the pinned managed guard before every readiness retry", () => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 1, - output: OPENSHELL_SANDBOX_NOT_READY_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_SANDBOX_NOT_READY_STDERR, - })); + it("rechecks the pinned managed guard before every readiness retry", async () => { + const commandExecutor = sequencedExecutor(completed(1, OPENSHELL_SANDBOX_NOT_READY_STDERR)); const beforeProbe = vi.fn().mockReturnValueOnce(true).mockReturnValue(false); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(false); expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(sleeps).toEqual([3]); }); - it("retries an inconclusive managed guard within the readiness deadline", () => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 0, - output: "", - stdout: "", - stderr: "", - })); + it("retries an inconclusive managed guard within the readiness deadline", async () => { + const commandExecutor = sequencedExecutor(completed(0)); const beforeProbe = vi.fn().mockReturnValueOnce(null).mockReturnValueOnce(true); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(true); expect(beforeProbe).toHaveBeenCalledTimes(2); - expect(captureOpenshellImpl).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(sleeps).toEqual([3]); }); - it("fails closed on a definitive managed guard failure without probing OpenShell", () => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 0, - output: "", - stdout: "", - stderr: "", - })); + it("fails closed on a definitive managed guard failure without probing OpenShell", async () => { + const commandExecutor = sequencedExecutor(completed(0)); const beforeProbe = vi.fn(() => false); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(false); expect(beforeProbe).toHaveBeenCalledOnce(); - expect(captureOpenshellImpl).not.toHaveBeenCalled(); + expect(commandExecutor.runBuffered).not.toHaveBeenCalled(); expect(sleeps).toEqual([]); }); - it("fails when the managed guard stays inconclusive until the deadline", () => { - const captureOpenshellImpl = vi.fn(() => ({ - status: 0, - output: "", - stdout: "", - stderr: "", - })); + it("fails when the managed guard stays inconclusive until the deadline", async () => { + const commandExecutor = sequencedExecutor(completed(0)); const beforeProbe = vi.fn(() => null); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { + await waitForRecreatedSandboxOpenShellReady("recreated-box", { beforeProbe, - captureOpenshellImpl, + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: 6, }), ).toBe(false); expect(beforeProbe).toHaveBeenCalledTimes(3); - expect(captureOpenshellImpl).not.toHaveBeenCalled(); + expect(commandExecutor.runBuffered).not.toHaveBeenCalled(); expect(sleeps).toEqual([3, 3]); }); - it("lets the recovery wait override replace an explicit readiness budget", () => { + it("lets the recovery wait override replace an explicit readiness budget", async () => { vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", "1"); vi.stubEnv("NEMOCLAW_SANDBOX_READY_TIMEOUT", "6"); - const captureOpenshellImpl = vi.fn(() => ({ - status: 1, - output: OPENSHELL_SANDBOX_NOT_READY_STDERR.trim(), - stdout: "", - stderr: OPENSHELL_SANDBOX_NOT_READY_STDERR, - })); + const commandExecutor = sequencedExecutor(completed(1, OPENSHELL_SANDBOX_NOT_READY_STDERR)); const sleeps: number[] = []; expect( - waitForRecreatedSandboxOpenShellReady("recreated-box", { - captureOpenshellImpl, + await waitForRecreatedSandboxOpenShellReady("recreated-box", { + commandExecutor, intervalSeconds: 3, sleepImpl: (seconds) => sleeps.push(seconds), timeoutSeconds: Number(process.env.NEMOCLAW_SANDBOX_READY_TIMEOUT), }), ).toBe(false); - expect(captureOpenshellImpl).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(sleeps).toEqual([]); }); }); @@ -696,29 +621,33 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () // A probe whose answers play out in order; the last answer repeats. const makeProbe = (answers: Array) => { const remaining = [...answers]; - return () => (remaining.length > 1 ? remaining.shift() : remaining[0]) ?? null; + return async () => (remaining.length > 1 ? remaining.shift() : remaining[0]) ?? null; }; - it("confirms the gateway is still serving after the settle window", () => { + it("confirms the gateway is still serving after the settle window", async () => { const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { probeImpl: makeProbe([true, true]), - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); // Default settle window of 25s between the two probes. expect(sleeps).toEqual([25]); }); - it("uses authenticated managed probes inside and at the settle deadline", () => { + it("uses authenticated managed probes inside and at the settle deadline", async () => { const sleeps: number[] = []; - const managedProbe = vi.fn(() => true); - const ordinaryProbe = vi.fn(() => false); - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const managedProbe = vi.fn(async () => true); + const ordinaryProbe = vi.fn(async () => false); + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { initialManagedHealthPassed: true, probeImpl: ordinaryProbe, managedProbeImpl: managedProbe, - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); expect(managedProbe).toHaveBeenCalledTimes(2); @@ -726,45 +655,51 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () expect(sleeps).toEqual([22, 3]); }); - it("retries one transient managed result without extending the settle window", () => { + it("retries one transient managed result without extending the settle window", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "5"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "2"; const sleeps: number[] = []; const managedProbe = vi.fn(makeProbe([null, true])); - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { initialManagedHealthPassed: true, managedProbeImpl: managedProbe, - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); expect(managedProbe).toHaveBeenCalledTimes(2); expect(sleeps).toEqual([3, 2]); }); - it("keeps a recent authenticated result when only the deadline probe is transient", () => { + it("keeps a recent authenticated result when only the deadline probe is transient", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "5"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "2"; const sleeps: number[] = []; const managedProbe = vi.fn(makeProbe([true, null])); - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { initialManagedHealthPassed: true, managedProbeImpl: managedProbe, - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); expect(managedProbe).toHaveBeenCalledTimes(2); expect(sleeps).toEqual([3, 2]); }); - it("does not let ordinary outer-namespace health override a managed probe failure", () => { + it("does not let ordinary outer-namespace health override a managed probe failure", async () => { const sleeps: number[] = []; - const managedProbe = vi.fn(() => false); - const ordinaryProbe = vi.fn(() => true); - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const managedProbe = vi.fn(async () => false); + const ordinaryProbe = vi.fn(async () => true); + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { initialManagedHealthPassed: true, probeImpl: ordinaryProbe, managedProbeImpl: managedProbe, - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(false); expect(managedProbe).toHaveBeenCalledOnce(); @@ -772,12 +707,12 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () expect(sleeps).toEqual([22]); }); - it("accepts the initial managed proof without another probe when settling is disabled", () => { + it("accepts the initial managed proof without another probe when settling is disabled", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; - const managedProbe = vi.fn(() => false); - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const managedProbe = vi.fn(async () => false); + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { initialManagedHealthPassed: true, - probeImpl: () => false, + probeImpl: async () => false, managedProbeImpl: managedProbe, sleepImpl: () => {}, }); @@ -785,75 +720,87 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () expect(managedProbe).not.toHaveBeenCalled(); }); - it("uses the bounded recovery window for transient stopped probes", () => { + it("uses the bounded recovery window for transient stopped probes", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { probeImpl: makeProbe([true, false, false, true]), - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); expect(sleeps).toEqual([25, 3, 3]); }); - it("uses the bounded recovery window for inconclusive post-settle transport", () => { + it("uses the bounded recovery window for inconclusive post-settle transport", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { probeImpl: makeProbe([true, null, null, true]), - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); expect(sleeps).toEqual([25, 3, 3]); }); - it("fails closed when post-settle transport stays inconclusive for the bounded window", () => { + it("fails closed when post-settle transport stays inconclusive for the bounded window", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { probeImpl: makeProbe([true, null]), - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(false); expect(sleeps).toEqual([25, 3, 3]); }); - it("fails recovery when the gateway serves once and then drops its listener (wedge)", () => { + it("fails recovery when the gateway serves once and then drops its listener (wedge)", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { initialManagedHealthPassed: true, probeImpl: makeProbe([true]), - managedProbeImpl: () => false, - sleepImpl: (seconds: number) => sleeps.push(seconds), + managedProbeImpl: async () => false, + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(false); expect(sleeps).toEqual([22]); }); - it("skips the settle confirm when NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS=0", () => { + it("skips the settle confirm when NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS=0", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { // A second probe would report the wedge; with the settle disabled the // first success must win and no second probe may run. probeImpl: makeProbe([true, false]), - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); expect(sleeps).toEqual([]); }); - it("still polls through initial failures before reaching the settle confirm", () => { + it("still polls through initial failures before reaching the settle confirm", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "5"; const sleeps: number[] = []; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { probeImpl: makeProbe([false, false, true, true]), - sleepImpl: (seconds: number) => sleeps.push(seconds), + sleepImpl: async (seconds: number) => { + sleeps.push(seconds); + }, }); expect(ok).toBe(true); // Two poll intervals (default 3s) before the first success, then the @@ -861,22 +808,22 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () expect(sleeps).toEqual([3, 3, 5]); }); - it("returns false when the gateway never serves within the wait budget", () => { + it("returns false when the gateway never serves within the wait budget", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "0"; - const ok = waitForRecoveredSandboxGateway("my-sandbox", { + const ok = await waitForRecoveredSandboxGateway("my-sandbox", { probeImpl: makeProbe([false]), sleepImpl: () => {}, }); expect(ok).toBe(false); }); - it("uses the manifest health timeout threaded by the recovery caller", () => { + it("uses the manifest health timeout threaded by the recovery caller", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; let probes = 0; - const ok = waitForRecoveredSandboxGateway("hermes-box", { - probeImpl: () => { + const ok = await waitForRecoveredSandboxGateway("hermes-box", { + probeImpl: async () => { probes += 1; return false; }, @@ -888,14 +835,14 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () expect(probes).toBe(31); }); - it("lets the recovery wait environment override take precedence over the manifest timeout", () => { + it("lets the recovery wait environment override take precedence over the manifest timeout", async () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; let probes = 0; - const ok = waitForRecoveredSandboxGateway("hermes-box", { - probeImpl: () => { + const ok = await waitForRecoveredSandboxGateway("hermes-box", { + probeImpl: async () => { probes += 1; return false; }, diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 4ebef65802a..7ec254f0a81 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -4,12 +4,19 @@ import { randomBytes } from "node:crypto"; import { stripAnsi } from "../../adapters/openshell/client"; import { withSelectedOpenShellCommandOptions } from "../../adapters/openshell/command-argv"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandExecutor, +} from "../../adapters/openshell/sandbox-command"; +import { + namedOpenShellGateway, + selectedOpenShellGateway, +} from "../../adapters/openshell/sandbox-observer"; import { buildOpenShellRuntimeSelectionEnv, captureOpenshell, - captureOpenshellForStatus, captureSandboxSshConfig, - getOpenshellBinary, isCommandTimeout, type OpenShellRuntimeSelection, runOpenshell, @@ -25,7 +32,7 @@ import { } from "../../adapters/sandbox/command-transport"; import * as agentRuntime from "../../agent/runtime"; import { G, R } from "../../cli/terminal-style"; -import { sleepSeconds, waitUntil } from "../../core/wait"; +import { sleepSeconds, waitUntilAsync } from "../../core/wait"; import { ROOT, shellQuote } from "../../runner"; import { isDirectSandboxContainerNotFoundError, @@ -35,7 +42,7 @@ import { resolvePrivilegedSandboxTarget, withPrivilegedSandboxExecutionLease, } from "../../sandbox/privileged-exec"; -import { withMcpLifecycleLockSync } from "../../state/mcp-lifecycle-lock-acquisition"; +import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock-acquisition"; import * as registry from "../../state/registry"; import { buildSubprocessEnv } from "../../subprocess-env"; import { @@ -133,9 +140,12 @@ export type SandboxExecCommandExecutionOptions = SandboxExecCommandOptions & { type ProcessRecoveryProbeTiming = { measure(stage: "processes" | "forward", operation: () => T): T; + measureAsync(stage: "processes" | "forward", operation: () => Promise): Promise; setForwardAction(action: "skipped" | "verified" | "restored" | "failed"): void; }; +type Awaitable = T | Promise; + function commandTransportDependencies(): CommandTransportDependencies { return { buildSandboxExecMarkedCommand, @@ -143,10 +153,9 @@ function commandTransportDependencies(): CommandTransportDependencies { captureSandboxSshConfig, executePrivilegedSandboxCommand: executeProviderPrivilegedSandboxCommand, extractSandboxExecCommandStdout, - getOpenshellBinary, + commandExecutor: createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }), isDirectSandboxFallbackUnavailableError, openshellProbeTimeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, - root: ROOT, }; } @@ -237,12 +246,12 @@ export function executePrivilegedSandboxCommand( ); } -export function executeSandboxExecCommand( +export async function executeSandboxExecCommand( sandboxName: string, command: string, timeout = DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, options: SandboxExecCommandExecutionOptions = {}, -): SandboxCommandResult | null { +): Promise { const { runtimeSelection, ...transportOptions } = options; const runtimeEnv = runtimeSelection ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), runtimeSelection) @@ -256,7 +265,7 @@ export function executeSandboxExecCommand( ...transportOptions, ...(runtimeSelection ? { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", gatewayName: runtimeSelection.gatewayName, } : {}), @@ -361,30 +370,24 @@ async function executeSandboxExecCommandForStatus( sandboxName: string, command: string, gatewayName?: string, - capture: typeof captureOpenshellForStatus = captureOpenshellForStatus, + commandExecutor: OpenShellSandboxBufferedCommandExecutor = createCliOpenShellSandboxCommandExecutor( + { hostCwd: ROOT }, + ), ): Promise { const markedCommand = buildSandboxExecMarkedCommand(command); - const result = await capture( - [ - "sandbox", - "exec", - "--name", - sandboxName, - ...(gatewayName ? ["-g", gatewayName] : []), - "--", - "sh", - "-c", - markedCommand, - ], - { ignoreError: true }, - ); - if (isCommandTimeout(result) || result.error) return null; - const commandStdout = extractSandboxExecCommandStdout(result.output || ""); + const result = await commandExecutor.runBuffered({ + sandboxName, + target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), + command: ["sh", "-c", markedCommand], + timeoutMilliseconds: DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, + }); + if (result.outcome.kind !== "completed") return null; + const commandStdout = extractSandboxExecCommandStdout(result.stdout); if (commandStdout === null) return null; return { - status: result.status ?? 1, + status: result.outcome.exitCode, stdout: commandStdout, - stderr: "", + stderr: result.stderr.trim(), }; } @@ -406,20 +409,20 @@ function parseSandboxGatewayProbe(result: SandboxCommandResult | null): boolean * Fixes #2342 — previously `curl -sf` failed on 401, causing false * "Health Offline" readings. */ -function isSandboxGatewayRunning( +async function isSandboxGatewayRunning( sandboxName: string, runtimeSelection?: OpenShellRuntimeSelection, -): boolean | null { +): Promise { const agent = agentRuntime.getSessionAgent(sandboxName); if (agent && !agentRuntime.hasGatewayRuntime(agent)) return null; const probeUrl = getSandboxHealthProbeUrl(sandboxName); const command = `HTTP_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 ${shellQuote(probeUrl)} 2>/dev/null || echo 000); case "$HTTP_CODE" in 200|401) echo RUNNING ;; *) echo STOPPED ;; esac`; const execProbe = parseSandboxGatewayProbe( - executeSandboxExecCommand( + await executeSandboxExecCommand( sandboxName, command, DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, - runtimeSelection ? { runtimeSelection } : {}, + runtimeSelection ? { runtimeSelection } : { localDockerFallbackPolicy: "read-only" }, ), ); if (execProbe !== null) return execProbe; @@ -648,7 +651,7 @@ function waitForFinalRelaunchManagedSupervisor( } function finalRelaunchContainerFailureDetail( - completion: ReturnType, + completion: Awaited>, ): string | null { if (completion.lifecycleStopAcknowledged === false) { return "OpenShell did not acknowledge the authoritative stop before the final replacement handoff. NemoClaw did not start the primary dashboard/API host forward"; @@ -689,7 +692,7 @@ function finalRelaunchRecoveryFailure( return recoveryFailureDetail ? { ...failure, recoveryFailureDetail } : failure; } -function finalizeRelaunchedRecovery( +async function finalizeRelaunchedRecovery( sandboxName: string, relaunch: ManagedSupervisorRelaunch, { @@ -701,12 +704,12 @@ function finalizeRelaunchedRecovery( printRecoveryHints: () => void; quiet: boolean; requestManagedProbe: typeof executeGatewaySupervisorAction; - waitForRecoveryReadiness: () => string | null; + waitForRecoveryReadiness: () => Promise; }, -): FinalRelaunchRecoveryFailure | null { - let completion: ReturnType; +): Promise { + let completion: Awaited>; try { - completion = relaunch.finalize(true); + completion = await relaunch.finalize(true); if (completion.stateRestored === false || completion.rolledBack) { const recoveryFailureDetail = completion.rolledBack ? "Sandbox recovery did not complete; the previous container was restored" @@ -749,7 +752,7 @@ function finalizeRelaunchedRecovery( `the managed supervisor health check for the pinned replacement container did not pass after the final replacement container restart. NemoClaw did not start the primary dashboard/API host forward. Managed supervisor health check result: ${managedSupervisor.failure.layer}: ${managedSupervisor.failure.detail}`, ); } - const finalReadinessFailureDetail = waitForRecoveryReadiness(); + const finalReadinessFailureDetail = await waitForRecoveryReadiness(); if (finalReadinessFailureDetail) { return finalRelaunchRecoveryFailure(finalReadinessFailureDetail); } @@ -768,12 +771,12 @@ function finalizeRelaunchedRecovery( return null; } -function recoveryDetailAfterRelaunchRollback( +async function recoveryDetailAfterRelaunchRollback( relaunch: ManagedSupervisorRelaunch, recoveryFailureDetail: string, -): string { +): Promise { try { - if (relaunch.finalize(false).rolledBack) return recoveryFailureDetail; + if ((await relaunch.finalize(false)).rolledBack) return recoveryFailureDetail; } catch { // Report only the fixed rollback classification below. Finalizer errors can // contain Docker paths, container IDs, or other untrusted runtime detail. @@ -820,7 +823,7 @@ export async function isSandboxGatewayRunningForStatus( gatewayName?: string, options: { getSessionAgent?: typeof agentRuntime.getSessionAgent; - capture?: typeof captureOpenshellForStatus; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; getHealthProbeUrl?: typeof getSandboxHealthProbeUrl; } = {}, ): Promise { @@ -829,7 +832,12 @@ export async function isSandboxGatewayRunningForStatus( const probeUrl = (options.getHealthProbeUrl ?? getSandboxHealthProbeUrl)(sandboxName); const command = `HTTP_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 ${shellQuote(probeUrl)} 2>/dev/null || echo 000); case "$HTTP_CODE" in 200|401) echo RUNNING ;; *) echo STOPPED ;; esac`; return parseSandboxGatewayProbe( - await executeSandboxExecCommandForStatus(sandboxName, command, gatewayName, options.capture), + await executeSandboxExecCommandForStatus( + sandboxName, + command, + gatewayName, + options.commandExecutor, + ), ); } @@ -1005,36 +1013,34 @@ function recoverSandboxProcesses( ).output, confirmMissingSupervisor: (containerId) => isExactlyManagedControlMarker( - effectivePinnedGatewaySupervisorAction( - sandboxName, - "probe", - 210000, - containerId, - ), + effectivePinnedGatewaySupervisorAction(sandboxName, "probe", 210000, containerId), "SUPERVISOR_NOT_RUNNING", ), restartRestoredManagedGateway: (containerId) => { const restarted = parseManagedGatewayControlCompletion( - effectivePinnedGatewaySupervisorAction( - sandboxName, - "restart", - 210000, - containerId, - ), + effectivePinnedGatewaySupervisorAction(sandboxName, "restart", 210000, containerId), ); if (restarted?.disposition !== "ok") return false; - return waitForRecoveredSandboxGateway(sandboxName, { - quiet, - initialManagedHealthPassed: true, - requireManagedProbe: true, - timeoutSeconds: gatewayRecoveryTimeoutSeconds(agent), - runtimeSelection, - managedProbeImpl: (name) => + const settleSeconds = readNonNegativeNumberEnv( + "NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS", + 25, + ); + if (settleSeconds <= 0) return true; + const intervalSeconds = readNonNegativeNumberEnv( + "NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", + 3, + ); + return confirmManagedGatewayWithinSettleWindow( + sandboxName, + (name) => confirmRecoveredSandboxGatewayManaged(name, { requestGatewaySupervisorActionImpl: (name, action) => effectivePinnedGatewaySupervisorAction(name, action, 210000, containerId), }), - }); + sleepSeconds, + settleSeconds, + intervalSeconds, + ); }, }, }); @@ -1085,15 +1091,15 @@ function recoverSandboxProcesses( return null; } -export function restartSandboxGateway( +export async function restartSandboxGateway( sandboxName: string, { quiet = false, deps = {}, runtimeSelection }: RestartSandboxGatewayOptions = {}, -): GatewayRestartResult { - return withUnsupportedHermesPortableGatewayRestartFence(sandboxName, () => { +): Promise { + return withUnsupportedHermesPortableGatewayRestartFence(sandboxName, async () => { const defaultSupervisorAction = runtimeSelection ? refuseHostLocalSupervisorForSelectedRuntime : executeGatewaySupervisorAction; - return withMcpLifecycleLockSync(sandboxName, () => + return withMcpLifecycleLock(sandboxName, () => restartSandboxGatewayWithDeps(sandboxName, { quiet, deps: { @@ -1106,7 +1112,7 @@ export function restartSandboxGateway( name, command, timeout, - runtimeSelection ? { runtimeSelection } : {}, + runtimeSelection ? { runtimeSelection } : { localDockerFallbackPolicy: "read-only" }, ), waitForRecoveredSandboxGateway: (name, options) => waitForRecoveredSandboxGateway(name, { @@ -1120,8 +1126,7 @@ export function restartSandboxGateway( deps.requestGatewaySupervisorAction ?? defaultSupervisorAction, }), }), - ensureSandboxPortForward: (name) => - ensureSandboxPortForward(name, { runtimeSelection }), + ensureSandboxPortForward: (name) => ensureSandboxPortForward(name, { runtimeSelection }), ensureHermesDashboardPortForwardIfEnabled: (name) => ensureHermesDashboardPortForwardIfEnabled(name, runtimeSelection), recoverMessagingHostForward: (name, options) => @@ -1163,16 +1168,22 @@ function normalizeOpenshellStructuredError(value: string): string { .trim(); } -function hasRetryableOpenshellFailureShape(result: ReturnType): boolean { - return result.status === 1 && !result.error && String(result.stderr ?? "").trim() !== ""; +function hasRetryableOpenshellFailureShape( + result: OpenShellSandboxBufferedCommandCompletion, +): boolean { + return ( + result.outcome.kind === "completed" && + result.outcome.exitCode === 1 && + result.stderr.trim() !== "" + ); } function isRetryableOpenshellReRegistrationState( - result: ReturnType, + result: OpenShellSandboxBufferedCommandCompletion, sandboxName: string, ): boolean { if (!hasRetryableOpenshellFailureShape(result)) return false; - const error = normalizeOpenshellStructuredError(String(result.stderr)); + const error = normalizeOpenshellStructuredError(result.stderr); // OpenShell can publish Ready before replacement registration settles. // Retry only if the readiness probe reports phase Error for this sandbox. // The CLI can emit informational stdout before this exact stderr refusal; @@ -1185,7 +1196,7 @@ function isRetryableOpenshellReRegistrationState( } // All less-specific transient signatures remain constrained to an otherwise // empty stdout stream so unrelated command output cannot be reclassified. - if (String(result.stdout ?? "").trim() !== "") return false; + if (result.stdout.trim() !== "") return false; if (error === OPENSHELL_SANDBOX_NOT_READY) return true; // OpenShell 0.0.85 can keep the recreated sandbox's cached phase at Ready @@ -1239,7 +1250,7 @@ type RecreatedSandboxOpenShellReadinessResult = }; type RecreatedSandboxOpenShellReadyOptions = { - captureOpenshellImpl?: typeof captureOpenshell; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; beforeProbe?: (timeoutMs: number) => boolean | null; intervalSeconds?: number; nowImpl?: () => number; @@ -1288,11 +1299,12 @@ const GATEWAY_RECOVERY_WAIT_DEFAULT_SECONDS = 120; * proving the control-plane readiness that gates state restoration and the * replacement-container commit. */ -function waitForRecreatedSandboxOpenShellReadyResult( +async function waitForRecreatedSandboxOpenShellReadyResult( sandboxName: string, options: RecreatedSandboxOpenShellReadyOptions = {}, -): RecreatedSandboxOpenShellReadinessResult { - const capture = options.captureOpenshellImpl ?? captureOpenshell; +): Promise { + const commandExecutor = + options.commandExecutor ?? createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); const now = options.nowImpl ?? Date.now; const sleep = options.sleepImpl ?? sleepSeconds; const requestedTimeoutSeconds = @@ -1346,20 +1358,21 @@ function waitForRecreatedSandboxOpenShellReadyResult( ready: false, }; } - const result = capture( - ["sandbox", "exec", "--name", sandboxName, "--", "true"], - withSelectedOpenShellCommandOptions( - { - ignoreError: true, - includeStderr: true, - includeStreams: true, - timeout: Math.max(1, Math.min(OPENSHELL_PROBE_TIMEOUT_MS, remainingMs)), - }, - options.runtimeSelection, - ), - ); - if (result.status === 0 && !result.error) return { ready: true }; - const openshellError = normalizeOpenshellStructuredError(String(result.stderr ?? "")); + const result = await commandExecutor.runBuffered({ + sandboxName, + target: options.runtimeSelection + ? namedOpenShellGateway(options.runtimeSelection.gatewayName) + : selectedOpenShellGateway(), + command: ["true"], + environment: options.runtimeSelection + ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), options.runtimeSelection) + : buildSubprocessEnv(), + timeoutMilliseconds: Math.max(1, Math.min(OPENSHELL_PROBE_TIMEOUT_MS, remainingMs)), + }); + if (result.outcome.kind === "completed" && result.outcome.exitCode === 0) { + return { ready: true }; + } + const openshellError = normalizeOpenshellStructuredError(result.stderr); if (openshellError) lastOpenshellError = openshellError; // This probe executes only `true`, so an OpenShell process timeout has no // mutation outcome to reconcile. Treat that exact timeout as inconclusive @@ -1372,10 +1385,10 @@ function waitForRecreatedSandboxOpenShellReadyResult( if (retryableReRegistrationState) observedRetryableReRegistrationState = true; const emptyReadOnlyProbeAfterReRegistration = observedRetryableReRegistrationState && - result.status === 1 && - !result.error && - String(result.stdout ?? "").trim() === "" && - String(result.stderr ?? "").trim() === ""; + result.outcome.kind === "completed" && + result.outcome.exitCode === 1 && + result.stdout.trim() === "" && + result.stderr.trim() === ""; // OpenShell can briefly return an empty exit-1 result after first exposing // the exact replacement re-registration state. Keep that result // inconclusive only inside the same bounded wait and behind the pinned @@ -1384,7 +1397,7 @@ function waitForRecreatedSandboxOpenShellReadyResult( if ( !retryableReRegistrationState && !emptyReadOnlyProbeAfterReRegistration && - !isCommandTimeout(result) + !(result.outcome.kind === "failed" && result.outcome.error.kind === "timeout") ) { return { failure: "openshell-readiness-failure", @@ -1416,11 +1429,11 @@ function waitForRecreatedSandboxOpenShellReadyResult( }; } -export function waitForRecreatedSandboxOpenShellReady( +export async function waitForRecreatedSandboxOpenShellReady( sandboxName: string, options: RecreatedSandboxOpenShellReadyOptions = {}, -): boolean { - return waitForRecreatedSandboxOpenShellReadyResult(sandboxName, options).ready; +): Promise { + return (await waitForRecreatedSandboxOpenShellReadyResult(sandboxName, options)).ready; } function gatewayRecoveryTimeoutSeconds( @@ -1511,19 +1524,39 @@ function confirmManagedGatewayWithinSettleWindow( return beforeDeadlineResult === true; } -export function waitForRecoveredSandboxGateway( +async function confirmManagedGatewayWithinSettleWindowAsync( + sandboxName: string, + managedProbe: (sandboxName: string) => Awaitable, + sleep: (seconds: number) => Awaitable, + settleSeconds: number, + intervalSeconds: number, +): Promise { + const retryLeadSeconds = + intervalSeconds > 0 ? Math.min(intervalSeconds, settleSeconds) : settleSeconds; + const beforeDeadlineSeconds = settleSeconds - retryLeadSeconds; + if (beforeDeadlineSeconds > 0) await sleep(beforeDeadlineSeconds); + + const beforeDeadlineResult = await managedProbe(sandboxName); + if (beforeDeadlineResult === false) return false; + if (retryLeadSeconds > 0) await sleep(retryLeadSeconds); + const atDeadlineResult = await managedProbe(sandboxName); + if (atDeadlineResult !== null) return atDeadlineResult; + return beforeDeadlineResult === true; +} + +export async function waitForRecoveredSandboxGateway( sandboxName: string, options: { - managedProbeImpl?: (sandboxName: string) => boolean | null; + managedProbeImpl?: (sandboxName: string) => Awaitable; initialManagedHealthPassed?: boolean; - probeImpl?: (sandboxName: string) => boolean | null; - sleepImpl?: (seconds: number) => void; + probeImpl?: (sandboxName: string) => Promise; + sleepImpl?: (seconds: number) => Awaitable; quiet?: boolean; timeoutSeconds?: number; requireManagedProbe?: boolean; runtimeSelection?: OpenShellRuntimeSelection; } = {}, -): boolean { +): Promise { const probe = options.probeImpl ?? ((name: string) => isSandboxGatewayRunning(name, options.runtimeSelection)); @@ -1549,11 +1582,11 @@ export function waitForRecoveredSandboxGateway( ? Math.max(1, Math.floor(timeoutSeconds / intervalSeconds) + 1) : Math.max(1, Math.floor(timeoutSeconds) + 1); - const probeDuringRecoveryWait = () => { - const managedResult = managedProbe?.(sandboxName) ?? null; + const probeDuringRecoveryWait = async () => { + const managedResult = managedProbe ? await managedProbe(sandboxName) : null; if (managedResult !== null) return managedResult; if (options.requireManagedProbe) return false; - return probe(sandboxName); + return await probe(sandboxName); }; // A successful managed restart/recover marker is already emitted only after @@ -1564,13 +1597,13 @@ export function waitForRecoveredSandboxGateway( const initialManagedHealthPassed = options.initialManagedHealthPassed === true; const recovered = initialManagedHealthPassed || - waitUntil(() => probeDuringRecoveryWait() === true, { + (await waitUntilAsync(async () => (await probeDuringRecoveryWait()) === true, { initialIntervalMs: intervalSeconds * 1000, maxIntervalMs: intervalSeconds * 1000, backoffFactor: 1, maxAttempts: attempts, - sleep: (ms) => sleep(ms / 1000), - }); + sleep: async (ms) => await sleep(ms / 1000), + })); if (!recovered) return false; // #4710: a freshly relaunched gateway can serve for ~20s and then drop @@ -1597,7 +1630,7 @@ export function waitForRecoveredSandboxGateway( // attempt is transient; a definitive failure is authoritative, and an // outer-namespace HTTP response must never override either result. if (!managedProbe) return false; - return confirmManagedGatewayWithinSettleWindow( + return confirmManagedGatewayWithinSettleWindowAsync( sandboxName, managedProbe, sleep, @@ -1605,18 +1638,18 @@ export function waitForRecoveredSandboxGateway( intervalSeconds, ); } - sleep(settleSeconds); + await sleep(settleSeconds); // A stopped HTTP probe is still only a point-in-time observation. PID 1 can // have respawned the gateway while OpenClaw is still finishing its startup // transition, so multiple stopped results may precede a healthy listener. // Give stopped and inconclusive probes the same bounded recovery window. // A persistent #4710 wedge still fails closed when that window expires. - return waitUntil(() => probeDuringRecoveryWait() === true, { + return waitUntilAsync(async () => (await probeDuringRecoveryWait()) === true, { initialIntervalMs: intervalSeconds * 1000, maxIntervalMs: intervalSeconds * 1000, backoffFactor: 1, maxAttempts: attempts, - sleep: (ms) => sleep(ms / 1000), + sleep: async (ms) => await sleep(ms / 1000), }); } @@ -1638,7 +1671,7 @@ function isHermesAgent( * log". Failures before forward recovery use `recoveryFailureDetail`; actual * forward failures retain `forwardRecoveryFailed` and their forward detail. */ -function checkAndRecoverSandboxProcessesWithoutHostLock( +async function checkAndRecoverSandboxProcessesWithoutHostLock( sandboxName: string, { quiet = false, @@ -1647,6 +1680,7 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( relaunchManagedSupervisorSessionImpl = relaunchManagedSupervisorSession, isSandboxGatewayRunningImpl = isSandboxGatewayRunning, waitForRecreatedSandboxOpenShellReadyImpl = waitForRecreatedSandboxOpenShellReady, + commandExecutor, managedControlNowImpl, managedControlTimeoutMs, isWsl: isWslOverride, @@ -1658,8 +1692,12 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( requestGatewaySupervisorAction?: typeof executeGatewaySupervisorAction; requestPinnedGatewaySupervisorAction?: RequestPinnedGatewaySupervisorAction; relaunchManagedSupervisorSessionImpl?: typeof relaunchManagedSupervisorSession; - isSandboxGatewayRunningImpl?: typeof isSandboxGatewayRunning; + isSandboxGatewayRunningImpl?: ( + sandboxName: string, + runtimeSelection?: OpenShellRuntimeSelection, + ) => Promise; waitForRecreatedSandboxOpenShellReadyImpl?: typeof waitForRecreatedSandboxOpenShellReady; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; managedControlNowImpl?: () => number; managedControlTimeoutMs?: number; isWsl?: boolean; @@ -1670,6 +1708,10 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( ) { const measure = (stage: "processes" | "forward", operation: () => T): T => probeTiming ? probeTiming.measure(stage, operation) : operation(); + const measureAsync = ( + stage: "processes" | "forward", + operation: () => Promise, + ): Promise => (probeTiming ? probeTiming.measureAsync(stage, operation) : operation()); const effectiveGatewaySupervisorAction = runtimeSelection && requestGatewaySupervisorAction === executeGatewaySupervisorAction ? refuseHostLocalSupervisorForSelectedRuntime @@ -1690,7 +1732,7 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( runtime: "terminal" as const, }; } - const running = measure("processes", () => + const running = await measureAsync("processes", () => isSandboxGatewayRunningImpl(sandboxName, runtimeSelection), ); if (running === null) { @@ -1904,7 +1946,7 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( // recovered process can be alive before the OpenAI-compatible API is ready. let gatewayReady = false; try { - gatewayReady = measure("processes", () => + gatewayReady = await measureAsync("processes", () => waitForRecoveredSandboxGateway(sandboxName, { quiet, initialManagedHealthPassed: recovery.kind === "managed", @@ -1932,7 +1974,7 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( ); } catch (error) { try { - relaunch?.finalize(false); + await relaunch?.finalize(false); } catch { // Preserve the original recovery error; the failure path below will // direct the operator to inspect/rebuild the sandbox. @@ -1944,17 +1986,17 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( ? `the managed supervisor health check for the recreated sandbox did not pass while NemoClaw waited for its gateway. Managed supervisor health check result: ${relaunchedManagedHealth.failure.layer}: ${relaunchedManagedHealth.failure.detail}` : "the recovered gateway did not become responsive before the recovery timeout"; const recoveryFailureDetail = relaunch - ? recoveryDetailAfterRelaunchRollback(relaunch, gatewayWaitFailureDetail) + ? await recoveryDetailAfterRelaunchRollback(relaunch, gatewayWaitFailureDetail) : gatewayWaitFailureDetail; const rollbackUnconfirmed = recoveryFailureDetail !== gatewayWaitFailureDetail; if (!quiet) { console.error(" Gateway process started but is not responding."); - printGatewayWedgeDiagnostics(sandboxName, (name, command) => + await printGatewayWedgeDiagnostics(sandboxName, (name, command) => executeSandboxExecCommand( name, command, DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, - runtimeSelection ? { runtimeSelection } : {}, + runtimeSelection ? { runtimeSelection } : { localDockerFallbackPolicy: "read-only" }, ), ); console.error(" Check /tmp/gateway.log inside the sandbox for details."); @@ -1986,8 +2028,9 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( // a replacement also rechecks its pinned identity before readiness. const recoveryRequiresReadiness = recovery.kind === "managed" || recovery.kind === "provider" || relaunch; - const waitForRecoveryReadiness = () => { + const waitForRecoveryReadiness = async () => { const readinessOptions: RecreatedSandboxOpenShellReadyOptions = { + commandExecutor, beforeProbe: relaunch ? (timeoutMs) => confirmRelaunchedManagedHealth?.(timeoutMs) ?? null : undefined, @@ -1995,8 +2038,8 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( }; const readiness = waitForRecreatedSandboxOpenShellReadyImpl === waitForRecreatedSandboxOpenShellReady - ? waitForRecreatedSandboxOpenShellReadyResult(sandboxName, readinessOptions) - : waitForRecreatedSandboxOpenShellReadyImpl(sandboxName, readinessOptions) + ? await waitForRecreatedSandboxOpenShellReadyResult(sandboxName, readinessOptions) + : (await waitForRecreatedSandboxOpenShellReadyImpl(sandboxName, readinessOptions)) ? ({ ready: true } as const) : ({ failure: "openshell-readiness-failure", ready: false } as const); return readiness.ready @@ -2012,11 +2055,11 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( ); }; const readinessFailureDetail = recoveryRequiresReadiness - ? measure("processes", waitForRecoveryReadiness) + ? await measureAsync("processes", waitForRecoveryReadiness) : null; if (readinessFailureDetail) { const recoveryFailureDetail = relaunch - ? recoveryDetailAfterRelaunchRollback(relaunch, readinessFailureDetail) + ? await recoveryDetailAfterRelaunchRollback(relaunch, readinessFailureDetail) : readinessFailureDetail; return { checked: true, @@ -2027,7 +2070,7 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( }; } if (relaunch) { - const finalizationFailure = measure("processes", () => + const finalizationFailure = await measureAsync("processes", () => finalizeRelaunchedRecovery(sandboxName, relaunch, { printRecoveryHints: () => printHostManagedGatewayRecoveryHints( @@ -2128,15 +2171,19 @@ function checkAndRecoverSandboxProcessesWithoutHostLock( return { checked: true, wasRunning: false, recovered: false, forwardRecovered: false }; } -export function checkAndRecoverSandboxProcesses( +export async function checkAndRecoverSandboxProcesses( sandboxName: string, options: { quiet?: boolean; requestGatewaySupervisorAction?: typeof executeGatewaySupervisorAction; requestPinnedGatewaySupervisorAction?: RequestPinnedGatewaySupervisorAction; relaunchManagedSupervisorSessionImpl?: typeof relaunchManagedSupervisorSession; - isSandboxGatewayRunningImpl?: typeof isSandboxGatewayRunning; + isSandboxGatewayRunningImpl?: ( + sandboxName: string, + runtimeSelection?: OpenShellRuntimeSelection, + ) => Promise; waitForRecreatedSandboxOpenShellReadyImpl?: typeof waitForRecreatedSandboxOpenShellReady; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; managedControlNowImpl?: () => number; managedControlTimeoutMs?: number; isWsl?: boolean; @@ -2145,7 +2192,7 @@ export function checkAndRecoverSandboxProcesses( runtimeSelection?: OpenShellRuntimeSelection; } = {}, ) { - return withMcpLifecycleLockSync(sandboxName, () => + return withMcpLifecycleLock(sandboxName, () => checkAndRecoverSandboxProcessesWithoutHostLock(sandboxName, options), ); } diff --git a/src/lib/actions/sandbox/rebuild-dcode-preflight.ts b/src/lib/actions/sandbox/rebuild-dcode-preflight.ts index 62234214c9b..54085e030c5 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-preflight.ts @@ -196,13 +196,13 @@ function resolveTarget( } } -function requireInferenceRoute( +async function requireInferenceRoute( sandboxName: string, target: ResolvedDcodeRebuildTarget, bail: DcodeRebuildPreflightBail, runtimeSelection?: OpenShellRuntimeSelection, -): void { - const result = probeSandboxInferenceInvocation({ +): Promise { + const result = await probeSandboxInferenceInvocation({ sandboxName, agentName: target.agent, ...target, @@ -515,7 +515,7 @@ export async function prepareDcodeReplacementBeforeMutation( const session = loadMatchingDcodeSession(sandboxName); const target = resolveTarget(entry, resumeConfig, bail, gatewayPort); - if (!skipLiveRoute) requireInferenceRoute(sandboxName, target, bail, runtimeSelection); + if (!skipLiveRoute) await requireInferenceRoute(sandboxName, target, bail, runtimeSelection); pinnedBase = resolvePinnedDcodeBaseImage(bail, input.baseImageOptions); const sandboxGpuConfig = getRecordedGpuConfig(sandboxName, entry, session); @@ -552,7 +552,7 @@ export async function prepareDcodeReplacementBeforeMutation( return null; } if (!input.checkGatewaySchema(runtimeSelection)) return null; - if (!skipLiveRoute) requireInferenceRoute(sandboxName, target, bail, runtimeSelection); + if (!skipLiveRoute) await requireInferenceRoute(sandboxName, target, bail, runtimeSelection); requireCurrentTarget(sandboxName, entry, target, resumeConfig, bail, gatewayPort); if (!verifyPreparedDcodeRebuildImage(buildContext) || !pinnedBase.verify()) { fail("the prepared DCode replacement inputs changed during preflight", bail); @@ -612,7 +612,7 @@ export async function revalidateDcodeReplacementAtMutationEdge( return false; } if (!input.checkGatewaySchema(runtimeSelection)) return false; - if (!skipLiveRoute) requireInferenceRoute(sandboxName, target, bail, runtimeSelection); + if (!skipLiveRoute) await requireInferenceRoute(sandboxName, target, bail, runtimeSelection); requireCurrentTarget(sandboxName, entry, target, resumeConfig, bail, gatewayPort); if (!replacement.verify()) { fail("the prepared DCode replacement inputs changed before deletion", bail); @@ -651,7 +651,7 @@ export async function revalidateManagedDcodeWorkloadAtMutationEdge( return false; } if (!input.checkGatewaySchema(runtimeSelection)) return false; - if (!skipLiveRoute) requireInferenceRoute(sandboxName, target, bail, runtimeSelection); + if (!skipLiveRoute) await requireInferenceRoute(sandboxName, target, bail, runtimeSelection); requireCurrentTarget(sandboxName, entry, target, resumeConfig, bail, gatewayPort); return true; } diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts index ad063c62588..195694b87c8 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts @@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({ reattachMcpAfterDeleteFailure: vi.fn(), removeSandboxRegistryEntryWithReceipt: vi.fn(() => null), waitUntil: vi.fn(), + waitUntilAsync: vi.fn(), warnUnpreservedUserManagedFiles: vi.fn(), runOpenshell: vi.fn( ( @@ -48,6 +49,7 @@ vi.mock("../../adapters/openshell/runtime", () => ({ vi.mock("../../core/wait", () => ({ waitUntil: mocks.waitUntil, + waitUntilAsync: mocks.waitUntilAsync, })); vi.mock("../../inference/nim", () => ({ @@ -483,12 +485,7 @@ describe("rebuild destroy phase", () => { expect(revalidateBeforeDelete).toHaveBeenCalledOnce(); expect(mocks.runOpenshell).not.toHaveBeenCalled(); expect(mocks.removeSandboxRegistryEntryWithReceipt).not.toHaveBeenCalled(); - expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith( - "alpha", - [], - [], - undefined, - ); + expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith("alpha", [], [], undefined); expect(mocks.stopNimContainer).not.toHaveBeenCalled(); expect(mocks.stopNimContainerByName).not.toHaveBeenCalled(); }); @@ -528,12 +525,7 @@ describe("rebuild destroy phase", () => { expect(revalidateBeforeDelete.mock.invocationCallOrder[0]).toBeLessThan( mocks.runOpenshell.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY, ); - expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith( - "alpha", - [], - [], - undefined, - ); + expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith("alpha", [], [], undefined); expect(mocks.teardownSandboxDashboardForward).not.toHaveBeenCalled(); expect(mocks.restoreSandboxLaunchForwards).not.toHaveBeenCalled(); expect(mocks.removeSandboxRegistryEntryWithReceipt).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts index 90a7f04da2a..45a2a925ce0 100644 --- a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts @@ -16,12 +16,9 @@ import { tempFiles, } from "../../../../test/helpers/rebuild-flow-generic-harness"; import { makePreparedRecoveryManifest } from "./rebuild-flow-test-fixtures"; -import { - enforceRemovedImmutabilityMigrationBoundary, -} from "../../state/migrations/removed-immutability"; +import { enforceRemovedImmutabilityMigrationBoundary } from "../../state/migrations/removed-immutability"; -const enforceRemovedImmutabilityMigrationBoundaryReal = - enforceRemovedImmutabilityMigrationBoundary; +const enforceRemovedImmutabilityMigrationBoundaryReal = enforceRemovedImmutabilityMigrationBoundary; describe("rebuildSandbox flow: lifecycle", () => { installRebuildFlowTestHooks(); @@ -57,9 +54,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); - expect( - harness.removeSandboxRegistryEntryWithReceiptSpy, - ).not.toHaveBeenCalled(); + expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); }); @@ -81,9 +76,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); - expect( - harness.removeSandboxRegistryEntryWithReceiptSpy, - ).not.toHaveBeenCalled(); + expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); expect(harness.retireRemovedImmutabilityStateRecordSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); }); @@ -109,13 +102,9 @@ describe("rebuildSandbox flow: lifecycle", () => { ).rejects.toThrow("Failed to back up sandbox state"); expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); - expect( - harness.retireRemovedImmutabilityStateRecordSpy, - ).not.toHaveBeenCalled(); + expect(harness.retireRemovedImmutabilityStateRecordSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); - expect( - harness.removeSandboxRegistryEntryWithReceiptSpy, - ).not.toHaveBeenCalled(); + expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); }); @@ -177,12 +166,8 @@ describe("rebuildSandbox flow: lifecycle", () => { "alpha", expect.objectContaining({ captureStateFile: expect.any(Function) }), ); - expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith( - "alpha", - ); - expect( - harness.prepareMcpBridgesForRebuildSpy.mock.invocationCallOrder[0], - ).toBeLessThan( + expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith("alpha"); + expect(harness.prepareMcpBridgesForRebuildSpy.mock.invocationCallOrder[0]).toBeLessThan( harness.warnUnpreservedUserManagedFilesSpy.mock.invocationCallOrder[0], ); expect(harness.runOpenshellSpy).toHaveBeenCalledWith( @@ -221,9 +206,7 @@ describe("rebuildSandbox flow: lifecycle", () => { }), ); const deleteCall = harness.runOpenshellSpy.mock.calls.findIndex( - (call) => - Array.isArray(call[0]) && - call[0].join(" ") === "sandbox delete -g nemoclaw alpha", + (call) => Array.isArray(call[0]) && call[0].join(" ") === "sandbox delete -g nemoclaw alpha", ); expect(harness.registryUpdateSpy.mock.invocationCallOrder[0]).toBeLessThan( harness.runOpenshellSpy.mock.invocationCallOrder[deleteCall], @@ -231,23 +214,12 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(harness.session.steps.gateway.status).toBe("complete"); expect(harness.session.steps.preflight.status).toBe("complete"); expect(harness.session.steps.sandbox.status).toBe("pending"); - expect(harness.restoreSandboxStateSpy).toHaveBeenCalledWith( - "alpha", - harness.backupPath, - { - targetAgentType: "openclaw", - }, - ); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( - "alpha", - [mcpEntry], - ); - expect( - harness.removeSandboxRegistryEntryWithReceiptSpy, - ).not.toHaveBeenCalled(); - expect( - harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n"), - ).toContain( + expect(harness.restoreSandboxStateSpy).toHaveBeenCalledWith("alpha", harness.backupPath, { + targetAgentType: "openclaw", + }); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); + expect(harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n")).toContain( "Preserving journaled source registry entry across sandbox recreation", ); expect(harness.applyPresetSpy).not.toHaveBeenCalled(); @@ -261,26 +233,22 @@ describe("rebuildSandbox flow: lifecycle", () => { "alpha", "openclaw doctor --fix", 300_000, - { allowLocalDockerFallback: false }, + { localDockerFallbackPolicy: "never" }, ); - expect( - harness.retireRemovedImmutabilityStateRecordSpy, - ).toHaveBeenCalledWith("alpha", "mutable-rebuild"); - expect( - harness.enforceRemovedImmutabilityMigrationBoundarySpy, - ).toHaveBeenCalledWith("alpha", { + expect(harness.retireRemovedImmutabilityStateRecordSpy).toHaveBeenCalledWith( + "alpha", + "mutable-rebuild", + ); + expect(harness.enforceRemovedImmutabilityMigrationBoundarySpy).toHaveBeenCalledWith("alpha", { allowStateRecord: true, }); expect( - harness.retireRemovedImmutabilityStateRecordSpy.mock - .invocationCallOrder[0], - ).toBeGreaterThan( - harness.restoreSandboxStateSpy.mock.invocationCallOrder[0], - ); + harness.retireRemovedImmutabilityStateRecordSpy.mock.invocationCallOrder[0], + ).toBeGreaterThan(harness.restoreSandboxStateSpy.mock.invocationCallOrder[0]); expect(process.env.NEMOCLAW_SANDBOX_NAME).toBe(originalSandboxName); - expect( - harness.logSpy.mock.calls.map((call) => String(call[0])).join("\n"), - ).toContain("rebuild completed"); + expect(harness.logSpy.mock.calls.map((call) => String(call[0])).join("\n")).toContain( + "rebuild completed", + ); }); it("retains removed immutability state when mutable config verification fails", async () => { @@ -299,13 +267,9 @@ describe("rebuildSandbox flow: lifecycle", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow( - /state was retained.*mutable config posture was not verified/u, - ); + ).rejects.toThrow(/state was retained.*mutable config posture was not verified/u); - expect( - harness.retireRemovedImmutabilityStateRecordSpy, - ).not.toHaveBeenCalled(); + expect(harness.retireRemovedImmutabilityStateRecordSpy).not.toHaveBeenCalled(); }); it("retires removed Shields state after a complete Pi terminal-agent rebuild", async () => { @@ -386,25 +350,17 @@ describe("rebuildSandbox flow: lifecycle", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).rejects.toThrow("Recreate failed"); - const output = harness.logSpy.mock.calls - .map((call) => String(call[0])) - .join("\n"); - const errors = harness.errorSpy.mock.calls - .map((call) => String(call[0])) - .join("\n"); + const output = harness.logSpy.mock.calls.map((call) => String(call[0])).join("\n"); + const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n"); expect(output).not.toContain("rebuilt successfully"); expect(errors).toContain("Inner onboarding completed with exit code 1"); expect(harness.restoreSandboxStateSpy).not.toHaveBeenCalled(); - expect( - harness.retireRemovedImmutabilityStateRecordSpy, - ).not.toHaveBeenCalled(); + expect(harness.retireRemovedImmutabilityStateRecordSpy).not.toHaveBeenCalled(); expect(process.exitCode).toBeUndefined(); }); it("keeps the original sandbox when the post-MCP OpenShell policy is unavailable", async () => { - const policyDirectory = createHarnessTempDir( - "nemoclaw-rebuild-policy-cleanup-", - ); + const policyDirectory = createHarnessTempDir("nemoclaw-rebuild-policy-cleanup-"); vi.spyOn(tempFiles, "secureTempFile").mockReturnValue( path.join(policyDirectory, "policy.yaml"), ); @@ -440,9 +396,7 @@ describe("rebuildSandbox flow: lifecycle", () => { ); expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledOnce(); - expect( - harness.reattachMcpProvidersAfterRebuildAbortSpy, - ).toHaveBeenCalledOnce(); + expect(harness.reattachMcpProvidersAfterRebuildAbortSpy).toHaveBeenCalledOnce(); expect(harness.onboardSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); expect(fs.readdirSync(policyDirectory)).toEqual([]); @@ -458,15 +412,11 @@ describe("rebuildSandbox flow: lifecycle", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow( - "Shared inference route changed before sandbox deletion.", - ); + ).rejects.toThrow("Shared inference route changed before sandbox deletion."); expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledOnce(); - expect( - harness.reattachMcpProvidersAfterRebuildAbortSpy, - ).toHaveBeenCalledOnce(); + expect(harness.reattachMcpProvidersAfterRebuildAbortSpy).toHaveBeenCalledOnce(); expect(harness.onboardSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); }); @@ -493,8 +443,7 @@ describe("rebuildSandbox flow: lifecycle", () => { ]; const harness = createRebuildFlowHarness({ captureOpenshell: () => { - const probe = - probeSequence[Math.min(sandboxGetAttempts, probeSequence.length - 1)]; + const probe = probeSequence[Math.min(sandboxGetAttempts, probeSequence.length - 1)]; sandboxGetAttempts += 1; events.push(probe.event); return probe.result; @@ -515,9 +464,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(events).toEqual(["stale-live", "absent", "absent", "onboard"]); expect( harness.captureOpenshellSpy.mock.calls.filter( - ([args]) => - Array.isArray(args) && - args.join(" ") === "sandbox get -g nemoclaw alpha", + ([args]) => Array.isArray(args) && args.join(" ") === "sandbox get -g nemoclaw alpha", ), ).toHaveLength(3); }); @@ -561,9 +508,7 @@ describe("rebuildSandbox flow: lifecycle", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow( - "Sandbox configuration changed before rebuild lock acquisition", - ); + ).rejects.toThrow("Sandbox configuration changed before rebuild lock acquisition"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); @@ -587,9 +532,7 @@ describe("rebuildSandbox flow: lifecycle", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow( - "Sandbox configuration changed before rebuild lock acquisition", - ); + ).rejects.toThrow("Sandbox configuration changed before rebuild lock acquisition"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); @@ -624,10 +567,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect.objectContaining({ toolDisclosure: "direct" }), ); expect(harness.session.toolDisclosure).toBe("direct"); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( - "alpha", - [mcpEntry], - ); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); harness.registryUpdateSpy.mock.calls.forEach(([, update]) => { expect(update).not.toHaveProperty("toolDisclosure"); }); @@ -659,9 +599,7 @@ describe("rebuildSandbox flow: lifecycle", () => { harness.rebuildSandbox("alpha", ["--yes", "--force"], { throwOnError: true }), ).resolves.toBeUndefined(); - expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith( - "alpha", - ); + expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith("alpha"); expect(harness.onboardSpy).toHaveBeenCalledOnce(); }); @@ -676,9 +614,7 @@ describe("rebuildSandbox flow: lifecycle", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).rejects.toThrow("Recreate failed"); - expect( - harness.removeSandboxRegistryEntryWithReceiptSpy, - ).not.toHaveBeenCalled(); + expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); }); it("disposes the base-image handoff when live-state preflight fails (#7144)", async () => { @@ -764,10 +700,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(harness.session.compatibleEndpointReasoningEffort).toBe("high"); expect(process.env.NEMOCLAW_REASONING).toBe("false"); expect(process.env.NEMOCLAW_REASONING_EFFORT).toBe("low"); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( - "alpha", - [mcpEntry], - ); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); } finally { restoreEnv(); } diff --git a/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts b/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts index 8f2c00326d4..1602c9fea69 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts @@ -30,21 +30,21 @@ const RESTART_REFUSED = { } as const; describe("binding the Hermes gateway to restored state", () => { - it("keeps selected OpenShell operations pinned while using frozen rebuild supervisor authority", () => { + it("keeps selected OpenShell operations pinned while using frozen rebuild supervisor authority", async () => { const runtimeSelection = { gatewayName: "nemoclaw-19080", workspace: "default", localTlsDir: "/authority/tls", }; const frozenTargetGatewaySupervisorAction = vi.fn(() => null); - const restartSandboxGateway = vi.fn(() => RESTART_SUCCEEDED); - const checkAndRecoverSandboxProcesses = vi.fn(() => ({ + const restartSandboxGateway = vi.fn(async () => RESTART_SUCCEEDED); + const checkAndRecoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: true, recovered: false, })); - const restartState = restartHermesGatewayAfterStateRestore("alpha", "hermes", { + const restartState = await restartHermesGatewayAfterStateRestore("alpha", "hermes", { frozenTargetGatewaySupervisorAction, restartSandboxGateway, runtimeSelection, @@ -57,7 +57,7 @@ describe("binding the Hermes gateway to restored state", () => { }); expect( - verifyHermesGatewayAfterStateRestore("alpha", "hermes", restartState, { + await verifyHermesGatewayAfterStateRestore("alpha", "hermes", restartState, { checkAndRecoverSandboxProcesses, frozenTargetGatewaySupervisorAction, runtimeSelection, @@ -69,15 +69,16 @@ describe("binding the Hermes gateway to restored state", () => { runtimeSelection, }); }); - it("preserves an MCP refusal before gateway replacement (#8671)", () => { - const restartState = restartHermesGatewayAfterStateRestore("alpha", "hermes", { - restartSandboxGateway: () => RESTART_REFUSED, + + it("preserves an MCP refusal before gateway replacement (#8671)", async () => { + const restartState = await restartHermesGatewayAfterStateRestore("alpha", "hermes", { + restartSandboxGateway: async () => RESTART_REFUSED, }); expect(restartState).toBe("restart-failed"); expect( - verifyHermesGatewayAfterStateRestore("alpha", "hermes", restartState, { - checkAndRecoverSandboxProcesses: () => ({ + await verifyHermesGatewayAfterStateRestore("alpha", "hermes", restartState, { + checkAndRecoverSandboxProcesses: async () => ({ checked: true, wasRunning: true, recovered: false, @@ -85,39 +86,42 @@ describe("binding the Hermes gateway to restored state", () => { }), ).toBe("unverified"); }); - - - - it("verifies the final cron-bound gateway without restarting after MCP restoration (#8472)", () => { + it("verifies the final cron-bound gateway without restarting after MCP restoration (#8472)", async () => { const original = { pid: 41, start_time: 902, drain_token: "restore-token" }; const replacement = { pid: 77, start_time: 903, drain_token: "restore-token" }; - const restartSandboxGateway = vi.fn(() => RESTART_SUCCEEDED); + const restartSandboxGateway = vi.fn(async () => RESTART_SUCCEEDED); const observeHermesCronReplacement = vi.fn(() => replacement); expect( - verifyHermesGatewayAfterStateRestoreForCronGate("alpha", "hermes", "restarted", original, { - restartSandboxGateway, - observeHermesCronReplacement, - checkAndRecoverSandboxProcesses: () => ({ - checked: true, - wasRunning: true, - recovered: false, - }), - }), + await verifyHermesGatewayAfterStateRestoreForCronGate( + "alpha", + "hermes", + "restarted", + original, + { + restartSandboxGateway, + observeHermesCronReplacement, + checkAndRecoverSandboxProcesses: async () => ({ + checked: true, + wasRunning: true, + recovered: false, + }), + }, + ), ).toEqual({ state: "healthy", replacementIdentity: replacement }); expect(restartSandboxGateway).not.toHaveBeenCalled(); expect(observeHermesCronReplacement).toHaveBeenCalledTimes(2); }); - it("rejects unstable final cron identity without restarting after MCP restoration (#8472)", () => { - const restartSandboxGateway = vi.fn(() => RESTART_SUCCEEDED); + it("rejects unstable final cron identity without restarting after MCP restoration (#8472)", async () => { + const restartSandboxGateway = vi.fn(async () => RESTART_SUCCEEDED); const observeHermesCronReplacement = vi .fn() .mockReturnValueOnce({ pid: 77, start_time: 903, drain_token: "restore-token" }) .mockReturnValueOnce({ pid: 88, start_time: 904, drain_token: "restore-token" }); expect( - verifyHermesGatewayAfterStateRestoreForCronGate( + await verifyHermesGatewayAfterStateRestoreForCronGate( "alpha", "hermes", "restarted", @@ -125,7 +129,7 @@ describe("binding the Hermes gateway to restored state", () => { { restartSandboxGateway, observeHermesCronReplacement, - checkAndRecoverSandboxProcesses: () => ({ + checkAndRecoverSandboxProcesses: async () => ({ checked: true, wasRunning: true, recovered: false, @@ -135,7 +139,6 @@ describe("binding the Hermes gateway to restored state", () => { ).toEqual({ state: "unverified" }); expect(restartSandboxGateway).not.toHaveBeenCalled(); }); - }); describe("Hermes rebuild post-restore verification", () => { diff --git a/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts b/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts index 6785830a61a..767716fac94 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts @@ -103,12 +103,20 @@ type GatewayRecoveryObservation = { interface HermesPostRestoreGatewayDeps { checkAndRecoverSandboxProcesses?: ( sandboxName: string, - options: { quiet: boolean; runtimeSelection?: OpenShellRuntimeSelection }, - ) => GatewayRecoveryObservation; + options: { + quiet: boolean; + requestGatewaySupervisorAction?: typeof executeGatewaySupervisorAction; + runtimeSelection?: OpenShellRuntimeSelection; + }, + ) => Promise; restartSandboxGateway?: ( sandboxName: string, - options: { quiet: boolean; runtimeSelection?: OpenShellRuntimeSelection }, - ) => GatewayRestartResult; + options: { + quiet: boolean; + deps?: { requestGatewaySupervisorAction: typeof executeGatewaySupervisorAction }; + runtimeSelection?: OpenShellRuntimeSelection; + }, + ) => Promise; observeHermesCronReplacement?: ( sandboxName: string, originalIdentity: HermesCronRestoreIdentity, @@ -141,41 +149,41 @@ export interface HermesPostRestoreGatewayVerification { * identity whose MCP load just converged. A gated rebuild keeps the root-owned * cron drain active across restart, MCP restoration, and final verification. */ -export function restartHermesGatewayAfterStateRestore( +export async function restartHermesGatewayAfterStateRestore( sandboxName: string, agentName: string, deps: HermesPostRestoreGatewayDeps = {}, -): HermesPostRestoreGatewayRestartState { +): Promise { if (agentName !== "hermes") return "not-applicable"; const restart = deps.restartSandboxGateway ?? restartSandboxGateway; const requestGatewaySupervisorAction = deps.frozenTargetGatewaySupervisorAction; - const result = restart(sandboxName, { + const result = await restart(sandboxName, { quiet: true, - ...(requestGatewaySupervisorAction - ? { deps: { requestGatewaySupervisorAction } } - : {}), + ...(requestGatewaySupervisorAction ? { deps: { requestGatewaySupervisorAction } } : {}), ...(deps.runtimeSelection ? { runtimeSelection: deps.runtimeSelection } : {}), }); if (result.ok) return "restarted"; return "restart-failed"; } -export function verifyHermesGatewayAfterStateRestore( +export async function verifyHermesGatewayAfterStateRestore( sandboxName: string, agentName: string, restartState: HermesPostRestoreGatewayRestartState, deps: HermesPostRestoreGatewayDeps = {}, -): HermesPostRestoreGatewayState { - return verifyHermesGatewayAfterStateRestoreImpl(sandboxName, agentName, restartState, deps).state; +): Promise { + return ( + await verifyHermesGatewayAfterStateRestoreImpl(sandboxName, agentName, restartState, deps) + ).state; } -export function verifyHermesGatewayAfterStateRestoreForCronGate( +export async function verifyHermesGatewayAfterStateRestoreForCronGate( sandboxName: string, agentName: string, restartState: HermesPostRestoreGatewayRestartState, originalIdentity: HermesCronRestoreIdentity, deps: HermesPostRestoreGatewayDeps = {}, -): HermesPostRestoreGatewayVerification { +): Promise { return verifyHermesGatewayAfterStateRestoreImpl( sandboxName, agentName, @@ -192,17 +200,16 @@ function sameGatewayIdentity( return left.pid === right.pid && left.start_time === right.start_time; } -function verifyHermesGatewayAfterStateRestoreImpl( +async function verifyHermesGatewayAfterStateRestoreImpl( sandboxName: string, agentName: string, restartState: HermesPostRestoreGatewayRestartState, deps: HermesPostRestoreGatewayDeps, originalIdentity?: HermesCronRestoreIdentity, -): HermesPostRestoreGatewayVerification { +): Promise { if (agentName !== "hermes") return { state: "not-applicable" }; const restarted = restartState === "restarted"; - const checkAndRecover = - deps.checkAndRecoverSandboxProcesses ?? checkAndRecoverSandboxProcesses; + const checkAndRecover = deps.checkAndRecoverSandboxProcesses ?? checkAndRecoverSandboxProcesses; const observeReplacement = deps.observeHermesCronReplacement ?? observeHermesCronReplacement; const maxAttempts = originalIdentity ? HERMES_GATEWAY_RECHECK_ATTEMPTS + 1 @@ -218,7 +225,7 @@ function verifyHermesGatewayAfterStateRestoreImpl( // later iteration must observe it both before and after health. } } - const observation: GatewayRecoveryObservation = checkAndRecover(sandboxName, { + const observation: GatewayRecoveryObservation = await checkAndRecover(sandboxName, { quiet: true, ...(deps.frozenTargetGatewaySupervisorAction ? { requestGatewaySupervisorAction: deps.frozenTargetGatewaySupervisorAction } diff --git a/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts b/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts index 87479b7bbea..bda6cb824e0 100644 --- a/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts @@ -80,7 +80,7 @@ describe("forced rebuild MCP preparation", () => { ); expect(mocks.executeSandboxExecCommand).toHaveBeenCalledWith("alpha", ":", undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); expect(mocks.executeSandboxCommand).toHaveBeenCalledWith("alpha", ":", { @@ -105,7 +105,7 @@ describe("forced rebuild MCP preparation", () => { runtimeSelection, }); expect(mocks.executeSandboxExecCommand).toHaveBeenCalledWith("alpha", ":", undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); expect(mocks.prepareExecUnavailable).toHaveBeenCalledWith("alpha", runtimeSelection); @@ -128,7 +128,7 @@ describe("forced rebuild MCP preparation", () => { ); expect(mocks.executeSandboxExecCommand).toHaveBeenCalledWith("alpha", ":", undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); expect(mocks.prepareExecUnavailable).toHaveBeenCalledWith("alpha", runtimeSelection); @@ -172,7 +172,7 @@ describe("forced rebuild MCP preparation", () => { runtimeSelection, }); expect(mocks.executeSandboxExecCommand).toHaveBeenCalledWith("alpha", ":", undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection, }); expect(mocks.prepareAbsent).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/rebuild-mcp-phase.ts b/src/lib/actions/sandbox/rebuild-mcp-phase.ts index fa812cc4f07..ea555af7115 100644 --- a/src/lib/actions/sandbox/rebuild-mcp-phase.ts +++ b/src/lib/actions/sandbox/rebuild-mcp-phase.ts @@ -45,17 +45,17 @@ export function resolveMcpPreparationRuntimeSelection( } } -function canExecuteMcpPreparation( +async function canExecuteMcpPreparation( sandboxName: string, runtimeSelection: ReturnType, -): boolean { +): Promise { // Live MCP preparation uses both transports: SSH-backed adapter // inspection/mutation and OpenShell-mediated adapter/provider operations. // Prove both before any mutation. A direct Docker fallback would not prove // that the OpenShell transport itself can run. const sshProbe = executeSandboxCommand(sandboxName, ":", { runtimeSelection }); - const execProbe = executeSandboxExecCommand(sandboxName, ":", undefined, { - allowLocalDockerFallback: false, + const execProbe = await executeSandboxExecCommand(sandboxName, ":", undefined, { + localDockerFallbackPolicy: "never", runtimeSelection, }); return sshProbe !== null && sshProbe.status === 0 && execProbe !== null && execProbe.status === 0; @@ -89,7 +89,7 @@ export async function prepareMcpForRebuild( force && !staleRecovery && requiresRuntimeSelection && - (!runtimeSelection || !canExecuteMcpPreparation(sandboxName, runtimeSelection)) + (!runtimeSelection || !(await canExecuteMcpPreparation(sandboxName, runtimeSelection))) ) { console.error(` ${YW}⚠${R} MCP transport probe failed; --force using host-side MCP recovery`); try { diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts index 3d012b70432..8909447beb0 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts @@ -46,7 +46,7 @@ describe("rebuild post-restore phase", () => { runtime: { kind: runtimeKindByAgent[agentName] }, }) as never, ); - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockImplementation(() => { + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockImplementation(async () => { order.push("doctor"); return { status: 0, stdout: "", stderr: "" }; }); @@ -71,10 +71,13 @@ describe("rebuild post-restore phase", () => { order.push("config-hash-final"); return true; }); - vi.spyOn(mutableConfigPerms, "repairMutableConfigPerms").mockReturnValue({ - applied: true, - verified: true, - errors: [], + vi.spyOn(mutableConfigPerms, "repairMutableConfigPerms").mockImplementation(() => { + order.push("permissions"); + return { + applied: true, + verified: true, + errors: [], + }; }); vi.spyOn(mutableConfigPerms, "inspectMutableHermesConfigPerms").mockReturnValue({ verified: true, @@ -85,17 +88,17 @@ describe("rebuild post-restore phase", () => { return true; }); vi.spyOn(rebuildHermesPostRestore, "restartHermesGatewayAfterStateRestore").mockImplementation( - (_sandboxName, targetAgentName) => + async (_sandboxName, targetAgentName) => targetAgentName === "hermes" ? "restarted" : "not-applicable", ); vi.spyOn(rebuildHermesPostRestore, "verifyHermesGatewayAfterStateRestore").mockImplementation( - (_sandboxName, targetAgentName) => + async (_sandboxName, targetAgentName) => targetAgentName === "hermes" ? "healthy" : "not-applicable", ); vi.spyOn( rebuildHermesPostRestore, "verifyHermesGatewayAfterStateRestoreForCronGate", - ).mockReturnValue({ + ).mockResolvedValue({ state: "healthy", replacementIdentity: { pid: 77, start_time: 903, drain_token: "restore-token" }, }); @@ -158,7 +161,9 @@ describe("rebuild post-restore phase", () => { "doctor", "reconcile", "messaging", + "permissions", "mcp", + "permissions", "config-hash", "config-hash-final", "host-forward", @@ -168,7 +173,68 @@ describe("rebuild post-restore phase", () => { "alpha", "openclaw doctor --fix", 300_000, - { allowLocalDockerFallback: false }, + { localDockerFallbackPolicy: "never" }, + ); + }); + + it("re-establishes mutable config permissions after MCP writers settle", async () => { + let repairAttempt = 0; + vi.mocked(mutableConfigPerms.repairMutableConfigPerms).mockImplementation(() => { + repairAttempt += 1; + order.push(`permissions:${String(repairAttempt)}`); + return repairAttempt === 1 + ? { applied: true, verified: true, errors: [] } + : { + applied: true, + verified: false, + errors: ["config.json mode changed after MCP restore"], + }; + }); + const args = input(); + + const verification = await runRebuildPostRestorePhase(args); + + expect(order).toEqual([ + "doctor", + "reconcile", + "messaging", + "permissions:1", + "mcp", + "permissions:2", + "config-hash", + "config-hash-final", + "host-forward", + "config-hash-final", + ]); + expect(verification).toEqual({ mutableConfigPermissionsVerified: false }); + expect(args.bail).not.toHaveBeenCalled(); + expect(vi.mocked(console.log).mock.calls.flat().join("\n")).toContain( + "Mutable config permissions were not verified", + ); + }); + + it("uses the verified final permission repair for prepared recovery", async () => { + let repairAttempt = 0; + vi.mocked(mutableConfigPerms.repairMutableConfigPerms).mockImplementation(() => { + repairAttempt += 1; + return repairAttempt === 1 + ? { + applied: true, + verified: false, + errors: ["initial repair did not verify"], + } + : { applied: true, verified: true, errors: [] }; + }); + const args = { ...input(), preparedBackupRecovery: true }; + + await expect(runRebuildPostRestorePhase(args)).resolves.toEqual({ + mutableConfigPermissionsVerified: true, + }); + + expect(mutableConfigPerms.repairMutableConfigPerms).toHaveBeenCalledTimes(2); + expect(args.bail).not.toHaveBeenCalled(); + expect(vi.mocked(console.log).mock.calls.flat().join("\n")).toContain( + "Sandbox 'alpha' rebuild completed", ); }); @@ -190,7 +256,7 @@ describe("rebuild post-restore phase", () => { "alpha", "openclaw doctor --fix", 300_000, - { allowLocalDockerFallback: false, runtimeSelection }, + { localDockerFallbackPolicy: "never", runtimeSelection }, ); expect(rebuildMessaging.reapplyMessagingManifestAfterOpenClawDoctor).toHaveBeenCalledWith( "alpha", @@ -233,13 +299,11 @@ describe("rebuild post-restore phase", () => { expect(args.bail).toHaveBeenCalledWith( "Recreated sandbox agent identity did not match the authoritative rebuild target.", ); - expect( - rebuildHermesPostRestore.restartHermesGatewayAfterStateRestore, - ).not.toHaveBeenCalled(); + expect(rebuildHermesPostRestore.restartHermesGatewayAfterStateRestore).not.toHaveBeenCalled(); }); it("does not record a final hash without trusted doctor completion (#9946)", async () => { - vi.mocked(processRecovery.executeSandboxExecCommand).mockReturnValue(null); + vi.mocked(processRecovery.executeSandboxExecCommand).mockResolvedValue(null); const args = input(); await runRebuildPostRestorePhase(args); @@ -276,7 +340,7 @@ describe("rebuild post-restore phase", () => { }); it("stops before later writes when doctor exits nonzero (#9946)", async () => { - vi.mocked(processRecovery.executeSandboxExecCommand).mockReturnValue({ + vi.mocked(processRecovery.executeSandboxExecCommand).mockResolvedValue({ status: 255, stdout: "", stderr: "", @@ -325,7 +389,7 @@ describe("rebuild post-restore phase", () => { it("captures a completed doctor mutation and rejects a later config change (#9946)", async () => { let configHashValid = true; - vi.mocked(processRecovery.executeSandboxExecCommand).mockImplementation(() => { + vi.mocked(processRecovery.executeSandboxExecCommand).mockImplementation(async () => { configHashValid = false; return { status: 0, stdout: "sensitive doctor output", stderr: "" }; }); @@ -497,7 +561,7 @@ describe("rebuild post-restore phase", () => { let dispatchHeld = true; const attemptDispatch = () => events.push(dispatchHeld ? "dispatch-blocked" : "dispatch-ran"); vi.mocked(rebuildHermesPostRestore.restartHermesGatewayAfterStateRestore).mockImplementation( - () => { + async () => { events.push("restart"); attemptDispatch(); return "restarted"; @@ -510,7 +574,7 @@ describe("rebuild post-restore phase", () => { }); vi.mocked( rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestoreForCronGate, - ).mockImplementation(() => { + ).mockImplementation(async () => { events.push("health-verified"); attemptDispatch(); return { @@ -570,7 +634,7 @@ describe("rebuild post-restore phase", () => { agentName = "hermes"; vi.mocked( rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestoreForCronGate, - ).mockReturnValue({ state: "unverified" }); + ).mockResolvedValue({ state: "unverified" }); const args = { ...input(), hermesCronRestoreIdentity: { @@ -598,7 +662,7 @@ describe("rebuild post-restore phase", () => { agentName = "hermes"; const events: string[] = []; vi.mocked(rebuildHermesPostRestore.restartHermesGatewayAfterStateRestore).mockImplementation( - () => { + async () => { events.push("restart-failed"); return "restart-failed"; }, @@ -609,7 +673,7 @@ describe("rebuild post-restore phase", () => { }); vi.mocked( rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestoreForCronGate, - ).mockImplementation((_sandboxName, _agentName, restartState) => { + ).mockImplementation(async (_sandboxName, _agentName, restartState) => { events.push(`verify:${restartState}`); return { state: "unverified" }; }); @@ -738,7 +802,7 @@ describe("rebuild post-restore phase", () => { vi.mocked(rebuildMcp.restoreMcpAfterRebuild).mockResolvedValue(false); vi.mocked( rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestoreForCronGate, - ).mockReturnValue({ state: "unverified" }); + ).mockResolvedValue({ state: "unverified" }); const args = { ...input(), hermesCronRestoreIdentity: { @@ -790,7 +854,7 @@ describe("rebuild post-restore phase", () => { it("does not print the Hermes API token notice when post-restore verification is incomplete (#7175)", async () => { agentName = "hermes"; - vi.mocked(rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestore).mockReturnValue( + vi.mocked(rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestore).mockResolvedValue( "unverified", ); const args = input(); @@ -835,7 +899,7 @@ describe("rebuild post-restore phase", () => { it("prints the Hermes API token notice after gateway recovery (#7175)", async () => { agentName = "hermes"; - vi.mocked(rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestore).mockReturnValue( + vi.mocked(rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestore).mockResolvedValue( "recovered", ); const args = input(); @@ -967,6 +1031,16 @@ describe("rebuild post-restore phase", () => { }); describe("Hermes operator config completion report", () => { + it("stays silent when no restore report exists", () => { + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + try { + printHermesOperatorConfigRestoreReport("hermes", undefined); + expect(log).not.toHaveBeenCalled(); + } finally { + log.mockRestore(); + } + }); + it("explicitly names restored keys and an empty dropped set", () => { const log = vi.spyOn(console, "log").mockImplementation(() => undefined); try { diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts index ac097ccc719..c51a35d76e5 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts @@ -110,9 +110,9 @@ export function printHermesOperatorConfigRestoreReport( targetAgentName: string, report: HermesOperatorConfigRestoreReport | undefined, ): void { - if (targetAgentName !== "hermes") return; - const restored = report?.restoredKeys.join(", ") || "none"; - const dropped = report?.droppedKeys.join(", ") || "none"; + if (targetAgentName !== "hermes" || !report) return; + const restored = report.restoredKeys.join(", ") || "none"; + const dropped = report.droppedKeys.join(", ") || "none"; console.log(` Restored Hermes operator config keys: ${restored}`); console.log(` Dropped Hermes operator config keys: ${dropped}`); } @@ -201,14 +201,43 @@ export async function runRebuildPostRestorePhase( } : {}; + const repairMutableOpenClawConfigPermissions = (message: string): void => { + mutablePermsRepairUnverified = true; + mutableConfigPermissionsVerified = false; + log(message); + let permRepair: ReturnType | null = null; + try { + permRepair = repairMutableConfigPerms(sandboxName); + } catch (error) { + mutablePermsRepairUnverified = true; + console.error( + ` ${YW}\u26a0${R} Mutable config permission repair errored: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if (permRepair === null) { + // The thrown error was reported above. + } else if (!permRepair.applied) { + log(`Mutable config permission repair skipped: ${permRepair.reason}`); + } else if (permRepair.verified) { + mutablePermsRepairUnverified = false; + mutableConfigPermissionsVerified = true; + console.log(` ${G}\u2713${R} Mutable config permissions restored`); + } else { + mutablePermsRepairUnverified = true; + console.error( + ` ${YW}\u26a0${R} Mutable config permission repair incomplete: ${permRepair.errors.join("; ")}`, + ); + } + }; + if (targetAgentName === "openclaw") { log("Running openclaw doctor --fix inside sandbox for post-upgrade structure repair"); - const doctorResult = executeSandboxExecCommand( + const doctorResult = await executeSandboxExecCommand( sandboxName, "openclaw doctor --fix", OPENCLAW_DOCTOR_TIMEOUT_MS, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", ...(mcpRuntimeSelection ? { runtimeSelection: mcpRuntimeSelection } : {}), }, ); @@ -247,29 +276,9 @@ export async function runRebuildPostRestorePhase( return; } - log("Restoring mutable OpenClaw config permissions after post-restore config writes"); - let permRepair: ReturnType | null = null; - try { - permRepair = repairMutableConfigPerms(sandboxName); - } catch (error) { - mutablePermsRepairUnverified = true; - console.error( - ` ${YW}\u26a0${R} Mutable config permission repair errored: ${error instanceof Error ? error.message : String(error)}`, - ); - } - if (permRepair === null) { - // The thrown error was reported above. - } else if (!permRepair.applied) { - log(`Mutable config permission repair skipped: ${permRepair.reason}`); - } else if (permRepair.verified) { - mutableConfigPermissionsVerified = true; - console.log(` ${G}\u2713${R} Mutable config permissions restored`); - } else { - mutablePermsRepairUnverified = true; - console.error( - ` ${YW}\u26a0${R} Mutable config permission repair incomplete: ${permRepair.errors.join("; ")}`, - ); - } + repairMutableOpenClawConfigPermissions( + "Restoring mutable OpenClaw config permissions after post-restore config writes", + ); } try { @@ -301,7 +310,7 @@ export async function runRebuildPostRestorePhase( // Restart before restoring MCP. The Hermes MCP transaction performs an // acknowledged reload of its own; restarting afterwards would replace the // only runtime whose managed MCP configuration was proven to have loaded. - const hermesGatewayRestartState = restartHermesGatewayAfterStateRestore( + const hermesGatewayRestartState = await restartHermesGatewayAfterStateRestore( sandboxName, targetAgentName, hermesPostRestoreGatewayDeps, @@ -311,6 +320,14 @@ export async function runRebuildPostRestorePhase( mcpEntries, mcpRuntimeSelection, )); + if (targetAgentName === "openclaw") { + // MCP restoration may write OpenClaw configuration after the earlier + // doctor/messaging repair. Re-establish the final mutable-config posture + // after that async writer has settled and before sealing the config hash. + repairMutableOpenClawConfigPermissions( + "Restoring mutable OpenClaw config permissions after MCP restoration", + ); + } if (targetAgentName === "openclaw" && mcpBridgeRestoreUnverified) { mutableConfigHashRefreshUnverified = true; } else if (targetAgentName === "openclaw") { @@ -324,7 +341,7 @@ export async function runRebuildPostRestorePhase( } } const hermesGatewayVerification = hermesCronRestoreIdentity - ? verifyHermesGatewayAfterStateRestoreForCronGate( + ? await verifyHermesGatewayAfterStateRestoreForCronGate( sandboxName, targetAgentName, hermesGatewayRestartState, @@ -332,7 +349,7 @@ export async function runRebuildPostRestorePhase( hermesPostRestoreGatewayDeps, ) : { - state: verifyHermesGatewayAfterStateRestore( + state: await verifyHermesGatewayAfterStateRestore( sandboxName, targetAgentName, hermesGatewayRestartState, @@ -490,8 +507,7 @@ export async function runRebuildPostRestorePhase( mutableConfigPermissionsVerified = true; log(`Verified the rebuilt ${targetAgentName} terminal-agent mutable posture`); } - const postRestoreComplete = - genericPostRestoreComplete && mutableConfigPermissionsVerified; + const postRestoreComplete = genericPostRestoreComplete && mutableConfigPermissionsVerified; if (postRestoreComplete) { console.log(` ${G}✓${R} Sandbox '${sandboxName}' rebuild completed`); if (versionCheck.expectedVersion) { diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index 110f303ae33..86cb5b5ef60 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -17,7 +17,7 @@ afterEach(() => { describe("establishRestoredSandboxGatewayPairing", () => { it("restarts the restored gateway before warm-up and after approval (#7431)", async () => { const order: string[] = []; - const restartRestoredSandboxGateway = vi.fn(() => { + const restartRestoredSandboxGateway = vi.fn(async () => { order.push("restart"); }); const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); @@ -48,7 +48,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { }); it("keeps the ordinary verifier as the sole success condition (#7431)", async () => { - const restartRestoredSandboxGateway = vi.fn(); + const restartRestoredSandboxGateway = vi.fn(async () => undefined); const warmupScopeUpgrade = vi.fn(); const approveRestoredClonePairing = vi.fn(() => "approve-failed" as const); const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); @@ -68,7 +68,9 @@ describe("establishRestoredSandboxGatewayPairing", () => { it("approves once when the first verifier publishes the clone scope upgrade (#7834)", async () => { const order: string[] = []; - const restartRestoredSandboxGateway = vi.fn(() => order.push("restart")); + const restartRestoredSandboxGateway = vi.fn(async () => { + order.push("restart"); + }); const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); const approveRestoredClonePairing = vi .fn(() => { @@ -214,7 +216,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { await expect( establishRestoredSandboxGatewayPairing("beta", { - restartRestoredSandboxGateway: vi.fn(() => {}), + restartRestoredSandboxGateway: vi.fn(async () => undefined), warmupScopeUpgrade, approveRestoredClonePairing, verifyGatewayPairing, @@ -313,16 +315,20 @@ describe("restartRestoredSandboxGateway", () => { expect(waitForManagedGatewaySupervisor).toHaveBeenCalledWith("beta"); }); - it("restarts through the existing supervisor-mediated gateway lifecycle (#7431)", () => { - const restartSandboxGateway = vi.fn(() => ({ + it("restarts through the existing supervisor-mediated gateway lifecycle (#7431)", async () => { + const restartSandboxGateway = vi.fn(async () => ({ ok: true as const, restarted: true as const, healthPassed: true as const, forwardRecovered: true, })); - const checkAndRecoverSandboxProcesses = vi.fn(); + const checkAndRecoverSandboxProcesses = vi.fn(async () => ({ + checked: false, + recovered: false, + forwardRecovered: false, + })); - restartRestoredSandboxGateway("beta", { + await restartRestoredSandboxGateway("beta", { restartSandboxGateway, checkAndRecoverSandboxProcesses, }); @@ -331,8 +337,8 @@ describe("restartRestoredSandboxGateway", () => { expect(checkAndRecoverSandboxProcesses).not.toHaveBeenCalled(); }); - it("transactionally relaunches an exactly missing restored supervisor (#7818)", () => { - const restartSandboxGateway = vi.fn(() => ({ + it("transactionally relaunches an exactly missing restored supervisor (#7818)", async () => { + const restartSandboxGateway = vi.fn(async () => ({ ok: false as const, failureLayer: "supervisor not running" as const, detail: "SUPERVISOR_NOT_RUNNING", @@ -342,16 +348,17 @@ describe("restartRestoredSandboxGateway", () => { _sandboxName: string, _options?: { quiet?: boolean; - isSandboxGatewayRunningImpl?: (sandboxName: string) => boolean | null; + isSandboxGatewayRunningImpl?: (sandboxName: string) => Promise; }, - ) => ({ - checked: true, - recovered: true, - forwardRecovered: true, - }), + ) => + Promise.resolve({ + checked: true, + recovered: true, + forwardRecovered: true, + }), ); - restartRestoredSandboxGateway("beta", { + await restartRestoredSandboxGateway("beta", { restartSandboxGateway, checkAndRecoverSandboxProcesses, }); @@ -361,27 +368,31 @@ describe("restartRestoredSandboxGateway", () => { isSandboxGatewayRunningImpl: expect.any(Function), }); const recoveryOptions = checkAndRecoverSandboxProcesses.mock.calls[0]?.[1]; - expect(recoveryOptions?.isSandboxGatewayRunningImpl?.("beta")).toBe(false); + await expect(recoveryOptions?.isSandboxGatewayRunningImpl?.("beta")).resolves.toBe(false); }); - it("waits for a newly created clone supervisor before retrying restart (#7818)", () => { + it("waits for a newly created clone supervisor before retrying restart (#7818)", async () => { const restartSandboxGateway = vi .fn() - .mockReturnValueOnce({ + .mockResolvedValueOnce({ ok: false as const, failureLayer: "supervisor not running" as const, detail: "SUPERVISOR_NOT_RUNNING", }) - .mockReturnValueOnce({ + .mockResolvedValueOnce({ ok: true as const, restarted: true as const, healthPassed: true as const, forwardRecovered: true, }); - const checkAndRecoverSandboxProcesses = vi.fn(); + const checkAndRecoverSandboxProcesses = vi.fn(async () => ({ + checked: false, + recovered: false, + forwardRecovered: false, + })); const waitForManagedGatewaySupervisor = vi.fn(() => true); - restartRestoredSandboxGateway("beta", { + await restartRestoredSandboxGateway("beta", { restartSandboxGateway, checkAndRecoverSandboxProcesses, waitForManagedGatewaySupervisor, @@ -392,32 +403,32 @@ describe("restartRestoredSandboxGateway", () => { expect(checkAndRecoverSandboxProcesses).not.toHaveBeenCalled(); }); - it("preserves the supervisor classification when relaunch is not fully proven (#7818)", () => { - const restartSandboxGateway = vi.fn(() => ({ + it("preserves the supervisor classification when relaunch is not fully proven (#7818)", async () => { + const restartSandboxGateway = vi.fn(async () => ({ ok: false as const, failureLayer: "supervisor not running" as const, detail: "SUPERVISOR_NOT_RUNNING", })); - const checkAndRecoverSandboxProcesses = vi.fn(() => ({ + const checkAndRecoverSandboxProcesses = vi.fn(async () => ({ checked: true, recovered: true, forwardRecovered: false, forwardRecoveryFailed: true, })); - expect(() => + await expect( restartRestoredSandboxGateway("beta", { restartSandboxGateway, checkAndRecoverSandboxProcesses, }), - ).toThrow("supervisor not running"); + ).rejects.toThrow("supervisor not running"); }); - it("propagates only the classified gateway restart failure (#7431)", () => { + it("propagates only the classified gateway restart failure (#7431)", async () => { let failure: unknown; try { - restartRestoredSandboxGateway("beta", { - restartSandboxGateway: () => ({ + await restartRestoredSandboxGateway("beta", { + restartSandboxGateway: async () => ({ ok: false, failureLayer: "health timeout", detail: "raw gateway output must stay private", diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.ts b/src/lib/actions/sandbox/restore-gateway-pairing.ts index 31770694fda..523ae4c2ab6 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.ts @@ -16,7 +16,7 @@ import type { GatewayRestartResult } from "./gateway-restart"; import { WARMUP_SESSION_ID_PREFIX } from "./warmup-session"; export type RestoreGatewayPairingDeps = { - restartRestoredSandboxGateway: (sandboxName: string) => void; + restartRestoredSandboxGateway: (sandboxName: string) => Promise; warmupScopeUpgrade: (sandboxName: string) => void; approveRestoredClonePairing: (sandboxName: string) => AutoPairApprovalReceipt | void; verifyGatewayPairing: (sandboxName: string) => RestoreGatewayPairingVerificationResult; @@ -35,19 +35,19 @@ type RestoredSandboxGatewayRestartDeps = { restartSandboxGateway: ( sandboxName: string, options?: { quiet?: boolean }, - ) => GatewayRestartResult; + ) => Promise; checkAndRecoverSandboxProcesses: ( sandboxName: string, options?: { quiet?: boolean; - isSandboxGatewayRunningImpl?: (sandboxName: string) => boolean | null; + isSandboxGatewayRunningImpl?: (sandboxName: string) => Promise; }, - ) => { + ) => Promise<{ checked: boolean; recovered: boolean; forwardRecovered: boolean; forwardRecoveryFailed?: boolean; - }; + }>; waitForManagedGatewaySupervisor?: (sandboxName: string) => boolean; }; @@ -67,18 +67,18 @@ export function waitForRestoredSandboxGatewaySupervisor( return deps.waitForManagedGatewaySupervisor?.(sandboxName) === true; } -export function restartRestoredSandboxGateway( +export async function restartRestoredSandboxGateway( sandboxName: string, deps: RestoredSandboxGatewayRestartDeps = defaultRestoredSandboxGatewayRestartDeps(), -): void { - let result = deps.restartSandboxGateway(sandboxName, { quiet: true }); +): Promise { + let result = await deps.restartSandboxGateway(sandboxName, { quiet: true }); if (!result.ok && result.failureLayer === "supervisor not running") { // OpenShell can publish a newly created clone as Ready before its persisted // startup command has brought up the managed supervisor. Give only that // exact state a bounded settling window before entering legacy-container // relaunch recovery. if (deps.waitForManagedGatewaySupervisor?.(sandboxName)) { - result = deps.restartSandboxGateway(sandboxName, { quiet: true }); + result = await deps.restartSandboxGateway(sandboxName, { quiet: true }); if (result.ok) return; } } @@ -87,14 +87,14 @@ export function restartRestoredSandboxGateway( // supervisor session exists. Reuse the existing transactional relaunch // path only for that exact classified failure. Recovery must prove both // the gateway and its primary forward before pairing work can continue. - const recovery = deps.checkAndRecoverSandboxProcesses(sandboxName, { + const recovery = await deps.checkAndRecoverSandboxProcesses(sandboxName, { quiet: true, // The failed supervisor restart already proves the gateway cannot be // managed through the current container. Skip the redundant sandbox-exec // probe, which is itself unavailable when that supervisor is missing. // The transactional relaunch still re-confirms the exact missing // supervisor against the pinned container before replacing it. - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, }); if ( recovery.checked && @@ -135,12 +135,12 @@ export async function establishRestoredSandboxGatewayPairing( deps: RestoreGatewayPairingDeps = defaultRestoreGatewayPairingDeps(), ): Promise { try { - deps.restartRestoredSandboxGateway(targetSandbox); + await deps.restartRestoredSandboxGateway(targetSandbox); deps.warmupScopeUpgrade(targetSandbox); let approvalReceipt = deps.approveRestoredClonePairing(targetSandbox) ?? "exec-failed"; // Publish the clone's approved pairing transition before an ordinary // authenticated verifier. The verifier alone decides success. - deps.restartRestoredSandboxGateway(targetSandbox); + await deps.restartRestoredSandboxGateway(targetSandbox); let verification = deps.verifyGatewayPairing(targetSandbox); if ( !verification.ok && @@ -152,7 +152,7 @@ export async function establishRestoredSandboxGatewayPairing( // published the exact scope-upgrade request. Approve that request once, // restart once, and keep the next ordinary verifier as the success gate. approvalReceipt = deps.approveRestoredClonePairing(targetSandbox) ?? "exec-failed"; - deps.restartRestoredSandboxGateway(targetSandbox); + await deps.restartRestoredSandboxGateway(targetSandbox); verification = deps.verifyGatewayPairing(targetSandbox); } if (!verification.ok) { diff --git a/src/lib/actions/sandbox/runtime/hermes-lifecycle.ts b/src/lib/actions/sandbox/runtime/hermes-lifecycle.ts index b613a675193..278325c0aae 100644 --- a/src/lib/actions/sandbox/runtime/hermes-lifecycle.ts +++ b/src/lib/actions/sandbox/runtime/hermes-lifecycle.ts @@ -28,9 +28,9 @@ export function createHermesCredentialEnvReconciliationRuntime( return result; }, parseRestartCompletion: gatewayRestart.parseManagedGatewayControlCompletion, - waitForGateway: (sandboxName: string, revalidate: (operation: string) => void) => { + waitForGateway: async (sandboxName: string, revalidate: (operation: string) => void) => { revalidate(`checking Hermes gateway health for sandbox '${sandboxName}'`); - const healthy = processRecovery.waitForRecoveredSandboxGateway(sandboxName, { + const healthy = await processRecovery.waitForRecoveredSandboxGateway(sandboxName, { quiet: true, initialManagedHealthPassed: true, requireManagedProbe: true, diff --git a/src/lib/actions/sandbox/sessions/passthrough.test.ts b/src/lib/actions/sandbox/sessions/passthrough.test.ts index 450a1ee1efd..fd649c3a114 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.test.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.test.ts @@ -2,8 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandExecutor, +} from "../../../adapters/openshell/sandbox-command"; -const captureMock = vi.hoisted(() => vi.fn()); +const runBufferedMock = vi.hoisted(() => + vi.fn(), +); const execMock = vi.hoisted(() => vi.fn(async () => {})); const ensureLiveMock = vi.hoisted(() => vi.fn(async () => ({}))); const getSandboxMock = vi.hoisted(() => vi.fn(() => null as { agent?: string } | null)); @@ -11,9 +17,6 @@ const withLifecycleLockMock = vi.hoisted(() => vi.fn(async (_sandboxName: string, operation: () => unknown) => await operation()), ); -vi.mock("../../../adapters/openshell/runtime", () => ({ - captureOpenshell: captureMock, -})); vi.mock("../exec", async () => { const actual = await vi.importActual("../exec"); return { ...actual, execSandbox: execMock }; @@ -26,12 +29,28 @@ vi.mock("../../../state/mcp-lifecycle-lock-acquisition", () => ({ import { WARMUP_SESSION_ID_PREFIX } from "../warmup-session"; import { + createSessionsPassthrough, filterWarmupSessionsListJson, filterWarmupSessionsListText, printSessionsPassthroughHelp, - runSessionsPassthrough, } from "./passthrough"; +const runSessionsPassthrough = createSessionsPassthrough({ + sandboxCommandExecutor: { runBuffered: runBufferedMock }, +}); + +function completedBufferedCommand( + stdout: string, + stderr = "", + exitCode = 0, +): OpenShellSandboxBufferedCommandCompletion { + return { + outcome: { kind: "completed", exitCode }, + stdout, + stderr, + }; +} + describe("filterWarmupSessionsListJson", () => { it("filters internal warm-up sessions from wrapped OpenClaw list JSON (#5511)", () => { const filtered = filterWarmupSessionsListJson( @@ -223,11 +242,12 @@ describe("runSessionsPassthrough", () => { let consoleErrorSpy: ReturnType; beforeEach(() => { - captureMock.mockReset(); + runBufferedMock.mockReset(); execMock.mockClear(); ensureLiveMock.mockClear(); getSandboxMock.mockReset(); getSandboxMock.mockReturnValue(null); + withLifecycleLockMock.mockClear(); stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true); stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true); consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); @@ -240,14 +260,17 @@ describe("runSessionsPassthrough", () => { }); it("captures and filters `sessions list --json` instead of streaming warm-up entries", async () => { - captureMock.mockReturnValueOnce({ - status: 0, - output: JSON.stringify({ - count: 1, - totalCount: 1, - sessions: [{ key: "agent:main:explicit:warm", sessionId: `${WARMUP_SESSION_ID_PREFIX}1` }], - }), - }); + runBufferedMock.mockResolvedValueOnce( + completedBufferedCommand( + JSON.stringify({ + count: 1, + totalCount: 1, + sessions: [ + { key: "agent:main:explicit:warm", sessionId: `${WARMUP_SESSION_ID_PREFIX}1` }, + ], + }), + ), + ); await runSessionsPassthrough("alpha", { verb: "list", @@ -259,22 +282,12 @@ describe("runSessionsPassthrough", () => { exit: expect.any(Function), }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "--name", - "alpha", - "--", - "openclaw", - "sessions", - "list", - "--agent", - "main", - "--json", - ], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(runBufferedMock).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "sessions", "list", "--agent", "main", "--json"], + outputLimitBytes: 64 * 1024 * 1024, + }); expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({ count: 0, totalCount: 0, @@ -283,40 +296,38 @@ describe("runSessionsPassthrough", () => { }); it("captures and filters text `sessions list` output", async () => { - captureMock.mockReturnValueOnce({ - status: 0, - stdout: [ - "Sessions listed: 1", - `direct agent:main:expli... 1m ago model id:${WARMUP_SESSION_ID_PREFIX}1`, - ].join("\n"), - stderr: "warning: noisy but non-fatal\n", - output: [ - "Sessions listed: 1", - `direct agent:main:expli... 1m ago model id:${WARMUP_SESSION_ID_PREFIX}1`, - ].join("\n"), - }); + runBufferedMock.mockResolvedValueOnce( + completedBufferedCommand( + [ + "Sessions listed: 1", + `direct agent:main:expli... 1m ago model id:${WARMUP_SESSION_ID_PREFIX}1`, + ].join("\n"), + "warning: noisy but non-fatal\n", + ), + ); await runSessionsPassthrough("alpha", { verb: "list", extraArgs: ["--agent", "main"] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalled(); + expect(runBufferedMock).toHaveBeenCalled(); expect(String(stdoutSpy.mock.calls[0]?.[0])).toBe("Sessions listed: 0\n"); expect(String(stderrSpy.mock.calls[0]?.[0])).toBe("warning: noisy but non-fatal\n"); }); it("also filters the parent `sessions` list shorthand", async () => { - captureMock.mockReturnValueOnce({ - status: 0, - output: `Sessions listed: 1\nid:${WARMUP_SESSION_ID_PREFIX}1`, - }); + runBufferedMock.mockResolvedValueOnce( + completedBufferedCommand(`Sessions listed: 1\nid:${WARMUP_SESSION_ID_PREFIX}1`), + ); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(runBufferedMock).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "sessions"], + outputLimitBytes: 64 * 1024 * 1024, + }); expect(String(stdoutSpy.mock.calls[0]?.[0])).toBe("Sessions listed: 0\n"); }); @@ -326,12 +337,13 @@ describe("runSessionsPassthrough", () => { ) => { throw new Error(`process.exit:${code}`); }) as never); - captureMock.mockReturnValueOnce({ - status: 0, - output: JSON.stringify({ - records: [{ sid: `${WARMUP_SESSION_ID_PREFIX}1` }], - }), - }); + runBufferedMock.mockResolvedValueOnce( + completedBufferedCommand( + JSON.stringify({ + records: [{ sid: `${WARMUP_SESSION_ID_PREFIX}1` }], + }), + ), + ); try { await expect( @@ -347,10 +359,7 @@ describe("runSessionsPassthrough", () => { it("passes through unrecognised JSON when it cannot leak a warm-up session", async () => { const raw = JSON.stringify({ records: [{ key: "agent:main:main", sessionId: "sid-real" }] }); - captureMock.mockReturnValueOnce({ - status: 0, - output: raw, - }); + runBufferedMock.mockResolvedValueOnce(completedBufferedCommand(raw)); await runSessionsPassthrough("alpha", { verb: "list", extraArgs: ["--json"] }); @@ -364,12 +373,13 @@ describe("runSessionsPassthrough", () => { ) => { throw new Error(`process.exit:${code}`); }) as never); - captureMock.mockReturnValueOnce({ - status: null, - output: "", + runBufferedMock.mockResolvedValueOnce({ + outcome: { + kind: "failed", + error: { kind: "capture", message: "stdout exceeded the buffered output limit" }, + }, stdout: "", stderr: "", - error: Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }), }); try { @@ -380,10 +390,11 @@ describe("runSessionsPassthrough", () => { exitSpy.mockRestore(); } - expect(captureMock).toHaveBeenCalledWith(expect.any(Array), { - ignoreError: true, - includeStreams: true, - maxBuffer: 64 * 1024 * 1024, + expect(runBufferedMock).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "sessions", "list", "--all-agents", "--json"], + outputLimitBytes: 64 * 1024 * 1024, }); expect(consoleErrorSpy).toHaveBeenCalledWith( expect.stringContaining("output exceeded NemoClaw's 64 MiB filtering buffer"), @@ -397,7 +408,7 @@ describe("runSessionsPassthrough", () => { await runSessionsPassthrough("hermes", { extraArgs: [] }); - expect(captureMock).not.toHaveBeenCalled(); + expect(runBufferedMock).not.toHaveBeenCalled(); expect(execMock).toHaveBeenCalledWith( "hermes", ["hermes", "sessions", "list"], @@ -408,15 +419,17 @@ describe("runSessionsPassthrough", () => { it("uses openclaw binary for openclaw-agent sandboxes (#6247)", async () => { getSandboxMock.mockReturnValue({ agent: "openclaw" }); - captureMock.mockReturnValueOnce({ status: 0, output: "Sessions listed: 0\n" }); + runBufferedMock.mockResolvedValueOnce(completedBufferedCommand("Sessions listed: 0\n")); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(runBufferedMock).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "sessions"], + outputLimitBytes: 64 * 1024 * 1024, + }); }); it("routes hermes `sessions list` with forwarded flags via execSandbox (#6247)", async () => { @@ -427,7 +440,7 @@ describe("runSessionsPassthrough", () => { extraArgs: ["--limit", "5"], }); - expect(captureMock).not.toHaveBeenCalled(); + expect(runBufferedMock).not.toHaveBeenCalled(); expect(execMock).toHaveBeenCalledWith( "hermes", ["hermes", "sessions", "list", "--limit", "5"], @@ -438,28 +451,32 @@ describe("runSessionsPassthrough", () => { it("defaults to the openclaw binary + filter path when the registry has no entry (#6247)", async () => { getSandboxMock.mockReturnValue(null); - captureMock.mockReturnValueOnce({ status: 0, output: "Sessions listed: 0\n" }); + runBufferedMock.mockResolvedValueOnce(completedBufferedCommand("Sessions listed: 0\n")); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(runBufferedMock).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "sessions"], + outputLimitBytes: 64 * 1024 * 1024, + }); }); it("defaults to the openclaw binary for an unknown agent value (#6247)", async () => { getSandboxMock.mockReturnValue({ agent: "custom-future-agent" }); - captureMock.mockReturnValueOnce({ status: 0, output: "Sessions listed: 0\n" }); + runBufferedMock.mockResolvedValueOnce(completedBufferedCommand("Sessions listed: 0\n")); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(runBufferedMock).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "sessions"], + outputLimitBytes: 64 * 1024 * 1024, + }); }); it("prints captured output when OpenClaw exits non-zero", async () => { @@ -468,12 +485,7 @@ describe("runSessionsPassthrough", () => { ) => { throw new Error(`process.exit:${code}`); }) as never); - captureMock.mockReturnValueOnce({ - status: 2, - output: "", - stdout: "", - stderr: "unknown flag: --bad\n", - }); + runBufferedMock.mockResolvedValueOnce(completedBufferedCommand("", "unknown flag: --bad\n", 2)); try { await expect( @@ -487,4 +499,56 @@ describe("runSessionsPassthrough", () => { expect(String(stderrSpy.mock.calls[0]?.[0])).toBe("unknown flag: --bad\n"); }); + it.each(["invocation", "unavailable", "timeout"] as const)( + "reports typed buffered %s failures with their captured streams", + async (kind) => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((( + code?: string | number | null, + ) => { + throw new Error(`process.exit:${code}`); + }) as never); + runBufferedMock.mockResolvedValueOnce({ + outcome: { + kind: "failed", + error: { kind, message: `OpenShell ${kind} failure` }, + }, + stdout: "partial output\n", + stderr: "transport detail\n", + }); + + try { + await expect( + runSessionsPassthrough("alpha", { verb: "list", extraArgs: ["--json"] }), + ).rejects.toThrow("process.exit:1"); + } finally { + exitSpy.mockRestore(); + } + + expect(String(stdoutSpy.mock.calls[0]?.[0])).toBe("partial output\n"); + expect(String(stderrSpy.mock.calls[0]?.[0])).toBe("transport detail\n"); + expect(consoleErrorSpy).toHaveBeenCalledWith( + ` Failed to invoke openshell: OpenShell ${kind} failure`, + ); + }, + ); + + it("reports an executor rejection and still releases the lifecycle lock", async () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((( + code?: string | number | null, + ) => { + throw new Error(`process.exit:${code}`); + }) as never); + runBufferedMock.mockRejectedValueOnce(new Error("adapter rejected")); + + try { + await expect( + runSessionsPassthrough("alpha", { verb: "list", extraArgs: ["--json"] }), + ).rejects.toThrow("process.exit:1"); + } finally { + exitSpy.mockRestore(); + } + + expect(consoleErrorSpy).toHaveBeenCalledWith(" Failed to invoke openshell: adapter rejected"); + expect(withLifecycleLockMock).toHaveBeenCalledOnce(); + }); }); diff --git a/src/lib/actions/sandbox/sessions/passthrough.ts b/src/lib/actions/sandbox/sessions/passthrough.ts index d881b433049..67179c25a11 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.ts @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { captureOpenshell } from "../../../adapters/openshell/runtime"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandExecutor, +} from "../../../adapters/openshell/sandbox-command"; import { CLI_NAME } from "../../../cli/branding"; import { deferSandboxLifecycleExit, @@ -10,7 +13,7 @@ import { import { assertHermesPortableCommandUnavailable } from "../../../onboard/experimental/portable-agent-lifecycle"; import { withMcpLifecycleLock } from "../../../state/mcp-lifecycle-lock-acquisition"; import * as registry from "../../../state/registry"; -import { buildOpenshellExecArgs, computeExitCode, execSandbox } from "../exec"; +import { execSandbox } from "../exec"; import { ensureLiveSandboxOrExit } from "../gateway-state"; import { isWarmupSessionId, WARMUP_SESSION_ID_PREFIX } from "../warmup-session"; import { balancedJsonCandidates, parseSessionIndex } from "./session-index"; @@ -24,6 +27,10 @@ export interface SessionsPassthroughOptions { extraArgs?: readonly string[]; } +export interface SessionsPassthroughDependencies { + sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor; +} + export function hasSessionsPassthroughHelpToken(args: readonly string[]): boolean { for (const arg of args) { if (arg === "--") break; @@ -138,14 +145,6 @@ function writeWithTrailingNewline(stream: NodeJS.WriteStream, value: string | un stream.write(value.endsWith("\n") ? value : `${value}\n`); } -function capturedStdout(result: { output: string; stdout?: string }): string { - return typeof result.stdout === "string" ? result.stdout.trim() : result.output; -} - -function capturedStderr(result: { stderr?: string }): string { - return typeof result.stderr === "string" ? result.stderr.trim() : ""; -} - function printJsonParseFailure(): void { console.error( " Could not parse `openclaw sessions list --json` output as a session index. Check the OpenClaw version pinned in agents/openclaw/manifest.yaml.", @@ -160,8 +159,8 @@ function printSessionsListCaptureBufferFailure(): void { ); } -function isCaptureBufferFailure(result: { error?: Error }): boolean { - return (result.error as NodeJS.ErrnoException | undefined)?.code === "ENOBUFS"; +function isCaptureBufferFailure(result: OpenShellSandboxBufferedCommandCompletion): boolean { + return result.outcome.kind === "failed" && result.outcome.error.kind === "capture"; } export function filterWarmupSessionsListJson(output: string): string | null { @@ -215,19 +214,27 @@ export function filterWarmupSessionsListText(output: string): string { .join("\n"); } -export async function runSessionsPassthrough( - sandboxName: string, - { verb, extraArgs = [] }: SessionsPassthroughOptions = {}, -): Promise { - return runWithDeferredSandboxLifecycleExit(async () => { - await withMcpLifecycleLock(sandboxName, () => { - assertHermesPortableCommandUnavailable(sandboxName, `sandbox:sessions:${verb ?? "list"}`); - return runSessionsPassthroughUnlocked(sandboxName, { verb, extraArgs }); +export function createSessionsPassthrough({ + sandboxCommandExecutor, +}: SessionsPassthroughDependencies) { + return async function runSessionsPassthrough( + sandboxName: string, + { verb, extraArgs = [] }: SessionsPassthroughOptions = {}, + ): Promise { + return runWithDeferredSandboxLifecycleExit(async () => { + await withMcpLifecycleLock(sandboxName, () => { + assertHermesPortableCommandUnavailable(sandboxName, `sandbox:sessions:${verb ?? "list"}`); + return runSessionsPassthroughUnlocked(sandboxCommandExecutor, sandboxName, { + verb, + extraArgs, + }); + }); }); - }); + }; } async function runSessionsPassthroughUnlocked( + sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor, sandboxName: string, { verb, extraArgs = [] }: SessionsPassthroughOptions = {}, ): Promise { @@ -251,14 +258,24 @@ async function runSessionsPassthroughUnlocked( else if (inSandboxBinary === "hermes") command.push("list"); for (const arg of extraArgs) command.push(arg); if (isFilterableListPassthrough(verb) && inSandboxBinary === "openclaw") { - const result = captureOpenshell(buildOpenshellExecArgs(sandboxName, command), { - ignoreError: true, - includeStreams: true, - maxBuffer: SESSIONS_LIST_CAPTURE_MAX_BUFFER_BYTES, - }); - const { code, errorMessage } = computeExitCode(result); - const capturedOutput = capturedStdout(result); - const capturedError = capturedStderr(result); + let result: OpenShellSandboxBufferedCommandCompletion; + try { + result = await sandboxCommandExecutor.runBuffered({ + sandboxName, + target: { kind: "selected" }, + command, + outputLimitBytes: SESSIONS_LIST_CAPTURE_MAX_BUFFER_BYTES, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + console.error(` Failed to invoke openshell: ${detail}`); + deferSandboxLifecycleExit(1); + } + const code = result.outcome.kind === "completed" ? result.outcome.exitCode : 1; + const errorMessage = + result.outcome.kind === "failed" ? result.outcome.error.message : undefined; + const capturedOutput = result.stdout.trim(); + const capturedError = result.stderr.trim(); if (code !== 0) { writeWithTrailingNewline(process.stdout, capturedOutput); writeWithTrailingNewline(process.stderr, capturedError); diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index 2997a9c839a..cea43526ae9 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -67,7 +67,7 @@ function harness(overrides: Partial = {}) { Promise.resolve(), ); const restoreStartupState = vi.fn>( - () => SUCCESSFUL_RECOVERY, + async () => SUCCESSFUL_RECOVERY, ); const waitForManagedGatewaySupervisor = vi.fn< NonNullable @@ -118,7 +118,7 @@ function harness(overrides: Partial = {}) { describe("startSandbox", () => { it("waits for OpenShell readiness before recovering sandbox processes (#8978)", async () => { const waitForSandboxReady = vi.fn(); - const restoreProcesses = vi.fn(() => SUCCESSFUL_RECOVERY); + const restoreProcesses = vi.fn(async () => SUCCESSFUL_RECOVERY); await restoreStoppedSandboxStartupState("my-sandbox", { waitForSandboxReady, @@ -133,7 +133,7 @@ describe("startSandbox", () => { it("waits for OpenShell readiness before recovering Hermes sandbox processes (#8978)", async () => { const waitForSandboxReady = vi.fn(); - const restoreProcesses = vi.fn(() => SUCCESSFUL_RECOVERY); + const restoreProcesses = vi.fn(async () => SUCCESSFUL_RECOVERY); await restoreStoppedSandboxStartupState("my-sandbox", { waitForSandboxReady, @@ -147,7 +147,7 @@ describe("startSandbox", () => { it("starts the container, then waits for readiness, then recovers, then probes the gateway (#8978)", async () => { const waitForSandboxReady = vi.fn(); - const restoreProcesses = vi.fn(() => SUCCESSFUL_RECOVERY); + const restoreProcesses = vi.fn(async () => SUCCESSFUL_RECOVERY); const h = harness({ restoreStartupState: (name: string) => restoreStoppedSandboxStartupState(name, { @@ -197,7 +197,7 @@ describe("startSandbox", () => { const observer: OpenShellSandboxObserver = { listSandboxes, }; - const restoreProcesses = vi.fn(() => SUCCESSFUL_RECOVERY); + const restoreProcesses = vi.fn(async () => SUCCESSFUL_RECOVERY); const h = harness({ allowDockerRuntimeInspection: false, observer, @@ -249,7 +249,7 @@ describe("startSandbox", () => { testTimeoutOptions(30_000), async () => { const h = harness(); - h.restoreStartupState.mockReturnValueOnce(FAILED_RECOVERY); + h.restoreStartupState.mockResolvedValueOnce(FAILED_RECOVERY); await expect(startSandbox("my-sandbox", h.deps)).rejects.toThrow("gateway did not recover"); expect(h.verifyGateway).not.toHaveBeenCalled(); @@ -268,12 +268,12 @@ describe("startSandbox", () => { it("waits for a transient managed supervisor before repeating full startup recovery (#8726)", async () => { const h = harness(); h.restoreStartupState - .mockReturnValueOnce({ + .mockResolvedValueOnce({ ...FAILED_RECOVERY, recoveryFailureLayer: "supervisor not running", recoveryFailureDetail: "SUPERVISOR_NOT_RUNNING", }) - .mockReturnValueOnce(SUCCESSFUL_RECOVERY); + .mockResolvedValueOnce(SUCCESSFUL_RECOVERY); h.waitForManagedGatewaySupervisor.mockReturnValue(true); const result = await startSandbox("my-sandbox", h.deps); @@ -296,7 +296,7 @@ describe("startSandbox", () => { it("preserves the first recovery failure when the managed supervisor remains absent (#8726)", async () => { const h = harness(); - h.restoreStartupState.mockReturnValue({ + h.restoreStartupState.mockResolvedValue({ ...FAILED_RECOVERY, recoveryFailureLayer: "supervisor not running", recoveryFailureDetail: "SUPERVISOR_NOT_RUNNING", @@ -312,7 +312,7 @@ describe("startSandbox", () => { it("preserves the first recovery failure when the managed supervisor wait throws (#8726)", async () => { const h = harness(); - h.restoreStartupState.mockReturnValue({ + h.restoreStartupState.mockResolvedValue({ ...FAILED_RECOVERY, recoveryFailureLayer: "supervisor not running", recoveryFailureDetail: "SUPERVISOR_NOT_RUNNING", @@ -336,7 +336,7 @@ describe("startSandbox", () => { recoveryFailureLayer: "supervisor not running" as const, recoveryFailureDetail: "SUPERVISOR_NOT_RUNNING", }; - h.restoreStartupState.mockReturnValue(missingSupervisor); + h.restoreStartupState.mockResolvedValue(missingSupervisor); h.waitForManagedGatewaySupervisor.mockReturnValue(true); await expect(startSandbox("my-sandbox", h.deps)).rejects.toThrow( @@ -362,7 +362,7 @@ describe("startSandbox", () => { ], ] as const)("does not wait after a %s (#8726)", async (_label, layer, detail) => { const h = harness(); - h.restoreStartupState.mockReturnValue({ + h.restoreStartupState.mockResolvedValue({ ...FAILED_RECOVERY, recoveryFailureLayer: layer, recoveryFailureDetail: detail, @@ -376,7 +376,7 @@ describe("startSandbox", () => { it("keeps successful legacy supervisor relaunch recovery free of a settling wait (#8726)", async () => { const h = harness(); - h.restoreStartupState.mockReturnValue({ + h.restoreStartupState.mockResolvedValue({ ...SUCCESSFUL_RECOVERY, wasRunning: false, recovered: true, @@ -416,7 +416,7 @@ describe("startSandbox", () => { async (agent, _layer, recovery, expected) => { const h = harness(); h.getSandbox.mockReturnValue(sandbox({ agent })); - h.restoreStartupState.mockReturnValue(recovery); + h.restoreStartupState.mockResolvedValue(recovery); const failure = await startSandbox("my-sandbox", h.deps).catch((error) => String(error)); expect(failure).toMatch(expected); @@ -428,7 +428,7 @@ describe("startSandbox", () => { it("does not claim preservation when startup recovery reports a failed rollback (#9364)", async () => { const h = harness(); - h.restoreStartupState.mockReturnValue({ + h.restoreStartupState.mockResolvedValue({ ...FAILED_RECOVERY, recoveryFailureDetail: "NemoClaw could not confirm rollback to the previous sandbox container. Inspect Docker state before retrying. Recovery failure before rollback: the sandbox did not become ready in OpenShell", @@ -477,7 +477,7 @@ describe("startSandbox", () => { }); it("repairs Hermes Portable forwards after lifecycle recovery (#11248)", async () => { - const probeInferenceInvocation = vi.fn(() => ({ ok: true }) as const); + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); const h = harness({ probeInferenceInvocation }); h.getSandbox.mockReturnValue( sandbox({ @@ -690,7 +690,7 @@ describe("startSandbox", () => { }); it("pins a Deep Agents Code start probe to its recorded gateway and managed launcher identity (#10080)", async () => { - const probeInferenceInvocation = vi.fn(() => ({ ok: true }) as const); + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); const h = harness({ probeInferenceInvocation }); h.getSandbox.mockReturnValue( sandbox({ @@ -724,7 +724,7 @@ describe("startSandbox", () => { }); it("pins a Hermes start probe to its recorded OpenShell gateway (#10302)", async () => { - const probeInferenceInvocation = vi.fn(() => ({ ok: true }) as const); + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); const h = harness({ probeInferenceInvocation }); h.getSandbox.mockReturnValue( sandbox({ @@ -758,7 +758,7 @@ describe("startSandbox", () => { it("exits nonzero when the started gateway will not serve an agent request", async () => { const probeInferenceInvocation = vi.fn( - () => + async () => ({ ok: false, detail: "sandbox inference invocation probe returned HTTP 401", @@ -779,7 +779,7 @@ describe("startSandbox", () => { }); it("stays unattested instead of failing when the sandbox records no route", async () => { - const probeInferenceInvocation = vi.fn(() => ({ ok: true }) as const); + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); const h = harness({ probeInferenceInvocation }); const result = await startSandbox("my-sandbox", h.deps); diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index 7b11e2d85cb..5b8c7f935c7 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -31,7 +31,7 @@ function verifyGateway(sandboxName: string): Promise { type SandboxStartupRecoveryResult = import("./connect").SandboxStartupRecoveryResult; -function restoreProcessState(sandboxName: string): SandboxStartupRecoveryResult { +function restoreProcessState(sandboxName: string): Promise { const { restoreSandboxStartupState } = require("./connect") as typeof import("./connect"); return restoreSandboxStartupState(sandboxName); } @@ -55,7 +55,7 @@ async function waitForSandboxReady( export interface SandboxStartupStateDeps { waitForSandboxReady?: (sandboxName: string) => void | Promise; - restoreProcessState?: (sandboxName: string) => SandboxStartupRecoveryResult; + restoreProcessState?: (sandboxName: string) => Promise; } export async function restoreStoppedSandboxStartupState( @@ -63,7 +63,7 @@ export async function restoreStoppedSandboxStartupState( deps: SandboxStartupStateDeps = {}, ): Promise { await (deps.waitForSandboxReady ?? waitForSandboxReady)(sandboxName); - return (deps.restoreProcessState ?? restoreProcessState)(sandboxName); + return await (deps.restoreProcessState ?? restoreProcessState)(sandboxName); } export interface SandboxStartDeps { @@ -71,11 +71,9 @@ export interface SandboxStartDeps { observer?: OpenShellSandboxObserver; environment?: NodeJS.ProcessEnv; getSandbox?: typeof registry.getSandbox; - restoreProcessState?: (sandboxName: string) => SandboxStartupRecoveryResult; + restoreProcessState?: (sandboxName: string) => Promise; runtimeProviders?: RuntimeProviderBundleRegistry; - restoreStartupState?: ( - sandboxName: string, - ) => SandboxStartupRecoveryResult | Promise; + restoreStartupState?: (sandboxName: string) => Promise; waitForManagedGatewaySupervisor?: (sandboxName: string) => boolean; verifyGateway?: (sandboxName: string) => Promise; probeInferenceInvocation?: typeof probeSandboxInferenceInvocation; @@ -128,18 +126,18 @@ function startupRecoveryError(sandboxName: string, detail: unknown): Error { * provider or no model has nothing to request, so start skips the request * instead of failing. */ -function checkStartedSandboxInference( +async function checkStartedSandboxInference( sandboxName: string, sandbox: SandboxEntry, deps: SandboxStartDeps, log: (message: string) => void, -): SandboxInferenceInvocationResult | null { +): Promise { const model = (sandbox.model ?? "").trim(); const provider = (sandbox.provider ?? "").trim(); if (!model || !provider) return null; const gatewayName = getPersistedSandboxTargetGatewayName(sandbox); log(" Checking that the sandbox serves an agent request…"); - return (deps.probeInferenceInvocation ?? probeSandboxInferenceInvocation)( + return await (deps.probeInferenceInvocation ?? probeSandboxInferenceInvocation)( { sandboxName, gatewayName, @@ -238,7 +236,7 @@ async function startSandboxWithinLifecycleFence( if (failure) throw startupRecoveryError(name, failure); log(" Checking gateway health and host forwards…"); await (deps.verifyGateway ?? verifyGateway)(name); - readiness.inference = checkStartedSandboxInference(name, resolved.sandbox, deps, log); + readiness.inference = await checkStartedSandboxInference(name, resolved.sandbox, deps, log); }); if (readiness.inference && !readiness.inference.ok) { log(` The sandbox started but inference is not usable: ${readiness.inference.detail}.`); diff --git a/src/lib/actions/sandbox/status-inference.test.ts b/src/lib/actions/sandbox/status-inference.test.ts index 247077d1307..29db149e64e 100644 --- a/src/lib/actions/sandbox/status-inference.test.ts +++ b/src/lib/actions/sandbox/status-inference.test.ts @@ -61,7 +61,7 @@ describe("sandbox status inference.local route health (#6192)", () => { : async () => options.routeHealth, ), probeSandboxInferenceInvocationImpl: vi.fn( - (_input: Parameters[0]) => + async (_input: Parameters[0]) => ({ ok: true }) as const, ), probeTerminalRuntimeHealth: vi.fn(() => ({ kind: "ok" as const, oomKillCount: 0 as const })), @@ -227,7 +227,7 @@ describe("sandbox status inference.local route health (#6192)", () => { detail: "route reachable", }, }); - deps.probeSandboxInferenceInvocationImpl.mockImplementation((input) => { + deps.probeSandboxInferenceInvocationImpl.mockImplementation(async (input) => { const command = buildSandboxInferenceInvocationCommand(input); expect(command).toContain("https://inference.local/v1/chat/completions"); expect(command).not.toContain("https://inference.local/v1/responses"); @@ -263,7 +263,7 @@ describe("sandbox status inference.local route health (#6192)", () => { detail: "route reachable", }, }); - deps.probeSandboxInferenceInvocationImpl.mockImplementation((input) => { + deps.probeSandboxInferenceInvocationImpl.mockImplementation(async (input) => { const command = buildSandboxInferenceInvocationCommand(input); expect(command).toContain("https://inference.local/v1/responses"); expect(command).not.toContain("https://inference.local/v1/chat/completions"); diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index a3cbc246e3f..8beb3577464 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -41,7 +41,7 @@ function snapshotDeps( }, probeProviderHealthImpl: () => providerHealth, probeSandboxInferenceGatewayHealthImpl: async () => gateway, - probeSandboxInferenceInvocationImpl: () => invocation, + probeSandboxInferenceInvocationImpl: async () => invocation, reportInferenceProbeRetry: vi.fn(), }, }; @@ -66,7 +66,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { recoverySandboxVia: "started-stopped-original", }; }; - const recoverSandboxProcesses = vi.fn(() => { + const recoverSandboxProcesses = vi.fn(async () => { order.push("recover-agent-and-forward"); return { checked: true, @@ -114,7 +114,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { .mockResolvedValueOnce(unreachable) .mockResolvedValueOnce(healthy); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: false, recovered: true, @@ -154,14 +154,14 @@ describe("collectSandboxStatusSnapshot inference route health", () => { const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => healthy); const probeSandboxInferenceInvocationImpl = vi .fn() - .mockReturnValueOnce({ + .mockResolvedValueOnce({ ok: false, detail: "sandbox inference invocation failed with status 6", httpStatus: null, }) - .mockReturnValueOnce({ ok: true }); + .mockResolvedValueOnce({ ok: true }); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: false, recovered: true, @@ -205,9 +205,9 @@ describe("collectSandboxStatusSnapshot inference route health", () => { recoverySandboxVia: "started-stopped-original", }); const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => healthy); - const probeSandboxInferenceInvocationImpl = vi.fn(() => failedInvocation); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => failedInvocation); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: false, recovered: true, @@ -248,7 +248,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { }); const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => unreachable); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: false, recovered: true, @@ -272,7 +272,9 @@ describe("collectSandboxStatusSnapshot inference route health", () => { it("does not mutate the agent or host forward during an ordinary present status lookup", async () => { const options = snapshotDeps(null); - const recoverSandboxProcesses = vi.fn(); + const recoverSandboxProcesses = vi.fn(async () => { + throw new Error("unexpected recovery"); + }); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); const probeSandboxInferenceGatewayHealthImpl = vi.fn( options.deps.probeSandboxInferenceGatewayHealthImpl, @@ -575,7 +577,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { "Inference gateway unreachable on https://inference.local/v1/models from inside the sandbox.", }; const options = snapshotDeps(gateway); - const probeSandboxInferenceInvocationImpl = vi.fn(() => ({ ok: true }) as const); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true }) as const); const snapshot = await collectSandboxStatusSnapshot("alpha", { ...options, @@ -621,7 +623,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { model: "openai/gpt-4o-mini", }, ); - const probeSandboxInferenceInvocationImpl = vi.fn(() => ({ ok: true }) as const); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true }) as const); const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => gateway); const snapshot = await collectSandboxStatusSnapshot("alpha", { ...options, @@ -671,7 +673,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { }, ); const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => gateway); - const probeSandboxInferenceInvocationImpl = vi.fn(() => ({ ok: true }) as const); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true }) as const); const snapshot = await collectSandboxStatusSnapshot("alpha", { ...options, @@ -753,15 +755,15 @@ describe("collectSandboxStatusSnapshot inference route health", () => { const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => healthy); const probeSandboxInferenceInvocationImpl = vi .fn() - .mockReturnValueOnce({ + .mockResolvedValueOnce({ ok: false, detail: `sandbox inference invocation probe returned HTTP ${httpStatus}`, httpStatus, }) - .mockReturnValueOnce({ ok: true }); + .mockResolvedValueOnce({ ok: true }); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); const reportInferenceProbeRetry = vi.fn(); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: true, recovered: false, @@ -818,14 +820,14 @@ describe("collectSandboxStatusSnapshot inference route health", () => { .fn() .mockResolvedValueOnce(healthy) .mockResolvedValueOnce(brokenRoute); - const probeSandboxInferenceInvocationImpl = vi.fn(() => ({ + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: false as const, detail: "sandbox inference invocation probe returned HTTP 503", httpStatus: 503, })); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); const reportInferenceProbeRetry = vi.fn(); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: true, recovered: false, @@ -872,10 +874,10 @@ describe("collectSandboxStatusSnapshot inference route health", () => { output: "Phase: Ready", }); const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => healthy); - const probeSandboxInferenceInvocationImpl = vi.fn(() => refused); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => refused); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); const reportInferenceProbeRetry = vi.fn(); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: true, recovered: false, @@ -975,10 +977,10 @@ describe("collectSandboxStatusSnapshot inference route health", () => { phase: "Ready", output: "Phase: Ready", }); - const probeSandboxInferenceInvocationImpl = vi.fn(() => testCase.invocation); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => testCase.invocation); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); const reportInferenceProbeRetry = vi.fn(); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: true, recovered: false, @@ -1019,9 +1021,9 @@ describe("collectSandboxStatusSnapshot inference route health", () => { output: "Phase: Ready", }); const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => brokenRoute); - const probeSandboxInferenceInvocationImpl = vi.fn(() => ({ ok: true }) as const); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true }) as const); const delayInferenceRecoveryProbe = vi.fn(async () => undefined); - const recoverSandboxProcesses = vi.fn(() => ({ + const recoverSandboxProcesses = vi.fn(async () => ({ checked: true, wasRunning: true, recovered: false, diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index 0d1fa24b80b..eae7d7783d1 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -73,8 +73,8 @@ function snapshotDeps(recoveryResult: unknown) { }, probeProviderHealthImpl, probeSandboxInferenceGatewayHealthImpl, - probeSandboxInferenceInvocationImpl: vi.fn(() => ({ ok: true }) as const), - recoverSandboxProcesses: vi.fn(() => recoveryResult) as never, + probeSandboxInferenceInvocationImpl: vi.fn(async () => ({ ok: true }) as const), + recoverSandboxProcesses: vi.fn(async () => recoveryResult) as never, }; } diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 7b16c6d3042..4dac8e7e5f0 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -64,7 +64,9 @@ type ProbeProviderHealth = ( provider: string, options?: ProviderHealthProbeOptions, ) => ProviderHealthStatus | null; -type ProbeSandboxInferenceGatewayHealth = typeof probeSandboxInferenceGatewayHealth; +type ProbeSandboxInferenceGatewayHealth = ( + ...args: Parameters +) => ReturnType; type DelayInferenceRecoveryProbe = (delayMs: number) => Promise; const INFERENCE_PROBE_ATTEMPTS = 3; @@ -265,9 +267,12 @@ export function resolveSandboxStatusAgent(agentName = "openclaw"): SandboxStatus type ReconcileSandboxGatewayState = (sandboxName: string) => Promise; type ProbeTerminalRuntimeHealth = (sandboxName: string) => TerminalRuntimeOomProbeResult; -type RecoverSandboxProcesses = +type ProductionRecoverSandboxProcesses = (typeof import("./status/process-recovery"))["checkAndRecoverSandboxProcesses"]; -type SandboxProcessRecoveryResult = ReturnType; +type SandboxProcessRecoveryResult = Awaited>; +type RecoverSandboxProcesses = ( + ...args: Parameters +) => Promise; type SandboxProcessRecoveryFailure = { layer: @@ -389,7 +394,7 @@ function reportInferenceProbeError(error: unknown, writer: (message: string) => function reportInferenceProbeRetry( gatewayChain: Awaited>, - invocation: ReturnType | null, + invocation: Awaited> | null, delayMs: number, attempt: number, writer: (message: string) => void, @@ -463,7 +468,7 @@ export async function collectSandboxStatusSnapshot( // The managed gateway service can restart a Docker sandbox before status // runs. OpenShell then reports Ready without a recoveredSandbox marker, // while the OpenClaw gateway and host forward can still be absent. - const recovery = (opts.deps?.recoverSandboxProcesses ?? loadRecoverSandboxProcesses())( + const recovery = await (opts.deps?.recoverSandboxProcesses ?? loadRecoverSandboxProcesses())( sandboxName, { quiet: true, @@ -624,7 +629,7 @@ export async function collectSandboxStatusSnapshot( const invocationModel = (invocationRoute.model || "").trim(); const invocationProvider = (invocationRoute.provider || "").trim(); const canProbeInvocation = Boolean(invocationModel && invocationProvider); - let invocation: ReturnType | null = null; + let invocation: Awaited> | null = null; try { const probe = opts.deps?.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth; @@ -633,7 +638,7 @@ export async function collectSandboxStatusSnapshot( gatewayChain = gatewayName ? await probe(sandboxName, { gatewayName }) : null; invocation = gatewayChain?.ok && canProbeInvocation - ? runSandboxInferenceInvocationProbe( + ? await runSandboxInferenceInvocationProbe( { sandboxName, gatewayName: gatewayName ?? undefined, diff --git a/src/lib/actions/sandbox/supervisor-relaunch.test.ts b/src/lib/actions/sandbox/supervisor-relaunch.test.ts index 92cf739f58a..55b1d4d3abf 100644 --- a/src/lib/actions/sandbox/supervisor-relaunch.test.ts +++ b/src/lib/actions/sandbox/supervisor-relaunch.test.ts @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, describe, expect, it, vi } from "vitest"; +import type { DockerGpuPatchFinalizeOutcome } from "../../onboard/docker-gpu-patch-finalize"; import type { DockerGpuPatchResult } from "../../onboard/docker-gpu-patch"; +import * as registry from "../../state/registry"; import { type ManagedSupervisorRelaunchDeps, relaunchManagedSupervisorSession, @@ -75,10 +77,17 @@ function baseDeps(overrides: ManagedSupervisorRelaunchDeps = {}) { failedFiles: [], })), removeBackup: vi.fn(() => true), + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }, runOpenshell: vi.fn(() => ({ status: 0, stdout: "No sandboxes found.\n" })), runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:00 Ready\n"), recreate: vi.fn(() => patchResult()), - finalize: vi.fn(({ supervisorReady }) => + finalize: vi.fn(async ({ supervisorReady }) => supervisorReady ? { backupRemoved: true, finalHandoffAcknowledged: true, rolledBack: false } : { backupRemoved: false, rolledBack: true }, @@ -124,7 +133,7 @@ describe("relaunchManagedSupervisorSession", () => { expect(deps.recreate).not.toHaveBeenCalled(); }); - it("pins the selected container and persists only a credential-free startup command", () => { + it("pins the selected container and persists only a credential-free startup command", async () => { vi.stubEnv("NEMOCLAW_EXTRA_PLACEHOLDER_KEYS", "CUSTOM_PROVIDER_CREDENTIAL"); vi.stubEnv("CUSTOM_PROVIDER_CREDENTIAL", "s3cr3t-token"); vi.stubEnv("HTTPS_PROXY", "http://proxyuser:proxypass@proxy.example:8080"); @@ -148,7 +157,7 @@ describe("relaunchManagedSupervisorSession", () => { expect(serialized).not.toContain("CUSTOM_PROVIDER_CREDENTIAL"); expect(serialized).not.toContain("proxypass"); - expect(relaunch?.finalize(true)).toEqual({ + expect(await relaunch?.finalize(true)).toEqual({ backupRemoved: true, finalHandoffAcknowledged: true, rolledBack: false, @@ -165,6 +174,7 @@ describe("relaunchManagedSupervisorSession", () => { supervisorReady: true, }, { + commandExecutor: deps.commandExecutor, runCaptureOpenshell: deps.runCaptureOpenshell, runOpenshell: deps.runOpenshell, }, @@ -172,6 +182,8 @@ describe("relaunchManagedSupervisorSession", () => { }); it("uses managed backup authority for default supervisor recovery", () => { + vi.stubEnv("NEMOCLAW_HERMES_API_PORT", "8642"); + vi.spyOn(registry, "getSandbox").mockReturnValue({ hermesApiPort: 8642 } as never); const managedBackup = vi .spyOn(backupAuthority, "backupSandboxStateWithManagedAuthority") .mockReturnValue({ @@ -209,6 +221,8 @@ describe("relaunchManagedSupervisorSession", () => { it("retains the managed Hermes browser URL during supervisor recovery", () => { vi.stubEnv("NEMOCLAW_EXTRA_PLACEHOLDER_KEYS", "HERMES_RECOVERY_CREDENTIAL"); vi.stubEnv("HERMES_RECOVERY_CREDENTIAL", "recovery-secret"); + vi.stubEnv("NEMOCLAW_HERMES_API_PORT", "8643"); + vi.spyOn(registry, "getSandbox").mockReturnValue({ hermesApiPort: 8643 } as never); const deps = baseDeps({ getSandbox: vi.fn(() => ({ name: "alpha", @@ -413,11 +427,11 @@ describe("relaunchManagedSupervisorSession", () => { ]); }); - it("rolls the container transaction back when managed readiness is not proven", () => { + it("rolls the container transaction back when managed readiness is not proven", async () => { const deps = baseDeps(); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(false)).toEqual({ + expect(await relaunch?.finalize(false)).toEqual({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -431,6 +445,35 @@ describe("relaunchManagedSupervisorSession", () => { }); }); + it("runs finalization once for concurrent matching callers", async () => { + let completeFinalization: ((outcome: DockerGpuPatchFinalizeOutcome) => void) | undefined; + const finalization = new Promise((resolve) => { + completeFinalization = resolve; + }); + const deps = baseDeps({ finalize: vi.fn(() => finalization) }); + const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); + + const first = relaunch?.finalize(true); + const second = relaunch?.finalize(true); + + expect(second).toBe(first); + await Promise.resolve(); + expect(deps.finalize).toHaveBeenCalledOnce(); + await expect(relaunch?.finalize(false)).rejects.toThrow( + "Supervisor relaunch transaction was finalized with conflicting state.", + ); + completeFinalization?.({ + backupRemoved: true, + finalHandoffAcknowledged: true, + rolledBack: false, + }); + await expect(first).resolves.toMatchObject({ + backupRemoved: true, + rolledBack: false, + stateRestored: true, + }); + }); + it("removes a partial state backup before it refuses recreation (#7404)", () => { const deps = baseDeps({ backupState: vi.fn(() => ({ @@ -453,7 +496,7 @@ describe("relaunchManagedSupervisorSession", () => { expect(deps.recreate).not.toHaveBeenCalled(); }); - it("rolls back the container transaction when state restore fails", () => { + it("rolls back the container transaction when state restore fails", async () => { const deps = baseDeps({ restoreState: vi.fn(() => ({ success: false, @@ -465,7 +508,7 @@ describe("relaunchManagedSupervisorSession", () => { }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toEqual({ + expect(await relaunch?.finalize(true)).toEqual({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -478,7 +521,7 @@ describe("relaunchManagedSupervisorSession", () => { }); }); - it("re-proves managed health after state restore and before commit", () => { + it("re-proves managed health after state restore and before commit", async () => { const order: string[] = []; const deps = baseDeps({ restoreState: vi.fn(() => { @@ -495,14 +538,14 @@ describe("relaunchManagedSupervisorSession", () => { order.push("restart-restored-gateway"); return true; }), - finalize: vi.fn(() => { + finalize: vi.fn(async () => { order.push("commit-container"); return { backupRemoved: true, rolledBack: false }; }), }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toMatchObject({ + expect(await relaunch?.finalize(true)).toMatchObject({ backupRemoved: true, rolledBack: false, stateRestored: true, @@ -517,26 +560,31 @@ describe("relaunchManagedSupervisorSession", () => { supervisorReady: true, }, { + commandExecutor: deps.commandExecutor, runCaptureOpenshell: deps.runCaptureOpenshell, runOpenshell: deps.runOpenshell, }, ); }); - it("uses only an injected host sleep for lifecycle polling after recreation (#9531)", () => { + it("uses only an injected host sleep for lifecycle polling after recreation (#9531)", async () => { const sleep = vi.fn(); const deps = baseDeps({ sleep }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toMatchObject({ backupRemoved: true, rolledBack: false }); + expect(await relaunch?.finalize(true)).toMatchObject({ + backupRemoved: true, + rolledBack: false, + }); expect(deps.finalize).toHaveBeenCalledWith(expect.objectContaining({ supervisorReady: true }), { + commandExecutor: deps.commandExecutor, runCaptureOpenshell: deps.runCaptureOpenshell, runOpenshell: deps.runOpenshell, sleep, }); }); - it("rolls back when managed health fails after state restore", () => { + it("rolls back when managed health fails after state restore", async () => { const order: string[] = []; const deps = baseDeps({ restoreState: vi.fn(() => { @@ -553,7 +601,7 @@ describe("relaunchManagedSupervisorSession", () => { order.push("restart-restored-gateway"); return false; }), - finalize: vi.fn(({ supervisorReady }) => { + finalize: vi.fn(async ({ supervisorReady }) => { order.push(supervisorReady ? "commit-container" : "rollback-container"); return supervisorReady ? { backupRemoved: true, rolledBack: false } @@ -562,7 +610,7 @@ describe("relaunchManagedSupervisorSession", () => { }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toEqual({ + expect(await relaunch?.finalize(true)).toEqual({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -575,7 +623,7 @@ describe("relaunchManagedSupervisorSession", () => { }); }); - it("rolls back before restore when the replacement container identity changes", () => { + it("rolls back before restore when the replacement container identity changes", async () => { const deps = baseDeps({ resolveContainer: vi .fn() @@ -584,7 +632,7 @@ describe("relaunchManagedSupervisorSession", () => { }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toEqual({ + expect(await relaunch?.finalize(true)).toEqual({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -598,13 +646,13 @@ describe("relaunchManagedSupervisorSession", () => { }); }); - it("retains the state backup when rollback fails", () => { + it("retains the state backup when rollback fails", async () => { const deps = baseDeps({ - finalize: vi.fn(() => ({ backupRemoved: false, rolledBack: false })), + finalize: vi.fn(async () => ({ backupRemoved: false, rolledBack: false })), }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(false)).toEqual({ + expect(await relaunch?.finalize(false)).toEqual({ backupRemoved: false, rolledBack: false, stateRestored: false, @@ -612,11 +660,11 @@ describe("relaunchManagedSupervisorSession", () => { expect(deps.removeBackup).not.toHaveBeenCalled(); }); - it("reports best-effort state-backup cleanup failure after a successful restore", () => { + it("reports best-effort state-backup cleanup failure after a successful restore", async () => { const deps = baseDeps({ removeBackup: vi.fn(() => false) }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toEqual({ + expect(await relaunch?.finalize(true)).toEqual({ backupRemoved: true, finalHandoffAcknowledged: true, rolledBack: false, @@ -625,9 +673,9 @@ describe("relaunchManagedSupervisorSession", () => { }); }); - it("retains the restored state backup when final handoff is not acknowledged (#9531)", () => { + it("retains the restored state backup when final handoff is not acknowledged (#9531)", async () => { const deps = baseDeps({ - finalize: vi.fn(() => ({ + finalize: vi.fn(async () => ({ backupRemoved: true, finalHandoffAcknowledged: false, lastSandboxPhase: "Deleting", @@ -636,7 +684,7 @@ describe("relaunchManagedSupervisorSession", () => { }); const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); - expect(relaunch?.finalize(true)).toEqual({ + expect(await relaunch?.finalize(true)).toEqual({ backupRemoved: true, finalHandoffAcknowledged: false, lastSandboxPhase: "Deleting", diff --git a/src/lib/actions/sandbox/supervisor-relaunch.ts b/src/lib/actions/sandbox/supervisor-relaunch.ts index 41b657a500f..38a292b407f 100644 --- a/src/lib/actions/sandbox/supervisor-relaunch.ts +++ b/src/lib/actions/sandbox/supervisor-relaunch.ts @@ -2,10 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 import { dockerCapture } from "../../adapters/docker"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import * as agentRuntime from "../../agent/runtime"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; import { shouldManageDashboardForAgent } from "../../onboard/dashboard-runtime"; import { type DockerContainerInspect, + type DockerGpuPatchResult, parseDockerInspectJson, } from "../../onboard/docker-gpu-patch"; import { sameContainerId } from "../../onboard/docker-gpu-patch-clone"; @@ -39,12 +43,14 @@ const DOCKER_INSPECT_TIMEOUT_MS = 15000; const STATE_BACKUP_MAX_RETRIES = 5; const STATE_BACKUP_RETRY_SECONDS = 2; +type ManagedSupervisorFinalizeOutcome = DockerGpuPatchFinalizeOutcome & { + stateRestored?: boolean; + stateBackupRemoved?: boolean; +}; + export type ManagedSupervisorRelaunch = { containerId: string; - finalize(supervisorReady: boolean): DockerGpuPatchFinalizeOutcome & { - stateRestored?: boolean; - stateBackupRemoved?: boolean; - }; + finalize(supervisorReady: boolean): Promise; }; export type ManagedSupervisorRelaunchDeps = { @@ -60,8 +66,17 @@ export type ManagedSupervisorRelaunchDeps = { sleep?: (seconds: number) => void; restoreState?: typeof sandboxState.restoreSandboxState; removeBackup?: typeof sandboxState.removeSandboxStateBackup; - recreate?: typeof recreateOpenShellDockerSandboxWithStartupCommand; - finalize?: typeof finalizeDockerGpuPatchBackup; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; + recreate?: ( + options: Parameters[0] & { + waitForSupervisor: false; + }, + deps?: Parameters[1], + ) => DockerGpuPatchResult; + finalize?: ( + options: Parameters[0], + deps?: Parameters[1], + ) => Promise; runOpenshell?: NonNullable[1]>["runOpenshell"]; runCaptureOpenshell?: NonNullable< Parameters[1] @@ -150,15 +165,12 @@ function reconstructSupervisorLaunchCommand( const loopbackDashboardUrl = `http://127.0.0.1:${dashboardPort}`; let chatUiUrl = manageDashboard ? loopbackDashboardUrl : ""; if (persistedAgent === "hermes" && manageDashboard && hermesDashboardEnabled) { - const readWorkloadAuthority = - deps.readManagedWorkloadAuthority ?? readManagedWorkloadAuthority; + const readWorkloadAuthority = deps.readManagedWorkloadAuthority ?? readManagedWorkloadAuthority; const profile = readWorkloadAuthority(entry)?.profile; if (profile?.dashboard.agent !== "hermes" || profile.dashboard.browserUrl === undefined) { if (!quiet) { console.error(" Trusted container recovery stopped because the Hermes dashboard profile"); - console.error( - " has no recorded browser URL. Rerun onboarding before retrying recovery.", - ); + console.error(" has no recorded browser URL. Rerun onboarding before retrying recovery."); } return null; } @@ -219,6 +231,8 @@ export function relaunchManagedSupervisorSession( const removeBackup = deps.removeBackup ?? sandboxState.removeSandboxStateBackup; const recreate = deps.recreate ?? recreateOpenShellDockerSandboxWithStartupCommand; const finalize = deps.finalize ?? finalizeDockerGpuPatchBackup; + const commandExecutor = + deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor({ hostCwd: REPOSITORY_ROOT }); let pendingStateBackupPath: string | null = null; try { const containerId = resolveContainer(sandboxName, driver); @@ -283,12 +297,9 @@ export function relaunchManagedSupervisorSession( waitForSupervisor: false, }); pendingStateBackupPath = null; - let completed: { + let completion: { supervisorReady: boolean; - outcome: DockerGpuPatchFinalizeOutcome & { - stateRestored?: boolean; - stateBackupRemoved?: boolean; - }; + promise: Promise; } | null = null; const removeSettledStateBackup = (): boolean => { try { @@ -297,92 +308,96 @@ export function relaunchManagedSupervisorSession( return false; } }; + const finalizeTransaction = async ( + supervisorReady: boolean, + ): Promise => { + const finalizeFailure = async () => { + const finalized = await finalize({ result, supervisorReady: false }); + return { + ...finalized, + stateRestored: false, + ...(finalized.rolledBack ? { stateBackupRemoved: removeSettledStateBackup() } : {}), + }; + }; + if (!supervisorReady) { + return finalizeFailure(); + } + let replacementOwned = false; + try { + replacementOwned = sameContainerId( + resolveContainer(sandboxName, driver), + result.newContainerId, + ); + } catch { + replacementOwned = false; + } + if (!replacementOwned) { + return finalizeFailure(); + } + let stateRestored = false; + try { + stateRestored = restoreState(sandboxName, backupManifest.backupPath).success; + } catch { + stateRestored = false; + } + if (!stateRestored) { + return finalizeFailure(); + } + let restoredManagedGatewayReady = false; + try { + restoredManagedGatewayReady = + restartRestoredManagedGateway?.(result.newContainerId) === true; + } catch { + restoredManagedGatewayReady = false; + } + if (!restoredManagedGatewayReady) { + // Apply restored state to a fresh managed gateway process. OpenClaw + // can otherwise retain pre-restore runtime state or enter its + // in-process reload path. Keep the previous container available for + // rollback until the pinned replacement restart and health proof + // both succeed. + return finalizeFailure(); + } + const runLifecycleProbe = deps.runOpenshell; + const captureLifecycleProbe = deps.runCaptureOpenshell; + if (!runLifecycleProbe || !captureLifecycleProbe) return finalizeFailure(); + const lifecycleDeps = { + commandExecutor, + runCaptureOpenshell: captureLifecycleProbe, + runOpenshell: runLifecycleProbe, + ...(deps.sleep ? { sleep: deps.sleep } : {}), + }; + const finalized = await finalize( + { + result, + supervisorReady: true, + sandboxName, + finalHandoffTimeoutSecs: getDockerGpuSupervisorReconnectTimeoutSecs(1), + }, + lifecycleDeps, + ); + return { + ...finalized, + stateRestored: true, + ...(finalized.finalHandoffAcknowledged === true + ? { stateBackupRemoved: removeSettledStateBackup() } + : {}), + }; + }; return { containerId: result.newContainerId, finalize(supervisorReady) { - if (completed) { - if (completed.supervisorReady !== supervisorReady) { - throw new Error( - "Supervisor relaunch transaction was finalized with conflicting state.", + if (completion) { + if (completion.supervisorReady !== supervisorReady) { + return Promise.reject( + new Error("Supervisor relaunch transaction was finalized with conflicting state."), ); } - return completed.outcome; - } - const finalizeFailure = () => { - const finalized = finalize({ result, supervisorReady: false }); - const outcome = { - ...finalized, - stateRestored: false, - ...(finalized.rolledBack ? { stateBackupRemoved: removeSettledStateBackup() } : {}), - }; - completed = { supervisorReady, outcome }; - return outcome; - }; - if (!supervisorReady) { - return finalizeFailure(); - } - let replacementOwned = false; - try { - replacementOwned = sameContainerId( - resolveContainer(sandboxName, driver), - result.newContainerId, - ); - } catch { - replacementOwned = false; - } - if (!replacementOwned) { - return finalizeFailure(); - } - let stateRestored = false; - try { - stateRestored = restoreState(sandboxName, backupManifest.backupPath).success; - } catch { - stateRestored = false; - } - if (!stateRestored) { - return finalizeFailure(); - } - let restoredManagedGatewayReady = false; - try { - restoredManagedGatewayReady = - restartRestoredManagedGateway?.(result.newContainerId) === true; - } catch { - restoredManagedGatewayReady = false; + return completion.promise; } - if (!restoredManagedGatewayReady) { - // Apply restored state to a fresh managed gateway process. OpenClaw - // can otherwise retain pre-restore runtime state or enter its - // in-process reload path. Keep the previous container available for - // rollback until the pinned replacement restart and health proof - // both succeed. - return finalizeFailure(); - } - const runLifecycleProbe = deps.runOpenshell; - const captureLifecycleProbe = deps.runCaptureOpenshell; - if (!runLifecycleProbe || !captureLifecycleProbe) return finalizeFailure(); - const lifecycleDeps = { - runCaptureOpenshell: captureLifecycleProbe, - runOpenshell: runLifecycleProbe, - ...(deps.sleep ? { sleep: deps.sleep } : {}), - }; - const finalized = finalize( - { - result, - supervisorReady: true, - sandboxName, - finalHandoffTimeoutSecs: getDockerGpuSupervisorReconnectTimeoutSecs(1), - }, - lifecycleDeps, - ); - const outcome = { - ...finalized, - stateRestored: true, - ...(finalized.finalHandoffAcknowledged === true - ? { stateBackupRemoved: removeSettledStateBackup() } - : {}), - }; - completed = { supervisorReady, outcome }; - return outcome; + const promise = Promise.resolve().then(() => finalizeTransaction(supervisorReady)); + completion = { supervisorReady, promise }; + return promise; }, }; } catch (error) { diff --git a/src/lib/actions/sandbox/terminal-connect-probe.test.ts b/src/lib/actions/sandbox/terminal-connect-probe.test.ts index f9400ea6fe1..86cc3743eb9 100644 --- a/src/lib/actions/sandbox/terminal-connect-probe.test.ts +++ b/src/lib/actions/sandbox/terminal-connect-probe.test.ts @@ -4,8 +4,33 @@ import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; import type { AgentDefinition } from "../../agent/defs"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { runTerminalAgentConnectProbe } from "./terminal-connect-probe"; +function commandExecutorThrough( + capture: () => { status: number; output: string } | undefined, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async () => { + const result = capture(); + return result + ? { + outcome: { kind: "completed" as const, exitCode: result.status }, + stdout: result.output, + stderr: "", + } + : { + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "unavailable" }, + }, + stdout: "", + stderr: "", + }; + }), + }; +} + const dcodeAgent = { name: "langchain-deepagents-code", runtime: { @@ -42,19 +67,19 @@ describe("terminal-agent connect inference route", () => { vi.restoreAllMocks(); }); - it("fails dcode probe-only before smoke checks when inference.local stays broken (#6191)", () => { + it("fails dcode probe-only before smoke checks when inference.local stays broken (#6191)", async () => { const capture = vi.fn(); const ensureInferenceRoute = vi.fn(() => ({ routeHealthy: false })); - expect(() => + await expect( runTerminalAgentConnectProbe({ agent: dcodeAgent, agentName: "LangChain Deep Agents Code", - capture: capture as never, + commandExecutor: commandExecutorThrough(capture), ensureInferenceRoute, sandboxName: "deep-code", }), - ).toThrow("process.exit(1)"); + ).rejects.toThrow("process.exit(1)"); expect(ensureInferenceRoute).toHaveBeenCalledWith("deep-code", { quiet: true }); expect(capture).not.toHaveBeenCalled(); @@ -64,19 +89,19 @@ describe("terminal-agent connect inference route", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it("preserves smoke-only probing for non-dcode terminal agents with no route (#6191)", () => { + it("preserves smoke-only probing for non-dcode terminal agents with no route (#6191)", async () => { const capture = vi.fn(); const ensureInferenceRoute = vi.fn(() => ({ routeHealthy: null })); - expect(() => + await expect( runTerminalAgentConnectProbe({ agent: otherTerminalAgent, agentName: "Other Terminal Agent", - capture: capture as never, + commandExecutor: commandExecutorThrough(capture), ensureInferenceRoute, sandboxName: "other-box", }), - ).not.toThrow(); + ).resolves.toBeUndefined(); expect(ensureInferenceRoute).toHaveBeenCalledWith("other-box", { quiet: true }); expect(capture).not.toHaveBeenCalled(); @@ -86,22 +111,22 @@ describe("terminal-agent connect inference route", () => { ); }); - it("lets dcode continue to terminal smoke checks when its route probe is inconclusive (#6191)", () => { + it("lets dcode continue to terminal smoke checks when its route probe is inconclusive (#6191)", async () => { const capture = vi.fn(() => ({ status: 0, output: "NEMOCLAW_AGENT_SMOKE_BEGIN\ndcode 0.1.12\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", })); const ensureInferenceRoute = vi.fn(() => ({ routeHealthy: null })); - expect(() => + await expect( runTerminalAgentConnectProbe({ agent: dcodeAgent, agentName: "LangChain Deep Agents Code", - capture: capture as never, + commandExecutor: commandExecutorThrough(capture), ensureInferenceRoute, sandboxName: "deep-code", }), - ).not.toThrow(); + ).resolves.toBeUndefined(); expect(ensureInferenceRoute).toHaveBeenCalledWith("deep-code", { quiet: true }); expect(capture).toHaveBeenCalledOnce(); @@ -111,22 +136,22 @@ describe("terminal-agent connect inference route", () => { ); }); - it("fails dcode connect when a hostile profile forges markers before a nonzero exit (#8624)", () => { + it("fails dcode connect when a hostile profile forges markers before a nonzero exit (#8624)", async () => { const capture = vi.fn(() => ({ status: 97, output: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", })); const ensureInferenceRoute = vi.fn(() => ({ routeHealthy: true })); - expect(() => + await expect( runTerminalAgentConnectProbe({ agent: dcodeAgent, agentName: "LangChain Deep Agents Code", - capture: capture as never, + commandExecutor: commandExecutorThrough(capture), ensureInferenceRoute, sandboxName: "deep-code", }), - ).toThrow("process.exit(1)"); + ).rejects.toThrow("process.exit(1)"); expect(capture).toHaveBeenCalledOnce(); expect(errorSpy).toHaveBeenCalledWith( diff --git a/src/lib/actions/sandbox/terminal-connect-probe.ts b/src/lib/actions/sandbox/terminal-connect-probe.ts index 0325c815626..6b93251d460 100644 --- a/src/lib/actions/sandbox/terminal-connect-probe.ts +++ b/src/lib/actions/sandbox/terminal-connect-probe.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { captureOpenshell } from "../../adapters/openshell/runtime"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import type { AgentDefinition } from "../../agent/defs"; import * as agentRuntime from "../../agent/runtime"; import { runAgentSmokeCommands } from "../../agent/terminal-smoke"; @@ -12,19 +12,19 @@ export type EnsureTerminalInferenceRoute = ( options: { quiet: true }, ) => { routeHealthy: boolean | null }; -export function runTerminalAgentConnectProbe({ +export async function runTerminalAgentConnectProbe({ agent, agentName, - capture, + commandExecutor, ensureInferenceRoute, sandboxName, }: { agent: AgentDefinition; agentName: string; - capture: typeof captureOpenshell; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; ensureInferenceRoute: EnsureTerminalInferenceRoute; sandboxName: string; -}): void { +}): Promise { const routeResult = ensureInferenceRoute(sandboxName, { quiet: true }); // Dcode is the terminal runtime whose configured inference.local route is // itself part of readiness. Keep this fail-fast agent-scoped so terminal @@ -43,7 +43,7 @@ export function runTerminalAgentConnectProbe({ ); process.exit(1); } - const smokeResult = runAgentSmokeCommands(sandboxName, agent, capture); + const smokeResult = await runAgentSmokeCommands(sandboxName, agent, commandExecutor); if (!smokeResult.ok) { console.error( ` Probe failed: ${agentName} terminal smoke command failed: ${smokeResult.command}`, diff --git a/src/lib/adapters/openshell/client.test.ts b/src/lib/adapters/openshell/client.test.ts index c086eb6d1ca..14d727d5c84 100644 --- a/src/lib/adapters/openshell/client.test.ts +++ b/src/lib/adapters/openshell/client.test.ts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { SpawnSyncReturns } from "node:child_process"; +import type { ChildProcess, SpawnSyncReturns } from "node:child_process"; +import { EventEmitter } from "node:events"; import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -12,6 +13,7 @@ import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { captureOpenshellCommand, captureOpenshellCommandAsync, + captureOpenshellCommandAsyncResult, captureSandboxSshConfigCommand, getInstalledOpenshellVersion, type OpenshellSpawnSync, @@ -448,6 +450,85 @@ describe("openshell helpers", () => { expect(result.signal).toBeTruthy(); }); + it("ignores empty async input so EPIPE cannot replace a successful close", async () => { + const child = new EventEmitter() as EventEmitter & ChildProcess; + const stdin = new EventEmitter() as EventEmitter & { + end: ReturnType; + }; + const stdout = new EventEmitter(); + const stderr = new EventEmitter(); + const observedStdio: unknown[] = []; + stdin.on("error", () => {}); + stdin.end = vi.fn(); + Object.assign(child, { + exitCode: null, + signalCode: null, + stdin, + stdout, + stderr, + kill: vi.fn(() => true), + }); + + const resultPromise = captureOpenshellCommandAsyncResult("openshell", ["status"], { + input: "", + spawnImpl: ((_binary: string, _args: readonly string[], options: { stdio?: unknown }) => { + observedStdio.push(options.stdio); + queueMicrotask(() => { + stdout.emit("data", "READY"); + stdin.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" })); + child.emit("close", 0, null); + }); + return child; + }) as never, + }); + + await expect(resultPromise).resolves.toEqual({ + status: 0, + signal: null, + stdout: "READY", + stderr: "", + }); + expect(observedStdio).toEqual([["ignore", "pipe", "pipe"]]); + expect(stdin.end).not.toHaveBeenCalled(); + }); + + it("returns a structured failure when async process creation throws", async () => { + const error = Object.assign(new Error("spawn openshell EACCES"), { code: "EACCES" }); + + await expect( + captureOpenshellCommandAsyncResult("openshell", ["status"], { + spawnImpl: (() => { + throw error; + }) as never, + }), + ).resolves.toEqual({ + status: null, + signal: null, + stdout: "", + stderr: "", + error, + }); + }); + + it("preserves a concrete async close status after its deadline", async () => { + const result = await captureOpenshellCommandAsync( + process.execPath, + ["-e", "process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000)"], + { + ignoreError: true, + timeout: 100, + killGraceMs: 10, + }, + ); + + expect(result).toEqual({ + status: 0, + output: "", + error: expect.objectContaining({ code: "ETIMEDOUT" }), + signal: null, + }); + }); + it("includes stderr in async capture output when requested", async () => { const result = await captureOpenshellCommandAsync( process.execPath, @@ -480,6 +561,16 @@ describe("openshell helpers", () => { }); }); + it("preserves the legacy unbounded async capture when maxBuffer is supplied", async () => { + const result = await captureOpenshellCommandAsync( + process.execPath, + ["-e", "process.stdout.write('x'.repeat(64))"], + { ignoreError: true, maxBuffer: 8 }, + ); + + expect(result).toEqual({ status: 0, output: "x".repeat(64), signal: null }); + }); + it("uses the injected exit handler on failure", () => { expect(() => runOpenshellCommand("openshell", ["status"], { diff --git a/src/lib/adapters/openshell/client.ts b/src/lib/adapters/openshell/client.ts index c86f15aae17..e9c04395b9f 100644 --- a/src/lib/adapters/openshell/client.ts +++ b/src/lib/adapters/openshell/client.ts @@ -31,6 +31,34 @@ export type OpenshellSpawnSync = ( export type OpenshellSpawn = typeof spawn; +export type OpenshellAsyncCaptureSignalSource = { + add: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; + remove: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; +}; + +export type OpenshellAsyncCaptureLifecycleOptions = Readonly<{ + cwd?: string; + environment?: NodeJS.ProcessEnv; + /** Nonempty input selects a pipe and is always ended. Empty input uses an ignored stdin. */ + input?: string; + killGraceMs?: number; + outputLimitBytes?: number; + signalSource?: OpenshellAsyncCaptureSignalSource; + spawnImpl?: OpenshellSpawn; + timeoutKillSignal?: "SIGTERM" | "SIGKILL"; + timeoutMilliseconds?: number; +}>; + +export type OpenshellAsyncCaptureLifecycleResult = Readonly<{ + status: number | null; + stdout: string; + stderr: string; + error?: Error; + signal: NodeJS.Signals | null; + timedOut?: boolean; + timeoutSignal?: NodeJS.Signals; +}>; + interface OpenshellSpawnOptions { cwd?: string; env?: NodeJS.ProcessEnv; @@ -328,77 +356,243 @@ export function captureOpenshellCommandAsync( args: string[], opts: CaptureOpenshellAsyncOptions = {}, ): Promise { + return captureOpenshellCommandAsyncResult(binary, args, { + cwd: opts.cwd, + environment: openshellSpawnEnv(opts), + killGraceMs: opts.killGraceMs, + spawnImpl: opts.spawnImpl, + timeoutKillSignal: + opts.killSignal === "SIGTERM" || opts.killSignal === "SIGKILL" ? opts.killSignal : undefined, + timeoutMilliseconds: opts.timeout, + }).then((result) => ({ + status: result.status ?? (result.timedOut ? null : 1), + output: `${result.stdout}${shouldIncludeStderr(opts) ? result.stderr : ""}`.trim(), + ...maybeCapturedStreams(result.stdout, result.stderr, opts), + ...(result.error ? { error: result.error } : {}), + signal: result.signal, + })); +} + +/** + * Own the asynchronous OpenShell child-process lifecycle shared by legacy + * status capture and the typed buffered sandbox-command adapter. + */ +export function captureOpenshellCommandAsyncResult( + binary: string, + args: readonly string[], + opts: OpenshellAsyncCaptureLifecycleOptions = {}, +): Promise { const spawnImpl = opts.spawnImpl ?? spawn; return new Promise((resolve) => { - const child = spawnImpl(binary, args, { - cwd: opts.cwd, - env: openshellSpawnEnv(opts), - detached: process.platform !== "win32", - stdio: ["ignore", "pipe", "pipe"], - }) as ChildProcess; - - let stdout = ""; - let stderr = ""; + const hasInput = opts.input !== undefined && opts.input.length > 0; + let child: ChildProcess; + try { + child = spawnImpl(binary, [...args], { + cwd: opts.cwd, + env: opts.environment, + detached: process.platform !== "win32", + stdio: [hasInput ? "pipe" : "ignore", "pipe", "pipe"], + }) as ChildProcess; + } catch (error) { + resolve({ + status: null, + signal: null, + stdout: "", + stderr: "", + error: error instanceof Error ? error : new Error(String(error)), + }); + return; + } + let settled = false; let timedOut = false; - let timeout: NodeJS.Timeout | undefined; - let killTimer: NodeJS.Timeout | undefined; - let forceTimer: NodeJS.Timeout | undefined; - let capturedError: Error | undefined; + let interruptedBy: "SIGTERM" | "SIGINT" | null = null; + let timeoutSignal: NodeJS.Signals | null = null; + let timeoutHandle: NodeJS.Timeout | undefined; + let killHandle: NodeJS.Timeout | undefined; + let forceHandle: NodeJS.Timeout | undefined; + let releaseSignals = () => {}; + let stdoutBytes = 0; + let stderrBytes = 0; + const stdoutChunks: Buffer[] = []; + const stderrChunks: Buffer[] = []; + const outputLimitBytes = + opts.outputLimitBytes === undefined || opts.outputLimitBytes === Number.POSITIVE_INFINITY + ? Number.POSITIVE_INFINITY + : Number.isFinite(opts.outputLimitBytes) + ? Math.max(0, opts.outputLimitBytes) + : 0; + const killGraceMs = opts.killGraceMs ?? 1000; const clearTimers = () => { - if (timeout) clearTimeout(timeout); - if (killTimer) clearTimeout(killTimer); - if (forceTimer) clearTimeout(forceTimer); + if (timeoutHandle) clearTimeout(timeoutHandle); + if (killHandle) clearTimeout(killHandle); + if (forceHandle) clearTimeout(forceHandle); }; - - const buildOutput = () => `${stdout}${shouldIncludeStderr(opts) ? stderr : ""}`.trim(); - - const settle = (status: number | null, signal: NodeJS.Signals | null, error?: Error) => { + const captured = () => ({ + stdout: Buffer.concat(stdoutChunks).toString("utf8"), + stderr: Buffer.concat(stderrChunks).toString("utf8"), + }); + const settle = (result: OpenshellAsyncCaptureLifecycleResult) => { if (settled) return; settled = true; clearTimers(); - resolve({ - status: status ?? (timedOut ? null : 1), - output: buildOutput(), - ...maybeCapturedStreams(stdout, stderr, opts), - ...(error ? { error } : {}), - signal, + releaseSignals(); + resolve(result); + }; + const capture = (stream: "stdout" | "stderr", chunk: Buffer | string) => { + if (settled) return; + const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + const currentBytes = stream === "stdout" ? stdoutBytes : stderrBytes; + const chunks = stream === "stdout" ? stdoutChunks : stderrChunks; + const available = Math.max(0, outputLimitBytes - currentBytes); + if (available > 0) chunks.push(bytes.subarray(0, available)); + if (stream === "stdout") stdoutBytes += bytes.length; + else stderrBytes += bytes.length; + if (bytes.length <= available) return; + const error = Object.assign(new Error(`${stream} exceeded the buffered output limit`), { + code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", }); + signalProcessTree(child, "SIGKILL"); + settle({ status: null, signal: child.signalCode, ...captured(), error }); + }; + const interruptionError = (signal: "SIGTERM" | "SIGINT") => + Object.assign(new Error(`OpenShell command cancelled by ${signal}`), { code: "ECANCELED" }); + const beginInterruption = (signal: "SIGTERM" | "SIGINT") => { + if (settled || timedOut || interruptedBy) return; + interruptedBy = signal; + if (timeoutHandle) clearTimeout(timeoutHandle); + signalProcessTree(child, signal); + killHandle = setTimeout(() => { + signalProcessTree(child, "SIGKILL"); + forceHandle = setTimeout(() => { + child.stdout?.destroy(); + child.stderr?.destroy(); + settle({ + status: null, + signal: "SIGKILL", + ...captured(), + error: interruptionError(signal), + }); + }, killGraceMs); + }, killGraceMs); }; - child.stdout?.setEncoding("utf8"); - child.stderr?.setEncoding("utf8"); - child.stdout?.on("data", (chunk) => { - stdout += chunk; - }); - child.stderr?.on("data", (chunk) => { - stderr += chunk; - }); - child.on("error", (error) => { - capturedError = error; - settle(1, null, error); + if (opts.signalSource) { + const forwardTerm = () => beginInterruption("SIGTERM"); + const forwardInt = () => beginInterruption("SIGINT"); + releaseSignals = () => { + opts.signalSource?.remove("SIGTERM", forwardTerm); + opts.signalSource?.remove("SIGINT", forwardInt); + }; + opts.signalSource.add("SIGTERM", forwardTerm); + opts.signalSource.add("SIGINT", forwardInt); + } + + child.stdout?.on("data", (chunk: Buffer | string) => capture("stdout", chunk)); + child.stderr?.on("data", (chunk: Buffer | string) => capture("stderr", chunk)); + child.once("error", (error) => { + if (timedOut) { + signalProcessTree(child, "SIGKILL"); + settle({ + status: null, + signal: child.signalCode ?? timeoutSignal, + ...captured(), + error: timeoutError(binary, [...args], opts.timeoutMilliseconds as number), + timedOut: true, + ...(timeoutSignal ? { timeoutSignal } : {}), + }); + return; + } + if (interruptedBy) { + signalProcessTree(child, "SIGKILL"); + settle({ + status: null, + signal: child.signalCode ?? interruptedBy, + ...captured(), + error: interruptionError(interruptedBy), + }); + return; + } + settle({ status: null, signal: child.signalCode, ...captured(), error }); }); - child.on("close", (status, signal) => { - settle(status, signal, capturedError); + child.once("close", (status, signal) => { + if (timedOut) { + signalProcessTree(child, "SIGKILL"); + settle({ + status, + signal, + ...captured(), + error: timeoutError(binary, [...args], opts.timeoutMilliseconds as number), + timedOut: true, + ...(timeoutSignal ? { timeoutSignal } : {}), + }); + return; + } + if (interruptedBy) { + signalProcessTree(child, "SIGKILL"); + settle({ + status: null, + signal: signal ?? interruptedBy, + ...captured(), + error: interruptionError(interruptedBy), + }); + return; + } + settle({ status, signal, ...captured() }); }); + if (hasInput) { + child.stdin?.once("error", (error) => { + if (settled) return; + signalProcessTree(child, "SIGKILL"); + settle({ status: null, signal: child.signalCode, ...captured(), error }); + }); + } - if (opts.timeout && opts.timeout > 0) { - timeout = setTimeout(() => { + if ( + opts.timeoutMilliseconds !== undefined && + Number.isFinite(opts.timeoutMilliseconds) && + opts.timeoutMilliseconds > 0 + ) { + timeoutHandle = setTimeout(() => { timedOut = true; - capturedError = timeoutError(binary, args, opts.timeout as number); + timeoutSignal = opts.timeoutKillSignal ?? "SIGTERM"; child.unref(); - signalProcessTree(child, "SIGTERM"); - killTimer = setTimeout(() => { + signalProcessTree(child, timeoutSignal); + if (timeoutSignal === "SIGKILL") { + forceHandle = setTimeout(() => { + child.stdout?.destroy(); + child.stderr?.destroy(); + settle({ + status: null, + signal: "SIGKILL", + ...captured(), + error: timeoutError(binary, [...args], opts.timeoutMilliseconds as number), + timedOut: true, + timeoutSignal: "SIGKILL", + }); + }, killGraceMs); + return; + } + killHandle = setTimeout(() => { + timeoutSignal = "SIGKILL"; signalProcessTree(child, "SIGKILL"); - forceTimer = setTimeout(() => { + forceHandle = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); - settle(null, "SIGKILL", capturedError); - }, opts.killGraceMs ?? 1000); - }, opts.killGraceMs ?? 1000); - }, opts.timeout); + settle({ + status: null, + signal: "SIGKILL", + ...captured(), + error: timeoutError(binary, [...args], opts.timeoutMilliseconds as number), + timedOut: true, + timeoutSignal: "SIGKILL", + }); + }, killGraceMs); + }, killGraceMs); + }, opts.timeoutMilliseconds); } + if (hasInput) child.stdin?.end(opts.input); }); } diff --git a/src/lib/adapters/openshell/sandbox-command-cli.test.ts b/src/lib/adapters/openshell/sandbox-command-cli.test.ts index bf47deda536..e68317a1383 100644 --- a/src/lib/adapters/openshell/sandbox-command-cli.test.ts +++ b/src/lib/adapters/openshell/sandbox-command-cli.test.ts @@ -2,11 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { buildCliOpenShellSandboxExecArgs, createCliOpenShellSandboxCommandExecutor, + createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor, + runCliOpenShellBufferedCommand, + type OpenShellBufferedCommandRunner, type OpenShellCommandChild, type OpenShellCommandSignalSource, } from "./sandbox-command-cli"; @@ -34,6 +40,14 @@ function completedChild( return child; } +function killTestProcess(pid: number): void { + try { + process.kill(pid, "SIGKILL"); + } catch { + // Expected when the command runner already terminated the process group. + } +} + describe("CLI OpenShell sandbox command executor", () => { afterEach(() => { vi.unstubAllEnvs(); @@ -94,6 +108,446 @@ describe("CLI OpenShell sandbox command executor", () => { completed.release(); }); + it("captures a buffered command with explicit target, environment, input, and limits", async () => { + const runBuffered = vi.fn(async () => ({ + status: 42, + signal: null, + stdout: "output\n", + stderr: "warning\n", + })); + const hostEnvironment = { PATH: "/trusted/bin", OPENSHELL_GATEWAY: "nemoclaw-8091" }; + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + runBuffered, + hostCwd: "/repo", + }); + + const completed = await executor.runBuffered({ + sandboxName: "alpha", + target: namedOpenShellGateway("nemoclaw-8091"), + command: ["sh", "-c", "read line; printf '%s' \"$line\""], + environment: hostEnvironment, + sandboxEnvironment: { HOME: "/usr/local/lib/nemoclaw", BASH_ENV: "", ENV: "" }, + input: "hello\n", + tty: false, + workdir: "/sandbox/work", + timeoutMilliseconds: 9000, + outputLimitBytes: 2048, + }); + + expect(completed).toEqual({ + outcome: { kind: "completed", exitCode: 42 }, + stdout: "output\n", + stderr: "warning\n", + }); + expect(runBuffered).toHaveBeenCalledWith( + "/usr/bin/openshell", + [ + "sandbox", + "exec", + "--name", + "alpha", + "-g", + "nemoclaw-8091", + "--workdir", + "/sandbox/work", + "--no-tty", + "--env", + "BASH_ENV=", + "--env", + "ENV=", + "--env", + "HOME=/usr/local/lib/nemoclaw", + "--", + "sh", + "-c", + "read line; printf '%s' \"$line\"", + ], + { + environment: hostEnvironment, + hostCwd: "/repo", + input: "hello\n", + timeoutMilliseconds: 9000, + outputLimitBytes: 2048, + }, + ); + }); + + it("binds buffered execution to retained binary, environment, and currentness", async () => { + const events: string[] = []; + let release!: () => void; + const runBuffered = vi.fn(async (binary, _args, options) => { + events.push(`run:${binary}:${options.environment?.OPENSHELL_GATEWAY ?? "missing"}`); + await new Promise((resolve) => { + release = resolve; + }); + return { status: 0, stdout: "ok", stderr: "" }; + }); + const assertCurrent = vi.fn(() => events.push("current")); + const executor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( + { + resolveBinary: () => "/retained/openshell", + hostCwd: "/repo", + hostEnv: { PATH: "/retained/bin", OPENSHELL_GATEWAY: "receipt-owned" }, + runBuffered, + }, + assertCurrent, + ); + + const pending = executor.runBuffered({ + sandboxName: "alpha", + target: namedOpenShellGateway("receipt-owned"), + command: ["true"], + }); + expect(events).toEqual(["current", "run:/retained/openshell:receipt-owned"]); + release(); + await expect(pending).resolves.toMatchObject({ stdout: "ok" }); + expect(events).toEqual(["current", "run:/retained/openshell:receipt-owned", "current"]); + expect(runBuffered).toHaveBeenCalledWith( + "/retained/openshell", + expect.any(Array), + expect.objectContaining({ + environment: { PATH: "/retained/bin", OPENSHELL_GATEWAY: "receipt-owned" }, + hostCwd: "/repo", + }), + ); + }); + + it("closes buffered stdin when no input is provided", async () => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "process.stdin.on('end', () => process.stdout.write('EOF')); process.stdin.resume();"], + { timeoutMilliseconds: 1000 }, + ); + + expect(result).toMatchObject({ status: 0, stdout: "EOF" }); + expect(result.timedOut).toBeUndefined(); + }); + + it("delivers nonempty buffered stdin exactly", async () => { + const input = "first line\nsecond line\n"; + const result = await runCliOpenShellBufferedCommand( + process.execPath, + [ + "-e", + "let input = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', chunk => input += chunk); process.stdin.on('end', () => process.stdout.write(input));", + ], + { input, timeoutMilliseconds: 1000 }, + ); + + expect(result).toMatchObject({ status: 0, stdout: input, stderr: "" }); + expect(result.error).toBeUndefined(); + }); + + it.each([ + ["stdout", "process.stdout.write('x'.repeat(64))"], + ["stderr", "process.stderr.write('x'.repeat(64))"], + ] as const)("bounds real buffered %s capture", async (stream, script) => { + const result = await runCliOpenShellBufferedCommand(process.execPath, ["-e", script], { + outputLimitBytes: 8, + timeoutMilliseconds: 1000, + }); + + expect(result.status).toBeNull(); + expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe( + "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", + ); + expect(Buffer.byteLength(result[stream])).toBe(8); + }); + + it.each([Number.NaN, Number.NEGATIVE_INFINITY])( + "fails closed for an invalid explicit buffered output limit of %s", + async (outputLimitBytes) => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "process.stdout.write('x')"], + { outputLimitBytes, timeoutMilliseconds: 1000 }, + ); + + expect(result.status).toBeNull(); + expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe( + "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", + ); + expect(result.stdout).toBe(""); + }, + ); + + it.runIf(process.platform !== "win32")( + "forwards host cancellation to the buffered process group and releases handlers", + async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-buffered-cancel-")); + const pidPath = path.join(directory, "descendant.pid"); + const survivorPath = path.join(directory, "descendant-survived"); + const signalEvents = new EventEmitter(); + const signalSource: OpenShellCommandSignalSource = { + add: (signal, listener) => signalEvents.on(signal, listener), + remove: (signal, listener) => signalEvents.off(signal, listener), + }; + let descendantPid: number | undefined; + try { + const descendantScript = [ + "const fs = require('node:fs');", + "process.on('SIGINT', () => {});", + `setTimeout(() => fs.writeFileSync(${JSON.stringify(survivorPath)}, 'alive'), 500);`, + "setInterval(() => {}, 1000);", + ].join(""); + const parentScript = [ + "const { spawn } = require('node:child_process');", + "const fs = require('node:fs');", + `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: 'ignore' });`, + `fs.writeFileSync(${JSON.stringify(pidPath)}, String(child.pid));`, + "process.on('SIGINT', () => process.exit(0));", + "setInterval(() => {}, 1000);", + ].join(""); + const pending = runCliOpenShellBufferedCommand(process.execPath, ["-e", parentScript], { + signalSource, + timeoutMilliseconds: 3000, + }); + await vi.waitFor(() => expect(fs.existsSync(pidPath)).toBe(true)); + signalEvents.emit("SIGINT"); + const result = await pending; + + descendantPid = Number(fs.readFileSync(pidPath, "utf8")); + expect(result).toMatchObject({ status: null, signal: "SIGINT" }); + expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe("ECANCELED"); + expect(signalEvents.listenerCount("SIGTERM")).toBe(0); + expect(signalEvents.listenerCount("SIGINT")).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 600)); + expect(fs.existsSync(survivorPath)).toBe(false); + } finally { + descendantPid === undefined || killTestProcess(descendantPid); + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it("marks only its own buffered deadline as a timeout", async () => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "setInterval(() => {}, 1000)"], + { timeoutMilliseconds: 10 }, + ); + + expect(result).toMatchObject({ status: null, signal: "SIGTERM", timedOut: true }); + }); + + it("keeps the timeout classification when SIGTERM triggers a clean exit", async () => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000)"], + { timeoutMilliseconds: 50 }, + ); + + expect(result).toMatchObject({ status: null, signal: "SIGTERM", timedOut: true }); + }); + + it("escalates a buffered timeout when the child ignores SIGTERM", async () => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"], + { timeoutMilliseconds: 200 }, + ); + + expect(result).toMatchObject({ status: null, signal: "SIGKILL", timedOut: true }); + }); + + it("supports immediate process-group SIGKILL for deadline-bounded probes", async () => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"], + { timeoutMilliseconds: 200, timeoutKillSignal: "SIGKILL" }, + ); + + expect(result).toMatchObject({ status: null, signal: "SIGKILL", timedOut: true }); + }); + + it.runIf(process.platform !== "win32")( + "terminates descendants when the direct buffered child exits cleanly on timeout", + async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-buffered-tree-")); + const pidPath = path.join(directory, "descendant.pid"); + const survivorPath = path.join(directory, "descendant-survived"); + let descendantPid: number | undefined; + try { + const descendantScript = [ + "const fs = require('node:fs');", + "process.on('SIGTERM', () => {});", + `setTimeout(() => fs.writeFileSync(${JSON.stringify(survivorPath)}, 'alive'), 500);`, + "setInterval(() => {}, 1000);", + ].join(""); + const parentScript = [ + "const { spawn } = require('node:child_process');", + "const fs = require('node:fs');", + `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: 'ignore' });`, + `fs.writeFileSync(${JSON.stringify(pidPath)}, String(child.pid));`, + "process.on('SIGTERM', () => process.exit(0));", + "setInterval(() => {}, 1000);", + ].join(""); + + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", parentScript], + { + timeoutMilliseconds: 250, + }, + ); + + descendantPid = Number(fs.readFileSync(pidPath, "utf8")); + expect(result).toMatchObject({ status: null, signal: "SIGTERM", timedOut: true }); + await new Promise((resolve) => setTimeout(resolve, 400)); + expect(fs.existsSync(survivorPath)).toBe(false); + } finally { + descendantPid === undefined || killTestProcess(descendantPid); + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it("terminates a buffered child that closes stdin early but remains alive", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-buffered-epipe-")); + const pidPath = path.join(directory, "child.pid"); + const survivorPath = path.join(directory, "child-survived"); + let childPid: number | undefined; + try { + const script = [ + "const fs = require('node:fs');", + `fs.writeFileSync(${JSON.stringify(pidPath)}, String(process.pid));`, + "fs.closeSync(0);", + `setTimeout(() => fs.writeFileSync(${JSON.stringify(survivorPath)}, 'alive'), 500);`, + "setInterval(() => {}, 1000);", + ].join(""); + const result = await runCliOpenShellBufferedCommand(process.execPath, ["-e", script], { + input: "x".repeat(10 * 1024 * 1024), + timeoutMilliseconds: 3000, + }); + + childPid = Number(fs.readFileSync(pidPath, "utf8")); + expect(result.status).toBeNull(); + expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe("EPIPE"); + expect(result.timedOut).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(fs.existsSync(survivorPath)).toBe(false); + } finally { + childPid === undefined || killTestProcess(childPid); + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + + it("preserves an explicit child signal when a later timeout was configured", async () => { + const result = await runCliOpenShellBufferedCommand( + process.execPath, + ["-e", "process.kill(process.pid, 'SIGTERM')"], + { timeoutMilliseconds: 1000 }, + ); + + expect(result).toMatchObject({ status: null, signal: "SIGTERM" }); + expect(result.timedOut).toBeUndefined(); + expect(result.error).toBeUndefined(); + }); + + it("uses a sanitized host environment when none is supplied", async () => { + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "must-not-leak"); + const runBuffered = vi.fn(async () => ({ + status: 0, + stdout: "", + stderr: "", + })); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + runBuffered, + }); + + await executor.runBuffered({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["true"], + }); + + const options = runBuffered.mock.calls[0]?.[2]; + expect(options?.environment).toBeDefined(); + expect(options?.environment).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); + }); + + it.each([ + ["an unavailable executable", "ENOENT", "unavailable"], + ["a host cancellation", "ECANCELED", "cancelled"], + ["a capture limit", "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", "capture"], + ["an unclassified transport failure", undefined, "invocation"], + ] as const)("maps %s for buffered execution", async (_label, code, kind) => { + const error = Object.assign(new Error("buffered command failed"), code ? { code } : {}); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + runBuffered: async () => ({ status: null, stdout: "partial", stderr: "detail", error }), + }); + + await expect( + executor.runBuffered({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["true"], + }), + ).resolves.toEqual({ + outcome: { kind: "failed", error: { kind, message: "buffered command failed" } }, + stdout: "partial", + stderr: "detail", + }); + }); + + it("maps a real buffered spawn failure to unavailable", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-missing-openshell-")); + try { + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => path.join(dir, "missing-openshell"), + }); + + await expect( + executor.runBuffered({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["true"], + }), + ).resolves.toEqual({ + outcome: { + kind: "failed", + error: { kind: "unavailable", message: expect.stringContaining("ENOENT") }, + }, + stdout: "", + stderr: "", + }); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + it("maps a buffered timeout without treating it as a remote exit", async () => { + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + runBuffered: async () => ({ + status: null, + signal: "SIGTERM", + stdout: "partial", + stderr: "", + timedOut: true, + }), + }); + + await expect( + executor.runBuffered({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["sleep", "30"], + timeoutMilliseconds: 10, + }), + ).resolves.toEqual({ + outcome: { + kind: "failed", + error: { kind: "timeout", message: "OpenShell command timed out" }, + }, + stdout: "partial", + stderr: "", + }); + }); + it("distinguishes an unavailable executable without spawning", async () => { const spawnChild = vi.fn(); const executor = createCliOpenShellSandboxCommandExecutor({ @@ -139,6 +593,7 @@ describe("CLI OpenShell sandbox command executor", () => { it.each([ ["an unavailable executable", "ENOENT", "unavailable"], + ["a host cancellation", "ECANCELED", "cancelled"], ["an unclassified transport failure", undefined, "invocation"], ] as const)("maps an asynchronous child error from %s", async (_label, code, kind) => { const events = new EventEmitter(); @@ -272,4 +727,24 @@ describe("CLI OpenShell sandbox command executor", () => { expect(resolveBinary).not.toHaveBeenCalled(); expect(spawnChild).not.toHaveBeenCalled(); }); + + it("rejects endpoint overrides from the buffered request environment", async () => { + const resolveBinary = vi.fn(() => "/usr/bin/openshell"); + const runBuffered = vi.fn(); + const executor = createCliOpenShellSandboxCommandExecutor({ resolveBinary, runBuffered }); + + await expect( + executor.runBuffered({ + sandboxName: "alpha", + target: namedOpenShellGateway("nemoclaw-8091"), + command: ["true"], + environment: { + PATH: "/usr/bin", + OPENSHELL_GATEWAY_ENDPOINT: "https://sibling.invalid", + }, + }), + ).rejects.toThrow("OPENSHELL_GATEWAY_ENDPOINT is set"); + expect(resolveBinary).not.toHaveBeenCalled(); + expect(runBuffered).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/adapters/openshell/sandbox-command-cli.ts b/src/lib/adapters/openshell/sandbox-command-cli.ts index a310092bd27..34b6bd4cdda 100644 --- a/src/lib/adapters/openshell/sandbox-command-cli.ts +++ b/src/lib/adapters/openshell/sandbox-command-cli.ts @@ -6,8 +6,16 @@ import { spawn, spawnSync, type SpawnSyncReturns } from "node:child_process"; import { spawnExitCode } from "../../core/process-exit"; import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { isValidName } from "../../sandbox-name-contract"; +import { buildSubprocessEnv } from "../../subprocess-env"; +import { + captureOpenshellCommandAsyncResult, + type OpenshellAsyncCaptureSignalSource, +} from "./client"; import { resolveOpenshellBinaryOrNull } from "./resolve-shared"; import { + type OpenShellSandboxBufferedCommandCompletion, + type OpenShellSandboxBufferedCommandRequest, + type OpenShellSandboxBufferedCommandExecutor, type OpenShellSandboxCommandCompletion, type OpenShellSandboxCommandExecutor, type OpenShellSandboxCommandRequest, @@ -35,10 +43,7 @@ export type OpenShellCommandSpawner = ( options: OpenShellCommandChildOptions, ) => OpenShellCommandChild; -export type OpenShellCommandSignalSource = { - add: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; - remove: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; -}; +export type OpenShellCommandSignalSource = OpenshellAsyncCaptureSignalSource; export type OpenShellCommandChildOptions = Readonly<{ stdin?: boolean; @@ -53,6 +58,29 @@ export type OpenShellCommandSpawnResult = Readonly<{ releaseSignals?: () => void; }>; +export type OpenShellBufferedCommandRunResult = Readonly<{ + status: number | null; + signal?: NodeJS.Signals | null; + stdout: string; + stderr: string; + error?: Error; + timedOut?: boolean; +}>; + +export type OpenShellBufferedCommandRunner = ( + binary: string, + args: readonly string[], + options: Readonly<{ + environment?: NodeJS.ProcessEnv; + hostCwd?: string; + input?: string; + outputLimitBytes?: number; + signalSource?: OpenShellCommandSignalSource; + timeoutMilliseconds?: number; + timeoutKillSignal?: "SIGTERM" | "SIGKILL"; + }>, +) => Promise; + export type OpenShellCommandProbeRunner = ( binary: string, args: readonly string[], @@ -62,6 +90,7 @@ export type CliOpenShellSandboxCommandExecutorDeps = Readonly<{ resolveBinary?: () => string | null; spawnChild?: OpenShellCommandSpawner; spawnProbe?: OpenShellCommandProbeRunner; + runBuffered?: OpenShellBufferedCommandRunner; signalSource?: OpenShellCommandSignalSource; hostCwd?: string; hostEnv?: NodeJS.ProcessEnv; @@ -71,11 +100,11 @@ function targetArgs(target: OpenShellGatewayTarget): string[] { return target.kind === "named" ? ["-g", target.gatewayName] : []; } -function assertTarget(target: OpenShellGatewayTarget): void { +function assertTarget(target: OpenShellGatewayTarget, environment = process.env): void { if (target.kind === "named" && !isValidName(target.gatewayName)) { throw new Error("Invalid OpenShell gateway name"); } - assertNoOpenShellGatewayEndpointOverride(); + assertNoOpenShellGatewayEndpointOverride(environment); } function assertSandboxName(sandboxName: string): void { @@ -83,13 +112,20 @@ function assertSandboxName(sandboxName: string): void { } export function buildCliOpenShellSandboxExecArgs( - request: OpenShellSandboxCommandRequest, + request: OpenShellSandboxCommandRequest | OpenShellSandboxBufferedCommandRequest, ): string[] { const argv = ["sandbox", "exec", "--name", request.sandboxName, ...targetArgs(request.target)]; if (request.workdir) argv.push("--workdir", request.workdir); if (request.tty === true) argv.push("--tty"); if (request.tty === false) argv.push("--no-tty"); - if (typeof request.timeoutSeconds === "number") { + if ("sandboxEnvironment" in request && request.sandboxEnvironment) { + for (const [name, value] of Object.entries(request.sandboxEnvironment).sort(([a], [b]) => + a.localeCompare(b), + )) { + argv.push("--env", `${name}=${value}`); + } + } + if ("timeoutSeconds" in request && typeof request.timeoutSeconds === "number") { argv.push("--timeout", String(request.timeoutSeconds)); } argv.push("--", ...request.command); @@ -126,6 +162,46 @@ const defaultSignalSource: OpenShellCommandSignalSource = { remove: (signal, listener) => process.off(signal, listener), }; +const DEFAULT_BUFFERED_OUTPUT_LIMIT_BYTES = 1024 * 1024; + +export const runCliOpenShellBufferedCommand: OpenShellBufferedCommandRunner = async ( + binary, + args, + options, +) => { + try { + const result = await captureOpenshellCommandAsyncResult(binary, args, { + cwd: options.hostCwd, + environment: options.environment, + // Ignored stdin supplies immediate EOF without opening a writable pipe + // that can race a short-lived child with EPIPE. + input: options.input, + outputLimitBytes: options.outputLimitBytes ?? DEFAULT_BUFFERED_OUTPUT_LIMIT_BYTES, + signalSource: options.signalSource ?? defaultSignalSource, + timeoutKillSignal: options.timeoutKillSignal, + timeoutMilliseconds: options.timeoutMilliseconds, + }); + return { + status: result.error ? null : result.status, + signal: result.signal ?? result.timeoutSignal ?? null, + stdout: result.stdout, + stderr: result.stderr, + ...(result.timedOut + ? { timedOut: true } + : result.error + ? { error: result.error, timedOut: false } + : {}), + }; + } catch (error) { + return { + status: null, + stdout: "", + stderr: "", + error: error instanceof Error ? error : new Error(String(error)), + }; + } +}; + export async function runCliOpenShellStreamingCommand( binary: string, args: readonly string[], @@ -170,7 +246,16 @@ export async function runCliOpenShellStreamingCommand( function commandError(error: Error) { const code = (error as NodeJS.ErrnoException).code; return { - kind: code === "ENOENT" ? "unavailable" : code === "ETIMEDOUT" ? "timeout" : "invocation", + kind: + code === "ENOENT" + ? "unavailable" + : code === "ECANCELED" + ? "cancelled" + : code === "ETIMEDOUT" + ? "timeout" + : code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" + ? "capture" + : "invocation", message: error.message, } as const; } @@ -179,6 +264,24 @@ function commandFailure(error: Error): OpenShellSandboxCommandOutcome { return { kind: "failed", error: commandError(error) }; } +function bufferedCommandCompletion( + result: OpenShellBufferedCommandRunResult, +): OpenShellSandboxBufferedCommandCompletion { + const outcome = result.timedOut + ? { + kind: "failed" as const, + error: { kind: "timeout" as const, message: "OpenShell command timed out" }, + } + : result.error + ? commandFailure(result.error) + : { + kind: "completed" as const, + exitCode: spawnExitCode(result), + ...(result.signal ? { signal: result.signal } : {}), + }; + return { outcome, stdout: result.stdout, stderr: result.stderr }; +} + function commandCompletion(result: OpenShellCommandSpawnResult): OpenShellSandboxCommandCompletion { return { outcome: result.error @@ -204,11 +307,12 @@ function unavailableBinary(): OpenShellSandboxCommandCompletion { export function createCliOpenShellSandboxCommandExecutor( deps: CliOpenShellSandboxCommandExecutorDeps = {}, -): OpenShellSandboxCommandExecutor { +): OpenShellSandboxCommandExecutor & OpenShellSandboxBufferedCommandExecutor { const resolveBinary = deps.resolveBinary ?? resolveOpenshellBinaryOrNull; const spawnProbe = deps.spawnProbe ?? ((binary, args) => spawnSync(binary, [...args], { stdio: ["ignore", "ignore", "ignore"] })); + const runBuffered = deps.runBuffered ?? runCliOpenShellBufferedCommand; return { probeDirectory: async (request) => { assertSandboxName(request.sandboxName); @@ -239,6 +343,32 @@ export function createCliOpenShellSandboxCommandExecutor( if (result.status === 0) return { state: "present" }; return result.status === 1 ? { state: "missing" } : { state: "unobservable" }; }, + runBuffered: async (request) => { + assertSandboxName(request.sandboxName); + const environment = request.environment ?? deps.hostEnv ?? buildSubprocessEnv(); + assertTarget(request.target, environment); + const binary = resolveBinary(); + if (!binary) { + return { + outcome: { + kind: "failed", + error: { kind: "unavailable", message: "OpenShell binary not found" }, + }, + stdout: "", + stderr: "", + }; + } + const result = await runBuffered(binary, buildCliOpenShellSandboxExecArgs(request), { + environment, + hostCwd: deps.hostCwd, + input: request.input, + outputLimitBytes: request.outputLimitBytes, + ...(deps.signalSource ? { signalSource: deps.signalSource } : {}), + timeoutMilliseconds: request.timeoutMilliseconds, + ...(request.timeoutKillSignal ? { timeoutKillSignal: request.timeoutKillSignal } : {}), + }); + return bufferedCommandCompletion(result); + }, runStreaming: async (request) => { assertSandboxName(request.sandboxName); assertTarget(request.target); @@ -259,3 +389,20 @@ export function createCliOpenShellSandboxCommandExecutor( }, }; } + +export function createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( + deps: CliOpenShellSandboxCommandExecutorDeps, + assertCurrent: () => void, +): OpenShellSandboxBufferedCommandExecutor { + const executor = createCliOpenShellSandboxCommandExecutor(deps); + return { + runBuffered: async (request) => { + assertCurrent(); + try { + return await executor.runBuffered(request); + } finally { + assertCurrent(); + } + }, + }; +} diff --git a/src/lib/adapters/openshell/sandbox-command.ts b/src/lib/adapters/openshell/sandbox-command.ts index 1639998c8da..cba29829e6c 100644 --- a/src/lib/adapters/openshell/sandbox-command.ts +++ b/src/lib/adapters/openshell/sandbox-command.ts @@ -13,8 +13,24 @@ export type OpenShellSandboxCommandRequest = Readonly<{ stdin?: boolean; }>; +export type OpenShellSandboxBufferedCommandRequest = Readonly<{ + sandboxName: string; + target: OpenShellGatewayTarget; + command: readonly string[]; + /** Environment for the host-side OpenShell process. */ + environment?: NodeJS.ProcessEnv; + /** Environment assignments for the command inside the sandbox. */ + sandboxEnvironment?: Readonly>; + input?: string; + tty?: boolean | null; + workdir?: string; + timeoutMilliseconds?: number; + timeoutKillSignal?: "SIGTERM" | "SIGKILL"; + outputLimitBytes?: number; +}>; + export type OpenShellSandboxCommandError = Readonly<{ - kind: "invocation" | "timeout" | "unavailable"; + kind: "cancelled" | "capture" | "invocation" | "timeout" | "unavailable"; message: string; }>; @@ -38,6 +54,12 @@ export type OpenShellSandboxCommandCompletion = Readonly<{ release: () => void; }>; +export type OpenShellSandboxBufferedCommandCompletion = Readonly<{ + outcome: OpenShellSandboxCommandOutcome; + stdout: string; + stderr: string; +}>; + export type OpenShellSandboxDirectoryProbe = | Readonly<{ state: "present" }> | Readonly<{ state: "missing" }> @@ -52,3 +74,9 @@ export interface OpenShellSandboxCommandExecutor { }): Promise; runStreaming(request: OpenShellSandboxCommandRequest): Promise; } + +export interface OpenShellSandboxBufferedCommandExecutor { + runBuffered( + request: OpenShellSandboxBufferedCommandRequest, + ): Promise; +} diff --git a/src/lib/adapters/sandbox/command-transport.test.ts b/src/lib/adapters/sandbox/command-transport.test.ts index 99ef24f9b12..96bbc45c72d 100644 --- a/src/lib/adapters/sandbox/command-transport.test.ts +++ b/src/lib/adapters/sandbox/command-transport.test.ts @@ -4,6 +4,9 @@ import { spawnSync } from "node:child_process"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../openshell/sandbox-command"; +import { namedOpenShellGateway } from "../openshell/sandbox-observer"; + const mocks = vi.hoisted(() => ({ createTempSshConfig: vi.fn(), resolveOpenshellSandboxSshHost: vi.fn(), @@ -61,10 +64,15 @@ function createDependencies( stderr: "", })), extractSandboxExecCommandStdout: vi.fn((output: string) => output), - getOpenshellBinary: vi.fn(() => "/usr/bin/openshell"), + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: "ok", + stderr: "", + })), + } as OpenShellSandboxBufferedCommandExecutor, isDirectSandboxFallbackUnavailableError: vi.fn(() => false), openshellProbeTimeoutMs: 5000, - root: "/repo", ...overrides, }; } @@ -134,45 +142,45 @@ describe("sandbox command transport", () => { expect(mocks.spawnSync.mock.calls[0]?.[2]).toMatchObject({ timeout: 300_000 }); }); - it("pins OpenShell exec to the requested gateway (#9834)", () => { + it("pins OpenShell exec to the requested gateway (#9834)", async () => { const deps = createDependencies(); - mocks.spawnSync.mockReturnValue(spawnResult("ok")); - expect( + await expect( executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { gatewayName: "recorded-gateway", }), - ).toEqual({ status: 0, stdout: "ok", stderr: "" }); - expect(mocks.spawnSync.mock.calls[0]?.[1]).toEqual([ - "sandbox", - "exec", - "--name", - "alpha", - "-g", - "recorded-gateway", - "--", - "sh", - "-c", - "marked:id", - ]); + ).resolves.toEqual({ status: 0, stdout: "ok", stderr: "" }); + expect(deps.commandExecutor.runBuffered).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: namedOpenShellGateway("recorded-gateway"), + command: ["sh", "-c", "marked:id"], + environment: { PATH: "/usr/bin" }, + timeoutMilliseconds: 9000, + }); }); - it("does not use local Docker fallback for gateway-pinned exec (#9834)", () => { + it("does not use local Docker fallback for gateway-pinned exec (#9834)", async () => { const deps = createDependencies({ extractSandboxExecCommandStdout: vi.fn(() => null), + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed", exitCode: 1 }, + stdout: "untrusted-output", + stderr: "", + })), + } as OpenShellSandboxBufferedCommandExecutor, }); - mocks.spawnSync.mockReturnValue(spawnResult("untrusted-output", { status: 1 })); - expect( + await expect( executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { gatewayName: "recorded-gateway", - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", }), - ).toBeNull(); + ).resolves.toBeNull(); expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); }); - it("uses the local fallback after an inconclusive OpenShell result", () => { + it("does not retry locally after an inconclusive completed OpenShell result", async () => { const events: string[] = []; const deps = createDependencies({ buildSandboxExecMarkedCommand: vi.fn((command: string) => { @@ -191,30 +199,226 @@ describe("sandbox command transport", () => { events.push(`parse:${output}`); return output === "fallback-output" ? "fallback-ok" : null; }), - getOpenshellBinary: vi.fn(() => { - events.push("openshell-resolution"); - return "/usr/bin/openshell"; - }), + commandExecutor: { + runBuffered: vi.fn(async () => { + events.push("openshell-execution"); + return { + outcome: { kind: "completed", exitCode: 1 }, + stdout: "unmarked-output", + stderr: "", + }; + }), + } as OpenShellSandboxBufferedCommandExecutor, }); - mocks.spawnSync.mockImplementation(() => { - events.push("openshell-spawn"); - return spawnResult("unmarked-output", { status: 1 }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, {}), + ).resolves.toBeNull(); + expect(events).toEqual(["mark", "environment", "openshell-execution", "parse:unmarked-output"]); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); + }); + + it.each(["read-only", "reconciled"] as const)( + "uses the %s fallback after an inconclusive completed result", + async (localDockerFallbackPolicy) => { + const deps = createDependencies({ + extractSandboxExecCommandStdout: vi.fn((output: string) => + output === "fallback-output" ? "fallback-ok" : null, + ), + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 1 }, + stdout: "unmarked-output", + stderr: "", + })), + }, + }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy, + }), + ).resolves.toEqual({ status: 0, stdout: "fallback-ok", stderr: "" }); + expect(deps.executePrivilegedSandboxCommand).toHaveBeenCalledOnce(); + }, + ); + + it.each(["read-only", "reconciled"] as const)( + "keeps a marked remote result final under the %s policy", + async (localDockerFallbackPolicy) => { + const deps = createDependencies(); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy, + }), + ).resolves.toEqual({ status: 0, stdout: "ok", stderr: "" }); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, "unavailable-only", "read-only", "reconciled"] as const)( + "uses the %s policy fallback when the OpenShell executable is unavailable", + async (localDockerFallbackPolicy) => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "unavailable" as const, message: "OpenShell binary not found" }, + }, + stdout: "", + stderr: "", + })), + }, + }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + ...(localDockerFallbackPolicy ? { localDockerFallbackPolicy } : {}), + }), + ).resolves.toEqual({ status: 0, stdout: "fallback-output", stderr: "" }); + expect(deps.executePrivilegedSandboxCommand).toHaveBeenCalledOnce(); + }, + ); + + it("does not use the never policy fallback when OpenShell is unavailable", async () => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "unavailable" as const, message: "OpenShell binary not found" }, + }, + stdout: "", + stderr: "", + })), + }, }); - expect(executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, {})).toEqual({ - status: 0, - stderr: "", - stdout: "fallback-ok", + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy: "never", + }), + ).resolves.toBeNull(); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); + }); + + it.each(["cancelled", "timeout", "capture", "invocation"] as const)( + "does not retry a typed %s failure through local Docker", + async (kind) => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "failed" as const, error: { kind, message: `${kind} failure` } }, + stdout: "partial", + stderr: "detail", + })), + }, + }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, {}), + ).resolves.toBeNull(); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ["read-only", "timeout"], + ["read-only", "capture"], + ["read-only", "invocation"], + ["reconciled", "timeout"], + ["reconciled", "capture"], + ["reconciled", "invocation"], + ] as const)( + "uses the %s fallback after a typed %s failure with an unknown outcome", + async (localDockerFallbackPolicy, kind) => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "failed" as const, error: { kind, message: `${kind} failure` } }, + stdout: "partial", + stderr: "detail", + })), + }, + }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy, + }), + ).resolves.toEqual({ status: 0, stdout: "fallback-output", stderr: "" }); + expect(deps.executePrivilegedSandboxCommand).toHaveBeenCalledOnce(); + }, + ); + + it.each(["read-only", "reconciled"] as const)( + "does not use the %s fallback after cancellation", + async (localDockerFallbackPolicy) => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "cancelled" as const, message: "cancelled by SIGINT" }, + }, + stdout: "partial", + stderr: "", + })), + }, + }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy, + }), + ).resolves.toBeNull(); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); + }, + ); + + it("does not catch validation or security refusals and retry through local Docker", async () => { + const refusal = new Error("gateway authority refused"); + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => { + throw refusal; + }), + }, }); - expect(events).toEqual([ - "mark", - "openshell-resolution", - "environment", - "openshell-spawn", - "parse:unmarked-output", - "fallback-execution", - "parse:fallback-output", - ]); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy: "read-only", + }), + ).rejects.toBe(refusal); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); }); + it("propagates a local Docker identity refusal after an eligible fallback", async () => { + const refusal = new Error("sandbox identity changed"); + const deps = createDependencies({ + executePrivilegedSandboxCommand: vi.fn(() => { + throw refusal; + }), + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "timeout" as const, message: "OpenShell command timed out" }, + }, + stdout: "", + stderr: "", + })), + }, + }); + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy: "read-only", + }), + ).rejects.toBe(refusal); + expect(deps.isDirectSandboxFallbackUnavailableError).toHaveBeenCalledWith(refusal); + }); }); diff --git a/src/lib/adapters/sandbox/command-transport.ts b/src/lib/adapters/sandbox/command-transport.ts index 1dac1265978..95bdfa6f31e 100644 --- a/src/lib/adapters/sandbox/command-transport.ts +++ b/src/lib/adapters/sandbox/command-transport.ts @@ -3,6 +3,8 @@ import { spawnSync } from "node:child_process"; import { createTempSshConfig } from "../../sandbox/temp-ssh-config"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../openshell/sandbox-command"; +import { namedOpenShellGateway, selectedOpenShellGateway } from "../openshell/sandbox-observer"; import { resolveOpenshellSandboxSshHost } from "../openshell/sandbox-ssh-host"; export type SandboxCommandResult = { @@ -11,8 +13,15 @@ export type SandboxCommandResult = { stderr: string; }; +/** + * Declares when a command is safe to repeat through the pinned local runtime. + * `read-only` commands cannot leave a mutation to reconcile. `reconciled` + * commands are idempotent and verify their postcondition before continuing. + */ +export type LocalDockerFallbackPolicy = "never" | "unavailable-only" | "read-only" | "reconciled"; + export type SandboxExecCommandOptions = { - allowLocalDockerFallback?: boolean; + localDockerFallbackPolicy?: LocalDockerFallbackPolicy; gatewayName?: string; runtimeEnv?: NodeJS.ProcessEnv; }; @@ -46,10 +55,9 @@ export type CommandTransportDependencies = { readonly error?: unknown; }; extractSandboxExecCommandStdout: (output: string) => string | null; - getOpenshellBinary: () => string; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; isDirectSandboxFallbackUnavailableError: (error: unknown) => boolean; openshellProbeTimeoutMs: number; - root: string; }; export const DEFAULT_SANDBOX_EXEC_TIMEOUT_MS = 15000; @@ -59,6 +67,10 @@ function resolveSandboxExecTimeout(timeout: number): number { return Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; } +function permitsUnknownOutcomeFallback(policy: LocalDockerFallbackPolicy): boolean { + return policy === "read-only" || policy === "reconciled"; +} + export function executeSandboxCommandTransport( deps: CommandTransportDependencies, sandboxName: string, @@ -158,44 +170,42 @@ function executeLocalSandboxCommand( } } -export function executeSandboxExecCommandTransport( +export async function executeSandboxExecCommandTransport( deps: CommandTransportDependencies, sandboxName: string, command: string, timeout: number, options: SandboxExecCommandOptions, -): SandboxCommandResult | null { +): Promise { const markedCommand = deps.buildSandboxExecMarkedCommand(command); const effectiveTimeout = resolveSandboxExecTimeout(timeout); - try { - const gatewayArgs = options.gatewayName ? ["-g", options.gatewayName] : []; - const result = spawnSync( - deps.getOpenshellBinary(), - [ - "sandbox", - "exec", - "--name", - sandboxName, - ...gatewayArgs, - "--", - "sh", - "-c", - markedCommand, - ], - { - cwd: deps.root, - encoding: "utf-8", - env: options.runtimeEnv ?? deps.buildSubprocessEnv(), - stdio: ["ignore", "pipe", "pipe"], - timeout: effectiveTimeout, - }, - ); - const parsed = parseSandboxCommandResult(deps, result); + const fallbackPolicy = options.localDockerFallbackPolicy ?? "unavailable-only"; + const completed = await deps.commandExecutor.runBuffered({ + sandboxName, + target: options.gatewayName + ? namedOpenShellGateway(options.gatewayName) + : selectedOpenShellGateway(), + command: ["sh", "-c", markedCommand], + environment: options.runtimeEnv ?? deps.buildSubprocessEnv(), + timeoutMilliseconds: effectiveTimeout, + }); + if (completed.outcome.kind === "completed") { + const parsed = parseSandboxCommandResult(deps, { + status: completed.outcome.exitCode, + stdout: completed.stdout, + stderr: completed.stderr, + }); if (parsed !== null) return parsed; - } catch { - // OpenShell transport failed; try the trusted direct-container fallback. + if (!permitsUnknownOutcomeFallback(fallbackPolicy)) return null; + } else if (completed.outcome.error.kind === "cancelled") { + return null; + } else if ( + completed.outcome.error.kind !== "unavailable" && + !permitsUnknownOutcomeFallback(fallbackPolicy) + ) { + return null; } - if (options.allowLocalDockerFallback === false) 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); diff --git a/src/lib/agent/binary-availability.ts b/src/lib/agent/binary-availability.ts index ea014d581df..331b552d483 100644 --- a/src/lib/agent/binary-availability.ts +++ b/src/lib/agent/binary-availability.ts @@ -1,14 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { + namedOpenShellGateway, + selectedOpenShellGateway, +} from "../adapters/openshell/sandbox-observer"; import { shellQuote } from "../runner"; import type { AgentDefinition } from "./defs"; -type RunCaptureOpenshell = ( - args: string[], - opts?: { ignoreError?: boolean; includeStderr?: boolean }, -) => string | { status?: number | null; output?: string | null } | null; - export type AgentBinaryAvailability = | { available: true } | { @@ -26,12 +26,12 @@ function agentExecutableName(agent: AgentDefinition): string { return configuredPath.split("/").filter(Boolean).pop() || agent.name; } -export function verifyAgentBinaryAvailable( +export async function verifyAgentBinaryAvailable( sandboxName: string, agent: AgentDefinition, - runCaptureOpenshell: RunCaptureOpenshell, + executor: OpenShellSandboxBufferedCommandExecutor, gatewayName?: string, -): AgentBinaryAvailability { +): Promise { const executable = agentExecutableName(agent); const binaryPath = typeof agent.binary_path === "string" ? agent.binary_path.trim() : ""; // Pi's fail-closed login profile verifies nproc as well as nofile. Ubuntu's @@ -52,30 +52,33 @@ export function verifyAgentBinaryAvailable( `resolved="$(command -v ${shellQuote(executable)} 2>/dev/null || true)"`, `[ -n "$resolved" ] && [ -x "$resolved" ] && echo ${shellQuote(`${AGENT_BINARY_CHECK_PREFIX}ok`)} || echo ${shellQuote(`${AGENT_BINARY_CHECK_PREFIX}not_found`)}`, ].join("; "); - const result = runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", + let result; + try { + result = await executor.runBuffered({ sandboxName, - ...(gatewayName ? ["-g", gatewayName] : []), - "--no-tty", - "--", - shellPath, - "-lc", - script, - ], - { ignoreError: true, includeStderr: true }, - ); - if (typeof result !== "string" && result?.status !== 0) { + target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), + command: [shellPath, "-lc", script], + tty: false, + }); + } catch { + return { available: false, reason: "unobservable", binaryPath: binaryPath || undefined }; + } + if (result.outcome.kind === "failed") { + return { + available: false, + reason: "unobservable", + binaryPath: binaryPath || undefined, + }; + } + if (result.outcome.exitCode !== 0) { return { available: false, reason: "unobservable", binaryPath: binaryPath || undefined, - ...(result ? { transportStatus: result.status ?? null } : {}), + transportStatus: result.outcome.exitCode, }; } - const status = (typeof result === "string" ? result : result?.output)?.trim() ?? ""; + const status = [result.stdout, result.stderr].filter(Boolean).join("\n").trim(); const marker = status .split(/\r?\n/) .map((line) => line.trim()) diff --git a/src/lib/agent/gateway-readiness.test.ts b/src/lib/agent/gateway-readiness.test.ts index 2ae6dba39d9..aa4ff739652 100644 --- a/src/lib/agent/gateway-readiness.test.ts +++ b/src/lib/agent/gateway-readiness.test.ts @@ -14,37 +14,45 @@ function clock() { } describe("waitForAgentGatewayReady", () => { - it("returns immediately when the agent gateway is already ready", () => { + it("returns immediately when the agent gateway is already ready", async () => { const time = clock(); - const probe = vi.fn(() => true); + const probe = vi.fn(async () => true); - expect(waitForAgentGatewayReady({ timeoutSeconds: 60, probe, ...time })).toBe(true); + await expect(waitForAgentGatewayReady({ timeoutSeconds: 60, probe, ...time })).resolves.toBe( + true, + ); expect(probe).toHaveBeenCalledOnce(); expect(time.sleepSeconds).not.toHaveBeenCalled(); }); - it("retries quickly and succeeds before the deadline", () => { + it("retries quickly and succeeds before the deadline", async () => { const time = clock(); - const probe = vi.fn().mockReturnValueOnce(false).mockReturnValue(true); + const probe = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true); - expect(waitForAgentGatewayReady({ timeoutSeconds: 60, probe, ...time })).toBe(true); + await expect(waitForAgentGatewayReady({ timeoutSeconds: 60, probe, ...time })).resolves.toBe( + true, + ); expect(probe).toHaveBeenCalledTimes(2); expect(time.sleepSeconds).toHaveBeenCalledWith(0.25); }); - it("uses the full short deadline before timing out", () => { + it("uses the full short deadline before timing out", async () => { const time = clock(); - const probe = vi.fn(() => false); + const probe = vi.fn(async () => false); - expect(waitForAgentGatewayReady({ timeoutSeconds: 0.1, probe, ...time })).toBe(false); + await expect(waitForAgentGatewayReady({ timeoutSeconds: 0.1, probe, ...time })).resolves.toBe( + false, + ); expect(time.sleepSeconds.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBe(0.1); }); - it("does not probe when the configured deadline is zero", () => { + it("does not probe when the configured deadline is zero", async () => { const time = clock(); - const probe = vi.fn(() => true); + const probe = vi.fn(async () => true); - expect(waitForAgentGatewayReady({ timeoutSeconds: 0, probe, ...time })).toBe(false); + await expect(waitForAgentGatewayReady({ timeoutSeconds: 0, probe, ...time })).resolves.toBe( + false, + ); expect(probe).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/agent/gateway-readiness.ts b/src/lib/agent/gateway-readiness.ts index 3f7e4ea00fb..6c70aee0d61 100644 --- a/src/lib/agent/gateway-readiness.ts +++ b/src/lib/agent/gateway-readiness.ts @@ -1,20 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { waitUntil } from "../core/wait"; +import { waitUntilAsync } from "../core/wait"; import { createReadinessWaitOptions } from "../onboard/readiness-wait"; -export function waitForAgentGatewayReady(options: { +export async function waitForAgentGatewayReady(options: { timeoutSeconds: number; - probe: () => boolean; + probe: () => Promise; sleepSeconds: (seconds: number) => void; now?: () => number; -}): boolean { +}): Promise { const waitOptions = createReadinessWaitOptions({ budgetMs: Math.max(0, options.timeoutSeconds * 1000), maxIntervalMs: 3_000, now: options.now, sleep: (ms) => options.sleepSeconds(ms / 1000), }); - return waitOptions !== null && waitUntil(options.probe, waitOptions); + return waitOptions !== null && (await waitUntilAsync(options.probe, waitOptions)); } diff --git a/src/lib/agent/onboard-terminal.test.ts b/src/lib/agent/onboard-terminal.test.ts index a62402b2485..e05133308b9 100644 --- a/src/lib/agent/onboard-terminal.test.ts +++ b/src/lib/agent/onboard-terminal.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandRequest } from "../adapters/openshell/sandbox-command"; import type { AgentDefinition } from "./defs"; import { loadAgent } from "./defs"; // Import source directly so tests cannot pass against a stale build. @@ -14,7 +15,11 @@ import { recordUnverifiedDeepAgentsRuntimeCall, } from "./onboard-terminal-fixtures"; -type RunCaptureOpenshell = OnboardContext["runCaptureOpenshell"]; +type RunCaptureOpenshell = ( + args: string[], + options?: { ignoreError?: boolean; includeStderr?: boolean; timeout?: number }, +) => string | null; +type StructuredCapture = (args: string[]) => { status: number | null; output: string }; function makeDeepAgentsCodeAgent(): AgentDefinition { return loadAgent("langchain-deepagents-code"); @@ -24,20 +29,48 @@ function makeNemoCuaAgent(): AgentDefinition { return loadAgent("nemocua", { NEMOCLAW_CUA_ENABLED: "1" }); } +function requestAsLegacyArgs(request: OpenShellSandboxBufferedCommandRequest): string[] { + const targetArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const ttyArgs = request.tty === false ? ["--no-tty"] : []; + const args = ["sandbox", "exec", "-n", request.sandboxName, ...targetArgs, ...ttyArgs]; + for (const [key, value] of Object.entries(request.sandboxEnvironment ?? {})) { + args.push("--env", `${key}=${value}`); + } + return [...args, "--", ...request.command]; +} + function createAgentSetupContext( runCaptureOpenshell: RunCaptureOpenshell = vi.fn((_args: string[]) => ""), - captureOpenshell: NonNullable = vi.fn((args, opts) => ({ - status: 0, - output: runCaptureOpenshell(args, opts) ?? "", - })), + captureOpenshell?: StructuredCapture, timing: Pick = {}, ) { + const runBuffered = vi.fn(async (request: OpenShellSandboxBufferedCommandRequest) => { + const isScript = request.command[0] === "/bin/bash" && request.command[1] === "-s"; + const args = requestAsLegacyArgs(request); + const captured = captureOpenshell?.(args); + const output = captured ? captured.output : runCaptureOpenshell(args, { ignoreError: true }); + const capturedCompletion = + output === null + ? { + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "unobservable" }, + }, + stdout: "", + stderr: "", + } + : { + outcome: { kind: "completed" as const, exitCode: captured?.status ?? 0 }, + stdout: output, + stderr: "", + }; + return isScript + ? { outcome: { kind: "completed" as const, exitCode: 0 }, stdout: "", stderr: "" } + : capturedCompletion; + }); return { step: vi.fn((_current: number, _total: number, _message: string) => undefined), - runCaptureOpenshell, - captureOpenshell, - openshellShellCommand: vi.fn(() => "openshell sandbox connect deepagents-code"), - openshellBinary: "/usr/bin/openshell", + sandboxCommandExecutor: { runBuffered }, startRecordedStep: vi.fn(async (_stepName: string, _updates: Record) => { return undefined; }), diff --git a/src/lib/agent/onboard.test.ts b/src/lib/agent/onboard.test.ts index 61769768b0e..c2bd85f9a8d 100644 --- a/src/lib/agent/onboard.test.ts +++ b/src/lib/agent/onboard.test.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; +import type { + OpenShellSandboxBufferedCommandExecutor, + OpenShellSandboxBufferedCommandRequest, +} from "../adapters/openshell/sandbox-command"; // The ready summary resolves the sandbox's API port from the registry. Stub the // lookup so these unit tests never read the developer's real state file. @@ -10,16 +14,6 @@ const getSandboxMock = vi.hoisted(() => ); vi.mock("../state/registry", () => ({ getSandbox: getSandboxMock })); -const mocks = vi.hoisted(() => ({ - run: vi.fn(), -})); - -vi.mock("../runner", async (importOriginal) => ({ - ...(await importOriginal()), - run: mocks.run, -})); - -import { sandboxConfigSyncArgs } from "../onboard/config-sync"; import type { AgentDefinition } from "./defs"; // Import source directly so tests cannot pass against a stale build. import { @@ -30,6 +24,11 @@ import { verifyAgentBinaryAvailable, } from "./onboard"; +type LegacyCapture = ( + args: string[], + options?: { ignoreError?: boolean; includeStderr?: boolean; timeout?: number }, +) => string | null; + function makeAgent(overrides: Partial = {}): AgentDefinition { return { name: "agent", @@ -74,6 +73,45 @@ function makeAgent(overrides: Partial = {}): AgentDefinition { }; } +function requestAsLegacyArgs(request: OpenShellSandboxBufferedCommandRequest): string[] { + const targetArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const ttyArgs = request.tty === false ? ["--no-tty"] : []; + const args = ["sandbox", "exec", "-n", request.sandboxName, ...targetArgs, ...ttyArgs]; + for (const [key, value] of Object.entries(request.sandboxEnvironment ?? {})) { + args.push("--env", `${key}=${value}`); + } + return [...args, "--", ...request.command]; +} + +function legacyBufferedExecutor( + capture: LegacyCapture, +): OpenShellSandboxBufferedCommandExecutor & { runBuffered: ReturnType } { + return { + runBuffered: vi.fn(async (request: OpenShellSandboxBufferedCommandRequest) => { + const isScript = request.command[0] === "/bin/bash" && request.command[1] === "-s"; + const output = capture(requestAsLegacyArgs(request), { ignoreError: true }); + const capturedCompletion = + output === null + ? { + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "unobservable" }, + }, + stdout: "", + stderr: "", + } + : { + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: output, + stderr: "", + }; + return isScript + ? { outcome: { kind: "completed" as const, exitCode: 0 }, stdout: "", stderr: "" } + : capturedCompletion; + }), + }; +} + const apiAgent = makeAgent({ name: "hermes", displayName: "Hermes Agent", @@ -294,16 +332,15 @@ describe("printDashboardUi with port 8642 outside the chat UI (#2078)", () => { describe("agent setup session boundaries", () => { function createAgentSetupContext( - runCaptureOpenshell: OnboardContext["runCaptureOpenshell"] = vi.fn(() => ""), + runCaptureOpenshell: LegacyCapture = vi.fn(() => ""), timing: Pick = {}, identityBoundary: Pick = {}, ) { + const sandboxCommandExecutor = legacyBufferedExecutor(runCaptureOpenshell); return { context: { step: vi.fn(), - runCaptureOpenshell, - openshellShellCommand: vi.fn(() => "openshell sandbox connect sandbox-x"), - openshellBinary: "/usr/bin/openshell", + sandboxCommandExecutor, startRecordedStep: vi.fn(async () => undefined), recordStepComplete: vi.fn(async () => undefined), recordStepFailed: vi.fn(async () => undefined), @@ -311,6 +348,7 @@ describe("agent setup session boundaries", () => { ...timing, ...identityBoundary, }, + runBuffered: sandboxCommandExecutor.runBuffered, }; } @@ -320,7 +358,6 @@ describe("agent setup session boundaries", () => { }); afterEach(() => { - mocks.run.mockReset(); vi.restoreAllMocks(); }); @@ -363,7 +400,7 @@ describe("agent setup session boundaries", () => { it("writes non-default agent configuration through noninteractive sandbox exec", async () => { const runCaptureOpenshell = vi.fn(() => "NEMOCLAW_AGENT_BINARY_CHECK:ok"); - const { context } = createAgentSetupContext(runCaptureOpenshell); + const { context, runBuffered } = createAgentSetupContext(runCaptureOpenshell); const agent = makeAgent({ name: "hermes", healthProbe: { url: "", port: 0, timeout_seconds: 0 }, @@ -371,16 +408,19 @@ describe("agent setup session boundaries", () => { await handleAgentSetup("sandbox-x", "meta-llama", "vllm-local", agent, false, null, context); - expect(mocks.run).toHaveBeenCalledTimes(1); - const [args, options] = mocks.run.mock.calls[0]; - expect(args).toEqual(["/usr/bin/openshell", ...sandboxConfigSyncArgs("sandbox-x")]); - expect(options).toMatchObject({ + const configRequest = runBuffered.mock.calls + .map(([request]) => request) + .find((request) => request.command[0] === "/bin/bash" && request.command[1] === "-s"); + expect(configRequest).toMatchObject({ + sandboxName: "sandbox-x", + target: { kind: "selected" }, + command: ["/bin/bash", "-s"], + tty: false, input: expect.any(String), - stdio: ["pipe", "ignore", "inherit"], }); - expect(options.input).toContain('"provider": "vllm-local"'); - expect(options.input).toContain('"model": "meta-llama"'); - expect(options.input).toContain('"agent": "hermes"'); + expect(configRequest?.input).toContain('"provider": "vllm-local"'); + expect(configRequest?.input).toContain('"model": "meta-llama"'); + expect(configRequest?.input).toContain('"agent": "hermes"'); }); it("retries a configured gateway probe through the supplied scheduler", async () => { @@ -389,7 +429,7 @@ describe("agent setup session boundaries", () => { nowMs += seconds * 1000; }); const runCaptureOpenshell = vi - .fn(() => "ok") + .fn(() => "ok") .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok") .mockReturnValueOnce(""); const { context } = createAgentSetupContext(runCaptureOpenshell, { @@ -427,7 +467,7 @@ describe("agent setup session boundaries", () => { nowMs += seconds * 1000; }); const runCaptureOpenshell = vi - .fn(() => "ok") + .fn(() => "ok") .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok") .mockReturnValueOnce(""); const refuseCompletion = () => { @@ -469,7 +509,7 @@ describe("agent setup session boundaries", () => { nowMs += seconds * 1000; }); const runCaptureOpenshell = vi - .fn(() => "") + .fn(() => "") .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok"); const { context } = createAgentSetupContext(runCaptureOpenshell, { now: () => nowMs, @@ -512,9 +552,7 @@ describe("agent setup session boundaries", () => { healthProbe: { url: "http://localhost:8642/health", port: 8642, timeout_seconds: 1 }, }); - function probeUrlsFrom( - runCaptureOpenshell: ReturnType>, - ): string[] { + function probeUrlsFrom(runCaptureOpenshell: ReturnType>): string[] { return runCaptureOpenshell.mock.calls .map(([args]) => args) .filter((args) => args.includes("curl")) @@ -524,7 +562,7 @@ describe("agent setup session boundaries", () => { it("probes the sandbox's own Hermes API port instead of the manifest default (#9739)", async () => { getSandboxMock.mockReturnValue({ hermesApiPort: 8643 }); const runCaptureOpenshell = vi - .fn(() => "ok") + .fn(() => "ok") .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok"); const { context } = createAgentSetupContext(runCaptureOpenshell); @@ -550,7 +588,7 @@ describe("agent setup session boundaries", () => { it("keeps the manifest probe port for a sandbox that owns the default API port (#9739)", async () => { getSandboxMock.mockReturnValue({ hermesApiPort: 8642 }); const runCaptureOpenshell = vi - .fn(() => "ok") + .fn(() => "ok") .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok"); const { context } = createAgentSetupContext(runCaptureOpenshell); @@ -571,7 +609,7 @@ describe("agent setup session boundaries", () => { it("leaves a non-Hermes probe URL on its manifest port when the registry records a Hermes API port (#9739)", async () => { getSandboxMock.mockReturnValue({ hermesApiPort: 8643 }); const runCaptureOpenshell = vi - .fn(() => "ok") + .fn(() => "ok") .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok"); const { context } = createAgentSetupContext(runCaptureOpenshell); @@ -593,7 +631,7 @@ describe("agent setup session boundaries", () => { it("retargets the resume health probe at the sandbox's own API port (#9739)", async () => { getSandboxMock.mockReturnValue({ hermesApiPort: 8643 }); - const runCaptureOpenshell = vi.fn(() => "ok"); + const runCaptureOpenshell = vi.fn(() => "ok"); const { context } = createAgentSetupContext(runCaptureOpenshell); await handleAgentSetup( @@ -613,46 +651,30 @@ describe("agent setup session boundaries", () => { }); describe("handleAgentSetup guards", () => { - it("accepts an executable configured binary path when PATH lookup is empty", () => { - let script = ""; - const result = verifyAgentBinaryAvailable( + it("accepts an executable configured binary path when PATH lookup is empty", async () => { + const executor = legacyBufferedExecutor( + () => "openshell noise\nNEMOCLAW_AGENT_BINARY_CHECK:ok", + ); + const result = await verifyAgentBinaryAvailable( "alpha", makeAgent({ name: "hermes", binary_path: "/usr/local/bin/hermes" }), - (args) => { - script = String(args.at(-1) || ""); - return "openshell noise\nNEMOCLAW_AGENT_BINARY_CHECK:ok"; - }, + executor, ); expect(result).toEqual({ available: true }); + const script = String(executor.runBuffered.mock.calls[0]?.[0].command.at(-1) ?? ""); expect(script).toContain("if [ -x '/usr/local/bin/hermes' ]; then"); expect(script).toContain("NEMOCLAW_AGENT_BINARY_CHECK:ok"); }); - it("does not reject a configured binary when PATH resolves the symlink target", () => { - let script = ""; - const result = verifyAgentBinaryAvailable( - "alpha", - makeAgent({ name: "hermes", binary_path: "/usr/local/bin/hermes" }), - (args) => { - script = String(args.at(-1) || ""); - return "openshell noise\nNEMOCLAW_AGENT_BINARY_CHECK:ok"; - }, + it("reports a configured binary path that exists but is not executable", async () => { + const executor = legacyBufferedExecutor( + () => "openshell noise\nNEMOCLAW_AGENT_BINARY_CHECK:not_executable", ); - - expect(result).toEqual({ available: true }); - expect(script).toContain("NEMOCLAW_AGENT_BINARY_CHECK:ok"); - }); - - it("reports a configured binary path that exists but is not executable", () => { - let script = ""; - const result = verifyAgentBinaryAvailable( + const result = await verifyAgentBinaryAvailable( "alpha", makeAgent({ name: "hermes", binary_path: "/usr/local/bin/hermes" }), - (args) => { - script = String(args.at(-1) || ""); - return "openshell noise\nNEMOCLAW_AGENT_BINARY_CHECK:not_executable"; - }, + executor, ); expect(result).toEqual({ @@ -660,14 +682,15 @@ describe("handleAgentSetup guards", () => { reason: "not_executable", binaryPath: "/usr/local/bin/hermes", }); + const script = String(executor.runBuffered.mock.calls[0]?.[0].command.at(-1) ?? ""); expect(script).toContain("[ -e '/usr/local/bin/hermes' ] && [ ! -x '/usr/local/bin/hermes' ]"); }); - it("distinguishes an unobservable sandbox exec from a missing binary", () => { - const result = verifyAgentBinaryAvailable( + it("distinguishes an unobservable sandbox exec from a missing binary", async () => { + const result = await verifyAgentBinaryAvailable( "alpha", makeAgent({ name: "pi", binary_path: "/usr/local/bin/pi" }), - () => null, + legacyBufferedExecutor(() => null), ); expect(result).toEqual({ @@ -677,24 +700,30 @@ describe("handleAgentSetup guards", () => { }); }); - it("accepts a marker from a successful structured OpenShell capture", () => { - expect( + it("accepts a marker from a successful buffered OpenShell completion", async () => { + await expect( verifyAgentBinaryAvailable( "alpha", makeAgent({ name: "pi", binary_path: "/usr/local/bin/pi" }), - () => ({ status: 0, output: "NEMOCLAW_AGENT_BINARY_CHECK:ok" }), + legacyBufferedExecutor(() => "NEMOCLAW_AGENT_BINARY_CHECK:ok"), ), - ).toEqual({ available: true }); + ).resolves.toEqual({ available: true }); }); - it("rejects marker text when the structured OpenShell transport failed", () => { - expect( + it("rejects marker text when the buffered command exits unsuccessfully", async () => { + await expect( verifyAgentBinaryAvailable( "alpha", makeAgent({ name: "pi", binary_path: "/usr/local/bin/pi" }), - () => ({ status: 1, output: "NEMOCLAW_AGENT_BINARY_CHECK:ok" }), + { + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 1 }, + stdout: "NEMOCLAW_AGENT_BINARY_CHECK:ok", + stderr: "", + }), + }, ), - ).toEqual({ + ).resolves.toEqual({ available: false, reason: "unobservable", binaryPath: "/usr/local/bin/pi", @@ -702,38 +731,28 @@ describe("handleAgentSetup guards", () => { }); }); - it("targets the owning gateway and disables TTY allocation for the binary probe", () => { - const runCaptureOpenshell = vi.fn(() => "NEMOCLAW_AGENT_BINARY_CHECK:ok"); + it("targets the owning gateway and disables TTY allocation for the binary probe", async () => { + const executor = legacyBufferedExecutor(() => "NEMOCLAW_AGENT_BINARY_CHECK:ok"); - expect( + await expect( verifyAgentBinaryAvailable( "alpha", makeAgent({ name: "pi", binary_path: "/usr/local/bin/pi" }), - runCaptureOpenshell, + executor, "nemoclaw", ), - ).toEqual({ available: true }); - expect(runCaptureOpenshell).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "-n", - "alpha", - "-g", - "nemoclaw", - "--no-tty", - "--", - "/bin/bash", - "-lc", - expect.stringContaining("NEMOCLAW_AGENT_BINARY_CHECK"), - ], - { ignoreError: true, includeStderr: true }, - ); + ).resolves.toEqual({ available: true }); + expect(executor.runBuffered).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw" }, + tty: false, + command: ["/bin/bash", "-lc", expect.stringContaining("NEMOCLAW_AGENT_BINARY_CHECK")], + }); }); }); describe("collectHermesStartupDiagnostics", () => { - it("includes Tirith marker content and binary state when the marker is present", () => { + it("includes Tirith marker content and binary state when the marker is present", async () => { const runCapture = vi.fn(() => [ "tirith marker: download_failed", @@ -743,21 +762,14 @@ describe("collectHermesStartupDiagnostics", () => { ].join("\n"), ); - const diagnostics = collectHermesStartupDiagnostics("alpha", runCapture); + const executor = legacyBufferedExecutor(runCapture); + const diagnostics = await collectHermesStartupDiagnostics("alpha", executor); - expect(runCapture).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-lc", - expect.stringContaining("/sandbox/.hermes/.tirith-install-failed"), - ], - { ignoreError: true }, - ); + expect(executor.runBuffered).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["sh", "-lc", expect.stringContaining("/sandbox/.hermes/.tirith-install-failed")], + }); expect(diagnostics.join("\n")).toContain("Hermes startup diagnostics:"); expect(diagnostics.join("\n")).toContain("tirith marker: download_failed"); expect(diagnostics.join("\n")).toContain( @@ -765,13 +777,15 @@ describe("collectHermesStartupDiagnostics", () => { ); }); - it("returns no extra lines when the Tirith marker is absent", () => { + it("returns no extra lines when the Tirith marker is absent", async () => { const runCapture = vi.fn(() => "tirith marker: absent\n"); - expect(collectHermesStartupDiagnostics("alpha", runCapture)).toEqual([]); + await expect( + collectHermesStartupDiagnostics("alpha", legacyBufferedExecutor(runCapture)), + ).resolves.toEqual([]); }); - it("redacts sensitive values from log tails", () => { + it("redacts sensitive values from log tails", async () => { const slackToken = ["xoxb", "123456789012", "abcdefghijkl"].join("-"); const runCapture = vi.fn(() => [ @@ -782,7 +796,9 @@ describe("collectHermesStartupDiagnostics", () => { ].join("\n"), ); - const output = collectHermesStartupDiagnostics("alpha", runCapture).join("\n"); + const output = ( + await collectHermesStartupDiagnostics("alpha", legacyBufferedExecutor(runCapture)) + ).join("\n"); expect(output).toContain("SLACK_BOT_TOKEN="); expect(output).not.toContain(slackToken); diff --git a/src/lib/agent/onboard.ts b/src/lib/agent/onboard.ts index d020850466f..5ee7b44c8e5 100644 --- a/src/lib/agent/onboard.ts +++ b/src/lib/agent/onboard.ts @@ -6,12 +6,13 @@ // NEMOCLAW_AGENT env var. The OpenClaw path never touches this module. import { buildValidatedCurlCommandArgs } from "../adapters/http/curl-args"; -import type { CaptureOpenshellResult } from "../adapters/openshell/client"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { getAgentBranding } from "../cli/branding"; import type { JsonObject as LooseObject } from "../core/json-types"; import { sleepSeconds } from "../core/wait"; import { getProviderSelectionConfig } from "../inference/config"; -import { runSandboxConfigSync, sandboxConfigSyncArgs } from "../onboard/config-sync"; +import { runSandboxConfigSync } from "../onboard/config-sync"; import { isValidForwardPort } from "../onboard/dashboard-runtime"; import { resolveSandboxHermesApiPort, @@ -26,7 +27,7 @@ export { withHermesApiPortReservationScope, } from "../onboard/hermes-api-port"; -import { redact, run } from "../runner"; +import { redact } from "../runner"; import * as registry from "../state/registry"; import * as baseImage from "./base-image"; import { describeAgentBinaryFailure, verifyAgentBinaryAvailable } from "./binary-availability"; @@ -48,16 +49,7 @@ export { verifyAgentBinaryAvailable } from "./binary-availability"; export interface OnboardContext { step: (current: number, total: number, message: string) => void; - runCaptureOpenshell: ( - args: string[], - opts?: { ignoreError?: boolean; includeStderr?: boolean; timeout?: number }, - ) => string | null; - captureOpenshell?: ( - args: string[], - opts?: { ignoreError?: boolean; includeStderr?: boolean; timeout?: number }, - ) => CaptureOpenshellResult; - openshellShellCommand: (args: string[], options?: { openshellBinary?: string }) => string; - openshellBinary: string; + sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor; gatewayName?: string; startRecordedStep: (stepName: string, updates: LooseObject) => Promise; recordStepComplete: (stepName: string, updates: LooseObject) => Promise; @@ -212,14 +204,21 @@ done * Returns no extra lines when the Tirith marker is absent so non-Tirith * failures keep the existing terse error shape. */ -export function collectHermesStartupDiagnostics( +export async function collectHermesStartupDiagnostics( sandboxName: string, - runCaptureOpenshell: OnboardContext["runCaptureOpenshell"], -): string[] { - const output = runCaptureOpenshell( - ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", HERMES_STARTUP_DIAGNOSTICS_SCRIPT], - { ignoreError: true }, - ); + executor: OpenShellSandboxBufferedCommandExecutor, +): Promise { + let output: string | null = null; + try { + const result = await executor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command: ["sh", "-lc", HERMES_STARTUP_DIAGNOSTICS_SCRIPT], + }); + if (result.outcome.kind === "completed") output = result.stdout || null; + } catch { + // Diagnostics are best effort and must not replace the health failure. + } const redactedOutput = String(redact(output ?? "")); const lines = redactedOutput .split(/\r?\n/) @@ -291,14 +290,14 @@ const AGENT_BINARY_OBSERVATION_ATTEMPTS = 31; const AGENT_BINARY_OBSERVATION_DELAY_SECONDS = 1; /** Retry only an unobservable read-only exec while a newly Ready sandbox settles. */ -function waitForAgentBinaryObservation( +async function waitForAgentBinaryObservation( sandboxName: string, agent: AgentDefinition, - runCaptureOpenshell: Parameters[2], + executor: OpenShellSandboxBufferedCommandExecutor, wait: (seconds: number) => void, gatewayName?: string, -) { - let result = verifyAgentBinaryAvailable(sandboxName, agent, runCaptureOpenshell, gatewayName); +): Promise>> { + let result = await verifyAgentBinaryAvailable(sandboxName, agent, executor, gatewayName); for ( let attempt = 1; !result.available && @@ -307,7 +306,7 @@ function waitForAgentBinaryObservation( attempt += 1 ) { wait(AGENT_BINARY_OBSERVATION_DELAY_SECONDS); - result = verifyAgentBinaryAvailable(sandboxName, agent, runCaptureOpenshell, gatewayName); + result = await verifyAgentBinaryAvailable(sandboxName, agent, executor, gatewayName); } return result; } @@ -328,9 +327,7 @@ export async function handleAgentSetup( ): Promise { const { step, - runCaptureOpenshell, - captureOpenshell, - openshellBinary: openshellBin, + sandboxCommandExecutor, startRecordedStep, recordStepComplete, recordStepFailed, @@ -338,49 +335,52 @@ export async function handleAgentSetup( revalidateSandboxIdentity, } = ctx; - const runSmokeCapture = - agent.name === "langchain-deepagents-code" && captureOpenshell - ? captureOpenshell - : runCaptureOpenshell; - const runBinaryCapture = captureOpenshell ?? runCaptureOpenshell; const waitForBinaryObservation = () => waitForAgentBinaryObservation( sandboxName, agent, - runBinaryCapture, + sandboxCommandExecutor, ctx.sleepSeconds ?? sleep, ctx.gatewayName, ); - const syncNemoClawConfig = (): void => { + const syncNemoClawConfig = async (): Promise => { revalidateSandboxIdentity?.(`synchronize agent configuration in sandbox '${sandboxName}'`); - runSandboxConfigSync(sandboxName, { + await runSandboxConfigSync(sandboxName, { getSelectionConfig: () => { const cfg = getProviderSelectionConfig(provider, model); return cfg ? { ...cfg, agent: agent.name } : null; }, - runConnectScript: (name, scriptContent) => { - run([openshellBin, ...sandboxConfigSyncArgs(name)], { - stdio: ["pipe", "ignore", "inherit"], + runConnectScript: async (name, scriptContent) => { + const result = await sandboxCommandExecutor.runBuffered({ + sandboxName: name, + target: selectedOpenShellGateway(), + command: ["/bin/bash", "-s"], + tty: false, input: scriptContent, }); + if (result.stderr) process.stderr.write(result.stderr); + if (result.outcome.kind === "failed") throw new Error(result.outcome.error.message); + if (result.outcome.exitCode !== 0) { + throw new Error(`OpenShell command failed (exit ${String(result.outcome.exitCode)})`); + } }, }); }; if (resume && sandboxName) { if (isTerminalAgent(agent)) { - const binaryAvailability = waitForBinaryObservation(); + const binaryAvailability = await waitForBinaryObservation(); if (binaryAvailability.available) { - syncNemoClawConfig(); - const smokeResult = runAgentSmokeCommands( + await syncNemoClawConfig(); + const smokeResult = await runAgentSmokeCommands( sandboxName, agent, - runSmokeCapture, + sandboxCommandExecutor, ctx.gatewayName, ); if (smokeResult.ok) { - await enforceTerminalAgentVersion(sandboxName, agent, runCaptureOpenshell, { + await enforceTerminalAgentVersion(sandboxName, agent, sandboxCommandExecutor, { beforeFailure: () => { revalidateSandboxIdentity?.( `start failed agent setup recording for sandbox '${sandboxName}'`, @@ -408,24 +408,23 @@ export async function handleAgentSetup( const probe = agent.healthProbe; if (probe?.url) { const probeUrl = resolveAgentHealthProbeUrl(agent, sandboxName, probe.url); - const result = runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", + let result: string | null = null; + try { + const completion = await sandboxCommandExecutor.runBuffered({ sandboxName, - "--", - "curl", - ...buildValidatedCurlCommandArgs(["-sf", "--max-time", "3", probeUrl]), - ], - { ignoreError: true }, - ); + target: selectedOpenShellGateway(), + command: ["curl", ...buildValidatedCurlCommandArgs(["-sf", "--max-time", "3", probeUrl])], + }); + if (completion.outcome.kind === "completed") result = completion.stdout || null; + } catch { + // A failed resume probe falls through to the normal setup path. + } if (isHealthProbeOk(result)) { // Re-sync `~/.nemoclaw/config.json` even on the resume skip path — // a rebuild destroys/recreates the container and the file reverts // to the Dockerfile's zero-byte placeholder. Mirrors the OpenClaw // path in src/lib/onboard.ts. Fixes #3999 for non-OpenClaw agents. - syncNemoClawConfig(); + await syncNemoClawConfig(); revalidateSandboxIdentity?.(`record resumed agent setup for sandbox '${sandboxName}'`); skippedStepMessage("agent_setup", sandboxName); await recordStepComplete("agent_setup", { sandboxName, provider, model }); @@ -438,7 +437,7 @@ export async function handleAgentSetup( await startRecordedStep("agent_setup", { sandboxName, provider, model }); step(7, 8, `Setting up ${agent.displayName} inside sandbox`); - const binaryAvailability = waitForBinaryObservation(); + const binaryAvailability = await waitForBinaryObservation(); if (!binaryAvailability.available) { await failAgentSetup( sandboxName, @@ -450,10 +449,15 @@ export async function handleAgentSetup( ); } - syncNemoClawConfig(); + await syncNemoClawConfig(); if (isTerminalAgent(agent)) { - const smokeResult = runAgentSmokeCommands(sandboxName, agent, runSmokeCapture, ctx.gatewayName); + const smokeResult = await runAgentSmokeCommands( + sandboxName, + agent, + sandboxCommandExecutor, + ctx.gatewayName, + ); if (!smokeResult.ok) { await failAgentSetup( sandboxName, @@ -464,7 +468,7 @@ export async function handleAgentSetup( revalidateSandboxIdentity, ); } - await enforceTerminalAgentVersion(sandboxName, agent, runCaptureOpenshell, { + await enforceTerminalAgentVersion(sandboxName, agent, sandboxCommandExecutor, { onFailure: (message) => failAgentSetup( sandboxName, @@ -486,24 +490,24 @@ export async function handleAgentSetup( const timeoutSecs = probe.timeout_seconds || 60; const probeUrl = resolveAgentHealthProbeUrl(agent, sandboxName, probe.url); console.log(` Waiting for ${agent.displayName} gateway (up to ${timeoutSecs}s)...`); - const healthy = waitForAgentGatewayReady({ + const healthy = await waitForAgentGatewayReady({ timeoutSeconds: timeoutSecs, now: ctx.now, sleepSeconds: ctx.sleepSeconds ?? sleep, - probe: () => { - const result = runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", + probe: async () => { + try { + const result = await sandboxCommandExecutor.runBuffered({ sandboxName, - "--", - "curl", - ...buildValidatedCurlCommandArgs(["-sf", "--max-time", "3", probeUrl]), - ], - { ignoreError: true }, - ); - return isHealthProbeOk(result); + target: selectedOpenShellGateway(), + command: [ + "curl", + ...buildValidatedCurlCommandArgs(["-sf", "--max-time", "3", probeUrl]), + ], + }); + return result.outcome.kind === "completed" && isHealthProbeOk(result.stdout); + } catch { + return false; + } }, }); if (healthy) { @@ -512,7 +516,7 @@ export async function handleAgentSetup( } else { const diagnostics = agent.name === "hermes" - ? collectHermesStartupDiagnostics(sandboxName, runCaptureOpenshell) + ? await collectHermesStartupDiagnostics(sandboxName, sandboxCommandExecutor) : []; await failAgentSetup( sandboxName, diff --git a/src/lib/agent/terminal-smoke.test.ts b/src/lib/agent/terminal-smoke.test.ts index 1d77297c1ac..f02b4ad67c7 100644 --- a/src/lib/agent/terminal-smoke.test.ts +++ b/src/lib/agent/terminal-smoke.test.ts @@ -4,8 +4,9 @@ import { describe, expect, it, vi } from "vitest"; import { DCODE_MANAGED_EXEC_LAUNCHER } from "../actions/sandbox/connect-inference-route-probe"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { type AgentDefinition, loadAgent } from "./defs"; -import { buildAgentSmokeArgs, runAgentSmokeCommands } from "./terminal-smoke"; +import { buildAgentSmokeRequest, runAgentSmokeCommands } from "./terminal-smoke"; function agent(name: string): AgentDefinition { return { name, runtime: { smoke_commands: ["dcode --version"] } } as unknown as AgentDefinition; @@ -13,113 +14,126 @@ function agent(name: string): AgentDefinition { describe("terminal agent smoke command invocation", () => { it("runs Deep Agents Code smoke commands without adding a login shell (#8624)", () => { - const args = buildAgentSmokeArgs( + const request = buildAgentSmokeRequest( "probe-box", agent("langchain-deepagents-code"), "dcode --version", ); - expect(args).not.toContain("-lc"); - expect(args.join(" ")).not.toContain("sh -lc"); - expect(args).toContain(DCODE_MANAGED_EXEC_LAUNCHER); - expect(args).toContain("HOME=/usr/local/lib/nemoclaw"); - expect(args).toContain("BASH_ENV="); - expect(args).toContain("ENV="); - expect(args.at(-1)).toBe("dcode --version"); + expect(request.command).not.toContain("-lc"); + expect(request.command.join(" ")).not.toContain("sh -lc"); + expect(request.command).toContain(DCODE_MANAGED_EXEC_LAUNCHER); + expect(request.sandboxEnvironment).toEqual({ + HOME: "/usr/local/lib/nemoclaw", + BASH_ENV: "", + ENV: "", + }); + expect(request.command.at(-1)).toBe("dcode --version"); + expect(request.tty).toBe(false); }); it("keeps the login shell for other terminal agents (#8624)", () => { - const args = buildAgentSmokeArgs("probe-box", agent("hermes"), "hermes --version"); + const request = buildAgentSmokeRequest("probe-box", agent("hermes"), "hermes --version"); - expect(args).toContain("-lc"); - expect(args).toContain("/bin/sh"); - expect(args).not.toContain(DCODE_MANAGED_EXEC_LAUNCHER); - expect(args.at(-1)).toBe("hermes --version"); + expect(request.command).toContain("-lc"); + expect(request.command).toContain("/bin/sh"); + expect(request.command).not.toContain(DCODE_MANAGED_EXEC_LAUNCHER); + expect(request.command.at(-1)).toBe("hermes --version"); }); it("uses Bash for Pi's exact resource-limit login profile", () => { - const args = buildAgentSmokeArgs("probe-box", agent("pi"), "pi --version"); + const request = buildAgentSmokeRequest("probe-box", agent("pi"), "pi --version"); - expect(args).toContain("/bin/bash"); - expect(args).toContain("-lc"); - expect(args.at(-3)).toContain('/bin/bash -lc "$1"'); - expect(args.at(-1)).toBe("pi --version"); + expect(request.command).toContain("/bin/bash"); + expect(request.command).toContain("-lc"); + expect(request.command.at(-3)).toContain('/bin/bash -lc "$1"'); + expect(request.command.at(-1)).toBe("pi --version"); }); - it("pins every smoke exec to the owning OpenShell gateway (#8942)", () => { - const capture = vi.fn((_args: string[]) => ({ - status: 0, - output: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", + it("pins every smoke exec to the owning OpenShell gateway (#8942)", async () => { + const runBuffered = vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", + stderr: "", })); - expect( + await expect( runAgentSmokeCommands( "alpha", loadAgent("langchain-deepagents-code"), - capture, + { runBuffered }, "nemoclaw-8091", ), - ).toEqual({ ok: true }); - - expect(capture).toHaveBeenCalled(); - capture.mock.calls.forEach(([args]) => { - expect(args.slice(0, 7)).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "-g", - "nemoclaw-8091", - "--no-tty", - ]); + ).resolves.toEqual({ ok: true }); + + expect(runBuffered).toHaveBeenCalled(); + runBuffered.mock.calls.forEach(([request]) => { + expect(request).toMatchObject({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw-8091" }, + tty: false, + }); }); }); - it("does not add a login shell to Deep Agents Code smoke exec (#8624)", () => { - const issued: string[][] = []; - const result = runAgentSmokeCommands( - "probe-box", - agent("langchain-deepagents-code"), - (args) => { - issued.push(args); + it("does not add a login shell to Deep Agents Code smoke exec (#8624)", async () => { + const issued: unknown[] = []; + const executor: OpenShellSandboxBufferedCommandExecutor = { + runBuffered: async (request) => { + issued.push(request); return { - status: 0, - output: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", + outcome: { kind: "completed", exitCode: 0 }, + stdout: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", + stderr: "", }; }, + }; + const result = await runAgentSmokeCommands( + "probe-box", + agent("langchain-deepagents-code"), + executor, ); expect(result).toEqual({ ok: true }); expect(issued).toHaveLength(1); - expect(issued[0]).not.toContain("-lc"); - expect(issued[0]!.join(" ")).not.toContain("sh -lc"); + expect(issued[0]).toMatchObject({ + command: expect.not.arrayContaining(["-lc"]), + }); }); - it("rejects forged managed markers when the transport exits before the runner (#8624)", () => { - const result = runAgentSmokeCommands("probe-box", agent("langchain-deepagents-code"), () => ({ - status: 97, - output: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", - })); + it("rejects forged managed markers when the transport exits before the runner (#8624)", async () => { + const result = await runAgentSmokeCommands("probe-box", agent("langchain-deepagents-code"), { + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 97 }, + stdout: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", + stderr: "", + }), + }); expect(result).toMatchObject({ ok: false, command: "dcode --version" }); }); - it("rejects string-only managed smoke evidence without transport status (#8624)", () => { - const result = runAgentSmokeCommands( - "probe-box", - agent("langchain-deepagents-code"), - () => "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", - ); + it("rejects a typed transport failure even when output contains success markers (#8624)", async () => { + const result = await runAgentSmokeCommands("probe-box", agent("langchain-deepagents-code"), { + runBuffered: async () => ({ + outcome: { kind: "failed", error: { kind: "invocation", message: "transport failed" } }, + stdout: "NEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:0\n", + stderr: "", + }), + }); expect(result).toMatchObject({ ok: false, command: "dcode --version" }); }); - it("rejects extra marker evidence around the managed runner boundary (#8624)", () => { - const result = runAgentSmokeCommands("probe-box", agent("langchain-deepagents-code"), () => ({ - status: 0, - output: - "NEMOCLAW_AGENT_SMOKE_EXIT:0\nNEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:42\n", - })); + it("rejects extra marker evidence around the managed runner boundary (#8624)", async () => { + const result = await runAgentSmokeCommands("probe-box", agent("langchain-deepagents-code"), { + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: + "NEMOCLAW_AGENT_SMOKE_EXIT:0\nNEMOCLAW_AGENT_SMOKE_BEGIN\nNEMOCLAW_AGENT_SMOKE_EXIT:42\n", + stderr: "", + }), + }); expect(result).toMatchObject({ ok: false, command: "dcode --version" }); }); diff --git a/src/lib/agent/terminal-smoke.ts b/src/lib/agent/terminal-smoke.ts index c103e64ab41..00a566f1e78 100644 --- a/src/lib/agent/terminal-smoke.ts +++ b/src/lib/agent/terminal-smoke.ts @@ -2,13 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { DCODE_MANAGED_EXEC_LAUNCHER } from "../actions/sandbox/connect-inference-route-probe"; +import type { + OpenShellSandboxBufferedCommandExecutor, + OpenShellSandboxBufferedCommandRequest, +} from "../adapters/openshell/sandbox-command"; +import { + namedOpenShellGateway, + selectedOpenShellGateway, +} from "../adapters/openshell/sandbox-observer"; import type { AgentDefinition } from "./defs"; -type RunCaptureOpenshell = ( - args: string[], - opts?: { ignoreError?: boolean; timeout?: number }, -) => string | { status?: number | null; output?: string | null } | null; - const SMOKE_EXIT_MARKER = "NEMOCLAW_AGENT_SMOKE_EXIT:"; const SMOKE_BEGIN_MARKER = "NEMOCLAW_AGENT_SMOKE_BEGIN"; @@ -52,75 +55,63 @@ function smokeRunner(shell: "sh -c" | "sh -lc" | "/bin/bash -lc"): string { * commands rely on profile-provided PATH entries and retain legacy diagnostic * markers. */ -export function buildAgentSmokeArgs( +export function buildAgentSmokeRequest( sandboxName: string, agent: AgentDefinition, command: string, gatewayName?: string, -): string[] { +): OpenShellSandboxBufferedCommandRequest { + const target = gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(); if (agent.name === "langchain-deepagents-code") { - return [ - "sandbox", - "exec", - "-n", + return { sandboxName, - ...(gatewayName ? ["-g", gatewayName] : []), - "--no-tty", - "--env", - "HOME=/usr/local/lib/nemoclaw", - "--env", - "BASH_ENV=", - "--env", - "ENV=", - "--", - DCODE_MANAGED_EXEC_LAUNCHER, - "/bin/sh", - "-c", - smokeRunner("sh -c"), - "nemoclaw-agent-smoke", - command, - ]; + target, + tty: false, + sandboxEnvironment: { HOME: "/usr/local/lib/nemoclaw", BASH_ENV: "", ENV: "" }, + command: [ + DCODE_MANAGED_EXEC_LAUNCHER, + "/bin/sh", + "-c", + smokeRunner("sh -c"), + "nemoclaw-agent-smoke", + command, + ], + }; } // Pi's system shell hooks enforce an exact nproc limit, which Ubuntu /bin/sh // cannot inspect. Use the Bash shell the Pi image provisions. const shellPath = agent.name === "pi" ? "/bin/bash" : "/bin/sh"; const commandShell = agent.name === "pi" ? "/bin/bash -lc" : "sh -lc"; - return [ - "sandbox", - "exec", - "-n", + return { sandboxName, - ...(gatewayName ? ["-g", gatewayName] : []), - "--", - shellPath, - "-lc", - smokeRunner(commandShell), - "nemoclaw-agent-smoke", - command, - ]; + target, + command: [shellPath, "-lc", smokeRunner(commandShell), "nemoclaw-agent-smoke", command], + }; } -export function runAgentSmokeCommands( +export async function runAgentSmokeCommands( sandboxName: string, agent: AgentDefinition, - runCaptureOpenshell: RunCaptureOpenshell, + executor: OpenShellSandboxBufferedCommandExecutor, gatewayName?: string, -): AgentSmokeCommandResult { +): Promise { // smoke_commands are shell-form commands from repository-shipped agents/*/manifest.yaml files. // Switch to argv-form commands before accepting custom or user-provided manifests here. const commands = agent.runtime?.smoke_commands ?? []; for (const command of commands) { - const result = runCaptureOpenshell( - buildAgentSmokeArgs(sandboxName, agent, command, gatewayName), - { - ignoreError: true, - }, - ); - const output = typeof result === "string" ? result : (result?.output ?? null); + let result; + try { + result = await executor.runBuffered( + buildAgentSmokeRequest(sandboxName, agent, command, gatewayName), + ); + } catch { + return { ok: false, command, output: null }; + } + const output = result.stdout || null; const requireManagedBoundary = agent.name === "langchain-deepagents-code"; const exitCode = getSmokeExitCode(output, requireManagedBoundary); const transportFailed = - requireManagedBoundary && (typeof result === "string" || result?.status !== 0); + result.outcome.kind === "failed" || (requireManagedBoundary && result.outcome.exitCode !== 0); if (exitCode !== 0 || transportFailed) { return { ok: false, command, output }; } diff --git a/src/lib/agent/terminal-version-drift.test.ts b/src/lib/agent/terminal-version-drift.test.ts index 5f362643589..b5e1a91370e 100644 --- a/src/lib/agent/terminal-version-drift.test.ts +++ b/src/lib/agent/terminal-version-drift.test.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandExecutor, +} from "../adapters/openshell/sandbox-command"; import type { AgentDefinition } from "./defs"; import { checkTerminalAgentVersion, @@ -19,10 +23,20 @@ function makeAgent(overrides: Partial = {}): AgentDefinition { } as unknown as AgentDefinition; } +function executorWith( + completion: OpenShellSandboxBufferedCommandCompletion, +): OpenShellSandboxBufferedCommandExecutor & { runBuffered: ReturnType } { + return { runBuffered: vi.fn(async () => completion) }; +} + +function completed(stdout: string): OpenShellSandboxBufferedCommandCompletion { + return { outcome: { kind: "completed", exitCode: 0 }, stdout, stderr: "" }; +} + describe("checkTerminalAgentVersion (#6193)", () => { - it("reports stale when the installed version is below expected_version", () => { - const runner = vi.fn(() => "LangChain Deep Agents Code v0.1.12"); - const result = checkTerminalAgentVersion("dcode-sb", makeAgent(), runner); + it("reports stale when the installed version is below expected_version", async () => { + const executor = executorWith(completed("LangChain Deep Agents Code v0.1.12")); + const result = await checkTerminalAgentVersion("dcode-sb", makeAgent(), executor); expect(result).toEqual({ status: "stale", installedVersion: "0.1.12", @@ -31,15 +45,17 @@ describe("checkTerminalAgentVersion (#6193)", () => { }); // Probes through the injected OpenShell runner (not a direct SSH spawn), // bounded by a timeout so a hung version command can't wedge onboarding. - expect(runner).toHaveBeenCalledWith( - ["sandbox", "exec", "-n", "dcode-sb", "--", "sh", "-lc", "dcode --version"], - expect.objectContaining({ ignoreError: true, timeout: expect.any(Number) }), - ); + expect(executor.runBuffered).toHaveBeenCalledWith({ + sandboxName: "dcode-sb", + target: { kind: "selected" }, + command: ["sh", "-lc", "dcode --version"], + timeoutMilliseconds: expect.any(Number), + }); }); - it("reports current when the installed version meets expected_version", () => { - const runner = vi.fn(() => "dcode v0.1.13"); - expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), runner)).toEqual({ + it("reports current when the installed version meets expected_version", async () => { + const executor = executorWith(completed("dcode v0.1.13")); + await expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), executor)).resolves.toEqual({ status: "current", installedVersion: "0.1.13", expectedVersion: "0.1.13", @@ -47,10 +63,10 @@ describe("checkTerminalAgentVersion (#6193)", () => { }); }); - it("uses Bash for Pi's exact resource-limit login profile", () => { - const runner = vi.fn(() => "pi 0.84.1"); + it("uses Bash for Pi's exact resource-limit login profile", async () => { + const executor = executorWith(completed("pi 0.84.1")); - expect( + await expect( checkTerminalAgentVersion( "pi-sb", makeAgent({ @@ -59,38 +75,42 @@ describe("checkTerminalAgentVersion (#6193)", () => { versionCommand: "pi --version", expectedVersion: "0.84.1", }), - runner, + executor, ), - ).toMatchObject({ status: "current", installedVersion: "0.84.1" }); - expect(runner).toHaveBeenCalledWith( - ["sandbox", "exec", "-n", "pi-sb", "--", "/bin/bash", "-lc", "pi --version"], - expect.objectContaining({ ignoreError: true, timeout: expect.any(Number) }), - ); + ).resolves.toMatchObject({ status: "current", installedVersion: "0.84.1" }); + expect(executor.runBuffered).toHaveBeenCalledWith({ + sandboxName: "pi-sb", + target: { kind: "selected" }, + command: ["/bin/bash", "-lc", "pi --version"], + timeoutMilliseconds: expect.any(Number), + }); }); - it("reports current when the installed version exceeds expected_version", () => { - const runner = vi.fn(() => "dcode v0.2.0"); - expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), runner)).toMatchObject({ + it("reports current when the installed version exceeds expected_version", async () => { + const executor = executorWith(completed("dcode v0.2.0")); + await expect( + checkTerminalAgentVersion("dcode-sb", makeAgent(), executor), + ).resolves.toMatchObject({ status: "current", installedVersion: "0.2.0", }); }); - it("does not probe when the manifest declares no expected_version", () => { - const runner = vi.fn(() => "dcode v0.1.12"); + it("does not probe when the manifest declares no expected_version", async () => { + const executor = executorWith(completed("dcode v0.1.12")); const agent = makeAgent({ expectedVersion: null } as Partial); - expect(checkTerminalAgentVersion("dcode-sb", agent, runner)).toEqual({ + await expect(checkTerminalAgentVersion("dcode-sb", agent, executor)).resolves.toEqual({ status: "not-required", installedVersion: null, expectedVersion: null, }); - expect(runner).not.toHaveBeenCalled(); + expect(executor.runBuffered).not.toHaveBeenCalled(); }); - it("reports unverified when the probe output has no parseable version", () => { + it("reports unverified when the probe output has no parseable version", async () => { const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => undefined); - const runner = vi.fn(() => "command not found"); - expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), runner)).toEqual({ + const executor = executorWith(completed("command not found")); + await expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), executor)).resolves.toEqual({ status: "unverified", installedVersion: null, expectedVersion: "0.1.13", @@ -100,10 +120,10 @@ describe("checkTerminalAgentVersion (#6193)", () => { debugSpy.mockRestore(); }); - it("does not attribute an unrelated version when the executable reports no version", () => { + it("does not attribute an unrelated version when the executable reports no version", async () => { const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => undefined); - const runner = vi.fn(() => "Python 3.12.0\ndcode command failed"); - expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), runner)).toEqual({ + const executor = executorWith(completed("Python 3.12.0\ndcode command failed")); + await expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), executor)).resolves.toEqual({ status: "unverified", installedVersion: null, expectedVersion: "0.1.13", @@ -113,10 +133,10 @@ describe("checkTerminalAgentVersion (#6193)", () => { debugSpy.mockRestore(); }); - it("reports unverified when the probe produces no output", () => { + it("reports unverified when the probe produces no output", async () => { const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => undefined); - const runner = vi.fn(() => ({ output: null })); - expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), runner)).toEqual({ + const executor = executorWith(completed("")); + await expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), executor)).resolves.toEqual({ status: "unverified", installedVersion: null, expectedVersion: "0.1.13", @@ -126,12 +146,14 @@ describe("checkTerminalAgentVersion (#6193)", () => { debugSpy.mockRestore(); }); - it("contains runner exceptions as an unverified result", () => { + it("contains runner exceptions as an unverified result", async () => { const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => undefined); - const runner = vi.fn(() => { - throw new Error("probe transport failed"); - }); - expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), runner)).toEqual({ + const executor = { + runBuffered: vi.fn(async () => { + throw new Error("probe transport failed"); + }), + }; + await expect(checkTerminalAgentVersion("dcode-sb", makeAgent(), executor)).resolves.toEqual({ status: "unverified", installedVersion: null, expectedVersion: "0.1.13", @@ -141,24 +163,34 @@ describe("checkTerminalAgentVersion (#6193)", () => { debugSpy.mockRestore(); }); - it("accepts the { output } runner result shape", () => { - const runner = vi.fn(() => ({ output: "dcode v0.1.12" })); - const result = checkTerminalAgentVersion("dcode-sb", makeAgent(), runner); - expect(result).toMatchObject({ status: "stale", installedVersion: "0.1.12" }); + it("contains typed transport failures as an unverified result", async () => { + const executor = executorWith({ + outcome: { kind: "failed", error: { kind: "timeout", message: "timed out" } }, + stdout: "dcode v0.1.12", + stderr: "", + }); + const result = await checkTerminalAgentVersion("dcode-sb", makeAgent(), executor); + expect(result).toMatchObject({ status: "unverified", reason: "probe-failed" }); }); - it.each([ - "dcode 0.1.12, built with SDK 9.8.7", - "built on 2026.7.1, dcode 0.1.12", - ])("uses the CLI version when probe output contains other versions: %s", (output) => { - const result = checkTerminalAgentVersion( - "dcode-sb", - makeAgent(), - vi.fn(() => output), - ); + it("reads version evidence from buffered stdout", async () => { + const executor = executorWith(completed("dcode v0.1.12")); + const result = await checkTerminalAgentVersion("dcode-sb", makeAgent(), executor); expect(result).toMatchObject({ status: "stale", installedVersion: "0.1.12" }); }); + it.each(["dcode 0.1.12, built with SDK 9.8.7", "built on 2026.7.1, dcode 0.1.12"])( + "uses the CLI version when probe output contains other versions: %s", + async (output) => { + const result = await checkTerminalAgentVersion( + "dcode-sb", + makeAgent(), + executorWith(completed(output)), + ); + expect(result).toMatchObject({ status: "stale", installedVersion: "0.1.12" }); + }, + ); + it("formats a stale-version failure with installed and required versions", () => { const line = formatTerminalAgentVersionFailure(makeAgent(), { status: "stale", @@ -172,13 +204,13 @@ describe("checkTerminalAgentVersion (#6193)", () => { expect(line).toContain("below required minimum"); }); - it("describes incomparable version schemes without claiming one is below the other", () => { + it("describes incomparable version schemes without claiming one is below the other", async () => { const stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true); try { - const result = checkTerminalAgentVersion( + const result = await checkTerminalAgentVersion( "dcode-sb", makeAgent({ expectedVersion: "0.17.0", versionScheme: "semver" }), - vi.fn(() => "dcode 2026.5.27"), + executorWith(completed("dcode 2026.5.27")), ); expect(result).toEqual({ status: "stale", diff --git a/src/lib/agent/terminal-version-drift.ts b/src/lib/agent/terminal-version-drift.ts index 4fae00bdc4e..fb8e52cef26 100644 --- a/src/lib/agent/terminal-version-drift.ts +++ b/src/lib/agent/terminal-version-drift.ts @@ -14,15 +14,12 @@ // promoted image and every resumed sandbox satisfy the active manifest. import { parseVersionFromText } from "../adapters/openshell/client"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts"; import { evaluateStaleness } from "../sandbox/version-scheme"; import type { AgentDefinition } from "./defs"; -export type RunCaptureOpenshell = ( - args: string[], - opts?: { ignoreError?: boolean; timeout?: number }, -) => string | { output?: string | null } | null; - export interface TerminalAgentVersionStale { status: "stale"; installedVersion: string; @@ -73,17 +70,17 @@ function unverifiedResult( * `unparseable-output` when the runtime cannot be verified. Unverified probes * never silently pass the version gate. */ -export function checkTerminalAgentVersion( +export async function checkTerminalAgentVersion( sandboxName: string, agent: AgentDefinition, - runCaptureOpenshell: RunCaptureOpenshell, -): TerminalAgentVersionCheck { + executor: OpenShellSandboxBufferedCommandExecutor, +): Promise { const expectedVersion = agent.expectedVersion; if (!expectedVersion) { return { status: "not-required", installedVersion: null, expectedVersion: null }; } - let result: ReturnType; + let result; try { // `version_command` is shell-form input from repository-shipped agent // manifests. Keep this boundary aligned with terminal-smoke.ts; convert it @@ -92,15 +89,20 @@ export function checkTerminalAgentVersion( // Pi's exact resource-limit login profile requires Bash because Ubuntu // /bin/sh cannot inspect nproc. const shellPath = agent.name === "pi" ? "/bin/bash" : "sh"; - result = runCaptureOpenshell( - ["sandbox", "exec", "-n", sandboxName, "--", shellPath, "-lc", agent.versionCommand], - { ignoreError: true, timeout: OPENSHELL_PROBE_TIMEOUT_MS }, - ); + result = await executor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command: [shellPath, "-lc", agent.versionCommand], + timeoutMilliseconds: OPENSHELL_PROBE_TIMEOUT_MS, + }); } catch { return unverifiedResult(sandboxName, expectedVersion, "probe-failed"); } - const output = typeof result === "string" ? result : (result?.output ?? null); + if (result.outcome.kind === "failed") { + return unverifiedResult(sandboxName, expectedVersion, "probe-failed"); + } + const output = result.stdout || null; if (!output) { return unverifiedResult(sandboxName, expectedVersion, "probe-failed"); } diff --git a/src/lib/agent/terminal-version-enforcement.ts b/src/lib/agent/terminal-version-enforcement.ts index a11215cdb79..d13593a5e02 100644 --- a/src/lib/agent/terminal-version-enforcement.ts +++ b/src/lib/agent/terminal-version-enforcement.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import type { AgentDefinition } from "./defs"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { checkTerminalAgentVersion, formatTerminalAgentVersionFailure, - type RunCaptureOpenshell, } from "./terminal-version-drift"; interface TerminalVersionEnforcementOptions { @@ -20,10 +20,10 @@ interface TerminalVersionEnforcementOptions { export async function enforceTerminalAgentVersion( sandboxName: string, agent: AgentDefinition, - runCaptureOpenshell: RunCaptureOpenshell, + executor: OpenShellSandboxBufferedCommandExecutor, options: TerminalVersionEnforcementOptions, ): Promise { - const result = checkTerminalAgentVersion(sandboxName, agent, runCaptureOpenshell); + const result = await checkTerminalAgentVersion(sandboxName, agent, executor); if (result.status === "current" || result.status === "not-required") return; await options.beforeFailure?.(); diff --git a/src/lib/channel-runtime-status.test.ts b/src/lib/channel-runtime-status.test.ts index e6d06dc3c65..8405858ec9d 100644 --- a/src/lib/channel-runtime-status.test.ts +++ b/src/lib/channel-runtime-status.test.ts @@ -18,8 +18,8 @@ import { function makeMockExec( configBody: string | null, logChannelsFound: string[] | null, -): (script: string) => { status: number; stdout: string; stderr: string } | null { - return (script: string) => { +): (script: string) => Promise<{ status: number; stdout: string; stderr: string } | null> { + return async (script: string) => { if (script.startsWith("cat ")) { if (configBody === null) return null; return { status: 0, stdout: configBody, stderr: "" }; @@ -141,24 +141,25 @@ describe("buildGatewayLogScanScript", () => { expect(script).toContain("echo GATEWAY_LOG_PROBED"); }); - it.each( - ["telegram", "discord", "slack", "whatsapp", "wechat", "openclaw-weixin"], - )("isolates the current launch segment with awk before grepping [%s]", (token) => { - // Without launch-segment isolation a stale channel mention from a - // previous gateway run would still satisfy the probe even though the - // *current* OpenClaw process never started the channel (#4156 review). - // The awk filter resets its buffer on every boot/respawn marker so - // only the segment since the last launch reaches grep. - const script = buildGatewayLogScanScript("/tmp/gateway.log"); - expect(script).toContain("(launched|respawning)"); - expect(script).toContain('buf=""'); - expect(script).toContain("grep -iwoE '"); + it.each(["telegram", "discord", "slack", "whatsapp", "wechat", "openclaw-weixin"])( + "isolates the current launch segment with awk before grepping [%s]", + (token) => { + // Without launch-segment isolation a stale channel mention from a + // previous gateway run would still satisfy the probe even though the + // *current* OpenClaw process never started the channel (#4156 review). + // The awk filter resets its buffer on every boot/respawn marker so + // only the segment since the last launch reaches grep. + const script = buildGatewayLogScanScript("/tmp/gateway.log"); + expect(script).toContain("(launched|respawning)"); + expect(script).toContain('buf=""'); + expect(script).toContain("grep -iwoE '"); - expect(script).toContain(token); + expect(script).toContain(token); - expect(script).not.toContain("tail -n"); - expect(script).not.toContain("grep -m 1 -iwF 'telegram'"); - }); + expect(script).not.toContain("tail -n"); + expect(script).not.toContain("grep -m 1 -iwF 'telegram'"); + }, + ); it("escapes single quotes in the log path", () => { const script = buildGatewayLogScanScript("/tmp/odd'path.log"); @@ -270,10 +271,10 @@ describe("buildGatewayLogScanScript end-to-end shell behavior", () => { }); describe("probeChannelRuntimeStatus", () => { - it("returns ok=false when sandbox exec fails", () => { - const result = probeChannelRuntimeStatus({ + it("returns ok=false when sandbox exec fails", async () => { + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", - executeSandboxCommand: () => null, + executeSandboxCommand: async () => null, }); expect(result.ok).toBe(false); expect(result.visibleChannels).toEqual([]); @@ -281,8 +282,8 @@ describe("probeChannelRuntimeStatus", () => { expect(result.logProbeOk).toBe(false); }); - it("returns ok=false when config file is missing or empty", () => { - const result = probeChannelRuntimeStatus({ + it("returns ok=false when config file is missing or empty", async () => { + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", executeSandboxCommand: makeMockExec("", []), }); @@ -290,8 +291,8 @@ describe("probeChannelRuntimeStatus", () => { expect(result.detail).toContain("missing or empty"); }); - it("returns ok=false on invalid JSON", () => { - const result = probeChannelRuntimeStatus({ + it("returns ok=false on invalid JSON", async () => { + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", executeSandboxCommand: makeMockExec("{not json", []), }); @@ -299,11 +300,11 @@ describe("probeChannelRuntimeStatus", () => { expect(result.detail).toContain("not valid JSON"); }); - it("treats a configured channel as visible when the gateway log mentions it", () => { + it("treats a configured channel as visible when the gateway log mentions it", async () => { const config = JSON.stringify({ channels: { telegram: { accounts: { default: { enabled: true } } } }, }); - const result = probeChannelRuntimeStatus({ + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", executeSandboxCommand: makeMockExec(config, ["telegram"]), }); @@ -313,7 +314,7 @@ describe("probeChannelRuntimeStatus", () => { expect(result.configuredButNotRunning).toEqual([]); }); - it("flags a configured channel as not-running when the gateway log never mentions it in the reporter case (#4156)", () => { + it("flags a configured channel as not-running when the gateway log never mentions it in the reporter case (#4156)", async () => { // Reporter symptom: openclaw.json had the telegram block but the // dashboard rendered "No channels found." This is the failure mode — // configured but the OpenClaw runtime never logged anything for it. @@ -326,7 +327,7 @@ describe("probeChannelRuntimeStatus", () => { }, }, }); - const result = probeChannelRuntimeStatus({ + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", executeSandboxCommand: makeMockExec(config, []), }); @@ -336,8 +337,8 @@ describe("probeChannelRuntimeStatus", () => { expect(result.configuredButNotRunning).toEqual(["telegram"]); }); - it("returns empty visible channels when runtime config has no channels block", () => { - const result = probeChannelRuntimeStatus({ + it("returns empty visible channels when runtime config has no channels block", async () => { + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", executeSandboxCommand: makeMockExec(JSON.stringify({ models: {} }), []), }); @@ -346,13 +347,13 @@ describe("probeChannelRuntimeStatus", () => { expect(result.configuredButNotRunning).toEqual([]); }); - it("collapses openclaw-weixin in the log onto the wechat channel name", () => { + it("collapses openclaw-weixin in the log onto the wechat channel name", async () => { const config = JSON.stringify({ channels: { "openclaw-weixin": { accounts: { "acct-1": { enabled: true } } }, }, }); - const result = probeChannelRuntimeStatus({ + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", // Log mentions only the plugin name, not "wechat" executeSandboxCommand: makeMockExec(config, ["openclaw-weixin"]), @@ -361,11 +362,11 @@ describe("probeChannelRuntimeStatus", () => { expect(result.configuredButNotRunning).toEqual([]); }); - it("keeps visibleChannels empty when the gateway log is missing, so callers do not treat an inconclusive probe as healthy", () => { + it("keeps visibleChannels empty when the gateway log is missing, so callers do not treat an inconclusive probe as healthy", async () => { const config = JSON.stringify({ channels: { telegram: { accounts: { default: { enabled: true } } } }, }); - const result = probeChannelRuntimeStatus({ + const result = await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", // logChannelsFound=null = no OK marker emitted = log unreadable executeSandboxCommand: makeMockExec(config, null), @@ -385,11 +386,11 @@ describe("probeChannelRuntimeStatus", () => { expect(result.detail).toContain("unreadable"); }); - it("escapes single quotes in the config file path", () => { + it("escapes single quotes in the config file path", async () => { const captured: string[] = []; - probeChannelRuntimeStatus({ + await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.open'claw/openclaw.json", - executeSandboxCommand: (script: string) => { + executeSandboxCommand: async (script: string) => { captured.push(script); if (script.startsWith("cat ")) return { status: 0, stdout: "{}", stderr: "" }; return { status: 0, stdout: "", stderr: "" }; @@ -398,12 +399,12 @@ describe("probeChannelRuntimeStatus", () => { expect(captured[0]).toContain(`'/sandbox/.open'\\''claw/openclaw.json'`); }); - it("honors a custom gateway log path override", () => { + it("honors a custom gateway log path override", async () => { const captured: string[] = []; - probeChannelRuntimeStatus({ + await probeChannelRuntimeStatus({ configFilePath: "/sandbox/.openclaw/openclaw.json", gatewayLogPath: "/var/log/openclaw/agent.log", - executeSandboxCommand: (script: string) => { + executeSandboxCommand: async (script: string) => { captured.push(script); if (script.startsWith("cat ")) return { status: 0, stdout: "{}", stderr: "" }; return { status: 0, stdout: "", stderr: "" }; diff --git a/src/lib/channel-runtime-status.ts b/src/lib/channel-runtime-status.ts index f6642333fa7..688ed0a5111 100644 --- a/src/lib/channel-runtime-status.ts +++ b/src/lib/channel-runtime-status.ts @@ -99,7 +99,7 @@ export interface ChannelRuntimeStatusDeps { /** Sandbox shell exec — returns `null` when the exec itself failed. */ executeSandboxCommand: ( script: string, - ) => { status: number; stdout: string; stderr: string } | null; + ) => Promise<{ status: number; stdout: string; stderr: string } | null>; } /** @@ -269,9 +269,11 @@ function escapeExtendedRegexLiteral(value: string): string { * desired, decide to fail. The detail string is the one the caller * should render verbatim in a diagnostic hint. */ -export function probeChannelRuntimeStatus(deps: ChannelRuntimeStatusDeps): RuntimeChannelStatus { +export async function probeChannelRuntimeStatus( + deps: ChannelRuntimeStatusDeps, +): Promise { const configFilePath = deps.configFilePath; - const result = deps.executeSandboxCommand( + const result = await deps.executeSandboxCommand( `cat ${shellQuote(configFilePath)} 2>/dev/null || true`, ); if (!result) { @@ -326,7 +328,7 @@ export function probeChannelRuntimeStatus(deps: ChannelRuntimeStatusDeps): Runti // O(file) scan per missing pattern — bounded and predictable. const gatewayLogPath = deps.gatewayLogPath || DEFAULT_GATEWAY_LOG_PATH; const logScript = buildGatewayLogScanScript(gatewayLogPath); - const logResult = deps.executeSandboxCommand(logScript); + const logResult = await deps.executeSandboxCommand(logScript); const logStdout = logResult && typeof logResult.stdout === "string" ? logResult.stdout : ""; const logProbeOk = logStdout.includes(LOG_PROBE_OK_MARKER); if (!logProbeOk) { diff --git a/src/lib/messaging/channels/channel-health.ts b/src/lib/messaging/channels/channel-health.ts index 03996204da4..6088fc547e7 100644 --- a/src/lib/messaging/channels/channel-health.ts +++ b/src/lib/messaging/channels/channel-health.ts @@ -67,7 +67,7 @@ export type ChannelHealthCommandRunner = ( sandboxName: string, command: string, timeoutMs: number, -) => ChannelHealthCommandResult | null | undefined; +) => Promise; /** * Options a channel-health status hook accepts. `executeSandboxCommand` is a diff --git a/src/lib/messaging/channels/openclaw-bridge-health.test.ts b/src/lib/messaging/channels/openclaw-bridge-health.test.ts index b66369f9848..a07e36d03ef 100644 --- a/src/lib/messaging/channels/openclaw-bridge-health.test.ts +++ b/src/lib/messaging/channels/openclaw-bridge-health.test.ts @@ -26,7 +26,7 @@ describe("OpenClaw bridge health hook", () => { { sandboxName: "alpha", log: (message) => logs.push(message), - executeSandboxCommand: (command) => { + executeSandboxCommand: async (command) => { commands.push(command); if (command.includes("openclaw.json")) { return { diff --git a/src/lib/messaging/channels/openclaw-bridge-health.ts b/src/lib/messaging/channels/openclaw-bridge-health.ts index 0cd8f1ac455..77b2a9aa52a 100644 --- a/src/lib/messaging/channels/openclaw-bridge-health.ts +++ b/src/lib/messaging/channels/openclaw-bridge-health.ts @@ -19,7 +19,7 @@ export interface OpenClawBridgeHealthCommandResult { export type OpenClawBridgeHealthCommandRunner = ( command: string, timeoutMs: number, -) => OpenClawBridgeHealthCommandResult | null | undefined; +) => Promise; export interface OpenClawBridgeHealthHookOptions { readonly sandboxName?: string; @@ -58,78 +58,83 @@ export function createOpenClawBridgeHealthHook( throw new Error("OpenClaw bridge health check requires executeSandboxCommand."); } - const log = options.log ?? console.log; - const sandboxName = normalizeSandboxName(options.sandboxName); - const configProbe = execute(`cat ${OPENCLAW_CONFIG_FILE} 2>/dev/null || true`, 10000); - if (!configProbe || configProbe.status !== 0 || !configProbe.stdout) { - log( - ` ⚠ Could not read ${OPENCLAW_CONFIG_FILE} to verify '${spec.channelId}' bridge startup.`, - ); - log(` Run the status command for '${sandboxName}' once the sandbox is fully running.`); - return {}; - } + return (async () => { + const log = options.log ?? console.log; + const sandboxName = normalizeSandboxName(options.sandboxName); + const configProbe = await execute(`cat ${OPENCLAW_CONFIG_FILE} 2>/dev/null || true`, 10000); + if (!configProbe || configProbe.status !== 0 || !configProbe.stdout) { + log( + ` ⚠ Could not read ${OPENCLAW_CONFIG_FILE} to verify '${spec.channelId}' bridge startup.`, + ); + log(` Run the status command for '${sandboxName}' once the sandbox is fully running.`); + return {}; + } - let channelBlock: unknown = null; - let channelEnabled = false; - try { - const cfg = JSON.parse(String(configProbe.stdout)); - channelBlock = getObjectPath(cfg, `channels.${spec.channelId}`); - channelEnabled = Boolean(getObjectPath(channelBlock, "enabled")); - } catch { - // Malformed config: continue to a clear disabled warning. - } + let channelBlock: unknown = null; + let channelEnabled = false; + try { + const cfg = JSON.parse(String(configProbe.stdout)); + channelBlock = getObjectPath(cfg, `channels.${spec.channelId}`); + channelEnabled = Boolean(getObjectPath(channelBlock, "enabled")); + } catch { + // Malformed config: continue to a clear disabled warning. + } - if (!channelEnabled) { - log( - ` ⚠ '${spec.channelId}' channel was not marked enabled in baked ${OPENCLAW_CONFIG_FILE} after rebuild.`, - ); - log( - " The bridge will not start. Re-run the sandbox rebuild or remove and add the channel again.", - ); - return {}; - } + if (!channelEnabled) { + log( + ` ⚠ '${spec.channelId}' channel was not marked enabled in baked ${OPENCLAW_CONFIG_FILE} after rebuild.`, + ); + log( + " The bridge will not start. Re-run the sandbox rebuild or remove and add the channel again.", + ); + return {}; + } - const logLineRegex = new RegExp( - `^\\[${escapeRegExp(spec.channelId)}\\] |^\\[channels\\] \\[${escapeRegExp(spec.channelId)}\\]`, - ); - const logProbe = execute(`tail -n 400 ${OPENCLAW_GATEWAY_LOG_FILE} 2>/dev/null || true`, 10000); - const lines = String(logProbe?.stdout || "") - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line.length > 0 && logLineRegex.test(line)); - if (lines.length === 0) { - log( - ` ⚠ '${spec.channelId}' bridge did not log a startup breadcrumb in ${OPENCLAW_GATEWAY_LOG_FILE} yet.`, + const logLineRegex = new RegExp( + `^\\[${escapeRegExp(spec.channelId)}\\] |^\\[channels\\] \\[${escapeRegExp(spec.channelId)}\\]`, ); - log( - ` Tail it with 'openshell sandbox exec --name ${sandboxName} -- tail -f ${OPENCLAW_GATEWAY_LOG_FILE}' if the channel stays silent.`, + const logProbe = await execute( + `tail -n 400 ${OPENCLAW_GATEWAY_LOG_FILE} 2>/dev/null || true`, + 10000, ); - return {}; - } + const lines = String(logProbe?.stdout || "") + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.length > 0 && logLineRegex.test(line)); + if (lines.length === 0) { + log( + ` ⚠ '${spec.channelId}' bridge did not log a startup breadcrumb in ${OPENCLAW_GATEWAY_LOG_FILE} yet.`, + ); + log( + ` Tail it with 'openshell sandbox exec --name ${sandboxName} -- tail -f ${OPENCLAW_GATEWAY_LOG_FILE}' if the channel stays silent.`, + ); + return {}; + } + + const credentialWarnings = lines.filter((line) => OPENCLAW_BRIDGE_WARNING_PATTERN.test(line)); + if (credentialWarnings.length > 0) { + log(` ⚠ '${spec.channelId}' bridge logged credential/startup warnings:`); + for (const line of credentialWarnings.slice(0, 3)) { + log(` ${line}`); + } + log( + ` Verify the OpenShell provider for ${spec.channelId} holds a valid credential and re-run the sandbox rebuild if needed.`, + ); + return {}; + } - const credentialWarnings = lines.filter((line) => OPENCLAW_BRIDGE_WARNING_PATTERN.test(line)); - if (credentialWarnings.length > 0) { - log(` ⚠ '${spec.channelId}' bridge logged credential/startup warnings:`); - for (const line of credentialWarnings.slice(0, 3)) { - log(` ${line}`); + if (lines.some((line) => OPENCLAW_BRIDGE_POSITIVE_STARTUP_PATTERN.test(line))) { + log(` ✓ '${spec.channelId}' bridge startup detected in sandbox runtime log.`); + spec.onStartupDetected?.({ channelBlock, log }); + return {}; } + + log(` ⚠ '${spec.channelId}' bridge log lines found but no startup confirmation yet.`); log( - ` Verify the OpenShell provider for ${spec.channelId} holds a valid credential and re-run the sandbox rebuild if needed.`, + ` Tail it with 'openshell sandbox exec --name ${sandboxName} -- tail -f ${OPENCLAW_GATEWAY_LOG_FILE}' if the channel stays silent.`, ); return {}; - } - - if (lines.some((line) => OPENCLAW_BRIDGE_POSITIVE_STARTUP_PATTERN.test(line))) { - log(` ✓ '${spec.channelId}' bridge startup detected in sandbox runtime log.`); - spec.onStartupDetected?.({ channelBlock, log }); - return {}; - } - - log(` ⚠ '${spec.channelId}' bridge log lines found but no startup confirmation yet.`); - log( - ` Tail it with 'openshell sandbox exec --name ${sandboxName} -- tail -f ${OPENCLAW_GATEWAY_LOG_FILE}' if the channel stays silent.`, - ); - return {}; + })(); }; } diff --git a/src/lib/messaging/channels/slack/hooks/status-health.test.ts b/src/lib/messaging/channels/slack/hooks/status-health.test.ts index b7aa9c1d6a8..4e81f64ec41 100644 --- a/src/lib/messaging/channels/slack/hooks/status-health.test.ts +++ b/src/lib/messaging/channels/slack/hooks/status-health.test.ts @@ -31,23 +31,23 @@ function context(inputs = BASE_INPUTS): MessagingHookContext { } as unknown as MessagingHookContext; } -function reportOf(result: MessagingHookResult | Promise): ChannelHealthReport { - const output = (result as MessagingHookResult).outputs?.channelHealth; +function reportOf(result: MessagingHookResult): ChannelHealthReport { + const output = result.outputs?.channelHealth; expect(output).toBeDefined(); return (output?.value as unknown as { report: ChannelHealthReport }).report; } -function runProbe( +async function runProbe( account: Record = {}, inputOverrides: Partial = {}, -): { report: ChannelHealthReport; execute: ReturnType } { +): Promise<{ report: ChannelHealthReport; execute: ReturnType }> { const stdout = JSON.stringify({ channels: { slack: { configured: true } }, channelAccounts: { slack: [{ accountId: "default", ...READY_ACCOUNT, ...account }] }, }); - const execute = vi.fn(() => ({ status: 0, stdout, stderr: "" })); + const execute = vi.fn(async () => ({ status: 0, stdout, stderr: "" })); const report = reportOf( - createSlackStatusHealthHook({ executeSandboxCommand: execute })( + await createSlackStatusHealthHook({ executeSandboxCommand: execute })( context({ ...BASE_INPUTS, ...inputOverrides }), ), ); @@ -55,8 +55,8 @@ function runProbe( } describe("slack.statusHealth hook", () => { - it("reports operational readiness for a connected account with a successful probe (#7383)", () => { - const { report, execute } = runProbe({ + it("reports operational readiness for a connected account with a successful probe (#7383)", async () => { + const { report, execute } = await runProbe({ lastProbeAt: Date.parse("2026-08-07T12:00:00.000Z"), probe: { ok: true, bot: { name: "test-bot" } }, }); @@ -83,9 +83,9 @@ describe("slack.statusHealth hook", () => { ); }); - it("keeps deferred Socket Mode initialization retryable without exposing errors or credentials (#7383)", () => { + it("keeps deferred Socket Mode initialization retryable without exposing errors or credentials (#7383)", async () => { const secret = "xoxb-secret-sentinel"; - const { report } = runProbe({ + const { report } = await runProbe({ connected: false, lastError: "socket mode connection timed out", probe: { ok: false, error: "network timeout " + secret }, @@ -105,8 +105,8 @@ describe("slack.statusHealth hook", () => { ["the preset is not registered", { presetApplied: false }, "policy_missing"], ["the preset is not applied", { presetOnGateway: false }, "policy_missing"], ["gateway policy is unknown", { presetOnGateway: null }, "policy_status_unavailable"], - ] as const)("skips the live probe when %s (#7383)", (_condition, inputs, reason) => { - const { report, execute } = runProbe({}, inputs); + ] as const)("skips the live probe when %s (#7383)", async (_condition, inputs, reason) => { + const { report, execute } = await runProbe({}, inputs); expect(report.readiness?.reason).toBe(reason); expect(report.signals.map(({ label }) => label)).toEqual([ @@ -138,9 +138,9 @@ describe("slack.statusHealth hook", () => { ], ] as const)( "classifies %s as terminal (#7383)", - (_condition, account, inputs, expected, signal) => { + async (_condition, account, inputs, expected, signal) => { const [state, category, reason, retryable] = expected; - const report = runProbe(account, inputs).report; + const report = (await runProbe(account, inputs)).report; expect(report.readiness).toMatchObject({ state, category, @@ -151,16 +151,16 @@ describe("slack.statusHealth hook", () => { }, ); - it("returns a null transition time for an out-of-range Slack timestamp (#7383)", () => { + it("returns a null transition time for an out-of-range Slack timestamp (#7383)", async () => { expect( - runProbe({ lastProbeAt: Number.MAX_SAFE_INTEGER }).report.readiness?.lastTransitionAt, + (await runProbe({ lastProbeAt: Number.MAX_SAFE_INTEGER })).report.readiness?.lastTransitionAt, ).toBeNull(); }); - it("keeps an unreachable live status probe retryable until the caller timeout (#7383)", () => { - const execute = vi.fn(() => null); + it("keeps an unreachable live status probe retryable until the caller timeout (#7383)", async () => { + const execute = vi.fn(async () => null); const report = reportOf( - createSlackStatusHealthHook({ executeSandboxCommand: execute })(context()), + await createSlackStatusHealthHook({ executeSandboxCommand: execute })(context()), ); expect(report.readiness).toMatchObject({ diff --git a/src/lib/messaging/channels/slack/hooks/status-health.ts b/src/lib/messaging/channels/slack/hooks/status-health.ts index 9ce40cdd363..36b7b445309 100644 --- a/src/lib/messaging/channels/slack/hooks/status-health.ts +++ b/src/lib/messaging/channels/slack/hooks/status-health.ts @@ -46,27 +46,29 @@ export function createSlackStatusHealthHook( const sandboxName = normalizeString(context.inputs?.currentSandbox); if (!execute || !sandboxName) return {}; - const timeoutMs = - typeof options.timeoutMs === "number" && - Number.isFinite(options.timeoutMs) && - options.timeoutMs > 0 - ? options.timeoutMs - : DEFAULT_CHANNEL_STATUS_HEALTH_TIMEOUT_MS; - const probe = canRunSlackProbe(context.inputs) - ? runSlackStatusProbe(execute, sandboxName, timeoutMs) - : UNREACHABLE_PROBE; - const report = evaluateSlackReadiness(context.inputs, probe); - return { - outputs: { - channelHealth: { - kind: "status", - value: { - type: MESSAGING_CHANNEL_HEALTH_OUTPUT_TYPE, - report, - } as unknown as MessagingSerializableValue, + return (async () => { + const timeoutMs = + typeof options.timeoutMs === "number" && + Number.isFinite(options.timeoutMs) && + options.timeoutMs > 0 + ? options.timeoutMs + : DEFAULT_CHANNEL_STATUS_HEALTH_TIMEOUT_MS; + const probe = canRunSlackProbe(context.inputs) + ? await runSlackStatusProbe(execute, sandboxName, timeoutMs) + : UNREACHABLE_PROBE; + const report = evaluateSlackReadiness(context.inputs, probe); + return { + outputs: { + channelHealth: { + kind: "status", + value: { + type: MESSAGING_CHANNEL_HEALTH_OUTPUT_TYPE, + report, + } as unknown as MessagingSerializableValue, + }, }, - }, - }; + }; + })(); }; } @@ -93,14 +95,14 @@ const UNREACHABLE_PROBE: SlackStatusProbe = { lastTransitionAt: null, }; -function runSlackStatusProbe( +async function runSlackStatusProbe( execute: NonNullable, sandboxName: string, timeoutMs: number, -): SlackStatusProbe { +): Promise { let payload: unknown; try { - const result = execute( + const result = await execute( sandboxName, `openclaw channels status --channel slack --probe --json --timeout ${timeoutMs}`, timeoutMs, diff --git a/src/lib/messaging/channels/telegram/hooks/status-health.test.ts b/src/lib/messaging/channels/telegram/hooks/status-health.test.ts index 1be4eefd9ed..cc6bcf993a2 100644 --- a/src/lib/messaging/channels/telegram/hooks/status-health.test.ts +++ b/src/lib/messaging/channels/telegram/hooks/status-health.test.ts @@ -42,25 +42,24 @@ function probeStdout(logLines: string[], procLines: string[]): string { type ExecResult = { status: number; stdout: string; stderr: string } | null; function makeExec(result: ExecResult) { - return vi.fn((_sandbox: string, _command: string, _timeout: number): ExecResult => result); + return vi.fn( + async (_sandbox: string, _command: string, _timeout: number): Promise => result, + ); } -// The hook is synchronous; the handler type is a sync|Promise union, so narrow. -function reportOf( - result: MessagingHookResult | Promise, -): ChannelHealthReport | undefined { - const value = (result as MessagingHookResult).outputs?.channelHealth?.value as unknown as +function reportOf(result: MessagingHookResult): ChannelHealthReport | undefined { + const value = result.outputs?.channelHealth?.value as unknown as | { report?: ChannelHealthReport } | undefined; return value?.report; } -function outputsOf(result: MessagingHookResult | Promise) { - return (result as MessagingHookResult).outputs; +function outputsOf(result: MessagingHookResult) { + return result.outputs; } describe("telegram.statusHealth hook", () => { - it("probes the gateway log and reports healthy for a ready bridge with inbound (#6743)", () => { + it("probes the gateway log and reports healthy for a ready bridge with inbound (#6743)", async () => { const exec = makeExec({ status: 0, stdout: probeStdout( @@ -72,7 +71,7 @@ describe("telegram.statusHealth hook", () => { ), stderr: "", }); - const result = createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); expect(reportOf(result)?.verdict).toBe("healthy"); // The probe reads the gateway's own breadcrumbs and never calls the Bot API. @@ -83,12 +82,12 @@ describe("telegram.statusHealth hook", () => { expect(command).not.toMatch(/curl/i); }); - it("emits a syntactically valid /bin/sh probe script (#6743)", () => { + it("emits a syntactically valid /bin/sh probe script (#6743)", async () => { // The probe is a multiline sh script (grep/awk pipelines, marker sequencing). // A shell syntax regression would fail every real probe while mocked-stdout // tests stay green, so validate the generated command with `sh -n`. const exec = makeExec({ status: 0, stdout: probeStdout([], []), stderr: "" }); - createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); + await createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); const command = exec.mock.calls[0]?.[1] ?? ""; const validation = spawnSync("sh", ["-n", "-c", command], { encoding: "utf-8" }); expect(validation.status, validation.stderr || validation.stdout).toBe(0); @@ -97,19 +96,19 @@ describe("telegram.statusHealth hook", () => { expect(command).toMatch(/pgrep -fa/); }); - it("reports not_started when pgrep completes with no gateway process", () => { + it("reports not_started when pgrep completes with no gateway process", async () => { const exec = makeExec({ status: 0, stdout: probeStdout([], []), stderr: "" }); - const result = createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); expect(reportOf(result)?.verdict).toBe("not_started"); }); - it("reports probe_failed when the sandbox exec fails", () => { + it("reports probe_failed when the sandbox exec fails", async () => { const exec = makeExec(null); - const result = createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); expect(reportOf(result)?.verdict).toBe("probe_failed"); }); - it("treats a non-zero exec as a failed probe even with healthy-looking stdout (#6887)", () => { + it("treats a non-zero exec as a failed probe even with healthy-looking stdout (#6887)", async () => { // A timed-out/killed exec can still carry partial stdout with a stale // provider-ready line — a non-zero status must not read as healthy. const exec = makeExec({ @@ -122,31 +121,31 @@ describe("telegram.statusHealth hook", () => { ), stderr: "sandbox exec timed out", }); - const result = createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createTelegramStatusHealthHook({ executeSandboxCommand: exec })(context()); expect(reportOf(result)?.verdict).toBe("probe_failed"); }); - it("derives config_gap / policy_gap from the host-fact inputs", () => { + it("derives config_gap / policy_gap from the host-fact inputs", async () => { const exec = makeExec({ status: 0, stdout: probeStdout([], []), stderr: "" }); const hook = createTelegramStatusHealthHook({ executeSandboxCommand: exec }); expect( - reportOf(hook(context({ ...BASE_INPUTS, channelEnabledInRegistry: false })))?.verdict, + reportOf(await hook(context({ ...BASE_INPUTS, channelEnabledInRegistry: false })))?.verdict, ).toBe("config_gap"); - expect(reportOf(hook(context({ ...BASE_INPUTS, presetApplied: false })))?.verdict).toBe( + expect(reportOf(await hook(context({ ...BASE_INPUTS, presetApplied: false })))?.verdict).toBe( "policy_gap", ); }); - it("no-ops for a non-telegram channel or without an exec runner", () => { + it("no-ops for a non-telegram channel or without an exec runner", async () => { const exec = makeExec({ status: 0, stdout: probeStdout([], []), stderr: "" }); expect( outputsOf( - createTelegramStatusHealthHook({ executeSandboxCommand: exec })( + await createTelegramStatusHealthHook({ executeSandboxCommand: exec })( context(BASE_INPUTS, "slack"), ), ), ).toBeUndefined(); - expect(outputsOf(createTelegramStatusHealthHook({})(context()))).toBeUndefined(); + expect(outputsOf(await createTelegramStatusHealthHook({})(context()))).toBeUndefined(); expect(exec).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/messaging/channels/telegram/hooks/status-health.ts b/src/lib/messaging/channels/telegram/hooks/status-health.ts index 039e8ad9905..f298b1cc966 100644 --- a/src/lib/messaging/channels/telegram/hooks/status-health.ts +++ b/src/lib/messaging/channels/telegram/hooks/status-health.ts @@ -53,52 +53,54 @@ export function createTelegramStatusHealthHook( // the top-level status runner does not thread an exec runner into this hook). if (!execute || !sandboxName) return {}; - const timeoutMs = normalizeTimeoutMs(options.timeoutMs); - const exec = execute(sandboxName, buildTelegramProbeScript(), timeoutMs); - const lines = String(exec?.stdout ?? "").split(/\r?\n/); - // A non-zero exec (timeout/kill/unhealthy sandbox) can still carry partial - // stdout with a stale `provider ready` line; require a clean exit so a failed - // probe classifies as probe_failed rather than a false healthy. - const reachable = exec?.status === 0 && lines.includes(TG_SHELL_OK); - - const logStart = lines.indexOf(TG_LOG_BEGIN); - const logEnd = lines.indexOf(TG_LOG_END); - const logLines = - logStart !== -1 && logEnd > logStart - ? lines - .slice(logStart + 1, logEnd) - .map((line) => line.trim()) - .filter(Boolean) - : []; - const breadcrumbs = reachable ? parseTelegramBreadcrumbs(logLines) : null; - - const sawProc = lines.some((line) => line.startsWith("PROC ")); - const sawProcDone = lines.includes(TG_PROC_DONE); - const gatewayProcessAlive = sawProc ? true : sawProcDone ? false : null; - - const input: TelegramProbeInput = { - agent: normalizeString(context.inputs?.agent) ?? "openclaw", - probeReachable: reachable, - gatewayProcessAlive, - breadcrumbs, - probedAt: normalizeString(context.inputs?.probedAt) ?? "", - presetApplied: Boolean(context.inputs?.presetApplied), - presetOnGateway: normalizeTristate(context.inputs?.presetOnGateway), - channelEnabledInRegistry: Boolean(context.inputs?.channelEnabledInRegistry), - }; - - const report = evaluateTelegramDiagnostics(input); - return { - outputs: { - channelHealth: { - kind: "status", - value: { - type: MESSAGING_CHANNEL_HEALTH_OUTPUT_TYPE, - report, - } as unknown as MessagingSerializableValue, + return (async () => { + const timeoutMs = normalizeTimeoutMs(options.timeoutMs); + const exec = await execute(sandboxName, buildTelegramProbeScript(), timeoutMs); + const lines = String(exec?.stdout ?? "").split(/\r?\n/); + // A non-zero exec (timeout/kill/unhealthy sandbox) can still carry partial + // stdout with a stale `provider ready` line; require a clean exit so a failed + // probe classifies as probe_failed rather than a false healthy. + const reachable = exec?.status === 0 && lines.includes(TG_SHELL_OK); + + const logStart = lines.indexOf(TG_LOG_BEGIN); + const logEnd = lines.indexOf(TG_LOG_END); + const logLines = + logStart !== -1 && logEnd > logStart + ? lines + .slice(logStart + 1, logEnd) + .map((line) => line.trim()) + .filter(Boolean) + : []; + const breadcrumbs = reachable ? parseTelegramBreadcrumbs(logLines) : null; + + const sawProc = lines.some((line) => line.startsWith("PROC ")); + const sawProcDone = lines.includes(TG_PROC_DONE); + const gatewayProcessAlive = sawProc ? true : sawProcDone ? false : null; + + const input: TelegramProbeInput = { + agent: normalizeString(context.inputs?.agent) ?? "openclaw", + probeReachable: reachable, + gatewayProcessAlive, + breadcrumbs, + probedAt: normalizeString(context.inputs?.probedAt) ?? "", + presetApplied: Boolean(context.inputs?.presetApplied), + presetOnGateway: normalizeTristate(context.inputs?.presetOnGateway), + channelEnabledInRegistry: Boolean(context.inputs?.channelEnabledInRegistry), + }; + + const report = evaluateTelegramDiagnostics(input); + return { + outputs: { + channelHealth: { + kind: "status", + value: { + type: MESSAGING_CHANNEL_HEALTH_OUTPUT_TYPE, + report, + } as unknown as MessagingSerializableValue, + }, }, - }, - }; + }; + })(); }; } diff --git a/src/lib/messaging/channels/whatsapp/hooks/status-health.test.ts b/src/lib/messaging/channels/whatsapp/hooks/status-health.test.ts index ff54d5cab67..ef4df6e174c 100644 --- a/src/lib/messaging/channels/whatsapp/hooks/status-health.test.ts +++ b/src/lib/messaging/channels/whatsapp/hooks/status-health.test.ts @@ -34,7 +34,7 @@ function context( type ExecResult = { status: number; stdout: string; stderr: string } | null; function makeExec(result: ExecResult) { - return vi.fn((_sandbox: string, _command: string, _timeout: number): ExecResult => result); + return vi.fn(async (_sandbox: string, _command: string, _timeout: number) => result); } // Sequential mock: each invocation of the hook only issues one exec call, but @@ -42,27 +42,25 @@ function makeExec(result: ExecResult) { // list of responses. function makeSequentialExec(results: readonly ExecResult[]) { let call = 0; - return vi.fn((_sandbox: string, _command: string, _timeout: number): ExecResult => { + return vi.fn(async (_sandbox: string, _command: string, _timeout: number) => { const value = results[call] ?? results[results.length - 1] ?? null; call += 1; return value; }); } -function reportOf( - result: MessagingHookResult | Promise, -): ChannelHealthReport | undefined { - const value = (result as MessagingHookResult).outputs?.channelHealth?.value as unknown as +function reportOf(result: MessagingHookResult): ChannelHealthReport | undefined { + const value = result.outputs?.channelHealth?.value as unknown as | { report?: ChannelHealthReport } | undefined; return value?.report; } -function outputsOf(result: MessagingHookResult | Promise) { - return (result as MessagingHookResult).outputs; +function outputsOf(result: MessagingHookResult) { + return result.outputs; } -function stringifyReport(result: MessagingHookResult | Promise): string { +function stringifyReport(result: MessagingHookResult): string { return JSON.stringify(reportOf(result)); } @@ -123,7 +121,7 @@ function hermesExec(options: { }) { const hasCreds = (credsFile: string) => options.credsDirs.some((dir) => credsFile === `${dir}/creds.json`); - return vi.fn((_sandbox: string, command: string, _timeout: number): ExecResult => { + return vi.fn(async (_sandbox: string, command: string, _timeout: number) => { return command.startsWith("python3 -c ") ? options.configProbeStdout !== undefined ? { status: 0, stdout: options.configProbeStdout, stderr: "" } @@ -205,9 +203,9 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { verdict: "idle", }, { label: "unpaired: linked=false", wa: UNPAIRED_WA, verdict: "unpaired" }, - ] as const)("reports verdict $verdict for $label", ({ wa, verdict }) => { + ] as const)("reports verdict $verdict for $label", async ({ wa, verdict }) => { const exec = makeExec({ status: 0, stdout: openclawJson(wa), stderr: "" }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); expect(reportOf(result)?.verdict).toBe(verdict); // The healthy path is the only case that must produce `healthy` — every // non-healthy fixture must render as something else so the PRA-1 root @@ -215,10 +213,10 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(reportOf(result)?.verdict === "healthy").toBe(verdict === "healthy"); }); - it("stopped bridge never emits verdict=healthy (PRA-1 explicit guard)", () => { + it("stopped bridge never emits verdict=healthy (PRA-1 explicit guard)", async () => { const exec = makeExec({ status: 0, stdout: openclawJson(STOPPED_WA), stderr: "" }); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), ); expect(report?.verdict).not.toBe("healthy"); const bridge = report?.signals.find((s) => s.label === "Bridge process"); @@ -230,9 +228,9 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { // emitted JSON, regardless of whether the fixture is healthy or stopped. { fixture: HEALTHY_WA, label: "healthy" }, { fixture: STOPPED_WA, label: "stopped" }, - ])("never propagates self.* or lastError values ($label)", ({ fixture }) => { + ])("never propagates self.* or lastError values ($label)", async ({ fixture }) => { const exec = makeExec({ status: 0, stdout: openclawJson(fixture), stderr: "" }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); const serialized = stringifyReport(result); expect(serialized).not.toContain(REDACTION_PHONE); expect(serialized).not.toContain("@s.whatsapp.net"); @@ -240,21 +238,21 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(serialized).not.toContain("disconnect from"); }); - it("maps an unrecognized healthState to a fixed token so free text cannot leak", () => { + it("maps an unrecognized healthState to a fixed token so free text cannot leak", async () => { // healthState is external JSON text; a compromised gateway could stuff PII // into it. Only the documented enum may be surfaced verbatim. const wa: WaFixture = { ...HEALTHY_WA, healthState: `leaked ${REDACTION_PHONE}` }; const exec = makeExec({ status: 0, stdout: openclawJson(wa), stderr: "" }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); const serialized = stringifyReport(result); expect(serialized).not.toContain(REDACTION_PHONE); expect(serialized).toContain("healthState=unknown"); }); - it("reports unknown for the bounded unconfigured response with no channel state", () => { + it("reports unknown for the bounded unconfigured response with no channel state", async () => { const exec = makeExec({ status: 0, stdout: openclawJson(null), stderr: "" }); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), ); expect(report?.verdict).not.toBe("healthy"); // paired stays null here, so the evaluator lands on "unknown" — @@ -265,7 +263,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(logSignal?.detail).toMatch(/not configured on the gateway/); }); - it("accepts the canonical successful payload without the failure-only reachability field", () => { + it("accepts the canonical successful payload without the failure-only reachability field", async () => { const payload = { channels: { whatsapp: { configured: true } }, channelAccounts: { @@ -275,12 +273,12 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }; const exec = makeExec({ status: 0, stdout: JSON.stringify(payload), stderr: "" }); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), ); expect(report?.verdict).toBe("healthy"); }); - it("selects the declared default account instead of trusting account-array order", () => { + it("selects the declared default account instead of trusting account-array order", async () => { const payload = { // Keep the summary deliberately unpaired so this test also proves the // probe consumes authoritative per-account state rather than the summary. @@ -295,7 +293,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }; const exec = makeExec({ status: 0, stdout: JSON.stringify(payload), stderr: "" }); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), ); expect(report?.verdict).toBe("healthy"); }); @@ -342,10 +340,10 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { configOnly: true, }, }, - ])("fails closed when the gateway is unreachable despite $label", ({ payload }) => { + ])("fails closed when the gateway is unreachable despite $label", async ({ payload }) => { const exec = makeExec({ status: 0, stdout: JSON.stringify(payload), stderr: "" }); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), ); expect(report?.verdict).toBe("probe_failed"); expect(report?.signals.some((signal) => signal.label === "Recent log signals")).toBe(false); @@ -406,16 +404,23 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { channelDefaultAccountId: { whatsapp: "default" }, }, }, - ])("fails closed when the live-status contract is invalid: $label (#7016)", ({ payload }) => { - const exec = makeExec({ status: 0, stdout: JSON.stringify(payload), stderr: "" }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); - const report = reportOf(result); - expect(report?.verdict).toBe("probe_failed"); - expect(stringifyReport(result)).not.toContain("channel runtime reports WhatsApp is not paired"); - expect(stringifyReport(result)).not.toContain("no bridge process"); - }); + ])( + "fails closed when the live-status contract is invalid: $label (#7016)", + async ({ payload }) => { + const exec = makeExec({ status: 0, stdout: JSON.stringify(payload), stderr: "" }); + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + context(), + ); + const report = reportOf(result); + expect(report?.verdict).toBe("probe_failed"); + expect(stringifyReport(result)).not.toContain( + "channel runtime reports WhatsApp is not paired", + ); + expect(stringifyReport(result)).not.toContain("no bridge process"); + }, + ); - it("degrades an out-of-range lastInboundAt to null instead of crashing", () => { + it("degrades an out-of-range lastInboundAt to null instead of crashing", async () => { // A finite-but-out-of-Date-range epoch (e.g. 1e300) passes Number.isFinite // yet makes `new Date(v).toISOString()` throw RangeError. The probe must // degrade it to null, not crash the whole status command. @@ -425,11 +430,11 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { stderr: "", }); const run = () => createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()); - expect(run).not.toThrow(); - expect(reportOf(run())?.verdict).toBeDefined(); + const result = await run(); + expect(reportOf(result)?.verdict).toBeDefined(); }); - it("guides the Hermes dashboard-only session split through re-pairing (#8184)", () => { + it("guides the Hermes dashboard-only session split through re-pairing (#8184)", async () => { const exec = makeExec({ status: 0, stdout: hermesSessionProbeOutput({ @@ -438,7 +443,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }), stderr: "", }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -479,12 +484,12 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }, ])( "keeps the durable session path for an unsupported compatibility value: $label (#8947)", - ({ sessionPath }) => { + async ({ sessionPath }) => { const exec = hermesExec({ configuredSessionPath: sessionPath, credsDirs: [HERMES_DASHBOARD_SESSION_DIR], }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -501,12 +506,12 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }, ); - it("reads the Hermes config only when the default session path is empty (#8718)", () => { + it("reads the Hermes config only when the default session path is empty (#8718)", async () => { const exec = hermesExec({ configuredSessionPath: HERMES_DASHBOARD_SESSION_DIR, credsDirs: [HERMES_DEFAULT_SESSION_DIR], }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -514,12 +519,12 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(report?.signals.find((s) => s.label === "Session path override")).toBeUndefined(); }); - it("keeps unrelated Hermes config values out of the report (#8718)", () => { + it("keeps unrelated Hermes config values out of the report (#8718)", async () => { const exec = hermesExec({ configuredSessionPath: HERMES_DASHBOARD_SESSION_DIR, credsDirs: [HERMES_DASHBOARD_SESSION_DIR], }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); expect(stringifyReport(result)).not.toContain("sk-do-not-leak-this"); @@ -528,13 +533,13 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { ); }); - it("keeps default diagnostics when the configured Hermes session probe fails (#8718)", () => { + it("keeps default diagnostics when the configured Hermes session probe fails (#8718)", async () => { const exec = hermesExec({ configuredSessionPath: HERMES_DASHBOARD_SESSION_DIR, configuredSessionProbeFails: true, credsDirs: [HERMES_DASHBOARD_SESSION_DIR], }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -547,12 +552,12 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(exec).toHaveBeenCalledTimes(3); }); - it("keeps Hermes fallback probes within one timeout budget (#8718)", () => { + it("keeps Hermes fallback probes within one timeout budget (#8718)", async () => { const exec = hermesExec({ configuredSessionPath: HERMES_DASHBOARD_SESSION_DIR, credsDirs: [HERMES_DASHBOARD_SESSION_DIR], }); - createWhatsappStatusHealthHook({ executeSandboxCommand: exec, timeoutMs: 8_000 })( + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec, timeoutMs: 8_000 })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const probeTimeouts = exec.mock.calls.map((call) => Number(call[2])); @@ -561,7 +566,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(probeTimeouts.reduce((total, timeout) => total + timeout, 0)).toBeLessThanOrEqual(8_000); }); - it("rejects a config probe response that carries unrelated values (#8718)", () => { + it("rejects a config probe response that carries unrelated values (#8718)", async () => { const secret = "sk-do-not-cross-the-sandbox-boundary"; const exec = hermesExec({ configProbeStdout: [ @@ -571,7 +576,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { ].join("\n"), credsDirs: [HERMES_DASHBOARD_SESSION_DIR], }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -583,9 +588,9 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(probeCommands[0]).toContain(`gateway='${HERMES_DEFAULT_SESSION_DIR}/creds.json'`); }); - it("falls back to the default session path when the Hermes config cannot be read (#8718)", () => { + it("falls back to the default session path when the Hermes config cannot be read (#8718)", async () => { const exec = hermesExec({ credsDirs: [HERMES_DASHBOARD_SESSION_DIR] }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -599,7 +604,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(report?.signals.find((s) => s.label === "Session path override")).toBeUndefined(); }); - it("does not treat a Hermes gateway session file as live inbound health", () => { + it("does not treat a Hermes gateway session file as live inbound health", async () => { const exec = makeExec({ status: 0, stdout: hermesSessionProbeOutput({ @@ -608,7 +613,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }), stderr: "", }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -633,9 +638,9 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { "DASHBOARD_SESSION=yes", ].join("\n"), }, - ])("reports probe_failed for malformed Hermes probe output: $label", ({ stdout }) => { + ])("reports probe_failed for malformed Hermes probe output: $label", async ({ stdout }) => { const exec = makeExec({ status: 0, stdout, stderr: "" }); - const result = createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + const result = await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context({ ...BASE_INPUTS, agent: "hermes" }), ); const report = reportOf(result); @@ -661,27 +666,29 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }, }, { label: "JSON but not an object", exec: { status: 0, stdout: '"hello"', stderr: "" } }, - ] as const)("verdict=probe_failed when $label", ({ exec }) => { + ] as const)("verdict=probe_failed when $label", async ({ exec }) => { const runner = makeExec(exec); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: runner })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: runner })(context()), ); expect(report?.verdict).toBe("probe_failed"); }); - it("reports probe_failed when the sandbox exec runner throws", () => { - const exec = vi.fn(() => { + it("reports probe_failed when the sandbox exec runner rejects", async () => { + const exec = vi.fn(async () => { throw new Error("sandbox exec unavailable"); }); const report = reportOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })(context()), ); expect(report?.verdict).toBe("probe_failed"); }); - it("invokes the openclaw CLI with the JSON + timeout flags", () => { + it("invokes the openclaw CLI with the JSON + timeout flags", async () => { const exec = makeExec({ status: 0, stdout: openclawJson(HEALTHY_WA), stderr: "" }); - createWhatsappStatusHealthHook({ executeSandboxCommand: exec, timeoutMs: 4500 })(context()); + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec, timeoutMs: 4500 })( + context(), + ); const command = String(exec.mock.calls[0]?.[1] ?? ""); expect(command).toContain("openclaw channels status --channel whatsapp --json"); expect(command).toContain("--timeout 4500"); @@ -692,7 +699,7 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { expect(command).not.toMatch(/DIR .* POPULATED/); }); - it("healthState surfaces neutral state signal only when non-healthy", () => { + it("healthState surfaces neutral state signal only when non-healthy", async () => { const stale: WaFixture = { ...HEALTHY_WA, healthState: "stale", @@ -704,10 +711,10 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { { status: 0, stdout: openclawJson(stale), stderr: "" }, ]); const hook = createWhatsappStatusHealthHook({ executeSandboxCommand: exec }); - const healthyReport = reportOf(hook(context())); + const healthyReport = reportOf(await hook(context())); // Healthy runs stay clean (no "Recent log signals" row from healthState). expect(healthyReport?.signals.some((s) => s.label === "Recent log signals")).toBe(false); - const staleReport = reportOf(hook(context())); + const staleReport = reportOf(await hook(context())); const staleLogs = staleReport?.signals.find((s) => s.label === "Recent log signals"); expect(staleLogs?.detail).toMatch(/healthState=stale/); expect(staleLogs?.detail).toMatch(/reconnectAttempts=3/); @@ -715,25 +722,27 @@ describe("whatsapp.statusHealth openclaw CLI probe", () => { }); describe("whatsapp.statusHealth wiring guards", () => { - it("no-ops for a non-whatsapp channel or without an exec runner", () => { + it("no-ops for a non-whatsapp channel or without an exec runner", async () => { const exec = makeExec({ status: 0, stdout: openclawJson(HEALTHY_WA), stderr: "" }); expect( outputsOf( - createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( + await createWhatsappStatusHealthHook({ executeSandboxCommand: exec })( context(BASE_INPUTS, "slack"), ), ), ).toBeUndefined(); - expect(outputsOf(createWhatsappStatusHealthHook({})(context()))).toBeUndefined(); + expect(outputsOf(await createWhatsappStatusHealthHook({})(context()))).toBeUndefined(); expect(exec).not.toHaveBeenCalled(); }); - it("derives config_gap / policy_gap from the host-fact inputs", () => { + it("derives config_gap / policy_gap from the host-fact inputs", async () => { const exec = makeExec({ status: 0, stdout: openclawJson(HEALTHY_WA), stderr: "" }); const hook = createWhatsappStatusHealthHook({ executeSandboxCommand: exec }); - const configGap = reportOf(hook(context({ ...BASE_INPUTS, channelEnabledInRegistry: false }))); + const configGap = reportOf( + await hook(context({ ...BASE_INPUTS, channelEnabledInRegistry: false })), + ); expect(configGap?.verdict).toBe("config_gap"); - const policyGap = reportOf(hook(context({ ...BASE_INPUTS, presetApplied: false }))); + const policyGap = reportOf(await hook(context({ ...BASE_INPUTS, presetApplied: false }))); expect(policyGap?.verdict).toBe("policy_gap"); }); }); diff --git a/src/lib/messaging/channels/whatsapp/hooks/status-health.ts b/src/lib/messaging/channels/whatsapp/hooks/status-health.ts index 25dc50fc59a..735dd065294 100644 --- a/src/lib/messaging/channels/whatsapp/hooks/status-health.ts +++ b/src/lib/messaging/channels/whatsapp/hooks/status-health.ts @@ -100,42 +100,44 @@ export function createWhatsappStatusHealthHook( // this hook). if (!execute || !sandboxName) return {}; - const agent = normalizeString(context.inputs?.agent) ?? "openclaw"; - const timeoutMs = normalizeTimeoutMs(options.timeoutMs); - const probe = - agent === "openclaw" - ? runOpenclawStatusProbe(execute, sandboxName, timeoutMs) - : agent === "hermes" - ? runHermesSessionProbe(execute, sandboxName, timeoutMs) - : null; - if (!probe) return {}; - - const input: WhatsappProbeInput = { - agent, - paired: probe.paired, - heartbeat: probe.heartbeat, - heartbeatParseError: null, - bridgeProcessAlive: probe.bridgeProcessAlive, - recentLogSignals: probe.recentLogSignals, - probeReachable: probe.probeReachable, - probedAt: normalizeString(context.inputs?.probedAt) ?? "", - presetApplied: Boolean(context.inputs?.presetApplied), - presetOnGateway: normalizeTristate(context.inputs?.presetOnGateway), - channelEnabledInRegistry: Boolean(context.inputs?.channelEnabledInRegistry), - ...(probe.sessionLocations ? { sessionLocations: probe.sessionLocations } : {}), - }; - const report = evaluateWhatsappDiagnostics(input); - return { - outputs: { - channelHealth: { - kind: "status", - value: { - type: MESSAGING_CHANNEL_HEALTH_OUTPUT_TYPE, - report, - } as unknown as MessagingSerializableValue, + return (async () => { + const agent = normalizeString(context.inputs?.agent) ?? "openclaw"; + const timeoutMs = normalizeTimeoutMs(options.timeoutMs); + const probe = + agent === "openclaw" + ? await runOpenclawStatusProbe(execute, sandboxName, timeoutMs) + : agent === "hermes" + ? await runHermesSessionProbe(execute, sandboxName, timeoutMs) + : null; + if (!probe) return {}; + + const input: WhatsappProbeInput = { + agent, + paired: probe.paired, + heartbeat: probe.heartbeat, + heartbeatParseError: null, + bridgeProcessAlive: probe.bridgeProcessAlive, + recentLogSignals: probe.recentLogSignals, + probeReachable: probe.probeReachable, + probedAt: normalizeString(context.inputs?.probedAt) ?? "", + presetApplied: Boolean(context.inputs?.presetApplied), + presetOnGateway: normalizeTristate(context.inputs?.presetOnGateway), + channelEnabledInRegistry: Boolean(context.inputs?.channelEnabledInRegistry), + ...(probe.sessionLocations ? { sessionLocations: probe.sessionLocations } : {}), + }; + const report = evaluateWhatsappDiagnostics(input); + return { + outputs: { + channelHealth: { + kind: "status", + value: { + type: MESSAGING_CHANNEL_HEALTH_OUTPUT_TYPE, + report, + } as unknown as MessagingSerializableValue, + }, }, - }, - }; + }; + })(); }; } @@ -191,15 +193,15 @@ const PROBE_UNREACHABLE: ProbeResult = { * reflects the in-process bridge's current state, so this replaces the old * log-scraping + pgrep + dir-listing signals with a single trusted source. */ -function runOpenclawStatusProbe( +async function runOpenclawStatusProbe( execute: NonNullable, sandboxName: string, timeoutMs: number, -): ProbeResult { +): Promise { const command = `openclaw channels status --channel whatsapp --json --timeout ${timeoutMs}`; - let exec: ReturnType; + let exec: Awaited>; try { - exec = execute(sandboxName, command, timeoutMs); + exec = await execute(sandboxName, command, timeoutMs); } catch { return PROBE_UNREACHABLE; } @@ -239,15 +241,15 @@ function runOpenclawStatusProbe( return mapOpenclawWaState(wa); } -function runHermesSessionProbe( +async function runHermesSessionProbe( execute: NonNullable, sandboxName: string, timeoutMs: number, -): ProbeResult { +): Promise { const configuredProbeTimeoutMs = Math.floor(timeoutMs / 4); const configProbeTimeoutMs = Math.floor(timeoutMs / 4); const defaultProbeTimeoutMs = timeoutMs - configProbeTimeoutMs - configuredProbeTimeoutMs; - const defaultLocations = probeHermesSessionDirs( + const defaultLocations = await probeHermesSessionDirs( execute, sandboxName, HERMES_DEFAULT_SESSION_DIR, @@ -264,11 +266,15 @@ function runHermesSessionProbe( if (configProbeTimeoutMs < 1 || configuredProbeTimeoutMs < 1) { return hermesProbeResult(defaultLocations, "default"); } - const configured = readHermesConfiguredSessionDir(execute, sandboxName, configProbeTimeoutMs); + const configured = await readHermesConfiguredSessionDir( + execute, + sandboxName, + configProbeTimeoutMs, + ); if (configured.source !== "config") { return hermesProbeResult(defaultLocations, configured.source); } - const configuredLocations = probeHermesSessionDirs( + const configuredLocations = await probeHermesSessionDirs( execute, sandboxName, configured.dir, @@ -298,15 +304,15 @@ function hermesProbeResult( }; } -function probeHermesSessionDirs( +async function probeHermesSessionDirs( execute: NonNullable, sandboxName: string, gatewaySessionDir: string, timeoutMs: number, -): WhatsappSessionLocations | null { - let exec: ReturnType; +): Promise { + let exec: Awaited>; try { - exec = execute(sandboxName, hermesSessionProbeCommand(gatewaySessionDir), timeoutMs); + exec = await execute(sandboxName, hermesSessionProbeCommand(gatewaySessionDir), timeoutMs); } catch { return null; } @@ -316,15 +322,15 @@ function probeHermesSessionDirs( type HermesSessionPathSource = NonNullable; -function readHermesConfiguredSessionDir( +async function readHermesConfiguredSessionDir( execute: NonNullable, sandboxName: string, timeoutMs: number, -): { readonly dir: string; readonly source: HermesSessionPathSource } { +): Promise<{ readonly dir: string; readonly source: HermesSessionPathSource }> { const fallback = { dir: HERMES_DEFAULT_SESSION_DIR, source: "default" } as const; - let exec: ReturnType; + let exec: Awaited>; try { - exec = execute(sandboxName, hermesConfiguredSessionPathCommand(), timeoutMs); + exec = await execute(sandboxName, hermesConfiguredSessionPathCommand(), timeoutMs); } catch { return fallback; } diff --git a/src/lib/messaging/hooks/status-runner.ts b/src/lib/messaging/hooks/status-runner.ts index 4a0c6945247..09b10427472 100644 --- a/src/lib/messaging/hooks/status-runner.ts +++ b/src/lib/messaging/hooks/status-runner.ts @@ -17,7 +17,7 @@ import { } from "../channels/channel-health"; import type { ChannelHookSpec, MessagingAgentId, MessagingSerializableValue } from "../manifest"; import { createBuiltInMessagingHookRegistry } from "./builtins"; -import { runMessagingHookSync } from "./hook-runner"; +import { runMessagingHook, runMessagingHookSync } from "./hook-runner"; export interface MessagingStatusHookRunOptions { readonly agent?: MessagingAgentId; @@ -75,6 +75,45 @@ export function runMessagingStatusHooks( return hookResults; } +export async function runMessagingStatusHooksAsync( + options: MessagingStatusHookRunOptions, +): Promise { + const hookRegistry = options.hookRegistry ?? createBuiltInMessagingHookRegistry(); + const manifestRegistry = createBuiltInChannelManifestRegistry(); + const agents: ReadonlySet = options.agent + ? new Set([options.agent]) + : (options.agents ?? new Set(["openclaw"])); + const hookResults: MessagingStatusHookRunResult[] = []; + const seen = new Set(); + + for (const agent of agents) { + for (const manifest of manifestRegistry.listAvailable({ agent })) { + if (options.channels && !options.channels.has(manifest.id)) continue; + for (const hook of manifest.hooks) { + if (!shouldRunStatusHook(hook, agent)) continue; + const key = `${manifest.id}\0${hook.id}\0${hook.handler}`; + if (seen.has(key)) continue; + seen.add(key); + try { + const result = await runMessagingHook(hook, hookRegistry, { + channelId: manifest.id, + inputs: createMessagingStatusHookInputs(options), + }); + hookResults.push({ + channelId: manifest.id, + hookId: hook.id, + outputs: result.outputs, + }); + } catch { + // Status hooks are advisory; a broken hook must not hide the rest of + // `nemoclaw status` or a channels-status probe. + } + } + } + } + return hookResults; +} + function shouldRunStatusHook(hook: ChannelHookSpec, agent: MessagingAgentId): boolean { return hook.phase === "status" && (!hook.agents || hook.agents.includes(agent)); } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index b1affbece07..739d84adf55 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -130,6 +130,7 @@ const { }: typeof import("./onboard/e2e-failure-injection") = require("./onboard/e2e-failure-injection"); const onboardTracing: typeof import("./onboard/tracing") = require("./onboard/tracing"); const sandboxReadinessTracing: typeof import("./onboard/sandbox-readiness-tracing") = require("./onboard/sandbox-readiness-tracing"); +const sandboxCommandCli: typeof import("./adapters/openshell/sandbox-command-cli") = require("./adapters/openshell/sandbox-command-cli"); const messagingChannelSetup: typeof import("./onboard/messaging-channel-setup") = require("./onboard/messaging-channel-setup"); const { applySessionRecovery } = require("./onboard/session-recovery") as typeof import("./onboard/session-recovery"); @@ -696,8 +697,8 @@ const { getGatewayPort: () => GATEWAY_PORT, getDockerDriverGatewayEndpoint, }); +const sandboxExec = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); -// Gateway state functions — delegated to src/lib/state/gateway.ts const { isSandboxReady, parseSandboxStatus, getSandboxStateFromOutputs } = gatewayState; const waitForSandboxReady = sandboxReadinessTracing.createCliSandboxReadyWaiter({ isLinuxDockerDriverGatewayEnabled, @@ -914,13 +915,14 @@ const { inspectSandboxForCreate, confirmRecreateForSelectionDrift, isOpenclawRea isAffirmativeAnswer, }); +const webSearchDeps = { prompt, note, isNonInteractive, cliName, commandExecutor: sandboxExec }; const { ensureValidatedWebSearchCredential, ensureValidatedBraveSearchCredential, configureWebSearch, verifyWebSearchInsideSandbox, webSearchProviderForConfig, -} = createWebSearchFlowHelpers({ prompt, note, isNonInteractive, cliName, runCaptureOpenshell }); +} = createWebSearchFlowHelpers(webSearchDeps); const { hasResponsesToolCall, @@ -1511,7 +1513,7 @@ const sandboxCreateOrchestrationRuntime = { get getDashboardForwardPort() { return getDashboardForwardPort; }, - readDcodeSelectionDrift: createDcodeSelectionDriftReader(runCaptureOpenshell, () => GATEWAY_NAME), + readDcodeSelectionDrift: createDcodeSelectionDriftReader(sandboxExec, () => GATEWAY_NAME), getDefaultSandboxNameForAgent, getDockerDriverGatewayStateDir, getHermesToolGatewayBroker, @@ -1555,6 +1557,7 @@ const sandboxCreateOrchestrationRuntime = { runSandboxProviderPreDeleteCleanup, sandboxAgent, sandboxBuildPatchConfig, + sandboxCommandExecutor: sandboxExec, get sandboxCancelRollback() { return sandboxCancelRollback; }, @@ -2489,12 +2492,8 @@ const setupMessagingChannels = messagingChannelSetup.createSetupMessagingChannel prompt, }); -// ── Step 7: OpenClaw ───────────────────────────────────────────── -const syncNemoClawConfigInSandbox = createNemoClawConfigSync({ - getProviderSelectionConfig, - run, - openshellArgv, -}); +const configSyncDeps = { getProviderSelectionConfig, sandboxCommandExecutor: sandboxExec }; +const syncNemoClawConfigInSandbox = createNemoClawConfigSync(configSyncDeps); const configureOpenclawSandbox = openclawSetup.createConfigureOpenclawSandbox({ syncNemoClawConfigInSandbox, @@ -3228,10 +3227,9 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { preserveRebuildLivePolicy: opts.rebuildPolicySourcePath !== undefined, agentSetupDeps: { handleAgentSetup: agentOnboard.handleAgentSetup, - agentSetupContext: () => ({ - ...{ step, runCaptureOpenshell, captureOpenshell }, - openshellShellCommand, - openshellBinary: getOpenshellBinary(), + agentSetupContext: (): import("./agent/onboard").OnboardContext => ({ + step, + sandboxCommandExecutor: sandboxExec, gatewayName: GATEWAY_NAME, startRecordedStep, recordStepComplete, @@ -3268,6 +3266,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { verifyCompatibleEndpointSandboxSmoke({ ...options, runOpenshell: runCoreGatewayOpenshell, + sandboxCommandExecutor: sandboxExec, redact, }), preparePolicyPresetResumeSelection, @@ -3301,7 +3300,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { chain, { executeSandboxCommand: (sandbox: string, script: string) => - executeSandboxCommandForVerification(sandbox, script), + executeSandboxCommandForVerification(sandbox, script, sandboxExec), probeHostPort: (port: number, probePath: string) => { const result = runCapture( [ diff --git a/src/lib/onboard/__test-helpers__/sandbox-gpu-create-flow.ts b/src/lib/onboard/__test-helpers__/sandbox-gpu-create-flow.ts index 21b5b7ab986..e37181841be 100644 --- a/src/lib/onboard/__test-helpers__/sandbox-gpu-create-flow.ts +++ b/src/lib/onboard/__test-helpers__/sandbox-gpu-create-flow.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { expect, vi } from "vitest"; import { createCliOpenShellSandboxObserver } from "../../adapters/openshell/sandbox-observer-cli"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import type { CheckpointPortableRuntimeAuthority } from "../../state/onboard-checkpoint-types"; import type { SandboxGpuProofResult } from "../../state/registry"; import type { ManagedBootstrapRuntimeCreateLifecycleInput } from "../managed-bootstrap/runtime-create"; @@ -89,6 +90,13 @@ export function createGpuFlowDeps( return ""; }); return { + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0, signal: null }, + stdout: "", + stderr: "", + })), + } satisfies OpenShellSandboxBufferedCommandExecutor, runOpenshell: vi.fn((args: string[]) => { assertSandboxProbeTarget(args); return args[0] === "sandbox" && args[1] === "get" diff --git a/src/lib/onboard/compatible-endpoint-smoke.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index ca5de7d6c12..3f3feb1ed8b 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandRequest } from "../adapters/openshell/sandbox-command"; import { runSmokeScript, writeFakeCurl, @@ -26,6 +27,41 @@ import { verifyCompatibleEndpointSandboxSmoke, } from "./compatible-endpoint-smoke"; +type CompatibleSmokeOptions = Parameters[0]; + +function bufferedExecutorThrough(runOpenshell: CompatibleSmokeOptions["runOpenshell"]) { + return { + runBuffered: vi.fn(async (request: OpenShellSandboxBufferedCommandRequest) => { + const targetArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const ttyArgs = request.tty === false ? ["--no-tty"] : []; + const args = ["sandbox", "exec", "-n", request.sandboxName, ...targetArgs, ...ttyArgs]; + for (const [key, value] of Object.entries(request.sandboxEnvironment ?? {})) { + args.push("--env", `${key}=${value}`); + } + const result = runOpenshell([...args, "--", ...request.command], { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: request.timeoutMilliseconds, + }); + return result.status === null + ? { + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "unobservable" }, + }, + stdout: spawnOutputToString(result.stdout), + stderr: spawnOutputToString(result.stderr), + } + : { + outcome: { kind: "completed" as const, exitCode: result.status }, + stdout: spawnOutputToString(result.stdout), + stderr: spawnOutputToString(result.stderr), + }; + }), + }; +} + const providerNeutralCases = ["openclaw", "hermes", "langchain-deepagents-code"].flatMap( (agentName) => [ { @@ -275,6 +311,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider, model: "nvidia/nemotron-3-ultra", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, agent, }); @@ -306,6 +343,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider: "compatible-endpoint", model: "nvidia/nemotron-3-ultra", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, messagingChannels: ["telegram"], }); @@ -317,6 +355,41 @@ describe("compatible endpoint sandbox smoke helpers", () => { ); }); + it("fails closed on a typed sandbox transport failure", async () => { + const runOpenshell = vi.fn().mockImplementation((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })); + const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`process.exit(${code})`); + }); + + try { + await expect( + verifyCompatibleEndpointSandboxSmoke({ + sandboxName: "smoke-sandbox", + provider: "compatible-endpoint", + model: "nvidia/nemotron-3-ultra", + runOpenshell, + sandboxCommandExecutor: { + runBuffered: async () => ({ + outcome: { + kind: "failed", + error: { kind: "timeout", message: "smoke timed out" }, + }, + stdout: "", + stderr: "", + }), + }, + redact: (value) => value, + }), + ).rejects.toThrow("process.exit(1)"); + expect(exit).toHaveBeenCalledWith(1); + } finally { + exit.mockRestore(); + } + }); + it("withholds sandbox-route success output when sandbox identity changes during proof (#9833)", async () => { const runOpenshell = vi .fn() @@ -333,6 +406,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider: "compatible-endpoint", model: "nvidia/nemotron-3-ultra", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, messagingChannels: ["telegram"], beforeSuccess: () => { @@ -362,6 +436,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider: "vllm-local", model: "qwen3.5-9b", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, forceCanonicalRoute: true, hostLocalInferenceProofAuthority: { @@ -412,6 +487,10 @@ describe("compatible endpoint sandbox smoke helpers", () => { const exit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`process.exit(${code})`); }); + const runOpenshell = vi.fn().mockReturnValue({ + status: 1, + stderr: "provider query failed", + }); try { await expect( @@ -419,7 +498,8 @@ describe("compatible endpoint sandbox smoke helpers", () => { sandboxName: "provider-lookup-failure-sandbox", provider: testCase.provider, model: "qwen3.5-9b", - runOpenshell: vi.fn().mockReturnValue({ status: 1, stderr: "provider query failed" }), + runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, messagingChannels: testCase.messagingChannels, forceCanonicalRoute: testCase.forceCanonicalRoute, @@ -466,6 +546,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider: "compatible-endpoint", model: "issue-10405-model", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, messagingChannels, }), @@ -503,6 +584,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { model: "qwen3.5-9b", endpointUrl: "https://inference.local/v1", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, messagingChannels: [], agent: { name: agentName }, @@ -565,6 +647,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider: "ollama-local", model: "qwen3.5-9b", runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, agent: { name: "hermes" }, forceCanonicalRoute: true, @@ -675,6 +758,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { provider: "ollama-local", model, runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), redact: (value) => value, forceCanonicalRoute: true, hostLocalInferenceProofAuthority: authority, diff --git a/src/lib/onboard/compatible-endpoint-smoke.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index 84cb9b6a05e..604ad894cc4 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { StdioOptions } from "node:child_process"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; import { shellQuote } from "../core/shell-quote"; import { compactText } from "../core/url-utils"; @@ -104,6 +105,7 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { provider: string; model: string; runOpenshell: CompatibleEndpointSmokeRun; + sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor; redact: (value: string) => string; endpointUrl?: string | null; credentialEnv?: string | null; @@ -129,6 +131,7 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { : " Verifying compatible endpoint through the sandbox runtime...", ); + const target = { kind: "selected" } as const; const adapter = createCliOpenShellProviderAdapter({ run: (command, runOptions) => { const result = options.runOpenshell(command, runOptions); @@ -146,7 +149,7 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { }, }); const providerResult = await adapter.getProvider({ - target: { kind: "selected" }, + target, providerName: options.provider, }); @@ -176,27 +179,18 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { options.hostLocalInferenceProofAuthority, ) : buildCompatibleEndpointSandboxSmokeCommand(options.model); - const smokeResult = options.runOpenshell( - forceCanonicalRoute - ? ["sandbox", "exec", "-n", options.sandboxName, "--", "python3", "-c", script] - : ["sandbox", "exec", "-n", options.sandboxName, "--", "sh", "-lc", script], - { - ignoreError: true, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: forceCanonicalRoute - ? PROVIDER_NEUTRAL_SMOKE_COMMAND_TIMEOUT_MS - : COMPATIBLE_ENDPOINT_SMOKE_COMMAND_TIMEOUT_MS, - }, - ); - const smokeOutput = [ - spawnOutputToString(smokeResult.stdout), - spawnOutputToString(smokeResult.stderr), - ] - .join("\n") - .trim(); - - if (smokeResult.status !== 0 || !/INFERENCE_SMOKE_OK/.test(smokeOutput)) { + const smokeResult = await options.sandboxCommandExecutor.runBuffered({ + sandboxName: options.sandboxName, + target, + command: forceCanonicalRoute ? ["python3", "-c", script] : ["sh", "-lc", script], + timeoutMilliseconds: forceCanonicalRoute + ? PROVIDER_NEUTRAL_SMOKE_COMMAND_TIMEOUT_MS + : COMPATIBLE_ENDPOINT_SMOKE_COMMAND_TIMEOUT_MS, + }); + const smokeOutput = [smokeResult.stdout, smokeResult.stderr].join("\n").trim(); + const smokeStatus = smokeResult.outcome.kind === "completed" ? smokeResult.outcome.exitCode : 1; + + if (smokeStatus !== 0 || !/INFERENCE_SMOKE_OK/.test(smokeOutput)) { console.error( options.forceCanonicalRoute ? " Provider-neutral sandbox inference smoke check failed." @@ -208,7 +202,7 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { ); } if (smokeOutput) console.error(` ${compactText(options.redact(smokeOutput)).slice(0, 1200)}`); - process.exit(smokeResult.status || 1); + process.exit(smokeStatus || 1); } options.beforeSuccess?.(); diff --git a/src/lib/onboard/config-sync.test.ts b/src/lib/onboard/config-sync.test.ts index 2495a108a21..21d7daf06a9 100644 --- a/src/lib/onboard/config-sync.test.ts +++ b/src/lib/onboard/config-sync.test.ts @@ -12,7 +12,6 @@ import { buildSandboxConfigSyncScript, createNemoClawConfigSync, runSandboxConfigSync, - sandboxConfigSyncArgs, } from "./config-sync"; const itUnix = process.platform === "win32" ? it.skip : it; @@ -57,8 +56,8 @@ function modeBits(file: string): number { } describe("sandbox config sync helpers", () => { - it("revalidates sandbox identity immediately before sandbox execution", () => { - const run = vi.fn(); + it("revalidates sandbox identity immediately before sandbox execution", async () => { + const runBuffered = vi.fn(); const revalidateSandboxIdentity = vi.fn(() => { throw new Error("sandbox identity changed"); }); @@ -73,31 +72,77 @@ describe("sandbox config sync helpers", () => { provider: "provider", providerLabel: "Provider", }), - run, - openshellArgv: (args) => ["openshell", ...args], + sandboxCommandExecutor: { runBuffered }, }); - expect(() => syncConfig("spark-box", "provider", "model", revalidateSandboxIdentity)).toThrow( - "sandbox identity changed", - ); + await expect( + syncConfig("spark-box", "provider", "model", revalidateSandboxIdentity), + ).rejects.toThrow("sandbox identity changed"); expect(revalidateSandboxIdentity).toHaveBeenCalledExactlyOnceWith( "synchronize OpenClaw config in sandbox 'spark-box'", ); - expect(run).not.toHaveBeenCalled(); + expect(runBuffered).not.toHaveBeenCalled(); }); - it("uses noninteractive sandbox exec for stdin scripts", () => { - expect(sandboxConfigSyncArgs("spark-box")).toEqual([ - "sandbox", - "exec", - "-n", - "spark-box", - "--no-tty", - "--", - "/bin/bash", - "-s", - ]); + it("uses noninteractive buffered sandbox exec for stdin scripts", async () => { + const runBuffered = vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })); + const syncConfig = createNemoClawConfigSync({ + getProviderSelectionConfig: () => ({ + endpointType: "custom", + endpointUrl: "https://inference.local/v1", + ncpPartner: null, + model: "model", + profile: "inference-local", + credentialEnv: "OPENAI_API_KEY", + provider: "provider", + providerLabel: "Provider", + }), + sandboxCommandExecutor: { runBuffered }, + }); + + await syncConfig("spark-box", "provider", "model"); + + expect(runBuffered).toHaveBeenCalledWith({ + sandboxName: "spark-box", + target: { kind: "selected" }, + command: ["/bin/bash", "-s"], + tty: false, + input: expect.stringContaining('"provider": "provider"'), + }); + }); + + it("propagates typed sandbox execution failures", async () => { + const syncConfig = createNemoClawConfigSync({ + getProviderSelectionConfig: () => ({ + endpointType: "custom", + endpointUrl: "https://inference.local/v1", + ncpPartner: null, + model: "model", + profile: "inference-local", + credentialEnv: "OPENAI_API_KEY", + provider: "provider", + providerLabel: "Provider", + }), + sandboxCommandExecutor: { + runBuffered: async () => ({ + outcome: { + kind: "failed", + error: { kind: "timeout", message: "config sync timed out" }, + }, + stdout: "", + stderr: "", + }), + }, + }); + + await expect(syncConfig("spark-box", "provider", "model")).rejects.toThrow( + "config sync timed out", + ); }); itUnix("writes provider selection and tightens managed config permissions", () => { @@ -193,9 +238,11 @@ describe("sandbox config sync helpers", () => { } }); - itUnix("passes the generated script directly to the sandbox executor", () => { + itUnix("passes the generated script directly to the sandbox executor", async () => { const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-sync-home-")); - const runConnectScript = vi.fn(); + const runConnectScript = vi.fn<(sandboxName: string, scriptContent: string) => Promise>( + async () => undefined, + ); const selection = { endpointType: "custom", endpointUrl: "https://inference.local/v1", @@ -207,7 +254,7 @@ describe("sandbox config sync helpers", () => { providerLabel: "Provider", } as const; try { - runSandboxConfigSync("spark-box", { + await runSandboxConfigSync("spark-box", { getSelectionConfig: () => selection, runConnectScript, }); diff --git a/src/lib/onboard/config-sync.ts b/src/lib/onboard/config-sync.ts index dc47e46a5e1..5098162bccd 100644 --- a/src/lib/onboard/config-sync.ts +++ b/src/lib/onboard/config-sync.ts @@ -2,55 +2,62 @@ // SPDX-License-Identifier: Apache-2.0 import type { ProviderSelectionConfig } from "../inference/config"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; export interface RunSandboxConfigSyncDeps { getSelectionConfig: () => ProviderSelectionConfig | null; - runConnectScript: (sandboxName: string, scriptContent: string) => void; + runConnectScript: (sandboxName: string, scriptContent: string) => Promise; } export interface NemoClawConfigSyncDeps { getProviderSelectionConfig(provider: string, model: string): ProviderSelectionConfig | null; - run(argv: string[], options: Record): unknown; - openshellArgv(args: string[]): string[]; + sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor; } const skipSandboxIdentityRevalidation = (_operation: string): void => undefined; export function createNemoClawConfigSync(deps: NemoClawConfigSyncDeps) { - return function syncNemoClawConfigInSandbox( + return async function syncNemoClawConfigInSandbox( sandboxName: string, provider: string, model: string, revalidateSandboxIdentity: (operation: string) => void = skipSandboxIdentityRevalidation, - ): void { - runSandboxConfigSync(sandboxName, { + ): Promise { + await runSandboxConfigSync(sandboxName, { getSelectionConfig: () => deps.getProviderSelectionConfig(provider, model), - runConnectScript: (name, scriptContent) => { + runConnectScript: async (name, scriptContent) => { revalidateSandboxIdentity(`synchronize OpenClaw config in sandbox '${name}'`); - deps.run(deps.openshellArgv(sandboxConfigSyncArgs(name)), { - stdio: ["pipe", "ignore", "inherit"], + const result = await deps.sandboxCommandExecutor.runBuffered({ + sandboxName: name, + target: selectedOpenShellGateway(), + command: ["/bin/bash", "-s"], + tty: false, input: scriptContent, }); + if (result.stderr) process.stderr.write(result.stderr); + if (result.outcome.kind === "failed") throw new Error(result.outcome.error.message); + if (result.outcome.exitCode !== 0) { + throw new Error(`OpenShell command failed (exit ${String(result.outcome.exitCode)})`); + } }, }); }; } -/** Run config sync without allocating the interactive sandbox terminal transport. */ -export function sandboxConfigSyncArgs(sandboxName: string): string[] { - return ["sandbox", "exec", "-n", sandboxName, "--no-tty", "--", "/bin/bash", "-s"]; -} - // Write `~/.nemoclaw/config.json` and normalize OpenClaw config-dir perms // inside the sandbox. Idempotent — safe to invoke from the rebuild resume // path where the Dockerfile leaves config.json as a zero-byte placeholder // that crashes the OpenClaw nemoclaw plugin's loadOnboardConfig. Fixes #3999. -export function runSandboxConfigSync(sandboxName: string, deps: RunSandboxConfigSyncDeps): void { +export async function runSandboxConfigSync( + sandboxName: string, + deps: RunSandboxConfigSyncDeps, +): Promise { const selectionConfig = deps.getSelectionConfig(); if (!selectionConfig) return; const sandboxConfig = { ...selectionConfig, onboardedAt: new Date().toISOString() }; const script = buildSandboxConfigSyncScript(sandboxConfig); - deps.runConnectScript(sandboxName, script); + await deps.runConnectScript(sandboxName, script); } export function buildSandboxConfigSyncScript(selectionConfig: ProviderSelectionConfig): string { diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index 0efbf71b3da..ecd2e3b193f 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -339,12 +339,12 @@ describe("created DCode sandbox finalization", () => { expect(restore).not.toHaveBeenCalled(); }); - it("merges stale backup preferences before live validation and registry publication (#6311)", () => { + it("merges stale backup preferences before live validation and registry publication (#6311)", async () => { const fixture = makeRestoreFixture(); const order: string[] = []; const registeredConfigs: string[] = []; try { - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "dcode", restoreBackupPath: fixture.backupPath, @@ -367,12 +367,17 @@ describe("created DCode sandbox finalization", () => { expect(options.allowCustomImageWholeStateFileRestore).toBeUndefined(); return sandboxState.restoreRecreatedSandboxState(name, backup, options); }, - getDcodeSelectionDrift: (name, provider, model, api) => { + getDcodeSelectionDrift: async (name, provider, model, api) => { order.push("validate"); return getDcodeSelectionDrift(name, provider, model, api, { getGatewayName: () => "nemoclaw-18081", - runCaptureOpenshell: () => - identityFromConfig(fs.readFileSync(fixture.currentPath, "utf8")), + commandExecutor: { + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: identityFromConfig(fs.readFileSync(fixture.currentPath, "utf8")), + stderr: "", + }), + }, }); }, register: () => { @@ -398,9 +403,9 @@ describe("created DCode sandbox finalization", () => { } }); - it("publishes fresh metadata after endpoint-aware OpenRouter validation (#9555)", () => { + it("publishes fresh metadata after endpoint-aware OpenRouter validation (#9555)", async () => { const endpointUrl = "https://openrouter.ai/api/v1"; - const getDcodeSelectionDrift = vi.fn(() => ({ + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: false, providerChanged: false, modelChanged: false, @@ -410,7 +415,7 @@ describe("created DCode sandbox finalization", () => { })); const register = vi.fn(); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "dcode", restoreBackupPath: null, @@ -470,6 +475,11 @@ describe("created DCode sandbox finalization", () => { "Runtime: Deep Agents Code (terminal)", ].join("\n"), ); + const runBuffered = vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: runCaptureOpenshell(), + stderr: "", + })); vi.spyOn(process, "exit").mockImplementation((code): never => { throw new Error(`exit ${code}`); }); @@ -562,17 +572,8 @@ describe("created DCode sandbox finalization", () => { release: null, fallbackDiagnostic: null, }, - null, vi.fn(), - vi.fn((input) => ({ - schemaVersion: 1, - origin: "sandbox-create", - gatewayName: input.gatewayName, - gatewayPort: input.gatewayPort, - sandboxName: input.sandboxName, - lifecycleGeneration: input.lifecycleGeneration, - sandboxIdentityFingerprint: input.lifecycleLiveIdentityFingerprint, - })), + { runBuffered }, ] as unknown as Parameters; const completion = createOnboardCreatedSandboxCompletion(...completionArgs); const created = { @@ -609,13 +610,13 @@ describe("created DCode sandbox finalization", () => { lifecycle, ), ).rejects.toThrow("exit 1"); - expect(runCaptureOpenshell).toHaveBeenCalledOnce(); + expect(runBuffered).toHaveBeenCalledOnce(); }); - it("does not publish registry metadata when live validation fails (#6311)", () => { + it("does not publish registry metadata when live validation fails (#6311)", async () => { const register = vi.fn(); const error = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "dcode", @@ -630,7 +631,7 @@ describe("created DCode sandbox finalization", () => { { discoverFreshOpenClawImagePluginInstalls: vi.fn(), restoreRecreatedSandboxState: vi.fn(), - getDcodeSelectionDrift: () => ({ + getDcodeSelectionDrift: async () => ({ changed: true, providerChanged: false, modelChanged: true, @@ -646,7 +647,7 @@ describe("created DCode sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(register).not.toHaveBeenCalled(); expect(error).toHaveBeenCalledWith(expect.stringContaining("sandbox still exists")); expect(error).toHaveBeenCalledWith(expect.stringContaining("rebuild is unsafe")); @@ -657,13 +658,13 @@ describe("created DCode sandbox finalization", () => { expect(error).toHaveBeenCalledWith(expect.stringContaining("nemoclaw onboard")); }); - it("rejects registration after a partial workspace restore (#6311)", () => { + it("rejects registration after a partial workspace restore (#6311)", async () => { const fixture = makeRestoreFixture(); const register = vi.fn(); const getDcodeSelectionDrift = vi.fn(); const error = vi.fn(); try { - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "dcode", @@ -698,7 +699,7 @@ describe("created DCode sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(error).toHaveBeenCalledWith( " Warning: workspace state restore was incomplete for sandbox 'dcode'.", @@ -726,11 +727,11 @@ describe("created DCode sandbox finalization", () => { } }); - it("keeps custom-image restores outside the managed config merge (#6311)", () => { + it("keeps custom-image restores outside the managed config merge (#6311)", async () => { const fixture = makeRestoreFixture(); const registeredConfigs: string[] = []; try { - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "custom-dcode", restoreBackupPath: fixture.backupPath, @@ -781,11 +782,11 @@ describe("created OpenClaw sandbox finalization", () => { }, ]; - it("skips image-plugin discovery for a managed OpenClaw image", () => { + it("skips image-plugin discovery for a managed OpenClaw image", async () => { const discoverFreshOpenClawImagePluginInstalls = vi.fn(); const register = vi.fn(); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: null, @@ -813,14 +814,14 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(undefined); }); - it("captures and registers a fresh image plugin baseline without a restore", () => { + it("captures and registers a fresh image plugin baseline without a restore", async () => { const order: string[] = []; const restoreRecreatedSandboxState = vi.fn(); const register = vi.fn(() => { order.push("register"); }); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: null, @@ -853,7 +854,7 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(pluginInstalls); }); - it("preserves the fresh image plugin baseline across recreation before registration", () => { + it("preserves the fresh image plugin baseline across recreation before registration", async () => { const order: string[] = []; const register = vi.fn(() => { order.push("register"); @@ -869,7 +870,7 @@ describe("created OpenClaw sandbox finalization", () => { }; }); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: "/tmp/openclaw-backup", @@ -911,7 +912,7 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(pluginInstalls, expect.anything()); }); - it("restores through a revalidated target row before publishing it (#10546)", () => { + it("restores through a revalidated target row before publishing it (#10546)", async () => { const order: string[] = []; const prepared = { name: "openclaw" } as SandboxEntry; const restoredTarget = { ...prepared } as SandboxEntry; @@ -925,7 +926,7 @@ describe("created OpenClaw sandbox finalization", () => { }); let revalidation = 0; - const result = finalizeCreatedSandbox( + const result = await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: "/tmp/managed-openclaw-backup", @@ -973,11 +974,11 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(undefined, publishedTarget); }); - it("does not publish the prepared target when managed restore fails (#10546)", () => { + it("does not publish the prepared target when managed restore fails (#10546)", async () => { const prepared = { name: "openclaw" } as SandboxEntry; const register = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "openclaw", @@ -1013,17 +1014,17 @@ describe("created OpenClaw sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(register).not.toHaveBeenCalled(); }); - it("fails closed before restore when prepared registration authority is unavailable", () => { + it("fails closed before restore when prepared registration authority is unavailable", async () => { const register = vi.fn(); const error = vi.fn(); const restoreRecreatedSandboxState = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "openclaw", @@ -1047,7 +1048,7 @@ describe("created OpenClaw sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(restoreRecreatedSandboxState).not.toHaveBeenCalled(); expect(register).not.toHaveBeenCalled(); @@ -1064,12 +1065,12 @@ describe("created OpenClaw sandbox finalization", () => { expect(error).toHaveBeenCalledWith(" Manual recovery: /tmp/managed-openclaw-backup"); }); - it("fails closed before restore and registration when provenance discovery fails", () => { + it("fails closed before restore and registration when provenance discovery fails", async () => { const restoreRecreatedSandboxState = vi.fn(); const register = vi.fn(); const error = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "openclaw", @@ -1098,7 +1099,7 @@ describe("created OpenClaw sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(restoreRecreatedSandboxState).not.toHaveBeenCalled(); expect(register).not.toHaveBeenCalled(); @@ -1116,11 +1117,11 @@ describe("created OpenClaw sandbox finalization", () => { expect(error).toHaveBeenCalledWith(" Manual recovery: /tmp/openclaw-backup"); }); - it("does not register after a marked backup provenance mismatch", () => { + it("does not register after a marked backup provenance mismatch", async () => { const register = vi.fn(); const error = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "openclaw", @@ -1157,7 +1158,7 @@ describe("created OpenClaw sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(register).not.toHaveBeenCalled(); expect(error).toHaveBeenCalledWith(expect.stringContaining("future rebuild would be unsafe")); diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index 8f62415b880..21f6a5bbe0c 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { restoreRecreatedSandboxStateWithManagedAuthority } from "../actions/sandbox/snapshot/restore-authority"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import * as buildContext from "../build-context"; import { resolveSandboxImageTagFromCreateOutput } from "../domain/sandbox/image-tag"; import type { @@ -83,7 +84,7 @@ export type CreatedSandboxFinalizationDeps = { model: string, preferredInferenceApi: string | null, endpointUrl: string | null, - ): SelectionDrift; + ): Promise; prepareRegistration?( openclawImagePluginInstalls?: readonly OpenClawImagePluginInstall[], ): SandboxEntry; @@ -703,6 +704,7 @@ export function createOnboardCreatedSandboxCompletion( workloadRuntime: WorkloadResolutionInput["runtime"], workload: WorkloadResolutionInput["workload"], note: (message: string) => void, + commandExecutor: OpenShellSandboxBufferedCommandExecutor, ): CreatedSandboxCompletionActions { const { provider, model, preferredInferenceApi, endpointUrl } = inference; const { createIntent, resolvedCreateIntent } = createContext; @@ -805,7 +807,7 @@ export function createOnboardCreatedSandboxCompletion( restoreRecreatedSandboxState: (name, backupPath, restoreOptions, resolveTarget) => restoreSelectedOnboardSnapshot(name, backupPath, restoreOptions, resolveTarget), getDcodeSelectionDrift: createDcodeSelectionDriftReader( - runCaptureOpenshell, + commandExecutor, () => gateway.gatewayName, ), note, @@ -817,10 +819,10 @@ export function createOnboardCreatedSandboxCompletion( } /** Restore state and validate the live managed DCode route before registry publication. */ -export function finalizeCreatedSandbox( +export async function finalizeCreatedSandbox( options: CreatedSandboxFinalizationOptions, deps: CreatedSandboxFinalizationDeps, -): SandboxEntry | void { +): Promise { const reportUnregisteredSandboxRecovery = (): void => { deps.error( ` NemoClaw left unregistered sandbox '${options.sandboxName}' in place because OpenShell can delete it only by mutable name.`, @@ -938,7 +940,7 @@ export function finalizeCreatedSandbox( } if (options.validateManagedDcode) { - const finalSelection = deps.getDcodeSelectionDrift( + const finalSelection = await deps.getDcodeSelectionDrift( options.sandboxName, options.provider, options.model, diff --git a/src/lib/onboard/created-sandbox-n1x-finalization.test.ts b/src/lib/onboard/created-sandbox-n1x-finalization.test.ts index 4a19efcb374..5981ca2fc15 100644 --- a/src/lib/onboard/created-sandbox-n1x-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-n1x-finalization.test.ts @@ -283,6 +283,13 @@ async function completeRegistration(createIntent: CreateIntent): Promise ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }, ); const created = { origin: "created", diff --git a/src/lib/onboard/custom-openclaw-runtime-diagnosis.test.ts b/src/lib/onboard/custom-openclaw-runtime-diagnosis.test.ts index 6a56d3467ae..113f8f7aab4 100644 --- a/src/lib/onboard/custom-openclaw-runtime-diagnosis.test.ts +++ b/src/lib/onboard/custom-openclaw-runtime-diagnosis.test.ts @@ -13,8 +13,8 @@ function probeResult(stdout: string) { } describe("classifyOpenClawRuntimeFailure", () => { - it("recognizes a normal managed runtime when startup and config artifacts exist", () => { - const result = classifyOpenClawRuntimeFailure("my-sandbox", () => + it("recognizes a normal managed runtime when startup and config artifacts exist", async () => { + const result = await classifyOpenClawRuntimeFailure("my-sandbox", async () => probeResult("nemoclaw-runtime-probe-v1 log=0 start=1 config=1"), ); expect(result).toEqual({ @@ -25,8 +25,8 @@ describe("classifyOpenClawRuntimeFailure", () => { }); }); - it("recognizes the base-only image when log, startup, and config artifacts are absent (#6108)", () => { - const result = classifyOpenClawRuntimeFailure("my-sandbox", () => + it("recognizes the base-only image when log, startup, and config artifacts are absent (#6108)", async () => { + const result = await classifyOpenClawRuntimeFailure("my-sandbox", async () => probeResult("nemoclaw-runtime-probe-v1 log=0 start=0 config=0"), ); expect(result.kind).toBe("base_only_image"); @@ -40,19 +40,21 @@ describe("classifyOpenClawRuntimeFailure", () => { ["gateway log only", "nemoclaw-runtime-probe-v1 log=1 start=0 config=0"], ["startup script only", "nemoclaw-runtime-probe-v1 log=0 start=1 config=0"], ["generated config only", "nemoclaw-runtime-probe-v1 log=0 start=0 config=1"], - ])("keeps a partial managed runtime inconclusive when it has %s", (_name, stdout) => { - const result = classifyOpenClawRuntimeFailure("my-sandbox", () => probeResult(stdout)); + ])("keeps a partial managed runtime inconclusive when it has %s", async (_name, stdout) => { + const result = await classifyOpenClawRuntimeFailure("my-sandbox", async () => + probeResult(stdout), + ); expect(result.kind).toBe("inconclusive"); expect(buildCustomOpenClawRuntimeFailureHints(result)).toBeNull(); }); - it("preserves an unreachable classification when sandbox exec fails", () => { - const result = classifyOpenClawRuntimeFailure("my-sandbox", () => null); + it("preserves an unreachable classification when sandbox exec fails", async () => { + const result = await classifyOpenClawRuntimeFailure("my-sandbox", async () => null); expect(result.kind).toBe("sandbox_unreachable"); }); - it("recognizes OpenShell-framed probe output", () => { - const result = classifyOpenClawRuntimeFailure("my-sandbox", () => + it("recognizes OpenShell-framed probe output", async () => { + const result = await classifyOpenClawRuntimeFailure("my-sandbox", async () => probeResult( "OpenShell sandbox exec output:\r\nstdout: nemoclaw-runtime-probe-v1 log=0 start=0 config=0\r\n", ), @@ -76,8 +78,8 @@ describe("classifyOpenClawRuntimeFailure", () => { probeResult("\fnemoclaw-runtime-probe-v1 log=0 start=0 config=0"), ], ["case-altered marker", probeResult("NEMOCLAW-runtime-probe-v1 log=0 start=0 config=0")], - ])("keeps a %s inconclusive", (_name, probe) => { - const result = classifyOpenClawRuntimeFailure("my-sandbox", () => probe); + ])("keeps a %s inconclusive", async (_name, probe) => { + const result = await classifyOpenClawRuntimeFailure("my-sandbox", async () => probe); expect(result).toEqual({ kind: "inconclusive", gatewayLogPresent: null, diff --git a/src/lib/onboard/custom-openclaw-runtime-diagnosis.ts b/src/lib/onboard/custom-openclaw-runtime-diagnosis.ts index b4089f6d766..6a597dc3745 100644 --- a/src/lib/onboard/custom-openclaw-runtime-diagnosis.ts +++ b/src/lib/onboard/custom-openclaw-runtime-diagnosis.ts @@ -4,7 +4,7 @@ export type SandboxCommandExecutor = ( name: string, script: string, -) => { status: number; stdout: string; stderr: string } | null; +) => Promise<{ status: number; stdout: string; stderr: string } | null>; export type OpenClawRuntimeFailureKind = | "normal_runtime" @@ -53,11 +53,11 @@ export function shouldDiagnoseCustomOpenClawRuntime( * Distinguish the documented sandbox-base-only failure from an ordinary * gateway startup failure without reading config or log contents. */ -export function classifyOpenClawRuntimeFailure( +export async function classifyOpenClawRuntimeFailure( sandboxName: string, executeSandboxCommand: SandboxCommandExecutor, -): OpenClawRuntimeFailureDiagnosis { - const result = executeSandboxCommand(sandboxName, OPENCLAW_RUNTIME_PROBE); +): Promise { + const result = await executeSandboxCommand(sandboxName, OPENCLAW_RUNTIME_PROBE); if (!result) { return { kind: "sandbox_unreachable", diff --git a/src/lib/onboard/dcode-selection-drift.test.ts b/src/lib/onboard/dcode-selection-drift.test.ts index 1def442b9c4..c088cd2c285 100644 --- a/src/lib/onboard/dcode-selection-drift.test.ts +++ b/src/lib/onboard/dcode-selection-drift.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { normalizeManagedDcodeModelName } from "../inference/managed-dcode/identity"; import { createDcodeSelectionDriftReader, @@ -15,13 +16,37 @@ import { } from "./dcode-selection-drift"; function driftDeps( - runCaptureOpenshell: DcodeSelectionDriftDeps["runCaptureOpenshell"], + run: () => string | null | undefined | Promise, requestedEndpointUrl?: string | null, ): DcodeSelectionDriftDeps { return { getGatewayName: () => "nemoclaw-18081", requestedEndpointUrl, - runCaptureOpenshell, + commandExecutor: bufferedExecutor(run), + }; +} + +function bufferedExecutor( + run: () => string | null | undefined | Promise, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async () => { + const output = await run(); + return output == null + ? { + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + }, + stdout: "", + stderr: "", + } + : { + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: output, + stderr: "", + }; + }), }; } @@ -81,14 +106,14 @@ describe("live DCode selection drift", () => { }); }); - it("accepts the generated OpenRouter identity (#9555)", () => { + it("accepts the generated OpenRouter identity (#9555)", async () => { const output = identity({ Provider: "openrouter", Model: "openrouter:nvidia/nemotron-3-ultra-550b-a55b", }); expect( - getDcodeSelectionDrift( + await getDcodeSelectionDrift( "alpha", "openrouter-api", "nvidia/nemotron-3-ultra-550b-a55b", @@ -105,18 +130,18 @@ describe("live DCode selection drift", () => { }); }); - it("accepts the generated OpenRouter identity for its compatible endpoint (#9555)", () => { + it("accepts the generated OpenRouter identity for its compatible endpoint (#9555)", async () => { const output = identity({ Provider: "openrouter", Model: "openrouter:nvidia/nemotron-3-ultra-550b-a55b", }); const readDcodeSelectionDrift = createDcodeSelectionDriftReader( - () => output, + bufferedExecutor(() => output), () => "nemoclaw-18081", ); expect( - readDcodeSelectionDrift( + await readDcodeSelectionDrift( "alpha", "compatible-endpoint", "nvidia/nemotron-3-ultra-550b-a55b", @@ -136,18 +161,18 @@ describe("live DCode selection drift", () => { "https://user:password@openrouter.ai/api/v1", "https://openrouter.ai/api/v1?route=other", "https://openrouter.ai/api/v1#route", - ])("rejects a noncanonical OpenRouter-compatible endpoint: %s (#9555)", (endpointUrl) => { + ])("rejects a noncanonical OpenRouter-compatible endpoint: %s (#9555)", async (endpointUrl) => { const output = identity({ Provider: "openrouter", Model: "openrouter:nvidia/nemotron-3-ultra-550b-a55b", }); const readDcodeSelectionDrift = createDcodeSelectionDriftReader( - () => output, + bufferedExecutor(() => output), () => "nemoclaw-18081", ); expect( - readDcodeSelectionDrift( + await readDcodeSelectionDrift( "alpha", "compatible-endpoint", "nvidia/nemotron-3-ultra-550b-a55b", @@ -162,18 +187,18 @@ describe("live DCode selection drift", () => { }); }); - it("keeps ordinary compatible endpoints on the OpenAI identity (#9555)", () => { + it("keeps ordinary compatible endpoints on the OpenAI identity (#9555)", async () => { const output = identity({ Provider: "compatible-endpoint", Model: "openai:model-a", }); const readDcodeSelectionDrift = createDcodeSelectionDriftReader( - () => output, + bufferedExecutor(() => output), () => "nemoclaw-18081", ); expect( - readDcodeSelectionDrift( + await readDcodeSelectionDrift( "alpha", "compatible-endpoint", "model-a", @@ -188,9 +213,9 @@ describe("live DCode selection drift", () => { }); }); - it("rejects an OpenAI identity for an OpenRouter selection (#9555)", () => { + it("rejects an OpenAI identity for an OpenRouter selection (#9555)", async () => { expect( - getDcodeSelectionDrift( + await getDcodeSelectionDrift( "alpha", "openrouter-api", "nvidia/nemotron-3-ultra-550b-a55b", @@ -214,16 +239,16 @@ describe("live DCode selection drift", () => { ).toMatchObject({ model: "openai:minimax/minimax-m2.5:free" }); }); - it("accepts only a live identity matching the requested selection (#6311)", () => { - const runCaptureOpenshell = vi.fn(() => identity()); + it("accepts only a live identity matching the requested selection (#6311)", async () => { + const commandExecutor = bufferedExecutor(() => identity()); expect( - getDcodeSelectionDrift( + await getDcodeSelectionDrift( "alpha", "nvidia-prod", "nvidia/nemotron-3-super-120b-a12b", null, - driftDeps(runCaptureOpenshell), + { commandExecutor, getGatewayName: () => "nemoclaw-18081" }, ), ).toEqual({ changed: false, @@ -233,20 +258,11 @@ describe("live DCode selection drift", () => { existingModel: "openai:nvidia/nemotron-3-super-120b-a12b", unknown: false, }); - expect(runCaptureOpenshell).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "--name", - "alpha", - "--gateway", - "nemoclaw-18081", - "--", - "/usr/local/bin/dcode", - "identity", - ], - { ignoreError: true }, - ); + expect(commandExecutor.runBuffered).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw-18081" }, + command: ["/usr/local/bin/dcode", "identity"], + }); }); it.each([ @@ -255,9 +271,9 @@ describe("live DCode selection drift", () => { identity({ Endpoint: "https://old.example/v1" }), ])( "reports provider drift for upstream, route, or endpoint changes [case %#] (#6311)", - (output) => { + async (output) => { expect( - getDcodeSelectionDrift( + await getDcodeSelectionDrift( "alpha", "nvidia-prod", "nvidia/nemotron-3-super-120b-a12b", @@ -273,9 +289,9 @@ describe("live DCode selection drift", () => { }, ); - it("reports model drift from the live DCode config (#6311)", () => { + it("reports model drift from the live DCode config (#6311)", async () => { expect( - getDcodeSelectionDrift( + await getDcodeSelectionDrift( "alpha", "nvidia-prod", "new-model", @@ -300,9 +316,9 @@ describe("live DCode selection drift", () => { throw new Error("sandbox unavailable"); }, ], - ])("fails closed for %s (#6311)", (_name, runCaptureOpenshell) => { + ])("fails closed for %s (#6311)", async (_name, runCaptureOpenshell) => { expect( - getDcodeSelectionDrift( + await getDcodeSelectionDrift( "alpha", "nvidia-prod", "model-a", diff --git a/src/lib/onboard/dcode-selection-drift.ts b/src/lib/onboard/dcode-selection-drift.ts index 39f12f2244d..f0afce7a5d2 100644 --- a/src/lib/onboard/dcode-selection-drift.ts +++ b/src/lib/onboard/dcode-selection-drift.ts @@ -3,6 +3,8 @@ import { getSandboxInferenceConfig } from "../inference/config"; import { resolveManagedDcodeIdentity } from "../inference/managed-dcode/identity"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { namedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import type { SelectionDrift } from "./selection-drift"; export type DcodeInferenceIdentity = { @@ -15,10 +17,7 @@ export type DcodeInferenceIdentity = { export type DcodeSelectionDriftDeps = { getGatewayName(): string; requestedEndpointUrl?: string | null; - runCaptureOpenshell( - args: string[], - options?: { ignoreError?: boolean }, - ): string | null | undefined; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; }; export type DcodeSelectionDriftReader = ( @@ -27,7 +26,7 @@ export type DcodeSelectionDriftReader = ( requestedModel: string | null, preferredInferenceApi: string | null, requestedEndpointUrl: string | null, -) => SelectionDrift; +) => Promise; const IDENTITY_FIELDS = ["Route", "Provider", "Model", "Endpoint"] as const; type IdentityField = (typeof IDENTITY_FIELDS)[number]; @@ -110,13 +109,13 @@ export function getExpectedDcodeInferenceIdentity( }; } -export function getDcodeSelectionDrift( +export async function getDcodeSelectionDrift( sandboxName: string, requestedProvider: string | null, requestedModel: string | null, preferredInferenceApi: string | null, deps: DcodeSelectionDriftDeps, -): SelectionDrift { +): Promise { const expected = getExpectedDcodeInferenceIdentity( requestedProvider, requestedModel, @@ -125,22 +124,16 @@ export function getDcodeSelectionDrift( ); if (!sandboxName || !expected) return { ...UNKNOWN_SELECTION_DRIFT }; - let output: string | null | undefined; + let output: string | null = null; try { - output = deps.runCaptureOpenshell( - [ - "sandbox", - "exec", - "--name", - sandboxName, - "--gateway", - deps.getGatewayName(), - "--", - "/usr/local/bin/dcode", - "identity", - ], - { ignoreError: true }, - ); + const completed = await deps.commandExecutor.runBuffered({ + sandboxName, + target: namedOpenShellGateway(deps.getGatewayName()), + command: ["/usr/local/bin/dcode", "identity"], + }); + if (completed.outcome.kind === "completed" && completed.outcome.exitCode === 0) { + output = completed.stdout; + } } catch { return { ...UNKNOWN_SELECTION_DRIFT }; } @@ -164,7 +157,7 @@ export function getDcodeSelectionDrift( } export function createDcodeSelectionDriftReader( - runCaptureOpenshell: DcodeSelectionDriftDeps["runCaptureOpenshell"], + commandExecutor: OpenShellSandboxBufferedCommandExecutor, getGatewayName: DcodeSelectionDriftDeps["getGatewayName"], ): DcodeSelectionDriftReader { return ( @@ -176,7 +169,7 @@ export function createDcodeSelectionDriftReader( ) => getDcodeSelectionDrift(sandboxName, requestedProvider, requestedModel, preferredInferenceApi, { getGatewayName, - runCaptureOpenshell, + commandExecutor, requestedEndpointUrl, }); } diff --git a/src/lib/onboard/docker-gpu-local-inference.test.ts b/src/lib/onboard/docker-gpu-local-inference.test.ts index 163572ee5b3..c9dfc42201d 100644 --- a/src/lib/onboard/docker-gpu-local-inference.test.ts +++ b/src/lib/onboard/docker-gpu-local-inference.test.ts @@ -36,7 +36,7 @@ function gpuPatchOptions(extra: Record = {}) { // emits either `NO_CURL` or `HTTP_`. This mock answers with `stdout`. // Typed `(sandboxName, script)` so `.mock.calls[i][1]` (the script) type-checks. function execEmitting(stdout: string, { status = 0, stderr = "" } = {}) { - return vi.fn((_sandboxName: string, _script: string) => ({ status, stdout, stderr })); + return vi.fn(async (_sandboxName: string, _script: string) => ({ status, stdout, stderr })); } describe("shouldUseDockerGpuPatchHostNetwork", () => { @@ -170,14 +170,18 @@ describe("getSandboxRuntimeInferenceEndpoint", () => { }); describe("verifyDockerGpuSandboxLocalInference", () => { - it("skips for non-local providers", () => { - const result = verifyDockerGpuSandboxLocalInference(GPU_CONFIG, "build", gpuPatchOptions()); + it("skips for non-local providers", async () => { + const result = await verifyDockerGpuSandboxLocalInference( + GPU_CONFIG, + "build", + gpuPatchOptions(), + ); expect(result).toEqual({ status: "skipped", reason: "not-local-provider" }); }); - it("skips the compatibility-only inference gate on the native route", () => { + it("skips the compatibility-only inference gate on the native route", async () => { const execInSandbox = vi.fn(); - const result = verifyDockerGpuSandboxLocalInference( + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ selectedRoute: "native", deps: { execInSandbox } }), @@ -187,9 +191,9 @@ describe("verifyDockerGpuSandboxLocalInference", () => { expect(execInSandbox).not.toHaveBeenCalled(); }); - it("probes inference.local from the runtime context, never a loopback or docker exec", () => { + it("probes inference.local from the runtime context, never a loopback or docker exec", async () => { const execInSandbox = execEmitting("HTTP_200"); - const result = verifyDockerGpuSandboxLocalInference( + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "vllm-local", gpuPatchOptions({ deps: { execInSandbox, sleep: vi.fn() } }), @@ -208,8 +212,8 @@ describe("verifyDockerGpuSandboxLocalInference", () => { expect(script).not.toContain("docker exec"); }); - it("fails on a 4xx because the route is reached but unusable instead of satisfying the proof (#4509)", () => { - const result = verifyDockerGpuSandboxLocalInference( + it("fails on a 4xx because the route is reached but unusable instead of satisfying the proof (#4509)", async () => { + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ deps: { execInSandbox: execEmitting("HTTP_404"), sleep: vi.fn() } }), @@ -221,10 +225,10 @@ describe("verifyDockerGpuSandboxLocalInference", () => { } }); - it("fails as unreachable and retries on HTTP 000 (#4509)", () => { + it("fails as unreachable and retries on HTTP 000 (#4509)", async () => { const execInSandbox = execEmitting("HTTP_000"); const sleep = vi.fn(); - const result = verifyDockerGpuSandboxLocalInference( + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ deps: { execInSandbox, sleep } }), @@ -243,8 +247,8 @@ describe("verifyDockerGpuSandboxLocalInference", () => { expect(sleep).toHaveBeenNthCalledWith(2, 2_000); }); - it("fails when the inference route is up but the local backend errors (HTTP 502)", () => { - const result = verifyDockerGpuSandboxLocalInference( + it("fails when the inference route is up but the local backend errors (HTTP 502)", async () => { + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ deps: { execInSandbox: execEmitting("HTTP_502"), sleep: vi.fn() } }), @@ -256,9 +260,9 @@ describe("verifyDockerGpuSandboxLocalInference", () => { } }); - it("soft-skips when the sandbox image genuinely lacks curl (custom --from base)", () => { + it("soft-skips when the sandbox image genuinely lacks curl (custom --from base)", async () => { const log = vi.fn(); - const result = verifyDockerGpuSandboxLocalInference( + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ log, deps: { execInSandbox: execEmitting("NO_CURL"), sleep: vi.fn() } }), @@ -267,8 +271,8 @@ describe("verifyDockerGpuSandboxLocalInference", () => { expect(log).toHaveBeenCalledWith(expect.stringContaining("curl is not available")); }); - it("fails (exec) — not soft-skip — when sandbox exec cannot run", () => { - const result = verifyDockerGpuSandboxLocalInference( + it("fails (exec) — not soft-skip — when sandbox exec cannot run", async () => { + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ deps: { execInSandbox: vi.fn(() => null), sleep: vi.fn() } }), @@ -280,8 +284,8 @@ describe("verifyDockerGpuSandboxLocalInference", () => { } }); - it("fails (exec) when exec runs but emits no sentinel (sandbox Error / exec denied)", () => { - const result = verifyDockerGpuSandboxLocalInference( + it("fails (exec) when exec runs but emits no sentinel (sandbox Error / exec denied)", async () => { + const result = await verifyDockerGpuSandboxLocalInference( GPU_CONFIG, "ollama-local", gpuPatchOptions({ diff --git a/src/lib/onboard/docker-gpu-local-inference.ts b/src/lib/onboard/docker-gpu-local-inference.ts index 46c1cb1e9e6..fa1c68e7b53 100644 --- a/src/lib/onboard/docker-gpu-local-inference.ts +++ b/src/lib/onboard/docker-gpu-local-inference.ts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { retryUntil } from "../core/retry"; +import { retryUntilAsync } from "../core/retry"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { getLocalProviderLabel } from "../inference/local"; import type { SandboxGpuProofResult } from "../state/registry"; @@ -148,8 +149,9 @@ export type SandboxExecResult = { } | null; export type DockerGpuSandboxInferenceVerifyDeps = { - execInSandbox?: (sandboxName: string, script: string) => SandboxExecResult; - sleep?: (milliseconds: number) => void; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; + execInSandbox?: (sandboxName: string, script: string) => Promise; + sleep?: (milliseconds: number) => void | Promise; }; export type DockerGpuSandboxInferenceVerification = @@ -192,14 +194,14 @@ type RuntimeProbeOutcome = * route resolves and responds; `000` means DNS failure or connection refused — * the reopened-#4509 symptom. */ -function probeSandboxRuntimeInference( +async function probeSandboxRuntimeInference( sandboxName: string, endpoint: string, deps: { execInSandbox: NonNullable; sleep: NonNullable; }, -): RuntimeProbeOutcome { +): Promise { // Single-quote the endpoint (POSIX-escaping any embedded quotes) so it can // never break out of the curl argument. It is a constant today, but the // signature accepts any string — keep the shell construction injection-safe. @@ -210,8 +212,8 @@ function probeSandboxRuntimeInference( `--connect-timeout ${DOCKER_GPU_INFERENCE_PROBE_CONNECT_TIMEOUT_SECS} ` + `--max-time ${DOCKER_GPU_INFERENCE_PROBE_MAX_TIME_SECS} ${safeEndpoint} 2>/dev/null || echo 000); ` + `echo "HTTP_$code"`; - const probe = (): RuntimeProbeOutcome => { - const result = deps.execInSandbox(sandboxName, script); + const probe = async (): Promise => { + const result = await deps.execInSandbox(sandboxName, script); if (result === null) { return { kind: "exec-failed", @@ -251,13 +253,15 @@ function probeSandboxRuntimeInference( }; }; - return retryUntil(probe, { + return retryUntilAsync(probe, { accept: (result) => result.kind === "ok" || result.kind === "no-curl", retryDelaysMs: Array.from( { length: DOCKER_GPU_INFERENCE_PROBE_MAX_ATTEMPTS - 1 }, () => DOCKER_GPU_INFERENCE_PROBE_RETRY_DELAY_MS, ), - sleep: deps.sleep, + sleep: async (milliseconds) => { + await deps.sleep(milliseconds); + }, }); } @@ -275,14 +279,14 @@ function probeSandboxRuntimeInference( * sandbox image genuinely lacks `curl` — OpenClaw's HTTP client does not need * it, so a missing probe tool must not block an otherwise usable sandbox. */ -export function verifyDockerGpuSandboxLocalInference( +export async function verifyDockerGpuSandboxLocalInference( config: DockerGpuLocalInferenceConfig, provider: string | null | undefined, options: DockerGpuLocalInferenceOptions & { sandboxName: string; deps?: DockerGpuSandboxInferenceVerifyDeps; }, -): DockerGpuSandboxInferenceVerification { +): Promise { if (options.selectedRoute !== "compatibility") { return { status: "skipped", reason: "not-docker-gpu-patch" }; } @@ -295,14 +299,19 @@ export function verifyDockerGpuSandboxLocalInference( } const deps = options.deps ?? {}; - const execInSandbox = deps.execInSandbox ?? executeSandboxCommandForVerification; + const execInSandbox = + deps.execInSandbox ?? + (async (sandboxName: string, script: string) => { + if (!deps.commandExecutor) return null; + return await executeSandboxCommandForVerification(sandboxName, script, deps.commandExecutor); + }); const sleep = deps.sleep ?? ((milliseconds: number) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.max(0, milliseconds)); }); - const outcome = probeSandboxRuntimeInference(options.sandboxName, endpoint, { + const outcome = await probeSandboxRuntimeInference(options.sandboxName, endpoint, { execInSandbox, sleep, }); @@ -415,7 +424,7 @@ export async function verifyGpuSandboxAfterReady( options: GpuSandboxAfterReadyOptions, ): Promise { await verifyGpuSandboxAccessAfterReady(config, options); - verifyGpuSandboxLocalInferenceAfterReady(config, provider, options); + await verifyGpuSandboxLocalInferenceAfterReady(config, provider, options); } export async function verifyGpuSandboxAccessAfterReady( @@ -451,15 +460,15 @@ export async function verifyGpuSandboxAccessAfterReady( } } -export function verifyGpuSandboxLocalInferenceAfterReady( +export async function verifyGpuSandboxLocalInferenceAfterReady( config: DockerGpuLocalInferenceConfig, provider: string | null | undefined, options: Omit & { beforeSuccess?: () => void; }, -): void { +): Promise { if (options.selectedRoute !== "compatibility") return; - const verification = verifyDockerGpuSandboxLocalInference(config, provider, { + const verification = await verifyDockerGpuSandboxLocalInference(config, provider, { sandboxName: options.sandboxName, dockerDriverGateway: options.dockerDriverGateway, selectedRoute: options.selectedRoute, @@ -507,7 +516,7 @@ export async function verifyGpuSandboxLocalInferenceAndCommitAfterReady( persistFinalHandoffAcknowledgement?: () => void, ): Promise { try { - verifyGpuSandboxLocalInferenceAfterReady(config, provider, { + await verifyGpuSandboxLocalInferenceAfterReady(config, provider, { ...options, beforeSuccess: revalidateBeforeCommit, }); diff --git a/src/lib/onboard/docker-gpu-patch-finalize.test.ts b/src/lib/onboard/docker-gpu-patch-finalize.test.ts index de5123d4451..c5aaac05c34 100644 --- a/src/lib/onboard/docker-gpu-patch-finalize.test.ts +++ b/src/lib/onboard/docker-gpu-patch-finalize.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { collectDockerGpuPatchDiagnostics, type DockerGpuPatchResult } from "./docker-gpu-patch"; import { type DockerGpuPatchFinalizeOutcome, @@ -39,10 +40,43 @@ function exactDeferredCreateResult(): DockerGpuPatchResult { }; } +function commandExecutorThrough( + runOpenshell: ( + args: string[], + opts?: Record, + ) => { + status: number | null; + stdout?: string; + stderr?: string; + }, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async (request) => { + const result = runOpenshell( + ["sandbox", "exec", "-n", request.sandboxName, "--", ...request.command], + { ignoreError: true, suppressOutput: true }, + ); + return { + outcome: + result.status === null + ? { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + } + : { kind: "completed" as const, exitCode: result.status }, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; + }), + }; +} + function readyHandoffDeps() { + const runOpenshell = vi.fn(() => ({ status: 0 })); return { runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:02 Ready\n"), - runOpenshell: vi.fn(() => ({ status: 0 })), + runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), }; } @@ -136,13 +170,13 @@ describe("isExactOpenShellDockerSandboxReplacement", () => { }); describe("finalizeDockerGpuPatchBackup", () => { - it("retains both containers when final acknowledgement probes are unavailable (#9531)", () => { + it("retains both containers when final acknowledgement probes are unavailable (#9531)", async () => { const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn(() => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); expect( - finalizeDockerGpuPatchBackup( + await finalizeDockerGpuPatchBackup( { result: exactDeferredCreateResult(), supervisorReady: true, @@ -164,7 +198,7 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(dockerStart).not.toHaveBeenCalled(); }); - it("uses authoritative OpenShell stop/start around the exact Docker commit (#9531)", () => { + it("uses authoritative OpenShell stop/start around the exact Docker commit (#9531)", async () => { const result = exactDeferredCreateResult(); const events: string[] = []; const dockerStop = vi.fn(() => { @@ -210,7 +244,7 @@ describe("finalizeDockerGpuPatchBackup", () => { return response.result; }); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -224,6 +258,7 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart, runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), now: () => new Date("2026-08-23T10:00:02Z"), }, @@ -278,7 +313,7 @@ describe("finalizeDockerGpuPatchBackup", () => { ); }); - it("reconciles a nonzero OpenShell start within the remaining handoff budget (#11096)", () => { + it("reconciles a nonzero OpenShell start within the remaining handoff budget (#11096)", async () => { const result = exactDeferredCreateResult(); let currentTimeMs = new Date("2026-09-04T07:42:01Z").getTime(); const phases = ["Provisioning", "Ready"]; @@ -303,7 +338,8 @@ describe("finalizeDockerGpuPatchBackup", () => { : { status: 0, stdout: "true\n" }; }); - const outcome = finalizeDockerGpuPatchBackup( + const commandExecutor = commandExecutorThrough(runOpenshell); + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -317,6 +353,7 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart: vi.fn(() => ({ status: 0 })), runCaptureOpenshell, runOpenshell, + commandExecutor, sleep: vi.fn(), now: () => new Date(currentTimeMs), }, @@ -339,9 +376,10 @@ describe("finalizeDockerGpuPatchBackup", () => { ["sandbox", "exec", "-n", "alpha", "--", "true"], expect.any(Object), ); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); }); - it("rejects a running replacement that stays Provisioning through the remaining handoff budget (#11096)", () => { + it("rejects a running replacement that stays Provisioning through the remaining handoff budget (#11096)", async () => { const result = exactDeferredCreateResult(); const startedAtMs = new Date("2026-09-04T07:42:01Z").getTime(); let currentTimeMs = startedAtMs; @@ -365,7 +403,7 @@ describe("finalizeDockerGpuPatchBackup", () => { : { status: 0, stdout: "true\n" }; }); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -379,6 +417,7 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart: vi.fn(() => ({ status: 0 })), runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn((seconds: number) => { currentTimeMs += seconds * 1000; }), @@ -403,11 +442,15 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(firstListTimeoutMs).toBeLessThanOrEqual(500); }); - it("fails immediately when OpenShell reports Deleting after the final start (#9531)", () => { + it("fails immediately when OpenShell reports Deleting after the final start (#9531)", async () => { const result = exactDeferredCreateResult(); const events: string[] = []; const sleep = vi.fn(); - const outcome = finalizeDockerGpuPatchBackup( + const runOpenshell = vi.fn((args: string[]) => { + events.push(args[1] === "stop" ? "stop through OpenShell" : "start through OpenShell"); + return { status: 0 }; + }); + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -428,10 +471,8 @@ describe("finalizeDockerGpuPatchBackup", () => { events.push("observe deleting"); return "alpha 2026-08-23 10:00:02 Deleting\n"; }), - runOpenshell: vi.fn((args: string[]) => { - events.push(args[1] === "stop" ? "stop through OpenShell" : "start through OpenShell"); - return { status: 0 }; - }), + runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), dockerRun: vi.fn(() => ({ status: 0, stdout: `${result.newContainerId}\n` })), sleep, }, @@ -456,7 +497,7 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(sleep).not.toHaveBeenCalled(); }); - it("scopes the final sole-container proof to the replacement gateway namespace", () => { + it("scopes the final sole-container proof to the replacement gateway namespace", async () => { const result = exactDeferredCreateResult(); const dockerRun = vi.fn((args: readonly string[]) => args[0] === "inspect" @@ -466,7 +507,8 @@ describe("finalizeDockerGpuPatchBackup", () => { : { status: 0, stdout: `${result.newContainerId}\n` }, ); - const outcome = finalizeDockerGpuPatchBackup( + const runOpenshell = vi.fn(() => ({ status: 0 })); + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -479,7 +521,8 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart: vi.fn(() => ({ status: 0 })), dockerRun, runCaptureOpenshell: vi.fn(() => "restored-name 2026-08-23 01:40:37 Ready\n"), - runOpenshell: vi.fn(() => ({ status: 0 })), + runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), }, ); @@ -520,7 +563,7 @@ describe("finalizeDockerGpuPatchBackup", () => { ]); }); - it("rejects multiple same-name containers within the replacement gateway namespace", () => { + it("rejects multiple same-name containers within the replacement gateway namespace", async () => { const result = exactDeferredCreateResult(); const dockerRun = vi.fn((args: readonly string[]) => args[0] === "inspect" @@ -532,7 +575,8 @@ describe("finalizeDockerGpuPatchBackup", () => { : { status: 0, stdout: `${result.newContainerId}\n` }, ); - const outcome = finalizeDockerGpuPatchBackup( + const runOpenshell = vi.fn(() => ({ status: 0 })); + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -545,7 +589,8 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart: vi.fn(() => ({ status: 0 })), dockerRun, runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 01:40:37 Ready\n"), - runOpenshell: vi.fn(() => ({ status: 0 })), + runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), }, ); @@ -558,7 +603,7 @@ describe("finalizeDockerGpuPatchBackup", () => { }); }); - it("does not require name absence between authoritative stop and start (#10153)", () => { + it("does not require name absence between authoritative stop and start (#10153)", async () => { const result = exactDeferredCreateResult(); const events: string[] = []; const dockerRunResults = { @@ -581,7 +626,7 @@ describe("finalizeDockerGpuPatchBackup", () => { return { status: 0 }; }); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -598,6 +643,7 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart, runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), }, ); @@ -618,14 +664,15 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(runOpenshell).not.toHaveBeenCalledWith(["sandbox", "list"], expect.any(Object)); }); - it("does not mutate containers when authoritative OpenShell stop fails (#10153)", () => { + it("does not mutate containers when authoritative OpenShell stop fails (#10153)", async () => { const result = exactDeferredCreateResult(); const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn(() => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 01:40:35 Ready\n"); - const outcome = finalizeDockerGpuPatchBackup( + const runOpenshell = vi.fn(() => ({ status: 1 })); + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -638,7 +685,8 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerRun: vi.fn(), dockerStart, runCaptureOpenshell, - runOpenshell: vi.fn(() => ({ status: 1 })), + runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), }, ); @@ -654,12 +702,12 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(runCaptureOpenshell).not.toHaveBeenCalled(); }); - it("rolls back to the backup container when supervisor reconnect failed", () => { + it("rolls back to the backup container when supervisor reconnect failed", async () => { const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn((_name: string) => ({ status: 0 })); const dockerRename = vi.fn((_old: string, _next: string) => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: false }, { dockerStop, dockerRm, dockerRename, dockerStart }, ); @@ -688,7 +736,7 @@ describe("finalizeDockerGpuPatchBackup", () => { ).toBe(false); }); - it("reports rolledBack=false when restoring the backup fails", () => { + it("reports rolledBack=false when restoring the backup fails", async () => { const newContainerId = "e".repeat(64); const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn((_name: string) => ({ status: 0 })); @@ -697,7 +745,7 @@ describe("finalizeDockerGpuPatchBackup", () => { stderr: "no such container", })); const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: { ...deferredCreateResult(), newContainerId }, supervisorReady: false, @@ -720,8 +768,8 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(diagnostics.summary).not.toContain("docker rm -f"); }); - it("does not report rollback success when restarting the backup has no exit status", () => { - const outcome = finalizeDockerGpuPatchBackup( + it("does not report rollback success when restarting the backup has no exit status", async () => { + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: false }, { dockerStop: vi.fn(() => ({ status: 0 })), @@ -740,10 +788,10 @@ describe("finalizeDockerGpuPatchBackup", () => { }); }); - it("is a no-op when the backup was already removed by the patch helper", () => { + it("is a no-op when the backup was already removed by the patch helper", async () => { const dockerRm = vi.fn((_name: string) => ({ status: 0 })); const result = { ...deferredCreateResult(), backupRemoved: true }; - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -756,14 +804,14 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(dockerRm).not.toHaveBeenCalled(); }); - it("reports backupRemoved=false when supervisor reconnect succeeded but docker rm of the backup failed", () => { + it("reports backupRemoved=false when supervisor reconnect succeeded but docker rm of the backup failed", async () => { const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn((_name: string) => ({ status: 1, stderr: "Error response from daemon: container is in use", })); const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: true, @@ -788,11 +836,11 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(dockerStart).not.toHaveBeenCalled(); }); - it("fails closed when backup removal has no exit status", () => { + it("fails closed when backup removal has no exit status", async () => { const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn((_name: string) => ({ status: null, stderr: "timed out" })); const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: true, @@ -813,12 +861,12 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(dockerStart).not.toHaveBeenCalled(); }); - it("retains the backup when the replacement cannot be stopped for the final handoff", () => { + it("retains the backup when the replacement cannot be stopped for the final handoff", async () => { const dockerStop = vi.fn(() => ({ status: 1 })); const dockerRm = vi.fn(() => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: true, @@ -839,7 +887,7 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(dockerStart).not.toHaveBeenCalled(); }); - it("rejects a nonzero OpenShell start when the exact replacement is not running (#11096)", () => { + it("rejects a nonzero OpenShell start when the exact replacement is not running (#11096)", async () => { const result = exactDeferredCreateResult(); const runOpenshell = vi .fn() @@ -854,7 +902,7 @@ describe("finalizeDockerGpuPatchBackup", () => { ? { status: 0, stdout: "current-gateway\n" } : { status: 0, stdout: "false\n" }; }); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result, supervisorReady: true, @@ -868,6 +916,7 @@ describe("finalizeDockerGpuPatchBackup", () => { dockerStart: vi.fn(() => ({ status: 1 })), runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), }, ); @@ -894,9 +943,9 @@ describe("finalizeDockerGpuPatchBackup", () => { ); }); - it("records a remaining exact-ID replacement when removal fails (#7996)", () => { + it("records a remaining exact-ID replacement when removal fails (#7996)", async () => { const newContainerId = "a".repeat(64); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: { ...deferredCreateResult(), newContainerId }, supervisorReady: false, @@ -919,9 +968,9 @@ describe("finalizeDockerGpuPatchBackup", () => { }); }); - it("records confirmed absence when exact-ID removal reports failure but listing is empty (#7996)", () => { + it("records confirmed absence when exact-ID removal reports failure but listing is empty (#7996)", async () => { const newContainerId = "b".repeat(64); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: { ...deferredCreateResult(), newContainerId }, supervisorReady: false, @@ -944,14 +993,14 @@ describe("finalizeDockerGpuPatchBackup", () => { }); }); - it("retries a failed replacement observation before confirming absence (#7996)", () => { + it("retries a failed replacement observation before confirming absence (#7996)", async () => { const newContainerId = "c".repeat(64); const dockerRun = vi .fn() .mockReturnValueOnce({ status: 1, stderr: "daemon unavailable" }) .mockReturnValueOnce({ status: 0, stdout: "" }); const sleep = vi.fn(); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: { ...deferredCreateResult(), newContainerId }, supervisorReady: false, @@ -972,11 +1021,11 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(sleep).toHaveBeenCalledWith(0.5); }); - it("keeps replacement presence unknown after repeated daemon errors (#7996)", () => { + it("keeps replacement presence unknown after repeated daemon errors (#7996)", async () => { const newContainerId = "d".repeat(64); const dockerRun = vi.fn(() => ({ status: 1, stderr: "daemon unavailable" })); const sleep = vi.fn(); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: { ...deferredCreateResult(), newContainerId }, supervisorReady: false, @@ -1004,9 +1053,9 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(diagnostics.summary).not.toContain("openshell sandbox delete"); }); - it("stops rollback before start when rename has no exit status", () => { + it("stops rollback before start when rename has no exit status", async () => { const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: false }, { dockerStop: vi.fn(() => ({ status: 0 })), @@ -1025,8 +1074,8 @@ describe("finalizeDockerGpuPatchBackup", () => { expect(dockerStart).not.toHaveBeenCalled(); }); - it("fails closed when rollback start has no exit status", () => { - const outcome = finalizeDockerGpuPatchBackup( + it("fails closed when rollback start has no exit status", async () => { + const outcome = await finalizeDockerGpuPatchBackup( { result: deferredCreateResult(), supervisorReady: false }, { dockerStop: vi.fn(() => ({ status: 0 })), diff --git a/src/lib/onboard/docker-gpu-patch-finalize.ts b/src/lib/onboard/docker-gpu-patch-finalize.ts index 837964440e9..07d36fee7f8 100644 --- a/src/lib/onboard/docker-gpu-patch-finalize.ts +++ b/src/lib/onboard/docker-gpu-patch-finalize.ts @@ -92,10 +92,10 @@ function runOpenShellLifecycleCommand( } } -export function finalizeDockerGpuPatchBackup( +export async function finalizeDockerGpuPatchBackup( options: DockerGpuPatchFinalizeOptions, deps: DockerGpuPatchDeps = {}, -): DockerGpuPatchFinalizeOutcome { +): Promise { const resolved = resolveDockerGpuPatchRollbackDeps(deps); const containerOpts = { ignoreError: true, @@ -115,7 +115,7 @@ export function finalizeDockerGpuPatchBackup( // point; failures after it require a sandbox rebuild. Success is withheld // until OpenShell reports Ready and Docker still proves the exact // replacement is the sole running labeled container (#9531, #10153). - if (!deps.runOpenshell || !deps.runCaptureOpenshell) { + if (!deps.commandExecutor || !deps.runOpenshell || !deps.runCaptureOpenshell) { return { backupRemoved: false, rolledBack: false, @@ -202,9 +202,9 @@ export function finalizeDockerGpuPatchBackup( ); const acknowledgement = remainingHandoffTimeoutMs > 0 - ? waitForOpenShellFinalHandoff(options.sandboxName, finalHandoffDeadlineMs, { + ? await waitForOpenShellFinalHandoff(options.sandboxName, finalHandoffDeadlineMs, { + commandExecutor: deps.commandExecutor, runCaptureOpenshell: deps.runCaptureOpenshell, - runOpenshell: deps.runOpenshell, sleep: deps.sleep, now, replacementIsExactAndRunning: (remainingMs) => diff --git a/src/lib/onboard/docker-gpu-patch-recreate.test.ts b/src/lib/onboard/docker-gpu-patch-recreate.test.ts index d5731c62dab..7ce46ca3059 100644 --- a/src/lib/onboard/docker-gpu-patch-recreate.test.ts +++ b/src/lib/onboard/docker-gpu-patch-recreate.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { createDockerGpuInspectFixture as inspectFixture } from "./__test-helpers__/docker-gpu-patch-fixtures"; import { getDockerGpuPatchFailureContext, @@ -20,8 +21,39 @@ function dockerCaptureFixture() { return vi.fn((args: readonly string[]) => responses[args[0]] ?? ""); } +function commandExecutorThrough( + runOpenshell: ( + args: string[], + opts?: Record, + ) => { + status: number | null; + stdout?: string; + stderr?: string; + }, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async (request) => { + const result = runOpenshell( + ["sandbox", "exec", "-n", request.sandboxName, "--", ...request.command], + { ignoreError: true, suppressOutput: true }, + ); + return { + outcome: + result.status === null + ? { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + } + : { kind: "completed" as const, exitCode: result.status }, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; + }), + }; +} + describe("Docker GPU recreate orchestration", () => { - it("recreates the OpenShell-managed container and waits for supervisor exec", () => { + it("recreates the OpenShell-managed container and waits for supervisor exec", async () => { const dockerCapture = dockerCaptureFixture(); const dockerRunResults = { ps: { status: 0, stdout: `${NEW_CONTAINER_ID}\n` }, @@ -42,7 +74,7 @@ describe("Docker GPU recreate orchestration", () => { const runOpenshell = vi.fn(() => ({ status: 0 })); const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 10:00:02 Ready\n"); - const result = recreateOpenShellDockerSandboxWithGpu( + const result = await recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, { dockerCapture, @@ -54,6 +86,7 @@ describe("Docker GPU recreate orchestration", () => { dockerStart, runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), now: () => new Date("2026-05-12T00:00:00Z"), detectSandboxFallbackDns: vi.fn(() => null), @@ -115,10 +148,11 @@ describe("Docker GPU recreate orchestration", () => { ); }); - it("does not report success when the final OpenShell phase is Deleting (#9531)", () => { + it("does not report success when the final OpenShell phase is Deleting (#9531)", async () => { + const runOpenshell = vi.fn(() => ({ status: 0 })); let failure: unknown; try { - recreateOpenShellDockerSandboxWithGpu( + await recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, { dockerCapture: dockerCaptureFixture(), @@ -129,7 +163,8 @@ describe("Docker GPU recreate orchestration", () => { dockerRm: vi.fn(() => ({ status: 0 })), dockerStart: vi.fn(() => ({ status: 0 })), runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:02 Deleting\n"), - runOpenshell: vi.fn(() => ({ status: 0 })), + runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), now: () => new Date("2026-05-12T00:00:00Z"), detectSandboxFallbackDns: vi.fn(() => null), diff --git a/src/lib/onboard/docker-gpu-patch-recreate.ts b/src/lib/onboard/docker-gpu-patch-recreate.ts index 7d2310ff366..94f5484e44b 100644 --- a/src/lib/onboard/docker-gpu-patch-recreate.ts +++ b/src/lib/onboard/docker-gpu-patch-recreate.ts @@ -149,21 +149,31 @@ export function getDockerGpuPatchFailureContext( return null; } +type RecreateOpenShellDockerSandboxContainerOptions = { + sandboxName: string; + gpuDevice?: string | null; + timeoutSecs?: number; + waitForSupervisor?: boolean; + openshellSandboxCommand?: readonly string[] | null; + requiredUlimits?: readonly import("./docker-gpu-patch-types").DockerUlimit[] | null; + expectedOldContainerId?: string | null; + backend?: "generic" | "jetson"; + dockerDesktopWsl?: boolean; + modeOverride?: DockerGpuPatchMode; +}; + +export function recreateOpenShellDockerSandboxContainer( + options: RecreateOpenShellDockerSandboxContainerOptions & { waitForSupervisor: false }, + deps?: DockerGpuPatchDeps, +): DockerGpuPatchResult; +export function recreateOpenShellDockerSandboxContainer( + options: RecreateOpenShellDockerSandboxContainerOptions, + deps?: DockerGpuPatchDeps, +): Promise; export function recreateOpenShellDockerSandboxContainer( - options: { - sandboxName: string; - gpuDevice?: string | null; - timeoutSecs?: number; - waitForSupervisor?: boolean; - openshellSandboxCommand?: readonly string[] | null; - requiredUlimits?: readonly import("./docker-gpu-patch-types").DockerUlimit[] | null; - expectedOldContainerId?: string | null; - backend?: "generic" | "jetson"; - dockerDesktopWsl?: boolean; - modeOverride?: DockerGpuPatchMode; - }, + options: RecreateOpenShellDockerSandboxContainerOptions, deps: DockerGpuPatchDeps = {}, -): DockerGpuPatchResult { +): DockerGpuPatchResult | Promise { const d = recreateDeps(deps); const context: DockerGpuPatchFailureContext = { sandboxName: options.sandboxName, @@ -388,51 +398,59 @@ export function recreateOpenShellDockerSandboxContainer( }); if (options.waitForSupervisor === false) return result(false); - const execReady = waitForOpenShellSupervisorReconnect( - options.sandboxName, - options.timeoutSecs ?? DOCKER_GPU_PATCH_WAIT_SECS, - deps, - ); const patchResult = result(false); - const finalization = execReady - ? finalizeDockerGpuPatchBackup( - { - result: patchResult, - supervisorReady: true, - sandboxName: options.sandboxName, - finalHandoffTimeoutSecs: options.timeoutSecs ?? DOCKER_GPU_PATCH_WAIT_SECS, - }, - deps, - ) - : finalizeDockerGpuPatchBackup({ result: patchResult, supervisorReady: false }, deps); - context.rolledBack = finalization.rolledBack; - context.backupRemoved = finalization.backupRemoved; - context.replacementStopConfirmed = finalization.replacementStopConfirmed; - context.replacementRemovalConfirmed = finalization.replacementRemovalConfirmed; - context.replacementPresence = finalization.replacementPresence; - context.lastSandboxPhase = finalization.lastSandboxPhase; - if (!execReady) { + return (async () => { + const execReady = deps.commandExecutor + ? await waitForOpenShellSupervisorReconnect( + options.sandboxName, + options.timeoutSecs ?? DOCKER_GPU_PATCH_WAIT_SECS, + { + commandExecutor: deps.commandExecutor, + runCaptureOpenshell: deps.runCaptureOpenshell, + sleep: deps.sleep, + errorPhaseDebouncePolls: deps.errorPhaseDebouncePolls, + }, + ) + : false; + const finalization = await (execReady + ? finalizeDockerGpuPatchBackup( + { + result: patchResult, + supervisorReady: true, + sandboxName: options.sandboxName, + finalHandoffTimeoutSecs: options.timeoutSecs ?? DOCKER_GPU_PATCH_WAIT_SECS, + }, + deps, + ) + : finalizeDockerGpuPatchBackup({ result: patchResult, supervisorReady: false }, deps)); + context.rolledBack = finalization.rolledBack; + context.backupRemoved = finalization.backupRemoved; + context.replacementStopConfirmed = finalization.replacementStopConfirmed; + context.replacementRemovalConfirmed = finalization.replacementRemovalConfirmed; + context.replacementPresence = finalization.replacementPresence; + context.lastSandboxPhase = finalization.lastSandboxPhase; + if (!execReady) { + throw new Error( + finalization.rolledBack + ? "OpenShell supervisor did not reconnect to the GPU-enabled container; pre-patch sandbox restored." + : "OpenShell supervisor did not reconnect to the GPU-enabled container and rollback failed; pre-patch sandbox was NOT restored.", + ); + } + if (finalization.finalHandoffAcknowledged) return result(true); + const rebuildRequired = finalization.backupRemoved + ? " The previous container was removed at the final handoff commit point; automatic rollback is unavailable. Rebuild the sandbox before retrying." + : ""; throw new Error( - finalization.rolledBack - ? "OpenShell supervisor did not reconnect to the GPU-enabled container; pre-patch sandbox restored." - : "OpenShell supervisor did not reconnect to the GPU-enabled container and rollback failed; pre-patch sandbox was NOT restored.", + finalization.lastSandboxPhase + ? `OpenShell did not acknowledge the final replacement handoff; last sandbox phase was ${finalization.lastSandboxPhase}.${rebuildRequired}` + : `OpenShell did not acknowledge the final replacement handoff.${rebuildRequired}`, ); - } - if (finalization.finalHandoffAcknowledged) return result(true); - const rebuildRequired = finalization.backupRemoved - ? " The previous container was removed at the final handoff commit point; automatic rollback is unavailable. Rebuild the sandbox before retrying." - : ""; - throw new Error( - finalization.lastSandboxPhase - ? `OpenShell did not acknowledge the final replacement handoff; last sandbox phase was ${finalization.lastSandboxPhase}.${rebuildRequired}` - : `OpenShell did not acknowledge the final replacement handoff.${rebuildRequired}`, - ); + })().catch((error) => { + throw decoratePatchError(error instanceof Error ? error : new Error(String(error)), context); + }); } catch (error) { throw decoratePatchError(error instanceof Error ? error : new Error(String(error)), context); } } -export const recreateOpenShellDockerSandboxWithGpu: ( - options: Omit[0], "modeOverride">, - deps?: DockerGpuPatchDeps, -) => DockerGpuPatchResult = recreateOpenShellDockerSandboxContainer; +export const recreateOpenShellDockerSandboxWithGpu = recreateOpenShellDockerSandboxContainer; diff --git a/src/lib/onboard/docker-gpu-patch-rollback.test.ts b/src/lib/onboard/docker-gpu-patch-rollback.test.ts index 14ecb44988d..41e95be9949 100644 --- a/src/lib/onboard/docker-gpu-patch-rollback.test.ts +++ b/src/lib/onboard/docker-gpu-patch-rollback.test.ts @@ -71,7 +71,7 @@ function inspectFixture(): DockerContainerInspect { } describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { - it("rolls back to the backup container when supervisor reconnect fails", () => { + it("rolls back to the backup container when supervisor reconnect fails", async () => { const dockerCapture = vi.fn((args: readonly string[]) => { if (args[0] === "ps") return "old-container-id\n"; if (args[0] === "inspect") return JSON.stringify([inspectFixture()]); @@ -87,7 +87,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { const runOpenshell = vi.fn(() => ({ status: 1, stderr: "supervisor unreachable" })); const runCaptureOpenshell = vi.fn(() => "alpha Error\n"); - expect(() => + await expect( recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, { @@ -106,7 +106,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { errorPhaseDebouncePolls: 1, }, ), - ).toThrow(/pre-patch sandbox restored/); + ).rejects.toThrow(/pre-patch sandbox restored/); const restoreRename = dockerRename.mock.calls.find( (call) => String(call[0]).includes("nemoclaw-gpu-backup") && call[1] === "openshell-alpha", @@ -121,7 +121,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { ).toBe(false); }); - it("retries from the restored sandbox after exact-ID replacement cleanup (#7996)", () => { + it("retries from the restored sandbox after exact-ID replacement cleanup (#7996)", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gpu-rollback-retry-")); const restoredId = "b".repeat(64); const replacementId = "a".repeat(64); @@ -282,6 +282,13 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { ? "No sandboxes found.\n" : "alpha 2026-08-23 10:00:02 Ready\n", ), + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }, sleep: vi.fn(), homedir: () => tmpDir, now: () => new Date("2026-07-03T00:00:00Z"), @@ -305,7 +312,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { }; try { - const rollback = finalizeDockerGpuPatchBackup( + const rollback = await finalizeDockerGpuPatchBackup( { result: failedResult, supervisorReady: false }, deps, ); @@ -350,7 +357,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { expect(alphaContainerIds()).toEqual([restoredId]); expect(unrelatedPresent).toBe(true); - const retried = recreateOpenShellDockerSandboxWithGpu( + const retried = await recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, deps, ); @@ -369,65 +376,65 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { } }); - it.each([ - 1, - null, - ])("restores the pre-patch sandbox when the recreate run returns status %s before the supervisor wait (#5512)", (runStatus) => { - const captureResponses: Record = { - ps: "old-container-id\n", - inspect: JSON.stringify([inspectFixture()]), - info: "", - }; - const dockerCapture = vi.fn( - (args: readonly string[]) => captureResponses[String(args[0])] ?? "", - ); - const dockerRun = vi.fn(() => ({ status: 0, stdout: "probe-id\n" })); - // The recreate `docker run` fails after the original was renamed aside. - const dockerRunDetached = vi.fn(() => ({ status: runStatus, stderr: "docker: boom" })); - const dockerRename = vi.fn((_old: string, _next: string) => ({ status: 0 })); - const dockerStop = vi.fn(() => ({ status: 0 })); - const dockerStart = vi.fn(() => ({ status: 0 })); - const dockerRm = vi.fn((_name: string) => ({ status: 0 })); - const runCaptureOpenshell = vi.fn(() => ""); - - expect(() => - recreateOpenShellDockerSandboxWithGpu( - { sandboxName: "alpha", timeoutSecs: 1 }, - { - dockerCapture, - dockerRun, - dockerRunDetached, - dockerRename, - dockerStop, - dockerStart, - dockerRm, - runCaptureOpenshell, - sleep: vi.fn(), - now: () => new Date("2026-05-12T00:00:00Z"), - ...offlineDnsDeps, - }, - ), - ).toThrow(/Could not start GPU-enabled sandbox container/); + it.each([1, null])( + "restores the pre-patch sandbox when the recreate run returns status %s before the supervisor wait (#5512)", + (runStatus) => { + const captureResponses: Record = { + ps: "old-container-id\n", + inspect: JSON.stringify([inspectFixture()]), + info: "", + }; + const dockerCapture = vi.fn( + (args: readonly string[]) => captureResponses[String(args[0])] ?? "", + ); + const dockerRun = vi.fn(() => ({ status: 0, stdout: "probe-id\n" })); + // The recreate `docker run` fails after the original was renamed aside. + const dockerRunDetached = vi.fn(() => ({ status: runStatus, stderr: "docker: boom" })); + const dockerRename = vi.fn((_old: string, _next: string) => ({ status: 0 })); + const dockerStop = vi.fn(() => ({ status: 0 })); + const dockerStart = vi.fn(() => ({ status: 0 })); + const dockerRm = vi.fn((_name: string) => ({ status: 0 })); + const runCaptureOpenshell = vi.fn(() => ""); + + expect(() => + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1 }, + { + dockerCapture, + dockerRun, + dockerRunDetached, + dockerRename, + dockerStop, + dockerStart, + dockerRm, + runCaptureOpenshell, + sleep: vi.fn(), + now: () => new Date("2026-05-12T00:00:00Z"), + ...offlineDnsDeps, + }, + ), + ).toThrow(/Could not start GPU-enabled sandbox container/); - // The original sandbox is restored from the backup (rename backup -> original, then start). - const restoreRename = dockerRename.mock.calls.find( - (call) => String(call[0]).includes("nemoclaw-gpu-backup") && call[1] === "openshell-alpha", - ); - expect(restoreRename).toBeDefined(); - expect(dockerStart).toHaveBeenCalledWith( - "openshell-alpha", - expect.objectContaining({ ignoreError: true }), - ); - // The failed recreate container (named originalName by `docker run --name`) is removed. - expect(dockerRm).toHaveBeenCalledWith( - "openshell-alpha", - expect.objectContaining({ ignoreError: true }), - ); - // The backup is renamed back, never left as an orphaned container. - expect( - dockerRm.mock.calls.some((call) => String(call[0]).includes("nemoclaw-gpu-backup")), - ).toBe(false); - }); + // The original sandbox is restored from the backup (rename backup -> original, then start). + const restoreRename = dockerRename.mock.calls.find( + (call) => String(call[0]).includes("nemoclaw-gpu-backup") && call[1] === "openshell-alpha", + ); + expect(restoreRename).toBeDefined(); + expect(dockerStart).toHaveBeenCalledWith( + "openshell-alpha", + expect.objectContaining({ ignoreError: true }), + ); + // The failed recreate container (named originalName by `docker run --name`) is removed. + expect(dockerRm).toHaveBeenCalledWith( + "openshell-alpha", + expect.objectContaining({ ignoreError: true }), + ); + // The backup is renamed back, never left as an orphaned container. + expect( + dockerRm.mock.calls.some((call) => String(call[0]).includes("nemoclaw-gpu-backup")), + ).toBe(false); + }, + ); it("does not start a replacement when the original-container rename has no exit status", () => { const captureResponses: Record = { @@ -557,7 +564,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { ); }); - it("reports rollback failure when restoring the backup container fails", () => { + it("reports rollback failure when restoring the backup container fails", async () => { const dockerCapture = vi.fn((args: readonly string[]) => { if (args[0] === "ps") return "old-container-id\n"; if (args[0] === "inspect") return JSON.stringify([inspectFixture()]); @@ -578,7 +585,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { const runOpenshell = vi.fn(() => ({ status: 1, stderr: "supervisor unreachable" })); const runCaptureOpenshell = vi.fn(() => "alpha Error\n"); - expect(() => + await expect( recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, { @@ -597,12 +604,12 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { errorPhaseDebouncePolls: 1, }, ), - ).toThrow(/rollback failed; pre-patch sandbox was NOT restored/); + ).rejects.toThrow(/rollback failed; pre-patch sandbox was NOT restored/); expect(dockerStart).not.toHaveBeenCalled(); }); - it("reports rollback failure when restarting the backup container fails", () => { + it("reports rollback failure when restarting the backup container fails", async () => { const dockerCapture = vi.fn((args: readonly string[]) => { if (args[0] === "ps") return "old-container-id\n"; if (args[0] === "inspect") return JSON.stringify([inspectFixture()]); @@ -618,7 +625,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { const runOpenshell = vi.fn(() => ({ status: 1, stderr: "supervisor unreachable" })); const runCaptureOpenshell = vi.fn(() => "alpha Error\n"); - expect(() => + await expect( recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, { @@ -637,7 +644,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { errorPhaseDebouncePolls: 1, }, ), - ).toThrow(/rollback failed; pre-patch sandbox was NOT restored/); + ).rejects.toThrow(/rollback failed; pre-patch sandbox was NOT restored/); expect(dockerStart).toHaveBeenCalledWith( "openshell-alpha", diff --git a/src/lib/onboard/docker-gpu-patch-types.ts b/src/lib/onboard/docker-gpu-patch-types.ts index 37262e4d77f..39113720bfd 100644 --- a/src/lib/onboard/docker-gpu-patch-types.ts +++ b/src/lib/onboard/docker-gpu-patch-types.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; + type DockerRunResult = { status?: number | null; stdout?: string | Buffer | null; @@ -23,6 +25,7 @@ type ContainerDnsProbeFn = ( ) => import("./preflight").DnsProbeResult; export type DockerGpuPatchDeps = { + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; dockerCapture?: DockerCaptureFn; dockerRun?: DockerRunFn; dockerRunDetached?: DockerRunFn; diff --git a/src/lib/onboard/docker-gpu-patch.ts b/src/lib/onboard/docker-gpu-patch.ts index 3396d537433..1823b69f85d 100644 --- a/src/lib/onboard/docker-gpu-patch.ts +++ b/src/lib/onboard/docker-gpu-patch.ts @@ -125,7 +125,7 @@ function printDockerGpuPatchCleanup( ); } -export function applyDockerGpuPatchOrExit( +export async function applyDockerGpuPatchOrExit( options: { sandboxName: string; gpuDevice?: string | null; @@ -139,11 +139,14 @@ export function applyDockerGpuPatchOrExit( openshellSandboxCommand?: readonly string[] | null; dockerDesktopWsl?: boolean; }, - deps: Pick, -): DockerGpuPatchResult { + deps: Pick< + DockerGpuPatchDeps, + "commandExecutor" | "runOpenshell" | "runCaptureOpenshell" | "sleep" + >, +): Promise { console.log(" Recreating OpenShell Docker sandbox container with NVIDIA GPU access..."); try { - const result = recreateOpenShellDockerSandboxWithGpu(options, deps); + const result = await recreateOpenShellDockerSandboxWithGpu(options, deps); console.log(` ✓ Docker GPU mode selected: ${result.mode.label}`); return result; } catch (error) { diff --git a/src/lib/onboard/docker-gpu-route-consumers.test.ts b/src/lib/onboard/docker-gpu-route-consumers.test.ts index b11215d340e..58142980bfd 100644 --- a/src/lib/onboard/docker-gpu-route-consumers.test.ts +++ b/src/lib/onboard/docker-gpu-route-consumers.test.ts @@ -140,7 +140,7 @@ describe("selected route consumers", () => { it("skips compatibility-only inference gates after native wins", async () => { const execInSandbox = vi.fn(); expect( - verifyDockerGpuSandboxLocalInference(GPU_CONFIG, "ollama-local", { + await verifyDockerGpuSandboxLocalInference(GPU_CONFIG, "ollama-local", { sandboxName: "alpha", dockerDriverGateway: true, selectedRoute: "native", diff --git a/src/lib/onboard/docker-gpu-sandbox-create-diagnostics.test.ts b/src/lib/onboard/docker-gpu-sandbox-create-diagnostics.test.ts index 05bf88d5e16..03c388cfc91 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create-diagnostics.test.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create-diagnostics.test.ts @@ -32,7 +32,7 @@ const RESULT: DockerGpuPatchResult = { describe("Docker GPU create diagnostics fail-safety (#6110)", () => { afterEach(() => vi.restoreAllMocks()); - it("still rolls back when pre-rollback diagnostic capture fails", () => { + it("still rolls back when pre-rollback diagnostic capture fails", async () => { vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); const deps = { @@ -41,7 +41,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { sleep: vi.fn(), dockerCapture: vi.fn(() => ""), }; - const finalizeBackup = vi.fn(() => ({ + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, })); @@ -54,7 +54,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { overrides: { findContainerIds: vi.fn(() => ["existing-container"]), recreatePatch: vi.fn(() => RESULT), - waitForSupervisor: vi.fn(() => false), + waitForSupervisor: vi.fn(async () => false), capturePreRollbackDiagnostics: vi.fn(() => { throw new Error("disk full"); }), @@ -64,7 +64,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(finalizeBackup).toHaveBeenCalledWith({ result: RESULT, supervisorReady: false }, deps); expect(onPatchFailureExit).toHaveBeenCalledTimes(1); @@ -75,7 +75,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { ); }); - it("captures before rollback when ensureApplied performs the recreate after create exits", () => { + it("captures before rollback when ensureApplied performs the recreate after create exits", async () => { vi.spyOn(console, "log").mockImplementation(() => {}); const deps = { runOpenshell: vi.fn(() => ({ status: 0 })), @@ -84,9 +84,9 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { dockerCapture: vi.fn(() => ""), }; const recreatePatch = vi.fn(() => RESULT); - const waitForSupervisor = vi.fn(() => false); + const waitForSupervisor = vi.fn(async () => false); const capturePreRollbackDiagnostics = vi.fn(() => null); - const finalizeBackup = vi.fn(() => ({ + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, })); @@ -105,8 +105,8 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { }, }); - patch.ensureApplied(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.ensureApplied(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(recreatePatch).toHaveBeenCalledWith( expect.objectContaining({ waitForSupervisor: false }), @@ -120,7 +120,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { expect(onPatchFailureExit).toHaveBeenCalledTimes(1); }); - it("forwards the pre-rollback classification when bundle collection fails (#7996)", () => { + it("forwards the pre-rollback classification when bundle collection fails (#7996)", async () => { vi.spyOn(console, "log").mockImplementation(() => {}); const deps = { runOpenshell: vi.fn(() => ({ status: 0 })), @@ -142,18 +142,18 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { deps, overrides: { recreatePatch: vi.fn(() => RESULT), - waitForSupervisor: vi.fn(() => false), + waitForSupervisor: vi.fn(async () => false), capturePreRollbackDiagnostics: vi.fn(() => ({ classification, diagnostics: null, })), - finalizeBackup: vi.fn(() => ({ backupRemoved: false, rolledBack: true })), + finalizeBackup: vi.fn(async () => ({ backupRemoved: false, rolledBack: true })), onPatchFailureExit, }, }); - patch.ensureApplied(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.ensureApplied(); + await patch.waitForSupervisorReconnectIfNeeded(); // The printer cannot rely on the replacement remaining inspectable after // rollback, so this hand-off preserves the exit-code evidence. @@ -164,7 +164,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { ); }); - it("passes a null pre-rollback classification when capture returns nothing (#7996)", () => { + it("passes a null pre-rollback classification when capture returns nothing (#7996)", async () => { vi.spyOn(console, "log").mockImplementation(() => {}); const deps = { runOpenshell: vi.fn(() => ({ status: 0 })), @@ -180,15 +180,15 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { deps, overrides: { recreatePatch: vi.fn(() => RESULT), - waitForSupervisor: vi.fn(() => false), + waitForSupervisor: vi.fn(async () => false), capturePreRollbackDiagnostics: vi.fn(() => null), - finalizeBackup: vi.fn(() => ({ backupRemoved: false, rolledBack: true })), + finalizeBackup: vi.fn(async () => ({ backupRemoved: false, rolledBack: true })), onPatchFailureExit, }, }); - patch.ensureApplied(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.ensureApplied(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(onPatchFailureExit).toHaveBeenCalledWith( "alpha", @@ -197,7 +197,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { ); }); - it("uses exact-ID cleanup when a restored sandbox retains the failed replacement (#7996)", () => { + it("uses exact-ID cleanup when a restored sandbox retains the failed replacement (#7996)", async () => { vi.spyOn(console, "log").mockImplementation(() => {}); const stderr: string[] = []; vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { @@ -275,7 +275,7 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { deps, overrides: { recreatePatch: vi.fn(() => result), - waitForSupervisor: vi.fn(() => false), + waitForSupervisor: vi.fn(async () => false), capturePreRollbackDiagnostics: (...args) => { captured = captureDockerGpuPreRollbackDiagnostics(...args); return captured; @@ -283,8 +283,8 @@ describe("Docker GPU create diagnostics fail-safety (#6110)", () => { }, }); - patch.ensureApplied(); - expect(() => patch.waitForSupervisorReconnectIfNeeded()).toThrow(/__test_exit__/); + await patch.ensureApplied(); + await expect(patch.waitForSupervisorReconnectIfNeeded()).rejects.toThrow(/__test_exit__/); const preRollback = (captured as DockerGpuPreRollbackDiagnostics | null)?.diagnostics; const preRollbackSummary = fs.readFileSync( diff --git a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts index 73198f33391..3a74dd50ef2 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts @@ -46,8 +46,8 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { const deps = makeDeps(); const result = deferredCreateResult(); const recreatePatch = vi.fn(() => result); - const waitForSupervisor = vi.fn(() => true); - const finalizeBackup = vi.fn(() => ({ + const waitForSupervisor = vi.fn(async () => true); + const finalizeBackup = vi.fn(async () => ({ backupRemoved: true, rolledBack: false, replacementRestarted: true, @@ -88,7 +88,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { // result still carries backupRemoved=false). expect(finalizeBackup).not.toHaveBeenCalled(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(waitForSupervisor).toHaveBeenCalledTimes(1); expect(finalizeBackup).not.toHaveBeenCalled(); @@ -114,8 +114,8 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { it("accepts a backup that the patch helper already finalized after reconnect", async () => { const deps = makeDeps(); const result = { ...deferredCreateResult(), backupRemoved: true }; - const waitForSupervisor = vi.fn(() => true); - const finalizeBackup = vi.fn(() => ({ + const waitForSupervisor = vi.fn(async () => true); + const finalizeBackup = vi.fn(async () => ({ backupRemoved: true, rolledBack: false, })); @@ -135,7 +135,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); await expect(patch.commitAfterReady()).resolves.toBeUndefined(); expect(finalizeBackup).toHaveBeenCalledWith( @@ -163,8 +163,8 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { overrides: { findContainerIds: vi.fn(() => ["existing-container"]), recreatePatch: vi.fn(() => result), - waitForSupervisor: vi.fn(() => true), - finalizeBackup: vi.fn(() => ({ + waitForSupervisor: vi.fn(async () => true), + finalizeBackup: vi.fn(async () => ({ backupRemoved: true, rolledBack: false, replacementRestarted: false, @@ -174,7 +174,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); await expect(patch.commitAfterReady()).rejects.toThrow("automatic rollback is unavailable"); expect(patch.allowsNotReadyLifecycleRevalidation()).toBe(false); expect(onPatchFailureExit).toHaveBeenCalledOnce(); @@ -186,7 +186,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { it("rejects final handoff when OpenShell reports Deleting after restart (#9531)", async () => { const deps = makeDeps(); const result = deferredCreateResult(); - const waitForSupervisor = vi.fn(() => true); + const waitForSupervisor = vi.fn(async () => true); const onPatchFailureExit = vi.fn(); const patch = createDockerGpuSandboxCreatePatch({ route: "compatibility", @@ -197,7 +197,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { findContainerIds: vi.fn(() => ["existing-container"]), recreatePatch: vi.fn(() => result), waitForSupervisor, - finalizeBackup: vi.fn(() => ({ + finalizeBackup: vi.fn(async () => ({ backupRemoved: true, rolledBack: false, replacementRestarted: true, @@ -209,7 +209,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); await expect(patch.commitAfterReady()).rejects.toThrow("automatic rollback is unavailable"); expect(waitForSupervisor).toHaveBeenCalledOnce(); @@ -219,7 +219,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { it("reports a failed post-Ready rollback instead of treating it as restored", async () => { const deps = makeDeps(); const result = deferredCreateResult(); - const finalizeBackup = vi.fn(() => ({ + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: false, })); @@ -232,14 +232,14 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { overrides: { findContainerIds: vi.fn(() => ["existing-container"]), recreatePatch: vi.fn(() => result), - waitForSupervisor: vi.fn(() => true), + waitForSupervisor: vi.fn(async () => true), finalizeBackup, onPatchFailureExit, }, }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); await patch.rollbackManagedStartupAfterCreateFailure(); expect(finalizeBackup).toHaveBeenCalledWith({ result, supervisorReady: false }, deps); @@ -269,8 +269,8 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { overrides: { findContainerIds: vi.fn(() => ["existing-container"]), recreatePatch: vi.fn(() => result), - waitForSupervisor: vi.fn(() => true), - finalizeBackup: vi.fn(() => ({ + waitForSupervisor: vi.fn(async () => true), + finalizeBackup: vi.fn(async () => ({ backupRemoved: false, rolledBack: false, })), @@ -279,7 +279,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(onPatchFailureExit).not.toHaveBeenCalled(); await expect(patch.commitAfterReady()).rejects.toThrow("final runtime handoff"); @@ -304,7 +304,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { it("rejects an early commit after rolling back before supervisor reconnect", async () => { const deps = makeDeps(); const result = deferredCreateResult(); - const finalizeBackup = vi.fn(() => ({ backupRemoved: false, rolledBack: true })); + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: true })); const onPatchFailureExit = vi.fn(); const patch = createDockerGpuSandboxCreatePatch({ route: "compatibility", @@ -331,13 +331,13 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { expect(onPatchFailureExit).toHaveBeenCalledOnce(); }); - it("rolls back to the backup container and surfaces rolledBack=true diagnostics when supervisorReady=false", () => { + it("rolls back to the backup container and surfaces rolledBack=true diagnostics when supervisorReady=false", async () => { const deps = makeDeps(); const result = deferredCreateResult(); const recreatePatch = vi.fn(() => result); - const waitForSupervisor = vi.fn(() => false); + const waitForSupervisor = vi.fn(async () => false); const capturePreRollbackDiagnostics = vi.fn(() => null); - const finalizeBackup = vi.fn(() => ({ + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, })); @@ -360,7 +360,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(capturePreRollbackDiagnostics).toHaveBeenCalledWith("alpha", result, deps); expect(capturePreRollbackDiagnostics.mock.invocationCallOrder[0]).toBeLessThan( @@ -377,12 +377,12 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { expect(context.backupContainerName).toBe(result.backupContainerName); }); - it("reports rolledBack=false in diagnostics when rollback itself fails", () => { + it("reports rolledBack=false in diagnostics when rollback itself fails", async () => { const deps = makeDeps(); const result = deferredCreateResult(); const recreatePatch = vi.fn(() => result); - const waitForSupervisor = vi.fn(() => false); - const finalizeBackup = vi.fn(() => ({ + const waitForSupervisor = vi.fn(async () => false); + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: false, })); @@ -406,7 +406,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(onPatchFailureExit).toHaveBeenCalledTimes(1); const [, error, exitDeps] = onPatchFailureExit.mock.calls[0]; @@ -415,7 +415,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { expect(context.rolledBack).toBe(false); }); - it("skips both apply and supervisor wait when no OpenShell container is found", () => { + it("skips both apply and supervisor wait when no OpenShell container is found", async () => { const deps = makeDeps(); const recreatePatch = vi.fn(); const waitForSupervisor = vi.fn(); @@ -438,7 +438,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(recreatePatch).not.toHaveBeenCalled(); expect(waitForSupervisor).not.toHaveBeenCalled(); @@ -475,7 +475,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { await patch.exitOnPatchError(); expect(onPatchFailureExit).toHaveBeenCalledTimes(1); // Supervisor wait must be skipped because needsSupervisorWait stayed false. - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(waitForSupervisor).not.toHaveBeenCalled(); expect(finalizeBackup).not.toHaveBeenCalled(); }); @@ -514,8 +514,8 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { overrides: { findContainerIds: vi.fn(() => ["existing-container"]), recreatePatch: vi.fn(() => result), - waitForSupervisor: vi.fn(() => true), - finalizeBackup: vi.fn(() => ({ + waitForSupervisor: vi.fn(async () => true), + finalizeBackup: vi.fn(async () => ({ backupRemoved: false, rolledBack: false, })), @@ -523,7 +523,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); await expect( patch.verifyGpuOrExit(() => { diff --git a/src/lib/onboard/docker-gpu-sandbox-create.ts b/src/lib/onboard/docker-gpu-sandbox-create.ts index 02644ee469b..969d373d310 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create.ts @@ -46,6 +46,7 @@ export { type DockerGpuSandboxCreateDeps = Pick< DockerGpuPatchDeps, + | "commandExecutor" | "runOpenshell" | "runCaptureOpenshell" | "sleep" @@ -60,10 +61,24 @@ type DockerGpuSandboxCreateDeps = Pick< | "now" >; -type WaitSupervisorFn = typeof waitForOpenShellSupervisorReconnect; +type WaitSupervisorFn = ( + sandboxName: string, + timeoutSecs: number, + deps: DockerGpuPatchDeps, +) => Promise; type FindContainerIdsFn = typeof findOpenShellDockerSandboxContainerIds; -type FinalizeBackupFn = typeof finalizeDockerGpuPatchBackup; +type FinalizeBackupFn = ( + ...args: Parameters +) => ReturnType; type CapturePreRollbackDiagnosticsFn = typeof captureDockerGpuPreRollbackDiagnostics; +type DeferredRecreateGpuPatchFn = ( + options: Parameters[0] & { waitForSupervisor: false }, + deps?: Parameters[1], +) => DockerGpuPatchResult; +type DeferredRecreateStartupPatchFn = ( + options: Parameters[0] & { waitForSupervisor: false }, + deps?: Parameters[1], +) => DockerGpuPatchResult; // Loosen the override return type from `never` to `void` so tests can pass a // plain `vi.fn()` mock. Production wires `printDockerGpuPatchFailureAndExit` // which has return type `never`; that is assignable to `void`. @@ -102,8 +117,8 @@ type DockerGpuSandboxCreatePatchOptions = { */ overrides?: { findContainerIds?: FindContainerIdsFn; - recreatePatch?: RecreateGpuPatchFn; - recreateStartupPatch?: RecreateStartupPatchFn; + recreatePatch?: DeferredRecreateGpuPatchFn; + recreateStartupPatch?: DeferredRecreateStartupPatchFn; waitForSupervisor?: WaitSupervisorFn; finalizeBackup?: FinalizeBackupFn; capturePreRollbackDiagnostics?: CapturePreRollbackDiagnosticsFn; @@ -130,7 +145,7 @@ export type DockerGpuSandboxCreatePatch = { request?: ManagedBootstrapNativeGpuFallbackRollbackRequest, ) => Promise; ensureApplied: () => Promise; - waitForSupervisorReconnectIfNeeded: () => void; + waitForSupervisorReconnectIfNeeded: () => Promise; /** * Commit an attached managed cutover or remove a legacy recreation backup. * Call only after authoritative Ready and the required GPU and applicable @@ -178,8 +193,17 @@ export function createDockerGpuSandboxCreatePatch( options.overrides?.findContainerIds ?? findOpenShellDockerSandboxContainerIds; const recreatePatch = options.overrides?.recreatePatch ?? recreateOpenShellDockerSandboxWithGpu; const recreateStartupPatch = options.overrides?.recreateStartupPatch; - const waitForSupervisor = - options.overrides?.waitForSupervisor ?? waitForOpenShellSupervisorReconnect; + const waitForSupervisor: WaitSupervisorFn = + options.overrides?.waitForSupervisor ?? + ((sandboxName, timeoutSecs, deps) => { + if (!deps.commandExecutor) { + throw new Error("OpenShell buffered command execution is unavailable."); + } + return waitForOpenShellSupervisorReconnect(sandboxName, timeoutSecs, { + ...deps, + commandExecutor: deps.commandExecutor, + }); + }); const finalizeBackup = options.overrides?.finalizeBackup ?? finalizeDockerGpuPatchBackup; const captureFailedClone = options.overrides?.capturePreRollbackDiagnostics ?? captureDockerGpuPreRollbackDiagnostics; @@ -212,8 +236,8 @@ export function createDockerGpuSandboxCreatePatch( gpuOptions: applyOptions, startupCommand: options.openshellSandboxCommand, requiredUlimits: options.requiredUlimits, - recreateGpu: recreatePatch, - recreateStartup: recreateStartupPatch, + recreateGpu: recreatePatch as RecreateGpuPatchFn, + recreateStartup: recreateStartupPatch as RecreateStartupPatchFn | undefined, }); const applyPatch = (deps: DockerGpuPatchDeps): void => { @@ -239,7 +263,7 @@ export function createDockerGpuSandboxCreatePatch( const finalization = (async () => { await managedBootstrapCutover?.rollback(); const finalizeOutcome = result - ? finalizeBackup({ result, supervisorReady: false }, options.deps) + ? await finalizeBackup({ result, supervisorReady: false }, options.deps) : null; cutoverFinalized = true; needsSupervisorWait = false; @@ -299,6 +323,7 @@ export function createDockerGpuSandboxCreatePatch( ); try { applyPatch({ + commandExecutor: options.deps.commandExecutor, runCaptureOpenshell: options.deps.runCaptureOpenshell, sleep: options.deps.sleep, }); @@ -368,7 +393,7 @@ export function createDockerGpuSandboxCreatePatch( } }, - waitForSupervisorReconnectIfNeeded() { + async waitForSupervisorReconnectIfNeeded() { if (!needsSupervisorWait || cutoverFinalized) return; const supervisorReconnectTimeoutSecs = getDockerGpuSupervisorReconnectTimeoutSecs( options.timeoutSecs, @@ -376,11 +401,11 @@ export function createDockerGpuSandboxCreatePatch( console.log( ` Waiting for OpenShell supervisor to reconnect to the recreated container (up to ${supervisorReconnectTimeoutSecs}s)...`, ); - const supervisorReady = waitForSupervisor( + const supervisorReady = await waitForSupervisor( options.sandboxName, supervisorReconnectTimeoutSecs, { - runOpenshell: options.deps.runOpenshell, + commandExecutor: options.deps.commandExecutor, runCaptureOpenshell: options.deps.runCaptureOpenshell, sleep: options.deps.sleep, }, @@ -408,7 +433,7 @@ export function createDockerGpuSandboxCreatePatch( } } const finalizeOutcome = result - ? finalizeBackup({ result, supervisorReady: false }, options.deps) + ? await finalizeBackup({ result, supervisorReady: false }, options.deps) : null; cutoverFinalized = true; needsSupervisorWait = false; @@ -504,7 +529,7 @@ export function createDockerGpuSandboxCreatePatch( options.timeoutSecs, ); const finalizeOutcome = result - ? finalizeBackup( + ? await finalizeBackup( { result, supervisorReady: true, diff --git a/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts b/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts index 2d8c98cef4a..85437a6fc40 100644 --- a/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts +++ b/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { getDockerGpuSupervisorReconnectErrorDebouncePolls, getDockerGpuSupervisorReconnectTimeoutSecs, @@ -10,14 +11,39 @@ import { waitForOpenShellSupervisorReconnect, } from "./docker-gpu-supervisor-reconnect"; +type LegacyExecResult = { status: number | null; stdout?: string; stderr?: string }; + +function commandExecutorThrough( + run: () => LegacyExecResult, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async () => { + const result = run(); + return { + outcome: + result.status === null + ? { kind: "failed" as const, error: { kind: "invocation" as const, message: "failed" } } + : { kind: "completed" as const, exitCode: result.status }, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; + }), + }; +} + describe("Docker GPU supervisor reconnect", () => { - it("does not report reconnect without an OpenShell execution boundary (#9531)", () => { - expect(waitForOpenShellSupervisorReconnect("alpha", 1, { sleep: vi.fn() })).toBe(false); + it("does not report reconnect when the OpenShell execution boundary fails (#9531)", async () => { + await expect( + waitForOpenShellSupervisorReconnect("alpha", 1, { + commandExecutor: commandExecutorThrough(() => ({ status: 1 })), + sleep: vi.fn(), + }), + ).resolves.toBe(false); }); }); describe("Docker GPU final handoff acknowledgement", () => { - it("expires a subsecond final handoff budget in milliseconds (#11096)", () => { + it("expires a subsecond final handoff budget in milliseconds (#11096)", async () => { vi.useFakeTimers(); try { const startedAtMs = new Date("2026-09-04T07:42:01Z").getTime(); @@ -27,9 +53,9 @@ describe("Docker GPU final handoff acknowledgement", () => { vi.advanceTimersByTime(seconds * 1000); }); - const acknowledgement = waitForOpenShellFinalHandoff("alpha", startedAtMs + 500, { + const acknowledgement = await waitForOpenShellFinalHandoff("alpha", startedAtMs + 500, { runCaptureOpenshell, - runOpenshell: vi.fn(() => ({ status: 1 })), + commandExecutor: commandExecutorThrough(() => ({ status: 1 })), replacementIsExactAndRunning: vi.fn(() => true), sleep, }); @@ -45,7 +71,7 @@ describe("Docker GPU final handoff acknowledgement", () => { } }); - it("accepts the exact running replacement only after OpenShell reports Ready (#9531)", () => { + it("accepts the exact running replacement only after OpenShell reports Ready (#9531)", async () => { const events: string[] = []; const runCaptureOpenshell = vi .fn() @@ -61,14 +87,15 @@ describe("Docker GPU final handoff acknowledgement", () => { events.push("exec ready"); return { status: 0 }; }); + const commandExecutor = commandExecutorThrough(runOpenshell); const replacementIsExactAndRunning = vi.fn(() => { events.push("confirm exact replacement"); return true; }); - const acknowledgement = waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { + const acknowledgement = await waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { runCaptureOpenshell, - runOpenshell, + commandExecutor, replacementIsExactAndRunning, sleep: vi.fn(), }); @@ -89,26 +116,25 @@ describe("Docker GPU final handoff acknowledgement", () => { timeout: expect.any(Number), }), ); - expect(runOpenshell).toHaveBeenCalledWith( - ["sandbox", "exec", "-n", "alpha", "--", "true"], + expect(commandExecutor.runBuffered).toHaveBeenCalledWith( expect.objectContaining({ - killProcessTreeOnTimeout: true, - killSignal: "SIGKILL", - timeout: expect.any(Number), + sandboxName: "alpha", + command: ["true"], + timeoutMilliseconds: expect.any(Number), }), ); }); - it("treats Deleting after the replacement start as terminal (#9531)", () => { + it("treats Deleting after the replacement start as terminal (#9531)", async () => { const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 10:00:00 Deleting\n"); const runOpenshell = vi.fn(() => ({ status: 1 })); const replacementIsExactAndRunning = vi.fn(() => true); const sleep = vi.fn(); expect( - waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { + await waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { runCaptureOpenshell, - runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), replacementIsExactAndRunning, sleep, }), @@ -119,14 +145,14 @@ describe("Docker GPU final handoff acknowledgement", () => { expect(sleep).not.toHaveBeenCalled(); }); - it("continues through Error only while the exact replacement is running (#9531)", () => { + it("continues through Error only while the exact replacement is running (#9531)", async () => { const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 10:00:00 Error\n"); const replacementIsExactAndRunning = vi.fn(() => false); expect( - waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { + await waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { runCaptureOpenshell, - runOpenshell: vi.fn(() => ({ status: 1 })), + commandExecutor: commandExecutorThrough(() => ({ status: 1 })), replacementIsExactAndRunning, sleep: vi.fn(), }), @@ -134,7 +160,7 @@ describe("Docker GPU final handoff acknowledgement", () => { expect(replacementIsExactAndRunning).toHaveBeenCalledOnce(); }); - it("allows a running replacement to progress from Error to Ready (#9531)", () => { + it("allows a running replacement to progress from Error to Ready (#9531)", async () => { const runCaptureOpenshell = vi .fn() .mockReturnValueOnce("alpha 2026-08-23 10:00:00 Error\n") @@ -143,9 +169,9 @@ describe("Docker GPU final handoff acknowledgement", () => { const replacementIsExactAndRunning = vi.fn(() => true); expect( - waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { + await waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { runCaptureOpenshell, - runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), replacementIsExactAndRunning, sleep: vi.fn(), }), @@ -154,7 +180,7 @@ describe("Docker GPU final handoff acknowledgement", () => { expect(runOpenshell).toHaveBeenCalledOnce(); }); - it("does not reuse a stale Ready phase after the sandbox row disappears (#9531)", () => { + it("does not reuse a stale Ready phase after the sandbox row disappears (#9531)", async () => { const runCaptureOpenshell = vi .fn() .mockReturnValueOnce("alpha 2026-08-23 10:00:00 Ready\n") @@ -163,9 +189,9 @@ describe("Docker GPU final handoff acknowledgement", () => { const replacementIsExactAndRunning = vi.fn().mockReturnValueOnce(true).mockReturnValue(false); expect( - waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { + await waitForOpenShellFinalHandoff("alpha", Date.now() + 60_000, { runCaptureOpenshell, - runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), replacementIsExactAndRunning, sleep: vi.fn(), }), @@ -193,7 +219,7 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { ).toBe(30); }); - it("short-circuits the supervisor-reconnect wait when the sandbox enters Error phase", () => { + it("short-circuits the supervisor-reconnect wait when the sandbox enters Error phase", async () => { const runOpenshell = vi.fn(() => ({ status: 1, stderr: "sandbox not ready" })); const listOutputs = [ "alpha Provisioning 1s ago", @@ -203,8 +229,8 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { const runCaptureOpenshell = vi.fn(() => listOutputs[Math.min(index++, listOutputs.length - 1)]); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, errorPhaseDebouncePolls: 1, @@ -215,7 +241,7 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { expect(sleep).toHaveBeenCalledTimes(1); }); - it("absorbs a transient Error phase shorter than the debounce window", () => { + it("absorbs a transient Error phase shorter than the debounce window", async () => { const execOutputs = [ { status: 1, stderr: "sandbox not ready" }, { status: 1, stderr: "sandbox not ready" }, @@ -236,8 +262,8 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { ); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, errorPhaseDebouncePolls: 5, @@ -247,13 +273,13 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { expect(runOpenshell).toHaveBeenCalledTimes(4); }); - it("still fast-fails when Error phase persists for the full debounce window", () => { + it("still fast-fails when Error phase persists for the full debounce window", async () => { const runOpenshell = vi.fn(() => ({ status: 1, stderr: "sandbox not ready" })); const runCaptureOpenshell = vi.fn(() => "alpha Error 1s ago"); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, errorPhaseDebouncePolls: 3, @@ -266,12 +292,12 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { expect(sleep).toHaveBeenCalledTimes(2); }); - it("does not accept a supervisor exec with no exit status", () => { + it("does not accept a supervisor exec with no exit status", async () => { const runOpenshell = vi.fn(() => ({ status: null, stderr: "timed out" })); const runCaptureOpenshell = vi.fn(() => "alpha Error 1s ago"); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep: vi.fn(), errorPhaseDebouncePolls: 1, @@ -281,7 +307,7 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { expect(runOpenshell).toHaveBeenCalledOnce(); }); - it("resets the consecutive-Error counter when the phase recovers", () => { + it("resets the consecutive-Error counter when the phase recovers", async () => { // Error, Error, Provisioning (counter resets), Error, Error, Error // -> bails out on the 3rd post-recovery Error, not earlier. const runOpenshell = vi.fn(() => ({ status: 1, stderr: "sandbox not ready" })); @@ -299,8 +325,8 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { ); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, errorPhaseDebouncePolls: 3, @@ -310,7 +336,7 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { expect(runOpenshell).toHaveBeenCalledTimes(6); }); - it("absorbs a Docker-CDI Error phase longer than the old 30s window", () => { + it("absorbs a Docker-CDI Error phase longer than the old 30s window", async () => { // #4948 runtime validation on the Docker-CDI GPU runner showed the // sandbox-list row can remain Error for roughly a minute after the CDI // recreate (`--device nvidia.com/gpu=all`) while the supervisor is still @@ -326,8 +352,8 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { ); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, }); @@ -351,15 +377,15 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { ).toBe(1); }); - it("clamps an injected debounce override to the same minimum as the env path", () => { + it("clamps an injected debounce override to the same minimum as the env path", async () => { // 0 / negative / fractional overrides must not bypass the ≥1 contract that // the env-backed helper enforces. const runOpenshell = vi.fn(() => ({ status: 1, stderr: "sandbox not ready" })); const runCaptureOpenshell = vi.fn(() => "alpha Error 1s ago"); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, errorPhaseDebouncePolls: 0, @@ -373,13 +399,13 @@ describe("docker-gpu-supervisor-reconnect Error-phase debounce", () => { it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])( "falls back to the env-backed default when an injected override is non-finite [case %#]", - (bogus) => { + async (bogus) => { const runOpenshell = vi.fn(() => ({ status: 1, stderr: "sandbox not ready" })); const runCaptureOpenshell = vi.fn(() => "alpha Error 1s ago"); const sleep = vi.fn(); - const ok = waitForOpenShellSupervisorReconnect("alpha", 600, { - runOpenshell, + const ok = await waitForOpenShellSupervisorReconnect("alpha", 600, { + commandExecutor: commandExecutorThrough(runOpenshell), runCaptureOpenshell, sleep, errorPhaseDebouncePolls: bogus, diff --git a/src/lib/onboard/docker-gpu-supervisor-reconnect.ts b/src/lib/onboard/docker-gpu-supervisor-reconnect.ts index 03722e6ac42..40a156427de 100644 --- a/src/lib/onboard/docker-gpu-supervisor-reconnect.ts +++ b/src/lib/onboard/docker-gpu-supervisor-reconnect.ts @@ -24,7 +24,8 @@ */ import { parseLiveSandboxEntries } from "../runtime-recovery"; -import { hasZeroDockerExitStatus } from "./docker-command-result"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { DOCKER_GPU_PATCH_TIMEOUT_MS } from "./docker-gpu-patch-constants"; import { envInt } from "./env"; @@ -57,25 +58,19 @@ export const DOCKER_GPU_SUPERVISOR_RECONNECT_ERROR_DEBOUNCE_ENV = const TERMINAL_SANDBOX_FAILURE_PHASES = new Set(["Error", "Failed", "CrashLoopBackOff"]); -type DockerRunResult = { - status?: number | null; - stdout?: string | Buffer | null; - stderr?: string | Buffer | null; -}; - -type RunOpenshellFn = (args: string[], opts?: Record) => DockerRunResult; type RunCaptureOpenshellFn = (args: string[], opts?: Record) => string; export type DockerGpuSupervisorReconnectDeps = { - runOpenshell?: RunOpenshellFn; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; runCaptureOpenshell?: RunCaptureOpenshellFn; sleep?: (seconds: number) => void; errorPhaseDebouncePolls?: number; }; type DockerFinalHandoffDeps = Required< - Pick + Pick > & + Required> & Pick & { now?: () => Date; /** @@ -118,11 +113,11 @@ function exactReplacementIsRunning( * sole running labeled container. Deleting is terminal after that start. * Error remains transient only while the exact replacement stays running. */ -export function waitForOpenShellFinalHandoff( +export async function waitForOpenShellFinalHandoff( sandboxName: string, deadlineMs: number, deps: DockerFinalHandoffDeps, -): DockerFinalHandoffAcknowledgement { +): Promise { const sleep = deps.sleep ?? defaultSleep; const now = deps.now ?? (() => new Date()); const startedAtMs = now().getTime(); @@ -165,18 +160,23 @@ export function waitForOpenShellFinalHandoff( if (currentPhase === "Ready") { const remainingBeforeExecMs = boundedDeadlineMs - now().getTime(); if (remainingBeforeExecMs <= 0) break; - const execResult = deps.runOpenshell(["sandbox", "exec", "-n", sandboxName, "--", "true"], { - ignoreError: true, - ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, - suppressOutput: true, - timeout: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingBeforeExecMs), + const execResult = await deps.commandExecutor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command: ["true"], + timeoutMilliseconds: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingBeforeExecMs), + timeoutKillSignal: "SIGKILL", }); const remainingAfterExecMs = boundedDeadlineMs - now().getTime(); const replacementIsRunning = exactReplacementIsRunning( deps.replacementIsExactAndRunning, remainingAfterExecMs, ); - if (hasZeroDockerExitStatus(execResult) && replacementIsRunning) { + if ( + execResult.outcome.kind === "completed" && + execResult.outcome.exitCode === 0 && + replacementIsRunning + ) { return { acknowledged: true, lastSandboxPhase }; } if (!replacementIsRunning) return { acknowledged: false, lastSandboxPhase }; @@ -224,12 +224,11 @@ function sandboxListShowsErrorPhase( } } -export function waitForOpenShellSupervisorReconnect( +export async function waitForOpenShellSupervisorReconnect( sandboxName: string, timeoutSecs: number, deps: DockerGpuSupervisorReconnectDeps, -): boolean { - if (!deps.runOpenshell) return false; +): Promise { const sleep = deps.sleep ?? defaultSleep; const deadline = Date.now() + Math.max(1, timeoutSecs) * 1000; const errorPhaseDebouncePolls = @@ -240,13 +239,14 @@ export function waitForOpenShellSupervisorReconnect( Math.max(1, Math.round(deps.errorPhaseDebouncePolls)); let consecutiveErrorPolls = 0; while (Date.now() <= deadline) { - const result = deps.runOpenshell(["sandbox", "exec", "-n", sandboxName, "--", "true"], { - ignoreError: true, - ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, - suppressOutput: true, - timeout: DOCKER_GPU_PATCH_TIMEOUT_MS, + const result = await deps.commandExecutor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command: ["true"], + timeoutMilliseconds: DOCKER_GPU_PATCH_TIMEOUT_MS, + timeoutKillSignal: "SIGKILL", }); - if (hasZeroDockerExitStatus(result)) return true; + if (result.outcome.kind === "completed" && result.outcome.exitCode === 0) return true; if ( deps.runCaptureOpenshell && sandboxListShowsErrorPhase(sandboxName, deps.runCaptureOpenshell) diff --git a/src/lib/onboard/docker-startup-command-patch.test.ts b/src/lib/onboard/docker-startup-command-patch.test.ts index 8923bb53062..2ee57e8e9af 100644 --- a/src/lib/onboard/docker-startup-command-patch.test.ts +++ b/src/lib/onboard/docker-startup-command-patch.test.ts @@ -3,13 +3,32 @@ import { describe, expect, it, vi } from "vitest"; -import type { DockerContainerInspect } from "./docker-gpu-patch"; +import type { DockerContainerInspect, DockerGpuPatchResult } from "./docker-gpu-patch"; import { recreateOpenShellDockerSandboxWithStartupCommand } from "./docker-startup-command-patch"; +type RecreateStartupCommandOptions = Parameters< + typeof recreateOpenShellDockerSandboxWithStartupCommand +>[0]; +type RecreateStartupCommandDeps = Parameters< + typeof recreateOpenShellDockerSandboxWithStartupCommand +>[1]; + +function recreateStartupCommandForTest( + options: RecreateStartupCommandOptions & { waitForSupervisor: false }, + deps?: RecreateStartupCommandDeps, +): DockerGpuPatchResult; +function recreateStartupCommandForTest( + options: RecreateStartupCommandOptions & { waitForSupervisor?: true }, + deps?: RecreateStartupCommandDeps, +): Promise; function recreateStartupCommandForTest( - options: Parameters[0], - deps: Parameters[1] = {}, -): ReturnType { + options: RecreateStartupCommandOptions, + deps?: RecreateStartupCommandDeps, +): DockerGpuPatchResult | Promise; +function recreateStartupCommandForTest( + options: RecreateStartupCommandOptions, + deps: RecreateStartupCommandDeps = {}, +): DockerGpuPatchResult | Promise { return recreateOpenShellDockerSandboxWithStartupCommand(options, { detectSandboxFallbackDns: () => null, ...deps, @@ -211,39 +230,39 @@ describe("Docker startup-command patch", () => { expect(dockerRunDetached).not.toHaveBeenCalled(); }); - it.each([ - "different-container-id", - "", - ])("refuses to mutate when the pinned container identity is changed or empty", (expectedOldContainerId) => { - const dockerStop = vi.fn(() => ({ status: 0 })); - const dockerRename = vi.fn(() => ({ status: 0 })); - const dockerRunDetached = vi.fn(() => ({ status: 0, stdout: "new-container-id\n" })); + it.each(["different-container-id", ""])( + "refuses to mutate when the pinned container identity is changed or empty", + (expectedOldContainerId) => { + const dockerStop = vi.fn(() => ({ status: 0 })); + const dockerRename = vi.fn(() => ({ status: 0 })); + const dockerRunDetached = vi.fn(() => ({ status: 0, stdout: "new-container-id\n" })); - expect(() => - recreateStartupCommandForTest( - { - sandboxName: "alpha", - openshellSandboxCommand: ["env", "nemoclaw-start"], - expectedOldContainerId, - }, - { - dockerCapture: vi.fn((args: readonly string[]) => - args[0] === "ps" - ? "old-container-id\n" - : args[0] === "inspect" - ? JSON.stringify([inspectFixture()]) - : "", - ), - dockerRunDetached, - dockerRename, - dockerStop, - }, - ), - ).toThrow("observed container differs from the pinned identity"); - expect(dockerStop).not.toHaveBeenCalled(); - expect(dockerRename).not.toHaveBeenCalled(); - expect(dockerRunDetached).not.toHaveBeenCalled(); - }); + expect(() => + recreateStartupCommandForTest( + { + sandboxName: "alpha", + openshellSandboxCommand: ["env", "nemoclaw-start"], + expectedOldContainerId, + }, + { + dockerCapture: vi.fn((args: readonly string[]) => + args[0] === "ps" + ? "old-container-id\n" + : args[0] === "inspect" + ? JSON.stringify([inspectFixture()]) + : "", + ), + dockerRunDetached, + dockerRename, + dockerStop, + }, + ), + ).toThrow("observed container differs from the pinned identity"); + expect(dockerStop).not.toHaveBeenCalled(); + expect(dockerRename).not.toHaveBeenCalled(); + expect(dockerRunDetached).not.toHaveBeenCalled(); + }, + ); it("does not rename or recreate when the original container cannot be stopped", () => { const dockerRename = vi.fn(() => ({ status: 0 })); diff --git a/src/lib/onboard/docker-startup-command-patch.ts b/src/lib/onboard/docker-startup-command-patch.ts index 2b5b6f761ef..1d393078733 100644 --- a/src/lib/onboard/docker-startup-command-patch.ts +++ b/src/lib/onboard/docker-startup-command-patch.ts @@ -10,22 +10,41 @@ import { const STARTUP_COMMAND_MODE = buildDockerGpuMode("startup-command"); +type RecreateStartupCommandOptions = { + sandboxName: string; + timeoutSecs?: number; + waitForSupervisor?: boolean; + openshellSandboxCommand: readonly string[]; + requiredUlimits?: readonly import("./docker-gpu-patch-types").DockerUlimit[] | null; + expectedOldContainerId?: string | null; +}; + +export function recreateOpenShellDockerSandboxWithStartupCommand( + options: RecreateStartupCommandOptions & { waitForSupervisor: false }, + deps?: DockerGpuPatchDeps, +): DockerGpuPatchResult; +export function recreateOpenShellDockerSandboxWithStartupCommand( + options: RecreateStartupCommandOptions & { waitForSupervisor?: true }, + deps?: DockerGpuPatchDeps, +): Promise; +export function recreateOpenShellDockerSandboxWithStartupCommand( + options: RecreateStartupCommandOptions, + deps?: DockerGpuPatchDeps, +): DockerGpuPatchResult | Promise; export function recreateOpenShellDockerSandboxWithStartupCommand( - options: { - sandboxName: string; - timeoutSecs?: number; - waitForSupervisor?: boolean; - openshellSandboxCommand: readonly string[]; - requiredUlimits?: readonly import("./docker-gpu-patch-types").DockerUlimit[] | null; - expectedOldContainerId?: string | null; - }, + options: RecreateStartupCommandOptions, deps: DockerGpuPatchDeps = {}, -): DockerGpuPatchResult { +): DockerGpuPatchResult | Promise { if (options.openshellSandboxCommand.length === 0) { throw new Error("OpenShell sandbox startup command is required for restart persistence."); } - return recreateOpenShellDockerSandboxContainer( - { ...options, modeOverride: STARTUP_COMMAND_MODE }, - deps, - ); + return options.waitForSupervisor === false + ? recreateOpenShellDockerSandboxContainer( + { ...options, waitForSupervisor: false, modeOverride: STARTUP_COMMAND_MODE }, + deps, + ) + : recreateOpenShellDockerSandboxContainer( + { ...options, waitForSupervisor: true, modeOverride: STARTUP_COMMAND_MODE }, + deps, + ); } diff --git a/src/lib/onboard/docker-startup-command-sandbox-create.test.ts b/src/lib/onboard/docker-startup-command-sandbox-create.test.ts index db2a995f6e8..61291200fbe 100644 --- a/src/lib/onboard/docker-startup-command-sandbox-create.test.ts +++ b/src/lib/onboard/docker-startup-command-sandbox-create.test.ts @@ -118,11 +118,11 @@ describe("Docker startup-command sandbox creation", () => { expect(patch.selectedMode()?.kind).toBe("startup-command"); }); - it("rolls back startup-command recreation when the supervisor does not reconnect", () => { + it("rolls back startup-command recreation when the supervisor does not reconnect", async () => { const deps = makeDeps(); const result = startupResult(); const capturePreRollbackDiagnostics = vi.fn(() => null); - const finalizeBackup = vi.fn(() => ({ backupRemoved: false, rolledBack: true })); + const finalizeBackup = vi.fn(async () => ({ backupRemoved: false, rolledBack: true })); const onPatchFailureExit = vi.fn(); const patch = createDockerGpuSandboxCreatePatch({ route: "native", @@ -134,7 +134,7 @@ describe("Docker startup-command sandbox creation", () => { overrides: { findContainerIds: vi.fn(() => ["existing-container"]), recreateStartupPatch: vi.fn(() => result), - waitForSupervisor: vi.fn(() => false), + waitForSupervisor: vi.fn(async () => false), capturePreRollbackDiagnostics, finalizeBackup, onPatchFailureExit, @@ -142,7 +142,7 @@ describe("Docker startup-command sandbox creation", () => { }); patch.maybeApplyDuringCreate(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(capturePreRollbackDiagnostics).toHaveBeenCalledWith("alpha", result, deps); expect(capturePreRollbackDiagnostics.mock.invocationCallOrder[0]).toBeLessThan( finalizeBackup.mock.invocationCallOrder[0], @@ -186,7 +186,7 @@ describe("Docker startup-command sandbox creation", () => { }); patch.maybeApplyDuringCreate(); await patch.ensureApplied(); - patch.waitForSupervisorReconnectIfNeeded(); + await patch.waitForSupervisorReconnectIfNeeded(); expect(patch.allowsNotReadyLifecycleRevalidation()).toBe(false); expect(commit).not.toHaveBeenCalled(); const firstCommit = patch.commitAfterReady(); diff --git a/src/lib/onboard/docker-startup-command-sandbox-create.ts b/src/lib/onboard/docker-startup-command-sandbox-create.ts index dd8df2e17b0..86ddffe130a 100644 --- a/src/lib/onboard/docker-startup-command-sandbox-create.ts +++ b/src/lib/onboard/docker-startup-command-sandbox-create.ts @@ -11,6 +11,11 @@ import { recreateOpenShellDockerSandboxWithStartupCommand } from "./docker-start export type RecreateGpuPatchFn = typeof recreateOpenShellDockerSandboxWithGpu; export type RecreateStartupPatchFn = typeof recreateOpenShellDockerSandboxWithStartupCommand; +type DockerSandboxRecreator = { + (waitForSupervisor: false, deps: DockerGpuPatchDeps): DockerGpuPatchResult; + (waitForSupervisor: true, deps: DockerGpuPatchDeps): Promise; +}; + export function createDockerSandboxRecreator(options: { gpuEnabled: boolean; gpuOptions: Parameters[0]; @@ -18,23 +23,24 @@ export function createDockerSandboxRecreator(options: { requiredUlimits?: Parameters[0]["requiredUlimits"]; recreateGpu?: RecreateGpuPatchFn; recreateStartup?: RecreateStartupPatchFn; -}): (waitForSupervisor: boolean, deps: DockerGpuPatchDeps) => DockerGpuPatchResult { +}): DockerSandboxRecreator { const recreateGpu = options.recreateGpu ?? recreateOpenShellDockerSandboxWithGpu; const recreateStartup = options.recreateStartup ?? recreateOpenShellDockerSandboxWithStartupCommand; - return (waitForSupervisor, deps) => { + return ((waitForSupervisor: boolean, deps: DockerGpuPatchDeps) => { if (options.gpuEnabled) { - return recreateGpu({ ...options.gpuOptions, waitForSupervisor }, deps); + return waitForSupervisor + ? recreateGpu({ ...options.gpuOptions, waitForSupervisor: true }, deps) + : recreateGpu({ ...options.gpuOptions, waitForSupervisor: false }, deps); } - return recreateStartup( - { - sandboxName: options.gpuOptions.sandboxName, - openshellSandboxCommand: options.startupCommand || [], - requiredUlimits: options.requiredUlimits, - timeoutSecs: options.gpuOptions.timeoutSecs, - waitForSupervisor, - }, - deps, - ); - }; + const startupOptions = { + sandboxName: options.gpuOptions.sandboxName, + openshellSandboxCommand: options.startupCommand || [], + requiredUlimits: options.requiredUlimits, + timeoutSecs: options.gpuOptions.timeoutSecs, + }; + return waitForSupervisor + ? recreateStartup({ ...startupOptions, waitForSupervisor: true }, deps) + : recreateStartup({ ...startupOptions, waitForSupervisor: false }, deps); + }) as DockerSandboxRecreator; } diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-inference.ts b/src/lib/onboard/experimental/hermes-portable-ollama-inference.ts index 118bf052d61..6fa4dc90c5d 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-inference.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-inference.ts @@ -221,6 +221,10 @@ function createHermesPortableOllamaRecoveryTimingRecorder( readonly onComplete: (durationMs: number) => void; }; readonly measure: (stage: HermesPortableOllamaRecoveryTimingStage, operation: () => T) => T; + readonly measureAsync: ( + stage: HermesPortableOllamaRecoveryTimingStage, + operation: () => Promise, + ) => Promise; readonly finish: ( runtimeAction: HermesPortableOllamaRecoveryTimingEvidence["runtimeAction"], counts: Pick< @@ -290,6 +294,23 @@ function createHermesPortableOllamaRecoveryTimingRecorder( onComplete: (durationMs: number) => recordExternalStage(stage, durationMs), }), measure: measureStage, + async measureAsync(stage, operation) { + const stageStartedAt = safeTimingNow(now); + const frame = { childMs: 0 }; + activeStages.push(frame); + try { + return await operation(); + } finally { + const duration = elapsed(stageStartedAt, safeTimingNow(now)); + activeStages.pop(); + durations.set( + stage, + Math.min(9_999_999, (durations.get(stage) ?? 0) + Math.max(0, duration - frame.childMs)), + ); + const parent = activeStages.at(-1); + if (parent) parent.childMs = Math.min(9_999_999, parent.childMs + duration); + } + }, finish(runtimeAction, counts, result = "proved"): void { if (finished) return; finished = true; @@ -337,8 +358,9 @@ function writeHermesPortablePublishedResumeTiming( ); } -const DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING: PodmanPublishedResumeTiming = - Object.freeze({ onComplete: writeHermesPortablePublishedResumeTiming }); +const DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING: PodmanPublishedResumeTiming = Object.freeze({ + onComplete: writeHermesPortablePublishedResumeTiming, +}); interface PreparedHermesPortableOllamaRecoveryEntry { readonly registryRecovery: PreparedPortableRegistryRecovery; @@ -432,8 +454,7 @@ function prepareHermesPortableOllamaRecoveryEntry(options: { assertForwardAuthority: runtimeOptions.assertForwardAuthority, }, publishedResumeTiming: - runtimeOptions.publishedResumeTiming ?? - DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING, + runtimeOptions.publishedResumeTiming ?? DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING, onFailureEvidence: (evidence) => { const message = redactOnboardDiagnosticText(evidence.message); if (message) console.error(` Podman inference ${evidence.phase}: ${message}`); @@ -460,8 +481,7 @@ function prepareHermesPortableOllamaRecoveryEntry(options: { environment: options.env, }, publishedResumeTiming: - runtimeOptions.publishedResumeTiming ?? - DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING, + runtimeOptions.publishedResumeTiming ?? DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING, onFailureEvidence: (evidence) => { const message = redactOnboardDiagnosticText(evidence.message); if (message) console.error(` Podman inference ${evidence.phase}: ${message}`); @@ -576,8 +596,7 @@ export function createHermesPortableOllamaRuntimeAuthority(options: { assertForwardAuthority: options.publishedRecovery.assertForwardAuthority, }, publishedResumeTiming: - options.publishedResumeTiming ?? - DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING, + options.publishedResumeTiming ?? DEFAULT_HERMES_PORTABLE_PUBLISHED_RESUME_TIMING, } : {}), authorityStore: openFilePersistedEngineAuthorityStore(inferenceStateDir), @@ -675,7 +694,7 @@ export interface HermesPortableOllamaRecoveryInput { readonly stateDir?: string; readonly runGatewayOpenshell: HermesPortableOllamaGatewayRunner; readonly readRegistry: (sandboxName: string) => SandboxEntry | null; - readonly verifyRoute: () => SandboxEntry; + readonly verifyRoute: () => Promise; readonly prepareProbeDependency?: () => HermesPortableOllamaPreparedProbeDependency; readonly assertCallerTransactionCurrent?: () => void; readonly assertCallerCurrent?: () => void; @@ -949,10 +968,10 @@ function restoreStoppedRuntime( } /** Resume and re-prove only the exact published Hermes Portable Ollama runtime. */ -export function recoverHermesPortableOllamaInference( +export async function recoverHermesPortableOllamaInference( input: HermesPortableOllamaRecoveryInput, overrides: Partial = {}, -): HermesPortableOllamaRecoveryResult { +): Promise { if (input.intent !== "connect-probe-only") { failRecovery("recovery is restricted to connect --probe-only"); } @@ -1171,8 +1190,8 @@ export function recoverHermesPortableOllamaInference( assertPreparedAuthorityCurrent(true); requireRetainedCurrent(); }; - const verifyFinalRoute = (): void => { - const verified = input.verifyRoute(); + const verifyFinalRoute = async (): Promise => { + const verified = await input.verifyRoute(); if (!isDeepStrictEqual(verified, input.entry)) { failRecovery("final route verification returned different registry authority"); } @@ -1207,7 +1226,7 @@ export function recoverHermesPortableOllamaInference( ); requireRetainedCurrent(); }); - recoveryTiming.measure("route", verifyFinalRoute); + await recoveryTiming.measureAsync("route", verifyFinalRoute); preparedDependency = recoveryTiming.measure( "dependency", () => input.prepareProbeDependency?.() ?? null, @@ -1277,7 +1296,7 @@ export function recoverHermesPortableOllamaInference( ); requireRetainedCurrent(); }); - recoveryTiming.measure("route", verifyFinalRoute); + await recoveryTiming.measureAsync("route", verifyFinalRoute); preparedDependency = recoveryTiming.measure( "dependency", () => input.prepareProbeDependency?.() ?? null, diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-published-engine-recovery.test.ts b/src/lib/onboard/experimental/hermes-portable-ollama-published-engine-recovery.test.ts index d018e3428e4..fc130692479 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-published-engine-recovery.test.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-published-engine-recovery.test.ts @@ -334,7 +334,7 @@ function composedRecovery(fixture: ReturnType, assertPublished = v readRegistry: vi.fn(() => fixture.entry), assertCallerTransactionCurrent: vi.fn(), assertCallerCurrent: vi.fn(), - verifyRoute: vi.fn(() => fixture.entry), + verifyRoute: vi.fn(async () => fixture.entry), prepareProbeDependency: undefined as Parameters< typeof recoverHermesPortableOllamaInference >[0]["prepareProbeDependency"], @@ -584,7 +584,7 @@ describe("Hermes Portable published engine recovery", () => { expect(fixture.harness.written).toEqual([fixture.serializedReceipt]); }); - it("composes the probe-only owner through private publication and final route proof (#10423)", () => { + it("composes the probe-only owner through private publication and final route proof (#10423)", async () => { const fixture = setup(); const beforeEntry = JSON.stringify(fixture.entry); const beforeContainer = fixture.harness.container()!; @@ -597,7 +597,7 @@ describe("Hermes Portable published engine recovery", () => { const observed = observePublishedFinalization(fixture.harness.events); Object.assign(composed.overrides, { prepareStartup: observed.prepareStartup }); const recoveryEventStart = fixture.harness.events.length; - composed.input.verifyRoute.mockImplementation(() => { + composed.input.verifyRoute.mockImplementation(async () => { fixture.harness.events.push("test:route-verified"); return fixture.entry; }); @@ -613,9 +613,9 @@ describe("Hermes Portable published engine recovery", () => { fixture.harness.events.push("test:registry-released"); }); - expect(recoverHermesPortableOllamaInference(composed.input, composed.overrides as never)).toBe( - "recovered", - ); + expect( + await recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), + ).toBe("recovered"); const afterContainer = fixture.harness.container()!; expect(afterContainer).toMatchObject({ running: true, status: "running" }); expect( @@ -656,7 +656,7 @@ describe("Hermes Portable published engine recovery", () => { expect(dependencyReleasedIndex).toBeGreaterThan(releasedIndex); }); - it("reuses a running published runtime with one GPU proof before route health (#10423)", () => { + it("reuses a running published runtime with one GPU proof before route health (#10423)", async () => { const onComplete = vi.fn(); const fixture = setup({ publishedResumeTiming: { onComplete } }); fixture.harness.container()!.running = true; @@ -674,9 +674,9 @@ describe("Hermes Portable published engine recovery", () => { const captureStart = fixture.currentExecutionCaptures.length; fixture.transactionAuthorityAssertions.splice(0); - expect(recoverHermesPortableOllamaInference(composed.input, composed.overrides as never)).toBe( - "reused", - ); + expect( + await recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), + ).toBe("reused"); const recoveryEvents = fixture.harness.events.slice(recoveryEventStart); expect(recoveryEvents.filter((event) => event.includes("/api/tags"))).toHaveLength(0); @@ -860,72 +860,75 @@ describe("Hermes Portable published engine recovery", () => { "network", "container", "registry", - ] as const)("rejects %s drift immediately after the exact GPU command (#10423)", (driftKind) => { - let armed = false; - let gpuCommandCompleted = false; - let commandEndpointDrifted = false; - let fixture: ReturnType; - let composed: ReturnType; - fixture = setup({ - assertTransactionAuthority(operation) { - expect( - armed && commandEndpointDrifted && operation === "host-local-inference", - "current executable or socket authority changed", - ).toBe(false); - }, - transformCapture(args, result) { - const firstGpuCommand = - armed && args[0] === "exec" && args[2] === "nvidia-smi" && !gpuCommandCompleted; - const drift = { - "lifecycle-receipt": () => - composed.input.assertCallerTransactionCurrent.mockImplementation(() => { - throw new Error("active receipt file identity changed"); - }), - "private-publication": () => - composed.assertPublished.mockImplementation(() => { - throw new Error("private publication receipt changed"); - }), - "command-endpoint": () => { - commandEndpointDrifted = true; - }, - network: () => { - fixture.harness.state.networkName = "drifted-network"; - }, - container: () => { - fixture.harness.container()!.labels[PODMAN_INFERENCE_SPEC_LABEL] = "0".repeat(64); - }, - registry: () => - composed.input.readRegistry.mockReturnValue({ - ...fixture.entry, - model: "registry-model-drift", - }), - }[driftKind]; - (firstGpuCommand - ? () => { - gpuCommandCompleted = true; - drift(); - } - : () => undefined)(); - return result; - }, - }); - fixture.harness.container()!.running = true; - fixture.harness.container()!.status = "running"; - composed = composedRecovery(fixture); - armed = true; - - expect(() => - recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), - ).toThrow(); - - expect(gpuCommandCompleted).toBe(true); - expect(composed.input.verifyRoute).not.toHaveBeenCalled(); - expect(composed.registryRecovery.release).not.toHaveBeenCalled(); - expect(composed.registryRecovery.rollback).toHaveBeenCalledOnce(); - expect(fixture.harness.container()).toMatchObject({ running: true, status: "running" }); - }); + ] as const)( + "rejects %s drift immediately after the exact GPU command (#10423)", + async (driftKind) => { + let armed = false; + let gpuCommandCompleted = false; + let commandEndpointDrifted = false; + let fixture: ReturnType; + let composed: ReturnType; + fixture = setup({ + assertTransactionAuthority(operation) { + expect( + armed && commandEndpointDrifted && operation === "host-local-inference", + "current executable or socket authority changed", + ).toBe(false); + }, + transformCapture(args, result) { + const firstGpuCommand = + armed && args[0] === "exec" && args[2] === "nvidia-smi" && !gpuCommandCompleted; + const drift = { + "lifecycle-receipt": () => + composed.input.assertCallerTransactionCurrent.mockImplementation(() => { + throw new Error("active receipt file identity changed"); + }), + "private-publication": () => + composed.assertPublished.mockImplementation(() => { + throw new Error("private publication receipt changed"); + }), + "command-endpoint": () => { + commandEndpointDrifted = true; + }, + network: () => { + fixture.harness.state.networkName = "drifted-network"; + }, + container: () => { + fixture.harness.container()!.labels[PODMAN_INFERENCE_SPEC_LABEL] = "0".repeat(64); + }, + registry: () => + composed.input.readRegistry.mockReturnValue({ + ...fixture.entry, + model: "registry-model-drift", + }), + }[driftKind]; + (firstGpuCommand + ? () => { + gpuCommandCompleted = true; + drift(); + } + : () => undefined)(); + return result; + }, + }); + fixture.harness.container()!.running = true; + fixture.harness.container()!.status = "running"; + composed = composedRecovery(fixture); + armed = true; + + await expect( + recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), + ).rejects.toThrow(); + + expect(gpuCommandCompleted).toBe(true); + expect(composed.input.verifyRoute).not.toHaveBeenCalled(); + expect(composed.registryRecovery.release).not.toHaveBeenCalled(); + expect(composed.registryRecovery.rollback).toHaveBeenCalledOnce(); + expect(fixture.harness.container()).toMatchObject({ running: true, status: "running" }); + }, + ); - it("rolls both stopped resources back when private publication drifts after start (#10423)", () => { + it("rolls both stopped resources back when private publication drifts after start (#10423)", async () => { const fixture = setup(); const assertPublished = vi.fn(() => { expect( @@ -936,7 +939,7 @@ describe("Hermes Portable published engine recovery", () => { let failure: unknown; try { - recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); + await recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); } catch (error) { failure = error; } @@ -948,7 +951,7 @@ describe("Hermes Portable published engine recovery", () => { expect(composed.input.verifyRoute).not.toHaveBeenCalled(); }); - it("restores both stopped resources when the sandbox registry drifts after start (#10423)", () => { + it("restores both stopped resources when the sandbox registry drifts after start (#10423)", async () => { const fixture = setup(); const composed = composedRecovery(fixture); composed.input.readRegistry.mockImplementation(() => @@ -959,7 +962,7 @@ describe("Hermes Portable published engine recovery", () => { let failure: unknown; try { - recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); + await recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); } catch (error) { failure = error; } @@ -970,10 +973,10 @@ describe("Hermes Portable published engine recovery", () => { expect(composed.registryRecovery.release).not.toHaveBeenCalled(); }); - it("restores both stopped resources when final managed route health fails (#10423)", () => { + it("restores both stopped resources when final managed route health fails (#10423)", async () => { const fixture = setup(); const composed = composedRecovery(fixture); - composed.input.verifyRoute.mockImplementation(() => { + composed.input.verifyRoute.mockImplementation(async () => { throw new Error("managed route unavailable"); }); const observed = observePublishedFinalization([]); @@ -983,9 +986,9 @@ describe("Hermes Portable published engine recovery", () => { rollback: vi.fn(), })); - expect(() => + await expect( recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), - ).toThrow(); + ).rejects.toThrow(); expect(fixture.harness.container()).toMatchObject({ running: false, status: "exited" }); expect(composed.input.verifyRoute).toHaveBeenCalledOnce(); @@ -995,7 +998,7 @@ describe("Hermes Portable published engine recovery", () => { expect(composed.registryRecovery.release).not.toHaveBeenCalled(); }); - it("restores both stopped resources when exact GPU identity changes (#10423)", () => { + it("restores both stopped resources when exact GPU identity changes (#10423)", async () => { const fixture = setup(); fixture.harness.state.gpuIdentities = ["GPU-00000000-0000-0000-0000-000000000000"]; const composed = composedRecovery(fixture); @@ -1006,9 +1009,9 @@ describe("Hermes Portable published engine recovery", () => { rollback: vi.fn(), })); - expect(() => + await expect( recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), - ).toThrow("requested CDI UUID authority"); + ).rejects.toThrow("requested CDI UUID authority"); expect(fixture.harness.container()).toMatchObject({ running: false, status: "exited" }); expect(composed.input.verifyRoute).not.toHaveBeenCalled(); @@ -1018,7 +1021,7 @@ describe("Hermes Portable published engine recovery", () => { expect(composed.registryRecovery.release).not.toHaveBeenCalled(); }); - it("restores stopped state when published authority drifts during precommit validation (#10423)", () => { + it("restores stopped state when published authority drifts during precommit validation (#10423)", async () => { let recoveryStarted = false; let validationReached = false; const fixture = setup({ @@ -1036,9 +1039,9 @@ describe("Hermes Portable published engine recovery", () => { const composed = composedRecovery(fixture, assertPublished); recoveryStarted = true; - expect(() => + await expect( recoverHermesPortableOllamaInference(composed.input, composed.overrides as never), - ).toThrow(); + ).rejects.toThrow(); expect(validationReached).toBe(true); expect(fixture.harness.container()).toMatchObject({ running: false, status: "exited" }); @@ -1047,7 +1050,7 @@ describe("Hermes Portable published engine recovery", () => { expect(composed.registryRecovery.release).not.toHaveBeenCalled(); }); - it("reports unproved restoration when the current network drifts after start (#10423)", () => { + it("reports unproved restoration when the current network drifts after start (#10423)", async () => { const fixture = setup(); const composed = composedRecovery(fixture); fixture.externalNetwork.assertCurrent.mockImplementation(() => { @@ -1058,7 +1061,7 @@ describe("Hermes Portable published engine recovery", () => { let failure: unknown; try { - recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); + await recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); } catch (error) { failure = error; } @@ -1070,14 +1073,14 @@ describe("Hermes Portable published engine recovery", () => { expect(composed.registryRecovery.release).not.toHaveBeenCalled(); }); - it("does not roll back the registry from an indeterminate stopped-looking runtime (#10423)", () => { + it("does not roll back the registry from an indeterminate stopped-looking runtime (#10423)", async () => { const fixture = setup(); fixture.harness.container()!.status = "unknown"; const composed = composedRecovery(fixture); let failure: unknown; try { - recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); + await recoverHermesPortableOllamaInference(composed.input, composed.overrides as never); } catch (error) { failure = error; } diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-recovery.test.ts b/src/lib/onboard/experimental/hermes-portable-ollama-recovery.test.ts index cae638c088c..61acc4a6b1a 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-recovery.test.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-recovery.test.ts @@ -159,9 +159,7 @@ function createHarness(initiallyRunning = false, registryInitiallyRunning = fals }); const assertOperating = vi.fn(() => events.push("operating")); const assertRuntimeRetainedCurrent = vi.fn(() => events.push("runtime-retained-current")); - const assertRuntimeTransactionCurrent = vi.fn(() => - events.push("runtime-transaction-current"), - ); + const assertRuntimeTransactionCurrent = vi.fn(() => events.push("runtime-transaction-current")); const assertRuntimeCurrent = vi.fn(() => { events.push("runtime-current"); expect(running).toBe(true); @@ -268,7 +266,7 @@ function createHarness(initiallyRunning = false, registryInitiallyRunning = fals stateDir: "/state", runGatewayOpenshell: vi.fn(), readRegistry: vi.fn(() => entry), - verifyRoute: vi.fn(() => { + verifyRoute: vi.fn(async () => { events.push("route"); return entry; }), @@ -421,14 +419,14 @@ describe("Hermes Portable Ollama inference recovery", () => { ["malformed", "not-json\n", "serialized receipt is not valid JSON"], ] as const)( "rejects an ollama-local registry receipt that is %s before registry recovery", - (_label, serializedReceipt, expectedError) => { + async (_label, serializedReceipt, expectedError) => { const harness = createHarness(); const entry = { ...harness.input.entry, hostLocalInferenceReceipt: serializedReceipt, } as SandboxEntry; - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, @@ -437,17 +435,17 @@ describe("Hermes Portable Ollama inference recovery", () => { }, harness.overrides as never, ), - ).toThrow(expectedError); + ).rejects.toThrow(expectedError); expect(harness.overrides.prepareRegistryRecovery).not.toHaveBeenCalled(); }, ); - it("resumes one stopped published runtime and commits only after final route proof", () => { + it("resumes one stopped published runtime and commits only after final route proof", async () => { const harness = createHarness(); - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - "recovered", - ); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe("recovered"); expect(harness.prepareStartup).toHaveBeenCalledOnce(); expect(harness.running()).toBe(true); @@ -464,16 +462,16 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.events.at(-1)).toBe("registry-release"); }); - it("uses retained inference currentness until one final full qualification", () => { + it("uses retained inference currentness until one final full qualification", async () => { const harness = createHarness(); const retained = vi.fn(); const full = vi.fn(() => ({ running: true, receipt: harness.receipt })); harness.overrides.assertPreparedInferenceAuthorityTransactionCurrent = retained; harness.overrides.assertPreparedInferenceAuthorityCurrent = full; - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - "recovered", - ); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe("recovered"); expect(retained).toHaveBeenCalledTimes(4); expect(full).toHaveBeenCalledOnce(); @@ -484,7 +482,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.writeExact).not.toHaveBeenCalled(); }); - it("rolls the exact stopped runtime back when retained inference authority drifts", () => { + it("rolls the exact stopped runtime back when retained inference authority drifts", async () => { const harness = createHarness(); const drift = new Error("retained inference authority changed"); harness.overrides.assertPreparedInferenceAuthorityTransactionCurrent = vi @@ -494,9 +492,9 @@ describe("Hermes Portable Ollama inference recovery", () => { throw drift; }); - expect(() => + await expect( recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), - ).toThrow(drift); + ).rejects.toThrow(drift); expect(harness.prepared.rollback).toHaveBeenCalledOnce(); expect(harness.input.verifyRoute).not.toHaveBeenCalled(); @@ -504,7 +502,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.running()).toBe(false); }); - it("releases a prepared probe dependency only after stopped-runtime finalization", () => { + it("releases a prepared probe dependency only after stopped-runtime finalization", async () => { const harness = createHarness(); const dependency = { release: vi.fn(() => harness.events.push("dependency-release")), @@ -512,7 +510,7 @@ describe("Hermes Portable Ollama inference recovery", () => { }; expect( - recoverHermesPortableOllamaInference( + await recoverHermesPortableOllamaInference( { ...harness.input, prepareProbeDependency: vi.fn(() => { @@ -539,11 +537,11 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(dependency.rollback).not.toHaveBeenCalled(); }); - it("restores the stopped runtime when probe-dependency preparation fails", () => { + it("restores the stopped runtime when probe-dependency preparation fails", async () => { const harness = createHarness(); const canary = new Error("forward preparation failed"); - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, @@ -553,7 +551,7 @@ describe("Hermes Portable Ollama inference recovery", () => { }, harness.overrides as never, ), - ).toThrow(canary); + ).rejects.toThrow(canary); expect(harness.prepared.rollback).toHaveBeenCalledOnce(); expect(harness.running()).toBe(false); @@ -563,7 +561,7 @@ describe("Hermes Portable Ollama inference recovery", () => { ); }); - it("rolls back a prepared probe dependency before the stopped runtime", () => { + it("rolls back a prepared probe dependency before the stopped runtime", async () => { const harness = createHarness(); const dependency = { release: vi.fn(() => harness.events.push("dependency-release")), @@ -574,12 +572,12 @@ describe("Hermes Portable Ollama inference recovery", () => { throw new Error("finalization failed"); }); - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, prepareProbeDependency: vi.fn(() => dependency) }, harness.overrides as never, ), - ).toThrow("finalization failed"); + ).rejects.toThrow("finalization failed"); expect(dependency.release).not.toHaveBeenCalled(); expect(harness.events.indexOf("dependency-rollback")).toBeLessThan( @@ -592,7 +590,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.registryRunning()).toBe(false); }); - it("restores forwards, the stopped runtime, and the registry after retained command drift", () => { + it("restores forwards, the stopped runtime, and the registry after retained command drift", async () => { const harness = createHarness(); const commandDrift = new Error("retained command authority changed"); const assertCallerCurrent = vi.fn(() => { @@ -603,7 +601,7 @@ describe("Hermes Portable Ollama inference recovery", () => { rollback: vi.fn(() => harness.events.push("dependency-rollback")), }; - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, @@ -618,7 +616,7 @@ describe("Hermes Portable Ollama inference recovery", () => { }, harness.overrides as never, ), - ).toThrow(commandDrift); + ).rejects.toThrow(commandDrift); expect(dependency.release).not.toHaveBeenCalled(); expect(dependency.rollback).toHaveBeenCalledOnce(); @@ -633,7 +631,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.registryRunning()).toBe(false); }); - it("keeps runtime restoration uncertainty dominant when command drift also breaks forward rollback", () => { + it("keeps runtime restoration uncertainty dominant when command drift also breaks forward rollback", async () => { const harness = createHarness(); const commandDrift = new Error("retained command authority changed"); const assertCallerCurrent = vi.fn(); @@ -655,7 +653,7 @@ describe("Hermes Portable Ollama inference recovery", () => { let caught: unknown; try { - recoverHermesPortableOllamaInference( + await recoverHermesPortableOllamaInference( { ...harness.input, assertCallerCurrent, @@ -684,7 +682,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.registryRunning()).toBe(true); }); - it("preserves probe-dependency restoration uncertainty after restoring Ollama", () => { + it("preserves probe-dependency restoration uncertainty after restoring Ollama", async () => { const harness = createHarness(); const restorationError = new Error("forward restoration unproved"); const dependency = { @@ -699,12 +697,12 @@ describe("Hermes Portable Ollama inference recovery", () => { throw new Error("lower finalization canary"); }); - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, prepareProbeDependency: vi.fn(() => dependency) }, harness.overrides as never, ), - ).toThrow(restorationError); + ).rejects.toThrow(restorationError); expect(harness.prepared.rollback).toHaveBeenCalledOnce(); expect(harness.running()).toBe(false); @@ -714,12 +712,12 @@ describe("Hermes Portable Ollama inference recovery", () => { ); }); - it("validates an already running runtime without invoking resume", () => { + it("validates an already running runtime without invoking resume", async () => { const harness = createHarness(true, true); - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - "reused", - ); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe("reused"); expect(harness.runtime.validatePublishedResume).toHaveBeenCalledOnce(); expect(harness.runtime.preserveForRebuild).not.toHaveBeenCalled(); @@ -729,19 +727,19 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.events.at(-1)).toBe("registry-release"); }); - it("preserves an existing recovery failure classification", () => { + it("preserves an existing recovery failure classification", async () => { const harness = createHarness(true, true); const nested = new HermesPortableOllamaRecoveryError( "runtime-restoration-unproved", "nested recovery remained indeterminate", ); - harness.input.verifyRoute.mockImplementation(() => { + harness.input.verifyRoute.mockImplementation(async () => { throw nested; }); let caught: unknown; try { - recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); } catch (error) { caught = error; } @@ -752,22 +750,22 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.events).not.toContain("registry-release"); }); - it("rejects a running runtime when published resume validation is unavailable", () => { + it("rejects a running runtime when published resume validation is unavailable", async () => { const harness = createHarness(true, true); const { validatePublishedResume: _validatePublishedResume, ...runtimeWithoutValidator } = harness.runtime; harness.managedOperation.managedRuntime = runtimeWithoutValidator as never; - expect(() => + await expect( recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), - ).toThrow("runtime provider lacks published resume validation"); + ).rejects.toThrow("runtime provider lacks published resume validation"); expect(harness.input.verifyRoute).not.toHaveBeenCalled(); expect(harness.prepareStartup).not.toHaveBeenCalled(); expect(harness.events).not.toContain("registry-release"); }); - it("does not invent runtime rollback for an already-running Ollama dependency failure", () => { + it("does not invent runtime rollback for an already-running Ollama dependency failure", async () => { const harness = createHarness(true, true); const dependency = { release: vi.fn(), @@ -788,24 +786,24 @@ describe("Hermes Portable Ollama inference recovery", () => { }), }); - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, prepareProbeDependency: vi.fn(() => dependency) }, harness.overrides as never, ), - ).toThrow("registry finalization failed"); + ).rejects.toThrow("registry finalization failed"); expect(dependency.rollback).toHaveBeenCalledOnce(); expect(harness.prepared.rollback).not.toHaveBeenCalled(); expect(harness.running()).toBe(true); }); - it("reconciles a stopped registry before validating an already running runtime", () => { + it("reconciles a stopped registry before validating an already running runtime", async () => { const harness = createHarness(true); - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - "reused", - ); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe("reused"); expect(harness.events).toContain("registry-start"); expect(harness.runtime.validatePublishedResume).toHaveBeenCalledOnce(); @@ -815,7 +813,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.events.at(-1)).toBe("registry-release"); }); - it("emits failed timing after final route failure restores the exact stopped state", () => { + it("emits failed timing after final route failure restores the exact stopped state", async () => { const harness = createHarness(); let now = 0; const routeError = new Error("route unavailable"); @@ -826,13 +824,13 @@ describe("Hermes Portable Ollama inference recovery", () => { onComplete, }, }); - harness.input.verifyRoute.mockImplementation(() => { + harness.input.verifyRoute.mockImplementation(async () => { throw routeError; }); let caught: unknown; try { - recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); } catch (error) { caught = error; } @@ -860,15 +858,15 @@ describe("Hermes Portable Ollama inference recovery", () => { ); }); - it("restores the exact stopped state when provider revalidation fails", () => { + it("restores the exact stopped state when provider revalidation fails", async () => { const harness = createHarness(); vi.mocked(harness.prepared.validateBeforeCommit).mockImplementation(() => { throw new Error("provider unavailable"); }); - expect(() => + await expect( recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), - ).toThrow("provider unavailable"); + ).rejects.toThrow("provider unavailable"); expect(harness.prepared.rollback).toHaveBeenCalledOnce(); expect(harness.input.verifyRoute).not.toHaveBeenCalled(); @@ -879,7 +877,7 @@ describe("Hermes Portable Ollama inference recovery", () => { ); }); - it("restores the exact stopped state when final published authority changes", () => { + it("restores the exact stopped state when final published authority changes", async () => { const harness = createHarness(); const assertCurrent = vi.fn(() => { throw new Error("published authority changed"); @@ -896,9 +894,9 @@ describe("Hermes Portable Ollama inference recovery", () => { assertCurrent, }); - expect(() => + await expect( recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), - ).toThrow("published authority changed"); + ).rejects.toThrow("published authority changed"); expect(harness.input.verifyRoute).toHaveBeenCalledOnce(); expect(harness.prepared.finalizePublishedResume).toHaveBeenCalledOnce(); @@ -908,7 +906,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.registryRunning()).toBe(false); }); - it("rejects Ollama registry provenance before runtime mutation", () => { + it("rejects Ollama registry provenance before runtime mutation", async () => { const harness = createHarness(); harness.input.entry = { ...harness.input.entry, @@ -920,9 +918,9 @@ describe("Hermes Portable Ollama inference recovery", () => { } as never; harness.input.readRegistry.mockReturnValue(harness.input.entry); - expect(() => + await expect( recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), - ).toThrow("Ollama registry must not contain llama.cpp provenance"); + ).rejects.toThrow("Ollama registry must not contain llama.cpp provenance"); expect(harness.prepareStartup).not.toHaveBeenCalled(); expect(harness.running()).toBe(false); @@ -930,15 +928,15 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.events).not.toContain("registry-start"); }); - it("is idempotent across a recovered probe and a second probe", () => { + it("is idempotent across a recovered probe and a second probe", async () => { const harness = createHarness(); - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - "recovered", - ); - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - "reused", - ); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe("recovered"); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe("reused"); expect(harness.prepareStartup).toHaveBeenCalledOnce(); expect(harness.runtime.validatePublishedResume).toHaveBeenCalledOnce(); @@ -950,76 +948,79 @@ describe("Hermes Portable Ollama inference recovery", () => { it.each([ ["recovered", false], ["reused", true], - ] as const)("emits fixed outer timing after a successful %s transaction", (action, running) => { - const harness = createHarness(running, running); - let now = 0; - const onComplete = vi.fn(); - Object.assign(harness.overrides, { - recoveryTiming: { - now: () => ++now, - onComplete, - }, - }); + ] as const)( + "emits fixed outer timing after a successful %s transaction", + async (action, running) => { + const harness = createHarness(running, running); + let now = 0; + const onComplete = vi.fn(); + Object.assign(harness.overrides, { + recoveryTiming: { + now: () => ++now, + onComplete, + }, + }); - expect(recoverHermesPortableOllamaInference(harness.input, harness.overrides as never)).toBe( - action, - ); + expect( + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), + ).toBe(action); - expect(onComplete).toHaveBeenCalledOnce(); - const evidence = onComplete.mock.calls[0]?.[0]; - expect(Object.keys(evidence).sort()).toEqual([ - "dependencyMs", - "entryAuthorityMs", - "exactRuntimeInspectionMs", - "finalCurrentnessMs", - "fullCurrentnessCount", - "operatingAuthorityMs", - "preRouteCurrentnessMs", - "preparedAuthorityInspectionCount", - "preparedInferenceAuthorityMs", - "privatePublicationMs", - "registryPreparationMs", - "result", - "retainedCurrentnessCount", - "routeMs", - "runtimeAction", - "runtimeAuthorityMs", - "totalMs", - ]); - expect(evidence).toMatchObject({ - exactRuntimeInspectionMs: 1, - operatingAuthorityMs: 1, - preparedInferenceAuthorityMs: 2, - privatePublicationMs: 1, - registryPreparationMs: 1, - retainedCurrentnessCount: action === "recovered" ? 4 : 3, - fullCurrentnessCount: 1, - preparedAuthorityInspectionCount: 2, - result: "proved", - runtimeAction: action, - runtimeAuthorityMs: 1, - }); - expect( - Object.entries(evidence) - .filter(([key]) => key.endsWith("Ms")) - .every(([, value]) => typeof value === "number" && value >= 0), - ).toBe(true); - expect(JSON.stringify(evidence)).not.toContain("qwen3-vl"); - }); + expect(onComplete).toHaveBeenCalledOnce(); + const evidence = onComplete.mock.calls[0]?.[0]; + expect(Object.keys(evidence).sort()).toEqual([ + "dependencyMs", + "entryAuthorityMs", + "exactRuntimeInspectionMs", + "finalCurrentnessMs", + "fullCurrentnessCount", + "operatingAuthorityMs", + "preRouteCurrentnessMs", + "preparedAuthorityInspectionCount", + "preparedInferenceAuthorityMs", + "privatePublicationMs", + "registryPreparationMs", + "result", + "retainedCurrentnessCount", + "routeMs", + "runtimeAction", + "runtimeAuthorityMs", + "totalMs", + ]); + expect(evidence).toMatchObject({ + exactRuntimeInspectionMs: 1, + operatingAuthorityMs: 1, + preparedInferenceAuthorityMs: 2, + privatePublicationMs: 1, + registryPreparationMs: 1, + retainedCurrentnessCount: action === "recovered" ? 4 : 3, + fullCurrentnessCount: 1, + preparedAuthorityInspectionCount: 2, + result: "proved", + runtimeAction: action, + runtimeAuthorityMs: 1, + }); + expect( + Object.entries(evidence) + .filter(([key]) => key.endsWith("Ms")) + .every(([, value]) => typeof value === "number" && value >= 0), + ).toBe(true); + expect(JSON.stringify(evidence)).not.toContain("qwen3-vl"); + }, + ); - it("rejects registry drift before a runtime resume", () => { + it("rejects registry drift before a runtime resume", async () => { const harness = createHarness(); harness.input.readRegistry.mockReturnValue({ ...harness.input.entry, model: "changed" }); - expect(() => + await expect( recoverHermesPortableOllamaInference(harness.input, harness.overrides as never), - ).toThrow("sandbox registry authority changed before recovery"); + ).rejects.toThrow("sandbox registry authority changed before recovery"); expect(harness.prepareStartup).not.toHaveBeenCalled(); expect(harness.running()).toBe(false); }); - it("restores a started registry when runtime reconstruction fails before Ollama mutation", () => { + it("restores a started registry when runtime reconstruction fails before Ollama mutation", async () => { const harness = createHarness(); harness.overrides.createRuntimeAuthority.mockImplementation(() => { throw new Error("runtime authority unavailable"); @@ -1027,7 +1028,7 @@ describe("Hermes Portable Ollama inference recovery", () => { let caught: unknown; try { - recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); } catch (error) { caught = error; } @@ -1040,7 +1041,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.events).toContain("registry-rollback"); }); - it("keeps engine qualification distinct from registry recovery postconditions", () => { + it("keeps engine qualification distinct from registry recovery postconditions", async () => { const harness = createHarness(); harness.overrides.prepareRecoveryEntry.mockImplementation(() => { throw new HermesPortableOllamaRecoveryPhaseError("REGISTRY_PREPARATION_AUTHORITY"); @@ -1048,7 +1049,7 @@ describe("Hermes Portable Ollama inference recovery", () => { let caught: unknown; try { - recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); } catch (error) { caught = error; } @@ -1066,7 +1067,7 @@ describe("Hermes Portable Ollama inference recovery", () => { ["runtime-inspection", "EXACT_RUNTIME_INSPECTION", 1], ] as const)( "classifies the fixed %s failure boundary after rollback", - (owner, phase, registryRollbackCount) => { + async (owner, phase, registryRollbackCount) => { const harness = createHarness(); const canary = "nested recovery diagnostic canary"; const onComplete = vi.fn(); @@ -1110,7 +1111,7 @@ describe("Hermes Portable Ollama inference recovery", () => { let caught: unknown; try { - recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); } catch (error) { caught = error; } @@ -1162,7 +1163,7 @@ describe("Hermes Portable Ollama inference recovery", () => { expect((caught as Error).message).not.toContain("registry restoration canary"); }); - it("reports registry restoration uncertainty instead of the nested phase", () => { + it("reports registry restoration uncertainty instead of the nested phase", async () => { const harness = createHarness(); const canary = "nested recovery diagnostic canary"; harness.overrides.prepareRegistryRecovery.mockReturnValue({ @@ -1181,7 +1182,7 @@ describe("Hermes Portable Ollama inference recovery", () => { let caught: unknown; try { - recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); + await recoverHermesPortableOllamaInference(harness.input, harness.overrides as never); } catch (error) { caught = error; } @@ -1191,15 +1192,15 @@ describe("Hermes Portable Ollama inference recovery", () => { expect(harness.prepareStartup).not.toHaveBeenCalled(); }); - it("rejects direct launch intent before registry or runtime mutation", () => { + it("rejects direct launch intent before registry or runtime mutation", async () => { const harness = createHarness(); - expect(() => + await expect( recoverHermesPortableOllamaInference( { ...harness.input, intent: "launch" } as never, harness.overrides as never, ), - ).toThrow("restricted to connect --probe-only"); + ).rejects.toThrow("restricted to connect --probe-only"); expect(harness.overrides.prepareRegistryRecovery).not.toHaveBeenCalled(); expect(harness.prepareStartup).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/machine/core-flow-phases.test.ts b/src/lib/onboard/machine/core-flow-phases.test.ts index 1b87c518967..cf952760063 100644 --- a/src/lib/onboard/machine/core-flow-phases.test.ts +++ b/src/lib/onboard/machine/core-flow-phases.test.ts @@ -247,7 +247,7 @@ function createPhases( messagingChannelConfigsEqual: () => true, getSandboxReuseState: () => "missing", getSandboxRecreateObservation: () => ({ state: "missing", liveIdentityFingerprint: null }), - getDcodeSelectionDrift: () => ({ changed: false, unknown: false }), + getDcodeSelectionDrift: async () => ({ changed: false, unknown: false }), hasSandboxGpuDrift: () => false, getSandboxHermesToolGateways: () => [], getSandboxRegistryEntry, diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index 6e9c740615c..83d9dc9eaaf 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -677,12 +677,12 @@ describe("finalizationHandlerDeps.waitForSandboxControlPlaneReady", () => { vi.unstubAllEnvs(); }); - it("delegates timeout selection to the recovery readiness helper", () => { + it("delegates timeout selection to the recovery readiness helper", async () => { vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", "75"); vi.stubEnv("NEMOCLAW_SANDBOX_READY_TIMEOUT", "180"); let effectiveTimeoutSeconds: number | undefined; const waitForRecreatedSandboxOpenShellReady = vi.fn( - (_name: string, options: { timeoutSeconds?: number } = {}) => { + async (_name: string, options: { timeoutSeconds?: number } = {}) => { const requestedTimeoutSeconds = options.timeoutSeconds ?? 120; effectiveTimeoutSeconds = Number( process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS ?? requestedTimeoutSeconds, @@ -695,7 +695,9 @@ describe("finalizationHandlerDeps.waitForSandboxControlPlaneReady", () => { waitForRecreatedSandboxOpenShellReady, }); - expect(finalizationHandlerDeps.waitForSandboxControlPlaneReady("policy-box")).toBe(true); + await expect( + finalizationHandlerDeps.waitForSandboxControlPlaneReady("policy-box"), + ).resolves.toBe(true); expect(waitForRecreatedSandboxOpenShellReady).toHaveBeenCalledWith("policy-box"); expect(effectiveTimeoutSeconds).toBe(75); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index dd4cb214e3d..b158e92016c 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -351,14 +351,14 @@ export function ordinaryOpenClawPairingIncompleteMessage( } export const finalizationHandlerDeps = { - waitForSandboxControlPlaneReady(name: string): boolean { + async waitForSandboxControlPlaneReady(name: string): Promise { return finalizationHandlerRuntime .loadProcessRecovery() .waitForRecreatedSandboxOpenShellReady(name); }, - checkAndRecoverSandboxProcesses(name: string, options: { quiet: boolean }): void { + async checkAndRecoverSandboxProcesses(name: string, options: { quiet: boolean }): Promise { const processRecovery = finalizationHandlerRuntime.loadProcessRecovery(); - processRecovery.checkAndRecoverSandboxProcesses(name, options); + await processRecovery.checkAndRecoverSandboxProcesses(name, options); }, settleOrdinaryOpenClawPairing(name: string): Promise { return settleOrdinaryOpenClawPairing(name, defaultPairingSettlementDeps()); diff --git a/src/lib/onboard/machine/handlers/finalization.test.ts b/src/lib/onboard/machine/handlers/finalization.test.ts index 1cda42ee1a4..41a1b9b68ed 100644 --- a/src/lib/onboard/machine/handlers/finalization.test.ts +++ b/src/lib/onboard/machine/handlers/finalization.test.ts @@ -31,7 +31,7 @@ function createDeps( setDefaultSandbox: vi.fn(), removeLegacy: vi.fn(), cleanupHost: vi.fn(), - recoverProcesses: vi.fn(), + recoverProcesses: vi.fn(async () => undefined), settleOrdinaryPairing: vi.fn(async () => ({ kind: "settled" as const })), ordinaryPairingIncompleteMessage: vi.fn( () => "OpenClaw onboarding is incomplete; resume onboarding.", @@ -45,7 +45,7 @@ function createDeps( buildChain: vi.fn(() => ({ port: 18789 })), verify: vi.fn(async () => ({ ok: true })), diagnostics: vi.fn(() => [" ✓ verified"]), - verifyWebSearch: vi.fn(() => true), + verifyWebSearch: vi.fn(async () => true), dashboard: vi.fn(), isHealthy: vi.fn(() => true), reportReadiness: vi.fn(), @@ -300,7 +300,7 @@ describe("finalization handlers", () => { it("relies on process recovery to restore the default OpenClaw dashboard forward", async () => { let forwardLive = false; - const recoverProcesses = vi.fn(() => { + const recoverProcesses = vi.fn(async () => { forwardLive = true; }); const verify = vi.fn(async () => ({ ok: forwardLive })); @@ -468,7 +468,7 @@ describe("finalization handlers", () => { it("does not complete when web-search credentials are exposed in the sandbox (#7425)", async () => { const { deps, calls } = createDeps({ - verifyWebSearchInsideSandbox: vi.fn(() => false), + verifyWebSearchInsideSandbox: vi.fn(async () => false), }); const agent = { name: "openclaw" }; diff --git a/src/lib/onboard/machine/handlers/finalization.ts b/src/lib/onboard/machine/handlers/finalization.ts index aebbe5f375b..ba248c6731c 100644 --- a/src/lib/onboard/machine/handlers/finalization.ts +++ b/src/lib/onboard/machine/handlers/finalization.ts @@ -41,7 +41,10 @@ export interface FinalizationStateOptions; removeLegacyCredentialsFile(): void; cleanupStaleHostFiles(): void; - checkAndRecoverSandboxProcesses(sandboxName: string, options: { quiet: boolean }): void; + checkAndRecoverSandboxProcesses( + sandboxName: string, + options: { quiet: boolean }, + ): Promise; settleOrdinaryOpenClawPairing( sandboxName: string, ): Promise; @@ -81,7 +84,7 @@ export interface FinalizationStateOptions; printDashboard( sandboxName: string, model: string, @@ -206,7 +209,7 @@ export async function handleFinalizationState; error(message?: string): void; exitProcess(code: number): never; } @@ -82,14 +82,14 @@ export function preserveManagedDcodeRegistryEntry( return { ...decision, removeRegistryEntry: false }; } -export function resolveSignals( +export async function resolveSignals( options: ResumeOptions, state: ResumeState, sandboxReuseState: string, registryEntry: SandboxEntry | null, dcodeAutoApprovalMode: DcodeAutoApprovalMode, deps: Deps, -): { inferenceSelectionChanged: boolean; dcodeAutoApprovalChanged: boolean } { +): Promise<{ inferenceSelectionChanged: boolean; dcodeAutoApprovalChanged: boolean }> { const sandboxName = state.sandboxName; const dcodeAutoApprovalChanged = hasDcodeAutoApprovalDrift({ liveExists: sandboxReuseState === "ready", @@ -113,7 +113,7 @@ export function resolveSignals( ); return deps.exitProcess(1); } - const drift = deps.getDcodeSelectionDrift( + const drift = await deps.getDcodeSelectionDrift( sandboxName, options.provider, options.model, diff --git a/src/lib/onboard/machine/handlers/sandbox-dcode-selection.test.ts b/src/lib/onboard/machine/handlers/sandbox-dcode-selection.test.ts index 7dd69a07340..38ec1939d6b 100644 --- a/src/lib/onboard/machine/handlers/sandbox-dcode-selection.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-dcode-selection.test.ts @@ -195,7 +195,7 @@ describe("handleSandboxState live DCode selection", () => { ["changed", { changed: true, unknown: false }], ["unreadable", { changed: false, unknown: true }], ])("recreates a ready sandbox when live selection is %s (#6311)", async (_label, drift) => { - const getDcodeSelectionDrift = vi.fn(() => drift); + const getDcodeSelectionDrift = vi.fn(async () => drift); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", getDcodeSelectionDrift, @@ -226,7 +226,7 @@ describe("handleSandboxState live DCode selection", () => { it("preserves registry fidelity when GPU drift recreates managed DCode (#6311)", async () => { const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", - getDcodeSelectionDrift: () => ({ changed: false, unknown: false }), + getDcodeSelectionDrift: async () => ({ changed: false, unknown: false }), hasSandboxGpuDrift: () => true, getSandboxRegistryEntry: (name) => dcodeRegistryEntry(name), }); @@ -246,7 +246,7 @@ describe("handleSandboxState live DCode selection", () => { }); it("reuses a ready sandbox only after the live selection is verified (#6311)", async () => { - const getDcodeSelectionDrift = vi.fn(() => ({ changed: false, unknown: false })); + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: false, unknown: false })); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", getDcodeSelectionDrift, @@ -262,7 +262,7 @@ describe("handleSandboxState live DCode selection", () => { it("reuses a ready OpenRouter-compatible sandbox after endpoint-aware verification (#9555)", async () => { const endpointUrl = "https://openrouter.ai/api/v1/"; - const getDcodeSelectionDrift = vi.fn(() => ({ changed: false, unknown: false })); + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: false, unknown: false })); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", getDcodeSelectionDrift, @@ -292,7 +292,7 @@ describe("handleSandboxState live DCode selection", () => { }); it("refuses managed DCode reuse when the registry record is missing (#6311)", async () => { - const getDcodeSelectionDrift = vi.fn(() => ({ changed: false, unknown: false })); + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: false, unknown: false })); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", getDcodeSelectionDrift, @@ -316,7 +316,7 @@ describe("handleSandboxState live DCode selection", () => { pendingRouteReservation: true, reservationSessionId: session.sessionId, }; - const getDcodeSelectionDrift = vi.fn(() => ({ changed: true, unknown: true })); + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: true, unknown: true })); const finalizeSandboxRouteReservation = vi.fn((name: string, sessionId: string) => { expect(name).toBe(registryEntry.name); expect(sessionId).toBe(registryEntry.reservationSessionId); @@ -349,7 +349,7 @@ describe("handleSandboxState live DCode selection", () => { }); it("fails closed for missing registry selection before live reuse (#6311)", async () => { - const getDcodeSelectionDrift = vi.fn(() => ({ changed: false, unknown: false })); + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: false, unknown: false })); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", getDcodeSelectionDrift, @@ -369,12 +369,10 @@ describe("handleSandboxState live DCode selection", () => { pendingRouteReservation: true, reservationSessionId: session.sessionId, }; - const getDcodeSelectionDrift = vi.fn(() => ({ changed: false, unknown: false })); - const updateSandboxRegistry = vi.fn( - (_name: string, updates: Record) => { - Object.assign(registryEntry, updates); - }, - ); + const getDcodeSelectionDrift = vi.fn(async () => ({ changed: false, unknown: false })); + const updateSandboxRegistry = vi.fn((_name: string, updates: Record) => { + Object.assign(registryEntry, updates); + }); const finalizeSandboxRouteReservation = vi.fn((name: string, sessionId: string) => { expect(name).toBe(registryEntry.name); expect(sessionId).toBe(registryEntry.reservationSessionId); diff --git a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts index 8b1bba05661..eefcbe6b8cc 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -283,7 +283,7 @@ export function createDeps( getSandboxReuseState: () => "missing", getSandboxRecreateObservation: () => ({ state: "missing", liveIdentityFingerprint: null }) as const, - getDcodeSelectionDrift: () => ({ changed: false, unknown: false }), + getDcodeSelectionDrift: async () => ({ changed: false, unknown: false }), hasSandboxGpuDrift: () => false, getSandboxHermesToolGateways: () => [], getSandboxRegistryEntry: (name: string) => ({ diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 98a68a72b79..baf05d66277 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -761,7 +761,7 @@ class SandboxStateFlow< : { source: "none" as const, plan: null }; const toolDisclosureSignals = resolveToolDisclosureResumeSignals(registryEntry, state.session); const sandboxReuseState = this.deps.getSandboxReuseState(state.sandboxName); - const dcodeResumeSignals = dcodeResume.resolveSignals( + const dcodeResumeSignals = await dcodeResume.resolveSignals( this.options, state, sandboxReuseState, diff --git a/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts b/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts index 7097aee35ff..f9056ffb108 100644 --- a/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { enforceManagedBootstrapRecoveryForSandbox, ManagedBootstrapRecoveryBlockedError, @@ -17,12 +18,42 @@ import { authority, type DockerFixtureOptions, durablePreparation, - fixture, + fixture as createFixture, IDENTITY, NEW_ID, OLD_ID, } from "./docker-test-fixture"; +function commandExecutorThrough( + fake: ReturnType, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async (request) => { + const result = fake.deps.runOpenshell?.( + ["sandbox", "exec", "-n", request.sandboxName, "--", ...request.command], + { ignoreError: true, suppressOutput: true }, + ); + return { + outcome: + result?.status == null + ? { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + } + : { kind: "completed" as const, exitCode: result.status }, + stdout: String(result?.stdout ?? ""), + stderr: String(result?.stderr ?? ""), + }; + }), + }; +} + +function fixture(options?: Parameters[0]) { + const fake = createFixture(options); + fake.deps.commandExecutor = commandExecutorThrough(fake); + return fake; +} + async function prepareTransaction( fake: ReturnType, agent: Parameters[0] = "hermes", @@ -131,76 +162,76 @@ describe("Docker managed bootstrap restart recovery", () => { readonly label: string; readonly options: DockerFixtureOptions; readonly phase: "cutover" | "staged"; - }[])("retains owner cleanup after a process restart from the durable $label phase", async ({ - options, - phase, - }) => { - const fake = fixture(options); - const transaction = await prepareTransaction(fake); - - await expect( - transaction.adapter.activateBootstrapReplacement({ - handle: transaction.handle, - snapshot: transaction.snapshot, - prepared: transaction.prepared, - durablePreparation: transaction.durable, - }), - ).rejects.toThrow(`crash after durable ${phase} fence`); - expect(fake.journal?.phase).toBe(phase); - - const restarted = createDockerManagedBootstrapAdapter(fake.deps); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ - receipts: [], - failures: [ - { - bootstrapIdentity: IDENTITY, - sourcePhase: "owner-cleanup-required", - code: "owner-cleanup-required", - blockingScope: "sandbox", - retryable: true, - }, - ], - }); - expect(fake.journal?.phase).toBe("owner-cleanup-required"); - expect(fake.finalization).toBeNull(); - expect(fake.replacement).toBeNull(); - expect(fake.original?.State?.Running).toBe(false); - expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); - - const ownerTransitions = fake.events.filter( - (event) => event === "journal:owner-cleanup-required", - ).length; - const mutationsAfterFirstRecovery = dockerMutationEvents(fake.events); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ - receipts: [], - failures: [{ code: "owner-cleanup-required" }], - }); - expect(fake.events.filter((event) => event === "journal:owner-cleanup-required")).toHaveLength( - ownerTransitions, - ); - expect(fake.journal?.phase).toBe("owner-cleanup-required"); - expect(fake.finalization).toBeNull(); - expect(dockerMutationEvents(fake.events)).toEqual(mutationsAfterFirstRecovery); - - fake.removeOriginalExternally(); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ - receipts: [ - { - bootstrapIdentity: IDENTITY, - sourcePhase: "owner-cleanup-required", - outcome: "rolled-back", - }, - ], - failures: [], - }); - expect(fake.journal).toBeNull(); - expect(fake.finalization?.phase).toBe("rolled-back"); - expect(fake.replacement).toBeNull(); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toEqual({ - receipts: [], - failures: [], - }); - }); + }[])( + "retains owner cleanup after a process restart from the durable $label phase", + async ({ options, phase }) => { + const fake = fixture(options); + const transaction = await prepareTransaction(fake); + + await expect( + transaction.adapter.activateBootstrapReplacement({ + handle: transaction.handle, + snapshot: transaction.snapshot, + prepared: transaction.prepared, + durablePreparation: transaction.durable, + }), + ).rejects.toThrow(`crash after durable ${phase} fence`); + expect(fake.journal?.phase).toBe(phase); + + const restarted = createDockerManagedBootstrapAdapter(fake.deps); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [ + { + bootstrapIdentity: IDENTITY, + sourcePhase: "owner-cleanup-required", + code: "owner-cleanup-required", + blockingScope: "sandbox", + retryable: true, + }, + ], + }); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + expect(fake.replacement).toBeNull(); + expect(fake.original?.State?.Running).toBe(false); + expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); + + const ownerTransitions = fake.events.filter( + (event) => event === "journal:owner-cleanup-required", + ).length; + const mutationsAfterFirstRecovery = dockerMutationEvents(fake.events); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [{ code: "owner-cleanup-required" }], + }); + expect( + fake.events.filter((event) => event === "journal:owner-cleanup-required"), + ).toHaveLength(ownerTransitions); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + expect(dockerMutationEvents(fake.events)).toEqual(mutationsAfterFirstRecovery); + + fake.removeOriginalExternally(); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [ + { + bootstrapIdentity: IDENTITY, + sourcePhase: "owner-cleanup-required", + outcome: "rolled-back", + }, + ], + failures: [], + }); + expect(fake.journal).toBeNull(); + expect(fake.finalization?.phase).toBe("rolled-back"); + expect(fake.replacement).toBeNull(); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toEqual({ + receipts: [], + failures: [], + }); + }, + ); it("publishes owner cleanup only after shared rollback, replacement cleanup, and restoration", async () => { const fake = fixture({ diff --git a/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts b/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts index 48a3ddf9ee2..a0c0a290dd1 100644 --- a/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { streamSandboxCreate } from "../../sandbox/create-stream"; import { dockerEnv, @@ -86,6 +87,16 @@ import type { ManagedBootstrapRuntimeCreateLifecycleInput } from "./runtime-crea const temporaryStateRoots: string[] = []; +function successfulCommandExecutor(): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }; +} + function compatibilityLifecycleInput( seed: ReturnType, dependencies: ManagedBootstrapRuntimeCreateLifecycleInput["dependencies"] & DockerGpuPatchDeps, @@ -136,7 +147,7 @@ function compatibilityLifecycleInput( gatewayPort: 8080, reverifyBridgeReachability: vi.fn(), }, - dependencies, + dependencies: { commandExecutor: successfulCommandExecutor(), ...dependencies }, }; } @@ -173,6 +184,7 @@ function gpuModeDependencies() { return { dockerRun, dependencies: { + commandExecutor: successfulCommandExecutor(), dockerCapture: vi.fn(() => ""), dockerRun, dockerRm: vi.fn(() => ({ status: 0 })), @@ -561,7 +573,7 @@ describe("Docker managed-bootstrap lifecycle composition", () => { gatewayPort: 0, reverifyBridgeReachability: () => undefined, }, - dependencies: {}, + dependencies: { commandExecutor: successfulCommandExecutor() }, }); const child = new FakeChild(); let ready = false; @@ -668,7 +680,7 @@ describe("Docker managed-bootstrap lifecycle composition", () => { gatewayPort: 0, reverifyBridgeReachability: () => undefined, }, - dependencies: {}, + dependencies: { commandExecutor: successfulCommandExecutor() }, }); await expect( diff --git a/src/lib/onboard/managed-bootstrap/docker-runtime.ts b/src/lib/onboard/managed-bootstrap/docker-runtime.ts index 6abdc929f13..ad33b79bc9e 100644 --- a/src/lib/onboard/managed-bootstrap/docker-runtime.ts +++ b/src/lib/onboard/managed-bootstrap/docker-runtime.ts @@ -213,6 +213,10 @@ function createDockerLifecycle( const backend = input.sandboxGpuConfig.hostGpuPlatform === "jetson" ? "jetson" : "generic"; const persistStartupCommand = input.persistStartupCommand && (input.route !== "native" || input.requiredLimits.length > 0); + const commandExecutor = input.dependencies.commandExecutor; + if (!commandExecutor) { + throw new Error("Docker managed bootstrap requires a buffered sandbox command executor."); + } const patch = createDockerGpuSandboxCreatePatch({ route: input.route, persistStartupCommand, @@ -224,7 +228,7 @@ function createDockerLifecycle( timeoutSecs: input.timeoutSecs, backend, dockerDesktopWsl, - deps: input.dependencies, + deps: { ...input.dependencies, commandExecutor }, ...(input.onPatchFailure ? { overrides: { diff --git a/src/lib/onboard/managed-bootstrap/docker.test.ts b/src/lib/onboard/managed-bootstrap/docker.test.ts index 2f51469ce35..2e25a5879aa 100644 --- a/src/lib/onboard/managed-bootstrap/docker.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker.test.ts @@ -3,6 +3,7 @@ import { assert, describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { MANAGED_BOOTSTRAP_IDENTITY_ENV, ManagedBootstrapDurableCommitCleanupPendingError, @@ -17,7 +18,7 @@ import { authority, completion, durablePreparation, - fixture, + fixture as createFixture, heldArgv, IDENTITY, NEW_ID, @@ -26,6 +27,36 @@ import { SUPPORTED_AGENTS, } from "./docker-test-fixture"; +function commandExecutorThrough( + fake: ReturnType, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async (request) => { + const result = fake.deps.runOpenshell?.( + ["sandbox", "exec", "-n", request.sandboxName, "--", ...request.command], + { ignoreError: true, suppressOutput: true }, + ); + return { + outcome: + result?.status == null + ? { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + } + : { kind: "completed" as const, exitCode: result.status }, + stdout: String(result?.stdout ?? ""), + stderr: String(result?.stderr ?? ""), + }; + }), + }; +} + +function fixture(options?: Parameters[0]) { + const fake = createFixture(options); + fake.deps.commandExecutor = commandExecutorThrough(fake); + return fake; +} + function expectEventBefore(events: readonly string[], before: string, after: string): void { expect(events).toContain(before); expect(events).toContain(after); diff --git a/src/lib/onboard/managed-bootstrap/docker.ts b/src/lib/onboard/managed-bootstrap/docker.ts index 8c281feb18c..f5f8f38cfc1 100644 --- a/src/lib/onboard/managed-bootstrap/docker.ts +++ b/src/lib/onboard/managed-bootstrap/docker.ts @@ -191,6 +191,7 @@ export type DockerManagedBootstrapDeps = Pick< | "dockerRun" | "dockerStart" | "dockerStop" + | "commandExecutor" | "runCaptureOpenshell" | "runOpenshell" | "sleep" @@ -3857,11 +3858,17 @@ export function createDockerManagedBootstrapAdapter( const supervisorReconnectTimeoutSecs = getDockerGpuSupervisorReconnectTimeoutSecs(timeoutSecs); if ( - !waitForOpenShellSupervisorReconnect( + !deps.commandExecutor || + !(await waitForOpenShellSupervisorReconnect( handle.sandbox.sandboxName, supervisorReconnectTimeoutSecs, - deps, - ) + { + commandExecutor: deps.commandExecutor, + runCaptureOpenshell: deps.runCaptureOpenshell, + sleep: deps.sleep, + errorPhaseDebouncePolls: deps.errorPhaseDebouncePolls, + }, + )) ) { throw new Error(supervisorReconnectFailureDetail(replacement.replacementRuntimeId, deps)); } diff --git a/src/lib/onboard/managed-bootstrap/runtime-create.ts b/src/lib/onboard/managed-bootstrap/runtime-create.ts index fb08faa9eb1..127fd57bb1f 100644 --- a/src/lib/onboard/managed-bootstrap/runtime-create.ts +++ b/src/lib/onboard/managed-bootstrap/runtime-create.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxGpuProofResult } from "../../state/registry"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import type { ManagedStartupRootApplyRequest } from "../managed-startup/root-apply"; import type { ManagedStartupStateRoot, @@ -25,6 +26,7 @@ export interface ManagedBootstrapRuntimeCommandResult { } export interface ManagedBootstrapRuntimeDependencies { + readonly commandExecutor?: OpenShellSandboxBufferedCommandExecutor; readonly runCaptureOpenshell?: (args: string[], options?: Record) => string; readonly runOpenshell?: ( args: string[], diff --git a/src/lib/onboard/openclaw-setup.test.ts b/src/lib/onboard/openclaw-setup.test.ts index 41b0c877da1..2ccc5018ac3 100644 --- a/src/lib/onboard/openclaw-setup.test.ts +++ b/src/lib/onboard/openclaw-setup.test.ts @@ -9,8 +9,12 @@ import { } from "./openclaw-setup"; describe("OpenClaw sandbox setup", () => { - it("shares config sync before web-search reconciliation", async () => { - const syncNemoClawConfigInSandbox = vi.fn(); + it("waits for config sync before web-search reconciliation", async () => { + let finishConfigSync!: () => void; + const configSync = new Promise((resolve) => { + finishConfigSync = resolve; + }); + const syncNemoClawConfigInSandbox = vi.fn(() => configSync); const reconcileWebSearch = vi.fn(async () => undefined); const revalidateSandboxIdentity = vi.fn(); const configureOpenclawSandbox = createConfigureOpenclawSandbox({ @@ -18,7 +22,7 @@ describe("OpenClaw sandbox setup", () => { reconcileWebSearch, }); - await configureOpenclawSandbox( + const configuring = configureOpenclawSandbox( "spark-box", "model", "provider", @@ -32,14 +36,33 @@ describe("OpenClaw sandbox setup", () => { "model", revalidateSandboxIdentity, ); + expect(reconcileWebSearch).not.toHaveBeenCalled(); + + finishConfigSync(); + await configuring; + expect(reconcileWebSearch).toHaveBeenCalledExactlyOnceWith( "spark-box", null, revalidateSandboxIdentity, ); - expect(syncNemoClawConfigInSandbox.mock.invocationCallOrder[0]).toBeLessThan( - reconcileWebSearch.mock.invocationCallOrder[0]!, - ); + }); + + it("propagates config sync failure before web-search reconciliation", async () => { + const syncNemoClawConfigInSandbox = vi.fn(async () => { + throw new Error("config sync failed"); + }); + const reconcileWebSearch = vi.fn(async () => undefined); + const configureOpenclawSandbox = createConfigureOpenclawSandbox({ + syncNemoClawConfigInSandbox, + reconcileWebSearch, + }); + + await expect( + configureOpenclawSandbox("spark-box", "model", "provider", null), + ).rejects.toThrow("config sync failed"); + + expect(reconcileWebSearch).not.toHaveBeenCalled(); }); it("delegates fresh setup to shared OpenClaw configuration", async () => { diff --git a/src/lib/onboard/openclaw-setup.ts b/src/lib/onboard/openclaw-setup.ts index 75f985ed11c..7e970c0f3c2 100644 --- a/src/lib/onboard/openclaw-setup.ts +++ b/src/lib/onboard/openclaw-setup.ts @@ -56,7 +56,7 @@ export interface ConfigureOpenclawSandboxDeps { provider: string, model: string, revalidateSandboxIdentity?: (operation: string) => void, - ): void; + ): Promise; reconcileWebSearch( sandboxName: string, webSearchConfig: WebSearchSelection, @@ -72,7 +72,12 @@ export function createConfigureOpenclawSandbox(deps: ConfigureOpenclawSandboxDep webSearchConfig: WebSearchSelection, revalidateSandboxIdentity?: (operation: string) => void, ): Promise { - deps.syncNemoClawConfigInSandbox(sandboxName, provider, model, revalidateSandboxIdentity); + await deps.syncNemoClawConfigInSandbox( + sandboxName, + provider, + model, + revalidateSandboxIdentity, + ); await deps.reconcileWebSearch(sandboxName, webSearchConfig, revalidateSandboxIdentity); }; } diff --git a/src/lib/onboard/policy-selection-application.test.ts b/src/lib/onboard/policy-selection-application.test.ts index 975dfde9037..d31e717d8ca 100644 --- a/src/lib/onboard/policy-selection-application.test.ts +++ b/src/lib/onboard/policy-selection-application.test.ts @@ -61,7 +61,7 @@ describe("onboarding policy application", () => { reason: "ready" as const, error: null, })), - waitForSandboxControlPlaneReady: vi.fn(() => true), + waitForSandboxControlPlaneReady: vi.fn(async () => true), parsePolicyPresetEnv: vi.fn(() => []), env: {}, }); @@ -109,7 +109,7 @@ describe("onboarding policy application", () => { reason: "ready" as const, error: null, })), - waitForSandboxControlPlaneReady: vi.fn(() => true), + waitForSandboxControlPlaneReady: vi.fn(async () => true), parsePolicyPresetEnv: vi.fn((value: string) => value .split(",") diff --git a/src/lib/onboard/policy-selection-host-local-route.test.ts b/src/lib/onboard/policy-selection-host-local-route.test.ts index 3c9ef3c06e3..af36d0dc8dd 100644 --- a/src/lib/onboard/policy-selection-host-local-route.test.ts +++ b/src/lib/onboard/policy-selection-host-local-route.test.ts @@ -37,7 +37,7 @@ function createHarness() { reason: "ready" as const, error: null, })), - waitForSandboxControlPlaneReady: vi.fn(() => true), + waitForSandboxControlPlaneReady: vi.fn(async () => true), syncPresetSelection, selectPolicyTier: vi.fn(async () => "balanced"), selectTierPresetsAndAccess: vi.fn( @@ -111,9 +111,7 @@ describe("host-local route-only policy selection", () => { const policyChecks = new Map([ ["apply policy presets to sandbox 'alpha'", refusePresetMutation], ]); - const revalidateSandboxIdentity = vi.fn((operation: string) => - policyChecks.get(operation)?.(), - ); + const revalidateSandboxIdentity = vi.fn((operation: string) => policyChecks.get(operation)?.()); await expect( setupPoliciesWithSelection(deps, "alpha", { diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index a298e442733..c3a9dc3a285 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -65,7 +65,7 @@ export type OnboardPolicyApplicationDeps = Omit< localInferenceProviders: readonly string[]; withSandboxMutationLock: typeof import("../state/mcp-lifecycle-lock").withSandboxMutationLock; waitForSandboxReady(sandboxName: string): Promise; - waitForSandboxControlPlaneReady(sandboxName: string): boolean; + waitForSandboxControlPlaneReady(sandboxName: string): Promise; parsePolicyPresetEnv(raw: string): string[]; env: NodeJS.ProcessEnv; }; @@ -131,7 +131,7 @@ export type SetupPolicySelectionDeps = { note: (message: string) => void; isNonInteractive: () => boolean; waitForSandboxReady: (sandboxName: string) => Promise; - waitForSandboxControlPlaneReady: (sandboxName: string) => boolean; + waitForSandboxControlPlaneReady: (sandboxName: string) => Promise; syncPresetSelection: ( sandboxName: string, currentAppliedPresets: string[], @@ -360,7 +360,7 @@ async function requireSandboxReady( console.error(` Sandbox '${sandboxName}' was not ready ${stage} policy application.`); process.exit(1); } - if (stage === "after" && !deps.waitForSandboxControlPlaneReady(sandboxName)) { + if (stage === "after" && !(await deps.waitForSandboxControlPlaneReady(sandboxName))) { console.error( ` Sandbox '${sandboxName}' did not re-register with OpenShell after policy application.`, ); diff --git a/src/lib/onboard/runtime-provider/podman.test.ts b/src/lib/onboard/runtime-provider/podman.test.ts index e34d1f647f4..5919ccac20e 100644 --- a/src/lib/onboard/runtime-provider/podman.test.ts +++ b/src/lib/onboard/runtime-provider/podman.test.ts @@ -270,7 +270,7 @@ describe("managed Podman runtime provider", () => { async (agent) => { const runtime = providerHarness(agent); const verifyGateway = vi.fn(async () => undefined); - const restoreStartupState = vi.fn(() => SUCCESSFUL_RECOVERY); + const restoreStartupState = vi.fn(async () => SUCCESSFUL_RECOVERY); const stopSandboxChannels = vi.fn(); await expect( @@ -313,7 +313,7 @@ describe("managed Podman runtime provider", () => { startSandbox(runtime.sandboxName, { getSandbox: () => runtime.entry, runtimeProviders: runtime.providers, - restoreStartupState: vi.fn(() => SUCCESSFUL_RECOVERY), + restoreStartupState: vi.fn(async () => SUCCESSFUL_RECOVERY), verifyGateway, log: vi.fn(), }), diff --git a/src/lib/onboard/sandbox-create-step.ts b/src/lib/onboard/sandbox-create-step.ts index 0cef3edfc7a..0042fa08acd 100644 --- a/src/lib/onboard/sandbox-create-step.ts +++ b/src/lib/onboard/sandbox-create-step.ts @@ -51,6 +51,7 @@ export type SandboxCreateStepDeps = { addTraceEvent: NonNullable; runOpenshell: GpuPatchDeps["runOpenshell"]; runCaptureOpenshell: NonNullable; + commandExecutor: NonNullable; sleepSeconds: GpuPatchDeps["sleep"]; }; @@ -113,6 +114,7 @@ export async function runSandboxCreateStep( deps: { runOpenshell: deps.runOpenshell, runCaptureOpenshell: deps.runCaptureOpenshell, + commandExecutor: deps.commandExecutor, sleep: deps.sleepSeconds, }, }); diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index 47202416d6f..3de1d8733cf 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -47,7 +47,9 @@ describe("created Hermes credential environment reconciliation", () => { events.push("registration:complete"); return { sandboxName: "alpha" }; }, - () => events.push("credentials:reconcile"), + async () => { + events.push("credentials:reconcile"); + }, ); expect(events).toEqual([ @@ -57,11 +59,11 @@ describe("created Hermes credential environment reconciliation", () => { ]); }); - it("restarts and rechecks the managed gateway after changing the env file", () => { + it("restarts and rechecks the managed gateway after changing the env file", async () => { const events: string[] = []; const restart = { status: 0, stdout: "managed completion", stderr: "" }; - reconcileCreatedHermesCredentialEnvironment( + await reconcileCreatedHermesCredentialEnvironment( { sandboxName: "alpha", plan }, { revalidateSandboxIdentity: (operation) => events.push(`identity:${operation}`), @@ -77,7 +79,7 @@ describe("created Hermes credential environment reconciliation", () => { events.push("parse"); return result === restart ? {} : null; }, - waitForGateway: () => { + waitForGateway: async () => { events.push("wait"); return true; }, @@ -96,11 +98,11 @@ describe("created Hermes credential environment reconciliation", () => { ]); }); - it("does not restart when the env file was already reconciled", () => { + it("does not restart when the env file was already reconciled", async () => { const restartGateway = vi.fn(); const waitForGateway = vi.fn(); - reconcileCreatedHermesCredentialEnvironment( + await reconcileCreatedHermesCredentialEnvironment( { sandboxName: "alpha", plan }, { revalidateSandboxIdentity: vi.fn(), @@ -116,7 +118,7 @@ describe("created Hermes credential environment reconciliation", () => { expect(waitForGateway).not.toHaveBeenCalled(); }); - it("refuses a same-name replacement at the credential mutation edge (#9833)", () => { + it("refuses a same-name replacement at the credential mutation edge (#9833)", async () => { const expectedIdentity = "identity-a"; let liveIdentity = expectedIdentity; const mutations: string[] = []; @@ -128,7 +130,7 @@ describe("created Hermes credential environment reconciliation", () => { liveIdentity = "identity-b"; }); - expect(() => + await expect( reconcileCreatedHermesCredentialEnvironment( { sandboxName: "alpha", plan }, { @@ -144,13 +146,13 @@ describe("created Hermes credential environment reconciliation", () => { }, vi.fn(), ), - ).toThrow(/sandbox identity changed/u); + ).rejects.toThrow(/sandbox identity changed/u); expect(mutations).toEqual([]); }); - it("fails onboarding when the changed gateway cannot prove restart completion", () => { + it("fails onboarding when the changed gateway cannot prove restart completion", async () => { const recordRecovery = vi.fn(); - expect(() => + await expect( reconcileCreatedHermesCredentialEnvironment( { sandboxName: "alpha", plan }, { @@ -162,7 +164,7 @@ describe("created Hermes credential environment reconciliation", () => { }, recordRecovery, ), - ).toThrow("managed gateway restart did not complete"); + ).rejects.toThrow("managed gateway restart did not complete"); expect(recordRecovery).toHaveBeenCalledOnce(); }); }); @@ -679,8 +681,8 @@ describe("sandbox recreate registry authority", () => { describe("managed DCode sandbox create selection", () => { it.each([null, "https://openrouter.ai/api/v1"])( "passes the selected endpoint to live drift validation: %s (#9555)", - (endpointUrl) => { - const readDcodeSelectionDrift = vi.fn(() => ({ + async (endpointUrl) => { + const readDcodeSelectionDrift = vi.fn(async () => ({ changed: false, providerChanged: false, modelChanged: false, @@ -689,7 +691,7 @@ describe("managed DCode sandbox create selection", () => { unknown: false, })); - readManagedDcodeCreateSelectionDrift( + await readManagedDcodeCreateSelectionDrift( { sandboxName: "saved", provider: "compatible-endpoint", diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index f7968402b41..d3677347d2a 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -811,7 +811,7 @@ export function finalizeRecreatedSourceHermesStateVolume( deps.removeSourceRegistryEntry(input.sourceEntry, input.sandboxName); } -export function readManagedDcodeCreateSelectionDrift( +export async function readManagedDcodeCreateSelectionDrift( input: { sandboxName: string; provider: string; @@ -821,7 +821,7 @@ export function readManagedDcodeCreateSelectionDrift( }, readDcodeSelectionDrift: DcodeSelectionDriftReader, ) { - return readDcodeSelectionDrift( + return await readDcodeSelectionDrift( input.sandboxName, input.provider, input.model, @@ -912,7 +912,7 @@ type CreatedHermesCredentialEnvReconciliationDeps = { readonly waitForGateway: ( sandboxName: string, revalidateSandboxIdentity: (operation: string) => void, - ) => boolean; + ) => Promise; readonly revalidateSandboxIdentity: (operation: string) => void; }; @@ -921,15 +921,15 @@ type CreatedHermesCredentialEnvReconciliationDeps = { * onboarding reports success. A changed env file is not effective until the * exact managed gateway supervisor restarts and passes its authenticated probe. */ -export function reconcileCreatedHermesCredentialEnvironment( +export async function reconcileCreatedHermesCredentialEnvironment( input: { readonly sandboxName: string; readonly plan: SandboxMessagingPlan | null; }, deps: CreatedHermesCredentialEnvReconciliationDeps, recordRecovery: () => void, -): void { - return runWithPostCreateRecovery(() => { +): Promise { + return runAsyncWithPostCreateRecovery(async () => { if (input.plan?.agent !== "hermes") return; deps.revalidateSandboxIdentity( @@ -947,7 +947,7 @@ export function reconcileCreatedHermesCredentialEnvironment( `Hermes messaging credential reconciliation changed the gateway environment for sandbox '${input.sandboxName}', but the managed gateway restart did not complete.`, ); } - if (!deps.waitForGateway(input.sandboxName, deps.revalidateSandboxIdentity)) { + if (!(await deps.waitForGateway(input.sandboxName, deps.revalidateSandboxIdentity))) { throw new Error( `Hermes messaging credential reconciliation restarted sandbox '${input.sandboxName}', but the managed gateway did not remain healthy.`, ); @@ -960,10 +960,10 @@ export function reconcileCreatedHermesCredentialEnvironment( export async function finalizeCreatedSandboxBeforeHermesCredentialReconciliation( completeRegistration: () => Promise, - reconcileCredentialEnvironment: () => void, + reconcileCredentialEnvironment: () => Promise, ): Promise { const registration = await completeRegistration(); - reconcileCredentialEnvironment(); + await reconcileCredentialEnvironment(); return registration; } @@ -1524,6 +1524,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche formatSandboxBuildEstimateNote, getDashboardForwardPort, readDcodeSelectionDrift, + sandboxCommandExecutor, getDefaultSandboxNameForAgent, getDockerDriverGatewayStateDir, getHermesToolGatewayBroker, @@ -2023,7 +2024,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche const needsProviderMigration = hasMessagingTokens && providerExistence.some(({ token, exists }) => token && !exists); const selectionDrift = isManagedDcodeAgent - ? readManagedDcodeCreateSelectionDrift( + ? await readManagedDcodeCreateSelectionDrift( { sandboxName, provider, model, preferredInferenceApi, createIntent }, readDcodeSelectionDrift, ) @@ -2966,6 +2967,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ...agentCreateInput, }, { + commandExecutor: sandboxCommandExecutor, runOpenshell: hermesPortableReadyRunner ?? runOpenshell, runCaptureOpenshell: hermesPortableReadyCapture ?? runCaptureOpenshell, sandboxObserver: createCliOpenShellSandboxObserverFromRunner( @@ -3066,6 +3068,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche managedWorkloadRuntime, preparedSandboxWorkload, note, + sandboxCommandExecutor, ); // Managed bootstrap can invalidate OpenShell's cached Ready state after it // replaces the container. Registry publication stays bound to the durable diff --git a/src/lib/onboard/sandbox-fresh-readiness.test.ts b/src/lib/onboard/sandbox-fresh-readiness.test.ts index 8d69ae3e89b..de5d62abd81 100644 --- a/src/lib/onboard/sandbox-fresh-readiness.test.ts +++ b/src/lib/onboard/sandbox-fresh-readiness.test.ts @@ -101,31 +101,31 @@ describe("fresh sandbox executable readiness", () => { vi.mocked(deps.runOpenshell).mockImplementation( createSequencedOpenShellRunner([ ["sandbox get -g nemoclaw alpha", [readySandboxGetResult(), readySandboxGetResult()]], - [ - "sandbox exec -g nemoclaw --name alpha -- true", - [ - { - status: 1, - stdout: "", - stderr: SANDBOX_NOT_READY_OUTPUT, - }, - { status: 0, stdout: "", stderr: "" }, - ], - ], ]), ); + vi.mocked(deps.commandExecutor.runBuffered) + .mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 1 }, + stdout: "", + stderr: SANDBOX_NOT_READY_OUTPUT, + }) + .mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 0 }, + stdout: "", + stderr: "", + }); await expect(runSandboxGpuCreateFlow(createInput(), deps)).resolves.toMatchObject({ route: "native", }); - expect( - vi - .mocked(deps.runOpenshell) - .mock.calls.filter( - ([args]) => args.join(" ") === "sandbox exec -g nemoclaw --name alpha -- true", - ), - ).toHaveLength(2); + expect(deps.commandExecutor.runBuffered).toHaveBeenCalledTimes(2); + expect(vi.mocked(deps.commandExecutor.runBuffered).mock.calls[0]?.[0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw" }, + command: ["true"], + timeoutKillSignal: "SIGKILL", + }); expect(deps.runOpenshell).not.toHaveBeenCalledWith( ["sandbox", "delete", "alpha"], expect.anything(), @@ -137,12 +137,13 @@ describe("fresh sandbox executable readiness", () => { vi.mocked(deps.runOpenshell).mockImplementation( createSequencedOpenShellRunner([ ["sandbox get -g nemoclaw alpha", [readySandboxGetResult()]], - [ - "sandbox exec -g nemoclaw --name alpha -- true", - [{ status: 1, stdout: "", stderr: "permission denied" }], - ], ]), ); + vi.mocked(deps.commandExecutor.runBuffered).mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 1 }, + stdout: "", + stderr: "permission denied", + }); mockExit(); await expect(runSandboxGpuCreateFlow(createInput(), deps)).rejects.toThrow("process.exit:1"); @@ -154,6 +155,7 @@ describe("fresh sandbox executable readiness", () => { expect(mocks.printSandboxCreateFailureDiagnostics).toHaveBeenCalledWith("alpha", { backupPath: null, }); + expect(deps.commandExecutor.runBuffered).toHaveBeenCalledTimes(1); }); it("preserves a fresh sandbox when sandbox get omits a durable ID (#9050)", async () => { @@ -170,10 +172,7 @@ describe("fresh sandbox executable readiness", () => { await expect(runSandboxGpuCreateFlow(createInput(), deps)).rejects.toThrow("process.exit:1"); - expect(deps.runOpenshell).not.toHaveBeenCalledWith( - ["sandbox", "exec", "-g", "nemoclaw", "--name", "alpha", "--", "true"], - expect.anything(), - ); + expect(deps.commandExecutor.runBuffered).not.toHaveBeenCalled(); expect(deps.runOpenshell).not.toHaveBeenCalledWith( ["sandbox", "delete", "alpha"], expect.anything(), @@ -197,10 +196,7 @@ describe("fresh sandbox executable readiness", () => { await expect(runSandboxGpuCreateFlow(createInput(), deps)).rejects.toThrow("process.exit:1"); - expect(deps.runOpenshell).not.toHaveBeenCalledWith( - ["sandbox", "exec", "-g", "nemoclaw", "--name", "alpha", "--", "true"], - expect.anything(), - ); + expect(deps.commandExecutor.runBuffered).not.toHaveBeenCalled(); expect(deps.runOpenshell).not.toHaveBeenCalledWith( ["sandbox", "delete", "alpha"], expect.anything(), @@ -214,12 +210,13 @@ describe("fresh sandbox executable readiness", () => { vi.mocked(deps.runOpenshell).mockImplementation( createSequencedOpenShellRunner([ ["sandbox get -g nemoclaw alpha", [readySandboxGetResult()]], - [ - ["sandbox", "exec", "-g", "nemoclaw", "--name", "alpha", "--", "true"].join(" "), - [timedOutOpenShellResult(SANDBOX_NOT_READY_OUTPUT)], - ], ]), ); + vi.mocked(deps.commandExecutor.runBuffered).mockResolvedValueOnce({ + outcome: { kind: "failed", error: { kind: "timeout", message: "spawn openshell timed out" } }, + stdout: "", + stderr: SANDBOX_NOT_READY_OUTPUT, + }); mockExit(); await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("process.exit:1"); @@ -227,17 +224,13 @@ describe("fresh sandbox executable readiness", () => { const identityOptions = vi .mocked(deps.runOpenshell) .mock.calls.find(([args]) => args.join(" ") === "sandbox get -g nemoclaw alpha")?.[1]; - const executableOptions = vi - .mocked(deps.runOpenshell) - .mock.calls.find( - ([args]) => args.join(" ") === "sandbox exec -g nemoclaw --name alpha -- true", - )?.[1]; + const executableOptions = vi.mocked(deps.commandExecutor.runBuffered).mock.calls[0]?.[0]; expect(identityOptions).toMatchObject({ killSignal: "SIGKILL" }); - expect(executableOptions).toMatchObject({ killSignal: "SIGKILL" }); + expect(executableOptions).toMatchObject({ timeoutKillSignal: "SIGKILL" }); expect(identityOptions?.timeout).toBeGreaterThan(0); expect(identityOptions?.timeout).toBeLessThanOrEqual(500); - expect(executableOptions?.timeout).toBeGreaterThan(0); - expect(executableOptions?.timeout).toBeLessThanOrEqual(500); + expect(executableOptions?.timeoutMilliseconds).toBeGreaterThan(0); + expect(executableOptions?.timeoutMilliseconds).toBeLessThanOrEqual(500); expect(deps.runOpenshell).not.toHaveBeenCalledWith( ["sandbox", "delete", "alpha"], expect.anything(), diff --git a/src/lib/onboard/sandbox-gpu-create-flow.test.ts b/src/lib/onboard/sandbox-gpu-create-flow.test.ts index 0519c45d5d6..dc10c26eff3 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.test.ts @@ -712,14 +712,15 @@ describe("runSandboxGpuCreateFlow native failure and readiness", () => { vi.mocked(deps.runOpenshell).mockImplementation( createSequencedOpenShellRunner([ ["sandbox get -g nemoclaw alpha", [readySandboxGetResult(), readySandboxGetResult()]], - [ - "sandbox exec -g nemoclaw --name alpha -- true", - [{ status: 1, stdout: "", stderr: "permission denied" }], - ], ]), ); - mocks.waitForCreatedSandboxReadyWithTrace.mockImplementationOnce((options) => { - expect(options.checkReadyIdentity?.()).toBe("probe_failed"); + vi.mocked(deps.commandExecutor.runBuffered).mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 1, signal: null }, + stdout: "", + stderr: "permission denied", + }); + mocks.waitForCreatedSandboxReadyWithTrace.mockImplementationOnce(async (options) => { + await expect(options.checkReadyIdentity?.()).resolves.toBe("probe_failed"); return { ready: false, reason: "identity_probe_failed", @@ -767,24 +768,24 @@ describe("runSandboxGpuCreateFlow native failure and readiness", () => { "sandbox get -g nemoclaw alpha", [readySandboxGetResult(), readySandboxGetResult(), readySandboxGetResult()], ], - [ - "sandbox exec -g nemoclaw --name alpha -- true", - [ - { - status: 1, - stdout: "", - stderr: - `Error: × code: 'The system is not in a state required for the operation's\n` + - ' │ execution\', message: "sandbox is not ready"\n', - }, - { status: 0, stdout: "", stderr: "" }, - ], - ], ]), ); - mocks.waitForCreatedSandboxReadyWithTrace.mockImplementationOnce((options) => { - expect(options.checkReadyIdentity?.()).toBe("not_ready"); - expect(options.checkReadyIdentity?.()).toBe("ready"); + vi.mocked(deps.commandExecutor.runBuffered) + .mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 1, signal: null }, + stdout: "", + stderr: + `Error: × code: 'The system is not in a state required for the operation's\n` + + ' │ execution\', message: "sandbox is not ready"\n', + }) + .mockResolvedValueOnce({ + outcome: { kind: "completed", exitCode: 0, signal: null }, + stdout: "", + stderr: "", + }); + mocks.waitForCreatedSandboxReadyWithTrace.mockImplementationOnce(async (options) => { + await expect(options.checkReadyIdentity?.()).resolves.toBe("not_ready"); + await expect(options.checkReadyIdentity?.()).resolves.toBe("ready"); return { ready: true, reason: "ready", failurePhase: null }; }); @@ -792,13 +793,7 @@ describe("runSandboxGpuCreateFlow native failure and readiness", () => { route: "none", }); - expect( - vi - .mocked(deps.runOpenshell) - .mock.calls.filter( - ([args]) => args.join(" ") === "sandbox exec -g nemoclaw --name alpha -- true", - ), - ).toHaveLength(2); + expect(deps.commandExecutor.runBuffered).toHaveBeenCalledTimes(2); expect(patch.rollbackManagedStartupAfterCreateFailure).not.toHaveBeenCalled(); expect(deps.runOpenshell).not.toHaveBeenCalledWith( ["sandbox", "delete", "alpha"], diff --git a/src/lib/onboard/sandbox-gpu-create-flow.ts b/src/lib/onboard/sandbox-gpu-create-flow.ts index 7b12c523c36..8133939b703 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.ts @@ -3,6 +3,7 @@ import type { AgentDefinition } from "../agent/defs"; import type { OpenShellSandboxObserver } from "../adapters/openshell/sandbox-observer"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { NEMOCLAW_CREATE_ATTEMPT_LABEL } from "../adapters/openshell/sandbox-identity"; import type { StreamSandboxCreateResult } from "../sandbox/create-stream"; import { redactFull } from "../security/redact"; @@ -302,6 +303,7 @@ export function refuseApfMutableNameFallbackCleanup(sandboxName: string) { } export interface SandboxGpuCreateFlowDeps { + commandExecutor: OpenShellSandboxBufferedCommandExecutor; runOpenshell: RunOpenshell; runCaptureOpenshell: RunCaptureOpenshell; sandboxObserver: OpenShellSandboxObserver; diff --git a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts index 18b27b1a9fe..bb98e1b50c3 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -138,7 +138,7 @@ describe("created sandbox identity gate", () => { await expect( options.observer.listSandboxes({ target: options.target }), ).resolves.toMatchObject({ ok: true }); - expect(options.checkReadyIdentity?.()).toBe("ready"); + await expect(options.checkReadyIdentity?.()).resolves.toBe("ready"); return { ready: true, reason: "ready", failurePhase: null }; }); @@ -155,10 +155,13 @@ describe("created sandbox identity gate", () => { ["sandbox", "get", "-g", gatewayName, "alpha"], expect.objectContaining({ ignoreError: true, suppressOutput: true }), ); - expect(deps.runOpenshell).toHaveBeenCalledWith( - ["sandbox", "exec", "-g", gatewayName, "--name", "alpha", "--", "true"], - expect.objectContaining({ ignoreError: true, suppressOutput: true }), - ); + expect(deps.commandExecutor.runBuffered).toHaveBeenCalledWith({ + command: ["true"], + sandboxName: "alpha", + target: { kind: "named", gatewayName }, + timeoutKillSignal: "SIGKILL", + timeoutMilliseconds: expect.any(Number), + }); }); it("resumes the exact verified sandbox without issuing another create (#9833)", async () => { @@ -380,8 +383,8 @@ describe("created sandbox identity gate", () => { ? (sandboxGetResults.shift() ?? resumedIdentityResult) : { status: 0, stdout: "", stderr: "" }, ); - mocks.waitForCreatedSandboxReadyWithTrace.mockImplementation((options) => { - expect(options.checkReadyIdentity?.()).toBe(expectedCheck); + mocks.waitForCreatedSandboxReadyWithTrace.mockImplementation(async (options) => { + await expect(options.checkReadyIdentity?.()).resolves.toBe(expectedCheck); return { ready: false, reason: expectedReason, failurePhase: null }; }); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index 8d7c07ac737..971430f8af8 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -17,6 +17,7 @@ import { resolveOpenShellSandboxId, settleCreatedOpenShellSandboxId, } from "../adapters/openshell/sandbox-identity"; +import { namedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { printSandboxCreateRecoveryHints } from "../build-context"; import { streamSandboxCreate, type StreamSandboxCreateResult } from "../sandbox/create-stream"; import { getReadyCheckOutputPatternsForAgent } from "../sandbox/create-stream-ready-gate"; @@ -178,7 +179,7 @@ async function rollbackNativeGpuFailureForFallback( return { nativeCleanupHandoff: rollback }; } -function normalizedOpenShellCommandOutput(result: OpenShellCommandResult): string { +function normalizedOpenShellCommandOutput(result: { stdout?: unknown; stderr?: unknown }): string { return `${String(result.stderr ?? "")}\n${String(result.stdout ?? "")}` .replace(ANSI_RE, "") .replace(/[×│]/gu, " ") @@ -336,7 +337,7 @@ function waitForCreatedOpenShellSandboxPublication( ); } -function checkRecreatedSandboxReadyIdentity( +async function checkRecreatedSandboxReadyIdentity( sandboxName: string, gatewayName: string, expectedSandboxId: string, @@ -347,10 +348,10 @@ function checkRecreatedSandboxReadyIdentity( if (identity.state === "not_ready") return "not_ready"; if (identity.state === "failed") return "probe_failed"; if (identity.sandboxId !== expectedSandboxId) return "identity_changed"; - return checkSandboxExecutableReadiness(sandboxName, gatewayName, deps, getRemainingMs); + return await checkSandboxExecutableReadiness(sandboxName, gatewayName, deps, getRemainingMs); } -function checkCreatedSandboxReadyIdentity( +async function checkCreatedSandboxReadyIdentity( sandboxName: string, gatewayName: string, deps: SandboxGpuCreateFlowDeps, @@ -359,10 +360,10 @@ function checkCreatedSandboxReadyIdentity( const identity = probeExactOpenShellSandboxId(sandboxName, gatewayName, deps, getRemainingMs); if (identity.state === "not_ready") return "not_ready"; if (identity.state === "failed") return "probe_failed"; - return checkSandboxExecutableReadiness(sandboxName, gatewayName, deps, getRemainingMs); + return await checkSandboxExecutableReadiness(sandboxName, gatewayName, deps, getRemainingMs); } -function checkSandboxExecutableReadiness( +async function checkSandboxExecutableReadiness( sandboxName: string, gatewayName: string, deps: SandboxGpuCreateFlowDeps, @@ -370,20 +371,17 @@ function checkSandboxExecutableReadiness( ): ReturnType { const timeout = remainingReadinessProbeTimeout(getRemainingMs); if (timeout === null) return "not_ready"; - const result = deps.runOpenshell( - ["sandbox", "exec", "-g", gatewayName, "--name", sandboxName, "--", "true"], - { - ignoreError: true, - suppressOutput: true, - timeout, - killSignal: "SIGKILL", - killProcessTreeOnTimeout: true, - }, - ); - if (result.status === 0 && !result.error) return "ready"; - if (result.error || result.status === null || ("signal" in result && result.signal)) { + const result = await deps.commandExecutor.runBuffered({ + sandboxName, + target: namedOpenShellGateway(gatewayName), + command: ["true"], + timeoutMilliseconds: timeout, + timeoutKillSignal: "SIGKILL", + }); + if (result.outcome.kind === "failed") { return "probe_failed"; } + if (result.outcome.exitCode === 0) return "ready"; return OPENSHELL_SANDBOX_NOT_READY.test(normalizedOpenShellCommandOutput(result)) ? "not_ready" : "probe_failed"; @@ -688,6 +686,7 @@ export function createSandboxGpuCreateAttemptRunner( reverifyBridgeReachability: reverifyManagedBridgeReachability, }, dependencies: { + commandExecutor: deps.commandExecutor, runCaptureOpenshell: deps.runCaptureOpenshell, runOpenshell: deps.runOpenshell, sleep: deps.sleep, diff --git a/src/lib/onboard/sandbox-readiness-tracing.test.ts b/src/lib/onboard/sandbox-readiness-tracing.test.ts index cead6a01d25..5b04790f490 100644 --- a/src/lib/onboard/sandbox-readiness-tracing.test.ts +++ b/src/lib/onboard/sandbox-readiness-tracing.test.ts @@ -8,6 +8,7 @@ import { type OpenShellSandboxObserver, type OpenShellSandboxReadinessProbe, } from "../adapters/openshell/sandbox-observer"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { pendingSandboxFrame, readySandboxFrame, @@ -38,6 +39,16 @@ function replay(frames: readonly SandboxObservationFrame[]) { return replaySandboxObservations(NAME, frames); } +function dashboardExecutorThrough(run: () => string): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: run(), + stderr: "", + })), + }; +} + describe("createSandboxReadyWaiter", () => { it("reads the authoritative gateway name for each CLI-backed wait (#9803)", async () => { let gatewayName = "nemoclaw"; @@ -285,7 +296,10 @@ describe("createSandboxReadyWaiter", () => { describe("waitForCreatedSandboxReadyWithTrace terminal-phase handling", () => { it("waits for the exact recreated sandbox to become executable before accepting stable Ready (#9050)", async () => { const { observer, listSandboxes, sleep } = replay([readySandboxFrame()]); - const checkReadyIdentity = vi.fn().mockReturnValueOnce("not_ready").mockReturnValue("ready"); + const checkReadyIdentity = vi + .fn() + .mockResolvedValueOnce("not_ready") + .mockResolvedValue("ready"); await expect( waitForCreatedSandboxReadyWithTrace({ @@ -312,7 +326,7 @@ describe("waitForCreatedSandboxReadyWithTrace terminal-phase handling", () => { timeoutSecs: 30, observer, target: TARGET, - checkReadyIdentity: () => "identity_changed", + checkReadyIdentity: async () => "identity_changed", sleep, }), ).resolves.toEqual({ ready: false, reason: "identity_changed", failurePhase: null }); @@ -328,7 +342,7 @@ describe("waitForCreatedSandboxReadyWithTrace terminal-phase handling", () => { timeoutSecs: 30, observer, target: TARGET, - checkReadyIdentity: () => "probe_failed", + checkReadyIdentity: async () => "probe_failed", sleep, }); expect(readiness).toEqual({ @@ -656,65 +670,65 @@ describe("waitForCreatedSandboxReadyWithTrace terminal-phase handling", () => { }); describe("waitForDashboardReadyWithTrace", () => { - it("traces a zero-budget deadline without probing", () => { + it("traces a zero-budget deadline without probing", async () => { const runCaptureOpenshell = vi.fn(() => "200"); const sleep = vi.fn(); const trace = vi.fn(); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - expect( + await expect( waitForDashboardReadyWithTrace({ sandboxName: NAME, port: 18789, - runCaptureOpenshell, + commandExecutor: dashboardExecutorThrough(runCaptureOpenshell), sleep, timeoutSecs: 0, trace, }), - ).toBe(false); + ).resolves.toBe(false); expect(trace).toHaveBeenCalledWith("not_ready", { attempts: 0, deadline_ms: 0 }); expect(runCaptureOpenshell).not.toHaveBeenCalled(); expect(sleep).not.toHaveBeenCalled(); expect(warn).toHaveBeenCalledWith(expect.stringContaining("0ms deadline")); }); - it("returns immediately when the dashboard is ready", () => { + it("returns immediately when the dashboard is ready", async () => { const runCaptureOpenshell = vi.fn(() => "200"); const sleep = vi.fn(); - expect( + await expect( waitForDashboardReadyWithTrace({ sandboxName: NAME, port: 18789, - runCaptureOpenshell, + commandExecutor: dashboardExecutorThrough(runCaptureOpenshell), sleep, }), - ).toBe(true); + ).resolves.toBe(true); expect(runCaptureOpenshell).toHaveBeenCalledOnce(); expect(sleep).not.toHaveBeenCalled(); }); - it("retries with fast polling and accepts an authenticated dashboard", () => { + it("retries with fast polling and accepts an authenticated dashboard", async () => { let nowMs = 1_000; const runCaptureOpenshell = vi.fn().mockReturnValueOnce("503").mockReturnValue("401"); const sleep = vi.fn((seconds: number) => { nowMs += seconds * 1000; }); - expect( + await expect( waitForDashboardReadyWithTrace({ sandboxName: NAME, port: 18789, - runCaptureOpenshell, + commandExecutor: dashboardExecutorThrough(runCaptureOpenshell), sleep, now: () => nowMs, }), - ).toBe(true); + ).resolves.toBe(true); expect(runCaptureOpenshell).toHaveBeenCalledTimes(2); expect(sleep).toHaveBeenCalledWith(0.25); }); - it("reports the actual short deadline on timeout", () => { + it("reports the actual short deadline on timeout", async () => { let nowMs = 1_000; const runCaptureOpenshell = vi.fn(() => "503"); const sleep = vi.fn((seconds: number) => { @@ -722,16 +736,16 @@ describe("waitForDashboardReadyWithTrace", () => { }); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - expect( + await expect( waitForDashboardReadyWithTrace({ sandboxName: NAME, port: 18789, - runCaptureOpenshell, + commandExecutor: dashboardExecutorThrough(runCaptureOpenshell), sleep, timeoutSecs: 0.1, now: () => nowMs, }), - ).toBe(false); + ).resolves.toBe(false); expect(sleep.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBe(0.1); expect(warn).toHaveBeenCalledWith(expect.stringContaining("100ms deadline")); }); diff --git a/src/lib/onboard/sandbox-readiness-tracing.ts b/src/lib/onboard/sandbox-readiness-tracing.ts index 6225eca9a82..88957961d80 100644 --- a/src/lib/onboard/sandbox-readiness-tracing.ts +++ b/src/lib/onboard/sandbox-readiness-tracing.ts @@ -9,6 +9,8 @@ import type { OpenShellSandboxReadinessProbe, OpenShellSandboxResult, } from "../adapters/openshell/sandbox-observer"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { namedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { createCliOpenShellLegacyPodReadinessProbe, @@ -113,7 +115,7 @@ export type SandboxReadyWaitResult = export type CreatedSandboxReadyIdentityCheck = ( getRemainingMs?: () => number, -) => "ready" | "not_ready" | "identity_changed" | "probe_failed"; +) => Promise<"ready" | "not_ready" | "identity_changed" | "probe_failed">; export interface SandboxReadyWaitDeps { observer: OpenShellSandboxObserver; @@ -466,7 +468,9 @@ export function waitForCreatedSandboxReadyWithTrace(options: { transient.error = null; const sandbox = observation.value.state === "present" ? observation.value.sandbox : null; if (sandbox?.readiness === "ready") { - const identity = options.checkReadyIdentity?.(getRemainingMs) ?? "ready"; + const identity = options.checkReadyIdentity + ? await options.checkReadyIdentity(getRemainingMs) + : "ready"; if (identity === "identity_changed") { addTraceEvent("identity_changed", { attempt }); result = { @@ -627,16 +631,16 @@ export function printReadinessFailure( export function waitForDashboardReadyWithTrace(options: { sandboxName: string; port: string | number; - runCaptureOpenshell: RunCaptureOpenshell; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; sleep: (seconds: number) => void; timeoutSecs?: number; now?: () => number; trace?: typeof addTraceEvent; -}): boolean { - const { sandboxName, port, runCaptureOpenshell, sleep } = options; +}): Promise { + const { sandboxName, port, commandExecutor, sleep } = options; const timeoutSecs = options.timeoutSecs ?? 30; const budgetMs = Math.max(0, timeoutSecs * 1000); - return withDashboardReadinessTrace(sandboxName, port, timeoutSecs, () => { + return withDashboardReadinessTrace(sandboxName, port, timeoutSecs, async () => { let attempt = 0; const waitOptions = createReadinessWaitOptions({ budgetMs, @@ -650,15 +654,12 @@ export function waitForDashboardReadyWithTrace(options: { } const ready = waitOptions !== null && - waitUntil(() => { + (await waitUntilAsync(async () => { attempt += 1; - const readyOutput = runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", - sandboxName, - "--", + const result = await commandExecutor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command: [ "curl", "-so", "/dev/null", @@ -668,12 +669,12 @@ export function waitForDashboardReadyWithTrace(options: { "3", `http://localhost:${port}/health`, ], - { ignoreError: true }, - ); + }); + const readyOutput = result.outcome.kind === "completed" ? result.stdout : ""; const readyCode = parseInt((readyOutput || "").trim(), 10) || 0; traceEvent("dashboard_probe", { attempt, http_status: readyCode }); return readyCode === 200 || readyCode === 401; - }, waitOptions); + }, waitOptions)); if (ready) { console.log(" ✓ Dashboard is live"); return true; diff --git a/src/lib/onboard/sandbox-verification-exec.test.ts b/src/lib/onboard/sandbox-verification-exec.test.ts new file mode 100644 index 00000000000..659cb729d0e --- /dev/null +++ b/src/lib/onboard/sandbox-verification-exec.test.ts @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { executeSandboxCommandForVerification } from "./sandbox-verification-exec"; + +describe("executeSandboxCommandForVerification", () => { + it("runs the verification script through the selected gateway with a bounded timeout", async () => { + const runBuffered = vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 7 }, + stdout: " output \n", + stderr: " warning \n", + })); + + await expect( + executeSandboxCommandForVerification("verify-box", "printf output", { runBuffered }), + ).resolves.toEqual({ status: 7, stdout: "output", stderr: "warning" }); + expect(runBuffered).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "verify-box", + target: { kind: "selected" }, + command: ["sh", "-c", "printf output"], + timeoutMilliseconds: 15_000, + }); + }); + + it("maps typed transport failures and executor rejections to an unreachable result", async () => { + await expect( + executeSandboxCommandForVerification("verify-box", "true", { + runBuffered: async () => ({ + outcome: { + kind: "failed", + error: { kind: "timeout", message: "timed out" }, + }, + stdout: "", + stderr: "", + }), + }), + ).resolves.toBeNull(); + + await expect( + executeSandboxCommandForVerification("verify-box", "true", { + runBuffered: async () => { + throw new Error("spawn rejected"); + }, + }), + ).resolves.toBeNull(); + }); +}); diff --git a/src/lib/onboard/sandbox-verification-exec.ts b/src/lib/onboard/sandbox-verification-exec.ts index e186d79faee..305aedd3427 100644 --- a/src/lib/onboard/sandbox-verification-exec.ts +++ b/src/lib/onboard/sandbox-verification-exec.ts @@ -8,27 +8,36 @@ * result, so we deliberately swallow spawn errors here. */ -import { spawnSync } from "node:child_process"; - -import { getOpenshellBinary } from "../adapters/openshell/runtime"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; const SANDBOX_EXEC_TIMEOUT_MS = 15000; export function executeSandboxCommandForVerification( sandboxName: string, script: string, -): { status: number; stdout: string; stderr: string } | null { + executor: OpenShellSandboxBufferedCommandExecutor, +): Promise<{ status: number; stdout: string; stderr: string } | null> { + return executeSandboxVerification(executor, sandboxName, script); +} + +async function executeSandboxVerification( + executor: OpenShellSandboxBufferedCommandExecutor, + sandboxName: string, + script: string, +): Promise<{ status: number; stdout: string; stderr: string } | null> { try { - const result = spawnSync( - getOpenshellBinary(), - ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-c", script], - { encoding: "utf-8", timeout: SANDBOX_EXEC_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }, - ); - if (result.error) return null; + const result = await executor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command: ["sh", "-c", script], + timeoutMilliseconds: SANDBOX_EXEC_TIMEOUT_MS, + }); + if (result.outcome.kind === "failed") return null; return { - status: result.status ?? 1, - stdout: (result.stdout || "").trim(), - stderr: (result.stderr || "").trim(), + status: result.outcome.exitCode, + stdout: result.stdout.trim(), + stderr: result.stderr.trim(), }; } catch { return null; diff --git a/src/lib/onboard/verify-channel-runtime.test.ts b/src/lib/onboard/verify-channel-runtime.test.ts index 4be433d45bd..8b8f3a5574b 100644 --- a/src/lib/onboard/verify-channel-runtime.test.ts +++ b/src/lib/onboard/verify-channel-runtime.test.ts @@ -19,26 +19,26 @@ function fakeAgent(format: string | null) { describe("buildChannelRuntimeProbe", () => { it("returns null when no agent is selected", () => { - expect(buildChannelRuntimeProbe(null, { executeSandboxCommand: () => null })).toBeNull(); + expect(buildChannelRuntimeProbe(null, { executeSandboxCommand: async () => null })).toBeNull(); }); it("returns null for non-JSON agents (e.g. Hermes uses yaml)", () => { expect( - buildChannelRuntimeProbe(fakeAgent("yaml"), { executeSandboxCommand: () => null }), + buildChannelRuntimeProbe(fakeAgent("yaml"), { executeSandboxCommand: async () => null }), ).toBeNull(); }); - it("returns a probe function for JSON agents (OpenClaw) that targets /", () => { + it("returns a probe function for JSON agents (OpenClaw) that targets /", async () => { const captured: string[] = []; const probe = buildChannelRuntimeProbe(fakeAgent("json"), { - executeSandboxCommand: (script: string) => { + executeSandboxCommand: async (script: string) => { captured.push(script); // First call reads the config; second call scans the gateway log. return { status: 0, stdout: script.startsWith("cat ") ? "{}" : "", stderr: "" }; }, }); expect(probe).toBeTypeOf("function"); - const result = probe!(); + const result = await probe!(); expect(result).not.toBeNull(); // The first exec call must be against the agent's config path (the // `cat ` snippet from probeChannelRuntimeStatus). diff --git a/src/lib/onboard/verify-channel-runtime.ts b/src/lib/onboard/verify-channel-runtime.ts index e1b3c8186e8..ed9d20d2b02 100644 --- a/src/lib/onboard/verify-channel-runtime.ts +++ b/src/lib/onboard/verify-channel-runtime.ts @@ -10,6 +10,7 @@ */ import type { AgentDefinition } from "../agent/defs"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { probeChannelRuntimeStatus, type ChannelRuntimeStatusDeps, @@ -40,7 +41,7 @@ export interface ChannelRuntimeProbeDeps { export function buildChannelRuntimeProbe( agent: AgentDefinition | null, deps: ChannelRuntimeProbeDeps, -): (() => RuntimeChannelStatus | null) | null { +): (() => Promise) | null { const configPaths = agent?.configPaths; if (!configPaths || configPaths.format !== "json") return null; const configFilePath = `${configPaths.dir}/${configPaths.configFile}`; @@ -60,11 +61,12 @@ export function buildChannelRuntimeProbe( export function buildOnboardChannelRuntimeProbe( agent: AgentDefinition | null, sandboxName: string, -): (() => RuntimeChannelStatus | null) | undefined { + commandExecutor: OpenShellSandboxBufferedCommandExecutor, +): (() => Promise) | undefined { return ( buildChannelRuntimeProbe(agent, { executeSandboxCommand: (script: string) => - executeSandboxCommandForVerification(sandboxName, script), + executeSandboxCommandForVerification(sandboxName, script, commandExecutor), }) ?? undefined ); } diff --git a/src/lib/onboard/web-search-flow.test.ts b/src/lib/onboard/web-search-flow.test.ts index 82126851ef2..eb6d6e2a32f 100644 --- a/src/lib/onboard/web-search-flow.test.ts +++ b/src/lib/onboard/web-search-flow.test.ts @@ -31,7 +31,13 @@ function helpers(overrides: Record = {}) { note: () => {}, isNonInteractive: () => true, cliName: () => "nemoclaw", - runCaptureOpenshell: () => null, + commandExecutor: { + runBuffered: async () => ({ + outcome: { kind: "failed", error: { kind: "invocation", message: "unavailable" } }, + stdout: "", + stderr: "", + }), + }, ...overrides, }); } @@ -49,7 +55,13 @@ describe("Brave key prompt empty-input escape (#6025)", () => { note: () => {}, isNonInteractive: () => false, cliName: () => "nemoclaw", - runCaptureOpenshell: () => null, + commandExecutor: { + runBuffered: async () => ({ + outcome: { kind: "failed", error: { kind: "invocation", message: "unavailable" } }, + stdout: "", + stderr: "", + }), + }, }); const result = await flow.promptBraveSearchApiKey(); @@ -106,36 +118,39 @@ describe("web search provider validation", () => { it.each([ ["brave", "brv-secret", "X-Subscription-Token: brv-secret"], ["tavily", "tvly-secret", "Authorization: Bearer tvly-secret"], - ] as const)("keeps the %s key out of curl argv in a temporary 0600 config", (provider, apiKey, header) => { - let configPath = ""; - vi.mocked(runCurlProbe).mockImplementationOnce((args, options) => { - configPath = String(options?.trustedConfigFiles?.[0] ?? ""); - expect(configPath).not.toBe(""); - expect(args.join(" ")).not.toContain(apiKey); - expect(args).toContain(configPath); - const configFd = fs.openSync( - configPath, - fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0), - ); - try { - expect(fs.fstatSync(configFd).mode & 0o777).toBe(0o600); - expect(fs.readFileSync(configFd, "utf8")).toContain(header); - } finally { - fs.closeSync(configFd); - } - return { - ok: true, - httpStatus: 200, - curlStatus: 0, - body: "{}", - stderr: "", - message: "ok", - }; - }); + ] as const)( + "keeps the %s key out of curl argv in a temporary 0600 config", + (provider, apiKey, header) => { + let configPath = ""; + vi.mocked(runCurlProbe).mockImplementationOnce((args, options) => { + configPath = String(options?.trustedConfigFiles?.[0] ?? ""); + expect(configPath).not.toBe(""); + expect(args.join(" ")).not.toContain(apiKey); + expect(args).toContain(configPath); + const configFd = fs.openSync( + configPath, + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0), + ); + try { + expect(fs.fstatSync(configFd).mode & 0o777).toBe(0o600); + expect(fs.readFileSync(configFd, "utf8")).toContain(header); + } finally { + fs.closeSync(configFd); + } + return { + ok: true, + httpStatus: 200, + curlStatus: 0, + body: "{}", + stderr: "", + message: "ok", + }; + }); - expect(helpers().validateWebSearchApiKey(provider, apiKey).ok).toBe(true); - expect(fs.existsSync(configPath)).toBe(false); - }); + expect(helpers().validateWebSearchApiKey(provider, apiKey).ok).toBe(true); + expect(fs.existsSync(configPath)).toBe(false); + }, + ); it("uses a POST JSON probe for Tavily", () => { helpers().validateTavilySearchApiKey("tvly-secret"); diff --git a/src/lib/onboard/web-search-flow.ts b/src/lib/onboard/web-search-flow.ts index a15f17ed81f..d3c2f90ecc8 100644 --- a/src/lib/onboard/web-search-flow.ts +++ b/src/lib/onboard/web-search-flow.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { createCurlAuthConfig } from "../adapters/http/auth-config"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import type { CurlProbeResult } from "../adapters/http/probe"; import { runCurlProbe } from "../adapters/http/probe"; import type { AgentDefinition } from "../agent/defs"; @@ -67,7 +68,7 @@ export interface WebSearchFlowDeps { note(message: string): void; isNonInteractive(): boolean; cliName(): string; - runCaptureOpenshell(args: string[], opts?: Record): string | null; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; env?: NodeJS.ProcessEnv; getCredential?: (envKey: string) => string | null; saveCredential?: (envKey: string, value: string) => void; @@ -105,7 +106,7 @@ export interface WebSearchFlowHelpers { sandboxName: string, agent: AgentDefinition | null | undefined, provider: WebSearchProvider, - ): boolean; + ): Promise; } export function createWebSearchFlowHelpers(deps: WebSearchFlowDeps): WebSearchFlowHelpers { @@ -478,13 +479,13 @@ export function createWebSearchFlowHelpers(deps: WebSearchFlowDeps): WebSearchFl } } - function verifyWebSearchInsideSandbox( + async function verifyWebSearchInsideSandbox( sandboxName: string, agent: AgentDefinition | null | undefined, provider: WebSearchProvider, - ): boolean { - return verifyWebSearchInsideSandboxWithDeps(sandboxName, agent, provider, { - runCaptureOpenshell: deps.runCaptureOpenshell, + ): Promise { + return await verifyWebSearchInsideSandboxWithDeps(sandboxName, agent, provider, { + commandExecutor: deps.commandExecutor, cliName: deps.cliName, webSearchEnvFor, webSearchLabelFor, diff --git a/src/lib/onboard/web-search-verify.test.ts b/src/lib/onboard/web-search-verify.test.ts index 4af694e8dae..d8f8b54a4e6 100644 --- a/src/lib/onboard/web-search-verify.test.ts +++ b/src/lib/onboard/web-search-verify.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { classifyWebSearchEnvBoundary, @@ -11,10 +12,22 @@ import { function deps(output: string | null | Array) { const outputs = Array.isArray(output) ? [...output] : [output]; + const runBuffered = vi.fn(async () => { + const result = outputs.shift() ?? null; + return result === null + ? { + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + }, + stdout: "", + stderr: "", + } + : { outcome: { kind: "completed" as const, exitCode: 0 }, stdout: result, stderr: "" }; + }); return { - runCaptureOpenshell: vi.fn( - () => outputs.shift() ?? null, - ), + runBuffered, + commandExecutor: { runBuffered }, cliName: vi.fn(() => "nemoclaw"), webSearchEnvFor: vi.fn((provider) => provider === "tavily" ? "TAVILY_API_KEY" : "BRAVE_API_KEY", @@ -24,11 +37,11 @@ function deps(output: string | null | Array) { ), log: vi.fn(), warn: vi.fn(), - } satisfies WebSearchVerifyDeps; + } satisfies WebSearchVerifyDeps & { runBuffered: typeof runBuffered }; } describe("verifyWebSearchInsideSandbox", () => { - it("verifies Hermes Tavily egress through JSON body credential rewriting", () => { + it("verifies Hermes Tavily egress through JSON body credential rewriting", async () => { // Before config diagnostics and the egress probe, the secret-boundary check // classifies the selected env var in-sandbox. const d = deps([ @@ -37,49 +50,40 @@ describe("verifyWebSearchInsideSandbox", () => { JSON.stringify({ results: [{ title: "NVIDIA" }] }) + "\nHTTP_STATUS:200\n", ]); - verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", d); + await verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", d); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(3); - expect(d.runCaptureOpenshell.mock.calls[1][0]).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "cat", - "/sandbox/.hermes/config.yaml", - ]); + expect(d.runBuffered).toHaveBeenCalledTimes(3); + expect(d.runBuffered.mock.calls[1][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["cat", "/sandbox/.hermes/config.yaml"], + }); // The boundary probe classifies in-sandbox with `sh -c` (no login profiles) // and returns only a marked sentinel. - expect(d.runCaptureOpenshell.mock.calls[0][0].slice(0, 7)).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-c", - ]); - expect(d.runCaptureOpenshell.mock.calls[0][0][7]).toContain("printenv TAVILY_API_KEY"); - expect(d.runCaptureOpenshell.mock.calls[0][0][7]).not.toContain("cat "); - expect(d.runCaptureOpenshell.mock.calls[2][0]).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-lc", - expect.stringContaining('"api_key":"openshell:resolve:env:TAVILY_API_KEY"'), - ]); + expect(d.runBuffered.mock.calls[0][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["sh", "-c", expect.stringContaining("printenv TAVILY_API_KEY")], + timeoutMilliseconds: 10_000, + }); + expect(d.runBuffered.mock.calls[0][0].command[2]).not.toContain("cat "); + expect(d.runBuffered.mock.calls[2][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: [ + "sh", + "-lc", + expect.stringContaining('"api_key":"openshell:resolve:env:TAVILY_API_KEY"'), + ], + }); expect(d.log).toHaveBeenCalledWith(" ✓ Tavily Search egress verified inside sandbox"); expect(d.warn).not.toHaveBeenCalled(); }); - it("blocks Hermes handoff when the sandbox env exposes a raw Tavily key (#7425)", () => { + it("blocks Hermes handoff when the sandbox env exposes a raw Tavily key (#7425)", async () => { const d = deps("__nemoclaw_wsenv__:raw-secret"); - const credentialBoundarySafe = verifyWebSearchInsideSandbox( + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( "alpha", { name: "hermes" }, "tavily", @@ -87,7 +91,7 @@ describe("verifyWebSearchInsideSandbox", () => { ); expect(credentialBoundarySafe).toBe(false); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(1); + expect(d.runBuffered).toHaveBeenCalledTimes(1); expect(d.warn).toHaveBeenCalledWith( " ✗ SECURITY: the Tavily Search credential is exposed in the sandbox environment.", ); @@ -126,21 +130,26 @@ describe("verifyWebSearchInsideSandbox", () => { }, ])( "blocks $label before configuration diagnostics (#7425)", - ({ agent, provider, config, alert }) => { + async ({ agent, provider, config, alert }) => { const d = deps(["__nemoclaw_wsenv__:raw-secret", config]); - const credentialBoundarySafe = verifyWebSearchInsideSandbox("alpha", agent, provider, d); + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( + "alpha", + agent, + provider, + d, + ); expect(credentialBoundarySafe).toBe(false); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(1); + expect(d.runBuffered).toHaveBeenCalledTimes(1); expect(d.warn).toHaveBeenCalledWith(alert); }, ); - it("does not treat pinned Hermes dump-shaped output as an active Tavily backend", () => { + it("does not treat pinned Hermes dump-shaped output as an active Tavily backend", async () => { const d = deps(["__nemoclaw_wsenv__:absent", "active toolsets: web, shell\n"]); - verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", d); + await verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", d); expect(d.warn).toHaveBeenCalledWith( " ⚠ Tavily Search was configured but Hermes config does not select web.backend=tavily.", @@ -148,24 +157,24 @@ describe("verifyWebSearchInsideSandbox", () => { expect(d.warn).toHaveBeenCalledWith( " Check: nemoclaw alpha exec -- cat /sandbox/.hermes/config.yaml", ); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(2); + expect(d.runBuffered).toHaveBeenCalledTimes(2); }); - it("warns when the Hermes config is missing or malformed", () => { + it("warns when the Hermes config is missing or malformed", async () => { const missing = deps(["__nemoclaw_wsenv__:absent", null]); - verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", missing); + await verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", missing); expect(missing.warn).toHaveBeenCalledWith( " ⚠ Could not read Hermes config to verify Tavily Search.", ); const malformed = deps(["__nemoclaw_wsenv__:absent", "web: [\n"]); - verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", malformed); + await verifyWebSearchInsideSandbox("alpha", { name: "hermes" }, "tavily", malformed); expect(malformed.warn).toHaveBeenCalledWith( " ⚠ Could not parse Hermes config to verify Tavily Search.", ); }); - it("verifies OpenClaw Brave Search egress through the subscription-token header", () => { + it("verifies OpenClaw Brave Search egress through the subscription-token header", async () => { // Current schema: the provider-owned apiKey lives under // plugins.entries.brave.config.webSearch, not inline on tools.web.search. const d = deps([ @@ -184,7 +193,7 @@ describe("verifyWebSearchInsideSandbox", () => { JSON.stringify({ web: { results: [{ title: "NVIDIA" }] } }) + "\nHTTP_STATUS:200\n", ]); - const credentialBoundarySafe = verifyWebSearchInsideSandbox( + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( "alpha", { name: "openclaw" }, "brave", @@ -192,31 +201,26 @@ describe("verifyWebSearchInsideSandbox", () => { ); expect(credentialBoundarySafe).toBe(true); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(3); - expect(d.runCaptureOpenshell.mock.calls[0][0].slice(0, 7)).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-c", - ]); - expect(d.runCaptureOpenshell.mock.calls[0][0][7]).toContain("printenv BRAVE_API_KEY"); - expect(d.runCaptureOpenshell.mock.calls[2][0]).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-lc", - expect.stringContaining("X-Subscription-Token: openshell:resolve:env:BRAVE_API_KEY"), - ]); + expect(d.runBuffered).toHaveBeenCalledTimes(3); + expect(d.runBuffered.mock.calls[0][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["sh", "-c", expect.stringContaining("printenv BRAVE_API_KEY")], + timeoutMilliseconds: 10_000, + }); + expect(d.runBuffered.mock.calls[2][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: [ + "sh", + "-lc", + expect.stringContaining("X-Subscription-Token: openshell:resolve:env:BRAVE_API_KEY"), + ], + }); expect(d.log).toHaveBeenCalledWith(" ✓ Brave Search egress verified inside sandbox"); }); - it("verifies OpenClaw Tavily Search egress through the bearer header", () => { + it("verifies OpenClaw Tavily Search egress through the bearer header", async () => { const d = deps([ "__nemoclaw_wsenv__:placeholder", JSON.stringify({ @@ -233,7 +237,7 @@ describe("verifyWebSearchInsideSandbox", () => { JSON.stringify({ results: [{ title: "NVIDIA" }] }) + "\nHTTP_STATUS:200\n", ]); - const credentialBoundarySafe = verifyWebSearchInsideSandbox( + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( "alpha", { name: "openclaw" }, "tavily", @@ -241,22 +245,21 @@ describe("verifyWebSearchInsideSandbox", () => { ); expect(credentialBoundarySafe).toBe(true); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(3); - expect(d.runCaptureOpenshell.mock.calls[2][0]).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-lc", - expect.stringContaining("Authorization: Bearer openshell:resolve:env:TAVILY_API_KEY"), - ]); - expect(d.runCaptureOpenshell.mock.calls[2][0][7]).toContain("https://api.tavily.com/search"); + expect(d.runBuffered).toHaveBeenCalledTimes(3); + expect(d.runBuffered.mock.calls[2][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: [ + "sh", + "-lc", + expect.stringContaining("Authorization: Bearer openshell:resolve:env:TAVILY_API_KEY"), + ], + }); + expect(d.runBuffered.mock.calls[2][0].command[2]).toContain("https://api.tavily.com/search"); expect(d.log).toHaveBeenCalledWith(" ✓ Tavily Search egress verified inside sandbox"); }); - it("does not accept an empty Tavily results array as successful verification", () => { + it("does not accept an empty Tavily results array as successful verification", async () => { const d = deps([ "__nemoclaw_wsenv__:absent", JSON.stringify({ @@ -273,7 +276,7 @@ describe("verifyWebSearchInsideSandbox", () => { JSON.stringify({ results: [] }) + "\nHTTP_STATUS:200\n", ]); - const credentialBoundarySafe = verifyWebSearchInsideSandbox( + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( "alpha", { name: "openclaw" }, "tavily", @@ -287,7 +290,7 @@ describe("verifyWebSearchInsideSandbox", () => { expect(d.log).not.toHaveBeenCalled(); }); - it("still probes legacy configs that carry the apiKey inline on tools.web.search", () => { + it("still probes legacy configs that carry the apiKey inline on tools.web.search", async () => { const d = deps([ "__nemoclaw_wsenv__:absent", JSON.stringify({ @@ -304,13 +307,13 @@ describe("verifyWebSearchInsideSandbox", () => { JSON.stringify({ web: { results: [{ title: "NVIDIA" }] } }) + "\nHTTP_STATUS:200\n", ]); - verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); + await verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(3); + expect(d.runBuffered).toHaveBeenCalledTimes(3); expect(d.log).toHaveBeenCalledWith(" ✓ Brave Search egress verified inside sandbox"); }); - it("warns when OpenClaw Brave Search egress rejects the placeholder", () => { + it("warns when OpenClaw Brave Search egress rejects the placeholder", async () => { const d = deps([ "__nemoclaw_wsenv__:placeholder", JSON.stringify({ @@ -327,7 +330,7 @@ describe("verifyWebSearchInsideSandbox", () => { '{"message":"Unauthorized"}\nHTTP_STATUS:401\n', ]); - verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); + await verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); expect(d.warn).toHaveBeenCalledWith( " ⚠ Brave Search config exists, but egress verification returned HTTP 401.", @@ -337,7 +340,7 @@ describe("verifyWebSearchInsideSandbox", () => { ); }); - it("refuses to probe when the apiKey is a literal secret rather than a placeholder", () => { + it("refuses to probe when the apiKey is a literal secret rather than a placeholder", async () => { const d = deps([ "__nemoclaw_wsenv__:absent", JSON.stringify({ @@ -353,30 +356,26 @@ describe("verifyWebSearchInsideSandbox", () => { }), ]); - verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); + await verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); // The config read and the sentinel-only boundary probe run, but no curl // probe interpolates the raw key. - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(2); - expect(d.runCaptureOpenshell.mock.calls[0][0].slice(0, 7)).toEqual([ - "sandbox", - "exec", - "-n", - "alpha", - "--", - "sh", - "-c", - ]); - const commandArguments = d.runCaptureOpenshell.mock.calls.flatMap(([args]) => args); + expect(d.runBuffered).toHaveBeenCalledTimes(2); + expect(d.runBuffered.mock.calls[0][0]).toMatchObject({ + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["sh", "-c", expect.any(String)], + }); + const commandArguments = d.runBuffered.mock.calls.flatMap(([request]) => request.command); expect(commandArguments.join("\n")).not.toContain("literal-secret-do-not-interpolate"); expect(d.warn).toHaveBeenCalledWith( " ⚠ Brave Search apiKey in openclaw.json is not an OpenShell placeholder; skipping egress probe.", ); }); - it("warns when OpenClaw config is malformed or disabled", () => { + it("warns when OpenClaw config is malformed or disabled", async () => { const malformed = deps(["__nemoclaw_wsenv__:absent", "not-json"]); - verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", malformed); + await verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", malformed); expect(malformed.warn).toHaveBeenCalledWith( " ⚠ Could not parse openclaw.json to verify web search config.", ); @@ -385,26 +384,26 @@ describe("verifyWebSearchInsideSandbox", () => { "__nemoclaw_wsenv__:absent", JSON.stringify({ tools: { web: { search: { enabled: false } } } }), ]); - verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", disabled); + await verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", disabled); expect(disabled.warn).toHaveBeenCalledWith( " ⚠ Web search was configured but tools.web.search is not enabled in openclaw.json.", ); }); - it("warns for unknown agents after checking the selected credential boundary", () => { + it("warns for unknown agents after checking the selected credential boundary", async () => { const unknown = deps("__nemoclaw_wsenv__:absent"); - verifyWebSearchInsideSandbox("alpha", { name: "other" }, "brave", unknown); + await verifyWebSearchInsideSandbox("alpha", { name: "other" }, "brave", unknown); expect(unknown.warn).toHaveBeenCalledWith( " ⚠ Web search verification is not implemented for agent 'other'.", ); }); - it("blocks handoff when the credential-boundary probe fails closed (#7425)", () => { + it("blocks handoff when the credential-boundary probe fails closed (#7425)", async () => { const throwing = deps(null); - throwing.runCaptureOpenshell = vi.fn(() => { + throwing.commandExecutor.runBuffered = vi.fn(async () => { throw new Error("boom"); }); - const credentialBoundarySafe = verifyWebSearchInsideSandbox( + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( "alpha", { name: "openclaw" }, "brave", @@ -416,12 +415,12 @@ describe("verifyWebSearchInsideSandbox", () => { ); }); - it("raises a security alert when the sandbox env exposes a raw Brave key (#7425)", () => { + it("raises a security alert when the sandbox env exposes a raw Brave key (#7425)", async () => { // The in-sandbox probe returns only the `raw-secret` sentinel — never the // key itself — so the guard does not pull the credential across the boundary. const d = deps("__nemoclaw_wsenv__:raw-secret"); - const credentialBoundarySafe = verifyWebSearchInsideSandbox( + const credentialBoundarySafe = await verifyWebSearchInsideSandbox( "alpha", { name: "openclaw" }, "brave", @@ -433,11 +432,11 @@ describe("verifyWebSearchInsideSandbox", () => { ); expect(d.warn).toHaveBeenCalledWith(" nemoclaw onboard --recreate-sandbox"); expect(credentialBoundarySafe).toBe(false); - expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(1); + expect(d.runBuffered).toHaveBeenCalledTimes(1); expect(d.log).not.toHaveBeenCalledWith(" ✓ Brave Search egress verified inside sandbox"); }); - it("accepts a resolve:env placeholder sentinel without a security alert", () => { + it("accepts a resolve:env placeholder sentinel without a security alert", async () => { const d = deps([ "__nemoclaw_wsenv__:placeholder", JSON.stringify({ @@ -454,9 +453,11 @@ describe("verifyWebSearchInsideSandbox", () => { JSON.stringify({ web: { results: [{ title: "NVIDIA" }] } }) + "\nHTTP_STATUS:200\n", ]); - verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); + await verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, "brave", d); - expect(d.warn.mock.calls.every((call) => !String(call[0] ?? "").includes("SECURITY"))).toBe(true); + expect(d.warn.mock.calls.every((call) => !String(call[0] ?? "").includes("SECURITY"))).toBe( + true, + ); expect(d.log).toHaveBeenCalledWith(" ✓ Brave Search egress verified inside sandbox"); }); }); diff --git a/src/lib/onboard/web-search-verify.ts b/src/lib/onboard/web-search-verify.ts index 21936d259ea..5b941e839cd 100644 --- a/src/lib/onboard/web-search-verify.ts +++ b/src/lib/onboard/web-search-verify.ts @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import YAML from "yaml"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; +import { selectedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { shellQuote } from "../core/shell-quote"; export type WebSearchVerifyProvider = "brave" | "tavily"; @@ -14,10 +16,7 @@ export type WebSearchVerifyAgent = | undefined; export type WebSearchVerifyDeps = { - runCaptureOpenshell: ( - args: string[], - options: { ignoreError: true; timeout: number }, - ) => string | null; + commandExecutor: OpenShellSandboxBufferedCommandExecutor; cliName: () => string; webSearchEnvFor: (provider: WebSearchVerifyProvider) => string; webSearchLabelFor: (provider: WebSearchVerifyProvider) => string; @@ -77,29 +76,39 @@ export function classifyWebSearchEnvBoundary( * actionable alert for a raw-secret exposure or an unverifiable result. Returns * true for either unsafe state so finalization can refuse a successful handoff. */ -function checkWebSearchEnvSecretBoundary( +async function runSandboxCommand( + deps: WebSearchVerifyDeps, + sandboxName: string, + command: readonly string[], + timeoutMilliseconds: number, +): Promise { + const completed = await deps.commandExecutor.runBuffered({ + sandboxName, + target: selectedOpenShellGateway(), + command, + timeoutMilliseconds, + }); + return completed.outcome.kind === "completed" && completed.outcome.exitCode === 0 + ? completed.stdout + : null; +} + +async function checkWebSearchEnvSecretBoundary( sandboxName: string, provider: WebSearchVerifyProvider, deps: WebSearchVerifyDeps, warn: (message?: string) => void, -): boolean { +): Promise { const envKey = deps.webSearchEnvFor(provider); let probe: string | null = null; try { - probe = deps.runCaptureOpenshell( + probe = await runSandboxCommand( + deps, + sandboxName, // `sh -c` (not `-lc`): no login profiles run, so their output cannot // contaminate the sentinel the host classifies. - [ - "sandbox", - "exec", - "-n", - sandboxName, - "--", - "sh", - "-c", - buildWebSearchEnvBoundaryScript(envKey), - ], - { ignoreError: true, timeout: 10_000 }, + ["sh", "-c", buildWebSearchEnvBoundaryScript(envKey)], + 10_000, ); } catch { // The missing sentinel below is handled as an unsafe, unknown boundary. @@ -226,28 +235,27 @@ function hasTavilyResult(body: string): boolean { * raw credential or an unverifiable isolation result returns false so onboarding * cannot report the sandbox as ready. */ -export function verifyWebSearchInsideSandbox( +export async function verifyWebSearchInsideSandbox( sandboxName: string, agent: WebSearchVerifyAgent, provider: WebSearchVerifyProvider, deps: WebSearchVerifyDeps, -): boolean { +): Promise { const log = deps.log ?? console.log; const warn = deps.warn ?? console.warn; const agentName = agent?.name || "openclaw"; - if (checkWebSearchEnvSecretBoundary(sandboxName, provider, deps, warn)) return false; + if (await checkWebSearchEnvSecretBoundary(sandboxName, provider, deps, warn)) return false; try { if (agentName === "hermes") { // Hermes v2026.6.19 `dump` does not expose web.backend. Inspect the // generated config directly, then prove that the configured body // placeholder is rewritten on a real request. - const configText = deps.runCaptureOpenshell( - ["sandbox", "exec", "-n", sandboxName, "--", "cat", "/sandbox/.hermes/config.yaml"], - { - ignoreError: true, - timeout: 10_000, - }, + const configText = await runSandboxCommand( + deps, + sandboxName, + ["cat", "/sandbox/.hermes/config.yaml"], + 10_000, ); if (!configText) { warn(" ⚠ Could not read Hermes config to verify Tavily Search."); @@ -272,18 +280,11 @@ export function verifyWebSearchInsideSandbox( } const placeholder = "openshell:resolve:env:TAVILY_API_KEY"; - const probe = deps.runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", - sandboxName, - "--", - "sh", - "-lc", - buildTavilyBodyEgressProbeCommand(placeholder), - ], - { ignoreError: true, timeout: 30_000 }, + const probe = await runSandboxCommand( + deps, + sandboxName, + ["sh", "-lc", buildTavilyBodyEgressProbeCommand(placeholder)], + 30_000, ); if (!probe) { warn(" ⚠ Tavily Search config exists, but the egress verification request failed."); @@ -300,9 +301,11 @@ export function verifyWebSearchInsideSandbox( } else if (agentName === "openclaw") { // OpenClaw: verify tools.web.search exists, then prove the selected // provider placeholder works at egress through its credential header. - const configCheck = deps.runCaptureOpenshell( - ["sandbox", "exec", "-n", sandboxName, "--", "cat", "/sandbox/.openclaw/openclaw.json"], - { ignoreError: true, timeout: 10_000 }, + const configCheck = await runSandboxCommand( + deps, + sandboxName, + ["cat", "/sandbox/.openclaw/openclaw.json"], + 10_000, ); if (!configCheck) { warn(" ⚠ Could not verify web search config inside sandbox."); @@ -347,9 +350,11 @@ export function verifyWebSearchInsideSandbox( provider === "tavily" ? buildTavilyEgressProbeCommand(apiKey) : buildBraveEgressProbeCommand(apiKey); - const probe = deps.runCaptureOpenshell( - ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", probeCommand], - { ignoreError: true, timeout: 30_000 }, + const probe = await runSandboxCommand( + deps, + sandboxName, + ["sh", "-lc", probeCommand], + 30_000, ); if (!probe) { warn(` ⚠ ${providerLabel} config exists, but the egress verification request failed.`); diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index e5feca6e623..cf711473f3f 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -107,7 +107,7 @@ interface ConfigUrlValidationOptions { allowPrivateUrls?: boolean; } -type ManagedGatewayRestart = (sandboxName: string) => { ok: boolean }; +type ManagedGatewayRestart = (sandboxName: string) => Promise<{ ok: boolean }>; export class SandboxConfigError extends Error { readonly lines: readonly string[]; @@ -126,15 +126,15 @@ function configFail(lines: string | readonly string[], exitCode = 1): never { throw new SandboxConfigError(lines, exitCode); } -function restartSandboxAgentAfterConfigSet( +async function restartSandboxAgentAfterConfigSet( sandboxName: string, agentName: string, restartImpl?: ManagedGatewayRestart, -): void { +): Promise { const restart = restartImpl ?? (require("../actions/sandbox/process-recovery").restartSandboxGateway as ManagedGatewayRestart); - const result = restart(sandboxName); + const result = await restart(sandboxName); if (!result.ok) { // The config was already written to disk (the CAS write above succeeded), // but the running agent was not reloaded. Say so plainly and point at the @@ -1417,7 +1417,7 @@ async function configSet(sandboxName: string, opts: ConfigSetOpts = {}): Promise // Restart if requested if (opts.restart) { - restartSandboxAgentAfterConfigSet(sandboxName, target.agentName); + await restartSandboxAgentAfterConfigSet(sandboxName, target.agentName); } else { console.log(""); for (const line of buildConfigSetRestartGuidance(sandboxName, target.agentName)) { diff --git a/src/lib/tunnel/allowed-origins.test.ts b/src/lib/tunnel/allowed-origins.test.ts index c25c490a7a5..6923953ecc9 100644 --- a/src/lib/tunnel/allowed-origins.test.ts +++ b/src/lib/tunnel/allowed-origins.test.ts @@ -34,7 +34,7 @@ function makeDeps(config: ConfigObject, target: AgentConfigTarget = OPENCLAW_TAR const readConfig = vi.fn((_sb: string, _t: AgentConfigTarget): ConfigObject => config); const writeConfig = vi.fn((_sb: string, _t: AgentConfigTarget, _c: ConfigObject): void => {}); const recomputeHash = vi.fn((_sb: string, _t: AgentConfigTarget): void => {}); - const reloadGateway = vi.fn((_sb: string): void => {}); + const reloadGateway = vi.fn(async (_sb: string): Promise => {}); const info = vi.fn((_msg: string): void => {}); const warn = vi.fn((_msg: string): void => {}); const deps: RegisterTunnelOriginDeps = { diff --git a/src/lib/tunnel/allowed-origins.ts b/src/lib/tunnel/allowed-origins.ts index 26ab9583b89..2453913cc05 100644 --- a/src/lib/tunnel/allowed-origins.ts +++ b/src/lib/tunnel/allowed-origins.ts @@ -80,7 +80,7 @@ export interface RegisterTunnelOriginDeps { readConfig: (sandboxName: string, target: AgentConfigTarget) => ConfigObject; writeConfig: (sandboxName: string, target: AgentConfigTarget, config: ConfigObject) => void; recomputeHash: (sandboxName: string, target: AgentConfigTarget) => void; - reloadGateway: (sandboxName: string) => void; + reloadGateway: (sandboxName: string) => Promise; info?: (msg: string) => void; warn?: (msg: string) => void; } @@ -96,11 +96,11 @@ type SandboxConfigModule = { * Default reload: the same managed gateway restart `config set --restart` uses. * A container restart re-reads the freshly written in-sandbox config on start. */ -function defaultReloadGateway(sandboxName: string): void { +async function defaultReloadGateway(sandboxName: string): Promise { const { restartSandboxGateway } = require("../actions/sandbox/process-recovery") as { - restartSandboxGateway: (name: string) => { ok: boolean }; + restartSandboxGateway: (name: string) => Promise<{ ok: boolean }>; }; - restartSandboxGateway(sandboxName); + await restartSandboxGateway(sandboxName); } function resolveDeps(deps: Partial): Required { @@ -149,15 +149,15 @@ function applyAllowedOrigins(config: ConfigObject, origins: string[]): void { /** * Register the tunnel's public origin into the in-sandbox gateway * allowedOrigins so the Web UI over the tunnel is accepted. Best-effort and - * synchronous: any failure is swallowed with a warning so a working tunnel + * asynchronous: any failure is swallowed with a warning so a working tunnel * start is never turned into a hard error. Idempotent (no write/reload when the * origin list is unchanged) and OpenClaw-only. */ -export function registerTunnelOrigin( +export async function registerTunnelOrigin( sandboxName: string, tunnelUrl: string, deps: Partial = {}, -): void { +): Promise { const origin = tunnelUrlToOrigin(tunnelUrl); if (origin === null) return; @@ -185,7 +185,7 @@ export function registerTunnelOrigin( info(`Registered tunnel origin with gateway: ${origin}`); info("Reloading gateway to apply tunnel origin..."); - resolved.reloadGateway(sandboxName); + await resolved.reloadGateway(sandboxName); } catch (err) { const message = err instanceof Error ? err.message : String(err); warn( diff --git a/src/lib/tunnel/services.ts b/src/lib/tunnel/services.ts index c9ed513d6eb..64ae2e5eb5a 100644 --- a/src/lib/tunnel/services.ts +++ b/src/lib/tunnel/services.ts @@ -712,7 +712,7 @@ export async function startAll(opts: ServiceOptions = {}): Promise { const sandboxName = resolveTunnelOriginSandboxName(opts); if (sandboxName) { try { - registerTunnelOrigin(sandboxName, tunnelUrl, { info, warn }); + await registerTunnelOrigin(sandboxName, tunnelUrl, { info, warn }); } catch (err) { warn(`Could not register tunnel origin (${err instanceof Error ? err.message : err}).`); } diff --git a/src/lib/verify-deployment-agent.test.ts b/src/lib/verify-deployment-agent.test.ts index e637dbfa26c..dec9a2bd6b8 100644 --- a/src/lib/verify-deployment-agent.test.ts +++ b/src/lib/verify-deployment-agent.test.ts @@ -9,7 +9,7 @@ const NO_RETRY = { retryDelaysMs: [], sleep: async (_ms: number) => {} }; function makeDeps(overrides: Record = {}) { return { - executeSandboxCommand: (_name: string, _script: string) => ({ + executeSandboxCommand: async (_name: string, _script: string) => ({ status: 0, stdout: "200", stderr: "", @@ -32,7 +32,7 @@ describe("verifyDeployment agent dashboard probes", () => { const sandboxScripts: string[] = []; const hostProbes: Array<{ port: number; path: string }> = []; const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { sandboxScripts.push(script); if (script.includes("inference.local")) return { status: 0, stdout: "200", stderr: "" }; if (script.includes("openclaw --version")) return { status: 0, stdout: "", stderr: "" }; diff --git a/src/lib/verify-deployment-messaging.test.ts b/src/lib/verify-deployment-messaging.test.ts index 12ace2dcff3..11b43a0fbbc 100644 --- a/src/lib/verify-deployment-messaging.test.ts +++ b/src/lib/verify-deployment-messaging.test.ts @@ -10,7 +10,7 @@ const NO_RETRY = { retryDelaysMs: [], sleep: async (_ms: number) => {} }; function makeDeps(overrides: Record = {}) { return { - executeSandboxCommand: (_name: string, _script: string) => ({ + executeSandboxCommand: async (_name: string, _script: string) => ({ status: 0, stdout: "200", stderr: "", @@ -43,23 +43,23 @@ describe("verifyDeployment messaging provider checks", () => { ]); }); - it.each([ - "my-sandbox-slack-bridge", - "my-sandbox-slack-app", - ])("warns when Slack provider %s is missing", async (missingProvider) => { - const deps = makeDeps({ - getMessagingChannels: () => ["slack"], - providerExistsInGateway: (name: string) => name !== missingProvider, - }); + it.each(["my-sandbox-slack-bridge", "my-sandbox-slack-app"])( + "warns when Slack provider %s is missing", + async (missingProvider) => { + const deps = makeDeps({ + getMessagingChannels: () => ["slack"], + providerExistsInGateway: (name: string) => name !== missingProvider, + }); - const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); + const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); - expect(result.healthy).toBe(true); - expect(result.verification.messagingBridgesHealthy).toBe(false); - const msgDiag = result.diagnostics.find((d) => d.link === "messaging"); - expect(msgDiag?.status).toBe("warn"); - expect(msgDiag?.detail).toContain("slack"); - }); + expect(result.healthy).toBe(true); + expect(result.verification.messagingBridgesHealthy).toBe(false); + const msgDiag = result.diagnostics.find((d) => d.link === "messaging"); + expect(msgDiag?.status).toBe("warn"); + expect(msgDiag?.detail).toContain("slack"); + }, + ); it("does not require a gateway provider for tokenless messaging channels", async () => { const checkedProviders: string[] = []; diff --git a/src/lib/verify-deployment.test.ts b/src/lib/verify-deployment.test.ts index 698fdd24c91..8bf7e245ff4 100644 --- a/src/lib/verify-deployment.test.ts +++ b/src/lib/verify-deployment.test.ts @@ -22,7 +22,7 @@ const CUSTOM_OPENCLAW_NO_RETRY = { function makeDeps(overrides: Record = {}) { return { - executeSandboxCommand: (_name: string, _script: string) => ({ + executeSandboxCommand: async (_name: string, _script: string) => ({ status: 0, stdout: "200", stderr: "", @@ -36,7 +36,7 @@ function makeDeps(overrides: Record = {}) { function makeFailedCustomOpenClawDeps(runtimeProbeStdout: string) { return makeDeps({ - executeSandboxCommand: (_name: string, script: string) => + executeSandboxCommand: async (_name: string, script: string) => script.includes("nemoclaw-runtime-probe-v1") ? { status: 0, stdout: runtimeProbeStdout, stderr: "" } : { status: 0, stdout: "000", stderr: "" }, @@ -86,7 +86,7 @@ describe("verifyDeployment", () => { it("treats HTTP 401 as a live gateway with device auth enabled (#2342)", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "401", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "401", stderr: "" }), probeHostPort: () => 401, }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); @@ -97,7 +97,7 @@ describe("verifyDeployment", () => { it("reports unhealthy when gateway returns 000 (not running)", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "000", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "000", stderr: "" }), }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); expect(result.healthy).toBe(false); @@ -154,7 +154,7 @@ describe("verifyDeployment", () => { it("keeps generic guidance when the custom sandbox is unreachable", async () => { const deps = makeDeps({ - executeSandboxCommand: () => null, + executeSandboxCommand: async () => null, probeHostPort: () => 0, }); const result = await verifyDeployment("my-sandbox", chain, deps, CUSTOM_OPENCLAW_NO_RETRY); @@ -167,7 +167,7 @@ describe("verifyDeployment", () => { it("does not probe the custom runtime contract when diagnosis is disabled", async () => { const scripts: string[] = []; const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { scripts.push(script); return { status: 0, stdout: "000", stderr: "" }; }, @@ -179,7 +179,7 @@ describe("verifyDeployment", () => { it("hint surfaces both the in-sandbox gateway log (via nemoclaw logs) and the host OpenShell log (#3563)", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "000", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "000", stderr: "" }), }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); const gwDiag = result.diagnostics.find((d) => d.link === "gateway"); @@ -195,7 +195,7 @@ describe("verifyDeployment", () => { it("reports unhealthy when sandbox is unreachable (SSH failed)", async () => { const deps = makeDeps({ - executeSandboxCommand: () => null, + executeSandboxCommand: async () => null, }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); expect(result.healthy).toBe(false); @@ -216,7 +216,7 @@ describe("verifyDeployment", () => { it("reports unhealthy when the inference route is unreachable (#6849)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { if (script.includes("inference.local")) { return { status: 0, stdout: "000", stderr: "" }; } @@ -234,7 +234,7 @@ describe("verifyDeployment", () => { it("reports unhealthy when only the inference route returns HTTP 5xx (#6849)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => ({ + executeSandboxCommand: async (_name: string, script: string) => ({ status: 0, stdout: script.includes("inference.local") ? "503" : "200", stderr: "", @@ -275,7 +275,7 @@ describe("verifyDeployment", () => { const deps = makeDeps({ getMessagingChannels: () => ["telegram"], providerExistsInGateway: () => true, - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: true, visibleChannels: [], configuredChannels: [], @@ -295,7 +295,7 @@ describe("verifyDeployment", () => { const deps = makeDeps({ getMessagingChannels: () => ["telegram"], providerExistsInGateway: () => true, - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: true, visibleChannels: [], configuredChannels: ["telegram"], @@ -323,7 +323,7 @@ describe("verifyDeployment", () => { it("does not falsely warn when runtime probe corroborates every configured channel", async () => { const deps = makeDeps({ getMessagingChannels: () => ["telegram"], - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: true, visibleChannels: ["telegram"], configuredChannels: ["telegram"], @@ -349,7 +349,7 @@ describe("verifyDeployment", () => { const deps = makeDeps({ getMessagingChannels: () => ["telegram"], providerExistsInGateway: () => true, - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: true, visibleChannels: [], configuredChannels: ["telegram"], @@ -381,7 +381,7 @@ describe("verifyDeployment", () => { const deps = makeDeps({ getMessagingChannels: () => ["telegram"], providerExistsInGateway: () => true, - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: true, visibleChannels: [], configuredChannels: [], @@ -406,7 +406,7 @@ describe("verifyDeployment", () => { const deps = makeDeps({ getMessagingChannels: () => ["telegram"], providerExistsInGateway: () => true, - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: false, visibleChannels: [], configuredChannels: [], @@ -431,7 +431,7 @@ describe("verifyDeployment", () => { let probeCalls = 0; const deps = makeDeps({ getMessagingChannels: () => [], - probeChannelRuntimeStatus: () => { + probeChannelRuntimeStatus: async () => { probeCalls += 1; return { ok: true, @@ -460,7 +460,7 @@ describe("verifyDeployment", () => { it("detects gateway version from openclaw --version", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { if (script.includes("openclaw --version")) { return { status: 0, stdout: "2026.5.27", stderr: "" }; } @@ -473,7 +473,7 @@ describe("verifyDeployment", () => { it("extracts the gateway version from decorated output (#5896)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => + executeSandboxCommand: async (_name: string, script: string) => script.includes("openclaw --version") ? { status: 0, @@ -490,7 +490,7 @@ describe("verifyDeployment", () => { it("rejects malformed gateway version output (#5896)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => + executeSandboxCommand: async (_name: string, script: string) => script.includes("openclaw --version") ? { status: 0, stdout: "OpenClaw development build\n", stderr: "" } : { status: 0, stdout: "200", stderr: "" }, @@ -503,7 +503,7 @@ describe("verifyDeployment", () => { it("rejects gateway versions with extra dotted components (#5896)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => + executeSandboxCommand: async (_name: string, script: string) => script.includes("openclaw --version") ? { status: 0, stdout: "OpenClaw 2026.5.27.1\n", stderr: "" } : { status: 0, stdout: "200", stderr: "" }, @@ -516,7 +516,7 @@ describe("verifyDeployment", () => { it("rejects version output from a failed OpenClaw command (#5896)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => + executeSandboxCommand: async (_name: string, script: string) => script.includes("openclaw --version") ? { status: 1, stdout: "OpenClaw v2026.5.27\n", stderr: "command failed" } : { status: 0, stdout: "200", stderr: "" }, @@ -529,7 +529,7 @@ describe("verifyDeployment", () => { it("reports null version when gateway is down (skips version probe)", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "000", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "000", stderr: "" }), }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); expect(result.verification.gatewayVersion).toBeNull(); @@ -548,7 +548,7 @@ describe("verifyDeployment", () => { it("reports HTTP 502 as gateway not running", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "502", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "502", stderr: "" }), }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); expect(result.healthy).toBe(false); @@ -557,7 +557,7 @@ describe("verifyDeployment", () => { it("inference route working when HTTP response received (even 401)", async () => { const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { if (script.includes("inference.local")) { return { status: 0, stdout: "401", stderr: "" }; } @@ -571,7 +571,7 @@ describe("verifyDeployment", () => { it("keeps the inference route reachability probe below the OpenClaw cron preflight timeout", async () => { const scripts: string[] = []; const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { scripts.push(script); return { status: 0, stdout: "200", stderr: "" }; }, @@ -586,7 +586,7 @@ describe("verifyDeployment", () => { it("retries the gateway probe and recovers when the gateway comes up late (#3563)", async () => { let gatewayCalls = 0; const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { if (script.includes("openclaw --version")) { return { status: 0, stdout: "2026.5.27", stderr: "" }; } @@ -615,7 +615,7 @@ describe("verifyDeployment", () => { it("keeps polling through a cold OpenClaw gateway startup before verification (#8901)", async () => { let elapsedMs = 0; const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => ({ + executeSandboxCommand: async (_name: string, script: string) => ({ status: 0, stdout: script.includes("openclaw --version") ? "2026.5.27" @@ -661,7 +661,7 @@ describe("verifyDeployment", () => { .mockReturnValueOnce({ status: 0, stdout: "000", stderr: "" }) .mockReturnValue({ status: 0, stdout: "200", stderr: "" }); const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => + executeSandboxCommand: async (_name: string, script: string) => script.includes("inference.local") ? probeInference() : { status: 0, stdout: "200", stderr: "" }, @@ -682,7 +682,7 @@ describe("verifyDeployment", () => { it("does not retry inference after the gateway retry budget is exhausted (#6849)", async () => { const scripts: string[] = []; const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { scripts.push(script); return { status: 0, stdout: "000", stderr: "" }; }, @@ -708,7 +708,7 @@ describe("verifyDeployment", () => { it("gives up after retry budget is exhausted and surfaces the last failure detail", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "000", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "000", stderr: "" }), probeHostPort: () => 0, }); const result = await verifyDeployment("my-sandbox", chain, deps, { @@ -727,7 +727,7 @@ describe("formatVerificationDiagnostics", () => { "my-sandbox", chain, makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { if (script.includes("openclaw --version")) { return { status: 0, stdout: "2026.5.27", stderr: "" }; } @@ -743,7 +743,7 @@ describe("formatVerificationDiagnostics", () => { it("prints failure diagnostics with hints when unhealthy", async () => { const deps = makeDeps({ - executeSandboxCommand: () => ({ status: 0, stdout: "000", stderr: "" }), + executeSandboxCommand: async () => ({ status: 0, stdout: "000", stderr: "" }), probeHostPort: () => 0, }); const result = await verifyDeployment("my-sandbox", chain, deps, NO_RETRY); @@ -758,7 +758,7 @@ describe("formatVerificationDiagnostics", () => { // dropped on the healthy path; the user only learned of the failure // from the dashboard's "No channels found" panel later. const deps = makeDeps({ - executeSandboxCommand: (_name: string, script: string) => { + executeSandboxCommand: async (_name: string, script: string) => { if (script.includes("openclaw --version")) { return { status: 0, stdout: "2026.5.18", stderr: "" }; } @@ -766,7 +766,7 @@ describe("formatVerificationDiagnostics", () => { }, getMessagingChannels: () => ["telegram"], providerExistsInGateway: () => true, - probeChannelRuntimeStatus: () => ({ + probeChannelRuntimeStatus: async () => ({ ok: true, visibleChannels: [], configuredChannels: ["telegram"], diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 30837875b0e..7c5d424289d 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -116,7 +116,7 @@ export interface VerifyDeploymentDeps { * the runtime view, so a user could land on the dashboard and see * "No channels found" without any NemoClaw warning. */ - probeChannelRuntimeStatus?: () => RuntimeChannelStatus | null; + probeChannelRuntimeStatus?: () => Promise; } export interface VerifyDeploymentOptions { @@ -189,17 +189,17 @@ export function buildGatewayLogHint( * Probe the gateway /health endpoint inside the sandbox. * Uses HTTP status code extraction (not curl -sf) so 401 counts as alive. */ -function probeGatewayInSandboxOnce( +async function probeGatewayInSandboxOnce( sandboxName: string, chain: DashboardDeliveryChain, deps: VerifyDeploymentDeps, -): { reachable: boolean; httpCode: number; detail: string } { +): Promise<{ reachable: boolean; httpCode: number; detail: string }> { const port = chain.gatewayPort ?? chain.port; const endpoint = chain.gatewayHealthEndpoint ?? chain.healthEndpoint; const script = `curl -so /dev/null -w '%{http_code}' --max-time 3 ` + `http://127.0.0.1:${port}${endpoint} 2>/dev/null || echo 000`; - const result = deps.executeSandboxCommand(sandboxName, script); + const result = await deps.executeSandboxCommand(sandboxName, script); if (!result) { return { reachable: false, httpCode: 0, detail: "sandbox unreachable (SSH failed)" }; } @@ -227,23 +227,26 @@ async function verifyGatewayInSandbox( /** * Retrieve the gateway version from inside the sandbox. */ -function fetchGatewayVersion(sandboxName: string, deps: VerifyDeploymentDeps): string | null { +async function fetchGatewayVersion( + sandboxName: string, + deps: VerifyDeploymentDeps, +): Promise { const script = "openclaw --version 2>/dev/null"; - const result = deps.executeSandboxCommand(sandboxName, script); + const result = await deps.executeSandboxCommand(sandboxName, script); if (!result || result.status !== 0 || !result.stdout.trim()) return null; return parseVersionFromText(result.stdout, "openclaw --version"); } type InferenceRouteStatus = "ok" | "unreachable" | "unhealthy"; -function probeInferenceRouteOnce( +async function probeInferenceRouteOnce( sandboxName: string, deps: VerifyDeploymentDeps, -): { status: InferenceRouteStatus; detail: string } { +): Promise<{ status: InferenceRouteStatus; detail: string }> { const script = `HTTP_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time ${INFERENCE_ROUTE_REACHABILITY_MAX_SECONDS} ` + `https://inference.local/v1/models 2>/dev/null || echo 000); echo $HTTP_CODE`; - const result = deps.executeSandboxCommand(sandboxName, script); + const result = await deps.executeSandboxCommand(sandboxName, script); if (!result) { return { status: "unreachable", detail: "sandbox unreachable" }; } @@ -440,7 +443,7 @@ async function verifyMessagingBridges( let runtimeProbeFailed = false; let runtimeProbeOnlyConfig = false; if (deps.probeChannelRuntimeStatus) { - const runtime = deps.probeChannelRuntimeStatus(); + const runtime = await deps.probeChannelRuntimeStatus(); if (runtime) { runtimeProbeDetail = runtime.detail; if (runtime.ok) { @@ -575,7 +578,7 @@ export async function verifyDeployment( // exec cannot safely prove that image artifacts are absent. const runtimeDiagnosis = !gateway.reachable && options.diagnoseCustomOpenClawRuntime - ? classifyOpenClawRuntimeFailure(sandboxName, deps.executeSandboxCommand) + ? await classifyOpenClawRuntimeFailure(sandboxName, deps.executeSandboxCommand) : null; const customRuntimeHints = runtimeDiagnosis ? buildCustomOpenClawRuntimeFailureHints(runtimeDiagnosis) @@ -590,7 +593,7 @@ export async function verifyDeployment( }); // 2. Gateway version (cosmetic — not a health signal) - const gatewayVersion = gateway.reachable ? fetchGatewayVersion(sandboxName, deps) : null; + const gatewayVersion = gateway.reachable ? await fetchGatewayVersion(sandboxName, deps) : null; // 3. Dashboard reachable from host (port forward) // A port forward cannot repair an image that has no managed gateway runtime, diff --git a/test/channels/channels-add-bridge-lifecycle.test.ts b/test/channels/channels-add-bridge-lifecycle.test.ts index 653f43cf5f5..ed311fd6fd1 100644 --- a/test/channels/channels-add-bridge-lifecycle.test.ts +++ b/test/channels/channels-add-bridge-lifecycle.test.ts @@ -360,7 +360,7 @@ beforeEach(() => { attempted: false, }); - vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ + vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue({ status: 0, stdout: "", stderr: "", diff --git a/test/channels/channels-add-preset.test.ts b/test/channels/channels-add-preset.test.ts index ebb56633ae7..b0f936b6416 100644 --- a/test/channels/channels-add-preset.test.ts +++ b/test/channels/channels-add-preset.test.ts @@ -293,7 +293,7 @@ beforeEach(() => { execSpy = vi .spyOn(processRecovery, "executeSandboxExecCommand") - .mockImplementation((_name, command) => { + .mockImplementation(async (_name, command) => { return command.includes("/sandbox/.openclaw/openclaw.json") ? { status: 0, stdout: JSON.stringify(testConfig), stderr: "" } : command.includes("tail -n 400") && command.includes("/tmp/gateway.log") diff --git a/test/cli/connect-recovery.test.ts b/test/cli/connect-recovery.test.ts index 5c09d15bb43..dbf7d39cda8 100644 --- a/test/cli/connect-recovery.test.ts +++ b/test/cli/connect-recovery.test.ts @@ -290,6 +290,7 @@ describe("CLI connect recovery process contracts", () => { expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe( true, ); + expect(calls.some((call) => call.includes("inference.local/v1/models"))).toBe(true); expect(calls).not.toContain("sandbox ssh-config alpha"); expect(calls).not.toContain("sandbox connect alpha"); expect(fs.existsSync(sshMarkerFile)).toBe(false); diff --git a/test/cli/connect-terminal-agent.test.ts b/test/cli/connect-terminal-agent.test.ts index 9d47a886237..26f0598bb30 100644 --- a/test/cli/connect-terminal-agent.test.ts +++ b/test/cli/connect-terminal-agent.test.ts @@ -50,7 +50,7 @@ describe("CLI dispatch for terminal agents", () => { " echo ' Phase: Ready'", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "-n" ] && [ "$4" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && { [ "$3" = "-n" ] || [ "$3" = "--name" ]; } && [ "$4" = "alpha" ]; then', // The smoke command is always the final argument. Read it from the end // so the stub does not depend on how many flags precede it (#8624). ' cmd="${*: -1}"', diff --git a/test/credentials/credential-migration-reconciliation.test.ts b/test/credentials/credential-migration-reconciliation.test.ts index 839eb461f50..042115c030d 100644 --- a/test/credentials/credential-migration-reconciliation.test.ts +++ b/test/credentials/credential-migration-reconciliation.test.ts @@ -73,7 +73,7 @@ async function finalizeMigration( toSessionUpdates: (updates) => updates, removeLegacyCredentialsFile, cleanupStaleHostFiles: () => undefined, - checkAndRecoverSandboxProcesses: () => undefined, + checkAndRecoverSandboxProcesses: async () => undefined, settleOrdinaryOpenClawPairing: async () => ({ kind: "settled" }), ordinaryOpenClawPairingIncompleteMessage: () => "OpenClaw onboarding is incomplete; resume onboarding.", @@ -87,7 +87,7 @@ async function finalizeMigration( formatVerificationDiagnostics: () => [], isDeploymentHealthy: () => true, reportDeploymentReadiness: () => undefined, - verifyWebSearchInsideSandbox: () => true, + verifyWebSearchInsideSandbox: async () => true, printDashboard: () => undefined, error: () => undefined, log: () => undefined, diff --git a/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts b/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts index dc77d766756..8f1cdf4c784 100644 --- a/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts +++ b/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts @@ -105,16 +105,12 @@ function isLegacyKeepaliveHandoffReceiptCandidate( typeof value === "object" && value !== null && !Array.isArray(value) && - ["oldContainerId", "newContainerId", "startupCommand"].some((key) => - Object.hasOwn(value, key), - ) + ["oldContainerId", "newContainerId", "startupCommand"].some((key) => Object.hasOwn(value, key)) ); } /** Read one final machine receipt without treating recreation progress as JSON. */ -export function parseLegacyKeepaliveHandoffReceipt( - output: string, -): LegacyKeepaliveHandoffReceipt { +export function parseLegacyKeepaliveHandoffReceipt(output: string): LegacyKeepaliveHandoffReceipt { const lines = output .split(/\r?\n/u) .map((line) => line.trim()) @@ -310,10 +306,10 @@ function legacyKeepaliveDockerCapture( }; } -export function createLegacyKeepaliveFixture( +export async function createLegacyKeepaliveFixture( options: LegacyKeepaliveFixtureOptions, deps: Partial = defaultDeps, -): ReturnType { +): Promise>> { requireFixtureInput(options.sandboxName.trim() !== "", "sandbox name is required"); requireFixtureInput( DOCKER_CONTAINER_ID_PATTERN.test(options.expectedContainerId), @@ -324,7 +320,7 @@ export function createLegacyKeepaliveFixture( const dockerCapture = deps.dockerCapture ?? defaultDeps.dockerCapture; const runOpenshell = deps.runOpenshell ?? defaultDeps.runOpenshell; const runCaptureOpenshell = deps.runCaptureOpenshell ?? defaultDeps.runCaptureOpenshell; - const result = recreate( + const result = await recreate( { sandboxName: options.sandboxName, expectedOldContainerId: options.expectedContainerId, @@ -357,13 +353,13 @@ export function createLegacyKeepaliveFixture( return result; } -function main(): void { +async function main(): Promise { const [sandboxName, expectedContainerId, ...extraArgs] = process.argv.slice(2); requireFixtureInput( sandboxName !== undefined && expectedContainerId !== undefined && extraArgs.length === 0, "usage: gateway-guard-legacy-keepalive-fixture ", ); - const result = createLegacyKeepaliveFixture({ sandboxName, expectedContainerId }); + const result = await createLegacyKeepaliveFixture({ sandboxName, expectedContainerId }); process.stdout.write( `${JSON.stringify({ oldContainerId: result.oldContainerId, @@ -377,11 +373,9 @@ const invokedAsScript = process.argv[1] !== undefined && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href; if (invokedAsScript) { - try { - main(); - } catch (error: unknown) { + main().catch((error: unknown) => { const detail = error instanceof Error ? error.message : String(error); process.stderr.write(`${redactString(detail)}\n`); process.exitCode = 1; - } + }); } diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index d12dc82ff3d..5d112828ebf 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -220,6 +220,7 @@ }, { "live": "test/e2e/live/gateway-guard-recovery.test.ts", + "liveSources": ["test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts"], "fast": [ "src/lib/actions/sandbox/supervisor-relaunch.test.ts", "src/lib/onboard/docker-gpu-patch-finalize.test.ts", diff --git a/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts b/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts index 2c223b7038f..c3ec384e1af 100644 --- a/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts +++ b/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts @@ -187,23 +187,25 @@ describe("gateway guard legacy keepalive fixture", () => { ); }); - it("recreates only the pinned sandbox container with the reviewed supervisor and legacy workload (#9364)", () => { + it("recreates only the pinned sandbox container with the reviewed supervisor and legacy workload (#9364)", async () => { const dockerCapture = vi.fn(() => managedRuntimeInspect()); - const recreate = vi.fn((_, deps: Parameters[1]) => { - const rewritten = JSON.parse( - deps?.dockerCapture?.(["inspect", "--type", "container", OLD_CONTAINER_ID], { - ignoreError: true, - }) ?? "null", - ); - expect(rewritten[0].Config).toMatchObject({ - Entrypoint: ["/opt/openshell/bin/openshell-sandbox"], - Cmd: ["--workdir", "/sandbox"], - Env: [MANAGED_RUNTIME_COMMAND_ENV, "OPENSHELL_SANDBOX_UID=", "OPENSHELL_SANDBOX_GID="], - }); - return successfulResult(); - }); + const recreate = vi.fn( + async (_, deps: Parameters[1]) => { + const rewritten = JSON.parse( + deps?.dockerCapture?.(["inspect", "--type", "container", OLD_CONTAINER_ID], { + ignoreError: true, + }) ?? "null", + ); + expect(rewritten[0].Config).toMatchObject({ + Entrypoint: ["/opt/openshell/bin/openshell-sandbox"], + Cmd: ["--workdir", "/sandbox"], + Env: [MANAGED_RUNTIME_COMMAND_ENV, "OPENSHELL_SANDBOX_UID=", "OPENSHELL_SANDBOX_GID="], + }); + return successfulResult(); + }, + ) as unknown as LegacyKeepaliveFixtureDeps["recreate"]; - const result = createLegacyKeepaliveFixture( + const result = await createLegacyKeepaliveFixture( { sandboxName: "e2e-2701", expectedContainerId: OLD_CONTAINER_ID, @@ -534,10 +536,10 @@ describe("gateway guard legacy keepalive fixture", () => { result: { ...successfulResult(), newContainerId: OLD_CONTAINER_ID }, error: "did not replace the container", }, - ])("fails closed for $name", ({ result, error }) => { - const recreate = vi.fn(() => result) as LegacyKeepaliveFixtureDeps["recreate"]; + ])("fails closed for $name", async ({ result, error }) => { + const recreate = vi.fn(async () => result) as unknown as LegacyKeepaliveFixtureDeps["recreate"]; - expect(() => + await expect( createLegacyKeepaliveFixture( { sandboxName: "e2e-2701", @@ -545,13 +547,15 @@ describe("gateway guard legacy keepalive fixture", () => { }, { recreate }, ), - ).toThrow(error); + ).rejects.toThrow(error); }); - it("rejects an abbreviated container ID before recreation", () => { - const recreate = vi.fn(() => successfulResult()); + it("rejects an abbreviated container ID before recreation", async () => { + const recreate = vi.fn(async () => + successfulResult(), + ) as unknown as LegacyKeepaliveFixtureDeps["recreate"]; - expect(() => + await expect( createLegacyKeepaliveFixture( { sandboxName: "e2e-2701", @@ -559,7 +563,7 @@ describe("gateway guard legacy keepalive fixture", () => { }, { recreate }, ), - ).toThrow("expected container ID must be a full Docker container ID"); + ).rejects.toThrow("expected container ID must be a full Docker container ID"); expect(recreate).not.toHaveBeenCalled(); }); diff --git a/test/helpers/managed-image-buildless-e2e.ts b/test/helpers/managed-image-buildless-e2e.ts index 49343f964fd..8ae3ddd572f 100644 --- a/test/helpers/managed-image-buildless-e2e.ts +++ b/test/helpers/managed-image-buildless-e2e.ts @@ -606,6 +606,36 @@ childProcess.spawn = (command, args = [], options = {}) => { return child; }; +const sandboxCommandCli = require( + ${source("src/lib/adapters/openshell/sandbox-command-cli.ts")}, +); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +replace(sandboxCommandCli, "createCliOpenShellSandboxCommandExecutor", (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const gatewayArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const command = [ + "openshell", + "sandbox", + "exec", + "--name", + request.sandboxName, + ...gatewayArgs, + "--", + ...request.command, + ]; + const stdout = runner.runCapture(command); + return { + outcome: { kind: "completed", exitCode: 0 }, + stdout: String(stdout || ""), + stderr: "", + }; + }, + }; +}); + const { loadAgent } = require(${source("src/lib/agent/defs.ts")}); const { createSandbox } = require(${source("src/lib/onboard.ts")}); @@ -843,7 +873,7 @@ function assertManagedLaunch( ); expect(sandboxExecCommands).toHaveLength(1); expect(sandboxExecCommands[0]).toContain( - `sandbox exec --name ${bootstrapRequest?.sandboxName} --gateway nemoclaw -- /usr/local/bin/dcode identity`, + `sandbox exec --name ${bootstrapRequest?.sandboxName} -g nemoclaw -- /usr/local/bin/dcode identity`, ); } else { expect( @@ -854,7 +884,7 @@ function assertManagedLaunch( expect( result.payload.runnerCommands.some((command) => command.includes( - `sandbox exec -g nemoclaw --name ${bootstrapRequest?.sandboxName} -- true`, + `sandbox exec --name ${bootstrapRequest?.sandboxName} -g nemoclaw -- true`, ), ), ).toBe(true); diff --git a/test/mcp/mcp-adapter-teardown-rollback.test.ts b/test/mcp/mcp-adapter-teardown-rollback.test.ts index 12b3b605554..56c0ef57c4b 100644 --- a/test/mcp/mcp-adapter-teardown-rollback.test.ts +++ b/test/mcp/mcp-adapter-teardown-rollback.test.ts @@ -48,14 +48,14 @@ const runtimeSelection = { gatewayName: "nemoclaw-8091", workspace: "default" } describe("MCP adapter teardown rollback", () => { beforeEach(() => { testState.observeCredentialRevision.mockReset(); - testState.registerAdapter.mockReset(); + testState.registerAdapter.mockReset().mockResolvedValue("v1"); }); - it("restores the adapter with the fresh opaque credential revision (#10300)", () => { + it("restores the adapter with the fresh opaque credential revision (#10300)", async () => { const opaqueRevision = "v4067750153477477215"; - testState.observeCredentialRevision.mockReturnValue(opaqueRevision); + testState.observeCredentialRevision.mockResolvedValue(opaqueRevision); - const failures = rollbackScrubbedMcpAdapters( + const failures = await rollbackScrubbedMcpAdapters( "alpha", sandbox, [{ ...entry, credentialRevision: "v1" }], @@ -76,10 +76,10 @@ describe("MCP adapter teardown rollback", () => { it.each(["absent", "canonical"] as const)( "reports rollback failure when fresh credential authority is %s (#10300)", - (observation) => { - testState.observeCredentialRevision.mockReturnValue(observation); + async (observation) => { + testState.observeCredentialRevision.mockResolvedValue(observation); - const failures = rollbackScrubbedMcpAdapters( + const failures = await rollbackScrubbedMcpAdapters( "alpha", sandbox, [{ ...entry, credentialRevision: "v4067750153477477215" }], diff --git a/test/mcp/mcp-destroy-lifecycle.test.ts b/test/mcp/mcp-destroy-lifecycle.test.ts index 7cf03868b0a..14e1b0b626b 100644 --- a/test/mcp/mcp-destroy-lifecycle.test.ts +++ b/test/mcp/mcp-destroy-lifecycle.test.ts @@ -1023,7 +1023,7 @@ describe("authenticated MCP sandbox destroy lifecycle", () => { expect(result?.entries).toEqual([bridgeEntries.github]); expect(testState.executeSandboxExecCommand).toHaveBeenCalledOnce(); expect(testState.executeSandboxExecCommand).toHaveBeenCalledWith("alpha", ":", undefined, { - allowLocalDockerFallback: false, + localDockerFallbackPolicy: "never", runtimeSelection: testState.runtimeSelection, }); expect(testState.executeSandboxCommand).toHaveBeenCalledWith("alpha", ":", { diff --git a/test/onboarding/config-set.test.ts b/test/onboarding/config-set.test.ts index ba1da934cd3..98b66b1c5f7 100644 --- a/test/onboarding/config-set.test.ts +++ b/test/onboarding/config-set.test.ts @@ -174,10 +174,10 @@ describe("config set helpers", () => { }); describe("restartSandboxAgentAfterConfigSet", () => { - it("routes --restart through the managed gateway supervisor flow", () => { + it("routes --restart through the managed gateway supervisor flow", async () => { const calls: string[] = []; - restartSandboxAgentAfterConfigSet("alpha", "openclaw", (sandboxName: string) => { + await restartSandboxAgentAfterConfigSet("alpha", "openclaw", async (sandboxName: string) => { calls.push(sandboxName); return { ok: true }; }); @@ -185,10 +185,10 @@ describe("config set helpers", () => { expect(calls).toEqual(["alpha"]); }); - it("fails with a written-but-not-applied message and a retry hint when the restart fails", () => { + it("fails with a written-but-not-applied message and a retry hint when the restart fails", async () => { let thrown: unknown; try { - restartSandboxAgentAfterConfigSet("alpha", "openclaw", () => ({ ok: false })); + await restartSandboxAgentAfterConfigSet("alpha", "openclaw", async () => ({ ok: false })); } catch (error) { thrown = error; } diff --git a/test/onboarding/docker-final-handoff-lifecycle.test.ts b/test/onboarding/docker-final-handoff-lifecycle.test.ts index b80e4485f15..83a77d1b5b6 100644 --- a/test/onboarding/docker-final-handoff-lifecycle.test.ts +++ b/test/onboarding/docker-final-handoff-lifecycle.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../../src/lib/adapters/openshell/sandbox-command"; import { createDockerFinalHandoffCaptureFixture, createDockerFinalHandoffRunFixture, @@ -13,8 +14,35 @@ import { recreateOpenShellDockerSandboxWithStartupCommand } from "../../src/lib/ const OLD_CONTAINER_ID = "a".repeat(64); const NEW_CONTAINER_ID = "b".repeat(64); +function commandExecutorThrough( + runOpenshell: ( + args: string[], + opts?: Record, + ) => { status: number | null; stdout?: string; stderr?: string }, +): OpenShellSandboxBufferedCommandExecutor { + return { + runBuffered: vi.fn(async (request) => { + const result = runOpenshell( + ["sandbox", "exec", "-n", request.sandboxName, "--", ...request.command], + { ignoreError: true, suppressOutput: true }, + ); + return { + outcome: + result.status === null + ? { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "failed" }, + } + : { kind: "completed" as const, exitCode: result.status }, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; + }), + }; +} + describe("Docker final handoff lifecycle integration", () => { - it("commits only between authoritative OpenShell stop and start receipts (#10153)", () => { + it("commits only between authoritative OpenShell stop and start receipts (#10153)", async () => { const events: string[] = []; const dockerStop = vi.fn((containerId: string) => { events.push( @@ -44,7 +72,7 @@ describe("Docker final handoff lifecycle integration", () => { return { status: 0 }; }); - const result = recreateOpenShellDockerSandboxWithStartupCommand( + const result = await recreateOpenShellDockerSandboxWithStartupCommand( { sandboxName: "alpha", expectedOldContainerId: OLD_CONTAINER_ID, @@ -61,6 +89,7 @@ describe("Docker final handoff lifecycle integration", () => { dockerStart, runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), now: () => new Date("2026-05-12T00:00:00Z"), detectSandboxFallbackDns: vi.fn(() => null), @@ -89,7 +118,7 @@ describe("Docker final handoff lifecycle integration", () => { expect(dockerStart).not.toHaveBeenCalled(); }); - it("does not cross the final Docker commit when authoritative OpenShell stop fails (#10153)", () => { + it("does not cross the final Docker commit when authoritative OpenShell stop fails (#10153)", async () => { const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn(() => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); @@ -101,7 +130,7 @@ describe("Docker final handoff lifecycle integration", () => { let failure: unknown; try { - recreateOpenShellDockerSandboxWithStartupCommand( + await recreateOpenShellDockerSandboxWithStartupCommand( { sandboxName: "alpha", expectedOldContainerId: OLD_CONTAINER_ID, @@ -118,6 +147,7 @@ describe("Docker final handoff lifecycle integration", () => { dockerStart, runCaptureOpenshell, runOpenshell, + commandExecutor: commandExecutorThrough(runOpenshell), sleep: vi.fn(), now: () => new Date("2026-05-12T00:00:00Z"), detectSandboxFallbackDns: vi.fn(() => null), diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index 9678b647e4b..4b9d5d8c783 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -200,6 +200,19 @@ describe("fresh create identity", () => { const dockerExecPath = JSON.stringify( path.join(repoRoot, "src", "lib", "adapters", "docker", "exec.ts"), ); + const sandboxCommandCliPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "adapters", "openshell", "sandbox-command-cli.ts"), + ); + const managedWorkloadOnboardPath = JSON.stringify( + path.join( + repoRoot, + "src", + "lib", + "onboard", + "managed-workload", + "onboard-orchestration.ts", + ), + ); const doctorHostCommandPath = JSON.stringify( path.join(repoRoot, "src", "lib", "actions", "sandbox", "doctor-host-command.ts"), ); @@ -371,6 +384,56 @@ runner.run = (command, opts = {}) => { if (_n(command).includes("forward list")) return "SANDBOX BIND PORT PID STATUS"; return ""; }; +const sandboxCommandCli = require(${sandboxCommandCliPath}); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +sandboxCommandCli.createCliOpenShellSandboxCommandExecutor = (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const gatewayArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const stdout = runner.runCapture([ + "openshell", "sandbox", "exec", "--name", request.sandboxName, + ...gatewayArgs, "--", ...request.command, + ]); + return { outcome: { kind: "completed", exitCode: 0 }, stdout: String(stdout || ""), stderr: "" }; + }, + }; +}; +const managedWorkloadOnboard = require(${managedWorkloadOnboardPath}); +const createManagedStateVolumeLifecycle = + managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle; +const managedLifecycleVolumes = new Map(); +managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = {}) => + createManagedStateVolumeLifecycle(input, { + ...deps, + runContainerEngine: (args) => { + const name = String(args.at(-1)); + if (args[0] === "inspect") { + const volume = managedLifecycleVolumes.get(name); + return volume + ? { status: 0, stdout: JSON.stringify(volume), stderr: "" } + : { status: 1, stdout: "", stderr: "no such volume" }; + } + if (args[0] === "create") { + const labels = {}; + for (let index = 1; index < args.length - 1; index += 1) { + if (args[index] !== "--label") continue; + const label = String(args[index + 1]); + const separator = label.indexOf("="); + labels[label.slice(0, separator)] = label.slice(separator + 1); + index += 1; + } + managedLifecycleVolumes.set(name, { Name: name, Labels: labels }); + return { status: 0, stdout: name, stderr: "" }; + } + if (args[0] === "rm") { + managedLifecycleVolumes.delete(name); + return { status: 0, stdout: name, stderr: "" }; + } + return { status: 1, stdout: "", stderr: "unexpected volume command" }; + }, + }); const retainedRegistryEntry = recoveryReentry && fs.existsSync(${JSON.stringify(payloadPath)}) ? JSON.parse(fs.readFileSync(${JSON.stringify(payloadPath)}, "utf8")).recoveryRegistryEntry : null; diff --git a/test/onboarding/onboard-fsm-live-slices.test.ts b/test/onboarding/onboard-fsm-live-slices.test.ts index 8b68ea11242..6db7fdc1710 100644 --- a/test/onboarding/onboard-fsm-live-slices.test.ts +++ b/test/onboarding/onboard-fsm-live-slices.test.ts @@ -257,7 +257,17 @@ if (scenario.mode === "dashboard-port-composition") { ensureFinalizationAgentDashboardForward: nextDashboardForward, }; }; - require(${agentOnboardPath}).handleAgentSetup = async () => undefined; + require(${agentOnboardPath}).handleAgentSetup = async ( + _sandboxName, + _model, + _provider, + _agent, + _resume, + _preparedSandbox, + context, + ) => { + called.push("agent-executor:" + typeof context.sandboxCommandExecutor?.runBuffered); + }; require(${agentSelectionPath}).createOnboardAgentSelector = () => async () => ({ name: "hermes", displayName: "Hermes Agent", @@ -660,6 +670,7 @@ describe("live onboard FSM slice boundaries", () => { assert.deepEqual(runSliceProbe({ slice: "final", mode: "dashboard-port-composition" }), [ "initial:init", "core", + "agent-executor:function", "forward-port:18791", "registry-port:18791", "dashboard-url:http://127.0.0.1:18791/", diff --git a/test/onboarding/onboard-prepared-build-context.test.ts b/test/onboarding/onboard-prepared-build-context.test.ts index a1216d2b3f4..cdb3d8131f8 100644 --- a/test/onboarding/onboard-prepared-build-context.test.ts +++ b/test/onboarding/onboard-prepared-build-context.test.ts @@ -68,6 +68,9 @@ function runPreparedContextScenario(scenario: PreparedContextScenario): Prepared path.join(repoRoot, "src", "lib", "onboard", "docker-gpu-sandbox-create.ts"), ); const waitPath = JSON.stringify(path.join(repoRoot, "src", "lib", "core", "wait.ts")); + const sandboxCommandCliPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "adapters", "openshell", "sandbox-command-cli.ts"), + ); const onboardScriptMocksPath = JSON.stringify( path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), ); @@ -78,6 +81,7 @@ const childProcess = require("node:child_process"); const { EventEmitter } = require("node:events"); const registry = require(${registryPath}); const fixtureMocks = require(${onboardScriptMocksPath}); +fixtureMocks.mockStandaloneGatewayTeardownAuthority(); const scenario = ${JSON.stringify(scenario)}; const buildCtx = ${JSON.stringify(preparedBuildCtx)}; const buildId = ${JSON.stringify(buildId)}; @@ -165,11 +169,10 @@ runner.runCapture = (command) => { const sandboxCapture = createdSandbox.capture(command); if (sandboxCapture !== null) return sandboxCapture; if ( - normalized.includes( - "sandbox exec --name " + - sandboxName + - " --gateway nemoclaw -- /usr/local/bin/dcode identity", - ) + normalized === + "openshell sandbox exec --name " + + sandboxName + + " -g nemoclaw -- /usr/local/bin/dcode identity" ) { return [ "Route: inference", @@ -180,6 +183,28 @@ runner.runCapture = (command) => { } return ""; }; +const sandboxCommandCli = require(${sandboxCommandCliPath}); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +sandboxCommandCli.createCliOpenShellSandboxCommandExecutor = (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const gatewayArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const stdout = runner.runCapture([ + "openshell", + "sandbox", + "exec", + "--name", + request.sandboxName, + ...gatewayArgs, + "--", + ...request.command, + ]); + return { outcome: { kind: "completed", exitCode: 0 }, stdout: String(stdout || ""), stderr: "" }; + }, + }; +}; registry.getDefault = () => null; registry.listExtraProviders = () => []; preflight.checkPortAvailable = async () => ({ ok: true }); diff --git a/test/onboarding/onboard-preset-diff.test.ts b/test/onboarding/onboard-preset-diff.test.ts index e824b648cfc..8f0021bcb8b 100644 --- a/test/onboarding/onboard-preset-diff.test.ts +++ b/test/onboarding/onboard-preset-diff.test.ts @@ -87,7 +87,7 @@ async function runPolicyScenario({ note: () => undefined, isNonInteractive: () => true, waitForSandboxReady: async () => ({ ready: true, reason: "ready", error: null }), - waitForSandboxControlPlaneReady: () => true, + waitForSandboxControlPlaneReady: async () => true, syncPresetSelection: (_sandboxName, current, selected) => { const currentSet = new Set(current); const selectedSet = new Set(selected); diff --git a/test/onboarding/onboard-reservation-recreate.test.ts b/test/onboarding/onboard-reservation-recreate.test.ts index 781d40f7098..749893d3d77 100644 --- a/test/onboarding/onboard-reservation-recreate.test.ts +++ b/test/onboarding/onboard-reservation-recreate.test.ts @@ -17,6 +17,12 @@ const repoRoot = path.join(import.meta.dirname, "../.."); const onboardScriptMocksPath = JSON.stringify( path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), ); +const sandboxCommandCliPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "adapters", "openshell", "sandbox-command-cli.ts"), +); +const managedWorkloadOnboardPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "managed-workload", "onboard-orchestration.ts"), +); describe("onboard sandbox recreate reservation safety", () => { it.each([ @@ -125,6 +131,56 @@ runner.runCapture = (command) => { } return ""; }; +const sandboxCommandCli = require(${sandboxCommandCliPath}); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +sandboxCommandCli.createCliOpenShellSandboxCommandExecutor = (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const gatewayArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const stdout = runner.runCapture([ + "openshell", "sandbox", "exec", "--name", request.sandboxName, + ...gatewayArgs, "--", ...request.command, + ]); + return { outcome: { kind: "completed", exitCode: 0 }, stdout: String(stdout || ""), stderr: "" }; + }, + }; +}; +const managedWorkloadOnboard = require(${managedWorkloadOnboardPath}); +const createManagedStateVolumeLifecycle = + managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle; +const managedVolumes = new Map(); +managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = {}) => + createManagedStateVolumeLifecycle(input, { + ...deps, + runContainerEngine: (args) => { + const name = String(args.at(-1)); + if (args[0] === "inspect") { + const volume = managedVolumes.get(name); + return volume + ? { status: 0, stdout: JSON.stringify(volume), stderr: "" } + : { status: 1, stdout: "", stderr: "no such volume" }; + } + if (args[0] === "create") { + const labels = {}; + for (let index = 1; index < args.length - 1; index += 1) { + if (args[index] !== "--label") continue; + const label = String(args[index + 1]); + const separator = label.indexOf("="); + labels[label.slice(0, separator)] = label.slice(separator + 1); + index += 1; + } + managedVolumes.set(name, { Name: name, Labels: labels }); + return { status: 0, stdout: name, stderr: "" }; + } + if (args[0] === "rm") { + managedVolumes.delete(name); + return { status: 0, stdout: name, stderr: "" }; + } + return { status: 1, stdout: "", stderr: "unexpected volume command" }; + }, + }); require(${onboardScriptMocksPath}).mockDockerSandboxLifecycleReleaseFromRunner(); onboardSession.saveSession(onboardSession.createSession({ @@ -478,6 +534,56 @@ runner.runCapture = (command) => { const mocked = fixtureMocks.mockOnboardRunCapture(command, { defaultCurlOutput: "ok" }); return mocked === null ? "" : mocked; }; +const sandboxCommandCli = require(${sandboxCommandCliPath}); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +sandboxCommandCli.createCliOpenShellSandboxCommandExecutor = (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const gatewayArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const stdout = runner.runCapture([ + "openshell", "sandbox", "exec", "--name", request.sandboxName, + ...gatewayArgs, "--", ...request.command, + ]); + return { outcome: { kind: "completed", exitCode: 0 }, stdout: String(stdout || ""), stderr: "" }; + }, + }; +}; +const managedWorkloadOnboard = require(${managedWorkloadOnboardPath}); +const createManagedStateVolumeLifecycle = + managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle; +const managedVolumes = new Map(); +managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = {}) => + createManagedStateVolumeLifecycle(input, { + ...deps, + runContainerEngine: (args) => { + const name = String(args.at(-1)); + if (args[0] === "inspect") { + const volume = managedVolumes.get(name); + return volume + ? { status: 0, stdout: JSON.stringify(volume), stderr: "" } + : { status: 1, stdout: "", stderr: "no such volume" }; + } + if (args[0] === "create") { + const labels = {}; + for (let index = 1; index < args.length - 1; index += 1) { + if (args[index] !== "--label") continue; + const label = String(args[index + 1]); + const separator = label.indexOf("="); + labels[label.slice(0, separator)] = label.slice(separator + 1); + index += 1; + } + managedVolumes.set(name, { Name: name, Labels: labels }); + return { status: 0, stdout: name, stderr: "" }; + } + if (args[0] === "rm") { + managedVolumes.delete(name); + return { status: 0, stdout: name, stderr: "" }; + } + return { status: 1, stdout: "", stderr: "unexpected volume command" }; + }, + }); const realProcessKill = process.kill.bind(process); process.kill = (pid, signal) => { diff --git a/test/onboarding/onboard-terminal-dashboard.test.ts b/test/onboarding/onboard-terminal-dashboard.test.ts index c9d9732aca5..69e9443080c 100644 --- a/test/onboarding/onboard-terminal-dashboard.test.ts +++ b/test/onboarding/onboard-terminal-dashboard.test.ts @@ -41,6 +41,9 @@ function runTerminalDashboardScenario(scenario: "create" | "reuse") { const sandboxCreateStreamPath = JSON.stringify( path.join(repoRoot, "src", "lib", "sandbox", "create-stream.ts"), ); + const sandboxCommandCliPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "adapters", "openshell", "sandbox-command-cli.ts"), + ); const onboardScriptMocksPath = JSON.stringify( path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), ); @@ -55,6 +58,7 @@ const path = require("node:path"); const runner = require(${runnerPath}); const registry = require(${registryPath}); const fixtureMocks = require(${onboardScriptMocksPath}); +fixtureMocks.mockStandaloneGatewayTeardownAuthority(); const agentDefs = require(${agentDefsPath}); const agentOnboard = require(${agentOnboardPath}); const dockerGpuSandboxCreate = require(${dockerGpuSandboxCreatePath}); @@ -142,13 +146,7 @@ runner.runCapture = (command) => { const sandboxCapture = createdSandbox.capture(command); if (sandboxCapture !== null) return sandboxCapture; commands.push({ command: normalized, env: null }); - if ( - normalized.includes( - "sandbox exec --name " + - sandboxName + - " --gateway nemoclaw -- /usr/local/bin/dcode identity", - ) - ) { + if (normalized.includes("sandbox exec") && normalized.includes("dcode identity")) { return [ "Route: inference", "Provider: nvidia-prod", @@ -160,6 +158,29 @@ runner.runCapture = (command) => { return ""; }; +const sandboxCommandCli = require(${sandboxCommandCliPath}); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +sandboxCommandCli.createCliOpenShellSandboxCommandExecutor = (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const gatewayArgs = request.target.kind === "named" ? ["-g", request.target.gatewayName] : []; + const stdout = runner.runCapture([ + "openshell", + "sandbox", + "exec", + "--name", + request.sandboxName, + ...gatewayArgs, + "--", + ...request.command, + ]); + return { outcome: { kind: "completed", exitCode: 0 }, stdout: String(stdout || ""), stderr: "" }; + }, + }; +}; + registry.getSandbox = () => scenario === "reuse" ? fixtureMocks.sandboxLifecycleFixture({ diff --git a/test/process-recovery/process-recovery-custom-agent.test.ts b/test/process-recovery/process-recovery-custom-agent.test.ts index 4dd675f8103..e2e9ca64538 100644 --- a/test/process-recovery/process-recovery-custom-agent.test.ts +++ b/test/process-recovery/process-recovery-custom-agent.test.ts @@ -95,14 +95,14 @@ function spawnResultForCommand( : { status: 1, stdout: "", stderr: "" }; } -function withFakeOpenshellBinary(fn: () => T): T { +async function withFakeOpenshellBinary(fn: () => Promise): Promise { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); const bin = path.join(dir, "openshell"); const previous = process.env.NEMOCLAW_OPENSHELL_BIN; fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); process.env.NEMOCLAW_OPENSHELL_BIN = bin; try { - return fn(); + return await fn(); } finally { restoreEnvValue("NEMOCLAW_OPENSHELL_BIN", previous); fs.rmSync(dir, { recursive: true, force: true }); @@ -110,7 +110,7 @@ function withFakeOpenshellBinary(fn: () => T): T { } describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { - it("retains SSH health-probe compatibility for an explicitly loaded custom gateway agent", () => { + it("retains SSH health-probe compatibility for an explicitly loaded custom gateway agent", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.ts"); const agentRuntime = requireSource("../../src/lib/agent/runtime.ts"); const registry = requireSource("../../src/lib/state/registry.ts"); @@ -153,9 +153,9 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { output: "SANDBOX BIND PORT PID STATUS", }); - expect( + await expect( withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("custom-box", { quiet: true })), - ).toEqual({ + ).resolves.toEqual({ checked: true, wasRunning: true, recovered: false, @@ -166,7 +166,7 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { expect(sshCommands[0]).not.toContain("gateway run"); }); - it("recovers a stopped custom gateway agent over SSH fallback", () => { + it("recovers a stopped custom gateway agent over SSH fallback", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.ts"); const agentRuntime = requireSource("../../src/lib/agent/runtime.ts"); const registry = requireSource("../../src/lib/state/registry.ts"); @@ -192,8 +192,7 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { vi.spyOn(childProcess, "spawnSync").mockImplementation( (command: unknown, rawArgs: unknown) => { healthProbeCalls += Number( - String(command).endsWith("openshell") && - getSandboxExecShellCommand(rawArgs).includes("HTTP_CODE=$(curl"), + command === "ssh" && getSandboxExecShellCommand(rawArgs).includes("HTTP_CODE=$(curl"), ); const setRecovered = (value: boolean): void => { recovered = value; @@ -228,11 +227,11 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - expect( + await expect( withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("custom-box", { quiet: true }), ), - ).toEqual({ + ).resolves.toEqual({ checked: true, wasRunning: false, recovered: true, @@ -250,7 +249,7 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { } }); - it("fails closed when a persisted non-OpenClaw manifest cannot be loaded", () => { + it("fails closed when a persisted non-OpenClaw manifest cannot be loaded", async () => { const agentRuntime = requireSource("../../src/lib/agent/runtime.ts"); const registry = requireSource("../../src/lib/state/registry.ts"); const childProcess = requireSource("node:child_process"); @@ -273,11 +272,14 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { dashboardPort: 19000, }); - expect( + await expect( withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("custom-box", { quiet: false }), + checkAndRecoverSandboxProcesses("custom-box", { + quiet: false, + isSandboxGatewayRunningImpl: async () => false, + }), ), - ).toEqual({ + ).resolves.toEqual({ checked: true, wasRunning: false, recovered: false, diff --git a/test/process-recovery/process-recovery-managed-controller.test.ts b/test/process-recovery/process-recovery-managed-controller.test.ts index 1772adbf029..04fb7fbea93 100644 --- a/test/process-recovery/process-recovery-managed-controller.test.ts +++ b/test/process-recovery/process-recovery-managed-controller.test.ts @@ -35,14 +35,14 @@ function getSandboxExecShellCommand(rawArgs: unknown): string { return match ? Buffer.from(match[1], "base64").toString("utf8") : payload; } -function withFakeOpenshellBinary(fn: () => T): T { +async function withFakeOpenshellBinary(fn: () => Promise): Promise { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); const bin = path.join(dir, "openshell"); const previous = process.env.NEMOCLAW_OPENSHELL_BIN; fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); process.env.NEMOCLAW_OPENSHELL_BIN = bin; try { - return fn(); + return await fn(); } finally { previous === undefined ? delete process.env.NEMOCLAW_OPENSHELL_BIN @@ -356,7 +356,7 @@ describe("managed gateway recovery controller", () => { }, ])( "enforces managed recovery for $label", - ({ + async ({ label, recoverResults, expectedResult, @@ -430,10 +430,15 @@ describe("managed gateway recovery controller", () => { output: runningForward, }); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => { + healthProbeCalls += 1; + return false; + }, + waitForRecreatedSandboxOpenShellReadyImpl: async () => true, }), ); expect(result).toEqual(expectedResult); diff --git a/test/process-recovery/process-recovery-primitives.test.ts b/test/process-recovery/process-recovery-primitives.test.ts index 91e39cd36a5..34f0549dca1 100644 --- a/test/process-recovery/process-recovery-primitives.test.ts +++ b/test/process-recovery/process-recovery-primitives.test.ts @@ -467,14 +467,14 @@ describe("executeGatewaySupervisorAction", () => { ); }); -function withFakeOpenshellBinary(fn: () => T): T { +async function withFakeOpenshellBinary(script: string, fn: () => Promise): Promise { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); const bin = path.join(dir, "openshell"); const previous = process.env.NEMOCLAW_OPENSHELL_BIN; - fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + fs.writeFileSync(bin, `#!/bin/sh\n${script}\n`, { mode: 0o755 }); process.env.NEMOCLAW_OPENSHELL_BIN = bin; try { - return fn(); + return await fn(); } finally { previous === undefined ? delete process.env.NEMOCLAW_OPENSHELL_BIN @@ -540,28 +540,24 @@ describe("resolveSandboxDashboardPort", () => { }); describe("executeSandboxExecCommand", () => { - it("does not forward an MCP credential to the OpenShell child process", () => { - const childProcess = requireSource("node:child_process"); - const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nREADY\n", - stderr: "", - } as never); + it("does not forward an MCP credential to the OpenShell child process", async () => { const priorSecret = process.env.TEST_MCP_RAW_TOKEN; const priorGateway = process.env.OPENSHELL_GATEWAY; process.env.TEST_MCP_RAW_TOKEN = "must-reach-only-provider-mutation"; process.env.OPENSHELL_GATEWAY = "nemoclaw-19080"; try { - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "printf READY"), + const result = await withFakeOpenshellBinary( + [ + 'test -z "${TEST_MCP_RAW_TOKEN+x}" || exit 90', + 'test "$OPENSHELL_GATEWAY" = "nemoclaw-19080" || exit 91', + 'test -n "$PATH" || exit 92', + "printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__' 'READY'", + ].join("\n"), + () => executeSandboxExecCommand("hermes-box", "printf READY"), ); - const options = spawn.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv }; expect(result).toEqual({ status: 0, stdout: "READY", stderr: "" }); - expect(options.env?.TEST_MCP_RAW_TOKEN).toBeUndefined(); - expect(options.env?.OPENSHELL_GATEWAY).toBe("nemoclaw-19080"); - expect(options.env?.PATH).toBe(process.env.PATH); } finally { priorSecret === undefined ? delete process.env.TEST_MCP_RAW_TOKEN @@ -572,39 +568,25 @@ describe("executeSandboxExecCommand", () => { } }); - it("honors the sandbox-exec timeout without falling back to SSH", () => { - const childProcess = requireSource("node:child_process"); + it("honors the sandbox-exec timeout without falling back to Docker", async () => { const privilegedExec = requireSource("../../src/lib/sandbox/privileged-exec.ts"); - const timeoutError = Object.assign(new Error("timed out"), { code: "ETIMEDOUT" }); - const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: null, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\n", - stderr: "", - error: timeoutError, - } as never); const executePrivileged = vi .spyOn(privilegedExec, "executePrivilegedSandboxCommand") - .mockReturnValue({ - status: null, - signal: null, - stdout: Buffer.alloc(0), - stderr: Buffer.alloc(0), - error: timeoutError, - } as never); + .mockImplementation(() => { + throw new Error("Docker fallback must not run after an OpenShell timeout"); + }); const previousTimeout = process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS; process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS = "50"; try { - const result = withFakeOpenshellBinary(() => + const startedAt = Date.now(); + const result = await withFakeOpenshellBinary("sleep 10", () => executeSandboxExecCommand("alpha", "printf RUNNING"), ); expect(result).toBeNull(); - expect(spawn.mock.calls.some(([command]) => command === "ssh")).toBe(false); - expect(spawn.mock.calls[0]?.[2]).toEqual(expect.objectContaining({ timeout: 50 })); - expect(executePrivileged.mock.calls[0]?.[2]).toEqual( - expect.objectContaining({ sanitizeEnvironment: true, timeout: 50 }), - ); + expect(Date.now() - startedAt).toBeLessThan(2_000); + expect(executePrivileged).not.toHaveBeenCalled(); } finally { previousTimeout === undefined ? delete process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS @@ -612,128 +594,77 @@ describe("executeSandboxExecCommand", () => { } }); - it("parses stdout-framed root exec output after the startup marker", () => { - const childProcess = requireSource("node:child_process"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: [ - "OpenShell sandbox exec output:", - "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__", - "stdout: SECRET_BOUNDARY_OK", - ].join("\n"), - stderr: "", - } as never); - - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + it("parses stdout-framed root exec output after the startup marker", async () => { + const result = await withFakeOpenshellBinary( + "printf '%s\\n' 'OpenShell sandbox exec output:' 'stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__' 'stdout: SECRET_BOUNDARY_OK'", + () => executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), ); expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); }); - it("rejects a non-frame preamble and surfaces a missing trusted fallback identity", () => { - const childProcess = requireSource("node:child_process"); + it("rejects a non-frame preamble without retrying through Docker", async () => { const privilegedExec = requireSource("../../src/lib/sandbox/privileged-exec.ts"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: [ - "operator preamble mentions __NEMOCLAW_SANDBOX_EXEC_STARTED__ before child stdout", - "stdout: RUNNING", - ].join("\n"), - stderr: "", - } as never); const executePrivileged = vi.spyOn(privilegedExec, "executePrivilegedSandboxCommand"); - expect(() => - withFakeOpenshellBinary(() => executeSandboxExecCommand("hermes-box", "echo RUNNING")), - ).toThrow(/No NemoClaw registry entry found.*refusing privileged exec/); - expect(executePrivileged).toHaveBeenCalledTimes(1); - }); - - it("keeps the Hermes validator source out of the host shell payload", () => { - const childProcess = requireSource("node:child_process"); - const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never); - - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand( - "hermes-box", - "python3 /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py env-file /sandbox/.hermes/.env\necho SECRET_BOUNDARY_OK", + await expect( + withFakeOpenshellBinary( + "printf '%s\\n' 'operator preamble mentions __NEMOCLAW_SANDBOX_EXEC_STARTED__ before child stdout' 'stdout: RUNNING'", + () => executeSandboxExecCommand("hermes-box", "echo RUNNING"), ), - ); - - const args = spawn.mock.calls[0]?.[1] as string[]; - const shellPayload = args.at(-1) ?? ""; - expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); - expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); - expect(shellPayload).toContain("base64 -d | sh"); - expect(shellPayload).not.toContain("echo SECRET_BOUNDARY_OK"); + ).resolves.toBeNull(); + expect(executePrivileged).not.toHaveBeenCalled(); }); - it("falls back to local Docker root exec when OpenShell exec output has no marker", () => { - const childProcess = requireSource("node:child_process"); - const privilegedExec = requireSource("../../src/lib/sandbox/privileged-exec.ts"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: "OpenShell transport preamble\n", - stderr: "", - } as never); - const executePrivileged = vi - .spyOn(privilegedExec, "executePrivilegedSandboxCommand") - .mockReturnValue({ - status: 0, - signal: null, - stdout: Buffer.from("__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n"), - stderr: Buffer.alloc(0), - } as never); + it("keeps the Hermes validator source out of the host shell payload", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-args-")); + const captureFile = path.join(dir, "args.txt"); - const priorSecret = process.env.TEST_MCP_RAW_TOKEN; - const priorGateway = process.env.OPENSHELL_GATEWAY; - process.env.TEST_MCP_RAW_TOKEN = "must-reach-only-provider-mutation"; - process.env.OPENSHELL_GATEWAY = "nemoclaw-19080"; - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), - ); - priorSecret === undefined - ? delete process.env.TEST_MCP_RAW_TOKEN - : (process.env.TEST_MCP_RAW_TOKEN = priorSecret); - priorGateway === undefined - ? delete process.env.OPENSHELL_GATEWAY - : (process.env.OPENSHELL_GATEWAY = priorGateway); + try { + const result = await withFakeOpenshellBinary( + `printf '%s\\n' "$@" > '${captureFile}'\nprintf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__' 'SECRET_BOUNDARY_OK'`, + () => + executeSandboxExecCommand( + "hermes-box", + "python3 /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py env-file /sandbox/.hermes/.env\necho SECRET_BOUNDARY_OK", + ), + ); - expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); - expect(executePrivileged).toHaveBeenCalledWith( - "hermes-box", - ["sh", "-c", expect.stringContaining("echo SECRET_BOUNDARY_OK")], - expect.objectContaining({ sanitizeEnvironment: true }), - ); + const shellPayload = fs.readFileSync(captureFile, "utf8"); + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); + expect(shellPayload).toContain("base64 -d | sh"); + expect(shellPayload).not.toContain("validate-hermes-env-secret-boundary.py"); + expect(shellPayload).not.toContain("/sandbox/.hermes/.env"); + expect(shellPayload).not.toContain("echo SECRET_BOUNDARY_OK"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } }); - it("does not let Docker fallback satisfy a strict provider credential proof", () => { - const childProcess = requireSource("node:child_process"); + it("does not let Docker fallback satisfy a strict provider credential proof", async () => { const privilegedExec = requireSource("../../src/lib/sandbox/privileged-exec.ts"); - const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 1, - stdout: "OpenShell transport failed before the child marker\n", - stderr: "gateway unavailable\n", - } as never); const executePrivileged = vi.spyOn(privilegedExec, "executePrivilegedSandboxCommand"); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-strict-provider-args-")); + const captureFile = path.join(dir, "args.txt"); - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", '[ -z "${FAKE_MCP_SECRET+x}" ]', undefined, { - allowLocalDockerFallback: false, - }), - ); + try { + const result = await withFakeOpenshellBinary( + `printf '%s\n' "$@" > '${captureFile}'\nexit 1`, + () => + executeSandboxExecCommand("hermes-box", '[ -z "${FAKE_MCP_SECRET+x}" ]', undefined, { + localDockerFallbackPolicy: "never", + }), + ); - expect(result).toBeNull(); - expect(executePrivileged).not.toHaveBeenCalled(); - const args = spawn.mock.calls[0]?.[1] as string[]; - const shellPayload = args.at(-1) ?? ""; - expect(shellPayload).not.toMatch(/[\r\n]/); - expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); + expect(result).toBeNull(); + expect(executePrivileged).not.toHaveBeenCalled(); + const shellPayload = fs.readFileSync(captureFile, "utf8").trim().split(/\r?\n/u).at(-1) ?? ""; + expect(shellPayload).not.toMatch(/[\r\n]/u); + expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } }); }); diff --git a/test/process-recovery/process-recovery-supervisor-relaunch.test.ts b/test/process-recovery/process-recovery-supervisor-relaunch.test.ts index c8f3d0926e1..159e8fc5fdd 100644 --- a/test/process-recovery/process-recovery-supervisor-relaunch.test.ts +++ b/test/process-recovery/process-recovery-supervisor-relaunch.test.ts @@ -70,7 +70,7 @@ function setImmediateRecoveryPolling() { function composedRelaunchTransaction( order: string[], finalizeTransaction: typeof finalizeDockerGpuPatchBackup = vi.fn( - ({ supervisorReady }: { supervisorReady: boolean }) => { + async ({ supervisorReady }: { supervisorReady: boolean }) => { order.push(supervisorReady ? "commit-container" : "rollback-container"); return supervisorReady ? { backupRemoved: true, rolledBack: false } @@ -82,6 +82,13 @@ function composedRelaunchTransaction( replacement: "replacement-container-id", }, ) { + const commandExecutor = { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }; const resolveContainer = vi .fn() .mockReturnValueOnce(containerIds.old) @@ -129,6 +136,7 @@ function composedRelaunchTransaction( }; }), removeBackup: vi.fn(() => true), + commandExecutor, runCaptureOpenshell, runOpenshell, recreate: vi.fn(() => ({ @@ -151,6 +159,7 @@ function composedRelaunchTransaction( }, ); return { + commandExecutor, finalizeTransaction, relaunchManagedSupervisorSessionImpl, runCaptureOpenshell, @@ -186,7 +195,7 @@ function scriptedPinnedGatewayRecovery( } describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { - it("reports the onboarding remediation for a legacy Hermes recovery refusal", () => { + it("reports the onboarding remediation for a legacy Hermes recovery refusal", async () => { setImmediateRecoveryPolling(); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", @@ -223,9 +232,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - const result = checkAndRecoverSandboxProcesses("legacy-hermes-box", { + const result = await checkAndRecoverSandboxProcesses("legacy-hermes-box", { quiet: false, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction: vi.fn(() => MISSING_MANAGED_SUPERVISOR), relaunchManagedSupervisorSessionImpl, }); @@ -239,7 +248,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(output).toContain("Rerun onboarding before retrying recovery"); }); - it("does not turn ambiguous supervisor unavailability into a container mutation", () => { + it("does not turn ambiguous supervisor unavailability into a container mutation", async () => { mockOpenClawSandbox("ambiguous-box"); setImmediateRecoveryPolling(); const requestGatewaySupervisorAction = vi.fn(() => ({ @@ -249,9 +258,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses("ambiguous-box", { + const result = await checkAndRecoverSandboxProcesses("ambiguous-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, }); @@ -261,7 +270,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(relaunchManagedSupervisorSessionImpl).not.toHaveBeenCalled(); }); - it("does not mutate on an embellished no-supervisor marker", () => { + it("does not mutate on an embellished no-supervisor marker", async () => { mockOpenClawSandbox("embellished-box"); setImmediateRecoveryPolling(); const requestGatewaySupervisorAction = vi.fn(() => ({ @@ -271,9 +280,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses("embellished-box", { + const result = await checkAndRecoverSandboxProcesses("embellished-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, }); @@ -283,7 +292,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(relaunchManagedSupervisorSessionImpl).not.toHaveBeenCalled(); }); - it("honors the relaunch kill switch through stable no-supervisor recovery", () => { + it("honors the relaunch kill switch through stable no-supervisor recovery", async () => { vi.stubEnv("NEMOCLAW_DISABLE_SUPERVISOR_RELAUNCH", "1"); mockOpenClawSandbox("legacy-box"); setImmediateRecoveryPolling(); @@ -303,9 +312,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); - const result = checkAndRecoverSandboxProcesses("legacy-box", { + const result = await checkAndRecoverSandboxProcesses("legacy-box", { quiet: false, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -331,10 +340,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ); }); - it("reports an unconfirmed rollback when recreated gateway health never resolves", () => { + it("reports an unconfirmed rollback when recreated gateway health never resolves", async () => { mockOpenClawSandbox("rejected-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ backupRemoved: false, rolledBack: false })); + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: false })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ containerId: "replacement-container-id", finalize, @@ -342,9 +351,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { const requestGatewaySupervisorAction = vi.fn(missingSupervisorOnRecover); const requestPinnedGatewaySupervisorAction = vi.fn(() => null); - const result = checkAndRecoverSandboxProcesses("rejected-box", { + const result = await checkAndRecoverSandboxProcesses("rejected-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -372,10 +381,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(finalize).toHaveBeenCalledWith(false); }); - it("reports a managed health failure during the recreated gateway wait", () => { + it("reports a managed health failure during the recreated gateway wait", async () => { mockOpenClawSandbox("wait-failed-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ backupRemoved: false, rolledBack: true })); + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: true })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ containerId: "replacement-container-id", finalize, @@ -387,9 +396,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { stderr: "GATEWAY_UNSAFE_CONFIG_PATH", })); - const result = checkAndRecoverSandboxProcesses("wait-failed-box", { + const result = await checkAndRecoverSandboxProcesses("wait-failed-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -414,18 +423,25 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(finalize).toHaveBeenCalledWith(false); }); - it("commits only after managed health accepts the recreated supervisor (#11107)", () => { + it("commits only after managed health accepts the recreated supervisor (#11107)", async () => { mockOpenClawSandbox("recovered-box"); setImmediateRecoveryPolling(); const order: string[] = []; - const { finalizeTransaction, relaunchManagedSupervisorSessionImpl, runOpenshell } = - composedRelaunchTransaction(order); + const { + commandExecutor, + finalizeTransaction, + relaunchManagedSupervisorSessionImpl, + runOpenshell, + } = composedRelaunchTransaction(order); const requestGatewaySupervisorAction = vi.fn(missingSupervisorOnRecover); const requestPinnedGatewaySupervisorAction = scriptedPinnedGatewayRecovery(order, { status: 0, stdout: `v1 ${"a".repeat(64)} complete ok 4242 4343\nGATEWAY_PID=4343`, stderr: "", }); + const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn( + async (_name, options) => options.beforeProbe?.(1000) === true, + ); vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ status: 0, @@ -433,12 +449,13 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = checkAndRecoverSandboxProcesses("recovered-box", { + const result = await checkAndRecoverSandboxProcesses("recovered-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, + waitForRecreatedSandboxOpenShellReadyImpl, }); expect(result).toMatchObject({ checked: true, wasRunning: false, recovered: true }); @@ -449,8 +466,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ); expect( requestGatewaySupervisorAction.mock.calls.every( - ([, , timeout]) => - typeof timeout === "number" && timeout > 0 && timeout <= 210_000, + ([, , timeout]) => typeof timeout === "number" && timeout > 0 && timeout <= 210_000, ), ).toBe(true); expect(relaunchManagedSupervisorSessionImpl).toHaveBeenCalledWith( @@ -482,6 +498,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { supervisorReady: true, }), { + commandExecutor, runCaptureOpenshell: expect.any(Function), runOpenshell, }, @@ -601,7 +618,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }, ])( "does not start the primary dashboard/API host forward when $condition (#9364)", - ({ + async ({ expectedDetail, expectedReadinessCalls, finalPinnedAction, @@ -610,7 +627,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }) => { mockOpenClawSandbox("failed-handoff-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn((_supervisorReady: boolean) => finalizeOutcome()); + const finalize = vi.fn(async (_supervisorReady: boolean) => finalizeOutcome()); const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ containerId: "replacement-container-id", finalize, @@ -624,12 +641,16 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { const waitForRecreatedSandboxOpenShellReadyImpl = vi .fn() .mockImplementationOnce( - (_name: string, options?: { beforeProbe?: (timeoutMs: number) => boolean | null }) => - options?.beforeProbe?.(1000) === true, + async ( + _name: string, + options?: { beforeProbe?: (timeoutMs: number) => boolean | null }, + ) => options?.beforeProbe?.(1000) === true, ) .mockImplementation( - (_name: string, options?: { beforeProbe?: (timeoutMs: number) => boolean | null }) => - options?.beforeProbe?.(1000) === true && finalReadinessReady, + async ( + _name: string, + options?: { beforeProbe?: (timeoutMs: number) => boolean | null }, + ) => options?.beforeProbe?.(1000) === true && finalReadinessReady, ); const captureOpenshell = vi .spyOn(openshellRuntime, "captureOpenshell") @@ -638,9 +659,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - const result = checkAndRecoverSandboxProcesses("failed-handoff-box", { + const result = await checkAndRecoverSandboxProcesses("failed-handoff-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -668,7 +689,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }, ); - it("rolls back when post-restore restart does not report an exact ok disposition", () => { + it("rolls back when post-restore restart does not report an exact ok disposition", async () => { mockOpenClawSandbox("post-restore-fail"); setImmediateRecoveryPolling(); const order: string[] = []; @@ -680,18 +701,22 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { stdout: `v1 ${"b".repeat(64)} complete already-running 4242 4242\nGATEWAY_PID=4242`, stderr: "", }); + const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn( + async (_name, options) => options.beforeProbe?.(1000) === true, + ); vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ status: 0, output: "SANDBOX BIND PORT PID STATUS\npost-restore-fail 127.0.0.1 18789 12345 running", }); - const result = checkAndRecoverSandboxProcesses("post-restore-fail", { + const result = await checkAndRecoverSandboxProcesses("post-restore-fail", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, + waitForRecreatedSandboxOpenShellReadyImpl, }); expect(result).toMatchObject({ @@ -710,10 +735,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ); }); - it("reports recovery failure when state restore rolls the replacement back", () => { + it("reports recovery failure when state restore rolls the replacement back", async () => { mockOpenClawSandbox("restore-failed-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -728,7 +753,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ( _name: string, _options?: { beforeProbe?: (timeoutMs: number) => boolean | null; timeoutSeconds?: number }, - ) => true, + ) => Promise.resolve(true), ); const captureOpenshell = vi .spyOn(openshellRuntime, "captureOpenshell") @@ -737,9 +762,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - const result = checkAndRecoverSandboxProcesses("restore-failed-box", { + const result = await checkAndRecoverSandboxProcesses("restore-failed-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -768,10 +793,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(runOpenshell).not.toHaveBeenCalled(); }); - it("prints generic recovery hints when state recovery and rollback both fail", () => { + it("prints generic recovery hints when state recovery and rollback both fail", async () => { mockOpenClawSandbox("restore-rollback"); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: false, stateRestored: false, @@ -791,13 +816,13 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - const result = checkAndRecoverSandboxProcesses("restore-rollback", { + const result = await checkAndRecoverSandboxProcesses("restore-rollback", { quiet: false, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, - waitForRecreatedSandboxOpenShellReadyImpl: vi.fn(() => true), + waitForRecreatedSandboxOpenShellReadyImpl: vi.fn(async () => true), }); expect(result).toMatchObject({ @@ -819,12 +844,12 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(output).not.toContain("Sandbox state restore failed"); }); - it("keeps polling a recreated OpenClaw gateway beyond its ordinary health timeout (#10153)", () => { + it("keeps polling a recreated OpenClaw gateway beyond its ordinary health timeout (#10153)", async () => { mockOpenClawSandbox("slow-recreated-box", 30); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "0"); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS", "0"); vi.stubEnv("NEMOCLAW_FORWARD_RECOVERY_WAIT_MS", "0"); - const finalize = vi.fn(() => ({ backupRemoved: true, rolledBack: false })); + const finalize = vi.fn(async () => ({ backupRemoved: true, rolledBack: false })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ containerId: "replacement-container-id", finalize, @@ -838,7 +863,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { : ACCEPTED_MANAGED_PROBE; }); const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn( - (_name, options) => options.beforeProbe?.(1000) === true, + async (_name, options) => options.beforeProbe?.(1000) === true, ); vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ @@ -847,9 +872,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { "SANDBOX BIND PORT PID STATUS\nslow-recreated-box 127.0.0.1 18789 12345 running", }); - const result = checkAndRecoverSandboxProcesses("slow-recreated-box", { + const result = await checkAndRecoverSandboxProcesses("slow-recreated-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -861,10 +886,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(finalize).toHaveBeenCalledWith(true); }); - it("uses the shared recreate-readiness budget after a longer gateway health wait", () => { + it("uses the shared recreate-readiness budget after a longer gateway health wait", async () => { mockOpenClawSandbox("unready-box", 600); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -879,13 +904,13 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ( _name: string, _options?: { beforeProbe?: (timeoutMs: number) => boolean | null; timeoutSeconds?: number }, - ) => false, + ) => Promise.resolve(false), ); const runOpenshell = vi.spyOn(openshellRuntime, "runOpenshell"); - const result = checkAndRecoverSandboxProcesses("unready-box", { + const result = await checkAndRecoverSandboxProcesses("unready-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -928,17 +953,17 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }, ])( "reports the readiness failure and unconfirmed rollback when $condition (#9364)", - ({ finalizeOutcome }) => { + async ({ finalizeOutcome }) => { mockOpenClawSandbox("rollback-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn((_supervisorReady: boolean) => finalizeOutcome()); + const finalize = vi.fn(async (_supervisorReady: boolean) => finalizeOutcome()); const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ containerId: "replacement-container-id", finalize, })); const requestGatewaySupervisorAction = vi.fn(() => MISSING_MANAGED_SUPERVISOR); const requestPinnedGatewaySupervisorAction = vi.fn(() => ACCEPTED_MANAGED_PROBE); - const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn(() => false); + const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn(async () => false); const captureOpenshell = vi .spyOn(openshellRuntime, "captureOpenshell") .mockReturnValue({ status: 0, output: "" }); @@ -946,9 +971,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - const result = checkAndRecoverSandboxProcesses("rollback-box", { + const result = await checkAndRecoverSandboxProcesses("rollback-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -977,10 +1002,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }, ); - it("reports the last structured OpenShell error when readiness times out", () => { + it("reports the last structured OpenShell error when readiness times out", async () => { mockOpenClawSandbox("relay-dropped-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -991,30 +1016,22 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { })); const requestGatewaySupervisorAction = vi.fn(() => MISSING_MANAGED_SUPERVISOR); const requestPinnedGatewaySupervisorAction = vi.fn(() => ACCEPTED_MANAGED_PROBE); - const timeoutError = Object.assign(new Error("timed out"), { code: "ETIMEDOUT" }); - const captureOpenshell = vi - .spyOn(openshellRuntime, "captureOpenshell") - .mockReturnValueOnce({ - status: 1, - output: OPENSHELL_RELAY_CHANNEL_DROPPED_STDERR.trim(), + const commandExecutor = { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 1 }, stdout: "", stderr: OPENSHELL_RELAY_CHANNEL_DROPPED_STDERR, - }) - .mockReturnValue({ - status: null, - output: "", - stdout: "", - stderr: "", - error: timeoutError, - }); + })), + }; const runOpenshell = vi.spyOn(openshellRuntime, "runOpenshell"); - const result = checkAndRecoverSandboxProcesses("relay-dropped-box", { + const result = await checkAndRecoverSandboxProcesses("relay-dropped-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, + commandExecutor, }); expect(result).toMatchObject({ @@ -1026,15 +1043,15 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { 'Last OpenShell readiness error: Error: status: Unavailable, message: "relay channel dropped"', ), }); - expect(captureOpenshell).toHaveBeenCalled(); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); expect(finalize).toHaveBeenCalledWith(false); expect(runOpenshell).not.toHaveBeenCalled(); }); - it("reports a definitive managed health failure separately from OpenShell readiness", () => { + it("reports a definitive managed health failure separately from OpenShell readiness", async () => { mockOpenClawSandbox("managed-failed-box"); setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ + const finalize = vi.fn(async () => ({ backupRemoved: false, rolledBack: true, stateRestored: false, @@ -1055,9 +1072,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { }); const captureOpenshell = vi.spyOn(openshellRuntime, "captureOpenshell"); - const result = checkAndRecoverSandboxProcesses("managed-failed-box", { + const result = await checkAndRecoverSandboxProcesses("managed-failed-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, @@ -1101,84 +1118,91 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { throw new Error("opaque-forward-probe-sentinel"); }, }, - ])("rejects a healthy forward when $condition (#9364)", ({ expectedDetail, finalProbe }) => { - mockOpenClawSandbox("drifted-box"); - vi.mocked(agentRuntime.getSessionAgent).mockReturnValue({ - name: "openclaw", - displayName: "OpenClaw", - forwardPort: 18789, - forward_ports: [19000], - healthProbe: { url: "http://127.0.0.1:18789/health", port: 18789, timeout_seconds: 30 }, - } as never); - setImmediateRecoveryPolling(); - const finalize = vi.fn(() => ({ backupRemoved: true, rolledBack: false })); - const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ - containerId: "replacement-container-id", - finalize, - })); - const requestGatewaySupervisorAction = vi.fn(() => MISSING_MANAGED_SUPERVISOR); - const acceptedProbe = ACCEPTED_MANAGED_PROBE; - const requestPinnedGatewaySupervisorAction = vi - .fn() - .mockReturnValueOnce(acceptedProbe) - .mockReturnValueOnce(acceptedProbe) - .mockImplementationOnce(finalProbe) - .mockReturnValue(acceptedProbe); - const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn( - (_name, options) => options.beforeProbe?.(1000) === true, - ); - vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); - vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ - status: 0, - output: "SANDBOX BIND PORT PID STATUS\ndrifted-box 127.0.0.1 18789 12345 running", - }); - const runOpenshell = vi - .spyOn(openshellRuntime, "runOpenshell") - .mockReturnValue({ status: 0 } as never); - const probeTiming = { - measure: (_stage: "processes" | "forward", operation: () => T): T => operation(), - setForwardAction: vi.fn(), - }; + ])( + "rejects a healthy forward when $condition (#9364)", + async ({ expectedDetail, finalProbe }) => { + mockOpenClawSandbox("drifted-box"); + vi.mocked(agentRuntime.getSessionAgent).mockReturnValue({ + name: "openclaw", + displayName: "OpenClaw", + forwardPort: 18789, + forward_ports: [19000], + healthProbe: { url: "http://127.0.0.1:18789/health", port: 18789, timeout_seconds: 30 }, + } as never); + setImmediateRecoveryPolling(); + const finalize = vi.fn(async () => ({ backupRemoved: true, rolledBack: false })); + const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ + containerId: "replacement-container-id", + finalize, + })); + const requestGatewaySupervisorAction = vi.fn(() => MISSING_MANAGED_SUPERVISOR); + const acceptedProbe = ACCEPTED_MANAGED_PROBE; + const requestPinnedGatewaySupervisorAction = vi + .fn() + .mockReturnValueOnce(acceptedProbe) + .mockReturnValueOnce(acceptedProbe) + .mockImplementationOnce(finalProbe) + .mockReturnValue(acceptedProbe); + const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn( + async (_name, options) => options.beforeProbe?.(1000) === true, + ); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: "SANDBOX BIND PORT PID STATUS\ndrifted-box 127.0.0.1 18789 12345 running", + }); + const runOpenshell = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockReturnValue({ status: 0 } as never); + const probeTiming = { + measure: (_stage: "processes" | "forward", operation: () => T): T => operation(), + measureAsync: ( + _stage: "processes" | "forward", + operation: () => Promise, + ): Promise => operation(), + setForwardAction: vi.fn(), + }; - const result = checkAndRecoverSandboxProcesses("drifted-box", { - quiet: true, - isSandboxGatewayRunningImpl: () => false, - requestGatewaySupervisorAction, - requestPinnedGatewaySupervisorAction, - relaunchManagedSupervisorSessionImpl, - waitForRecreatedSandboxOpenShellReadyImpl, - probeTiming, - }); + const result = await checkAndRecoverSandboxProcesses("drifted-box", { + quiet: true, + isSandboxGatewayRunningImpl: async () => false, + requestGatewaySupervisorAction, + requestPinnedGatewaySupervisorAction, + relaunchManagedSupervisorSessionImpl, + waitForRecreatedSandboxOpenShellReadyImpl, + probeTiming, + }); - expect(result).toMatchObject({ - checked: true, - wasRunning: false, - recovered: false, - forwardRecovered: false, - recoveryFailureDetail: expect.stringContaining(expectedDetail), - }); - expect("recoveryFailureDetail" in result ? result.recoveryFailureDetail : "").not.toContain( - "opaque-", - ); - expect(result).not.toHaveProperty("forwardRecoveryFailed"); - expect(requestPinnedGatewaySupervisorAction).toHaveBeenCalledTimes(3); - expect(requestPinnedGatewaySupervisorAction).toHaveBeenLastCalledWith( - "drifted-box", - "probe", - 15000, - "replacement-container-id", - ); - expect(finalize).toHaveBeenCalledWith(true); - expect(probeTiming.setForwardAction).toHaveBeenCalledOnce(); - expect(probeTiming.setForwardAction).toHaveBeenCalledWith("failed"); - expect(runOpenshell).not.toHaveBeenCalled(); - }); + expect(result).toMatchObject({ + checked: true, + wasRunning: false, + recovered: false, + forwardRecovered: false, + recoveryFailureDetail: expect.stringContaining(expectedDetail), + }); + expect("recoveryFailureDetail" in result ? result.recoveryFailureDetail : "").not.toContain( + "opaque-", + ); + expect(result).not.toHaveProperty("forwardRecoveryFailed"); + expect(requestPinnedGatewaySupervisorAction).toHaveBeenCalledTimes(3); + expect(requestPinnedGatewaySupervisorAction).toHaveBeenLastCalledWith( + "drifted-box", + "probe", + 15000, + "replacement-container-id", + ); + expect(finalize).toHaveBeenCalledWith(true); + expect(probeTiming.setForwardAction).toHaveBeenCalledOnce(); + expect(probeTiming.setForwardAction).toHaveBeenCalledWith("failed"); + expect(runOpenshell).not.toHaveBeenCalled(); + }, + ); - it("reports GATEWAY_UNSAFE_CONFIG_PATH after a transient identity refusal clears (#9364)", () => { + it("reports GATEWAY_UNSAFE_CONFIG_PATH after a transient identity refusal clears (#9364)", async () => { mockOpenClawSandbox("current-probe-box"); setImmediateRecoveryPolling(); vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", "1"); - const finalize = vi.fn(() => ({ backupRemoved: true, rolledBack: false })); + const finalize = vi.fn(async () => ({ backupRemoved: true, rolledBack: false })); const relaunchManagedSupervisorSessionImpl = vi.fn(() => ({ containerId: "replacement-container-id", finalize, @@ -1196,7 +1220,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { .mockReturnValueOnce(ACCEPTED_MANAGED_PROBE) .mockReturnValue(unsafeConfigProbe); const waitForRecreatedSandboxOpenShellReadyImpl = vi.fn( - (_name, options) => options.beforeProbe?.(1000) === true, + async (_name, options) => options.beforeProbe?.(1000) === true, ); vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ @@ -1208,9 +1232,9 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - const result = checkAndRecoverSandboxProcesses("current-probe-box", { + const result = await checkAndRecoverSandboxProcesses("current-probe-box", { quiet: true, - isSandboxGatewayRunningImpl: () => false, + isSandboxGatewayRunningImpl: async () => false, requestGatewaySupervisorAction, requestPinnedGatewaySupervisorAction, relaunchManagedSupervisorSessionImpl, diff --git a/test/process-recovery/process-recovery.test.ts b/test/process-recovery/process-recovery.test.ts index eb2f264409a..c0baf49a389 100644 --- a/test/process-recovery/process-recovery.test.ts +++ b/test/process-recovery/process-recovery.test.ts @@ -53,14 +53,14 @@ function expectBoundedGatewayRecoveryCall(request: unknown): void { expect(timeout).toBeLessThanOrEqual(210_000); } -function withFakeOpenshellBinary(fn: () => T): T { +async function withFakeOpenshellBinary(fn: () => T | Promise): Promise { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); const bin = path.join(dir, "openshell"); const previous = process.env.NEMOCLAW_OPENSHELL_BIN; fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); process.env.NEMOCLAW_OPENSHELL_BIN = bin; try { - return fn(); + return await fn(); } finally { if (previous === undefined) { delete process.env.NEMOCLAW_OPENSHELL_BIN; @@ -110,38 +110,45 @@ function compactTeamsMessagingPlan(port = "3978") { } describe("checkAndRecoverSandboxProcesses", () => { - it("does not attempt gateway recovery for terminal agents", () => { + it("does not attempt gateway recovery for terminal agents", async () => { const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ runtime: { kind: "terminal" }, } as never); - expect(checkAndRecoverSandboxProcesses("terminal-box", { quiet: true })).toEqual({ - checked: true, - wasRunning: null, - recovered: false, - forwardRecovered: false, - runtime: "terminal", - }); + await expect(checkAndRecoverSandboxProcesses("terminal-box", { quiet: true })).resolves.toEqual( + { + checked: true, + wasRunning: null, + recovered: false, + forwardRecovered: false, + runtime: "terminal", + }, + ); }); - it("waits for stopped Hermes recovery after managed OpenShell control succeeds", () => { + it("waits for stopped Hermes recovery after managed OpenShell control succeeds", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); const forwardHealth = requireSource("../../src/lib/actions/sandbox/forward-health.js"); - const childProcess = requireSource("node:child_process"); const runningForward = `SANDBOX BIND PORT PID STATUS hermes-box 127.0.0.1 18789 12345 running`; const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; - const commands: string[] = []; - let restarted = false; - const requestGatewaySupervisorAction = vi.fn(() => { - restarted = true; - return { status: 0, stdout: "GATEWAY_PID=4242\n", stderr: "" }; - }); + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); + const commandExecutor = { + runBuffered: vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + })), + }; // The gateway retry is under test; host-forward readiness is fully mocked. vi.stubEnv("NEMOCLAW_FORWARD_RECOVERY_WAIT_MS", "0"); @@ -150,18 +157,6 @@ hermes-box 127.0.0.1 18789 12345 running`; process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; try { - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - const isHealthProbe = shellCommand.includes("HTTP_CODE=$(curl"); - const probeStatus = restarted ? "RUNNING" : "STOPPED"; - const stdout = isHealthProbe - ? `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${probeStatus}\n` - : "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n"; - commands.push(String(command)); - return { status: 0, stdout, stderr: "" } as never; - }, - ); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", displayName: "Hermes Agent", @@ -190,15 +185,24 @@ hermes-box 127.0.0.1 18789 12345 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => false, + commandExecutor, }), ); expect(result.recovered).toBe(true); expect(result.wasRunning).toBe(false); - expect(commands).not.toContain("ssh"); + expect(commandExecutor.runBuffered).toHaveBeenCalledOnce(); + expect(commandExecutor.runBuffered).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "hermes-box", + target: { kind: "selected" }, + command: ["true"], + }), + ); expectBoundedGatewayRecoveryCall(requestGatewaySupervisorAction); } finally { previousWaitSeconds === undefined @@ -224,7 +228,7 @@ hermes-box 127.0.0.1 18789 12345 running`; ["a non-exact self-recovery marker", "", "prefix SUPERVISOR_UNAVAILABLE suffix"], ["an extra self-recovery error", "", "SUPERVISOR_UNAVAILABLE\nGATEWAY_FAILED"], ["a self-recovery marker on stdout", "SUPERVISOR_UNAVAILABLE", ""], - ])("does not accept %s for Hermes", (_label, stdout, stderr) => { + ])("does not accept %s for Hermes", async (_label, stdout, stderr) => { const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); const childProcess = requireSource("node:child_process"); @@ -265,14 +269,15 @@ hermes-box 127.0.0.1 18789 12345 running`; dashboardPort: 18789, }); - expect( + await expect( withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => false, }), ), - ).toEqual({ + ).resolves.toEqual({ checked: true, wasRunning: false, recovered: false, @@ -281,7 +286,7 @@ hermes-box 127.0.0.1 18789 12345 running`; expectBoundedGatewayRecoveryCall(requestGatewaySupervisorAction); }); - it("leaves enabled Hermes dashboard recovery to the PID 1 supervisor", () => { + it("leaves enabled Hermes dashboard recovery to the PID 1 supervisor", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -351,14 +356,16 @@ hermes-box 127.0.0.1 18789 12345 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - expect( + await expect( withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => false, + waitForRecreatedSandboxOpenShellReadyImpl: async () => true, }), ), - ).toEqual({ + ).resolves.toEqual({ checked: true, wasRunning: false, recovered: true, @@ -379,7 +386,7 @@ hermes-box 127.0.0.1 18789 12345 running`; } }); - it("keeps quiet stopped-Hermes recovery failures off stderr", () => { + it("keeps quiet stopped-Hermes recovery failures off stderr", async () => { const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); const childProcess = requireSource("node:child_process"); @@ -397,11 +404,16 @@ hermes-box 127.0.0.1 18789 12345 running`; name: "hermes-box", }); - withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true })); + await withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + isSandboxGatewayRunningImpl: async () => false, + }), + ); expect(errorSpy).not.toHaveBeenCalled(); }); - it("refuses recovery of a running Hermes gateway when /sandbox/.hermes/.env contains raw secret-shaped values", () => { + it("refuses recovery of a running Hermes gateway when /sandbox/.hermes/.env contains raw secret-shaped values", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -451,10 +463,11 @@ hermes-box 127.0.0.1 18789 12345 running`; .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(result).toEqual({ @@ -482,7 +495,7 @@ hermes-box 127.0.0.1 18789 12345 running`; expect(errorOutput).toContain("[SECURITY] TELEGRAM_BOT_TOKEN (line 3)"); }); - it("fails safe on a running Hermes sandbox when the agent definition cannot be loaded", () => { + it("fails safe on a running Hermes sandbox when the agent definition cannot be loaded", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -521,10 +534,11 @@ hermes-box 127.0.0.1 18789 12345 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(result).toEqual({ @@ -549,7 +563,7 @@ hermes-box 127.0.0.1 18789 12345 running`; ["OpenShell managed controller", { status: 0, stdout: "GATEWAY_PID=4242\n", stderr: "" }], ])( "falls through when the Hermes $label reports a healthy gateway", - (_label, supervisorResult) => { + async (_label, supervisorResult) => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -579,10 +593,11 @@ hermes-box 127.0.0.1 18789 12345 running`; output: "SANDBOX BIND PORT PID STATUS", }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(result).toEqual({ @@ -596,7 +611,7 @@ hermes-box 127.0.0.1 18789 12345 running`; }, ); - it("refuses recovery when the Hermes secret-boundary validator is absent on an older sandbox image", () => { + it("refuses recovery when the Hermes secret-boundary validator is absent on an older sandbox image", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -640,10 +655,11 @@ hermes-box 127.0.0.1 18789 12345 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(result).toEqual({ @@ -663,7 +679,7 @@ hermes-box 127.0.0.1 18789 12345 running`; expect(errorOutput).toContain("Re-image the sandbox with a current Hermes build."); }); - it("does not invoke the Hermes PID 1 supervisor path for a running OpenClaw sandbox", () => { + it("does not invoke the Hermes PID 1 supervisor path for a running OpenClaw sandbox", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -692,10 +708,11 @@ hermes-box 127.0.0.1 18789 12345 running`; .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - withFakeOpenshellBinary(() => + await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(requestGatewaySupervisorAction).not.toHaveBeenCalled(); @@ -706,7 +723,7 @@ hermes-box 127.0.0.1 18789 12345 running`; ).toBe(false); }); - it("fails safe on a running Hermes gateway when the supervisor channel is unreachable", () => { + it("fails safe on a running Hermes gateway when the supervisor channel is unreachable", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -749,10 +766,11 @@ hermes-box 127.0.0.1 18789 12345 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(result).toEqual({ @@ -773,7 +791,7 @@ hermes-box 127.0.0.1 18789 12345 running`; ); }); - it("treats a non-zero boundary check without the REFUSED marker as unexpected, not raw-secret", () => { + it("treats a non-zero boundary check without the REFUSED marker as unexpected, not raw-secret", async () => { const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../../src/lib/agent/runtime.js"); const registry = requireSource("../../src/lib/state/registry.js"); @@ -814,10 +832,11 @@ hermes-box 127.0.0.1 18789 12345 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => + const result = await withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true, requestGatewaySupervisorAction, + isSandboxGatewayRunningImpl: async () => true, }), ); expect(result).toEqual({ diff --git a/test/repository/layer-import-boundaries.test.ts b/test/repository/layer-import-boundaries.test.ts index 6b3d2e4a15f..9ce362eaf44 100644 --- a/test/repository/layer-import-boundaries.test.ts +++ b/test/repository/layer-import-boundaries.test.ts @@ -10,6 +10,7 @@ import { findLayerImportBoundaryViolations, findManagedRuntimeBoundaryViolations, } from "../../scripts/checks/layer-import-boundaries.mts"; +import { testTimeoutOptions } from "../helpers/timeouts"; const REPO_ROOT = path.join(import.meta.dirname, "../.."); let fixtureCounter = 0; @@ -42,14 +43,176 @@ function scanFixture(fixture: string, source: string) { } describe("CLI layer import boundaries (#6245)", () => { - it("keeps domain, adapter, action, and command layers separated (#6245)", () => { - expect(findLayerImportBoundaryViolations()).toEqual([]); - }); + it( + "keeps domain, adapter, action, and command layers separated (#6245)", + testTimeoutOptions(60_000), + () => { + expect(findLayerImportBoundaryViolations()).toEqual([]); + }, + ); it("keeps managed runtime orchestration provider-neutral (#9145)", () => { expect(findManagedRuntimeBoundaryViolations()).toEqual([]); }); + it("keeps buffered sandbox commands on the async executor (#10991)", () => { + const violations = scanFixture( + fixturePath("src/lib/onboard", "buffered-exec-helper"), + 'import { buildOpenshellExecArgs } from "../actions/sandbox/exec";\nexport const value = buildOpenshellExecArgs;\n', + ); + + expect(violations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ rule: "buffered-exec-uses-async-executor" }), + ]), + ); + }); + + it.each([ + [ + "static require destructuring", + 'const { buildOpenshellExecArgs } = require("../actions/sandbox/exec");\nexport const value = buildOpenshellExecArgs;\n', + ], + [ + "TypeScript import equals", + 'import legacy = require("../actions/sandbox/exec");\nexport const value = legacy.buildOpenshellExecArgs;\n', + ], + [ + "namespace import computed property", + 'import * as legacy from "../actions/sandbox/exec";\nexport const value = legacy["buildOpenshellExecArgs"];\n', + ], + [ + "static require namespace computed property", + 'const legacy = require("../actions/sandbox/exec");\nexport const value = legacy["buildOpenshellExecArgs"];\n', + ], + [ + "nested static require destructuring", + 'export function value() {\n const { buildOpenshellExecArgs } = require("../actions/sandbox/exec");\n return buildOpenshellExecArgs;\n}\n', + ], + [ + "static require computed destructuring", + 'const { ["buildOpenshellExecArgs"]: value } = require("../actions/sandbox/exec");\nexport { value };\n', + ], + [ + "static require quoted destructuring", + 'const { "buildOpenshellExecArgs": value } = require("../actions/sandbox/exec");\nexport { value };\n', + ], + [ + "direct require property", + 'export const value = require("../actions/sandbox/exec").buildOpenshellExecArgs;\n', + ], + [ + "direct require computed property", + 'export const value = require("../actions/sandbox/exec")["buildOpenshellExecArgs"];\n', + ], + [ + "dynamic import property", + 'export async function value() {\n return (await import("../actions/sandbox/exec")).buildOpenshellExecArgs;\n}\n', + ], + [ + "awaited dynamic import computed property", + 'export async function value() {\n return (await import("../actions/sandbox/exec"))["buildOpenshellExecArgs"];\n}\n', + ], + [ + "awaited dynamic import binding", + 'export async function value() {\n const { buildOpenshellExecArgs } = await import("../actions/sandbox/exec");\n return buildOpenshellExecArgs;\n}\n', + ], + [ + "export assignment of a namespace import", + 'import * as legacy from "../actions/sandbox/exec";\nexport = legacy;\n', + ], + [ + "default export of a namespace import", + 'import * as legacy from "../actions/sandbox/exec";\nexport default legacy;\n', + ], + ["export assignment of a direct require", 'export = require("../actions/sandbox/exec");\n'], + ["default export of a direct require", 'export default require("../actions/sandbox/exec");\n'], + ["named re-export", 'export { buildOpenshellExecArgs } from "../actions/sandbox/exec";\n'], + [ + "aliased named re-export", + 'export { buildOpenshellExecArgs as legacyBuild } from "../actions/sandbox/exec";\n', + ], + ["namespace re-export", 'export * as legacy from "../actions/sandbox/exec";\n'], + [ + "namespace re-export with comments", + 'export /* keep */ * /* keep */ as legacy from "../actions/sandbox/exec";\n', + ], + [ + "namespace re-export with line comments", + 'export // keep\n* // keep\nas legacy from "../actions/sandbox/exec";\n', + ], + [ + "namespace re-export with adjacent comments", + 'export/**//**/*/**//**/as legacy from "../actions/sandbox/exec";\n', + ], + [ + "namespace re-export after an interpolated template", + 'const value = 1; const template = `x ${value} y`; export * as legacy from "../actions/sandbox/exec";\n', + ], + ["star re-export", 'export * from "../actions/sandbox/exec";\n'], + ])("rejects buffered sandbox commands through %s (#10991)", (_label, source) => { + const violations = scanFixture( + fixturePath("src/lib/onboard", "buffered-exec-helper-alternate"), + source, + ); + + expect(violations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ rule: "buffered-exec-uses-async-executor" }), + ]), + ); + }); + + it.each([ + ["another named export", 'export { execSandbox } from "../actions/sandbox/exec";\n'], + [ + "another export renamed to the legacy name", + 'export { execSandbox as buildOpenshellExecArgs } from "../actions/sandbox/exec";\n', + ], + [ + "a type-only named export", + 'export type { buildOpenshellExecArgs } from "../actions/sandbox/exec";\n', + ], + ["a type-only star export", 'export type * from "../actions/sandbox/exec";\n'], + [ + "a type-only namespace export", + 'export type * as legacy from "../actions/sandbox/exec";\n', + ], + [ + "comment and string namespace-export bait", + '// export * as legacy\nconst bait = "export * as legacy";\nexport { execSandbox } from "../actions/sandbox/exec";\n', + ], + [ + "template and regular-expression namespace-export bait", + 'const template = `export * as`; const pattern = /export * as/;\nexport { execSandbox } from "../actions/sandbox/exec";\n', + ], + ])("allows %s from the legacy helper module (#10991)", (_label, source) => { + const violations = scanFixture( + fixturePath("src/lib/onboard", "buffered-exec-helper-allowed-export"), + source, + ); + + expect(violations).not.toEqual( + expect.arrayContaining([ + expect.objectContaining({ rule: "buffered-exec-uses-async-executor" }), + ]), + ); + }); + + it("scans comment-heavy namespace-export near misses without backtracking (#10991)", () => { + const comments = "/*x*/".repeat(10_000); + const violations = scanFixture( + fixturePath("src/lib/onboard", "buffered-exec-helper-comment-noise"), + `const value = 1; const asValue = 2; export ${comments} { value }; export ${comments} * ${comments} from "../safe";\n`, + ); + + expect(violations).not.toEqual( + expect.arrayContaining([ + expect.objectContaining({ rule: "buffered-exec-uses-async-executor" }), + ]), + ); + }); + it("collects TypeScript import-equals references (#6245)", () => { const violations = scanFixture( fixturePath("src/lib/domain", "import-equals"), @@ -118,9 +281,7 @@ describe("CLI layer import boundaries (#6245)", () => { const violations = scanFixture(fixturePath("src/lib", "bin-lib-call"), source); expect(violations).toEqual( - expect.arrayContaining([ - expect.objectContaining({ rule: "src-no-bin-lib-shims" }), - ]), + expect.arrayContaining([expect.objectContaining({ rule: "src-no-bin-lib-shims" })]), ); }); @@ -270,12 +431,8 @@ describe("CLI layer import boundaries (#6245)", () => { "src/lib/domain", `emitted-specifier-importer-${sourceExtension.slice(1)}`, ); - const specifier = path - .relative(path.dirname(importer), target) - .split(path.sep) - .join("/"); - const emittedSpecifier = - specifier.slice(0, -sourceExtension.length) + emittedExtension; + const specifier = path.relative(path.dirname(importer), target).split(path.sep).join("/"); + const emittedSpecifier = specifier.slice(0, -sourceExtension.length) + emittedExtension; try { fs.writeFileSync(target, "export const value = true;\n"); fs.writeFileSync( diff --git a/test/runtime/policy/policy-tiers-onboard.test.ts b/test/runtime/policy/policy-tiers-onboard.test.ts index 4075fc993a8..56bbc5dbd44 100644 --- a/test/runtime/policy/policy-tiers-onboard.test.ts +++ b/test/runtime/policy/policy-tiers-onboard.test.ts @@ -139,7 +139,7 @@ function createSetupHarness({ note: (message) => notes.push(message), isNonInteractive: () => nonInteractive, waitForSandboxReady: async () => ({ ready: true, reason: "ready", error: null }), - waitForSandboxControlPlaneReady: () => true, + waitForSandboxControlPlaneReady: async () => true, syncPresetSelection: (sandboxName, current, selected, accessByName) => { syncCalls.push({ sandboxName, diff --git a/test/security/shellquote-sandbox.test.ts b/test/security/shellquote-sandbox.test.ts index a9daf75af30..fc3f00be56f 100644 --- a/test/security/shellquote-sandbox.test.ts +++ b/test/security/shellquote-sandbox.test.ts @@ -66,6 +66,7 @@ describe("sandboxName command hardening in onboard.js", () => { const preflightPath = sourceModule("onboard", "preflight.ts"); const credentialsPath = sourceModule("credentials", "store.ts"); const streamPath = sourceModule("sandbox", "create-stream.ts"); + const sandboxCommandCliPath = sourceModule("adapters", "openshell", "sandbox-command-cli.ts"); const onboardScriptMocksPath = JSON.stringify( path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), ); @@ -78,6 +79,7 @@ describe("sandboxName command hardening in onboard.js", () => { const runner = require(${runnerPath}); const registry = require(${registryPath}); const fixtureMocks = require(${onboardScriptMocksPath}); +fixtureMocks.mockStandaloneGatewayTeardownAuthority(); const preflight = require(${preflightPath}); const credentials = require(${credentialsPath}); const sandboxCreateStream = require(${streamPath}); @@ -133,6 +135,22 @@ runner.runCapture = (command) => { if (mockedCapture !== null) return mockedCapture; return ""; }; +const sandboxCommandCli = require(${sandboxCommandCliPath}); +const createCommandExecutor = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor; +sandboxCommandCli.createCliOpenShellSandboxCommandExecutor = (deps) => { + const executor = createCommandExecutor(deps); + return { + ...executor, + runBuffered: async (request) => { + const command = [ + "openshell", + ...sandboxCommandCli.buildCliOpenShellSandboxExecArgs(request), + ]; + commands.push({ type: "buffered", command: asText(command), env: null }); + return { outcome: { kind: "completed", exitCode: 0 }, stdout: "", stderr: "" }; + }, + }; +}; registry.getSandbox = () => null; registry.getDisabledChannels = () => []; registry.registerSandbox = () => true; @@ -236,7 +254,7 @@ try { ).toBe(true); expect( payload.commands.some((entry: { command: string }) => - entry.command.includes("sandbox exec -g nemoclaw --name my-assistant -- true"), + entry.command.includes("sandbox exec --name my-assistant -g nemoclaw -- true"), ), ).toBe(true); } finally { diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index d76179a608c..4e4b82a18a3 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -7,6 +7,10 @@ import { createRequire } from "node:module"; import { type MockInstance, vi } from "vitest"; import type { ManagedGatewayControlCompletion } from "../../src/lib/actions/sandbox/gateway-restart"; import type { SecretBoundaryRefusalReason } from "../../src/lib/actions/sandbox/hermes-secret-boundary-recovery"; +import type { + OpenShellSandboxBufferedCommandCompletion, + OpenShellSandboxBufferedCommandRequest, +} from "../../src/lib/adapters/openshell/sandbox-command"; import type { WslDetectionOptions } from "../../src/lib/platform"; import type { ConfigObject } from "../../src/lib/security/credential-filter"; import type { SandboxEntry } from "../../src/lib/state/registry"; @@ -67,6 +71,7 @@ export type ConnectHarness = { resolveAgentConfigSpy: MockInstance; restoreSandboxStartupState: RestoreSandboxStartupState; runAutoPairSpy: MockInstance; + sandboxRunBufferedSpy: MockInstance; runSandboxExecChildSpy: MockInstance; runOpenshellSpy: MockInstance; runSetupDnsProxySpy: MockInstance; @@ -183,6 +188,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne } as never)) as never); const runtime = requireDist("../../src/lib/adapters/openshell/runtime.js"); + const sandboxCommandCli = requireDist("../../src/lib/adapters/openshell/sandbox-command-cli.js"); const resolve = requireDist("../../src/lib/adapters/openshell/resolve.js"); const agentRuntime = requireDist("../../src/lib/agent/runtime.js"); const dns = requireDist("../../src/lib/actions/dns/index.js"); @@ -325,8 +331,8 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne )) as never); const recoverHermesPortableOllamaInferenceSpy = vi .spyOn(hermesInferenceRecovery, "recoverHermesPortableInferenceForConnectProbe") - .mockImplementation(((input: { - verifyRoute: () => unknown; + .mockImplementation((async (input: { + verifyRoute: () => Promise; prepareProbeDependency?: () => { release: () => void }; }) => { if (options.hermesInferenceRecoveryPhase) { @@ -343,7 +349,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne "nested recovery diagnostic canary", ); } - input.verifyRoute(); + await input.verifyRoute(); input.prepareProbeDependency?.().release(); return "reused"; }) as never); @@ -406,6 +412,47 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne }); const inferenceProbeResponses = [...(options.inferenceProbeResponses ?? [])]; const listOutputs = [...(options.listOutputs ?? [])]; + const sandboxRunBufferedSpy = vi.fn(async (request: OpenShellSandboxBufferedCommandRequest) => { + if (!request.command.join(" ").includes("inference.local/v1/models")) { + return { + outcome: { kind: "completed", exitCode: 0 }, + stdout: "", + stderr: "", + } satisfies OpenShellSandboxBufferedCommandCompletion; + } + const response = inferenceProbeResponses.shift() ?? "OK 200"; + if (typeof response === "string") { + return { + outcome: { kind: "completed", exitCode: 0 }, + stdout: response, + stderr: "", + } satisfies OpenShellSandboxBufferedCommandCompletion; + } + return { + outcome: + response.status === null + ? { kind: "failed", error: { kind: "capture", message: "capture failed" } } + : { kind: "completed", exitCode: response.status ?? 0 }, + stdout: response.output ?? "", + stderr: response.stderr ?? "", + } satisfies OpenShellSandboxBufferedCommandCompletion; + }); + vi.spyOn(sandboxCommandCli, "createCliOpenShellSandboxCommandExecutor").mockReturnValue({ + runBuffered: sandboxRunBufferedSpy, + }); + vi.spyOn( + sandboxCommandCli, + "createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor", + ).mockImplementation(((_dependencies: unknown, assertCurrent: () => void) => ({ + runBuffered: async (request: OpenShellSandboxBufferedCommandRequest) => { + assertCurrent(); + try { + return await sandboxRunBufferedSpy(request); + } finally { + assertCurrent(); + } + }, + })) as never); const captureOpenshellImplementation = (args: unknown) => { const argv = Array.isArray(args) ? args : []; if (argv[0] === "sandbox" && argv[1] === "list") { @@ -625,6 +672,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne resolveAgentConfigSpy, restoreSandboxStartupState: requireDist(connectModulePath).restoreSandboxStartupState, runAutoPairSpy, + sandboxRunBufferedSpy, runSandboxExecChildSpy, settlePortablePairingSpy, runOpenshellSpy,