From dafd88992e130d3c6fc433d9ad5a9782f4ace229 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 14:22:36 -0700 Subject: [PATCH 01/34] fix: reconcile non-root OpenClaw model config Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 92 ++++++-- .../runtime/nemoclaw-start-config-io.test.ts | 24 +- .../runtime/nemoclaw-start-reconcile.test.ts | 221 ++++++++++++++++-- 3 files changed, 290 insertions(+), 47 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 30e04575f5f..d923d0472ed 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -954,12 +954,6 @@ apply_model_override() { || [ -n "${NEMOCLAW_INFERENCE_API_OVERRIDE:-}" ] \ || return 0 - # Host overrides require root startup authority. - if [ "$(id -u)" -ne 0 ]; then - printf '[SECURITY] Model/inference overrides ignored — requires root (non-root mode cannot write to config)\n' >&2 - return 0 - fi - local config_file="/sandbox/.openclaw/openclaw.json" local hash_file="/sandbox/.openclaw/.config-hash" @@ -970,6 +964,11 @@ apply_model_override() { return 1 fi + if [ "$(id -u)" -ne 0 ] && [ ! -w "$config_file" ]; then + printf '[SECURITY] Model/inference overrides ignored: OpenClaw config is not writable by the sandbox user\n' >&2 + return 0 + fi + local model_override="${NEMOCLAW_MODEL_OVERRIDE:-}" local api_override="${NEMOCLAW_INFERENCE_API_OVERRIDE:-}" @@ -1107,8 +1106,8 @@ PYOVERRIDE # reconciliation the file's stale entry can be pushed back, reverting # the route. # -# Probe the live gateway via `openshell inference get --json` and -# treat it as the source of truth: when the gateway model differs +# Probe the live gateway via `openshell inference get` and treat its +# inference section as the source of truth: when the gateway model differs # from the file, align both primary and the inference provider's # first model entry so the agent identity and the gateway route stay # consistent across the next reconcile cycle. @@ -1126,44 +1125,91 @@ reconcile_agent_model_with_provider() { # overwrite the user's explicit choice with an inference/-prefixed variant. [ -z "${NEMOCLAW_MODEL_OVERRIDE:-}" ] || return 0 - if [ "$(id -u)" -ne 0 ]; then - return 0 - fi - local config_file="/sandbox/.openclaw/openclaw.json" local hash_file="/sandbox/.openclaw/.config-hash" [ -f "$config_file" ] || return 0 if [ -L "$config_file" ] || [ -L "$hash_file" ]; then + printf '[SECURITY] Refusing agent model reconciliation: config or hash path is a symlink\n' >&2 + return 1 + fi + + if [ "$(id -u)" -ne 0 ] && [ ! -w "$config_file" ]; then + printf '[config] Agent model reconciliation skipped: OpenClaw config is not writable by the sandbox user\n' >&2 return 0 fi local gateway_model="" if command -v openshell >/dev/null 2>&1; then gateway_model="$( - python3 - <<'PYPROBE' -import json, subprocess + /usr/bin/python3 -I - <<'PYPROBE' +import re +import subprocess +import sys + +ansi_escape = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|[@-_])") + try: result = subprocess.run( - ["openshell", "inference", "get", "--json"], + ["openshell", "inference", "get"], capture_output=True, + encoding="utf-8", + errors="replace", + text=True, timeout=3, check=False, ) -except Exception: +except subprocess.TimeoutExpired: + print("[config] Gateway model probe unavailable: openshell inference get timed out", file=sys.stderr) + raise SystemExit(0) +except OSError: + print("[config] Gateway model probe unavailable: openshell inference get could not start", file=sys.stderr) raise SystemExit(0) if result.returncode != 0: + print( + f"[config] Gateway model probe unavailable: openshell inference get exited with status {result.returncode}", + file=sys.stderr, + ) raise SystemExit(0) -try: - data = json.loads(result.stdout) -except Exception: + +lines = ansi_escape.sub("", result.stdout).splitlines() +section_count = 0 +in_inference_section = False +models = [] +unconfigured = False +for line in lines: + if re.fullmatch(r"(?:Gateway )?Inference:\s*", line, re.IGNORECASE): + section_count += 1 + in_inference_section = True + continue + if in_inference_section and re.fullmatch(r"\S.*:\s*", line): + in_inference_section = False + continue + if not in_inference_section: + continue + if re.fullmatch(r"\s*Not configured\s*", line, re.IGNORECASE): + unconfigured = True + continue + match = re.fullmatch(r"\s*Model:\s*(.+?)\s*", line) + if match: + models.append(match.group(1)) + +if section_count == 1 and unconfigured and not models: + print("[config] Gateway model probe unavailable: openshell reported no configured inference route", file=sys.stderr) + raise SystemExit(0) +if section_count != 1 or len(models) != 1: + print("[config] Gateway model probe unavailable: openshell returned malformed inference output", file=sys.stderr) raise SystemExit(0) -model = data.get("model") if isinstance(data, dict) else None -if isinstance(model, str) and model: - print(model) +model = models[0] +if len(model) > 512 or re.fullmatch(r"[A-Za-z0-9._:/-]+", model) is None: + print("[SECURITY] Gateway model probe rejected an unsafe model identifier", file=sys.stderr) + raise SystemExit(0) +print(model) PYPROBE )" + else + printf '[config] Gateway model probe unavailable: openshell is not installed\n' >&2 fi local provider_model_ref @@ -1261,6 +1307,8 @@ if os.environ.get("RECONCILE_SOURCE") == "gateway": models_list[0] = first first["id"] = bare first["name"] = provider_model + first.pop("contextWindow", None) + first.pop("maxTokens", None) with open(config_file, "w") as f: json.dump(cfg, f, indent=2) PYRECONCILE_WRITE diff --git a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts index cb5c34944f6..b8512b45ea8 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts @@ -24,7 +24,7 @@ describe("runtime model override (#759)", () => { return extractShellFunctionFromSource(src, name); } - function runApplyModelOverride(env: Record = {}) { + function runApplyModelOverride(env: Record = {}, userId = 0) { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-model-override-")); const openclawDir = path.join(root, ".openclaw"); fs.mkdirSync(openclawDir, { recursive: true }); @@ -64,7 +64,7 @@ describe("runtime model override (#759)", () => { const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", - "id() { echo 0; }", + `id() { echo ${userId}; }`, "normalize_mutable_config_perms() { :; }", 'run_openclaw_config_as_owner() { "$@"; }', `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, @@ -124,6 +124,26 @@ describe("runtime model override (#759)", () => { expect(modes.hash).toBe(0o660); }); + it("applies an explicit model override as a non-root custom image user (#12033)", () => { + const { result, config, hash, modes } = runApplyModelOverride( + { NEMOCLAW_MODEL_OVERRIDE: "new-model" }, + 1000, + ); + + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("new-model"); + expect(config.models.providers.inference.models[0]).toMatchObject({ + id: "new-model", + name: "new-model", + }); + expect(hash).toContain("openclaw.json"); + expect(modes).toEqual({ + dir: 0o2770, + config: 0o660, + hash: 0o660, + }); + }); + it.each([ { env: { NEMOCLAW_CONTEXT_WINDOW: "not-a-number" }, diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 70b4e207c9e..b53da1747db 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -17,19 +17,24 @@ const START_SCRIPT = path.join( interface RunReconcileOptions { /** - * Output the stubbed `openshell inference get --json` should print. + * Model the stubbed `openshell inference get` should print. * - undefined → no openshell on PATH (probe falls back to in-file logic). - * - "" → openshell exists but returns empty JSON (probe yields no model). - * - non-empty string → openshell returns `{"model": }`. + * - "" → openshell exists but returns an unconfigured inference section. + * - non-empty string → openshell returns a configured inference section. * Ignored when `gatewayRawOutput` is set. */ gatewayModel?: string; /** - * Raw stdout the stub emits instead of a JSON-formatted payload. Use to - * exercise malformed-JSON or unexpected-shape paths. Takes precedence - * over `gatewayModel` when both are set. + * Raw stdout the stub emits instead of a formatted inference section. + * Takes precedence over `gatewayModel` when both are set. */ gatewayRawOutput?: string; + gatewayExitCode?: number; + gatewayDelaySeconds?: number; + userId?: number; + symlink?: "config" | "hash"; + configWritable?: boolean; + hashFailure?: boolean; env?: Record; } @@ -53,9 +58,24 @@ describe("agent identity reconciliation with provider (#3175)", () => { fs.writeFileSync(configPath, JSON.stringify(initialConfig)); fs.writeFileSync(hashPath, "oldhash\n"); fs.chmodSync(openclawDir, 0o2770); - fs.chmodSync(configPath, 0o660); + fs.chmodSync(configPath, options.configWritable === false ? 0o440 : 0o660); fs.chmodSync(hashPath, 0o660); + const prepareSymlink = { + config: () => { + const target = path.join(openclawDir, "openclaw.real.json"); + fs.renameSync(configPath, target); + fs.symlinkSync(target, configPath); + }, + hash: () => { + const target = path.join(openclawDir, ".config-hash.real"); + fs.renameSync(hashPath, target); + fs.symlinkSync(target, hashPath); + }, + none: () => undefined, + }[options.symlink ?? "none"]; + prepareSymlink(); + const binDir = path.join(root, "bin"); fs.mkdirSync(binDir); const installStub = @@ -65,13 +85,15 @@ describe("agent identity reconciliation with provider (#3175)", () => { options.gatewayRawOutput !== undefined ? options.gatewayRawOutput : options.gatewayModel === "" - ? "{}" - : JSON.stringify({ model: options.gatewayModel }); + ? "Gateway Inference:\n Not configured\n" + : `Gateway Inference:\n Provider: test-provider\n Model: ${options.gatewayModel}\n`; const stub = [ "#!/usr/bin/env bash", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - ` printf '%s' ${JSON.stringify(payload)}`, - " exit 0", + ' [ "$#" -eq 2 ] || exit 64', + options.gatewayDelaySeconds ? ` sleep ${options.gatewayDelaySeconds}` : " :", + ` printf '%b' ${JSON.stringify(payload)}`, + ` exit ${options.gatewayExitCode ?? 0}`, "fi", "exit 1", "", @@ -82,7 +104,9 @@ describe("agent identity reconciliation with provider (#3175)", () => { const helperFns = [ "normalize_mutable_config_perms() { :; }", 'run_openclaw_config_as_owner() { "$@"; }', - `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, + options.hashFailure + ? "ensure_mutable_openclaw_config_hash() { return 19; }" + : `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, ].join("\n"); const fn = extractShellFunction("reconcile_agent_model_with_provider").replaceAll( "/sandbox", @@ -91,7 +115,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", - "id() { echo 0; }", + `id() { echo ${options.userId ?? 0}; }`, helperFns, fn, "reconcile_agent_model_with_provider", @@ -233,7 +257,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).toBe("oldhash\n"); }); - it("still reconciles from the live gateway when no explicit model override is set", () => { + it("reconciles a sandbox-owned config as a non-root custom image user (#12033)", () => { const { result, config, hash } = runReconcile( { agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, @@ -246,7 +270,11 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, }, }, - { gatewayModel: "nvidia/nemotron-3-super-120b-a12b" }, + { + gatewayRawOutput: + "\\x1b[32mGateway Inference:\\x1b[0m\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + userId: 1000, + }, ); expect(result.status).toBe(0); @@ -263,6 +291,29 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).toContain("openclaw.json"); }); + it("explains why a non-root user cannot reconcile a sealed config (#12033)", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "old-model", name: "inference/old-model" }], + }, + }, + }, + }; + const { result, config, hash } = runReconcile(initial, { + gatewayModel: "new-model", + userId: 1000, + configWritable: false, + }); + + expect(result.status).toBe(0); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(result.stderr).toContain("OpenClaw config is not writable by the sandbox user"); + }); + it("patches primary AND models[0] to the live gateway model when both file fields are stale", () => { const { result, config, hash } = runReconcile( { @@ -271,7 +322,14 @@ describe("agent identity reconciliation with provider (#3175)", () => { providers: { inference: { api: "openai-completions", - models: [{ id: "nvidia-routed", name: "inference/nvidia-routed" }], + models: [ + { + id: "nvidia-routed", + name: "inference/nvidia-routed", + contextWindow: 131072, + maxTokens: 4096, + }, + ], }, }, }, @@ -289,6 +347,8 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(config.models.providers.inference.models[0].id).toBe( "nvidia/nemotron-3-super-120b-a12b", ); + expect(config.models.providers.inference.models[0]).not.toHaveProperty("contextWindow"); + expect(config.models.providers.inference.models[0]).not.toHaveProperty("maxTokens"); expect(hash).not.toBe("oldhash\n"); expect(hash).toContain("openclaw.json"); }); @@ -326,7 +386,14 @@ describe("agent identity reconciliation with provider (#3175)", () => { providers: { inference: { api: "openai-completions", - models: [{ id: "nvidia/synced", name: "inference/nvidia/synced" }], + models: [ + { + id: "nvidia/synced", + name: "inference/nvidia/synced", + contextWindow: 131072, + maxTokens: 4096, + }, + ], }, }, }, @@ -336,6 +403,10 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(result.status).toBe(0); expect(config.agents.defaults.model.primary).toBe("inference/nvidia/synced"); + expect(config.models.providers.inference.models[0]).toMatchObject({ + contextWindow: 131072, + maxTokens: 4096, + }); expect(hash).toBe("oldhash\n"); }); @@ -458,12 +529,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).not.toBe("oldhash\n"); }); - it("falls back to the in-file reconcile when the gateway probe emits malformed JSON", () => { - // A future packaging shift could ship an `openshell` shim that doesn't - // implement `inference get --json` and returns junk on stdout. The - // current absorb-via-SystemExit(0) path should still leave the user - // in the legacy in-file reconcile state — pinning this so a refactor - // of the probe parser can't silently degrade to "do nothing". + it("warns and falls back to the in-file reconcile for malformed gateway output", () => { const { result, config } = runReconcile( { agents: { defaults: { model: { primary: "inference/old-model" } } }, @@ -484,5 +550,114 @@ describe("agent identity reconciliation with provider (#3175)", () => { // model, models[0] stays untouched (same shape as the empty-probe case). expect(config.agents.defaults.model.primary).toBe("inference/nvidia/new-model"); expect(config.models.providers.inference.models[0].id).toBe("nvidia/new-model"); + expect(result.stderr).toContain("openshell returned malformed inference output"); + expect(result.stderr).not.toContain(""); + }); + + it.each([ + ["unsafe characters", "model;unsafe"], + ["an oversized identifier", "m".repeat(513)], + ])("rejects %s from the gateway without logging the value", (_, gatewayModel) => { + const { result, config, hash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "safe-file-model", name: "inference/safe-file-model" }], + }, + }, + }, + }, + { gatewayModel }, + ); + + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/safe-file-model"); + expect(hash).not.toBe("oldhash\n"); + expect(result.stderr).toContain("rejected an unsafe model identifier"); + expect(result.stderr).not.toContain(gatewayModel); + }); + + it("warns and falls back when the gateway probe command fails", () => { + const { result, config } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "file-model", name: "inference/file-model" }], + }, + }, + }, + }, + { gatewayRawOutput: "provider-secret-output", gatewayExitCode: 7 }, + ); + + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/file-model"); + expect(result.stderr).toContain("exited with status 7"); + expect(result.stderr).not.toContain("provider-secret-output"); + }); + + it("warns and falls back when the gateway probe times out", () => { + const { result, config } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "file-model", name: "inference/file-model" }], + }, + }, + }, + }, + { gatewayModel: "delayed-model", gatewayDelaySeconds: 4 }, + ); + + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/file-model"); + expect(result.stderr).toContain("timed out"); + }); + + it.each(["config", "hash"] as const)("fails closed for a symlinked %s path", (symlink) => { + const { result, config, hash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "file-model", name: "inference/file-model" }], + }, + }, + }, + }, + { gatewayModel: "gateway-model", symlink }, + ); + + expect(result.status).toBe(1); + expect(config.agents.defaults.model.primary).toBe("inference/old-model"); + expect(hash).toBe("oldhash\n"); + expect(result.stderr).toContain("config or hash path is a symlink"); + }); + + it("propagates a hash refresh failure after the config write", () => { + const { result, config, hash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "file-model", name: "inference/file-model" }], + }, + }, + }, + }, + { gatewayModel: "gateway-model", hashFailure: true }, + ); + + expect(result.status).toBe(19); + expect(config.agents.defaults.model.primary).toBe("inference/gateway-model"); + expect(hash).toBe("oldhash\n"); }); }); From e362e835a5f50c05bc557760bafcf6fda39d14af Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 14:51:33 -0700 Subject: [PATCH 02/34] fix: preserve limits during primary reconciliation Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 9 ++++-- .../runtime/nemoclaw-start-config-io.test.ts | 32 ++++++++++--------- .../runtime/nemoclaw-start-reconcile.test.ts | 32 +++++++++++++++++++ 3 files changed, 56 insertions(+), 17 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index d923d0472ed..bc3726d27b7 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1305,10 +1305,15 @@ if os.environ.get("RECONCILE_SOURCE") == "gateway": if not isinstance(first, dict): first = {} models_list[0] = first + provider_model_unchanged = ( + first.get("name") == provider_model + and first.get("id") in (bare, provider_model) + ) first["id"] = bare first["name"] = provider_model - first.pop("contextWindow", None) - first.pop("maxTokens", None) + if not provider_model_unchanged: + first.pop("contextWindow", None) + first.pop("maxTokens", None) with open(config_file, "w") as f: json.dump(cfg, f, indent=2) PYRECONCILE_WRITE diff --git a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts index b8512b45ea8..db7cd19fffe 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawn, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -56,6 +57,11 @@ describe("runtime model override (#759)", () => { fs.chmodSync(openclawDir, 0o2770); fs.chmodSync(configPath, 0o660); fs.chmodSync(hashPath, 0o660); + const initialModes = { + dir: fs.statSync(openclawDir).mode & 0o7777, + config: fs.statSync(configPath).mode & 0o777, + hash: fs.statSync(hashPath).mode & 0o777, + }; const helperFns = [extractShellFunction("openclaw_config_dir_owner")] .join("\n") @@ -79,7 +85,9 @@ describe("runtime model override (#759)", () => { encoding: "utf-8", env: { ...process.env, ...env }, }); - const config = JSON.parse(fs.readFileSync(configPath, "utf-8")); + const configBytes = fs.readFileSync(configPath); + const config = JSON.parse(configBytes.toString("utf-8")); + const configDigest = createHash("sha256").update(configBytes).digest("hex"); const hash = fs.readFileSync(hashPath, "utf-8"); const modes = { dir: fs.statSync(openclawDir).mode & 0o7777, @@ -87,11 +95,11 @@ describe("runtime model override (#759)", () => { hash: fs.statSync(hashPath).mode & 0o777, }; fs.rmSync(root, { recursive: true, force: true }); - return { result, config, hash, modes }; + return { result, config, configDigest, hash, initialModes, modes }; } it("applies model, API, context, max-token, and reasoning overrides and recomputes the hash", () => { - const { result, config, hash } = runApplyModelOverride({ + const { result, config, configDigest, hash } = runApplyModelOverride({ NEMOCLAW_MODEL_OVERRIDE: "new-model", NEMOCLAW_INFERENCE_API_OVERRIDE: "anthropic-messages", NEMOCLAW_CONTEXT_WINDOW: "4096", @@ -110,22 +118,20 @@ describe("runtime model override (#759)", () => { maxTokens: 512, reasoning: true, }); - expect(hash).toContain("openclaw.json"); + expect(hash.trim().split(/\s+/)).toEqual([configDigest, "openclaw.json"]); }); it("restores mutable config permissions after successful overrides", () => { - const { result, modes } = runApplyModelOverride({ + const { result, initialModes, modes } = runApplyModelOverride({ NEMOCLAW_MODEL_OVERRIDE: "new-model", }); expect(result.status).toBe(0); - expect(modes.dir).toBe(0o2770); - expect(modes.config).toBe(0o660); - expect(modes.hash).toBe(0o660); + expect(modes).toEqual(initialModes); }); it("applies an explicit model override as a non-root custom image user (#12033)", () => { - const { result, config, hash, modes } = runApplyModelOverride( + const { result, config, configDigest, hash, initialModes, modes } = runApplyModelOverride( { NEMOCLAW_MODEL_OVERRIDE: "new-model" }, 1000, ); @@ -136,12 +142,8 @@ describe("runtime model override (#759)", () => { id: "new-model", name: "new-model", }); - expect(hash).toContain("openclaw.json"); - expect(modes).toEqual({ - dir: 0o2770, - config: 0o660, - hash: 0o660, - }); + expect(hash.trim().split(/\s+/)).toEqual([configDigest, "openclaw.json"]); + expect(modes).toEqual(initialModes); }); it.each([ diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index b53da1747db..53f45d93c54 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -410,6 +410,38 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).toBe("oldhash\n"); }); + it("preserves explicit limits when only the primary model reference is stale", () => { + const { result, config, hash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/stale-primary" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: [ + { + id: "nvidia/synced", + name: "inference/nvidia/synced", + contextWindow: 131072, + maxTokens: 4096, + }, + ], + }, + }, + }, + }, + { gatewayModel: "nvidia/synced" }, + ); + + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/nvidia/synced"); + expect(config.models.providers.inference.models[0]).toMatchObject({ + contextWindow: 131072, + maxTokens: 4096, + }); + expect(hash).not.toBe("oldhash\n"); + }); + it("falls back to the in-file reconcile when the gateway probe returns no model", () => { const { result, config } = runReconcile( { From f380fc657c77cc677592f340aa997a988dd152e1 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:07:30 -0700 Subject: [PATCH 03/34] fix: preserve limits for matching model ids Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 5 +-- .../runtime/nemoclaw-start-reconcile.test.ts | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index bc3726d27b7..1fcb26ce073 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1305,10 +1305,7 @@ if os.environ.get("RECONCILE_SOURCE") == "gateway": if not isinstance(first, dict): first = {} models_list[0] = first - provider_model_unchanged = ( - first.get("name") == provider_model - and first.get("id") in (bare, provider_model) - ) + provider_model_unchanged = first.get("id") in (bare, provider_model) first["id"] = bare first["name"] = provider_model if not provider_model_unchanged: diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 53f45d93c54..f708f084876 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -442,6 +442,39 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).not.toBe("oldhash\n"); }); + it("preserves explicit limits when the provider ID matches but its name is stale", () => { + const { result, config, hash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/nvidia/synced" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: [ + { + id: "nvidia/synced", + name: "inference/stale-name", + contextWindow: 131072, + maxTokens: 4096, + }, + ], + }, + }, + }, + }, + { gatewayModel: "nvidia/synced" }, + ); + + expect(result.status).toBe(0); + expect(config.models.providers.inference.models[0]).toMatchObject({ + id: "nvidia/synced", + name: "inference/nvidia/synced", + contextWindow: 131072, + maxTokens: 4096, + }); + expect(hash).not.toBe("oldhash\n"); + }); + it("falls back to the in-file reconcile when the gateway probe returns no model", () => { const { result, config } = runReconcile( { From 8692e78f67661fae7ecc5b25e62def95269f7e69 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 16:39:50 -0700 Subject: [PATCH 04/34] test(openclaw): close custom image review gaps Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/switch-models.mdx | 9 +++ .../runtime/nemoclaw-start-config-io.test.ts | 37 +++++---- .../runtime/nemoclaw-start-reconcile.test.ts | 79 +++++++++++-------- .../live/openclaw-inference-switch-helpers.ts | 49 ++++++++++++ .../live/openclaw-inference-switch.test.ts | 64 +++++++++++++-- .../openclaw-custom-image-fixture.test.ts | 37 +++++++++ 6 files changed, 222 insertions(+), 53 deletions(-) create mode 100644 test/e2e/support/openclaw-custom-image-fixture.test.ts diff --git a/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index 731fe107736..ab916ceedcb 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -43,6 +43,15 @@ If the route metadata is incomplete, NemoClaw stops and tells you to re-run onbo + + +When the selected model ID changes, NemoClaw removes `contextWindow` and `maxTokens` values inherited from the previous model entry. +OpenClaw then uses the new model's catalog values or defaults. +To keep explicit limits for the new model, recreate the sandbox after you set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model. +Refer to [Configure Model Limits](configure-model-limits) for the environment variable requirements. + + + For Hermes, the command recomputes the target model's context window before it updates the main configuration and dashboard profile. diff --git a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts index db7cd19fffe..4168df5b84c 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts @@ -81,21 +81,28 @@ describe("runtime model override (#759)", () => { ].join("\n"); const script = path.join(root, "run.sh"); fs.writeFileSync(script, wrapper, { mode: 0o700 }); - const result = spawnSync("bash", [script], { - encoding: "utf-8", - env: { ...process.env, ...env }, - }); - const configBytes = fs.readFileSync(configPath); - const config = JSON.parse(configBytes.toString("utf-8")); - const configDigest = createHash("sha256").update(configBytes).digest("hex"); - const hash = fs.readFileSync(hashPath, "utf-8"); - const modes = { - dir: fs.statSync(openclawDir).mode & 0o7777, - config: fs.statSync(configPath).mode & 0o777, - hash: fs.statSync(hashPath).mode & 0o777, - }; - fs.rmSync(root, { recursive: true, force: true }); - return { result, config, configDigest, hash, initialModes, modes }; + const configFd = fs.openSync(configPath, "r"); + const hashFd = fs.openSync(hashPath, "r"); + try { + const result = spawnSync("bash", [script], { + encoding: "utf-8", + env: { ...process.env, ...env }, + }); + const configBytes = fs.readFileSync(configFd); + const config = JSON.parse(configBytes.toString("utf-8")); + const configDigest = createHash("sha256").update(configBytes).digest("hex"); + const hash = fs.readFileSync(hashFd, "utf-8"); + const modes = { + dir: fs.statSync(openclawDir).mode & 0o7777, + config: fs.fstatSync(configFd).mode & 0o777, + hash: fs.fstatSync(hashFd).mode & 0o777, + }; + return { result, config, configDigest, hash, initialModes, modes }; + } finally { + fs.closeSync(hashFd); + fs.closeSync(configFd); + fs.rmSync(root, { recursive: true, force: true }); + } } it("applies model, API, context, max-token, and reasoning overrides and recomputes the hash", () => { diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index f708f084876..1e4abf3ab55 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -32,6 +32,7 @@ interface RunReconcileOptions { gatewayExitCode?: number; gatewayDelaySeconds?: number; userId?: number; + useActualUser?: boolean; symlink?: "config" | "hash"; configWritable?: boolean; hashFailure?: boolean; @@ -103,7 +104,9 @@ describe("agent identity reconciliation with provider (#3175)", () => { const helperFns = [ "normalize_mutable_config_perms() { :; }", - 'run_openclaw_config_as_owner() { "$@"; }', + options.useActualUser + ? extractShellFunction("run_openclaw_config_as_owner") + : 'run_openclaw_config_as_owner() { "$@"; }', options.hashFailure ? "ensure_mutable_openclaw_config_hash() { return 19; }" : `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, @@ -115,7 +118,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", - `id() { echo ${options.userId ?? 0}; }`, + ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), helperFns, fn, "reconcile_agent_model_with_provider", @@ -257,39 +260,51 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).toBe("oldhash\n"); }); - it("reconciles a sandbox-owned config as a non-root custom image user (#12033)", () => { - const { result, config, hash } = runReconcile( - { - agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, - models: { - providers: { - inference: { - api: "openai-completions", - models: [{ id: "nvidia-routed", name: "inference/nvidia-routed" }], + it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( + "reconciles an actually owned config as the current non-root user (#12033)", + () => { + const { result, config, hash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: [ + { + id: "nvidia-routed", + name: "inference/nvidia-routed", + contextWindow: 131072, + maxTokens: 4096, + }, + ], + }, }, }, }, - }, - { - gatewayRawOutput: - "\\x1b[32mGateway Inference:\\x1b[0m\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", - userId: 1000, - }, - ); - - expect(result.status).toBe(0); - expect(config.agents.defaults.model.primary).toBe( - "inference/nvidia/nemotron-3-super-120b-a12b", - ); - expect(config.models.providers.inference.models[0].name).toBe( - "inference/nvidia/nemotron-3-super-120b-a12b", - ); - expect(config.models.providers.inference.models[0].id).toBe( - "nvidia/nemotron-3-super-120b-a12b", - ); - expect(hash).not.toBe("oldhash\n"); - expect(hash).toContain("openclaw.json"); - }); + { + gatewayRawOutput: + "\\x1b[32mGateway Inference:\\x1b[0m\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + useActualUser: true, + }, + ); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(config.agents.defaults.model.primary).toBe( + "inference/nvidia/nemotron-3-super-120b-a12b", + ); + expect(config.models.providers.inference.models[0].name).toBe( + "inference/nvidia/nemotron-3-super-120b-a12b", + ); + expect(config.models.providers.inference.models[0].id).toBe( + "nvidia/nemotron-3-super-120b-a12b", + ); + expect(config.models.providers.inference.models[0]).not.toHaveProperty("contextWindow"); + expect(config.models.providers.inference.models[0]).not.toHaveProperty("maxTokens"); + expect(hash).not.toBe("oldhash\n"); + expect(hash).toContain("openclaw.json"); + }, + ); it("explains why a non-root user cannot reconcile a sealed config (#12033)", () => { const initial = { diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 6c336a5f6ea..35ba477a8a9 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -7,8 +7,57 @@ // accepted while echoed or embedded tokens are rejected, without gating on // NEMOCLAW_RUN_LIVE_E2E=1. +import fs from "node:fs"; +import path from "node:path"; + import type { RetryFailureClass } from "../../../tools/e2e/retry-evidence.mts"; +export const BAKED_STALE_CONTEXT_WINDOW = 131_072; +export const BAKED_STALE_MAX_TOKENS = 4_095; + +export function stageNonRootCustomOpenClawImageDockerfile( + home: string, + imageReference: string, +): string { + const buildContext = path.join(home, "custom-image"); + const dockerfile = path.join(buildContext, "Dockerfile"); + fs.mkdirSync(buildContext, { recursive: true }); + fs.writeFileSync( + dockerfile, + [ + `FROM ${imageReference}`, + "ARG NEMOCLAW_TOOL_DISCLOSURE=progressive", + "ENV NEMOCLAW_TOOL_DISCLOSURE=${NEMOCLAW_TOOL_DISCLOSURE}", + "USER root", + "RUN node <<'NODE'", + 'const fs = require("node:fs");', + 'const configPath = "/sandbox/.openclaw/openclaw.json";', + 'const config = JSON.parse(fs.readFileSync(configPath, "utf8"));', + 'const staleModel = "nvidia/baked-stale-model";', + "config.agents.defaults.model.primary = `inference/${staleModel}`;", + "const model = config.models.providers.inference.models[0];", + "model.id = staleModel;", + "model.name = `inference/${staleModel}`;", + `model.contextWindow = ${BAKED_STALE_CONTEXT_WINDOW};`, + `model.maxTokens = ${BAKED_STALE_MAX_TOKENS};`, + "fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\\n`);", + "NODE", + "RUN cd /sandbox/.openclaw && sha256sum openclaw.json >.config-hash && chown sandbox:sandbox openclaw.json .config-hash && chmod 660 openclaw.json .config-hash", + "USER sandbox", + "", + ].join("\n"), + ); + return dockerfile; +} + +export async function whenCustomImage( + dockerfile: string | undefined, + verify: () => Promise, +): Promise { + if (!dockerfile) return; + await verify(); +} + export interface OpenClawPostSwitchInferenceAttempt { exitCode: number | null; httpStatus: string; diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 96d1f37cf01..400abb21046 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -48,6 +48,10 @@ import { import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import { runBoundedRetry } from "../../../tools/e2e/retry-evidence.mts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { + liveE2eManagedImageCatalog, + readLiveE2eManagedImageCatalogContracts, +} from "../../../src/lib/onboard/workload/preparation.ts"; import { agentReplyContainsToken, anthropicToolCount, @@ -56,6 +60,8 @@ import { MOCK_BASELINE_MODEL, mockBaselineInference, parseOpenClawGatewayModelRun, + stageNonRootCustomOpenClawImageDockerfile, + whenCustomImage, } from "./openclaw-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_MODEL, @@ -160,7 +166,7 @@ function proveMockBaselineAuthentication( ): Promise { return baseline ? proveSelectedMockBaselineAuthentication(baseline, sandbox, home, artifacts) - : Promise.resolve(expect(baseline).toBeUndefined()); + : Promise.resolve(); } async function proveSelectedMockBaselineAuthentication( @@ -514,7 +520,6 @@ async function assertRegistryAndSession( const registryPath = path.join(home, ".nemoclaw", "sandboxes.json"); const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")) as SandboxRegistry; const sandbox = registry.sandboxes?.[SANDBOX_NAME]; - expect(sandbox, `sandbox ${SANDBOX_NAME} missing from registry`).toBeTruthy(); expect(sandbox?.provider).toBe(SWITCH_PROVIDER); expect(sandbox?.model).toBe(SWITCH_MODEL); expect(sandbox?.nimContainer).toBeNull(); @@ -539,7 +544,6 @@ async function assertRegistryAndSession( const sessionPath = path.join(home, ".nemoclaw", "onboard-session.json"); const session = JSON.parse(fs.readFileSync(sessionPath, "utf8")) as OnboardSession; - expect(Object.keys(session).length, "onboard session is empty").toBeGreaterThan(0); expect(session.sandboxName).toBe(SANDBOX_NAME); expect(session.provider).toBe(SWITCH_PROVIDER); expect(session.model).toBe(SWITCH_MODEL); @@ -587,7 +591,6 @@ async function assertOpenClawConfig(sandbox: SandboxClient, home: string): Promi expect(provider?.api).toBe(SWITCH_INFERENCE_API); expect(firstModel?.id).toBe(SWITCH_MODEL); expect(firstModel?.name).toBe(expectedPrimary); - expect(typeof firstModel?.maxTokens).toBe("number"); expect(firstModel?.maxTokens).toBeGreaterThan(0); const hashCheck = await sandboxShell( @@ -600,7 +603,6 @@ async function assertOpenClawConfig(sandbox: SandboxClient, home: string): Promi }, ); expect(hashCheck.exitCode, resultText(hashCheck)).toBe(0); - expect(hashCheck.stdout.trim()).toBe("OK"); } function httpStatusFromResponse(response: string): string { @@ -944,6 +946,7 @@ test( contracts: [ "the selected runtime is available and an authenticated compatible baseline endpoint is staged", "install.sh --non-interactive onboards an OpenClaw sandbox", + "Docker execution also proves non-root custom-image startup reconciles a divergent baked model and removes its stale limits", "when selected, the mock baseline route completes one explicit authenticated fixture request", "nemoclaw inference set switches the running sandbox route", "OpenClaw gateway is supervisor-restarted after every changed inference configuration", @@ -982,6 +985,7 @@ test( const baseline = baselineProvider ? mockBaselineInference(baselineProvider.baseUrl) : requireHostedInferenceConfig(secrets); + const baselineModel = baseline.env.NEMOCLAW_MODEL; const apiKey = baseline.apiKey; const publicApiKey = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER @@ -992,6 +996,14 @@ test( ); const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-switch-home-")); + const selectedImageCatalog = liveE2eManagedImageCatalog(process.env); + const customImageContract = selectedImageCatalog + ? readLiveE2eManagedImageCatalogContracts(selectedImageCatalog).get("openclaw") + : undefined; + const customImageDockerfile = + (process.env.NEMOCLAW_GATEWAY_RUNTIME ?? "docker") === "docker" && customImageContract + ? stageNonRootCustomOpenClawImageDockerfile(home, customImageContract?.reference ?? "") + : undefined; let mockProvider: MockAnthropicProvider | undefined; cleanup.trackDisposable( `remove OpenClaw inference switch test home for ${SANDBOX_NAME}`, @@ -1035,6 +1047,12 @@ test( cwd: REPO_ROOT, env: commandEnv(home, { ...baseline.env, + ...(customImageDockerfile + ? { + NEMOCLAW_FROM_DOCKERFILE: customImageDockerfile, + NEMOCLAW_SANDBOX_PREBUILD: "1", + } + : {}), NEMOCLAW_RECREATE_SANDBOX: "1", }), redactionValues, @@ -1052,6 +1070,41 @@ test( skip("NVIDIA endpoint validation was unavailable/rate-limited during onboarding"); } expect(install.exitCode, installText).toBe(0); + await whenCustomImage(customImageDockerfile, async () => { + const startupConfigResult = await sandbox.exec( + SANDBOX_NAME, + ["cat", "/sandbox/.openclaw/openclaw.json"], + { + artifactName: "read-openclaw-config-after-custom-image-startup", + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }, + ); + const startupConfig = JSON.parse(startupConfigResult.stdout) as OpenClawConfig; + const startupModel = startupConfig.models?.providers?.inference?.models?.[0]; + expect(startupConfig.agents?.defaults?.model?.primary).toBe(`inference/${baselineModel}`); + expect(startupModel?.id).toBe(baselineModel); + expect(startupModel).not.toHaveProperty("contextWindow"); + expect(startupModel).not.toHaveProperty("maxTokens"); + + const runtimeUser = await sandbox.exec(SANDBOX_NAME, ["id", "-u"], { + artifactName: "read-custom-image-runtime-user", + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }); + expect(Number(runtimeUser.stdout.trim())).toBeGreaterThan(0); + + const startupHash = await sandboxShell( + sandbox, + home, + "cd /sandbox/.openclaw && sha256sum -c .config-hash --status", + { + artifactName: "openclaw-config-hash-after-custom-image-startup", + timeoutMs: COMMAND_TIMEOUT_MS, + }, + ); + expect(startupHash.exitCode, resultText(startupHash)).toBe(0); + }); await proveMockBaselineAuthentication(baselineProvider, sandbox, home, artifacts); progress.phase("prepare the switched provider and endpoint"); @@ -1076,7 +1129,6 @@ test( switchBinding && redactionValues.push(switchBinding.credentialValue); progress.phase("switch the route and verify restart semantics"); - expect(baseline.env.NEMOCLAW_PREFERRED_API).toBe("openai-completions"); const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1"; expect(SWITCH_INFERENCE_API).toBe( apiFamilyChanges ? "anthropic-messages" : "openai-completions", diff --git a/test/e2e/support/openclaw-custom-image-fixture.test.ts b/test/e2e/support/openclaw-custom-image-fixture.test.ts new file mode 100644 index 00000000000..da603e058e7 --- /dev/null +++ b/test/e2e/support/openclaw-custom-image-fixture.test.ts @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { validateToolDisclosureDockerfileContract } from "../../../src/lib/onboard/dockerfile-tool-disclosure-contract.ts"; +import { MANAGED_IMAGE_REPOSITORIES } from "../../../src/lib/onboard/managed-image/contract.ts"; +import { + BAKED_STALE_CONTEXT_WINDOW, + BAKED_STALE_MAX_TOKENS, + stageNonRootCustomOpenClawImageDockerfile, +} from "../live/openclaw-inference-switch-helpers.ts"; + +describe("OpenClaw custom-image inference fixture", () => { + it("layers stale model limits onto the exact selected image and restores a non-root final user", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-image-fixture-")); + try { + const expectedImage = `${MANAGED_IMAGE_REPOSITORIES.openclaw}@sha256:${"1".repeat(64)}`; + const dockerfilePath = stageNonRootCustomOpenClawImageDockerfile(home, expectedImage); + const dockerfile = fs.readFileSync(dockerfilePath, "utf8"); + + expect(dockerfile).toContain(`FROM ${expectedImage}`); + expect(dockerfile).toContain(`model.contextWindow = ${BAKED_STALE_CONTEXT_WINDOW};`); + expect(dockerfile).toContain(`model.maxTokens = ${BAKED_STALE_MAX_TOKENS};`); + expect(dockerfile.trimEnd().endsWith("USER sandbox")).toBe(true); + expect(() => + validateToolDisclosureDockerfileContract(dockerfile, "progressive"), + ).not.toThrow(); + } finally { + fs.rmSync(home, { force: true, recursive: true }); + } + }); +}); From 441af47bef4f49d9205e641eda9b18cae9316542 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:45:55 -0700 Subject: [PATCH 05/34] test(openclaw): exercise actual permission boundaries Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../runtime/nemoclaw-start-config-io.test.ts | 8 ++-- .../runtime/nemoclaw-start-reconcile.test.ts | 43 ++++++++++--------- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts index 4168df5b84c..fb44f19fca5 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts @@ -57,10 +57,12 @@ describe("runtime model override (#759)", () => { fs.chmodSync(openclawDir, 0o2770); fs.chmodSync(configPath, 0o660); fs.chmodSync(hashPath, 0o660); + const configFd = fs.openSync(configPath, "r"); + const hashFd = fs.openSync(hashPath, "r"); const initialModes = { dir: fs.statSync(openclawDir).mode & 0o7777, - config: fs.statSync(configPath).mode & 0o777, - hash: fs.statSync(hashPath).mode & 0o777, + config: fs.fstatSync(configFd).mode & 0o777, + hash: fs.fstatSync(hashFd).mode & 0o777, }; const helperFns = [extractShellFunction("openclaw_config_dir_owner")] @@ -81,8 +83,6 @@ describe("runtime model override (#759)", () => { ].join("\n"); const script = path.join(root, "run.sh"); fs.writeFileSync(script, wrapper, { mode: 0o700 }); - const configFd = fs.openSync(configPath, "r"); - const hashFd = fs.openSync(hashPath, "r"); try { const result = spawnSync("bash", [script], { encoding: "utf-8", diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 1e4abf3ab55..5105c0fd658 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -306,28 +306,31 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, ); - it("explains why a non-root user cannot reconcile a sealed config (#12033)", () => { - const initial = { - agents: { defaults: { model: { primary: "inference/old-model" } } }, - models: { - providers: { - inference: { - models: [{ id: "old-model", name: "inference/old-model" }], + it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( + "explains why an actual non-root user cannot reconcile a sealed config (#12033)", + () => { + const initial = { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "old-model", name: "inference/old-model" }], + }, }, }, - }, - }; - const { result, config, hash } = runReconcile(initial, { - gatewayModel: "new-model", - userId: 1000, - configWritable: false, - }); - - expect(result.status).toBe(0); - expect(config).toEqual(initial); - expect(hash).toBe("oldhash\n"); - expect(result.stderr).toContain("OpenClaw config is not writable by the sandbox user"); - }); + }; + const { result, config, hash } = runReconcile(initial, { + gatewayModel: "new-model", + useActualUser: true, + configWritable: false, + }); + + expect(result.status).toBe(0); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(result.stderr).toContain("OpenClaw config is not writable by the sandbox user"); + }, + ); it("patches primary AND models[0] to the live gateway model when both file fields are stale", () => { const { result, config, hash } = runReconcile( From 58af59a8c49dded56517ebf7ff885a395e242b42 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:49:38 -0700 Subject: [PATCH 06/34] test(e2e): map custom image parity coverage Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/mock-parity.json | 1 + 1 file changed, 1 insertion(+) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 8ae8cfa6ef6..445fd03585d 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -717,6 +717,7 @@ "test/e2e/support/compatible-anthropic-switch.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", + "test/e2e/support/openclaw-custom-image-fixture.test.ts", "test/e2e/support/openclaw-inference-switch-helpers.test.ts" ] }, From 62bdb2e05b4e370b8740bb433d831226eee43a0a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 08:32:46 -0700 Subject: [PATCH 07/34] test(e2e): record effective custom image limits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../live/openclaw-inference-switch.test.ts | 52 +++++++++++++++++-- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 400abb21046..a3dd59d6e48 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -55,6 +55,8 @@ import { import { agentReplyContainsToken, anthropicToolCount, + BAKED_STALE_CONTEXT_WINDOW, + BAKED_STALE_MAX_TOKENS, classifyOpenClawPostSwitchInferenceAttempt, MOCK_BASELINE_API_KEY, MOCK_BASELINE_MODEL, @@ -946,7 +948,7 @@ test( contracts: [ "the selected runtime is available and an authenticated compatible baseline endpoint is staged", "install.sh --non-interactive onboards an OpenClaw sandbox", - "Docker execution also proves non-root custom-image startup reconciles a divergent baked model and removes its stale limits", + "Docker execution also proves non-root custom-image startup reconciles a divergent baked model and resolves new effective limits", "when selected, the mock baseline route completes one explicit authenticated fixture request", "nemoclaw inference set switches the running sandbox route", "OpenClaw gateway is supervisor-restarted after every changed inference configuration", @@ -1084,8 +1086,52 @@ test( const startupModel = startupConfig.models?.providers?.inference?.models?.[0]; expect(startupConfig.agents?.defaults?.model?.primary).toBe(`inference/${baselineModel}`); expect(startupModel?.id).toBe(baselineModel); - expect(startupModel).not.toHaveProperty("contextWindow"); - expect(startupModel).not.toHaveProperty("maxTokens"); + + const effectiveModelResult = await sandbox.exec( + SANDBOX_NAME, + [ + "openclaw", + "infer", + "model", + "inspect", + "--model", + `inference/${baselineModel}`, + "--json", + ], + { + artifactName: "inspect-effective-model-after-custom-image-startup", + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }, + ); + expect(effectiveModelResult.exitCode, resultText(effectiveModelResult)).toBe(0); + const effectiveModel = JSON.parse(effectiveModelResult.stdout) as Record; + const { + contextWindow: effectiveContextWindow, + id, + maxTokens: effectiveMaxTokens, + provider, + } = effectiveModel; + const effectiveModelMatches = + provider === "inference" && + id === baselineModel && + typeof effectiveContextWindow === "number" && + effectiveContextWindow > 0 && + effectiveContextWindow !== BAKED_STALE_CONTEXT_WINDOW && + typeof effectiveMaxTokens === "number" && + effectiveMaxTokens > 0 && + effectiveMaxTokens !== BAKED_STALE_MAX_TOKENS; + expect( + effectiveModelMatches, + `OpenClaw retained stale or invalid custom-image model metadata: ${JSON.stringify(effectiveModel)}`, + ).toBe(true); + await artifacts.writeJson("custom-image-effective-model.json", { + contextWindow: effectiveContextWindow, + maximumOutputTokens: effectiveMaxTokens, + modelId: id, + modelRef: `${String(provider)}/${String(id)}`, + provider, + }); const runtimeUser = await sandbox.exec(SANDBOX_NAME, ["id", "-u"], { artifactName: "read-custom-image-runtime-user", From e8ef2cbe66223ac138d43fc8a0a0d088566e088d Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:06:33 -0700 Subject: [PATCH 08/34] fix: pass routed model to custom OpenClaw images Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/switch-models.mdx | 5 +- scripts/nemoclaw-start.sh | 26 +++++--- src/lib/onboard/docker-startup-command-env.ts | 13 ++++ src/lib/onboard/sandbox-create-launch.test.ts | 59 ++++++++++++++++++- src/lib/onboard/sandbox-create-launch.ts | 13 +++- .../runtime/nemoclaw-start-reconcile.test.ts | 25 +++++++- 6 files changed, 127 insertions(+), 14 deletions(-) diff --git a/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index ab916ceedcb..ab59e67ad8e 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -45,8 +45,9 @@ If the route metadata is incomplete, NemoClaw stops and tells you to re-run onbo -When the selected model ID changes, NemoClaw removes `contextWindow` and `maxTokens` values inherited from the previous model entry. -OpenClaw then uses the new model's catalog values or defaults. +At runtime, NemoClaw replaces `contextWindow` only when it resolves a value for the selected model and can retain an existing `maxTokens` value. +During custom-image startup, if the OpenClaw configuration still names a different model ID than the host-selected route, NemoClaw removes both inherited values while it reconciles that stale configuration. +OpenClaw then uses the selected model's catalog values or defaults. To keep explicit limits for the new model, recreate the sandbox after you set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model. Refer to [Configure Model Limits](configure-model-limits) for the environment variable requirements. diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index f63c7abde2b..19bfb9e461e 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -17,6 +17,7 @@ # NEMOCLAW_MODEL_OVERRIDE Override the primary model at startup without rebuilding # the sandbox image. Must match the model configured on # the gateway via `openshell inference set`. +# NEMOCLAW_ROUTED_MODEL Host-selected route model for custom-image startup. # NEMOCLAW_INFERENCE_API_OVERRIDE Override the inference API type when switching between # provider families (e.g., "anthropic-messages" or # "openai-completions"). Only needed for cross-provider switches. @@ -1106,9 +1107,10 @@ PYOVERRIDE # reconciliation the file's stale entry can be pushed back, reverting # the route. # -# Probe the live gateway via `openshell inference get` and treat its -# inference section as the source of truth: when the gateway model differs -# from the file, align both primary and the inference provider's +# A custom-image launch passes the host-selected route model through +# NEMOCLAW_ROUTED_MODEL. Otherwise, probe the live gateway via +# `openshell inference get`. When either route model differs from the file, +# align both primary and the inference provider's # first model entry so the agent identity and the gateway route stay # consistent across the next reconcile cycle. # @@ -1140,8 +1142,16 @@ reconcile_agent_model_with_provider() { return 0 fi - local gateway_model="" - if command -v openshell >/dev/null 2>&1; then + local gateway_model="${NEMOCLAW_ROUTED_MODEL:-}" + local model_source="route" + if [ -n "$gateway_model" ]; then + if [ "${#gateway_model}" -gt 512 ] \ + || ! printf '%s' "$gateway_model" | grep -qE '^[A-Za-z0-9._:/-]+$'; then + printf '[SECURITY] Routed model rejected an unsafe model identifier\n' >&2 + return 1 + fi + elif command -v openshell >/dev/null 2>&1; then + model_source="gateway" gateway_model="$( /usr/bin/python3 -I - <<'PYPROBE' import re @@ -1214,7 +1224,7 @@ PYPROBE local provider_model_ref provider_model_ref="$( - run_openclaw_config_as_owner /usr/bin/env GATEWAY_MODEL="${gateway_model:-}" \ + run_openclaw_config_as_owner /usr/bin/env GATEWAY_MODEL="${gateway_model:-}" MODEL_SOURCE="$model_source" \ /usr/bin/python3 -I - "$config_file" <<'PYRECONCILE_READ' import json, os, sys @@ -1250,7 +1260,7 @@ if gateway_target is not None: first_id_ok = isinstance(first_id, str) and (first_id == bare or first_id == gateway_target) if primary_ok and first_name_ok and first_id_ok: sys.exit(0) - print(f"gateway\t{gateway_target}") + print(f"{os.environ.get('MODEL_SOURCE', 'gateway')}\t{gateway_target}") sys.exit(0) # Legacy fallback: gateway probe is unavailable. Align primary with @@ -1288,7 +1298,7 @@ config_file, provider_model = sys.argv[1], sys.argv[2] with open(config_file) as f: cfg = json.load(f) cfg.setdefault("agents", {}).setdefault("defaults", {}).setdefault("model", {})["primary"] = provider_model -if os.environ.get("RECONCILE_SOURCE") == "gateway": +if os.environ.get("RECONCILE_SOURCE") != "legacy": bare = ( provider_model[len("inference/"):] if provider_model.startswith("inference/") diff --git a/src/lib/onboard/docker-startup-command-env.ts b/src/lib/onboard/docker-startup-command-env.ts index 1637117e645..0c7a9502ce3 100644 --- a/src/lib/onboard/docker-startup-command-env.ts +++ b/src/lib/onboard/docker-startup-command-env.ts @@ -25,6 +25,9 @@ const OPENCLAW_AUTO_PAIR_RUNTIME_ENV_KEYS = [ ] as const; const OPENCLAW_DIAGNOSTIC_RUNTIME_ENV_KEYS = ["NEMOCLAW_MCP_SHADOW_DIAGNOSTICS"] as const; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_ENV = "NEMOCLAW_MCP_TOOLS_LIST_TIMEOUT_MS"; +const OPENCLAW_ROUTED_MODEL_ENV = "NEMOCLAW_ROUTED_MODEL"; +const OPENCLAW_ROUTED_MODEL_MAX_LENGTH = 512; +const OPENCLAW_ROUTED_MODEL_PATTERN = /^[A-Za-z0-9._:/-]+$/; const OPENCLAW_GATEWAY_URL_ENV = "OPENCLAW_GATEWAY_URL"; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_MIN_MS = 1500; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_MAX_MS = 10_000; @@ -99,6 +102,7 @@ export interface SandboxRuntimeEnvArgsInput { extraPlaceholderKeys: readonly string[]; allowHermesApiPortOverride?: boolean; observabilityEnabled?: boolean; + openClawRoutedModel?: string; sandboxName?: string; env: NodeJS.ProcessEnv; omitCredentialEnv?: boolean; @@ -125,6 +129,15 @@ export function buildSandboxRuntimeEnvArgs(input: SandboxRuntimeEnvArgsInput): { appendOpenClawAutoPairRuntimeEnvArgs(envArgs, agent, env); appendOpenClawDiagnosticRuntimeEnvArgs(envArgs, agent, env); appendOpenClawMcpToolsListTimeoutRuntimeEnvArg(envArgs, agent, env); + if ((!agent || agent.name === "openclaw") && input.openClawRoutedModel) { + if ( + input.openClawRoutedModel.length > OPENCLAW_ROUTED_MODEL_MAX_LENGTH || + !OPENCLAW_ROUTED_MODEL_PATTERN.test(input.openClawRoutedModel) + ) { + throw new Error("The selected OpenClaw route model has an invalid identifier."); + } + envArgs.push(formatEnvAssignment(OPENCLAW_ROUTED_MODEL_ENV, input.openClawRoutedModel)); + } appendHermesDashboardEnvArgs(envArgs, input.hermesDashboardState, formatEnvAssignment); if (agent?.name === "hermes" && input.sandboxName) { const apiPort = diff --git a/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index cbeb580b180..5ae865c3b33 100644 --- a/src/lib/onboard/sandbox-create-launch.test.ts +++ b/src/lib/onboard/sandbox-create-launch.test.ts @@ -677,6 +677,62 @@ describe("prepareSandboxCreateLaunch", () => { }); describe("prepareSandboxCreateLaunchWithPrebuild", () => { + it("passes the selected route model to a custom non-root OpenClaw image", async () => { + const buildCtx = createTrustedBuildContext(); + const dockerfile = path.join(buildCtx, "Dockerfile"); + const result = await prepareSandboxCreateLaunchWithPrebuild({ + agent: { name: "openclaw" } as any, + chatUiUrl: "", + createArgs: ["--from", dockerfile, "--name", "demo"], + env: { NEMOCLAW_MODEL: "provider/selected-model" }, + extraPlaceholderKeys: [], + getDashboardForwardPort: () => "0", + hermesDashboardState: disabledHermesDashboardState, + manageDashboard: false, + openshellShellCommand: (args) => args.join(" "), + sandboxName: "demo", + buildEnv: () => ({}), + prebuild: { + buildCtx, + buildId: "build-123", + dockerDriverGateway: true, + env: { NEMOCLAW_SANDBOX_PREBUILD: "1" }, + origin: "custom", + }, + }); + + expect(result.envArgs).toContain("NEMOCLAW_ROUTED_MODEL=provider/selected-model"); + expect(result.createCommand).toContain("NEMOCLAW_ROUTED_MODEL=provider/selected-model"); + }); + + it("rejects an unsafe selected route model before sandbox creation", async () => { + const buildCtx = createTrustedBuildContext(); + const dockerfile = path.join(buildCtx, "Dockerfile"); + + await expect( + prepareSandboxCreateLaunchWithPrebuild({ + agent: { name: "openclaw" } as any, + chatUiUrl: "", + createArgs: ["--from", dockerfile, "--name", "demo"], + env: { NEMOCLAW_MODEL: "model;unsafe" }, + extraPlaceholderKeys: [], + getDashboardForwardPort: () => "0", + hermesDashboardState: disabledHermesDashboardState, + manageDashboard: false, + openshellShellCommand: (args) => args.join(" "), + sandboxName: "demo", + buildEnv: () => ({}), + prebuild: { + buildCtx, + buildId: "build-123", + dockerDriverGateway: true, + env: { NEMOCLAW_SANDBOX_PREBUILD: "1" }, + origin: "custom", + }, + }), + ).rejects.toThrow("selected OpenClaw route model has an invalid identifier"); + }); + it("hands the build-qualified image to the canonical launch renderer", async () => { const buildCtx = createTrustedBuildContext(); const dockerfile = path.join(buildCtx, "Dockerfile"); @@ -685,7 +741,7 @@ describe("prepareSandboxCreateLaunchWithPrebuild", () => { agent: null, chatUiUrl: "", createArgs: ["--from", dockerfile, "--name", "demo"], - env: {}, + env: { NEMOCLAW_MODEL: "provider/generated-model" }, extraPlaceholderKeys: [], getDashboardForwardPort: () => "0", hermesDashboardState: disabledHermesDashboardState, @@ -714,6 +770,7 @@ describe("prepareSandboxCreateLaunchWithPrebuild", () => { expect(result.createCommand).toContain( "sandbox create --from nemoclaw-sandbox-local:demo-build-123 --name demo", ); + expect(result.envArgs.some((arg) => arg.startsWith("NEMOCLAW_ROUTED_MODEL="))).toBe(false); expect(buildImage).toHaveBeenCalledOnce(); }); diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index 7856fb6e33a..879df44f4c8 100644 --- a/src/lib/onboard/sandbox-create-launch.ts +++ b/src/lib/onboard/sandbox-create-launch.ts @@ -33,6 +33,8 @@ export const OPENSHELL_SANDBOX_SUPERVISOR_ARGV = Object.freeze([ export interface SandboxCreateLaunchInput { agent: AgentDefinition | null | undefined; observabilityEnabled?: boolean; + /** Selected route model injected only for a custom OpenClaw image. */ + openClawRoutedModel?: string; chatUiUrl: string; createArgs: readonly string[]; sandboxName?: string; @@ -122,6 +124,7 @@ export function prepareSandboxRuntimeLaunch( hermesApiPort: input.hermesApiPort, extraPlaceholderKeys: input.extraPlaceholderKeys, observabilityEnabled: input.observabilityEnabled, + openClawRoutedModel: input.openClawRoutedModel, sandboxName: input.sandboxName, allowHermesApiPortOverride: true, env, @@ -215,7 +218,15 @@ export async function prepareSandboxCreateLaunchWithPrebuild( sandboxName: input.sandboxName, }); return { - ...prepareSandboxCreateLaunch({ ...launchInput, createArgs: prebuild.createArgs }), + ...prepareSandboxCreateLaunch({ + ...launchInput, + createArgs: prebuild.createArgs, + openClawRoutedModel: + prebuildInput.origin === "custom" && + (!launchInput.agent || launchInput.agent.name === "openclaw") + ? (launchInput.env ?? process.env).NEMOCLAW_MODEL?.trim() + : undefined, + }), prebuild, }; } diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 5105c0fd658..dadeed08af6 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -283,8 +283,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, }, { - gatewayRawOutput: - "\\x1b[32mGateway Inference:\\x1b[0m\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + env: { NEMOCLAW_ROUTED_MODEL: "nvidia/nemotron-3-super-120b-a12b" }, useActualUser: true, }, ); @@ -306,6 +305,28 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, ); + it("rejects an unsafe host-routed model without changing the config", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/safe-file-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "safe-file-model", name: "inference/safe-file-model" }], + }, + }, + }, + }; + const { result, config, hash } = runReconcile(initial, { + env: { NEMOCLAW_ROUTED_MODEL: "model;unsafe" }, + }); + + expect(result.status).toBe(1); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(result.stderr).toContain("Routed model rejected an unsafe model identifier"); + expect(result.stderr).not.toContain("model;unsafe"); + }); + it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( "explains why an actual non-root user cannot reconcile a sealed config (#12033)", () => { From 29a5c02cab5aefe2bae5d44b59d23a8c1790e78f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 10:53:37 -0700 Subject: [PATCH 09/34] fix(onboard): pass selected model through custom workload launch Signed-off-by: Aaron Erickson --- docs/inference/switch-models.mdx | 4 ++- .../onboard-orchestration.test.ts | 20 +++++++++++++ .../managed-workload/onboard-orchestration.ts | 5 ++++ .../live/openclaw-inference-switch-helpers.ts | 8 ------ .../live/openclaw-inference-switch.test.ts | 28 +++++++++++-------- 5 files changed, 45 insertions(+), 20 deletions(-) diff --git a/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index ab59e67ad8e..cfe34d891c6 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -46,7 +46,9 @@ If the route metadata is incomplete, NemoClaw stops and tells you to re-run onbo At runtime, NemoClaw replaces `contextWindow` only when it resolves a value for the selected model and can retain an existing `maxTokens` value. -During custom-image startup, if the OpenClaw configuration still names a different model ID than the host-selected route, NemoClaw removes both inherited values while it reconciles that stale configuration. +During custom-image startup, NemoClaw reconciles a stale model ID with the host-selected route only when the sandbox user can write `/sandbox/.openclaw/openclaw.json`. +That reconciliation removes both inherited limits when the model ID changes. +If the configuration is not writable, NemoClaw reports that reconciliation was skipped and preserves the existing configuration. OpenClaw then uses the selected model's catalog values or defaults. To keep explicit limits for the new model, recreate the sandbox after you set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model. Refer to [Configure Model Limits](configure-model-limits) for the environment variable requirements. diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index 022d4bf06b6..9881c03affb 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -746,6 +746,20 @@ describe("managed workload onboard orchestration", () => { }; it.each([ + { + behavior: "passes the selected routed model through the production custom OpenClaw launch", + agentName: "openclaw", + fromDockerfile: "/custom/Dockerfile", + preparedBuildContext: { + ...preparedHermesContext, + origin: "custom" as const, + rebuildTarget: { agentName: "openclaw", fromDockerfile: "/custom/Dockerfile" }, + }, + expectedFromDockerfile: "/custom/Dockerfile", + expectedStageCalls: 0, + expectedRawCreate: false, + expectedRoutedModel: "nvidia/selected-model", + }, { behavior: "stages a fresh LangChain Deep Agents Code build before resolving patch metadata", agentName: "langchain-deepagents-code", @@ -787,6 +801,7 @@ describe("managed workload onboard orchestration", () => { fromDockerfile, preparedBuildContext, preResolvedBaseImageMetadata: resolutionMetadata, + model: "nvidia/selected-model", } as never; }); const resolveSandboxBuildPatch = vi.fn(async (input: Record) => { @@ -881,6 +896,11 @@ describe("managed workload onboard orchestration", () => { }, } as unknown as Parameters[0]); + expect( + preparedLaunch.launch.envArgs.filter((value) => value.startsWith("NEMOCLAW_ROUTED_MODEL=")), + ).toEqual( + testCase.expectedRoutedModel ? [`NEMOCLAW_ROUTED_MODEL=${testCase.expectedRoutedModel}`] : [], + ); expect(resolvePatchInput).toHaveBeenCalledOnce(); expect(resolveSandboxBuildPatch).toHaveBeenCalledOnce(); expect(materializeSandboxCreatePlan).toHaveBeenCalledWith( diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index ad361dfec8a..45ddebc9310 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -592,6 +592,11 @@ export async function prepareOnboardSandboxWorkloadLaunch( const runtimeLaunch = prepareSandboxRuntimeLaunch({ ...launchInput, policyAttached: Boolean(createPlan.createRequest.policyPath), + openClawRoutedModel: + buildContext.origin === "custom" && + (!launchInput.agent || launchInput.agent.name === "openclaw") + ? patchInput.model || undefined + : undefined, }); const { createArgs: _portableArgs, ...prebuild } = await prebuildSandboxImageIfEligible({ buildCtx: buildContext.buildCtx, diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 35ba477a8a9..136692af18d 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -50,14 +50,6 @@ export function stageNonRootCustomOpenClawImageDockerfile( return dockerfile; } -export async function whenCustomImage( - dockerfile: string | undefined, - verify: () => Promise, -): Promise { - if (!dockerfile) return; - await verify(); -} - export interface OpenClawPostSwitchInferenceAttempt { exitCode: number | null; httpStatus: string; diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index a3dd59d6e48..4d5fe70b6d2 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -63,7 +63,6 @@ import { mockBaselineInference, parseOpenClawGatewayModelRun, stageNonRootCustomOpenClawImageDockerfile, - whenCustomImage, } from "./openclaw-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_MODEL, @@ -470,8 +469,11 @@ async function prepareCompatibleAnthropicSwitchBinding( home: string, mockProvider: MockAnthropicProvider | undefined, ): Promise { - if (SWITCH_PROVIDER !== "compatible-anthropic-endpoint") return null; - if (SWITCH_INFERENCE_API !== "anthropic-messages") return null; + if ( + SWITCH_PROVIDER !== "compatible-anthropic-endpoint" || + SWITCH_INFERENCE_API !== "anthropic-messages" + ) + return null; const endpointUrl = process.env.NEMOCLAW_SWITCH_ENDPOINT_URL ?? mockProvider?.endpointUrl ?? ""; const binding = compatibleAnthropicSwitchBinding(endpointUrl); @@ -998,13 +1000,15 @@ test( ); const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-switch-home-")); - const selectedImageCatalog = liveE2eManagedImageCatalog(process.env); - const customImageContract = selectedImageCatalog - ? readLiveE2eManagedImageCatalogContracts(selectedImageCatalog).get("openclaw") - : undefined; + const gatewayRuntime = process.env.NEMOCLAW_GATEWAY_RUNTIME ?? "docker"; const customImageDockerfile = - (process.env.NEMOCLAW_GATEWAY_RUNTIME ?? "docker") === "docker" && customImageContract - ? stageNonRootCustomOpenClawImageDockerfile(home, customImageContract?.reference ?? "") + gatewayRuntime === "docker" + ? stageNonRootCustomOpenClawImageDockerfile( + home, + readLiveE2eManagedImageCatalogContracts(liveE2eManagedImageCatalog(process.env)!).get( + "openclaw", + )!.reference, + ) : undefined; let mockProvider: MockAnthropicProvider | undefined; cleanup.trackDisposable( @@ -1072,7 +1076,7 @@ test( skip("NVIDIA endpoint validation was unavailable/rate-limited during onboarding"); } expect(install.exitCode, installText).toBe(0); - await whenCustomImage(customImageDockerfile, async () => { + if (customImageDockerfile) { const startupConfigResult = await sandbox.exec( SANDBOX_NAME, ["cat", "/sandbox/.openclaw/openclaw.json"], @@ -1150,7 +1154,7 @@ test( }, ); expect(startupHash.exitCode, resultText(startupHash)).toBe(0); - }); + } await proveMockBaselineAuthentication(baselineProvider, sandbox, home, artifacts); progress.phase("prepare the switched provider and endpoint"); @@ -1248,6 +1252,8 @@ test( await artifacts.target.complete({ id: "openclaw-inference-switch", status: "passed", + gatewayRuntime, + customImageReconciliation: customImageDockerfile ? "passed" : "not-applicable", assertions: { runtimeProviderAvailable: true, installCompleted: install.exitCode === 0, From a6148938bb75b67fd9be49aca8ee4061ef63de60 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 11:42:48 -0700 Subject: [PATCH 10/34] test(e2e): require Docker custom image proof Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../live/openclaw-inference-switch.test.ts | 28 ++++++------------- ...inference-switch-workflow-boundary.test.ts | 1 + test/e2e/support/workflow-plan.test.ts | 3 +- tools/e2e/target-catalogue.mts | 2 +- 4 files changed, 13 insertions(+), 21 deletions(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 4d5fe70b6d2..7a702bc2bc7 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -1000,16 +1000,12 @@ test( ); const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-switch-home-")); - const gatewayRuntime = process.env.NEMOCLAW_GATEWAY_RUNTIME ?? "docker"; - const customImageDockerfile = - gatewayRuntime === "docker" - ? stageNonRootCustomOpenClawImageDockerfile( - home, - readLiveE2eManagedImageCatalogContracts(liveE2eManagedImageCatalog(process.env)!).get( - "openclaw", - )!.reference, - ) - : undefined; + const customImageDockerfile = stageNonRootCustomOpenClawImageDockerfile( + home, + readLiveE2eManagedImageCatalogContracts(liveE2eManagedImageCatalog(process.env)!).get( + "openclaw", + )!.reference, + ); let mockProvider: MockAnthropicProvider | undefined; cleanup.trackDisposable( `remove OpenClaw inference switch test home for ${SANDBOX_NAME}`, @@ -1053,12 +1049,8 @@ test( cwd: REPO_ROOT, env: commandEnv(home, { ...baseline.env, - ...(customImageDockerfile - ? { - NEMOCLAW_FROM_DOCKERFILE: customImageDockerfile, - NEMOCLAW_SANDBOX_PREBUILD: "1", - } - : {}), + NEMOCLAW_FROM_DOCKERFILE: customImageDockerfile, + NEMOCLAW_SANDBOX_PREBUILD: "1", NEMOCLAW_RECREATE_SANDBOX: "1", }), redactionValues, @@ -1076,7 +1068,7 @@ test( skip("NVIDIA endpoint validation was unavailable/rate-limited during onboarding"); } expect(install.exitCode, installText).toBe(0); - if (customImageDockerfile) { + { const startupConfigResult = await sandbox.exec( SANDBOX_NAME, ["cat", "/sandbox/.openclaw/openclaw.json"], @@ -1252,8 +1244,6 @@ test( await artifacts.target.complete({ id: "openclaw-inference-switch", status: "passed", - gatewayRuntime, - customImageReconciliation: customImageDockerfile ? "passed" : "not-applicable", assertions: { runtimeProviderAvailable: true, installCompleted: install.exitCode === 0, diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index 9981402d2be..da82a7566cb 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -18,6 +18,7 @@ describe("inference-switch catalogue boundary", () => { expect(openclaw).toMatchObject({ profile: "standard", testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + gatewayRuntimes: ["docker"], environment: { NEMOCLAW_AGENT: "openclaw", NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 3b6b66654c8..79e39f593f6 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -141,11 +141,12 @@ describe("E2E workflow plan", () => { "ubuntu-repo-cloud-openclaw", ]); expect(plan.testMatrix).toEqual([]); - expect(catalogueIds).toHaveLength(45); + expect(catalogueIds).toHaveLength(44); expect(catalogueIds).not.toEqual( expect.arrayContaining([ "bootstrap-install-smoke", "gpu-e2e", + "openclaw-inference-switch", "rebuild-hermes", "rebuild-openclaw", ]), diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 46446f61ac2..7115809cfd3 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1103,7 +1103,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ OPENSHELL_GATEWAY: "nemoclaw", }, }), - managedRuntimeTarget("openclaw-inference-switch", { + dockerOnlyTarget("openclaw-inference-switch", { displayName: "Inference: OpenClaw switches providers and remains responsive", agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; compatible inference fixtures", From e114358b96a07147a4ccae67ee47395401f48602 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:26:03 -0700 Subject: [PATCH 11/34] fix(openclaw): consume custom image route once Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/switch-models.mdx | 5 +- scripts/nemoclaw-start.sh | 135 +++++++++++++++++- .../runtime/nemoclaw-start-reconcile.test.ts | 71 ++++++++- .../live/openclaw-inference-switch.test.ts | 27 ++-- 4 files changed, 221 insertions(+), 17 deletions(-) diff --git a/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index cfe34d891c6..2ebf7113603 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -49,8 +49,9 @@ At runtime, NemoClaw replaces `contextWindow` only when it resolves a value for During custom-image startup, NemoClaw reconciles a stale model ID with the host-selected route only when the sandbox user can write `/sandbox/.openclaw/openclaw.json`. That reconciliation removes both inherited limits when the model ID changes. If the configuration is not writable, NemoClaw reports that reconciliation was skipped and preserves the existing configuration. -OpenClaw then uses the selected model's catalog values or defaults. -To keep explicit limits for the new model, recreate the sandbox after you set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model. +That preserved configuration can still contain the image's inherited model ID and limits. +Make the configuration writable by the sandbox user in the custom image, then recreate the sandbox. +To keep explicit limits for the new model, set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model before you recreate the sandbox. Refer to [Configure Model Limits](configure-model-limits) for the environment variable requirements. diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 19bfb9e461e..09149957b5d 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1122,6 +1122,116 @@ PYOVERRIDE # values still win. No-op when already in sync. # Ref: https://github.com/NVIDIA/NemoClaw/issues/3175 +# OpenShell persists sandbox-create environment values across stop/start. Record +# successful consumption of NEMOCLAW_ROUTED_MODEL so that create-time metadata +# cannot overwrite a later `inference set`. The receipt is read and written as +# the config owner; root never opens an agent-controlled path. +routed_model_receipt() { + local operation="$1" + local config_dir="/sandbox/.openclaw" + + run_openclaw_config_as_owner /usr/bin/python3 -I - "$config_dir" "$operation" <<'PYROUTEDMODELRECEIPT' +import os +import secrets +import stat +import sys + +config_dir, operation = sys.argv[1:] +marker_name = ".nemoclaw-routed-model-applied" +expected = b"nemoclaw-routed-model-applied-v1\n" +directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) +file_flags = os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) + +directory_fd = os.open(config_dir, directory_flags) +try: + directory = os.fstat(directory_fd) + if directory.st_uid != os.geteuid() or directory.st_gid != os.getegid(): + raise OSError("config directory owner does not match the runtime user") + config_fd = os.open("openclaw.json", file_flags, dir_fd=directory_fd) + try: + config = os.fstat(config_fd) + current_config = os.stat("openclaw.json", dir_fd=directory_fd, follow_symlinks=False) + if ( + not stat.S_ISREG(config.st_mode) + or (config.st_dev, config.st_ino) != (current_config.st_dev, current_config.st_ino) + or config.st_uid != os.geteuid() + or config.st_gid != os.getegid() + or config.st_nlink != 1 + ): + raise OSError("OpenClaw config is not a trusted regular file") + receipt_mode = stat.S_IMODE(config.st_mode) + finally: + os.close(config_fd) + + if operation == "check": + try: + marker_fd = os.open(marker_name, file_flags, dir_fd=directory_fd) + except FileNotFoundError: + raise SystemExit(1) + try: + opened = os.fstat(marker_fd) + current = os.stat(marker_name, dir_fd=directory_fd, follow_symlinks=False) + content = bytearray() + while len(content) <= len(expected): + chunk = os.read(marker_fd, len(expected) + 1 - len(content)) + if not chunk: + break + content.extend(chunk) + if ( + not stat.S_ISREG(opened.st_mode) + or (opened.st_dev, opened.st_ino) != (current.st_dev, current.st_ino) + or opened.st_uid != os.geteuid() + or opened.st_gid != os.getegid() + or stat.S_IMODE(opened.st_mode) != receipt_mode + or opened.st_nlink != 1 + or bytes(content) != expected + ): + raise OSError("routed-model receipt is not a trusted regular file") + finally: + os.close(marker_fd) + elif operation == "write": + temp_name = f".{marker_name}.{secrets.token_hex(12)}.tmp" + temp_fd = os.open( + temp_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0), + 0o600, + dir_fd=directory_fd, + ) + try: + os.fchmod(temp_fd, receipt_mode) + offset = 0 + while offset < len(expected): + offset += os.write(temp_fd, expected[offset:]) + os.fsync(temp_fd) + os.link( + temp_name, + marker_name, + src_dir_fd=directory_fd, + dst_dir_fd=directory_fd, + follow_symlinks=False, + ) + os.unlink(temp_name, dir_fd=directory_fd) + os.fsync(directory_fd) + except Exception: + try: + os.unlink(temp_name, dir_fd=directory_fd) + except OSError: + pass + raise + finally: + os.close(temp_fd) + else: + raise OSError("unsupported routed-model receipt operation") +except SystemExit: + raise +except Exception as error: + print(f"[SECURITY] Routed-model receipt {operation} failed: {error}", file=sys.stderr) + raise SystemExit(2) +finally: + os.close(directory_fd) +PYROUTEDMODELRECEIPT +} + reconcile_agent_model_with_provider() { # apply_model_override already won; reconciling against the gateway would # overwrite the user's explicit choice with an inference/-prefixed variant. @@ -1142,16 +1252,27 @@ reconcile_agent_model_with_provider() { return 0 fi - local gateway_model="${NEMOCLAW_ROUTED_MODEL:-}" - local model_source="route" - if [ -n "$gateway_model" ]; then + local gateway_model="" + local model_source="gateway" + local routed_model_pending=0 + local routed_model_receipt_status=0 + if [ -n "${NEMOCLAW_ROUTED_MODEL:-}" ]; then + routed_model_receipt check || routed_model_receipt_status=$? + if [ "$routed_model_receipt_status" -eq 1 ]; then + gateway_model="$NEMOCLAW_ROUTED_MODEL" + model_source="route" + routed_model_pending=1 + elif [ "$routed_model_receipt_status" -ne 0 ]; then + return "$routed_model_receipt_status" + fi + fi + if [ "$routed_model_pending" -eq 1 ]; then if [ "${#gateway_model}" -gt 512 ] \ || ! printf '%s' "$gateway_model" | grep -qE '^[A-Za-z0-9._:/-]+$'; then printf '[SECURITY] Routed model rejected an unsafe model identifier\n' >&2 return 1 fi elif command -v openshell >/dev/null 2>&1; then - model_source="gateway" gateway_model="$( /usr/bin/python3 -I - <<'PYPROBE' import re @@ -1279,6 +1400,9 @@ PYRECONCILE_READ )" if [ -z "$provider_model_ref" ]; then + if [ "$routed_model_pending" -eq 1 ]; then + routed_model_receipt write || return $? + fi return 0 fi @@ -1334,6 +1458,9 @@ PYRECONCILE_WRITE fi normalize_mutable_config_perms || _write_rc=$? + if [ "$_write_rc" -eq 0 ] && [ "$routed_model_pending" -eq 1 ]; then + routed_model_receipt write || _write_rc=$? + fi [ "$_write_rc" -eq 0 ] || return "$_write_rc" } diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index dadeed08af6..fd313de5d84 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -37,6 +37,7 @@ interface RunReconcileOptions { configWritable?: boolean; hashFailure?: boolean; env?: Record; + routedModelReceipt?: "valid" | "symlink"; } describe("agent identity reconciliation with provider (#3175)", () => { @@ -61,6 +62,16 @@ describe("agent identity reconciliation with provider (#3175)", () => { fs.chmodSync(openclawDir, 0o2770); fs.chmodSync(configPath, options.configWritable === false ? 0o440 : 0o660); fs.chmodSync(hashPath, 0o660); + const routedModelReceiptPath = path.join(openclawDir, ".nemoclaw-routed-model-applied"); + const prepareRoutedModelReceipt = { + valid: () => { + fs.writeFileSync(routedModelReceiptPath, "nemoclaw-routed-model-applied-v1\n"); + fs.chmodSync(routedModelReceiptPath, options.configWritable === false ? 0o440 : 0o660); + }, + symlink: () => fs.symlinkSync(configPath, routedModelReceiptPath), + none: () => undefined, + }[options.routedModelReceipt ?? "none"]; + prepareRoutedModelReceipt(); const prepareSymlink = { config: () => { @@ -111,6 +122,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { ? "ensure_mutable_openclaw_config_hash() { return 19; }" : `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, ].join("\n"); + const receiptFn = extractShellFunction("routed_model_receipt").replaceAll("/sandbox", root); const fn = extractShellFunction("reconcile_agent_model_with_provider").replaceAll( "/sandbox", root, @@ -120,6 +132,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { "set -euo pipefail", ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), helperFns, + receiptFn, fn, "reconcile_agent_model_with_provider", ].join("\n"); @@ -148,8 +161,11 @@ describe("agent identity reconciliation with provider (#3175)", () => { }); const config = JSON.parse(fs.readFileSync(configPath, "utf-8")); const hash = fs.readFileSync(hashPath, "utf-8"); + const routedModelReceipt = fs.existsSync(routedModelReceiptPath) + ? fs.readFileSync(routedModelReceiptPath, "utf-8") + : null; fs.rmSync(root, { recursive: true, force: true }); - return { result, config, hash }; + return { result, config, hash, routedModelReceipt }; } it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { @@ -263,7 +279,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( "reconciles an actually owned config as the current non-root user (#12033)", () => { - const { result, config, hash } = runReconcile( + const { result, config, hash, routedModelReceipt } = runReconcile( { agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, models: { @@ -302,9 +318,60 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(config.models.providers.inference.models[0]).not.toHaveProperty("maxTokens"); expect(hash).not.toBe("oldhash\n"); expect(hash).toContain("openclaw.json"); + expect(routedModelReceipt).toBe("nemoclaw-routed-model-applied-v1\n"); }, ); + it("does not replay the create-time routed model after a later model switch", () => { + const switched = { + agents: { defaults: { model: { primary: "inference/nvidia/switched-model" } } }, + models: { + providers: { + inference: { + models: [ + { + id: "nvidia/switched-model", + name: "inference/nvidia/switched-model", + contextWindow: 262_144, + maxTokens: 16_384, + }, + ], + }, + }, + }, + }; + const { result, config, hash } = runReconcile(switched, { + env: { NEMOCLAW_ROUTED_MODEL: "nvidia/create-time-model" }, + routedModelReceipt: "valid", + }); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(config).toEqual(switched); + expect(hash).toBe("oldhash\n"); + }); + + it("fails closed when the routed-model receipt is a symlink", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/nvidia/baked-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "nvidia/baked-model", name: "inference/nvidia/baked-model" }], + }, + }, + }, + }; + const { result, config, hash } = runReconcile(initial, { + env: { NEMOCLAW_ROUTED_MODEL: "nvidia/create-time-model" }, + routedModelReceipt: "symlink", + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("Routed-model receipt check failed"); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + }); + it("rejects an unsafe host-routed model without changing the config", () => { const initial = { agents: { defaults: { model: { primary: "inference/safe-file-model" } } }, diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 7a702bc2bc7..ed9336f83e9 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -933,6 +933,7 @@ test( "install and onboard baseline OpenClaw", "prepare the switched provider and endpoint", "switch the route and verify restart semantics", + "stop and start the sandbox without replaying the create-time route", "inspect route configuration and recorded state", "prove inference.local and OpenClaw gateway inference", "apply sandbox retention and record the result", @@ -954,6 +955,7 @@ test( "when selected, the mock baseline route completes one explicit authenticated fixture request", "nemoclaw inference set switches the running sandbox route", "OpenClaw gateway is supervisor-restarted after every changed inference configuration", + "a later sandbox stop/start preserves the switched model instead of replaying the create-time route", "OpenShell route points at the switched provider/model", "OpenClaw config and .config-hash reflect the switched inference API/model", "registry and onboard session record the switched provider/model", @@ -962,11 +964,6 @@ test( ], }); - expect( - fs.existsSync(CLI_ENTRYPOINT), - "run `npm run build:cli` before live repo CLI targets", - ).toBe(true); - await runtimeProvider.requireAvailable({ artifactName: "prereq-runtime-info-openclaw-inference-switch", scenarioLabel: "OpenClaw inference switch", @@ -1171,10 +1168,6 @@ test( switchBinding && redactionValues.push(switchBinding.credentialValue); progress.phase("switch the route and verify restart semantics"); - const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1"; - expect(SWITCH_INFERENCE_API).toBe( - apiFamilyChanges ? "anthropic-messages" : "openai-completions", - ); const pidBefore = await openclawGatewayPid(sandbox, home); const switchResult = await runOpenClawInferenceSetWithRetry( host, @@ -1200,6 +1193,21 @@ test( ).toBe(false); } + progress.phase("stop and start the sandbox without replaying the create-time route"); + const gatewayName = process.env.OPENSHELL_GATEWAY ?? "nemoclaw"; + const stop = await sandbox.openshell(["sandbox", "stop", "-g", gatewayName, SANDBOX_NAME], { + artifactName: "openshell-stop-after-openclaw-inference-switch", + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }); + expect(stop.exitCode, resultText(stop)).toBe(0); + const start = await sandbox.openshell(["sandbox", "start", "-g", gatewayName, SANDBOX_NAME], { + artifactName: "openshell-start-after-openclaw-inference-switch", + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }); + expect(start.exitCode, resultText(start)).toBe(0); + progress.phase("inspect route configuration and recorded state"); await assertOpenShellRoute(host, home); await assertOpenClawConfig(sandbox, home); @@ -1249,6 +1257,7 @@ test( installCompleted: install.exitCode === 0, inferenceSetCompleted: switchResult.exitCode === 0, gatewayRestartExpected: true, + switchedModelSurvivedSandboxRestart: true, gatewayPidStable, routeChecked: true, configChecked: true, From 4aebf61aeedb6f1558137e3be28bd625b375debf Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:12:12 -0700 Subject: [PATCH 12/34] fix(e2e): select custom-image proof for source changes Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/workflow-plan.test.ts | 11 +++++++++++ tools/e2e/target-catalogue.mts | 8 +++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 47d8b0a55b0..105ad59bdf9 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -738,6 +738,17 @@ describe("E2E workflow plan", () => { }, ); + it.each([ + "scripts/nemoclaw-start.sh", + "src/lib/onboard/docker-startup-command-env.ts", + "src/lib/onboard/managed-workload/onboard-orchestration.ts", + "src/lib/onboard/sandbox-create-launch.ts", + ])("selects the Docker custom-image proof when %s changes", (changedFile) => { + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + "openclaw-inference-switch", + ); + }); + it.each([ "src/lib/adapters/openshell/command-execution.ts", "src/lib/adapters/openshell/forward-cli.ts", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index dc6f11fc5f6..9389155effd 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1147,7 +1147,13 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ installMode: "none", restoreCli: true, exposeCliBin: true, - owningPaths: ["test/e2e/live/openclaw-inference-switch-helpers.ts"], + owningPaths: [ + "scripts/nemoclaw-start.sh", + "src/lib/onboard/docker-startup-command-env.ts", + "src/lib/onboard/managed-workload/onboard-orchestration.ts", + "src/lib/onboard/sandbox-create-launch.ts", + "test/e2e/live/openclaw-inference-switch-helpers.ts", + ], environment: { ...nonInteractive, NEMOCLAW_AGENT: "openclaw", From d9c3580724e981819ee62c2a5388b1ae75328d44 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:33:56 -0700 Subject: [PATCH 13/34] fix(openclaw): reconcile custom image model at build time Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/switch-models.mdx | 10 +- scripts/nemoclaw-start.sh | 143 +----------------- src/lib/onboard/docker-startup-command-env.ts | 13 -- ...le-custom-openclaw-model-reconcile.test.ts | 106 +++++++++++++ src/lib/onboard/dockerfile-patch.ts | 93 ++++++++++++ .../onboard-orchestration.test.ts | 19 --- .../managed-workload/onboard-orchestration.ts | 5 - src/lib/onboard/sandbox-create-launch.test.ts | 57 ------- src/lib/onboard/sandbox-create-launch.ts | 8 - .../sandbox-dockerfile-patch-flow.test.ts | 35 +++++ .../onboard/sandbox-dockerfile-patch-flow.ts | 3 + .../runtime/nemoclaw-start-reconcile.test.ts | 75 +-------- 12 files changed, 250 insertions(+), 317 deletions(-) create mode 100644 src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts diff --git a/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index 2ebf7113603..4733d1fafc4 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -46,11 +46,11 @@ If the route metadata is incomplete, NemoClaw stops and tells you to re-run onbo At runtime, NemoClaw replaces `contextWindow` only when it resolves a value for the selected model and can retain an existing `maxTokens` value. -During custom-image startup, NemoClaw reconciles a stale model ID with the host-selected route only when the sandbox user can write `/sandbox/.openclaw/openclaw.json`. -That reconciliation removes both inherited limits when the model ID changes. -If the configuration is not writable, NemoClaw reports that reconciliation was skipped and preserves the existing configuration. -That preserved configuration can still contain the image's inherited model ID and limits. -Make the configuration writable by the sandbox user in the custom image, then recreate the sandbox. +For an OpenClaw custom image built with `--from`, onboarding patches an inherited model ID to the selected route during the image build. +It removes both inherited limits when the model ID changes and refreshes `.config-hash` before restoring the custom image's final user. +On later starts, NemoClaw can also reconcile drift from the live gateway when the sandbox user can write `/sandbox/.openclaw/openclaw.json`. +If that runtime configuration is not writable, NemoClaw reports that reconciliation was skipped and preserves the existing configuration. +Make the configuration writable by the sandbox user if later runtime route changes must update the file, then recreate the sandbox. To keep explicit limits for the new model, set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model before you recreate the sandbox. Refer to [Configure Model Limits](configure-model-limits) for the environment variable requirements. diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 09149957b5d..42edf0092fd 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -17,7 +17,6 @@ # NEMOCLAW_MODEL_OVERRIDE Override the primary model at startup without rebuilding # the sandbox image. Must match the model configured on # the gateway via `openshell inference set`. -# NEMOCLAW_ROUTED_MODEL Host-selected route model for custom-image startup. # NEMOCLAW_INFERENCE_API_OVERRIDE Override the inference API type when switching between # provider families (e.g., "anthropic-messages" or # "openai-completions"). Only needed for cross-provider switches. @@ -1107,10 +1106,8 @@ PYOVERRIDE # reconciliation the file's stale entry can be pushed back, reverting # the route. # -# A custom-image launch passes the host-selected route model through -# NEMOCLAW_ROUTED_MODEL. Otherwise, probe the live gateway via -# `openshell inference get`. When either route model differs from the file, -# align both primary and the inference provider's +# Probe the live gateway via `openshell inference get`. When the route model +# differs from the file, align both primary and the inference provider's # first model entry so the agent identity and the gateway route stay # consistent across the next reconcile cycle. # @@ -1122,116 +1119,6 @@ PYOVERRIDE # values still win. No-op when already in sync. # Ref: https://github.com/NVIDIA/NemoClaw/issues/3175 -# OpenShell persists sandbox-create environment values across stop/start. Record -# successful consumption of NEMOCLAW_ROUTED_MODEL so that create-time metadata -# cannot overwrite a later `inference set`. The receipt is read and written as -# the config owner; root never opens an agent-controlled path. -routed_model_receipt() { - local operation="$1" - local config_dir="/sandbox/.openclaw" - - run_openclaw_config_as_owner /usr/bin/python3 -I - "$config_dir" "$operation" <<'PYROUTEDMODELRECEIPT' -import os -import secrets -import stat -import sys - -config_dir, operation = sys.argv[1:] -marker_name = ".nemoclaw-routed-model-applied" -expected = b"nemoclaw-routed-model-applied-v1\n" -directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) -file_flags = os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) - -directory_fd = os.open(config_dir, directory_flags) -try: - directory = os.fstat(directory_fd) - if directory.st_uid != os.geteuid() or directory.st_gid != os.getegid(): - raise OSError("config directory owner does not match the runtime user") - config_fd = os.open("openclaw.json", file_flags, dir_fd=directory_fd) - try: - config = os.fstat(config_fd) - current_config = os.stat("openclaw.json", dir_fd=directory_fd, follow_symlinks=False) - if ( - not stat.S_ISREG(config.st_mode) - or (config.st_dev, config.st_ino) != (current_config.st_dev, current_config.st_ino) - or config.st_uid != os.geteuid() - or config.st_gid != os.getegid() - or config.st_nlink != 1 - ): - raise OSError("OpenClaw config is not a trusted regular file") - receipt_mode = stat.S_IMODE(config.st_mode) - finally: - os.close(config_fd) - - if operation == "check": - try: - marker_fd = os.open(marker_name, file_flags, dir_fd=directory_fd) - except FileNotFoundError: - raise SystemExit(1) - try: - opened = os.fstat(marker_fd) - current = os.stat(marker_name, dir_fd=directory_fd, follow_symlinks=False) - content = bytearray() - while len(content) <= len(expected): - chunk = os.read(marker_fd, len(expected) + 1 - len(content)) - if not chunk: - break - content.extend(chunk) - if ( - not stat.S_ISREG(opened.st_mode) - or (opened.st_dev, opened.st_ino) != (current.st_dev, current.st_ino) - or opened.st_uid != os.geteuid() - or opened.st_gid != os.getegid() - or stat.S_IMODE(opened.st_mode) != receipt_mode - or opened.st_nlink != 1 - or bytes(content) != expected - ): - raise OSError("routed-model receipt is not a trusted regular file") - finally: - os.close(marker_fd) - elif operation == "write": - temp_name = f".{marker_name}.{secrets.token_hex(12)}.tmp" - temp_fd = os.open( - temp_name, - os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0), - 0o600, - dir_fd=directory_fd, - ) - try: - os.fchmod(temp_fd, receipt_mode) - offset = 0 - while offset < len(expected): - offset += os.write(temp_fd, expected[offset:]) - os.fsync(temp_fd) - os.link( - temp_name, - marker_name, - src_dir_fd=directory_fd, - dst_dir_fd=directory_fd, - follow_symlinks=False, - ) - os.unlink(temp_name, dir_fd=directory_fd) - os.fsync(directory_fd) - except Exception: - try: - os.unlink(temp_name, dir_fd=directory_fd) - except OSError: - pass - raise - finally: - os.close(temp_fd) - else: - raise OSError("unsupported routed-model receipt operation") -except SystemExit: - raise -except Exception as error: - print(f"[SECURITY] Routed-model receipt {operation} failed: {error}", file=sys.stderr) - raise SystemExit(2) -finally: - os.close(directory_fd) -PYROUTEDMODELRECEIPT -} - reconcile_agent_model_with_provider() { # apply_model_override already won; reconciling against the gateway would # overwrite the user's explicit choice with an inference/-prefixed variant. @@ -1254,25 +1141,7 @@ reconcile_agent_model_with_provider() { local gateway_model="" local model_source="gateway" - local routed_model_pending=0 - local routed_model_receipt_status=0 - if [ -n "${NEMOCLAW_ROUTED_MODEL:-}" ]; then - routed_model_receipt check || routed_model_receipt_status=$? - if [ "$routed_model_receipt_status" -eq 1 ]; then - gateway_model="$NEMOCLAW_ROUTED_MODEL" - model_source="route" - routed_model_pending=1 - elif [ "$routed_model_receipt_status" -ne 0 ]; then - return "$routed_model_receipt_status" - fi - fi - if [ "$routed_model_pending" -eq 1 ]; then - if [ "${#gateway_model}" -gt 512 ] \ - || ! printf '%s' "$gateway_model" | grep -qE '^[A-Za-z0-9._:/-]+$'; then - printf '[SECURITY] Routed model rejected an unsafe model identifier\n' >&2 - return 1 - fi - elif command -v openshell >/dev/null 2>&1; then + if command -v openshell >/dev/null 2>&1; then gateway_model="$( /usr/bin/python3 -I - <<'PYPROBE' import re @@ -1400,9 +1269,6 @@ PYRECONCILE_READ )" if [ -z "$provider_model_ref" ]; then - if [ "$routed_model_pending" -eq 1 ]; then - routed_model_receipt write || return $? - fi return 0 fi @@ -1458,9 +1324,6 @@ PYRECONCILE_WRITE fi normalize_mutable_config_perms || _write_rc=$? - if [ "$_write_rc" -eq 0 ] && [ "$routed_model_pending" -eq 1 ]; then - routed_model_receipt write || _write_rc=$? - fi [ "$_write_rc" -eq 0 ] || return "$_write_rc" } diff --git a/src/lib/onboard/docker-startup-command-env.ts b/src/lib/onboard/docker-startup-command-env.ts index 0c7a9502ce3..1637117e645 100644 --- a/src/lib/onboard/docker-startup-command-env.ts +++ b/src/lib/onboard/docker-startup-command-env.ts @@ -25,9 +25,6 @@ const OPENCLAW_AUTO_PAIR_RUNTIME_ENV_KEYS = [ ] as const; const OPENCLAW_DIAGNOSTIC_RUNTIME_ENV_KEYS = ["NEMOCLAW_MCP_SHADOW_DIAGNOSTICS"] as const; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_ENV = "NEMOCLAW_MCP_TOOLS_LIST_TIMEOUT_MS"; -const OPENCLAW_ROUTED_MODEL_ENV = "NEMOCLAW_ROUTED_MODEL"; -const OPENCLAW_ROUTED_MODEL_MAX_LENGTH = 512; -const OPENCLAW_ROUTED_MODEL_PATTERN = /^[A-Za-z0-9._:/-]+$/; const OPENCLAW_GATEWAY_URL_ENV = "OPENCLAW_GATEWAY_URL"; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_MIN_MS = 1500; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_MAX_MS = 10_000; @@ -102,7 +99,6 @@ export interface SandboxRuntimeEnvArgsInput { extraPlaceholderKeys: readonly string[]; allowHermesApiPortOverride?: boolean; observabilityEnabled?: boolean; - openClawRoutedModel?: string; sandboxName?: string; env: NodeJS.ProcessEnv; omitCredentialEnv?: boolean; @@ -129,15 +125,6 @@ export function buildSandboxRuntimeEnvArgs(input: SandboxRuntimeEnvArgsInput): { appendOpenClawAutoPairRuntimeEnvArgs(envArgs, agent, env); appendOpenClawDiagnosticRuntimeEnvArgs(envArgs, agent, env); appendOpenClawMcpToolsListTimeoutRuntimeEnvArg(envArgs, agent, env); - if ((!agent || agent.name === "openclaw") && input.openClawRoutedModel) { - if ( - input.openClawRoutedModel.length > OPENCLAW_ROUTED_MODEL_MAX_LENGTH || - !OPENCLAW_ROUTED_MODEL_PATTERN.test(input.openClawRoutedModel) - ) { - throw new Error("The selected OpenClaw route model has an invalid identifier."); - } - envArgs.push(formatEnvAssignment(OPENCLAW_ROUTED_MODEL_ENV, input.openClawRoutedModel)); - } appendHermesDashboardEnvArgs(envArgs, input.hermesDashboardState, formatEnvAssignment); if (agent?.name === "hermes" && input.sandboxName) { const apiPort = diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts new file mode 100644 index 00000000000..fef6a3a2486 --- /dev/null +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { patchStagedDockerfile } from "./dockerfile-patch"; + +describe("custom OpenClaw Dockerfile model reconciliation", () => { + it("drops stale limits for the selected model and preserves the final image user", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-model-patch-")); + try { + const dockerfilePath = path.join(root, "Dockerfile"); + fs.writeFileSync( + dockerfilePath, + [ + "FROM example.invalid/openclaw@sha256:" + "1".repeat(64), + "ARG NEMOCLAW_TOOL_DISCLOSURE=progressive", + "USER 1001:1001", + ].join("\n"), + ); + + patchStagedDockerfile( + dockerfilePath, + "provider/selected-model", + "http://127.0.0.1:18789", + "build-1", + null, + null, + null, + null, + false, + null, + [], + { agentName: "openclaw", reconcileCustomOpenClawModel: true }, + ); + + const patched = fs.readFileSync(dockerfilePath, "utf-8"); + expect(patched).toContain("ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="); + expect(patched).toContain("sha256sum openclaw.json > .config-hash"); + expect(patched.trimEnd().endsWith("USER 1001:1001")).toBe(true); + + const embedded = patched.match( + /<<'PYNEMOCLAWCUSTOMROUTE'\n([\s\S]*?)\nPYNEMOCLAWCUSTOMROUTE/u, + )?.[1]; + expect(embedded).toBeDefined(); + const configPath = path.join(root, "openclaw.json"); + fs.writeFileSync( + configPath, + JSON.stringify({ + agents: { defaults: { model: { primary: "inference/baked-model" } } }, + models: { + providers: { + inference: { + models: [ + { + id: "baked-model", + name: "inference/baked-model", + contextWindow: 131_072, + maxTokens: 4_096, + }, + ], + }, + }, + }, + }), + ); + const program = embedded!.replace( + 'config_path = "/sandbox/.openclaw/openclaw.json"', + `config_path = ${JSON.stringify(configPath)}`, + ); + const result = spawnSync("/usr/bin/python3", ["-I", "-c", program], { + encoding: "utf-8", + env: { + ...process.env, + NEMOCLAW_CUSTOM_ROUTE_MODEL_B64: Buffer.from("provider/selected-model", "utf8").toString( + "base64", + ), + }, + }); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(configPath, "utf8"))).toEqual({ + agents: { defaults: { model: { primary: "inference/provider/selected-model" } } }, + models: { + providers: { + inference: { + models: [ + { + id: "provider/selected-model", + name: "inference/provider/selected-model", + }, + ], + }, + }, + }, + }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 77fd399cbe0..1656eed93ce 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -192,6 +192,96 @@ export interface PatchStagedDockerfileOptions { compatibleEndpointReasoning?: "true" | "false"; wslDashboardExposure?: boolean; rebuildPreservedEnv?: readonly PreservedEnvFile[]; + reconcileCustomOpenClawModel?: boolean; +} + +function appendCustomOpenClawModelReconcile(dockerfile: string, model: string): string { + const instructions = dockerfileInstructions(dockerfile); + const finalFromIndex = instructions.reduce( + (last, instruction, index) => (/^FROM(?:\s|$)/i.test(instruction.text) ? index : last), + -1, + ); + const finalUser = instructions + .slice(finalFromIndex + 1) + .reduce( + (last, instruction) => (/^USER(?:\s|$)/i.test(instruction.text) ? instruction : last), + null, + ); + const restoreUser = finalUser?.text ?? "USER sandbox"; + const encodedModel = Buffer.from(model, "utf8").toString("base64"); + + return `${dockerfile.trimEnd()} + +# Reconcile inherited OpenClaw model metadata with this custom image's route. +ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} +USER root +RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' +import base64 +import json +import os +import re +import stat + +config_path = "/sandbox/.openclaw/openclaw.json" +if os.path.exists(config_path): + model = base64.b64decode( + os.environ["NEMOCLAW_CUSTOM_ROUTE_MODEL_B64"], validate=True + ).decode("utf-8") + if len(model) > 512 or re.fullmatch(r"[A-Za-z0-9._:/-]+", model) is None: + raise SystemExit("custom OpenClaw route model is invalid") + flags = os.O_RDWR | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) + config_fd = os.open(config_path, flags) + try: + metadata = os.fstat(config_fd) + current = os.stat(config_path, follow_symlinks=False) + if ( + not stat.S_ISREG(metadata.st_mode) + or (metadata.st_dev, metadata.st_ino) != (current.st_dev, current.st_ino) + or metadata.st_nlink != 1 + ): + raise OSError("OpenClaw config is not a trusted regular file") + with os.fdopen(config_fd, "r+", encoding="utf-8", closefd=False) as config_file: + config = json.load(config_file) + provider_model = model if model.startswith("inference/") else f"inference/{model}" + bare_model = model.removeprefix("inference/") + config.setdefault("agents", {}).setdefault("defaults", {}).setdefault("model", {})[ + "primary" + ] = provider_model + inference = config.setdefault("models", {}).setdefault("providers", {}).setdefault( + "inference", {} + ) + models = inference.get("models") + if not isinstance(models, list) or not models: + models = [{}] + inference["models"] = models + first = models[0] + if not isinstance(first, dict): + first = {} + models[0] = first + model_changed = first.get("id") not in (bare_model, provider_model) + first["id"] = bare_model + first["name"] = provider_model + if model_changed: + first.pop("contextWindow", None) + first.pop("maxTokens", None) + config_file.seek(0) + json.dump(config, config_file, indent=2) + config_file.write("\\n") + config_file.truncate() + config_file.flush() + os.fsync(config_fd) + finally: + os.close(config_fd) +PYNEMOCLAWCUSTOMROUTE +RUN if [ -f /sandbox/.openclaw/openclaw.json ]; then \\ + cd /sandbox/.openclaw; \\ + rm -f -- .config-hash; \\ + sha256sum openclaw.json > .config-hash; \\ + chown --reference=openclaw.json .config-hash; \\ + chmod --reference=openclaw.json .config-hash; \\ + fi +${restoreUser} +`; } function openClawRuntimeUserArg(dockerfile: string): DockerfileInstruction | null { @@ -704,6 +794,9 @@ export function patchStagedDockerfile( ); } } + if (options.reconcileCustomOpenClawModel) { + dockerfile = appendCustomOpenClawModelReconcile(dockerfile, sanitizedModel); + } replaceDockerfilePatchSnapshot(dockerfilePath, patchSnapshot, dockerfile); return { dashboardRemoteBindPrepared }; diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index 9881c03affb..075a37d0eba 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -746,20 +746,6 @@ describe("managed workload onboard orchestration", () => { }; it.each([ - { - behavior: "passes the selected routed model through the production custom OpenClaw launch", - agentName: "openclaw", - fromDockerfile: "/custom/Dockerfile", - preparedBuildContext: { - ...preparedHermesContext, - origin: "custom" as const, - rebuildTarget: { agentName: "openclaw", fromDockerfile: "/custom/Dockerfile" }, - }, - expectedFromDockerfile: "/custom/Dockerfile", - expectedStageCalls: 0, - expectedRawCreate: false, - expectedRoutedModel: "nvidia/selected-model", - }, { behavior: "stages a fresh LangChain Deep Agents Code build before resolving patch metadata", agentName: "langchain-deepagents-code", @@ -896,11 +882,6 @@ describe("managed workload onboard orchestration", () => { }, } as unknown as Parameters[0]); - expect( - preparedLaunch.launch.envArgs.filter((value) => value.startsWith("NEMOCLAW_ROUTED_MODEL=")), - ).toEqual( - testCase.expectedRoutedModel ? [`NEMOCLAW_ROUTED_MODEL=${testCase.expectedRoutedModel}`] : [], - ); expect(resolvePatchInput).toHaveBeenCalledOnce(); expect(resolveSandboxBuildPatch).toHaveBeenCalledOnce(); expect(materializeSandboxCreatePlan).toHaveBeenCalledWith( diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index 45ddebc9310..ad361dfec8a 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -592,11 +592,6 @@ export async function prepareOnboardSandboxWorkloadLaunch( const runtimeLaunch = prepareSandboxRuntimeLaunch({ ...launchInput, policyAttached: Boolean(createPlan.createRequest.policyPath), - openClawRoutedModel: - buildContext.origin === "custom" && - (!launchInput.agent || launchInput.agent.name === "openclaw") - ? patchInput.model || undefined - : undefined, }); const { createArgs: _portableArgs, ...prebuild } = await prebuildSandboxImageIfEligible({ buildCtx: buildContext.buildCtx, diff --git a/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index 5ae865c3b33..0939938f30b 100644 --- a/src/lib/onboard/sandbox-create-launch.test.ts +++ b/src/lib/onboard/sandbox-create-launch.test.ts @@ -677,62 +677,6 @@ describe("prepareSandboxCreateLaunch", () => { }); describe("prepareSandboxCreateLaunchWithPrebuild", () => { - it("passes the selected route model to a custom non-root OpenClaw image", async () => { - const buildCtx = createTrustedBuildContext(); - const dockerfile = path.join(buildCtx, "Dockerfile"); - const result = await prepareSandboxCreateLaunchWithPrebuild({ - agent: { name: "openclaw" } as any, - chatUiUrl: "", - createArgs: ["--from", dockerfile, "--name", "demo"], - env: { NEMOCLAW_MODEL: "provider/selected-model" }, - extraPlaceholderKeys: [], - getDashboardForwardPort: () => "0", - hermesDashboardState: disabledHermesDashboardState, - manageDashboard: false, - openshellShellCommand: (args) => args.join(" "), - sandboxName: "demo", - buildEnv: () => ({}), - prebuild: { - buildCtx, - buildId: "build-123", - dockerDriverGateway: true, - env: { NEMOCLAW_SANDBOX_PREBUILD: "1" }, - origin: "custom", - }, - }); - - expect(result.envArgs).toContain("NEMOCLAW_ROUTED_MODEL=provider/selected-model"); - expect(result.createCommand).toContain("NEMOCLAW_ROUTED_MODEL=provider/selected-model"); - }); - - it("rejects an unsafe selected route model before sandbox creation", async () => { - const buildCtx = createTrustedBuildContext(); - const dockerfile = path.join(buildCtx, "Dockerfile"); - - await expect( - prepareSandboxCreateLaunchWithPrebuild({ - agent: { name: "openclaw" } as any, - chatUiUrl: "", - createArgs: ["--from", dockerfile, "--name", "demo"], - env: { NEMOCLAW_MODEL: "model;unsafe" }, - extraPlaceholderKeys: [], - getDashboardForwardPort: () => "0", - hermesDashboardState: disabledHermesDashboardState, - manageDashboard: false, - openshellShellCommand: (args) => args.join(" "), - sandboxName: "demo", - buildEnv: () => ({}), - prebuild: { - buildCtx, - buildId: "build-123", - dockerDriverGateway: true, - env: { NEMOCLAW_SANDBOX_PREBUILD: "1" }, - origin: "custom", - }, - }), - ).rejects.toThrow("selected OpenClaw route model has an invalid identifier"); - }); - it("hands the build-qualified image to the canonical launch renderer", async () => { const buildCtx = createTrustedBuildContext(); const dockerfile = path.join(buildCtx, "Dockerfile"); @@ -770,7 +714,6 @@ describe("prepareSandboxCreateLaunchWithPrebuild", () => { expect(result.createCommand).toContain( "sandbox create --from nemoclaw-sandbox-local:demo-build-123 --name demo", ); - expect(result.envArgs.some((arg) => arg.startsWith("NEMOCLAW_ROUTED_MODEL="))).toBe(false); expect(buildImage).toHaveBeenCalledOnce(); }); diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index 879df44f4c8..a336bb51102 100644 --- a/src/lib/onboard/sandbox-create-launch.ts +++ b/src/lib/onboard/sandbox-create-launch.ts @@ -33,8 +33,6 @@ export const OPENSHELL_SANDBOX_SUPERVISOR_ARGV = Object.freeze([ export interface SandboxCreateLaunchInput { agent: AgentDefinition | null | undefined; observabilityEnabled?: boolean; - /** Selected route model injected only for a custom OpenClaw image. */ - openClawRoutedModel?: string; chatUiUrl: string; createArgs: readonly string[]; sandboxName?: string; @@ -124,7 +122,6 @@ export function prepareSandboxRuntimeLaunch( hermesApiPort: input.hermesApiPort, extraPlaceholderKeys: input.extraPlaceholderKeys, observabilityEnabled: input.observabilityEnabled, - openClawRoutedModel: input.openClawRoutedModel, sandboxName: input.sandboxName, allowHermesApiPortOverride: true, env, @@ -221,11 +218,6 @@ export async function prepareSandboxCreateLaunchWithPrebuild( ...prepareSandboxCreateLaunch({ ...launchInput, createArgs: prebuild.createArgs, - openClawRoutedModel: - prebuildInput.origin === "custom" && - (!launchInput.agent || launchInput.agent.name === "openclaw") - ? (launchInput.env ?? process.env).NEMOCLAW_MODEL?.trim() - : undefined, }), prebuild, }; diff --git a/src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts b/src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts index 1f46aef1c2e..75ef033aa71 100644 --- a/src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts +++ b/src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts @@ -406,6 +406,41 @@ describe("prepareSandboxDockerfilePatch", () => { }); }); + it("requests build-time model reconciliation only for custom OpenClaw", async () => { + const patchStagedDockerfile = vi.fn(); + + await prepareSandboxDockerfilePatch({ + agent: { name: "openclaw" } as any, + fromDockerfile: "/repo/Containerfile", + sandboxBaseImage: "ghcr.io/nvidia/nemoclaw/sandbox-base", + sandboxBaseTag: "latest", + stagedDockerfile: "/tmp/Dockerfile", + model: "provider/selected-model", + chatUiUrl: "http://127.0.0.1:7000", + provider: null, + preferredInferenceApi: null, + webSearchConfig: null, + hermesToolGateways: [], + sandboxGpuConfig, + deps: { + isLinuxDockerDriverGatewayEnabled: vi.fn(() => false), + pullAndResolveBaseImageDigest: vi.fn(() => ({ + digest: "sha256:custom-openclaw", + ref: "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:custom-openclaw", + })), + enforceDockerGpuPatchPreserveNetwork: vi.fn(async () => false), + patchStagedDockerfile, + now: () => 1, + }, + }); + + expect(patchStagedDockerfile.mock.calls[0]?.[11]).toMatchObject({ + agentName: "openclaw", + reconcileCustomOpenClawModel: true, + requireToolDisclosureContract: true, + }); + }); + it("keeps the per-run rewrite for managed agents that consume the build id", async () => { const patchStagedDockerfile = vi.fn(); diff --git a/src/lib/onboard/sandbox-dockerfile-patch-flow.ts b/src/lib/onboard/sandbox-dockerfile-patch-flow.ts index 14c3386762c..b4b5516a8bf 100644 --- a/src/lib/onboard/sandbox-dockerfile-patch-flow.ts +++ b/src/lib/onboard/sandbox-dockerfile-patch-flow.ts @@ -228,6 +228,9 @@ export async function prepareSandboxDockerfilePatch({ ...(compatibleEndpointReasoning ? { compatibleEndpointReasoning } : {}), ...(dcodeAutoApprovalMode ? { dcodeAutoApprovalMode } : {}), requireToolDisclosureContract: Boolean(fromDockerfile), + ...(fromDockerfile && managedAgentName === "openclaw" + ? { reconcileCustomOpenClawModel: true } + : {}), ...(metadata ? { baseImageResolutionMetadata: metadata } : {}), }; })(), diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index fd313de5d84..97721ace385 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -37,7 +37,6 @@ interface RunReconcileOptions { configWritable?: boolean; hashFailure?: boolean; env?: Record; - routedModelReceipt?: "valid" | "symlink"; } describe("agent identity reconciliation with provider (#3175)", () => { @@ -62,17 +61,6 @@ describe("agent identity reconciliation with provider (#3175)", () => { fs.chmodSync(openclawDir, 0o2770); fs.chmodSync(configPath, options.configWritable === false ? 0o440 : 0o660); fs.chmodSync(hashPath, 0o660); - const routedModelReceiptPath = path.join(openclawDir, ".nemoclaw-routed-model-applied"); - const prepareRoutedModelReceipt = { - valid: () => { - fs.writeFileSync(routedModelReceiptPath, "nemoclaw-routed-model-applied-v1\n"); - fs.chmodSync(routedModelReceiptPath, options.configWritable === false ? 0o440 : 0o660); - }, - symlink: () => fs.symlinkSync(configPath, routedModelReceiptPath), - none: () => undefined, - }[options.routedModelReceipt ?? "none"]; - prepareRoutedModelReceipt(); - const prepareSymlink = { config: () => { const target = path.join(openclawDir, "openclaw.real.json"); @@ -122,7 +110,6 @@ describe("agent identity reconciliation with provider (#3175)", () => { ? "ensure_mutable_openclaw_config_hash() { return 19; }" : `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, ].join("\n"); - const receiptFn = extractShellFunction("routed_model_receipt").replaceAll("/sandbox", root); const fn = extractShellFunction("reconcile_agent_model_with_provider").replaceAll( "/sandbox", root, @@ -132,7 +119,6 @@ describe("agent identity reconciliation with provider (#3175)", () => { "set -euo pipefail", ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), helperFns, - receiptFn, fn, "reconcile_agent_model_with_provider", ].join("\n"); @@ -161,11 +147,8 @@ describe("agent identity reconciliation with provider (#3175)", () => { }); const config = JSON.parse(fs.readFileSync(configPath, "utf-8")); const hash = fs.readFileSync(hashPath, "utf-8"); - const routedModelReceipt = fs.existsSync(routedModelReceiptPath) - ? fs.readFileSync(routedModelReceiptPath, "utf-8") - : null; fs.rmSync(root, { recursive: true, force: true }); - return { result, config, hash, routedModelReceipt }; + return { result, config, hash }; } it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { @@ -279,7 +262,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( "reconciles an actually owned config as the current non-root user (#12033)", () => { - const { result, config, hash, routedModelReceipt } = runReconcile( + const { result, config, hash } = runReconcile( { agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, models: { @@ -299,7 +282,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, }, { - env: { NEMOCLAW_ROUTED_MODEL: "nvidia/nemotron-3-super-120b-a12b" }, + gatewayModel: "nvidia/nemotron-3-super-120b-a12b", useActualUser: true, }, ); @@ -318,11 +301,10 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(config.models.providers.inference.models[0]).not.toHaveProperty("maxTokens"); expect(hash).not.toBe("oldhash\n"); expect(hash).toContain("openclaw.json"); - expect(routedModelReceipt).toBe("nemoclaw-routed-model-applied-v1\n"); }, ); - it("does not replay the create-time routed model after a later model switch", () => { + it("preserves a later model switch when the live gateway probe is unavailable", () => { const switched = { agents: { defaults: { model: { primary: "inference/nvidia/switched-model" } } }, models: { @@ -340,60 +322,13 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, }, }; - const { result, config, hash } = runReconcile(switched, { - env: { NEMOCLAW_ROUTED_MODEL: "nvidia/create-time-model" }, - routedModelReceipt: "valid", - }); + const { result, config, hash } = runReconcile(switched); expect(result.status, result.stderr || result.stdout).toBe(0); expect(config).toEqual(switched); expect(hash).toBe("oldhash\n"); }); - it("fails closed when the routed-model receipt is a symlink", () => { - const initial = { - agents: { defaults: { model: { primary: "inference/nvidia/baked-model" } } }, - models: { - providers: { - inference: { - models: [{ id: "nvidia/baked-model", name: "inference/nvidia/baked-model" }], - }, - }, - }, - }; - const { result, config, hash } = runReconcile(initial, { - env: { NEMOCLAW_ROUTED_MODEL: "nvidia/create-time-model" }, - routedModelReceipt: "symlink", - }); - - expect(result.status).not.toBe(0); - expect(result.stderr).toContain("Routed-model receipt check failed"); - expect(config).toEqual(initial); - expect(hash).toBe("oldhash\n"); - }); - - it("rejects an unsafe host-routed model without changing the config", () => { - const initial = { - agents: { defaults: { model: { primary: "inference/safe-file-model" } } }, - models: { - providers: { - inference: { - models: [{ id: "safe-file-model", name: "inference/safe-file-model" }], - }, - }, - }, - }; - const { result, config, hash } = runReconcile(initial, { - env: { NEMOCLAW_ROUTED_MODEL: "model;unsafe" }, - }); - - expect(result.status).toBe(1); - expect(config).toEqual(initial); - expect(hash).toBe("oldhash\n"); - expect(result.stderr).toContain("Routed model rejected an unsafe model identifier"); - expect(result.stderr).not.toContain("model;unsafe"); - }); - it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( "explains why an actual non-root user cannot reconcile a sealed config (#12033)", () => { From a48a7c947fffc7dbd5317eced26c0a9c46a8198c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 17:42:19 -0700 Subject: [PATCH 14/34] fix(openclaw): preserve explicit custom image limits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...le-custom-openclaw-model-reconcile.test.ts | 35 +++++++++++++--- src/lib/onboard/dockerfile-patch.ts | 41 ++++++++++++++++--- test/e2e/support/workflow-plan.test.ts | 2 + tools/e2e/target-catalogue.mts | 2 + 4 files changed, 69 insertions(+), 11 deletions(-) diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index fef6a3a2486..07ff064aa8e 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -6,12 +6,31 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { patchStagedDockerfile } from "./dockerfile-patch"; describe("custom OpenClaw Dockerfile model reconciliation", () => { - it("drops stale limits for the selected model and preserves the final image user", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it.each([ + { + behavior: "drops inherited limits", + contextWindow: "", + maxTokens: "", + expectedLimits: {}, + }, + { + behavior: "retains explicit limits", + contextWindow: "65536", + maxTokens: "8192", + expectedLimits: { contextWindow: 65_536, maxTokens: 8_192 }, + }, + ])("$behavior for the selected model and preserves the final image user", (testCase) => { + vi.stubEnv("NEMOCLAW_CONTEXT_WINDOW", testCase.contextWindow); + vi.stubEnv("NEMOCLAW_MAX_TOKENS", testCase.maxTokens); const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-model-patch-")); try { const dockerfilePath = path.join(root, "Dockerfile"); @@ -40,7 +59,11 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { ); const patched = fs.readFileSync(dockerfilePath, "utf-8"); - expect(patched).toContain("ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="); + const encodedModel = /^ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=(.+)$/mu.exec(patched)?.[1] ?? ""; + const encodedLimits = + /^ARG NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64=(.+)$/mu.exec(patched)?.[1] ?? ""; + expect(encodedModel).not.toBe(""); + expect(encodedLimits).not.toBe(""); expect(patched).toContain("sha256sum openclaw.json > .config-hash"); expect(patched.trimEnd().endsWith("USER 1001:1001")).toBe(true); @@ -77,9 +100,8 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { encoding: "utf-8", env: { ...process.env, - NEMOCLAW_CUSTOM_ROUTE_MODEL_B64: Buffer.from("provider/selected-model", "utf8").toString( - "base64", - ), + NEMOCLAW_CUSTOM_ROUTE_MODEL_B64: encodedModel, + NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64: encodedLimits, }, }); @@ -93,6 +115,7 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { { id: "provider/selected-model", name: "inference/provider/selected-model", + ...testCase.expectedLimits, }, ], }, diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 1656eed93ce..db766dde14c 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -195,7 +195,11 @@ export interface PatchStagedDockerfileOptions { reconcileCustomOpenClawModel?: boolean; } -function appendCustomOpenClawModelReconcile(dockerfile: string, model: string): string { +function appendCustomOpenClawModelReconcile( + dockerfile: string, + model: string, + explicitLimits: { contextWindow?: string; maxTokens?: string }, +): string { const instructions = dockerfileInstructions(dockerfile); const finalFromIndex = instructions.reduce( (last, instruction, index) => (/^FROM(?:\s|$)/i.test(instruction.text) ? index : last), @@ -209,13 +213,15 @@ function appendCustomOpenClawModelReconcile(dockerfile: string, model: string): ); const restoreUser = finalUser?.text ?? "USER sandbox"; const encodedModel = Buffer.from(model, "utf8").toString("base64"); + const encodedLimits = Buffer.from(JSON.stringify(explicitLimits), "utf8").toString("base64"); return `${dockerfile.trimEnd()} # Reconcile inherited OpenClaw model metadata with this custom image's route. ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} +ARG NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64=${encodedLimits} USER root -RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' +RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64="\${NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' import base64 import json import os @@ -229,6 +235,21 @@ if os.path.exists(config_path): ).decode("utf-8") if len(model) > 512 or re.fullmatch(r"[A-Za-z0-9._:/-]+", model) is None: raise SystemExit("custom OpenClaw route model is invalid") + explicit_limits = json.loads( + base64.b64decode( + os.environ["NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64"], validate=True + ).decode("utf-8") + ) + if not isinstance(explicit_limits, dict) or set(explicit_limits) - { + "contextWindow", + "maxTokens", + }: + raise SystemExit("custom OpenClaw route limits are invalid") + for field, value in explicit_limits.items(): + if not isinstance(value, str) or re.fullmatch(r"[1-9][0-9]*", value) is None: + raise SystemExit("custom OpenClaw route limits are invalid") + if field == "contextWindow" and int(value) > ${MAX_AUTODETECTED_OLLAMA_CONTEXT_WINDOW}: + raise SystemExit("custom OpenClaw route context window is too large") flags = os.O_RDWR | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) config_fd = os.open(config_path, flags) try: @@ -262,8 +283,11 @@ if os.path.exists(config_path): first["id"] = bare_model first["name"] = provider_model if model_changed: - first.pop("contextWindow", None) - first.pop("maxTokens", None) + for field in ("contextWindow", "maxTokens"): + if field in explicit_limits: + first[field] = int(explicit_limits[field]) + else: + first.pop(field, None) config_file.seek(0) json.dump(config, config_file, indent=2) config_file.write("\\n") @@ -795,7 +819,14 @@ export function patchStagedDockerfile( } } if (options.reconcileCustomOpenClawModel) { - dockerfile = appendCustomOpenClawModelReconcile(dockerfile, sanitizedModel); + dockerfile = appendCustomOpenClawModelReconcile(dockerfile, sanitizedModel, { + ...(contextWindow && + POSITIVE_INT_RE.test(contextWindow) && + Number(contextWindow) <= MAX_AUTODETECTED_OLLAMA_CONTEXT_WINDOW + ? { contextWindow } + : {}), + ...(maxTokens && POSITIVE_INT_RE.test(maxTokens) ? { maxTokens } : {}), + }); } replaceDockerfilePatchSnapshot(dockerfilePath, patchSnapshot, dockerfile); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 105ad59bdf9..f2a4c2a6134 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -741,8 +741,10 @@ describe("E2E workflow plan", () => { it.each([ "scripts/nemoclaw-start.sh", "src/lib/onboard/docker-startup-command-env.ts", + "src/lib/onboard/dockerfile-patch.ts", "src/lib/onboard/managed-workload/onboard-orchestration.ts", "src/lib/onboard/sandbox-create-launch.ts", + "src/lib/onboard/sandbox-dockerfile-patch-flow.ts", ])("selects the Docker custom-image proof when %s changes", (changedFile) => { expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( "openclaw-inference-switch", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 9389155effd..f84a8156861 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1150,8 +1150,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ owningPaths: [ "scripts/nemoclaw-start.sh", "src/lib/onboard/docker-startup-command-env.ts", + "src/lib/onboard/dockerfile-patch.ts", "src/lib/onboard/managed-workload/onboard-orchestration.ts", "src/lib/onboard/sandbox-create-launch.ts", + "src/lib/onboard/sandbox-dockerfile-patch-flow.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", ], environment: { From d7f3d00e0861dfde7153b79d96c648ada475c6ed Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 19:11:45 -0700 Subject: [PATCH 15/34] test(openclaw): prove custom image limits are replaced Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...erfile-custom-openclaw-model-reconcile.test.ts | 13 +++++++++++-- src/lib/onboard/dockerfile-patch.ts | 11 +++++------ test/e2e/live/openclaw-inference-switch.test.ts | 15 +++++++++++++-- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index 07ff064aa8e..c7a3cba7ea8 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -20,12 +20,21 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { behavior: "drops inherited limits", contextWindow: "", maxTokens: "", + inheritedModelId: "baked-model", expectedLimits: {}, }, { behavior: "retains explicit limits", contextWindow: "65536", maxTokens: "8192", + inheritedModelId: "baked-model", + expectedLimits: { contextWindow: 65_536, maxTokens: 8_192 }, + }, + { + behavior: "overrides inherited limits when the model already matches", + contextWindow: "65536", + maxTokens: "8192", + inheritedModelId: "provider/selected-model", expectedLimits: { contextWindow: 65_536, maxTokens: 8_192 }, }, ])("$behavior for the selected model and preserves the final image user", (testCase) => { @@ -81,8 +90,8 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { inference: { models: [ { - id: "baked-model", - name: "inference/baked-model", + id: testCase.inheritedModelId, + name: `inference/${testCase.inheritedModelId}`, contextWindow: 131_072, maxTokens: 4_096, }, diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index db766dde14c..f90ef64d8af 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -282,12 +282,11 @@ if os.path.exists(config_path): model_changed = first.get("id") not in (bare_model, provider_model) first["id"] = bare_model first["name"] = provider_model - if model_changed: - for field in ("contextWindow", "maxTokens"): - if field in explicit_limits: - first[field] = int(explicit_limits[field]) - else: - first.pop(field, None) + for field in ("contextWindow", "maxTokens"): + if field in explicit_limits: + first[field] = int(explicit_limits[field]) + elif model_changed: + first.pop(field, None) config_file.seek(0) json.dump(config, config_file, indent=2) config_file.write("\\n") diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index ed9336f83e9..92f7b0eddbb 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -115,7 +115,12 @@ interface OpenClawConfig { baseUrl?: unknown; apiKey?: unknown; api?: unknown; - models?: Array<{ id?: unknown; name?: unknown; maxTokens?: unknown }>; + models?: Array<{ + contextWindow?: unknown; + id?: unknown; + name?: unknown; + maxTokens?: unknown; + }>; } >; }; @@ -1078,7 +1083,13 @@ test( const startupConfig = JSON.parse(startupConfigResult.stdout) as OpenClawConfig; const startupModel = startupConfig.models?.providers?.inference?.models?.[0]; expect(startupConfig.agents?.defaults?.model?.primary).toBe(`inference/${baselineModel}`); - expect(startupModel?.id).toBe(baselineModel); + expect( + startupModel !== undefined && + startupModel.id === baselineModel && + !Object.hasOwn(startupModel, "contextWindow") && + !Object.hasOwn(startupModel, "maxTokens"), + `OpenClaw retained stale custom-image config metadata: ${JSON.stringify(startupModel)}`, + ).toBe(true); const effectiveModelResult = await sandbox.exec( SANDBOX_NAME, From 580a576f9769a3c5ac6d20a33c21812edf2b4246 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 24 Sep 2026 06:24:02 -0700 Subject: [PATCH 16/34] docs(openclaw): clarify custom image model limits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/configure-model-limits.mdx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/inference/configure-model-limits.mdx b/docs/inference/configure-model-limits.mdx index 9ea4c1e3066..d40b2f00c20 100644 --- a/docs/inference/configure-model-limits.mdx +++ b/docs/inference/configure-model-limits.mdx @@ -61,6 +61,11 @@ OpenClaw accepts an explicit context window and maximum output-token count. | `NEMOCLAW_CONTEXT_WINDOW` | Positive integer in tokens | `131072` | | `NEMOCLAW_MAX_TOKENS` | Positive integer in tokens | `4096` | +These defaults apply to NemoClaw-managed images. +For a custom image supplied with `--from`, startup keeps valid explicit overrides. +When the selected model differs from the inherited image model, startup removes inherited `contextWindow` and `maxTokens` values if no valid explicit overrides exist. +OpenClaw and the selected model then determine the effective limits. + Export one or both values before onboarding. ```bash From ebb846671d3636ea01a5fcb0ac67cac49f8342ce Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:27:15 -0700 Subject: [PATCH 17/34] fix(onboard): preserve custom image runtime behavior Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/configure-model-limits.mdx | 6 ++-- ...le-custom-openclaw-model-reconcile.test.ts | 35 +++++++++++++++++++ src/lib/onboard/dockerfile-patch.ts | 9 +++-- .../live/openclaw-inference-switch.test.ts | 26 +++++++++----- test/e2e/support/workflow-plan.test.ts | 19 ++++++++-- tools/e2e/target-catalogue.mts | 3 +- 6 files changed, 79 insertions(+), 19 deletions(-) diff --git a/docs/inference/configure-model-limits.mdx b/docs/inference/configure-model-limits.mdx index d40b2f00c20..d9d1a1ddefe 100644 --- a/docs/inference/configure-model-limits.mdx +++ b/docs/inference/configure-model-limits.mdx @@ -62,8 +62,10 @@ OpenClaw accepts an explicit context window and maximum output-token count. | `NEMOCLAW_MAX_TOKENS` | Positive integer in tokens | `4096` | These defaults apply to NemoClaw-managed images. -For a custom image supplied with `--from`, startup keeps valid explicit overrides. -When the selected model differs from the inherited image model, startup removes inherited `contextWindow` and `maxTokens` values if no valid explicit overrides exist. +For a custom image supplied with `--from`, NemoClaw applies valid explicit overrides when it builds the sandbox image. +A runtime route change does not rebuild that image. +Recreate the sandbox to apply explicit limits to the new route. +When the selected model differs from the inherited image model, NemoClaw removes inherited `contextWindow` and `maxTokens` values during that build if no valid explicit overrides exist. OpenClaw and the selected model then determine the effective limits. Export one or both values before onboarding. diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index c7a3cba7ea8..db3692f68ae 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -135,4 +135,39 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { fs.rmSync(root, { recursive: true, force: true }); } }); + + it("does not invent a final image user when the Dockerfile declares no USER", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-model-user-patch-")); + try { + const dockerfilePath = path.join(root, "Dockerfile"); + fs.writeFileSync( + dockerfilePath, + [ + "FROM example.invalid/openclaw@sha256:" + "1".repeat(64), + "ARG NEMOCLAW_TOOL_DISCLOSURE=progressive", + ].join("\n"), + ); + + patchStagedDockerfile( + dockerfilePath, + "provider/selected-model", + "http://127.0.0.1:18789", + "build-1", + null, + null, + null, + null, + false, + null, + [], + { agentName: "openclaw", reconcileCustomOpenClawModel: true }, + ); + + const patched = fs.readFileSync(dockerfilePath, "utf-8"); + expect(patched.match(/^USER(?:\s|$).*$/gimu)).toBeNull(); + expect(patched.trimEnd().endsWith("fi")).toBe(true); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index f90ef64d8af..e8d8d46ee4d 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -211,7 +211,8 @@ function appendCustomOpenClawModelReconcile( (last, instruction) => (/^USER(?:\s|$)/i.test(instruction.text) ? instruction : last), null, ); - const restoreUser = finalUser?.text ?? "USER sandbox"; + const useRoot = finalUser === null ? "" : "USER root\n"; + const restoreUser = finalUser === null ? "" : `\n${finalUser.text}`; const encodedModel = Buffer.from(model, "utf8").toString("base64"); const encodedLimits = Buffer.from(JSON.stringify(explicitLimits), "utf8").toString("base64"); @@ -220,8 +221,7 @@ function appendCustomOpenClawModelReconcile( # Reconcile inherited OpenClaw model metadata with this custom image's route. ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} ARG NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64=${encodedLimits} -USER root -RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64="\${NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' +${useRoot}RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64="\${NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' import base64 import json import os @@ -302,8 +302,7 @@ RUN if [ -f /sandbox/.openclaw/openclaw.json ]; then \\ sha256sum openclaw.json > .config-hash; \\ chown --reference=openclaw.json .config-hash; \\ chmod --reference=openclaw.json .config-hash; \\ - fi -${restoreUser} + fi${restoreUser} `; } diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 92f7b0eddbb..f29fdb4657c 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -1002,12 +1002,16 @@ test( ); const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-switch-home-")); - const customImageDockerfile = stageNonRootCustomOpenClawImageDockerfile( - home, - readLiveE2eManagedImageCatalogContracts(liveE2eManagedImageCatalog(process.env)!).get( - "openclaw", - )!.reference, - ); + const customImageRuntime = process.env.NEMOCLAW_CUSTOM_IMAGE_RUNTIME; + const customImageDockerfile = + runtimeProvider.id === customImageRuntime + ? stageNonRootCustomOpenClawImageDockerfile( + home, + readLiveE2eManagedImageCatalogContracts(liveE2eManagedImageCatalog(process.env)!).get( + "openclaw", + )!.reference, + ) + : null; let mockProvider: MockAnthropicProvider | undefined; cleanup.trackDisposable( `remove OpenClaw inference switch test home for ${SANDBOX_NAME}`, @@ -1051,8 +1055,12 @@ test( cwd: REPO_ROOT, env: commandEnv(home, { ...baseline.env, - NEMOCLAW_FROM_DOCKERFILE: customImageDockerfile, - NEMOCLAW_SANDBOX_PREBUILD: "1", + ...(customImageDockerfile === null + ? {} + : { + NEMOCLAW_FROM_DOCKERFILE: customImageDockerfile, + NEMOCLAW_SANDBOX_PREBUILD: "1", + }), NEMOCLAW_RECREATE_SANDBOX: "1", }), redactionValues, @@ -1070,7 +1078,7 @@ test( skip("NVIDIA endpoint validation was unavailable/rate-limited during onboarding"); } expect(install.exitCode, installText).toBe(0); - { + if (customImageDockerfile !== null) { const startupConfigResult = await sandbox.exec( SANDBOX_NAME, ["cat", "/sandbox/.openclaw/openclaw.json"], diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index f2a4c2a6134..b7ddd954bee 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -158,12 +158,12 @@ describe("E2E workflow plan", () => { "ubuntu-repo-cloud-openclaw", ]); expect(plan.testMatrix).toEqual([]); - expect(catalogueIds).toHaveLength(46); + expect(catalogueIds).toHaveLength(47); + expect(catalogueIds).toContain("openclaw-inference-switch"); expect(catalogueIds).not.toEqual( expect.arrayContaining([ "bootstrap-install-smoke", "gpu-e2e", - "openclaw-inference-switch", "rebuild-hermes", "rebuild-openclaw", ]), @@ -751,6 +751,21 @@ describe("E2E workflow plan", () => { ); }); + it("runs provider switching on Docker and Podman with custom-image setup limited to Docker", () => { + const target = catalogueTarget("openclaw-inference-switch"); + const plan = buildE2eWorkflowPlan( + { targets: "openclaw-inference-switch" }, + { gatewayRuntimes: ["docker", "podman"] }, + ); + + expect(target.gatewayRuntimes).toEqual(["docker", "podman"]); + expect(target.environment.NEMOCLAW_CUSTOM_IMAGE_RUNTIME).toBe("docker"); + expect(plan.catalogueMatrices.standard.map((row) => [row.id, row.runtime_provider])).toEqual([ + ["openclaw-inference-switch", "docker"], + ["openclaw-inference-switch", "podman"], + ]); + }); + it.each([ "src/lib/adapters/openshell/command-execution.ts", "src/lib/adapters/openshell/forward-cli.ts", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index f84a8156861..a38984a2515 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1138,7 +1138,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ OPENSHELL_GATEWAY: "nemoclaw", }, }), - dockerOnlyTarget("openclaw-inference-switch", { + managedRuntimeTarget("openclaw-inference-switch", { displayName: "Inference: OpenClaw switches providers and remains responsive", agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; compatible inference fixtures", @@ -1165,6 +1165,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_CUSTOM_IMAGE_RUNTIME: "docker", OPENSHELL_GATEWAY: "nemoclaw", }, }), From 03fd2cb36dbbca38df8c9c63cd0d9e48f6684ad2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 25 Sep 2026 14:06:39 -0700 Subject: [PATCH 18/34] test(e2e): restore Podman switch boundary Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/inference-switch-workflow-boundary.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index da82a7566cb..702ced1e871 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -18,9 +18,10 @@ describe("inference-switch catalogue boundary", () => { expect(openclaw).toMatchObject({ profile: "standard", testFile: "test/e2e/live/openclaw-inference-switch.test.ts", - gatewayRuntimes: ["docker"], + gatewayRuntimes: ["docker", "podman"], environment: { NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_CUSTOM_IMAGE_RUNTIME: "docker", NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", }, }); From 0c30034310adf05d26218455a5c186f8d9be77d9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 07:05:47 -0700 Subject: [PATCH 19/34] fix(openclaw): repair stale config hash on retry Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 10 +++ .../runtime/nemoclaw-start-reconcile.test.ts | 65 +++++++++++++++---- 2 files changed, 63 insertions(+), 12 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index c1a1bf02621..b95e064f7f9 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1264,6 +1264,7 @@ if gateway_target is not None: first_name_ok = isinstance(first_name, str) and first_name == gateway_target first_id_ok = isinstance(first_id, str) and (first_id == bare or first_id == gateway_target) if primary_ok and first_name_ok and first_id_ok: + print("already-synced") sys.exit(0) print(f"{os.environ.get('MODEL_SOURCE', 'gateway')}\t{gateway_target}") sys.exit(0) @@ -1278,11 +1279,20 @@ legacy_target = qualify(first.get("name") or first.get("id")) if legacy_target is None: sys.exit(0) if isinstance(primary, str) and primary == legacy_target: + print("already-synced") sys.exit(0) print(f"legacy\t{legacy_target}") PYRECONCILE_READ )" + if [ "$provider_model_ref" = "already-synced" ]; then + # A prior attempt may have installed this config before its hash refresh + # failed. Keep the retry fail-closed until both files agree. + local _hash_rc=0 + ensure_mutable_openclaw_config_hash || _hash_rc=$? + return "$_hash_rc" + fi + if [ -z "$provider_model_ref" ]; then return 0 fi diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 97721ace385..7617c856a2a 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; @@ -35,7 +36,7 @@ interface RunReconcileOptions { useActualUser?: boolean; symlink?: "config" | "hash"; configWritable?: boolean; - hashFailure?: boolean; + hashFailure?: boolean | "once"; env?: Record; } @@ -101,14 +102,25 @@ describe("agent identity reconciliation with provider (#3175)", () => { fs.writeFileSync(path.join(binDir, "openshell"), stub, { mode: 0o755 }); } + const hashHelper = + options.hashFailure === true + ? "ensure_mutable_openclaw_config_hash() { return 19; }" + : options.hashFailure === "once" + ? [ + "_hash_refresh_attempt=0", + "ensure_mutable_openclaw_config_hash() {", + " _hash_refresh_attempt=$((_hash_refresh_attempt + 1))", + ' [ "$_hash_refresh_attempt" -gt 1 ] || return 19', + ` (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash)`, + "}", + ].join("\n") + : `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`; const helperFns = [ "normalize_mutable_config_perms() { :; }", options.useActualUser ? extractShellFunction("run_openclaw_config_as_owner") : 'run_openclaw_config_as_owner() { "$@"; }', - options.hashFailure - ? "ensure_mutable_openclaw_config_hash() { return 19; }" - : `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, + hashHelper, ].join("\n"); const fn = extractShellFunction("reconcile_agent_model_with_provider").replaceAll( "/sandbox", @@ -120,6 +132,13 @@ describe("agent identity reconciliation with provider (#3175)", () => { ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), helperFns, fn, + ...(options.hashFailure === "once" + ? [ + "_first_reconcile_rc=0", + "reconcile_agent_model_with_provider || _first_reconcile_rc=$?", + '[ "$_first_reconcile_rc" -eq 19 ] || exit 91', + ] + : []), "reconcile_agent_model_with_provider", ].join("\n"); const script = path.join(root, "run.sh"); @@ -145,10 +164,12 @@ describe("agent identity reconciliation with provider (#3175)", () => { encoding: "utf-8", env: { ...process.env, ...options.env, PATH: pathValue }, }); - const config = JSON.parse(fs.readFileSync(configPath, "utf-8")); + const configRaw = fs.readFileSync(configPath, "utf-8"); + const config = JSON.parse(configRaw); const hash = fs.readFileSync(hashPath, "utf-8"); + const expectedHash = `${createHash("sha256").update(configRaw).digest("hex")} openclaw.json\n`; fs.rmSync(root, { recursive: true, force: true }); - return { result, config, hash }; + return { result, config, hash, expectedHash }; } it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { @@ -171,7 +192,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { }); it("is a no-op when primary already matches the provider's model", () => { - const { result, config, hash } = runReconcile({ + const { result, config, hash, expectedHash } = runReconcile({ agents: { defaults: { model: { primary: "inference/nvidia/same-model" } }, }, @@ -187,7 +208,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(result.status).toBe(0); expect(config.agents.defaults.model.primary).toBe("inference/nvidia/same-model"); - expect(hash).toBe("oldhash\n"); + expect(hash).toBe(expectedHash); }); it("falls back to an inference-qualified model ref when provider metadata lacks name", () => { @@ -322,11 +343,11 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, }, }; - const { result, config, hash } = runReconcile(switched); + const { result, config, hash, expectedHash } = runReconcile(switched); expect(result.status, result.stderr || result.stdout).toBe(0); expect(config).toEqual(switched); - expect(hash).toBe("oldhash\n"); + expect(hash).toBe(expectedHash); }); it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( @@ -420,7 +441,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { }); it("is a no-op when the live gateway model matches both file fields", () => { - const { result, config, hash } = runReconcile( + const { result, config, hash, expectedHash } = runReconcile( { agents: { defaults: { model: { primary: "inference/nvidia/synced" } } }, models: { @@ -448,7 +469,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { contextWindow: 131072, maxTokens: 4096, }); - expect(hash).toBe("oldhash\n"); + expect(hash).toBe(expectedHash); }); it("preserves explicit limits when only the primary model reference is stale", () => { @@ -766,4 +787,24 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(config.agents.defaults.model.primary).toBe("inference/gateway-model"); expect(hash).toBe("oldhash\n"); }); + + it("repairs the stale hash when reconciliation retries after a hash refresh failure", () => { + const { result, config, hash, expectedHash } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "file-model", name: "inference/file-model" }], + }, + }, + }, + }, + { gatewayModel: "gateway-model", hashFailure: "once" }, + ); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/gateway-model"); + expect(hash).toBe(expectedHash); + }); }); From 2cb8947d7d98431d72afa5e55fa4b6bae4c55bcb Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:14:29 -0700 Subject: [PATCH 20/34] fix(openclaw): scope startup route probe Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 2 +- test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index b95e064f7f9..c1ed7134925 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1167,7 +1167,7 @@ ansi_escape = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|[@-_])") try: result = subprocess.run( - ["openshell", "inference", "get"], + ["openshell", "inference", "get", "-g", "nemoclaw"], capture_output=True, encoding="utf-8", errors="replace", diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 7617c856a2a..04198c71edc 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -18,7 +18,7 @@ const START_SCRIPT = path.join( interface RunReconcileOptions { /** - * Model the stubbed `openshell inference get` should print. + * Model the stubbed `openshell inference get -g nemoclaw` should print. * - undefined → no openshell on PATH (probe falls back to in-file logic). * - "" → openshell exists but returns an unconfigured inference section. * - non-empty string → openshell returns a configured inference section. @@ -91,7 +91,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { const stub = [ "#!/usr/bin/env bash", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - ' [ "$#" -eq 2 ] || exit 64', + ' [ "$#" -eq 4 ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ] || exit 64', options.gatewayDelaySeconds ? ` sleep ${options.gatewayDelaySeconds}` : " :", ` printf '%b' ${JSON.stringify(payload)}`, ` exit ${options.gatewayExitCode ?? 0}`, From fa410c4216b8d621f6c04485f970dd91bb7e2478 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 09:05:10 -0700 Subject: [PATCH 21/34] fix(openclaw): preserve selected gateway probe Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 7 +++- src/lib/onboard/docker-startup-command-env.ts | 7 ++++ src/lib/onboard/sandbox-create-launch.test.ts | 27 +++++++++++++++ src/lib/onboard/sandbox-create-launch.ts | 2 ++ .../onboard/sandbox-create/orchestration.ts | 1 + .../runtime/nemoclaw-start-reconcile.test.ts | 33 +++++++++++++++++-- 6 files changed, 73 insertions(+), 4 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index c1ed7134925..a1d56b47762 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1159,15 +1159,20 @@ reconcile_agent_model_with_provider() { if command -v openshell >/dev/null 2>&1; then gateway_model="$( /usr/bin/python3 -I - <<'PYPROBE' +import os import re import subprocess import sys ansi_escape = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|[@-_])") +gateway_name = os.environ.get("NEMOCLAW_OPENSHELL_GATEWAY_NAME", "nemoclaw") +if not re.fullmatch(r"nemoclaw(?:-[1-9][0-9]{0,4})?", gateway_name): + print("[config] Gateway model probe unavailable: invalid NemoClaw gateway name", file=sys.stderr) + raise SystemExit(0) try: result = subprocess.run( - ["openshell", "inference", "get", "-g", "nemoclaw"], + ["openshell", "inference", "get", "-g", gateway_name], capture_output=True, encoding="utf-8", errors="replace", diff --git a/src/lib/onboard/docker-startup-command-env.ts b/src/lib/onboard/docker-startup-command-env.ts index 1637117e645..c80a5c92b5c 100644 --- a/src/lib/onboard/docker-startup-command-env.ts +++ b/src/lib/onboard/docker-startup-command-env.ts @@ -25,6 +25,7 @@ const OPENCLAW_AUTO_PAIR_RUNTIME_ENV_KEYS = [ ] as const; const OPENCLAW_DIAGNOSTIC_RUNTIME_ENV_KEYS = ["NEMOCLAW_MCP_SHADOW_DIAGNOSTICS"] as const; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_ENV = "NEMOCLAW_MCP_TOOLS_LIST_TIMEOUT_MS"; +const OPENCLAW_INFERENCE_GATEWAY_NAME_ENV = "NEMOCLAW_OPENSHELL_GATEWAY_NAME"; const OPENCLAW_GATEWAY_URL_ENV = "OPENCLAW_GATEWAY_URL"; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_MIN_MS = 1500; const OPENCLAW_MCP_TOOLS_LIST_TIMEOUT_MAX_MS = 10_000; @@ -100,6 +101,7 @@ export interface SandboxRuntimeEnvArgsInput { allowHermesApiPortOverride?: boolean; observabilityEnabled?: boolean; sandboxName?: string; + openshellGatewayName?: string; env: NodeJS.ProcessEnv; omitCredentialEnv?: boolean; } @@ -125,6 +127,11 @@ export function buildSandboxRuntimeEnvArgs(input: SandboxRuntimeEnvArgsInput): { appendOpenClawAutoPairRuntimeEnvArgs(envArgs, agent, env); appendOpenClawDiagnosticRuntimeEnvArgs(envArgs, agent, env); appendOpenClawMcpToolsListTimeoutRuntimeEnvArg(envArgs, agent, env); + if ((!agent || agent.name === "openclaw") && input.openshellGatewayName) { + envArgs.push( + formatEnvAssignment(OPENCLAW_INFERENCE_GATEWAY_NAME_ENV, input.openshellGatewayName), + ); + } appendHermesDashboardEnvArgs(envArgs, input.hermesDashboardState, formatEnvAssignment); if (agent?.name === "hermes" && input.sandboxName) { const apiPort = diff --git a/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index 0939938f30b..76c0f6b017a 100644 --- a/src/lib/onboard/sandbox-create-launch.test.ts +++ b/src/lib/onboard/sandbox-create-launch.test.ts @@ -110,6 +110,33 @@ describe("buildSandboxRuntimeEnvArgs", () => { expect(envArgs).toContain("NEMOCLAW_HERMES_API_PORT=8647"); }); + it("injects the selected OpenShell gateway name only for OpenClaw", () => { + const base = { + chatUiUrl: "", + manageDashboard: false, + getDashboardForwardPort: () => "0", + hermesDashboardState: disabledHermesDashboardState, + extraPlaceholderKeys: [], + env: {} as NodeJS.ProcessEnv, + openshellGatewayName: "nemoclaw-18081", + }; + + const openclaw = buildSandboxRuntimeEnvArgs({ + ...base, + agent: { name: "openclaw", configPaths: { dir: "/sandbox/.openclaw" } } as any, + }).envArgs; + const hermes = buildSandboxRuntimeEnvArgs({ + ...base, + agent: { name: "hermes", configPaths: { dir: "/sandbox/.hermes" } } as any, + hermesApiPort: 8642, + }).envArgs; + + expect(openclaw).toContain("NEMOCLAW_OPENSHELL_GATEWAY_NAME=nemoclaw-18081"); + expect(hermes.some((entry) => entry.startsWith("NEMOCLAW_OPENSHELL_GATEWAY_NAME="))).toBe( + false, + ); + }); + it("omits NEMOCLAW_SANDBOX_NAME when no sandbox name is known", () => { const envArgs = buildSandboxRuntimeEnvArgs({ agent: { name: "openclaw", configPaths: { dir: "/sandbox/.openclaw" } } as any, diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index a336bb51102..fbc61c74179 100644 --- a/src/lib/onboard/sandbox-create-launch.ts +++ b/src/lib/onboard/sandbox-create-launch.ts @@ -42,6 +42,7 @@ export interface SandboxCreateLaunchInput { hermesDashboardState: HermesDashboardOnboardState; /** Reserved host port for this Hermes sandbox's OpenAI-compatible API. */ hermesApiPort?: number | null; + openshellGatewayName?: string; manageDashboard?: boolean; openshellShellCommand: OpenshellShellCommand; openshellArgv?: OpenshellArgv; @@ -123,6 +124,7 @@ export function prepareSandboxRuntimeLaunch( extraPlaceholderKeys: input.extraPlaceholderKeys, observabilityEnabled: input.observabilityEnabled, sandboxName: input.sandboxName, + openshellGatewayName: input.openshellGatewayName, allowHermesApiPortOverride: true, env, }); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 45f8002e4f6..92ceb5b18a9 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -2628,6 +2628,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche observabilityEnabled: createIntent?.observabilityEnabled === true, chatUiUrl, sandboxName, + openshellGatewayName: GATEWAY_NAME, env: process.env, extraPlaceholderKeys: resolvedCreateIntent.extraPlaceholderKeys, getDashboardForwardPort, diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 04198c71edc..075a26871a3 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -18,7 +18,7 @@ const START_SCRIPT = path.join( interface RunReconcileOptions { /** - * Model the stubbed `openshell inference get -g nemoclaw` should print. + * Model the stubbed `openshell inference get -g ` should print. * - undefined → no openshell on PATH (probe falls back to in-file logic). * - "" → openshell exists but returns an unconfigured inference section. * - non-empty string → openshell returns a configured inference section. @@ -32,6 +32,7 @@ interface RunReconcileOptions { gatewayRawOutput?: string; gatewayExitCode?: number; gatewayDelaySeconds?: number; + gatewayName?: string; userId?: number; useActualUser?: boolean; symlink?: "config" | "hash"; @@ -82,6 +83,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { const installStub = options.gatewayRawOutput !== undefined || options.gatewayModel !== undefined; if (installStub) { + const gatewayName = options.gatewayName ?? "nemoclaw"; const payload = options.gatewayRawOutput !== undefined ? options.gatewayRawOutput @@ -91,7 +93,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { const stub = [ "#!/usr/bin/env bash", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - ' [ "$#" -eq 4 ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ] || exit 64', + ` [ "$#" -eq 4 ] && [ "$3" = "-g" ] && [ "$4" = ${JSON.stringify(gatewayName)} ] || exit 64`, options.gatewayDelaySeconds ? ` sleep ${options.gatewayDelaySeconds}` : " :", ` printf '%b' ${JSON.stringify(payload)}`, ` exit ${options.gatewayExitCode ?? 0}`, @@ -162,7 +164,12 @@ describe("agent identity reconciliation with provider (#3175)", () => { const pathValue = installStub ? `${binDir}${path.delimiter}${scrubbedPath}` : scrubbedPath; const result = spawnSync("bash", [script], { encoding: "utf-8", - env: { ...process.env, ...options.env, PATH: pathValue }, + env: { + ...process.env, + ...(options.gatewayName ? { NEMOCLAW_OPENSHELL_GATEWAY_NAME: options.gatewayName } : {}), + ...options.env, + PATH: pathValue, + }, }); const configRaw = fs.readFileSync(configPath, "utf-8"); const config = JSON.parse(configRaw); @@ -415,6 +422,26 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).toContain("openclaw.json"); }); + it("queries the selected nondefault OpenShell gateway", () => { + const { result, config } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: [{ id: "old-model", name: "inference/old-model" }], + }, + }, + }, + }, + { gatewayModel: "new-model", gatewayName: "nemoclaw-18081" }, + ); + + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/new-model"); + }); + it("accepts an inference-qualified gateway model without double-prefixing", () => { const { result, config } = runReconcile( { From 790ccb500d611f264c8d824fc5d74c2fe3a788ac Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 10:36:21 -0700 Subject: [PATCH 22/34] docs(openclaw): clarify custom image limits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/configure-model-limits.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/inference/configure-model-limits.mdx b/docs/inference/configure-model-limits.mdx index d9d1a1ddefe..25b3aca07af 100644 --- a/docs/inference/configure-model-limits.mdx +++ b/docs/inference/configure-model-limits.mdx @@ -76,7 +76,8 @@ export NEMOCLAW_MAX_TOKENS=8192 $$nemoclaw onboard ``` -NemoClaw ignores invalid values and uses the default instead. +NemoClaw does not apply invalid values. +For a custom image whose selected model changes, NemoClaw removes inherited limits instead of applying the managed-image defaults. From 2104192c4684188fcdef6462e68920c3b2927c5b Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 11:35:16 -0700 Subject: [PATCH 23/34] test(e2e): select inference switch owner Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/workflow-plan.test.ts | 1 + tools/e2e/target-catalogue.mts | 1 + 2 files changed, 2 insertions(+) diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 33df9aa1c69..f3b4df420fd 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -754,6 +754,7 @@ describe("E2E workflow plan", () => { "src/lib/onboard/docker-startup-command-env.ts", "src/lib/onboard/dockerfile-patch.ts", "src/lib/onboard/managed-workload/onboard-orchestration.ts", + "src/lib/onboard/sandbox-create/orchestration.ts", "src/lib/onboard/sandbox-create-launch.ts", "src/lib/onboard/sandbox-dockerfile-patch-flow.ts", ])("selects the Docker custom-image proof when %s changes", (changedFile) => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index a47e0e655eb..42f85afd183 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1152,6 +1152,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ "src/lib/onboard/docker-startup-command-env.ts", "src/lib/onboard/dockerfile-patch.ts", "src/lib/onboard/managed-workload/onboard-orchestration.ts", + "src/lib/onboard/sandbox-create/orchestration.ts", "src/lib/onboard/sandbox-create-launch.ts", "src/lib/onboard/sandbox-dockerfile-patch-flow.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", From 4b2e9ec377440ab7def5d582b1b9ea8cdd74ed19 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 12:20:59 -0700 Subject: [PATCH 24/34] docs(openclaw): clarify mixed custom image limits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/configure-model-limits.mdx | 2 +- ...kerfile-custom-openclaw-model-reconcile.test.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/inference/configure-model-limits.mdx b/docs/inference/configure-model-limits.mdx index 25b3aca07af..671c713e61d 100644 --- a/docs/inference/configure-model-limits.mdx +++ b/docs/inference/configure-model-limits.mdx @@ -77,7 +77,7 @@ $$nemoclaw onboard ``` NemoClaw does not apply invalid values. -For a custom image whose selected model changes, NemoClaw removes inherited limits instead of applying the managed-image defaults. +For a custom image whose selected model differs from the inherited image model, NemoClaw applies each valid explicit limit independently and removes each inherited limit that has no explicit replacement. diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index db3692f68ae..785d9e5d082 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -30,6 +30,20 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { inheritedModelId: "baked-model", expectedLimits: { contextWindow: 65_536, maxTokens: 8_192 }, }, + { + behavior: "replaces only the explicit context window", + contextWindow: "65536", + maxTokens: "", + inheritedModelId: "baked-model", + expectedLimits: { contextWindow: 65_536 }, + }, + { + behavior: "replaces only the explicit maximum output-token count", + contextWindow: "", + maxTokens: "8192", + inheritedModelId: "baked-model", + expectedLimits: { maxTokens: 8_192 }, + }, { behavior: "overrides inherited limits when the model already matches", contextWindow: "65536", From 19897b15c645806f740777fb57cb294e5ac9e194 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:15:12 -0700 Subject: [PATCH 25/34] test(openclaw): exercise non-root model override Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/manage-sandboxes/runtime-controls.mdx | 7 ++- .../runtime/nemoclaw-start-config-io.test.ts | 46 +++++++++++-------- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/docs/manage-sandboxes/runtime-controls.mdx b/docs/manage-sandboxes/runtime-controls.mdx index bdf02fa0b85..a180c6d181e 100644 --- a/docs/manage-sandboxes/runtime-controls.mdx +++ b/docs/manage-sandboxes/runtime-controls.mdx @@ -22,8 +22,8 @@ Some changes apply at runtime, while image and filesystem changes require a rebu | Item | When the change takes effect | How to change it | | --- | --- | --- | -| Inference provider | Runtime route and config update; rebuild only if you need to recreate the image | Run `$$nemoclaw inference set` | -| Inference model on the current provider | Runtime route and config update | Run `$$nemoclaw inference set` | +| Inference provider | Runtime route update; configuration update only when the sandbox user can write `/sandbox/.openclaw/openclaw.json` | Run `$$nemoclaw inference set` | +| Inference model on the current provider | Runtime route update; configuration update only when the sandbox user can write `/sandbox/.openclaw/openclaw.json` | Run `$$nemoclaw inference set` | | Sub-agent | Re-onboard required because the sub-agent and workspace are baked at onboard | `$$nemoclaw onboard --recreate-sandbox` | | Network policy preset | Runtime on the next request; rebuild only if the preset adds bind-mounted secrets | `$$nemoclaw policy add ` or `policy remove ` | | Network allowlist | Runtime on the next request | `openshell policy set` or the interactive approval prompt at the gateway | @@ -40,6 +40,9 @@ Some changes apply at runtime, while image and filesystem changes require a rebu | `agents.list` | Runtime after gateway restart; generated OpenClaw configuration disables hot reload | Prefer agent or NemoClaw commands that keep host and sandbox state aligned, then run `$$nemoclaw gateway restart` | | `openclaw.json` keys | Mixed; supported config and inference updates apply at runtime, while image, policy, web search, and channel changes can require rebuild | Use `$$nemoclaw inference set` or `$$nemoclaw config set` so the config and integrity hash change together | +If NemoClaw skips custom-image configuration synchronization, update the image so the sandbox user owns and can write the OpenClaw configuration, then recreate the sandbox. +Refer to [Switch Models](../../inference/manage-inference/switch-models) for the custom-image route and configuration behavior. + For a new or pristine OpenClaw workspace, `NEMOCLAW_MINIMAL_BOOTSTRAP=1` avoids roughly 3,000 tokens of per-turn project-context overhead by skipping the default template seed. It does not delete existing workspace files. The runtime source of truth is `/sandbox/.openclaw/openclaw.json`. The host registry caches metadata, but the image and OpenClaw read from the in-sandbox file. diff --git a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts index fb44f19fca5..c1fa187c6d8 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts @@ -25,7 +25,10 @@ describe("runtime model override (#759)", () => { return extractShellFunctionFromSource(src, name); } - function runApplyModelOverride(env: Record = {}, userId = 0) { + function runApplyModelOverride( + env: Record = {}, + options: { userId?: number; useActualUser?: boolean } = {}, + ) { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-model-override-")); const openclawDir = path.join(root, ".openclaw"); fs.mkdirSync(openclawDir, { recursive: true }); @@ -65,16 +68,20 @@ describe("runtime model override (#759)", () => { hash: fs.fstatSync(hashFd).mode & 0o777, }; - const helperFns = [extractShellFunction("openclaw_config_dir_owner")] + const helperFns = [ + extractShellFunction("openclaw_config_dir_owner"), + options.useActualUser + ? extractShellFunction("run_openclaw_config_as_owner") + : 'run_openclaw_config_as_owner() { "$@"; }', + ] .join("\n") .replaceAll("/sandbox", root); const fn = extractShellFunction("apply_model_override").replaceAll("/sandbox", root); const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", - `id() { echo ${userId}; }`, + ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), "normalize_mutable_config_perms() { :; }", - 'run_openclaw_config_as_owner() { "$@"; }', `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, `stat() { if [ "$1" = "-c" ] && [ "$2" = "%U" ] && [ "$3" = ${JSON.stringify(openclawDir)} ]; then echo sandbox; return 0; fi; command stat "$@"; }`, helperFns, @@ -137,21 +144,24 @@ describe("runtime model override (#759)", () => { expect(modes).toEqual(initialModes); }); - it("applies an explicit model override as a non-root custom image user (#12033)", () => { - const { result, config, configDigest, hash, initialModes, modes } = runApplyModelOverride( - { NEMOCLAW_MODEL_OVERRIDE: "new-model" }, - 1000, - ); + it.runIf(typeof process.getuid === "function" && process.getuid() !== 0)( + "applies an explicit model override as the current non-root custom image user (#12033)", + () => { + const { result, config, configDigest, hash, initialModes, modes } = runApplyModelOverride( + { NEMOCLAW_MODEL_OVERRIDE: "new-model" }, + { useActualUser: true }, + ); - expect(result.status).toBe(0); - expect(config.agents.defaults.model.primary).toBe("new-model"); - expect(config.models.providers.inference.models[0]).toMatchObject({ - id: "new-model", - name: "new-model", - }); - expect(hash.trim().split(/\s+/)).toEqual([configDigest, "openclaw.json"]); - expect(modes).toEqual(initialModes); - }); + expect(result.status).toBe(0); + expect(config.agents.defaults.model.primary).toBe("new-model"); + expect(config.models.providers.inference.models[0]).toMatchObject({ + id: "new-model", + name: "new-model", + }); + expect(hash.trim().split(/\s+/)).toEqual([configDigest, "openclaw.json"]); + expect(modes).toEqual(initialModes); + }, + ); it.each([ { From 87c3ada566505488e1ea97df6ff61734234ebaae Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 14:36:53 -0700 Subject: [PATCH 26/34] fix(openclaw): preserve custom route on first start Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 102 ++++++++- ...le-custom-openclaw-model-reconcile.test.ts | 107 +++++++++ src/lib/onboard/dockerfile-patch.ts | 28 +++ .../runtime/nemoclaw-start-reconcile.test.ts | 212 +++++++++++++++++- 4 files changed, 443 insertions(+), 6 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index a1d56b47762..bb710069e4d 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1141,11 +1141,16 @@ reconcile_agent_model_with_provider() { local config_file="/sandbox/.openclaw/openclaw.json" local hash_file="/sandbox/.openclaw/.config-hash" + local custom_route_marker="/sandbox/.openclaw/.nemoclaw-custom-route-pending" [ -f "$config_file" ] || return 0 - if [ -L "$config_file" ] || [ -L "$hash_file" ]; then - printf '[SECURITY] Refusing agent model reconciliation: config or hash path is a symlink\n' >&2 + if [ -L "$config_file" ] || [ -L "$hash_file" ] || [ -L "$custom_route_marker" ]; then + printf '[SECURITY] Refusing agent model reconciliation: config, hash, or receipt path is a symlink\n' >&2 + return 1 + fi + if [ -e "$custom_route_marker" ] && [ ! -f "$custom_route_marker" ]; then + printf '[SECURITY] Refusing agent model reconciliation: custom-image route receipt is not a regular file\n' >&2 return 1 fi @@ -1156,7 +1161,71 @@ reconcile_agent_model_with_provider() { local gateway_model="" local model_source="gateway" - if command -v openshell >/dev/null 2>&1; then + if [ -f "$custom_route_marker" ]; then + if ! run_openclaw_config_as_owner /usr/bin/python3 -I - \ + "$config_file" "$custom_route_marker" <<'PYCUSTOMROUTE'; then +import hashlib +import os +import re +import stat +import sys + +config_path, marker_path = sys.argv[1:] +flags = os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) + + +def open_regular(path): + descriptor = os.open(path, flags) + metadata = os.fstat(descriptor) + current = os.stat(path, follow_symlinks=False) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or (metadata.st_dev, metadata.st_ino) != (current.st_dev, current.st_ino) + ): + os.close(descriptor) + raise OSError("path is not a trusted regular file") + return descriptor + + +def read_bounded(descriptor, limit): + chunks = [] + remaining = limit + 1 + while remaining > 0: + chunk = os.read(descriptor, remaining) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) + + +try: + config_fd = open_regular(config_path) + marker_fd = open_regular(marker_path) + try: + config = read_bounded(config_fd, 8 * 1024 * 1024) + marker = read_bounded(marker_fd, 255) + finally: + os.close(marker_fd) + os.close(config_fd) +except OSError: + raise SystemExit(1) + +if len(config) > 8 * 1024 * 1024 or len(marker) > 255: + raise SystemExit(1) +match = re.fullmatch(rb"([a-f0-9]{64}) openclaw\.json\n", marker) +if match is None or hashlib.sha256(config).hexdigest().encode("ascii") != match.group(1): + raise SystemExit(1) +PYCUSTOMROUTE + printf '[SECURITY] Refusing invalid custom-image route receipt\n' >&2 + return 1 + fi + # The staged Dockerfile already reconciled the selected route into this + # exact config. Keep that create-time choice authoritative for the first + # launch; the marker is retired only after the gateway reports readiness. + model_source="custom-image" + elif command -v openshell >/dev/null 2>&1; then gateway_model="$( /usr/bin/python3 -I - <<'PYPROBE' import os @@ -1357,6 +1426,31 @@ PYRECONCILE_WRITE [ "$_write_rc" -eq 0 ] || return "$_write_rc" } +retire_custom_route_reconcile_marker() { + local marker="/sandbox/.openclaw/.nemoclaw-custom-route-pending" + [ -e "$marker" ] || [ -L "$marker" ] || return 0 + if [ -L "$marker" ] || [ ! -f "$marker" ]; then + printf '[SECURITY] Refusing unsafe custom-image route receipt retirement\n' >&2 + return 1 + fi + run_openclaw_config_as_owner /bin/rm -f -- "$marker" +} + +settle_custom_route_reconcile_marker() { + local pid="$1" + local expected_identity="$2" + local marker="/sandbox/.openclaw/.nemoclaw-custom-route-pending" + [ -e "$marker" ] || [ -L "$marker" ] || return 0 + if ! wait_for_openclaw_gateway_internal "$pid" "$expected_identity"; then + printf '[config] Custom-image route receipt retained because the first gateway launch did not become ready\n' >&2 + return 0 + fi + if ! retire_custom_route_reconcile_marker; then + printf '[SECURITY] Custom-image route receipt could not be retired after gateway readiness\n' >&2 + fi + return 0 +} + # ── Runtime CORS origin override ────────────────────────────────── # Adds a browser origin to gateway.controlUi.allowedOrigins at startup # without rebuilding the sandbox image. Useful for custom domains/ports. @@ -5140,6 +5234,7 @@ launch_openclaw_gateway() { exit 1 fi record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" + settle_custom_route_reconcile_marker "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh SANDBOX_WAIT_PID="$GATEWAY_PID" echo "[gateway] openclaw gateway launched as native 'sandbox' agent user (pid $GATEWAY_PID)" >&2 @@ -5152,6 +5247,7 @@ launch_openclaw_gateway_non_root() { "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" || return 1 capture_openclaw_pid_start_identity "$GATEWAY_PID" GATEWAY_PID_START_IDENTITY || exit 1 record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" + settle_custom_route_reconcile_marker "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" _nemoclaw_capture_epoch_realtime _NEMOCLAW_GATEWAY_SPAWN_FINISHED_EPOCH record_portable_openclaw_gateway_startup_timing echo "[gateway] openclaw gateway launched (pid $GATEWAY_PID)" >&2 diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index 785d9e5d082..28d8d87a951 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -15,6 +16,56 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { vi.unstubAllEnvs(); }); + function customRouteProgram(root: string): { configPath: string; program: string } { + const dockerfilePath = path.join(root, "Dockerfile"); + fs.writeFileSync( + dockerfilePath, + [ + "FROM example.invalid/openclaw@sha256:" + "1".repeat(64), + "ARG NEMOCLAW_TOOL_DISCLOSURE=progressive", + ].join("\n"), + ); + patchStagedDockerfile( + dockerfilePath, + "provider/selected-model", + "http://127.0.0.1:18789", + "build-1", + null, + null, + null, + null, + false, + null, + [], + { agentName: "openclaw", reconcileCustomOpenClawModel: true }, + ); + const embedded = fs + .readFileSync(dockerfilePath, "utf8") + .match(/<<'PYNEMOCLAWCUSTOMROUTE'\n([\s\S]*?)\nPYNEMOCLAWCUSTOMROUTE/u)?.[1]; + expect(embedded).toBeDefined(); + const configPath = path.join(root, "openclaw.json"); + fs.writeFileSync( + configPath, + JSON.stringify({ + agents: { defaults: { model: { primary: "inference/baked-model" } } }, + models: { + providers: { + inference: { + models: [{ id: "baked-model", name: "inference/baked-model" }], + }, + }, + }, + }), + ); + return { + configPath, + program: embedded!.replace( + 'config_path = "/sandbox/.openclaw/openclaw.json"', + `config_path = ${JSON.stringify(configPath)}`, + ), + }; + } + it.each([ { behavior: "drops inherited limits", @@ -88,6 +139,7 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { expect(encodedModel).not.toBe(""); expect(encodedLimits).not.toBe(""); expect(patched).toContain("sha256sum openclaw.json > .config-hash"); + expect(patched).toContain(".nemoclaw-custom-route-pending"); expect(patched.trimEnd().endsWith("USER 1001:1001")).toBe(true); const embedded = patched.match( @@ -145,6 +197,10 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { }, }, }); + const configBytes = fs.readFileSync(configPath); + expect(fs.readFileSync(path.join(root, ".nemoclaw-custom-route-pending"), "utf8")).toBe( + `${createHash("sha256").update(configBytes).digest("hex")} openclaw.json\n`, + ); } finally { fs.rmSync(root, { recursive: true, force: true }); } @@ -184,4 +240,55 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { fs.rmSync(root, { recursive: true, force: true }); } }); + + it("atomically replaces a pre-existing custom-route receipt symlink", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-model-marker-link-")); + try { + const { program } = customRouteProgram(root); + const targetPath = path.join(root, "receipt-target"); + const markerPath = path.join(root, ".nemoclaw-custom-route-pending"); + fs.writeFileSync(targetPath, "unchanged\n"); + fs.symlinkSync(targetPath, markerPath); + + const result = spawnSync("/usr/bin/python3", ["-I", "-c", program], { + encoding: "utf-8", + env: { + ...process.env, + NEMOCLAW_CUSTOM_ROUTE_MODEL_B64: + Buffer.from("provider/selected-model").toString("base64"), + NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64: Buffer.from("{}").toString("base64"), + }, + }); + + expect(result.status, result.stderr).toBe(0); + expect(fs.lstatSync(markerPath).isFile()).toBe(true); + expect(fs.readFileSync(targetPath, "utf8")).toBe("unchanged\n"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("fails closed for a pre-existing custom-route receipt directory", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-model-marker-dir-")); + try { + const { program } = customRouteProgram(root); + const markerPath = path.join(root, ".nemoclaw-custom-route-pending"); + fs.mkdirSync(markerPath); + + const result = spawnSync("/usr/bin/python3", ["-I", "-c", program], { + encoding: "utf-8", + env: { + ...process.env, + NEMOCLAW_CUSTOM_ROUTE_MODEL_B64: + Buffer.from("provider/selected-model").toString("base64"), + NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64: Buffer.from("{}").toString("base64"), + }, + }); + + expect(result.status).not.toBe(0); + expect(fs.lstatSync(markerPath).isDirectory()).toBe(true); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index e8d8d46ee4d..fe07ac1c6f5 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -223,12 +223,14 @@ ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} ARG NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64=${encodedLimits} ${useRoot}RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64="\${NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' import base64 +import hashlib import json import os import re import stat config_path = "/sandbox/.openclaw/openclaw.json" +marker_path = os.path.join(os.path.dirname(config_path), ".nemoclaw-custom-route-pending") if os.path.exists(config_path): model = base64.b64decode( os.environ["NEMOCLAW_CUSTOM_ROUTE_MODEL_B64"], validate=True @@ -293,6 +295,30 @@ if os.path.exists(config_path): config_file.truncate() config_file.flush() os.fsync(config_fd) + config_file.seek(0) + config_digest = hashlib.sha256(config_file.read().encode("utf-8")).hexdigest() + try: + os.unlink(marker_path) + except FileNotFoundError: + pass + marker_flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) + marker_fd = os.open(marker_path, marker_flags, stat.S_IMODE(metadata.st_mode)) + try: + marker_metadata = os.fstat(marker_fd) + marker_current = os.stat(marker_path, follow_symlinks=False) + if ( + not stat.S_ISREG(marker_metadata.st_mode) + or (marker_metadata.st_dev, marker_metadata.st_ino) + != (marker_current.st_dev, marker_current.st_ino) + or marker_metadata.st_nlink != 1 + ): + raise OSError("custom route receipt is not a trusted regular file") + with os.fdopen(marker_fd, "w", encoding="ascii", closefd=False) as marker_file: + marker_file.write(f"{config_digest} openclaw.json\\n") + marker_file.flush() + os.fsync(marker_fd) + finally: + os.close(marker_fd) finally: os.close(config_fd) PYNEMOCLAWCUSTOMROUTE @@ -301,7 +327,9 @@ RUN if [ -f /sandbox/.openclaw/openclaw.json ]; then \\ rm -f -- .config-hash; \\ sha256sum openclaw.json > .config-hash; \\ chown --reference=openclaw.json .config-hash; \\ + chown --reference=openclaw.json .nemoclaw-custom-route-pending; \\ chmod --reference=openclaw.json .config-hash; \\ + chmod --reference=openclaw.json .nemoclaw-custom-route-pending; \\ fi${restoreUser} `; } diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 075a26871a3..90f5af2bb88 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -35,9 +35,11 @@ interface RunReconcileOptions { gatewayName?: string; userId?: number; useActualUser?: boolean; - symlink?: "config" | "hash"; + symlink?: "config" | "hash" | "marker"; configWritable?: boolean; hashFailure?: boolean | "once"; + customRoutePending?: boolean | "directory" | "invalid"; + retireCustomRouteBeforeRetry?: boolean; env?: Record; } @@ -60,6 +62,24 @@ describe("agent identity reconciliation with provider (#3175)", () => { const hashPath = path.join(openclawDir, ".config-hash"); fs.writeFileSync(configPath, JSON.stringify(initialConfig)); fs.writeFileSync(hashPath, "oldhash\n"); + const customRouteMarkerPath = path.join(openclawDir, ".nemoclaw-custom-route-pending"); + const prepareCustomRouteMarker = new Map< + boolean | "directory" | "invalid" | undefined, + () => void + >([ + [undefined, () => undefined], + [false, () => undefined], + ["directory", () => fs.mkdirSync(customRouteMarkerPath)], + ["invalid", () => fs.writeFileSync(customRouteMarkerPath, "invalid\n")], + [ + true, + () => { + const digest = createHash("sha256").update(fs.readFileSync(configPath)).digest("hex"); + fs.writeFileSync(customRouteMarkerPath, `${digest} openclaw.json\n`); + }, + ], + ]).get(options.customRoutePending); + prepareCustomRouteMarker!(); fs.chmodSync(openclawDir, 0o2770); fs.chmodSync(configPath, options.configWritable === false ? 0o440 : 0o660); fs.chmodSync(hashPath, 0o660); @@ -74,6 +94,11 @@ describe("agent identity reconciliation with provider (#3175)", () => { fs.renameSync(hashPath, target); fs.symlinkSync(target, hashPath); }, + marker: () => { + const target = path.join(openclawDir, ".nemoclaw-custom-route-pending.real"); + fs.renameSync(customRouteMarkerPath, target); + fs.symlinkSync(target, customRouteMarkerPath); + }, none: () => undefined, }[options.symlink ?? "none"]; prepareSymlink(); @@ -128,12 +153,17 @@ describe("agent identity reconciliation with provider (#3175)", () => { "/sandbox", root, ); + const retireFn = extractShellFunction("retire_custom_route_reconcile_marker").replaceAll( + "/sandbox", + root, + ); const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), helperFns, fn, + retireFn, ...(options.hashFailure === "once" ? [ "_first_reconcile_rc=0", @@ -141,6 +171,9 @@ describe("agent identity reconciliation with provider (#3175)", () => { '[ "$_first_reconcile_rc" -eq 19 ] || exit 91', ] : []), + ...(options.retireCustomRouteBeforeRetry + ? ["reconcile_agent_model_with_provider", "retire_custom_route_reconcile_marker"] + : []), "reconcile_agent_model_with_provider", ].join("\n"); const script = path.join(root, "run.sh"); @@ -174,9 +207,44 @@ describe("agent identity reconciliation with provider (#3175)", () => { const configRaw = fs.readFileSync(configPath, "utf-8"); const config = JSON.parse(configRaw); const hash = fs.readFileSync(hashPath, "utf-8"); + const customRoutePending = fs.existsSync(customRouteMarkerPath); const expectedHash = `${createHash("sha256").update(configRaw).digest("hex")} openclaw.json\n`; fs.rmSync(root, { recursive: true, force: true }); - return { result, config, hash, expectedHash }; + return { result, config, hash, expectedHash, customRoutePending }; + } + + function runCustomRouteSettlement(gatewayReady: boolean) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-route-settlement-")); + const openclawDir = path.join(root, ".openclaw"); + const markerPath = path.join(openclawDir, ".nemoclaw-custom-route-pending"); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.writeFileSync(markerPath, `${"a".repeat(64)} openclaw.json\n`); + const retireFn = extractShellFunction("retire_custom_route_reconcile_marker").replaceAll( + "/sandbox", + root, + ); + const settleFn = extractShellFunction("settle_custom_route_reconcile_marker").replaceAll( + "/sandbox", + root, + ); + const script = path.join(root, "run.sh"); + fs.writeFileSync( + script, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + 'run_openclaw_config_as_owner() { "$@"; }', + `wait_for_openclaw_gateway_internal() { return ${gatewayReady ? 0 : 23}; }`, + retireFn, + settleFn, + 'settle_custom_route_reconcile_marker "123" "pid-identity"', + ].join("\n"), + { mode: 0o700 }, + ); + const result = spawnSync("bash", [script], { encoding: "utf-8" }); + const markerPending = fs.existsSync(markerPath); + fs.rmSync(root, { recursive: true, force: true }); + return { result, markerPending }; } it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { @@ -258,6 +326,144 @@ describe("agent identity reconciliation with provider (#3175)", () => { // ── Gateway-as-source-of-truth path (the #3175 user-reported repro) ── + it("keeps the staged custom-image route authoritative for its first launch (#12033)", () => { + const selected = { + agents: { defaults: { model: { primary: "inference/custom/selected" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: [{ id: "custom/selected", name: "inference/custom/selected" }], + }, + }, + }, + }; + const { result, config, hash, expectedHash, customRoutePending } = runReconcile(selected, { + customRoutePending: true, + gatewayModel: "nvidia/nemotron-3-super-120b-a12b", + }); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(config).toEqual(selected); + expect(hash).toBe(expectedHash); + expect(customRoutePending).toBe(true); + }); + + it("fails closed when the staged custom-image route receipt does not match the config", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/custom/selected" } } }, + models: { + providers: { + inference: { + models: [{ id: "custom/selected", name: "inference/custom/selected" }], + }, + }, + }, + }; + const { result, config, hash, customRoutePending } = runReconcile(initial, { + customRoutePending: "invalid", + gatewayModel: "nvidia/nemotron-3-super-120b-a12b", + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("invalid custom-image route receipt"); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(customRoutePending).toBe(true); + }); + + it("fails closed when the staged custom-image route receipt is a symlink", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/custom/selected" } } }, + models: { + providers: { + inference: { + models: [{ id: "custom/selected", name: "inference/custom/selected" }], + }, + }, + }, + }; + const { result, config, hash, customRoutePending } = runReconcile(initial, { + customRoutePending: true, + gatewayModel: "nvidia/nemotron-3-super-120b-a12b", + symlink: "marker", + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("config, hash, or receipt path is a symlink"); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(customRoutePending).toBe(true); + }); + + it("fails closed when the staged custom-image route receipt is not a regular file", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/custom/selected" } } }, + models: { + providers: { + inference: { + models: [{ id: "custom/selected", name: "inference/custom/selected" }], + }, + }, + }, + }; + const { result, config, hash, customRoutePending } = runReconcile(initial, { + customRoutePending: "directory", + gatewayModel: "nvidia/nemotron-3-super-120b-a12b", + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("custom-image route receipt is not a regular file"); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(customRoutePending).toBe(true); + }); + + it("uses the live gateway after the first custom-image launch retires its receipt", () => { + const { result, config, hash, customRoutePending } = runReconcile( + { + agents: { defaults: { model: { primary: "inference/custom/selected" } } }, + models: { + providers: { + inference: { + models: [{ id: "custom/selected", name: "inference/custom/selected" }], + }, + }, + }, + }, + { + customRoutePending: true, + gatewayModel: "provider/switched", + retireCustomRouteBeforeRetry: true, + }, + ); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(config.agents.defaults.model.primary).toBe("inference/provider/switched"); + expect(config.models.providers.inference.models[0]).toMatchObject({ + id: "provider/switched", + name: "inference/provider/switched", + }); + expect(hash).not.toBe("oldhash\n"); + expect(customRoutePending).toBe(false); + }); + + it.each([ + { gatewayReady: true, markerPending: false }, + { gatewayReady: false, markerPending: true }, + ])( + "retires the custom-image route receipt only after gateway readiness: $gatewayReady", + ({ gatewayReady, markerPending }) => { + const settled = runCustomRouteSettlement(gatewayReady); + + expect(settled.result.status, settled.result.stderr || settled.result.stdout).toBe(0); + expect(settled.markerPending).toBe(markerPending); + expect(settled.result.stderr).toContain( + gatewayReady ? "" : "first gateway launch did not become ready", + ); + }, + ); + it("preserves an explicit model override when the live gateway reports a conflicting model", () => { const initial = { agents: { @@ -792,7 +998,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(result.status).toBe(1); expect(config.agents.defaults.model.primary).toBe("inference/old-model"); expect(hash).toBe("oldhash\n"); - expect(result.stderr).toContain("config or hash path is a symlink"); + expect(result.stderr).toContain("config, hash, or receipt path is a symlink"); }); it("propagates a hash refresh failure after the config write", () => { From e355e705d8e884214eae00227c19c8b80d0ea2f9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 26 Sep 2026 15:22:31 -0700 Subject: [PATCH 27/34] fix(openclaw): fail closed on receipt cleanup Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 6 +++++ .../runtime/nemoclaw-start-reconcile.test.ts | 22 ++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index bb710069e4d..b4b40d58b9e 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1447,6 +1447,12 @@ settle_custom_route_reconcile_marker() { fi if ! retire_custom_route_reconcile_marker; then printf '[SECURITY] Custom-image route receipt could not be retired after gateway readiness\n' >&2 + # A successful launch with the pending receipt still present would keep + # later restarts pinned to the create-time route. Stop the proven child + # and fail this launch so the retained receipt remains a first-launch + # retry contract instead of becoming stale runtime authority. + stop_openclaw_gateway_fail_closed + return 1 fi return 0 } diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 90f5af2bb88..484b5a94ca9 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -213,10 +213,11 @@ describe("agent identity reconciliation with provider (#3175)", () => { return { result, config, hash, expectedHash, customRoutePending }; } - function runCustomRouteSettlement(gatewayReady: boolean) { + function runCustomRouteSettlement(gatewayReady: boolean, retirementFails = false) { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-route-settlement-")); const openclawDir = path.join(root, ".openclaw"); const markerPath = path.join(openclawDir, ".nemoclaw-custom-route-pending"); + const stoppedPath = path.join(root, "gateway-stopped"); fs.mkdirSync(openclawDir, { recursive: true }); fs.writeFileSync(markerPath, `${"a".repeat(64)} openclaw.json\n`); const retireFn = extractShellFunction("retire_custom_route_reconcile_marker").replaceAll( @@ -233,8 +234,11 @@ describe("agent identity reconciliation with provider (#3175)", () => { [ "#!/usr/bin/env bash", "set -euo pipefail", - 'run_openclaw_config_as_owner() { "$@"; }', + retirementFails + ? 'run_openclaw_config_as_owner() { [ "$1" != /bin/rm ] || return 29; "$@"; }' + : 'run_openclaw_config_as_owner() { "$@"; }', `wait_for_openclaw_gateway_internal() { return ${gatewayReady ? 0 : 23}; }`, + `stop_openclaw_gateway_fail_closed() { : >${JSON.stringify(stoppedPath)}; }`, retireFn, settleFn, 'settle_custom_route_reconcile_marker "123" "pid-identity"', @@ -243,8 +247,9 @@ describe("agent identity reconciliation with provider (#3175)", () => { ); const result = spawnSync("bash", [script], { encoding: "utf-8" }); const markerPending = fs.existsSync(markerPath); + const gatewayStopped = fs.existsSync(stoppedPath); fs.rmSync(root, { recursive: true, force: true }); - return { result, markerPending }; + return { result, markerPending, gatewayStopped }; } it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { @@ -464,6 +469,17 @@ describe("agent identity reconciliation with provider (#3175)", () => { }, ); + it("stops the ready gateway and fails when the custom-image route receipt cannot retire", () => { + const settled = runCustomRouteSettlement(true, true); + + expect(settled.result.status).not.toBe(0); + expect(settled.markerPending).toBe(true); + expect(settled.gatewayStopped).toBe(true); + expect(settled.result.stderr).toContain( + "Custom-image route receipt could not be retired after gateway readiness", + ); + }); + it("preserves an explicit model override when the live gateway reports a conflicting model", () => { const initial = { agents: { From 47686a54a0704ec4228cb15bc05bccc0105ac39f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 27 Sep 2026 09:53:45 -0700 Subject: [PATCH 28/34] fix(onboard): finalize custom route receipt by descriptor Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../dockerfile-custom-openclaw-model-reconcile.test.ts | 9 ++++++++- src/lib/onboard/dockerfile-patch.ts | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index 28d8d87a951..c6c0a284525 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -167,6 +167,7 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { }, }), ); + fs.chmodSync(configPath, 0o640); const program = embedded!.replace( 'config_path = "/sandbox/.openclaw/openclaw.json"', `config_path = ${JSON.stringify(configPath)}`, @@ -198,9 +199,15 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { }, }); const configBytes = fs.readFileSync(configPath); - expect(fs.readFileSync(path.join(root, ".nemoclaw-custom-route-pending"), "utf8")).toBe( + const markerPath = path.join(root, ".nemoclaw-custom-route-pending"); + expect(fs.readFileSync(markerPath, "utf8")).toBe( `${createHash("sha256").update(configBytes).digest("hex")} openclaw.json\n`, ); + const configMetadata = fs.statSync(configPath); + const markerMetadata = fs.statSync(markerPath); + expect(markerMetadata.mode & 0o777).toBe(configMetadata.mode & 0o777); + expect(markerMetadata.uid).toBe(configMetadata.uid); + expect(markerMetadata.gid).toBe(configMetadata.gid); } finally { fs.rmSync(root, { recursive: true, force: true }); } diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index fe07ac1c6f5..11eff962382 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -313,6 +313,8 @@ if os.path.exists(config_path): or marker_metadata.st_nlink != 1 ): raise OSError("custom route receipt is not a trusted regular file") + os.fchown(marker_fd, metadata.st_uid, metadata.st_gid) + os.fchmod(marker_fd, stat.S_IMODE(metadata.st_mode)) with os.fdopen(marker_fd, "w", encoding="ascii", closefd=False) as marker_file: marker_file.write(f"{config_digest} openclaw.json\\n") marker_file.flush() @@ -327,9 +329,7 @@ RUN if [ -f /sandbox/.openclaw/openclaw.json ]; then \\ rm -f -- .config-hash; \\ sha256sum openclaw.json > .config-hash; \\ chown --reference=openclaw.json .config-hash; \\ - chown --reference=openclaw.json .nemoclaw-custom-route-pending; \\ chmod --reference=openclaw.json .config-hash; \\ - chmod --reference=openclaw.json .nemoclaw-custom-route-pending; \\ fi${restoreUser} `; } From 8a54f32aafd5bd8fb43b681482b04600e8bb484a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:35:20 -0700 Subject: [PATCH 29/34] fix(onboard): retire custom route receipt after policy verification Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- scripts/nemoclaw-start.sh | 33 ------- src/lib/onboard.ts | 24 +++--- .../created-sandbox-finalization.test.ts | 79 +++++++++++++++++ .../onboard/created-sandbox-finalization.ts | 44 ++++++++++ .../machine/final-flow-phases.runtime.test.ts | 46 ++++++++++ src/lib/onboard/machine/final-flow-phases.ts | 10 +-- .../orchestration-route-receipt.test.ts | 53 ++++++++++++ .../onboard/sandbox-create/orchestration.ts | 33 +++++++ .../runtime/nemoclaw-start-reconcile.test.ts | 85 ++----------------- 9 files changed, 281 insertions(+), 126 deletions(-) create mode 100644 src/lib/onboard/sandbox-create/orchestration-route-receipt.test.ts diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index b4b40d58b9e..0266a7ca147 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -1426,37 +1426,6 @@ PYRECONCILE_WRITE [ "$_write_rc" -eq 0 ] || return "$_write_rc" } -retire_custom_route_reconcile_marker() { - local marker="/sandbox/.openclaw/.nemoclaw-custom-route-pending" - [ -e "$marker" ] || [ -L "$marker" ] || return 0 - if [ -L "$marker" ] || [ ! -f "$marker" ]; then - printf '[SECURITY] Refusing unsafe custom-image route receipt retirement\n' >&2 - return 1 - fi - run_openclaw_config_as_owner /bin/rm -f -- "$marker" -} - -settle_custom_route_reconcile_marker() { - local pid="$1" - local expected_identity="$2" - local marker="/sandbox/.openclaw/.nemoclaw-custom-route-pending" - [ -e "$marker" ] || [ -L "$marker" ] || return 0 - if ! wait_for_openclaw_gateway_internal "$pid" "$expected_identity"; then - printf '[config] Custom-image route receipt retained because the first gateway launch did not become ready\n' >&2 - return 0 - fi - if ! retire_custom_route_reconcile_marker; then - printf '[SECURITY] Custom-image route receipt could not be retired after gateway readiness\n' >&2 - # A successful launch with the pending receipt still present would keep - # later restarts pinned to the create-time route. Stop the proven child - # and fail this launch so the retained receipt remains a first-launch - # retry contract instead of becoming stale runtime authority. - stop_openclaw_gateway_fail_closed - return 1 - fi - return 0 -} - # ── Runtime CORS origin override ────────────────────────────────── # Adds a browser origin to gateway.controlUi.allowedOrigins at startup # without rebuilding the sandbox image. Useful for custom domains/ports. @@ -5240,7 +5209,6 @@ launch_openclaw_gateway() { exit 1 fi record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" - settle_custom_route_reconcile_marker "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh SANDBOX_WAIT_PID="$GATEWAY_PID" echo "[gateway] openclaw gateway launched as native 'sandbox' agent user (pid $GATEWAY_PID)" >&2 @@ -5253,7 +5221,6 @@ launch_openclaw_gateway_non_root() { "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" || return 1 capture_openclaw_pid_start_identity "$GATEWAY_PID" GATEWAY_PID_START_IDENTITY || exit 1 record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" - settle_custom_route_reconcile_marker "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" _nemoclaw_capture_epoch_realtime _NEMOCLAW_GATEWAY_SPAWN_FINISHED_EPOCH record_portable_openclaw_gateway_startup_timing echo "[gateway] openclaw gateway launched (pid $GATEWAY_PID)" >&2 diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index e24c9c6aa57..6daf5fb390d 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -52,7 +52,7 @@ const preparedDcodeRebuild: typeof import("./onboard/prepared-dcode-rebuild") = const sandboxBuildPatchConfig: typeof import("./onboard/sandbox-build-patch-config") = require("./onboard/sandbox-build-patch-config"); const baseImageResolutionFlow: typeof import("./onboard/base-image-resolution-flow") = require("./onboard/base-image-resolution-flow"); const sandboxCreateIntentResolution: typeof import("./onboard/sandbox-create-intent-resolution") = require("./onboard/sandbox-create-intent-resolution"); -const sandboxCreateOrchestration: typeof import("./onboard/sandbox-create/orchestration") = require("./onboard/sandbox-create/orchestration"); +const sandboxCreate: typeof import("./onboard/sandbox-create/orchestration") = require("./onboard/sandbox-create/orchestration"); const managedWorkloadOnboard: typeof import("./onboard/managed-workload/onboard-orchestration") = require("./onboard/managed-workload/onboard-orchestration"); const onboardEntryOptions: typeof import("./onboard/entry-options") = require("./onboard/entry-options"); const onboardSessionBootstrap: typeof import("./onboard/session-bootstrap") = require("./onboard/session-bootstrap"); @@ -117,6 +117,7 @@ const { completeOrdinaryOnboardSandboxCreation, createOnboardCreatedSandboxCompletion, createOnboardCreatedSandboxRegistration, + retireCustomOpenClawRouteReceiptAfterPolicies, }: typeof import("./onboard/created-sandbox-finalization") = require("./onboard/created-sandbox-finalization"); const providerKeyBridge: typeof import("./onboard/provider-key-bridge") = require("./onboard/provider-key-bridge"); const compatibleEndpointGatewayRoute: typeof import("./onboard/inference-providers/compatible-endpoint-gateway-route") = require("./onboard/inference-providers/compatible-endpoint-gateway-route"); @@ -1428,7 +1429,7 @@ const { getSandboxRuntimeRegistryFields, hasSandboxGpuDrift, updateReusedSandbox getInstalledOpenshellVersion, runCaptureOpenshell, }); -const sandboxCreateOrchestrationRuntime = { +const sandboxRuntime = { DASHBOARD_PORT, get GATEWAY_NAME() { return GATEWAY_NAME; @@ -1449,6 +1450,7 @@ const sandboxCreateOrchestrationRuntime = { confirmRecreateForSelectionDrift, createOnboardCreatedSandboxCompletion, createOnboardCreatedSandboxRegistration, + retireCustomOpenClawRouteReceiptAfterPolicies, createSandboxRecreateProtection, dashboardRuntime, dcodeAutoApprovalFlow, @@ -1545,11 +1547,9 @@ const sandboxCreateOrchestrationRuntime = { dockerInfoFormat, runCapture, }; -export type SandboxCreateOrchestrationRuntime = typeof sandboxCreateOrchestrationRuntime; +export type SandboxCreateOrchestrationRuntime = typeof sandboxRuntime; const createSandboxWithBaseImageResolution = - sandboxCreateOrchestration.createSandboxWithBaseImageResolution( - sandboxCreateOrchestrationRuntime, - ); + sandboxCreate.createSandboxWithBaseImageResolution(sandboxRuntime); const { createSandbox, createSandboxWithTemporaryManagedRuntime } = agentOnboard.createHermesApiPortScopedSandboxEntryPoints({ createBaseImageResolutionContext: () => @@ -3077,7 +3077,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { messagingChannelConfigsEqual, getSandboxReuseState, getSandboxRecreateObservation, - getDcodeSelectionDrift: sandboxCreateOrchestrationRuntime.readDcodeSelectionDrift, + getDcodeSelectionDrift: sandboxRuntime.readDcodeSelectionDrift, hasSandboxGpuDrift, getSandboxHermesToolGateways: (name) => registry.getSandbox(name)?.hermesToolGateways, getSandboxRegistryEntry: registry.getSandbox, @@ -3164,9 +3164,9 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { GATEWAY_NAME, gatewayLifecycleAdapter, ); - const finalFlowContext = prepareFinalOnboardFlowContext(coreFlowResult); - let liveFinalFlowContext: InitialOnboardFlowContext = finalFlowContext; - const finalSandboxRegistration = registry.getSandbox(finalFlowContext.sandboxName); + const finalContext = prepareFinalOnboardFlowContext(coreFlowResult); + let liveFinalFlowContext: InitialOnboardFlowContext = finalContext; + const finalSandboxRegistration = registry.getSandbox(finalContext.sandboxName); const finalFlowPhases = createFinalOnboardFlowPhases< InitialOnboardFlowContext, import("./dashboard/contract").DashboardDeliveryChain, @@ -3293,11 +3293,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { }, }); const finalFlowResult = await runFinalOnboardFlowSlice({ - context: finalFlowContext, + context: finalContext, runtime: onboardRuntimeBoundary.getRuntime(), phases: finalFlowPhases, recordRepairEvent, - afterPoliciesReady: () => sandboxCancelRollback.disarm(), + afterPoliciesReady: () => sandboxCreate.retireRoute(sandboxRuntime, finalContext, agent), onContextUpdated: (context) => { liveFinalFlowContext = context; }, diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index b6cb1ba742c..0bf00de72f5 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as restoreWindow from "../actions/sandbox/runtime/openclaw-lifecycle"; +import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import type { SandboxEntry } from "../state/registry"; import type { QualifiedSandboxInferenceRouteReservation } from "../state/registry/route-reservation"; import * as sandboxState from "../state/sandbox"; @@ -18,6 +19,7 @@ import { createOnboardCreatedSandboxCompletion, createOnboardCreatedSandboxRegistration, finalizeCreatedSandbox, + retireCustomOpenClawRouteReceiptAfterPolicies, restoreSelectedOnboardSnapshot, } from "./created-sandbox-finalization"; import { getDcodeSelectionDrift } from "./dcode-selection-drift"; @@ -85,6 +87,83 @@ describe("created sandbox registration authority", () => { }); }); +describe("custom OpenClaw route receipt retirement", () => { + it("retires through the selected sandbox only after both identity checks succeed", async () => { + const order: string[] = []; + const runBuffered = vi.fn( + async (request) => { + order.push("exec"); + expect(request).toEqual({ + sandboxName: "custom-box", + target: { kind: "named", gatewayName: "nemoclaw-18080" }, + command: ["/bin/rm", "-f", "--", "/sandbox/.openclaw/.nemoclaw-custom-route-pending"], + tty: false, + timeoutMilliseconds: 30_000, + timeoutKillSignal: "SIGKILL", + outputLimitBytes: 4_096, + }); + return { + outcome: { kind: "completed", exitCode: 0 }, + stdout: "", + stderr: "", + }; + }, + ); + const revalidateSandboxIdentity = vi.fn((operation: string) => { + order.push(operation.startsWith("retiring") ? "identity-before" : "identity-after"); + }); + + await retireCustomOpenClawRouteReceiptAfterPolicies({ + sandboxName: "custom-box", + gatewayName: "nemoclaw-18080", + customOpenClawImage: true, + sandboxCommandExecutor: { runBuffered }, + revalidateSandboxIdentity, + }); + + expect(order).toEqual(["identity-before", "exec", "identity-after"]); + expect(revalidateSandboxIdentity).toHaveBeenCalledTimes(2); + }); + + it("does nothing for a sandbox without a custom OpenClaw image", async () => { + const runBuffered = vi.fn(); + const revalidateSandboxIdentity = vi.fn(); + + await retireCustomOpenClawRouteReceiptAfterPolicies({ + sandboxName: "managed-box", + gatewayName: "nemoclaw-18080", + customOpenClawImage: false, + sandboxCommandExecutor: { runBuffered }, + revalidateSandboxIdentity, + }); + + expect(runBuffered).not.toHaveBeenCalled(); + expect(revalidateSandboxIdentity).not.toHaveBeenCalled(); + }); + + it("fails closed before the final identity check when retirement fails", async () => { + const revalidateSandboxIdentity = vi.fn(); + + await expect( + retireCustomOpenClawRouteReceiptAfterPolicies({ + sandboxName: "custom-box", + gatewayName: "nemoclaw-18080", + customOpenClawImage: true, + sandboxCommandExecutor: { + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 23 }, + stdout: "", + stderr: "permission denied", + }), + }, + revalidateSandboxIdentity, + }), + ).rejects.toThrow("receipt retirement failed for sandbox 'custom-box' with exit code 23"); + + expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); + }); +}); + describe("new sandbox cancellation recovery", () => { it("preserves recovery guidance when the durable identity is unavailable (#9833)", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => undefined); diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index 38ec3a7a7aa..85185b86339 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -168,6 +168,50 @@ export interface CreatedSandboxCompletionActions { ): Promise; } +const CUSTOM_OPENCLAW_ROUTE_RECEIPT = "/sandbox/.openclaw/.nemoclaw-custom-route-pending"; + +/** + * Retire the build-time custom-route receipt only after the host has observed + * the sandbox inference boundary succeed. The OpenShell exec enters through + * nemoclaw-start, so the still-present receipt protects this command's own + * startup reconciliation before the command removes it. + */ +export async function retireCustomOpenClawRouteReceiptAfterPolicies(input: { + readonly sandboxName: string; + readonly gatewayName: string; + readonly customOpenClawImage: boolean; + readonly sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor; + readonly revalidateSandboxIdentity: (operation: string) => void; +}): Promise { + if (!input.customOpenClawImage) return; + + input.revalidateSandboxIdentity( + `retiring custom-image route receipt for sandbox '${input.sandboxName}'`, + ); + const completion = await input.sandboxCommandExecutor.runBuffered({ + sandboxName: input.sandboxName, + target: { kind: "named", gatewayName: input.gatewayName }, + command: ["/bin/rm", "-f", "--", CUSTOM_OPENCLAW_ROUTE_RECEIPT], + tty: false, + timeoutMilliseconds: 30_000, + timeoutKillSignal: "SIGKILL", + outputLimitBytes: 4_096, + }); + if (completion.outcome.kind !== "completed") { + throw new Error( + `Custom-image route receipt retirement could not run for sandbox '${input.sandboxName}': ${completion.outcome.error.kind}.`, + ); + } + if (completion.outcome.exitCode !== 0) { + throw new Error( + `Custom-image route receipt retirement failed for sandbox '${input.sandboxName}' with exit code ${String(completion.outcome.exitCode)}.`, + ); + } + input.revalidateSandboxIdentity( + `confirming custom-image route receipt retirement for sandbox '${input.sandboxName}'`, + ); +} + type OnboardCreatedSandboxRegistration = ( created: SandboxGpuCreateFlowResult | null, configuredReceipt: HermesPortableConfiguredReceipt | null, diff --git a/src/lib/onboard/machine/final-flow-phases.runtime.test.ts b/src/lib/onboard/machine/final-flow-phases.runtime.test.ts index 1c007ab9410..18c6e85d92c 100644 --- a/src/lib/onboard/machine/final-flow-phases.runtime.test.ts +++ b/src/lib/onboard/machine/final-flow-phases.runtime.test.ts @@ -355,6 +355,52 @@ describe("final onboard flow runtime boundary", () => { expect(order).toEqual(["openclaw", "agent-forward", "policies"]); }); + it("waits for asynchronous policy-boundary cleanup before finalization", async () => { + const order: string[] = []; + const harness = createRuntimeHarness(sessionAt("openclaw")); + const recorders = harness.boundary.recorders(); + const phases = createPhases("openclaw", order, { + loadSession: harness.getSession, + recordStepSkipped: recorders.recordStepSkipped, + recordStateSkipped: recorders.recordStateSkipped, + startRecordedStep: recorders.startRecordedStep, + recordStepComplete: recorders.recordStepComplete, + }); + let releaseCleanup!: () => void; + const cleanupPending = new Promise((resolve) => { + releaseCleanup = resolve; + }); + + const flow = runFinalOnboardFlowSlice({ + context: context({ session: harness.getSession() }), + runtime: harness.boundary.getRuntime(), + phases, + recordRepairEvent: recorders.recordRepairEvent, + afterPoliciesReady: async () => { + order.push("cleanup-start"); + await cleanupPending; + order.push("cleanup-complete"); + }, + }); + await vi.waitFor(() => expect(order).toContain("cleanup-start")); + + expect(order).toEqual(["openclaw", "agent-forward", "policies", "cleanup-start"]); + expect(harness.getSession().machine.state).toBe("finalizing"); + + releaseCleanup(); + await flow; + + expect(order).toEqual([ + "openclaw", + "agent-forward", + "policies", + "cleanup-start", + "cleanup-complete", + "set-default", + "verify", + ]); + }); + it("keeps rollback armed when a policies prerequisite repair fails", async () => { const order: string[] = []; const harness = createRuntimeHarness(sessionAt("post_verify")); diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index cf60e40011d..0ac7ff9cf9c 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -211,14 +211,14 @@ function isPoliciesAppliedResult(result: OnboardStateResult): boolean { function withAfterPoliciesReady( runtime: OnboardMachineRunnerRuntime, - afterPoliciesReady: (() => void) | undefined, + afterPoliciesReady: (() => void | Promise) | undefined, ): OnboardMachineRunnerRuntime { if (!afterPoliciesReady) return runtime; return { session: runtime.session.bind(runtime), async applyResult(result) { const session = await runtime.applyResult(result); - if (isPoliciesAppliedResult(result)) afterPoliciesReady(); + if (isPoliciesAppliedResult(result)) await afterPoliciesReady(); return session; }, }; @@ -329,7 +329,7 @@ async function runFinalFlowPrerequisiteRepairs[]; recordRepairEvent: FinalFlowRepairEventRecorder; - afterPoliciesReady?(): void; + afterPoliciesReady?(): void | Promise; onContextUpdated?(context: Context): void; }): Promise<{ context: Context; pause?: OnboardStatePauseResult }> { const entryIndex = options.phases.findIndex((phase) => phase.state === options.entryState); @@ -385,7 +385,7 @@ async function runFinalFlowPrerequisiteRepairs[]; recordRepairEvent: FinalFlowRepairEventRecorder; - afterPoliciesReady?(): void; + afterPoliciesReady?(): void | Promise; onContextUpdated?(context: Context): void; }) { const canonicalFlow = canonicalFinalFlowPhases(options.phases); diff --git a/src/lib/onboard/sandbox-create/orchestration-route-receipt.test.ts b/src/lib/onboard/sandbox-create/orchestration-route-receipt.test.ts new file mode 100644 index 00000000000..71a9457c0dd --- /dev/null +++ b/src/lib/onboard/sandbox-create/orchestration-route-receipt.test.ts @@ -0,0 +1,53 @@ +// 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 type { SandboxCreateOrchestrationRuntime } from "../../onboard"; +import { retireCustomOpenClawRouteReceiptAfterPolicies } from "../created-sandbox-finalization"; +import { retireRoute } from "./orchestration"; + +describe("custom OpenClaw route receipt handoff", () => { + it("retires after exact identity checks and disarms rollback last", async () => { + const order: string[] = []; + const registered = { + lifecycleGeneration: "generation-1", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + }; + const runtime = { + GATEWAY_NAME: "nemoclaw-18080", + registry: { getSandbox: vi.fn(() => registered) }, + sandboxRecreateTransaction: { + revalidateCreatedSandboxLifecycleRegistration: vi.fn(() => { + order.push("identity"); + }), + }, + getSandboxRecreateObservation: vi.fn(), + getRequestedSandboxAgentName: vi.fn(() => "openclaw"), + sandboxCommandExecutor: { + runBuffered: vi.fn(async () => { + order.push("retire"); + return { + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: "", + stderr: "", + }; + }), + }, + retireCustomOpenClawRouteReceiptAfterPolicies, + sandboxCancelRollback: { disarm: vi.fn(() => order.push("disarm")) }, + } as unknown as SandboxCreateOrchestrationRuntime; + + await retireRoute(runtime, { sandboxName: "custom-box", fromDockerfile: "/tmp/Dockerfile" }, { + name: "openclaw", + } as never); + + expect(order).toEqual(["identity", "retire", "identity", "disarm"]); + expect(runtime.sandboxCommandExecutor.runBuffered).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "custom-box", + target: { kind: "named", gatewayName: "nemoclaw-18080" }, + }), + ); + }); +}); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index da48012401b..5c11d78e38d 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -118,6 +118,39 @@ function cancelRecoveryIdentity( }; } +export async function retireRoute( + runtime: SandboxCreateOrchestrationRuntime, + context: { readonly sandboxName: string; readonly fromDockerfile: string | null }, + agent: AgentDefinition | null, +): Promise { + const { sandboxName } = context; + const revalidateSandboxIdentity = (operation: string): void => { + const registered = runtime.registry.getSandbox(sandboxName); + if (!registered?.lifecycleGeneration || !registered.lifecycleLiveIdentityFingerprint) { + throw new Error( + `Cannot ${operation}: sandbox '${sandboxName}' has no registered lifecycle identity.`, + ); + } + runtime.sandboxRecreateTransaction.revalidateCreatedSandboxLifecycleRegistration( + { sandboxName, gatewayName: runtime.GATEWAY_NAME }, + { + lifecycleGeneration: registered.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: registered.lifecycleLiveIdentityFingerprint, + }, + runtime.getSandboxRecreateObservation, + ); + }; + await runtime.retireCustomOpenClawRouteReceiptAfterPolicies({ + sandboxName, + gatewayName: runtime.GATEWAY_NAME, + customOpenClawImage: + Boolean(context.fromDockerfile) && runtime.getRequestedSandboxAgentName(agent) === "openclaw", + sandboxCommandExecutor: runtime.sandboxCommandExecutor, + revalidateSandboxIdentity, + }); + runtime.sandboxCancelRollback.disarm(); +} + /** Finalize provider arguments from the exact policy that creation consumes. */ type ManagedBootstrapRuntimePatch = Readonly<{ allowsNotReadyLifecycleRevalidation?(): boolean; diff --git a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts index 484b5a94ca9..5e86f12897c 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start-reconcile.test.ts @@ -39,7 +39,7 @@ interface RunReconcileOptions { configWritable?: boolean; hashFailure?: boolean | "once"; customRoutePending?: boolean | "directory" | "invalid"; - retireCustomRouteBeforeRetry?: boolean; + retireCustomRouteAfterProtectedCommands?: boolean; env?: Record; } @@ -153,17 +153,12 @@ describe("agent identity reconciliation with provider (#3175)", () => { "/sandbox", root, ); - const retireFn = extractShellFunction("retire_custom_route_reconcile_marker").replaceAll( - "/sandbox", - root, - ); const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", ...(options.useActualUser ? [] : [`id() { echo ${options.userId ?? 0}; }`]), helperFns, fn, - retireFn, ...(options.hashFailure === "once" ? [ "_first_reconcile_rc=0", @@ -171,8 +166,12 @@ describe("agent identity reconciliation with provider (#3175)", () => { '[ "$_first_reconcile_rc" -eq 19 ] || exit 91', ] : []), - ...(options.retireCustomRouteBeforeRetry - ? ["reconcile_agent_model_with_provider", "retire_custom_route_reconcile_marker"] + ...(options.retireCustomRouteAfterProtectedCommands + ? [ + "reconcile_agent_model_with_provider", + "reconcile_agent_model_with_provider", + `/bin/rm -f -- ${JSON.stringify(customRouteMarkerPath)}`, + ] : []), "reconcile_agent_model_with_provider", ].join("\n"); @@ -213,45 +212,6 @@ describe("agent identity reconciliation with provider (#3175)", () => { return { result, config, hash, expectedHash, customRoutePending }; } - function runCustomRouteSettlement(gatewayReady: boolean, retirementFails = false) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-route-settlement-")); - const openclawDir = path.join(root, ".openclaw"); - const markerPath = path.join(openclawDir, ".nemoclaw-custom-route-pending"); - const stoppedPath = path.join(root, "gateway-stopped"); - fs.mkdirSync(openclawDir, { recursive: true }); - fs.writeFileSync(markerPath, `${"a".repeat(64)} openclaw.json\n`); - const retireFn = extractShellFunction("retire_custom_route_reconcile_marker").replaceAll( - "/sandbox", - root, - ); - const settleFn = extractShellFunction("settle_custom_route_reconcile_marker").replaceAll( - "/sandbox", - root, - ); - const script = path.join(root, "run.sh"); - fs.writeFileSync( - script, - [ - "#!/usr/bin/env bash", - "set -euo pipefail", - retirementFails - ? 'run_openclaw_config_as_owner() { [ "$1" != /bin/rm ] || return 29; "$@"; }' - : 'run_openclaw_config_as_owner() { "$@"; }', - `wait_for_openclaw_gateway_internal() { return ${gatewayReady ? 0 : 23}; }`, - `stop_openclaw_gateway_fail_closed() { : >${JSON.stringify(stoppedPath)}; }`, - retireFn, - settleFn, - 'settle_custom_route_reconcile_marker "123" "pid-identity"', - ].join("\n"), - { mode: 0o700 }, - ); - const result = spawnSync("bash", [script], { encoding: "utf-8" }); - const markerPending = fs.existsSync(markerPath); - const gatewayStopped = fs.existsSync(stoppedPath); - fs.rmSync(root, { recursive: true, force: true }); - return { result, markerPending, gatewayStopped }; - } - it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { const { result, config, hash } = runReconcile({ agents: { defaults: { model: { primary: "inference/old-model" } } }, @@ -424,7 +384,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(customRoutePending).toBe(true); }); - it("uses the live gateway after the first custom-image launch retires its receipt", () => { + it("protects startup and smoke boundaries before host-observed receipt retirement", () => { const { result, config, hash, customRoutePending } = runReconcile( { agents: { defaults: { model: { primary: "inference/custom/selected" } } }, @@ -439,7 +399,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { { customRoutePending: true, gatewayModel: "provider/switched", - retireCustomRouteBeforeRetry: true, + retireCustomRouteAfterProtectedCommands: true, }, ); @@ -453,33 +413,6 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(customRoutePending).toBe(false); }); - it.each([ - { gatewayReady: true, markerPending: false }, - { gatewayReady: false, markerPending: true }, - ])( - "retires the custom-image route receipt only after gateway readiness: $gatewayReady", - ({ gatewayReady, markerPending }) => { - const settled = runCustomRouteSettlement(gatewayReady); - - expect(settled.result.status, settled.result.stderr || settled.result.stdout).toBe(0); - expect(settled.markerPending).toBe(markerPending); - expect(settled.result.stderr).toContain( - gatewayReady ? "" : "first gateway launch did not become ready", - ); - }, - ); - - it("stops the ready gateway and fails when the custom-image route receipt cannot retire", () => { - const settled = runCustomRouteSettlement(true, true); - - expect(settled.result.status).not.toBe(0); - expect(settled.markerPending).toBe(true); - expect(settled.gatewayStopped).toBe(true); - expect(settled.result.stderr).toContain( - "Custom-image route receipt could not be retired after gateway readiness", - ); - }); - it("preserves an explicit model override when the live gateway reports a conflicting model", () => { const initial = { agents: { From 8e2f4abe0e050e3f684463eb759bdae2190ca2ea Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:14:46 -0700 Subject: [PATCH 30/34] docs(inference): clarify custom image model limits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/switch-models.mdx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index 4733d1fafc4..52d34dfe395 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -47,11 +47,12 @@ If the route metadata is incomplete, NemoClaw stops and tells you to re-run onbo At runtime, NemoClaw replaces `contextWindow` only when it resolves a value for the selected model and can retain an existing `maxTokens` value. For an OpenClaw custom image built with `--from`, onboarding patches an inherited model ID to the selected route during the image build. -It removes both inherited limits when the model ID changes and refreshes `.config-hash` before restoring the custom image's final user. +When the model ID changes, onboarding keeps each valid explicit limit and removes only an inherited limit without an explicit replacement. +It then refreshes `.config-hash` before restoring the custom image's final user. On later starts, NemoClaw can also reconcile drift from the live gateway when the sandbox user can write `/sandbox/.openclaw/openclaw.json`. If that runtime configuration is not writable, NemoClaw reports that reconciliation was skipped and preserves the existing configuration. Make the configuration writable by the sandbox user if later runtime route changes must update the file, then recreate the sandbox. -To keep explicit limits for the new model, set `NEMOCLAW_CONTEXT_WINDOW` and `NEMOCLAW_MAX_TOKENS` to values supported by that model before you recreate the sandbox. +To keep an explicit limit for the new model, set its corresponding `NEMOCLAW_CONTEXT_WINDOW` or `NEMOCLAW_MAX_TOKENS` value before you recreate the sandbox. Refer to [Configure Model Limits](configure-model-limits) for the environment variable requirements. From 3c381f8d3bd5c10297bf7cb3eee50d3e36e1a285 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:35:00 -0700 Subject: [PATCH 31/34] fix(onboard): retire custom route after verification Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/onboard.ts | 2 +- .../machine/final-flow-phases.runtime.test.ts | 94 ++++++++++++++----- src/lib/onboard/machine/final-flow-phases.ts | 53 ++++++----- test/e2e/support/workflow-plan.test.ts | 3 + tools/e2e/target-catalogue.mts | 3 + 5 files changed, 106 insertions(+), 49 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 6daf5fb390d..06e77ab6863 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3297,7 +3297,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { runtime: onboardRuntimeBoundary.getRuntime(), phases: finalFlowPhases, recordRepairEvent, - afterPoliciesReady: () => sandboxCreate.retireRoute(sandboxRuntime, finalContext, agent), + afterVerified: () => sandboxCreate.retireRoute(sandboxRuntime, finalContext, agent), onContextUpdated: (context) => { liveFinalFlowContext = context; }, diff --git a/src/lib/onboard/machine/final-flow-phases.runtime.test.ts b/src/lib/onboard/machine/final-flow-phases.runtime.test.ts index 18c6e85d92c..a9cd9f024e0 100644 --- a/src/lib/onboard/machine/final-flow-phases.runtime.test.ts +++ b/src/lib/onboard/machine/final-flow-phases.runtime.test.ts @@ -70,7 +70,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, - afterPoliciesReady: () => { + afterVerified: () => { order.push("disarm"); }, }); @@ -79,9 +79,9 @@ describe("final onboard flow runtime boundary", () => { "openclaw", "agent-forward", "policies", - "disarm", "set-default", "verify", + "disarm", ]); expect(harness.getSession()).toMatchObject({ status: "complete", @@ -134,7 +134,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent, - afterPoliciesReady: () => { + afterVerified: () => { order.push("disarm"); }, }); @@ -144,9 +144,9 @@ describe("final onboard flow runtime boundary", () => { ? ["openclaw", "agent-forward"] : ["agent-setup", "agent-forward"]), "policies", - "disarm", "set-default", "verify", + "disarm", ]); expect(harness.getSession()).toMatchObject({ status: "complete", @@ -239,7 +239,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, - afterPoliciesReady: () => { + afterVerified: () => { order.push("disarm"); }, }); @@ -248,9 +248,9 @@ describe("final onboard flow runtime boundary", () => { "agent-setup", "agent-forward", "policies", - "disarm", "set-default", "verify", + "disarm", ]); expect(harness.getSession()).toMatchObject({ status: "complete", @@ -310,7 +310,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, - afterPoliciesReady: () => { + afterVerified: () => { order.push("disarm"); }, onContextUpdated: (updatedContext) => { @@ -322,9 +322,9 @@ describe("final onboard flow runtime boundary", () => { "openclaw", "agent-forward", "policies", - "disarm", "set-default", "verify:slack,discord", + "disarm", ]); }); @@ -346,7 +346,7 @@ describe("final onboard flow runtime boundary", () => { }, phases, recordRepairEvent: vi.fn(), - afterPoliciesReady: () => { + afterVerified: () => { order.push("disarm"); }, }), @@ -355,7 +355,7 @@ describe("final onboard flow runtime boundary", () => { expect(order).toEqual(["openclaw", "agent-forward", "policies"]); }); - it("waits for asynchronous policy-boundary cleanup before finalization", async () => { + it("waits for asynchronous route retirement after final verification", async () => { const order: string[] = []; const harness = createRuntimeHarness(sessionAt("openclaw")); const recorders = harness.boundary.recorders(); @@ -376,7 +376,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, - afterPoliciesReady: async () => { + afterVerified: async () => { order.push("cleanup-start"); await cleanupPending; order.push("cleanup-complete"); @@ -384,8 +384,15 @@ describe("final onboard flow runtime boundary", () => { }); await vi.waitFor(() => expect(order).toContain("cleanup-start")); - expect(order).toEqual(["openclaw", "agent-forward", "policies", "cleanup-start"]); - expect(harness.getSession().machine.state).toBe("finalizing"); + expect(order).toEqual([ + "openclaw", + "agent-forward", + "policies", + "set-default", + "verify", + "cleanup-start", + ]); + expect(harness.getSession().machine.state).toBe("post_verify"); releaseCleanup(); await flow; @@ -394,11 +401,50 @@ describe("final onboard flow runtime boundary", () => { "openclaw", "agent-forward", "policies", + "set-default", + "verify", "cleanup-start", "cleanup-complete", + ]); + }); + + it("keeps final verification retryable when route retirement fails", async () => { + const order: string[] = []; + const harness = createRuntimeHarness(sessionAt("openclaw")); + const recorders = harness.boundary.recorders(); + const phases = createPhases("openclaw", order, { + loadSession: harness.getSession, + recordStepSkipped: recorders.recordStepSkipped, + recordStateSkipped: recorders.recordStateSkipped, + startRecordedStep: recorders.startRecordedStep, + recordStepComplete: recorders.recordStepComplete, + }); + + await expect( + runFinalOnboardFlowSlice({ + context: context({ session: harness.getSession() }), + runtime: harness.boundary.getRuntime(), + phases, + recordRepairEvent: recorders.recordRepairEvent, + afterVerified: () => { + order.push("retire"); + throw new Error("retirement failed"); + }, + }), + ).rejects.toThrow("retirement failed"); + + expect(order).toEqual([ + "openclaw", + "agent-forward", + "policies", "set-default", "verify", + "retire", ]); + expect(harness.getSession()).toMatchObject({ + status: "in_progress", + machine: { state: "post_verify" }, + }); }); it("keeps rollback armed when a policies prerequisite repair fails", async () => { @@ -416,7 +462,7 @@ describe("final onboard flow runtime boundary", () => { }, }); const recordRepairEvent = vi.fn(recorders.recordRepairEvent); - const afterPoliciesReady = vi.fn(); + const afterVerified = vi.fn(); await expect( runFinalOnboardFlowSlice({ @@ -424,12 +470,12 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent, - afterPoliciesReady, + afterVerified, }), ).rejects.toThrow("policy repair failed"); expect(order).toEqual(["openclaw", "agent-forward", "policies"]); - expect(afterPoliciesReady).not.toHaveBeenCalled(); + expect(afterVerified).not.toHaveBeenCalled(); expect(recordRepairEvent).toHaveBeenLastCalledWith("state.repair.failed", { state: "policies", error: "policy repair failed", @@ -461,20 +507,13 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, - afterPoliciesReady: () => { + afterVerified: () => { order.push("disarm"); }, }), ).rejects.toThrow("verification failed"); - expect(order).toEqual([ - "openclaw", - "agent-forward", - "policies", - "disarm", - "set-default", - "verify", - ]); + expect(order).toEqual(["openclaw", "agent-forward", "policies", "set-default", "verify"]); expect(printDashboard).not.toHaveBeenCalled(); expect(harness.getSession()).toMatchObject({ status: "in_progress", @@ -490,6 +529,7 @@ describe("final onboard flow runtime boundary", () => { .fn() .mockResolvedValueOnce(deploymentResult(false)) .mockResolvedValueOnce(deploymentResult(true)); + const afterVerified = vi.fn(); const phases = createPhases("openclaw", order, { loadSession: harness.getSession, recordStepSkipped: recorders.recordStepSkipped, @@ -504,6 +544,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, + afterVerified, }); expect(first.session).toMatchObject({ @@ -511,15 +552,18 @@ describe("final onboard flow runtime boundary", () => { resumable: true, machine: { state: "post_verify" }, }); + expect(afterVerified).not.toHaveBeenCalled(); const resumed = await runFinalOnboardFlowSlice({ context: context({ resume: true, session: harness.getSession() }), runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, + afterVerified, }); expect(verifyDeployment).toHaveBeenCalledTimes(2); + expect(afterVerified).toHaveBeenCalledOnce(); expect(resumed.session).toMatchObject({ status: "complete", resumable: false, diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 0ac7ff9cf9c..9d4f3a4d255 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -201,27 +201,34 @@ export function createFinalOnboardFlowPhases< return [branchSetupPhase, policiesPhase, finalizationPhase, postVerifyPhase]; } -function isPoliciesAppliedResult(result: OnboardStateResult): boolean { +function isSuccessfulFinalVerification(result: OnboardStateHandlerResult): boolean { + const results = Array.isArray(result) + ? (result as readonly OnboardStateResult[]) + : [result as OnboardStateResult]; return ( - result.type === "transition" && - result.next === "finalizing" && - result.metadata?.state === "policies" + results.length === 1 && + results[0].type === "complete" && + results[0].metadata?.state === "post_verify" ); } -function withAfterPoliciesReady( - runtime: OnboardMachineRunnerRuntime, - afterPoliciesReady: (() => void | Promise) | undefined, -): OnboardMachineRunnerRuntime { - if (!afterPoliciesReady) return runtime; - return { - session: runtime.session.bind(runtime), - async applyResult(result) { - const session = await runtime.applyResult(result); - if (isPoliciesAppliedResult(result)) await afterPoliciesReady(); - return session; - }, - }; +function withAfterVerified( + phases: readonly OnboardSequencePhase[], + afterVerified: (() => void | Promise) | undefined, +): readonly OnboardSequencePhase[] { + if (!afterVerified) return phases; + return phases.map((phase) => + phase.state === "post_verify" + ? { + ...phase, + async run(context) { + const result = await phase.run(context); + if (isSuccessfulFinalVerification(result.result)) await afterVerified(); + return result; + }, + } + : phase, + ); } function withContextObserver( @@ -329,7 +336,6 @@ async function runFinalFlowPrerequisiteRepairs[]; recordRepairEvent: FinalFlowRepairEventRecorder; - afterPoliciesReady?(): void | Promise; onContextUpdated?(context: Context): void; }): Promise<{ context: Context; pause?: OnboardStatePauseResult }> { const entryIndex = options.phases.findIndex((phase) => phase.state === options.entryState); @@ -385,7 +391,6 @@ async function runFinalFlowPrerequisiteRepairs[]; recordRepairEvent: FinalFlowRepairEventRecorder; - afterPoliciesReady?(): void | Promise; + afterVerified?(): void | Promise; onContextUpdated?(context: Context): void; }) { const canonicalFlow = canonicalFinalFlowPhases(options.phases); @@ -430,7 +435,6 @@ export async function runFinalOnboardFlowSlice { it.each([ "scripts/nemoclaw-start.sh", + "src/lib/onboard.ts", + "src/lib/onboard/created-sandbox-finalization.ts", "src/lib/onboard/docker-startup-command-env.ts", "src/lib/onboard/dockerfile-patch.ts", + "src/lib/onboard/machine/final-flow-phases.ts", "src/lib/onboard/managed-workload/onboard-orchestration.ts", "src/lib/onboard/sandbox-create/orchestration.ts", "src/lib/onboard/sandbox-create-launch.ts", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 42f85afd183..434525d2133 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1149,8 +1149,11 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ exposeCliBin: true, owningPaths: [ "scripts/nemoclaw-start.sh", + "src/lib/onboard.ts", + "src/lib/onboard/created-sandbox-finalization.ts", "src/lib/onboard/docker-startup-command-env.ts", "src/lib/onboard/dockerfile-patch.ts", + "src/lib/onboard/machine/final-flow-phases.ts", "src/lib/onboard/managed-workload/onboard-orchestration.ts", "src/lib/onboard/sandbox-create/orchestration.ts", "src/lib/onboard/sandbox-create-launch.ts", From d796a5a22324c44377e858b2128d3a3aa2f109d7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:37:49 -0700 Subject: [PATCH 32/34] fix(onboard): persist custom route runtime identity Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../dockerfile-custom-openclaw-model-reconcile.test.ts | 4 ++++ src/lib/onboard/dockerfile-patch.ts | 3 +++ 2 files changed, 7 insertions(+) diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index c6c0a284525..35fa0c2b332 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -140,6 +140,10 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { expect(encodedLimits).not.toBe(""); expect(patched).toContain("sha256sum openclaw.json > .config-hash"); expect(patched).toContain(".nemoclaw-custom-route-pending"); + expect(patched).toContain( + "ENV NEMOCLAW_MODEL=provider/selected-model \\\n" + + " NEMOCLAW_PRIMARY_MODEL_REF=inference/provider/selected-model", + ); expect(patched.trimEnd().endsWith("USER 1001:1001")).toBe(true); const embedded = patched.match( diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 11eff962382..5255eea4cea 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -215,12 +215,15 @@ function appendCustomOpenClawModelReconcile( const restoreUser = finalUser === null ? "" : `\n${finalUser.text}`; const encodedModel = Buffer.from(model, "utf8").toString("base64"); const encodedLimits = Buffer.from(JSON.stringify(explicitLimits), "utf8").toString("base64"); + const primaryModelRef = model.startsWith("inference/") ? model : `inference/${model}`; return `${dockerfile.trimEnd()} # Reconcile inherited OpenClaw model metadata with this custom image's route. ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} ARG NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64=${encodedLimits} +ENV NEMOCLAW_MODEL=${model} \\ + NEMOCLAW_PRIMARY_MODEL_REF=${primaryModelRef} ${useRoot}RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64="\${NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64}" /usr/bin/python3 - <<'PYNEMOCLAWCUSTOMROUTE' import base64 import hashlib From 85a1a09f65aaf7b03429e7f539f94fd22943187d Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:46:59 -0700 Subject: [PATCH 33/34] fix(onboard): reconcile custom route after sandbox creation Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/onboard/config-sync.test.ts | 76 +++++++++++++ src/lib/onboard/config-sync.ts | 104 +++++++++++++++++- .../onboard/machine/final-flow-phases.test.ts | 16 +++ src/lib/onboard/machine/final-flow-phases.ts | 1 + .../machine/handlers/agent-setup.test.ts | 18 +++ .../onboard/machine/handlers/agent-setup.ts | 29 +++-- src/lib/onboard/openclaw-setup.test.ts | 44 ++++++++ src/lib/onboard/openclaw-setup.ts | 56 +++++++--- test/helpers/onboard-final-flow-phases.ts | 16 ++- 9 files changed, 335 insertions(+), 25 deletions(-) diff --git a/src/lib/onboard/config-sync.test.ts b/src/lib/onboard/config-sync.test.ts index 387d5758010..57907a8f3fa 100644 --- a/src/lib/onboard/config-sync.test.ts +++ b/src/lib/onboard/config-sync.test.ts @@ -251,6 +251,82 @@ describe("sandbox config sync helpers", () => { }, ); + itUnix("reconciles a custom image route before native gateway restart", () => { + const homeDir = createConfigSyncHome(); + const openclawDir = path.join(homeDir, ".openclaw"); + const openclawConfig = path.join(openclawDir, "openclaw.json"); + const customRouteReceipt = path.join(openclawDir, ".nemoclaw-custom-route-pending"); + fs.mkdirSync(openclawDir, { mode: 0o700 }); + const inheritedConfig = { + agents: { + defaults: { model: { primary: "inference/nvidia/nemotron-3-super-120b-a12b" } }, + }, + models: { + providers: { + inference: { + models: [ + { + id: "nvidia/nemotron-3-super-120b-a12b", + name: "inference/nvidia/nemotron-3-super-120b-a12b", + contextWindow: 131072, + maxTokens: 4096, + }, + ], + }, + }, + }, + }; + fs.writeFileSync(openclawConfig, `${JSON.stringify(inheritedConfig, null, 2)}\n`, { + mode: 0o600, + }); + fs.writeFileSync( + customRouteReceipt, + `${createHash("sha256").update(fs.readFileSync(openclawConfig)).digest("hex")} openclaw.json\n`, + { mode: 0o600 }, + ); + + const script = buildSandboxConfigSyncScript(selection, false, true); + const { nativeCalls } = runConfigSyncScript(script, homeDir, String(process.getuid?.())); + + const reconciled = JSON.parse(fs.readFileSync(openclawConfig, "utf8")); + expect(reconciled.agents.defaults.model.primary).toBe(`inference/${selection.model}`); + expect(reconciled.models.providers.inference.models[0]).toEqual({ + id: selection.model, + name: `inference/${selection.model}`, + }); + const expectedHash = createHash("sha256").update(fs.readFileSync(openclawConfig)).digest("hex"); + expect(fs.readFileSync(customRouteReceipt, "utf8")).toBe(`${expectedHash} openclaw.json\n`); + expect(fs.readFileSync(path.join(openclawDir, ".config-hash"), "utf8")).toBe( + `${expectedHash} openclaw.json\n`, + ); + expect(nativeCalls.map((call) => call.split("|")[0])).toEqual(["config validate"]); + }); + + itUnix("refuses custom route reconciliation when its receipt is missing", () => { + const homeDir = createConfigSyncHome(); + const openclawDir = path.join(homeDir, ".openclaw"); + fs.mkdirSync(openclawDir, { mode: 0o700 }); + fs.writeFileSync( + path.join(openclawDir, "openclaw.json"), + '{"agents":{"defaults":{"model":{"primary":"inference/base"}}}}\n', + { mode: 0o600 }, + ); + + const script = buildSandboxConfigSyncScript(selection, false, true); + const { result, nativeCalls } = runConfigSyncScript( + script, + homeDir, + String(process.getuid?.()), + undefined, + { expectedStatus: 1 }, + ); + + expect(result.stderr).toContain( + "Refusing custom OpenClaw route reconciliation without its regular receipt", + ); + expect(nativeCalls).toEqual([]); + }); + itUnix("syncs selection metadata and completes managed OpenClaw session state", () => { const homeDir = createConfigSyncHome(); const openclawDir = path.join(homeDir, ".openclaw"); diff --git a/src/lib/onboard/config-sync.ts b/src/lib/onboard/config-sync.ts index 40d1d2146b4..4c2b65eb1b1 100644 --- a/src/lib/onboard/config-sync.ts +++ b/src/lib/onboard/config-sync.ts @@ -9,6 +9,7 @@ export interface RunSandboxConfigSyncDeps { getSelectionConfig: () => ProviderSelectionConfig | null; runConnectScript: (sandboxName: string, scriptContent: string) => Promise; managedProfileApplied?: boolean; + reconcileCustomOpenClawRoute?: boolean; } export interface NemoClawConfigSyncDeps { @@ -25,10 +26,12 @@ export function createNemoClawConfigSync(deps: NemoClawConfigSyncDeps) { model: string, revalidateSandboxIdentity: (operation: string) => void = skipSandboxIdentityRevalidation, managedProfileApplied = false, + reconcileCustomOpenClawRoute = false, ): Promise { await runSandboxConfigSync(sandboxName, { getSelectionConfig: () => deps.getProviderSelectionConfig(provider, model), managedProfileApplied, + reconcileCustomOpenClawRoute, runConnectScript: async (name, scriptContent) => { revalidateSandboxIdentity(`synchronize OpenClaw config in sandbox '${name}'`); const result = await deps.sandboxCommandExecutor.runBuffered({ @@ -58,14 +61,112 @@ export async function runSandboxConfigSync( const selectionConfig = deps.getSelectionConfig(); if (!selectionConfig) return; const sandboxConfig = { ...selectionConfig, onboardedAt: new Date().toISOString() }; - const script = buildSandboxConfigSyncScript(sandboxConfig, deps.managedProfileApplied === true); + const script = buildSandboxConfigSyncScript( + sandboxConfig, + deps.managedProfileApplied === true, + deps.reconcileCustomOpenClawRoute === true, + ); await deps.runConnectScript(sandboxName, script); } export function buildSandboxConfigSyncScript( selectionConfig: ProviderSelectionConfig & { agent?: string }, managedProfileApplied = false, + reconcileCustomOpenClawRoute = false, ): string { + const encodedModel = Buffer.from(selectionConfig.model, "utf8").toString("base64"); + const customRouteReconcile = reconcileCustomOpenClawRoute + ? ` + custom_route_marker="$config_dir/.nemoclaw-custom-route-pending" + if [ -f "$config_dir/openclaw.json" ]; then + if [ ! -f "$custom_route_marker" ] || [ -L "$custom_route_marker" ]; then + echo "Refusing custom OpenClaw route reconciliation without its regular receipt" >&2 + exit 1 + fi + NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} python3 -I - \ + "$config_dir/openclaw.json" "$custom_route_marker" <<'PYNEMOCLAWCUSTOMROUTE' +import base64 +import hashlib +import json +import os +import re +import stat +import sys + +config_path, marker_path = sys.argv[1:] +model = base64.b64decode( + os.environ["NEMOCLAW_CUSTOM_ROUTE_MODEL_B64"], validate=True +).decode("utf-8") +if len(model) > 512 or re.fullmatch(r"[A-Za-z0-9._:/-]+", model) is None: + raise SystemExit("custom OpenClaw route model is invalid") + + +def open_regular(path, flags): + descriptor = os.open(path, flags | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0)) + metadata = os.fstat(descriptor) + current = os.stat(path, follow_symlinks=False) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or (metadata.st_dev, metadata.st_ino) != (current.st_dev, current.st_ino) + ): + os.close(descriptor) + raise OSError("path is not a trusted regular file") + return descriptor + + +config_fd = open_regular(config_path, os.O_RDWR) +marker_fd = open_regular(marker_path, os.O_RDWR) +try: + with os.fdopen(config_fd, "r+", encoding="utf-8", closefd=False) as config_file: + config = json.load(config_file) + if not isinstance(config, dict): + raise ValueError("OpenClaw config must be an object") + agents = config.setdefault("agents", {}) + defaults = agents.setdefault("defaults", {}) + model_config = defaults.setdefault("model", {}) + providers = config.setdefault("models", {}).setdefault("providers", {}) + inference = providers.setdefault("inference", {}) + if not all( + isinstance(value, dict) + for value in (agents, defaults, model_config, providers, inference) + ): + raise ValueError("OpenClaw config has an invalid model structure") + models = inference.get("models") + if not isinstance(models, list) or not models: + models = [{}] + inference["models"] = models + first = models[0] + if not isinstance(first, dict): + first = {} + models[0] = first + provider_model = model if model.startswith("inference/") else f"inference/{model}" + bare_model = model.removeprefix("inference/") + model_changed = first.get("id") not in (bare_model, provider_model) + model_config["primary"] = provider_model + first["id"] = bare_model + first["name"] = provider_model + if model_changed: + first.pop("contextWindow", None) + first.pop("maxTokens", None) + config_file.seek(0) + json.dump(config, config_file, indent=2) + config_file.write("\\n") + config_file.truncate() + config_file.flush() + os.fsync(config_fd) + config_file.seek(0) + digest = hashlib.sha256(config_file.read().encode("utf-8")).hexdigest() + with os.fdopen(marker_fd, "w", encoding="ascii", closefd=False) as marker_file: + marker_file.write(f"{digest} openclaw.json\\n") + marker_file.flush() + os.fsync(marker_fd) +finally: + os.close(marker_fd) + os.close(config_fd) +PYNEMOCLAWCUSTOMROUTE + fi` + : ""; const writeSelection = ` set -euo pipefail # OpenShell exec and the OpenClaw gateway can expose different HOME values. @@ -120,6 +221,7 @@ if [ -d "$config_dir" ]; then exit 1 fi export HOME=/sandbox OPENCLAW_STATE_DIR="$config_dir" OPENCLAW_CONFIG_PATH="$config_dir/openclaw.json" +${customRouteReconcile} /usr/local/bin/openclaw config validate (cd "$config_dir" && sha256sum openclaw.json >.config-hash) python3 -I /usr/local/lib/nemoclaw/normalize_mutable_config_perms.py "$config_dir" "$current_uid" "$(id -g)" diff --git a/src/lib/onboard/machine/final-flow-phases.test.ts b/src/lib/onboard/machine/final-flow-phases.test.ts index e5527894771..0b015854c6d 100644 --- a/src/lib/onboard/machine/final-flow-phases.test.ts +++ b/src/lib/onboard/machine/final-flow-phases.test.ts @@ -123,6 +123,22 @@ describe("final onboard flow phases", () => { expect(order).toEqual(["openclaw", "agent-forward", "policies", "set-default", "verify"]); }); + it("reconciles the route only for a fresh custom OpenClaw image", async () => { + const setupOpenclaw = vi.fn(async () => undefined); + const [branchPhase] = createPhases("openclaw", [], { setupOpenclaw }); + + await branchPhase.run(context({ fromDockerfile: "/tmp/CustomDockerfile" })); + + expect(setupOpenclaw).toHaveBeenCalledExactlyOnceWith( + "my-sandbox", + "nvidia/test", + "nim", + null, + undefined, + true, + ); + }); + it("carries merged policy messaging channels into the final flow context", async () => { const mergePolicyMessagingChannels = vi.fn(() => ["slack", "discord"]); const [, policiesPhase] = createPhases("openclaw", [], { mergePolicyMessagingChannels }); diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 9d4f3a4d255..7c9c591b62f 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -89,6 +89,7 @@ export function createFinalOnboardFlowPhases< hermesAuthMethod: context.hermesAuthMethod, hermesToolGateways: context.hermesToolGateways, managedOpenclawStartup: options.managedOpenclawStartup === true, + customOpenclawImage: Boolean(context.fromDockerfile) && context.agent === null, deps: options.agentSetupDeps, }); return { diff --git a/src/lib/onboard/machine/handlers/agent-setup.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index 4909ce64b5f..cca6ce979f5 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -360,6 +360,24 @@ describe("handleAgentSetupState", () => { }); }); + it("requests route reconciliation for a fresh custom OpenClaw image", async () => { + const { deps, calls } = createDeps(); + + await handleAgentSetupState({ + ...baseOptions(deps), + customOpenclawImage: true, + }); + + expect(calls.setupOpenclaw).toHaveBeenCalledExactlyOnceWith( + "my-assistant", + "model", + "provider", + null, + undefined, + true, + ); + }); + it("waits for managed OpenClaw before syncing selection metadata without legacy setup", async () => { const { deps, calls } = createDeps(); calls.controlPlaneReady.mockResolvedValue(true); diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index f79c03594cb..0f28b678fdb 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -17,6 +17,7 @@ export interface AgentSetupStateOptions { hermesAuthMethod: string | null; hermesToolGateways: string[]; managedOpenclawStartup?: boolean; + customOpenclawImage?: boolean; revalidateSandboxIdentity?: (operation: string) => void; deps: { handleAgentSetup( @@ -50,6 +51,7 @@ export interface AgentSetupStateOptions { provider: string, webSearchConfig: WebSearchSelection, revalidateSandboxIdentity?: (operation: string) => void, + reconcileCustomOpenClawRoute?: boolean, ): Promise; configureOpenclawSandbox( sandboxName: string, @@ -58,6 +60,7 @@ export interface AgentSetupStateOptions { webSearchConfig: WebSearchSelection, revalidateSandboxIdentity?: (operation: string) => void, managedProfileApplied?: boolean, + reconcileCustomOpenClawRoute?: boolean, ): Promise; recordStepComplete(stepName: string, updates: SessionUpdates): Promise; toSessionUpdates(updates: Record): SessionUpdates; @@ -80,6 +83,7 @@ export async function handleAgentSetupState({ hermesAuthMethod, hermesToolGateways, managedOpenclawStartup = false, + customOpenclawImage = false, revalidateSandboxIdentity, deps, }: AgentSetupStateOptions): Promise { @@ -154,13 +158,24 @@ export async function handleAgentSetupState({ } else { await deps.startRecordedStep("openclaw", { sandboxName, provider, model }); revalidateSandboxIdentity?.(`configure OpenClaw in sandbox '${sandboxName}'`); - await deps.setupOpenclaw( - sandboxName, - model, - provider, - webSearchConfig, - revalidateSandboxIdentity, - ); + if (customOpenclawImage) { + await deps.setupOpenclaw( + sandboxName, + model, + provider, + webSearchConfig, + revalidateSandboxIdentity, + true, + ); + } else { + await deps.setupOpenclaw( + sandboxName, + model, + provider, + webSearchConfig, + revalidateSandboxIdentity, + ); + } revalidateSandboxIdentity?.(`complete OpenClaw setup for sandbox '${sandboxName}'`); await deps.recordStepComplete( "openclaw", diff --git a/src/lib/onboard/openclaw-setup.test.ts b/src/lib/onboard/openclaw-setup.test.ts index 1e209446a77..901bb83a42e 100644 --- a/src/lib/onboard/openclaw-setup.test.ts +++ b/src/lib/onboard/openclaw-setup.test.ts @@ -115,6 +115,25 @@ describe("OpenClaw sandbox setup", () => { expect(reconcileWebSearch).not.toHaveBeenCalled(); }); + it("forwards custom-image route reconciliation to config sync", async () => { + const syncNemoClawConfigInSandbox = vi.fn(async () => undefined); + const configureOpenclawSandbox = createConfigureOpenclawSandbox({ + syncNemoClawConfigInSandbox, + reconcileWebSearch: vi.fn(async () => undefined), + }); + + await configureOpenclawSandbox("spark-box", "model", "provider", null, undefined, false, true); + + expect(syncNemoClawConfigInSandbox).toHaveBeenCalledExactlyOnceWith( + "spark-box", + "provider", + "model", + undefined, + false, + true, + ); + }); + it("delegates fresh setup to shared OpenClaw configuration", async () => { const configureOpenclawSandbox = vi.fn(async () => undefined); const restartNativeGateway = vi.fn(async () => ({ ok: true as const })); @@ -140,6 +159,31 @@ describe("OpenClaw sandbox setup", () => { expect(configureOpenclawSandbox).toHaveBeenCalledBefore(restartNativeGateway); }); + it("reconciles a custom-image route before restarting the native gateway", async () => { + const configureOpenclawSandbox = vi.fn(async () => undefined); + const restartNativeGateway = vi.fn(async () => ({ ok: true as const })); + const setup = createOpenclawSetup({ + step: vi.fn(), + agentProductName: () => "OpenClaw", + configureOpenclawSandbox, + restartNativeGateway, + shouldRestartNativeGateway: () => true, + }); + + await setup("spark-box", "selected-model", "provider", null, undefined, true); + + expect(configureOpenclawSandbox).toHaveBeenCalledExactlyOnceWith( + "spark-box", + "selected-model", + "provider", + null, + undefined, + false, + true, + ); + expect(configureOpenclawSandbox).toHaveBeenCalledBefore(restartNativeGateway); + }); + it("leaves ordinary providers on their initial native gateway", async () => { const restartNativeGateway = vi.fn(async () => ({ ok: true as const })); const setup = createOpenclawSetup({ diff --git a/src/lib/onboard/openclaw-setup.ts b/src/lib/onboard/openclaw-setup.ts index 6476e75169f..f702fe9073a 100644 --- a/src/lib/onboard/openclaw-setup.ts +++ b/src/lib/onboard/openclaw-setup.ts @@ -107,6 +107,7 @@ export interface ConfigureOpenclawSandboxDeps { model: string, revalidateSandboxIdentity?: (operation: string) => void, managedProfileApplied?: boolean, + reconcileCustomOpenClawRoute?: boolean, ): Promise; reconcileWebSearch( sandboxName: string, @@ -123,14 +124,26 @@ export function createConfigureOpenclawSandbox(deps: ConfigureOpenclawSandboxDep webSearchConfig: WebSearchSelection, revalidateSandboxIdentity?: (operation: string) => void, managedProfileApplied = false, + reconcileCustomOpenClawRoute = false, ): Promise { - await deps.syncNemoClawConfigInSandbox( - sandboxName, - provider, - model, - revalidateSandboxIdentity, - managedProfileApplied, - ); + if (reconcileCustomOpenClawRoute) { + await deps.syncNemoClawConfigInSandbox( + sandboxName, + provider, + model, + revalidateSandboxIdentity, + managedProfileApplied, + true, + ); + } else { + await deps.syncNemoClawConfigInSandbox( + sandboxName, + provider, + model, + revalidateSandboxIdentity, + managedProfileApplied, + ); + } await deps.reconcileWebSearch(sandboxName, webSearchConfig, revalidateSandboxIdentity); }; } @@ -153,6 +166,8 @@ export interface OpenclawSetupDeps { provider: string, webSearchConfig: WebSearchSelection, revalidateSandboxIdentity?: (operation: string) => void, + managedProfileApplied?: boolean, + reconcileCustomOpenClawRoute?: boolean, ): Promise; } @@ -163,16 +178,29 @@ export function createOpenclawSetup(deps: OpenclawSetupDeps) { provider: string, webSearchConfig: WebSearchSelection, revalidateSandboxIdentity?: (operation: string) => void, + reconcileCustomOpenClawRoute = false, ): Promise { deps.step(7, 8, `Setting up ${deps.agentProductName()} inside sandbox`); - await deps.configureOpenclawSandbox( - sandboxName, - model, - provider, - webSearchConfig, - revalidateSandboxIdentity, - ); + if (reconcileCustomOpenClawRoute) { + await deps.configureOpenclawSandbox( + sandboxName, + model, + provider, + webSearchConfig, + revalidateSandboxIdentity, + false, + true, + ); + } else { + await deps.configureOpenclawSandbox( + sandboxName, + model, + provider, + webSearchConfig, + revalidateSandboxIdentity, + ); + } if (deps.shouldRestartNativeGateway(provider)) { revalidateSandboxIdentity?.(`restart native OpenClaw gateway in sandbox '${sandboxName}'`); const restart = await deps.restartNativeGateway(sandboxName); diff --git a/test/helpers/onboard-final-flow-phases.ts b/test/helpers/onboard-final-flow-phases.ts index 3cc933255a3..24ceed86deb 100644 --- a/test/helpers/onboard-final-flow-phases.ts +++ b/test/helpers/onboard-final-flow-phases.ts @@ -78,6 +78,14 @@ export type RecorderOverrides = { Agent | null, WebSearchConfig >["deps"]["setupPoliciesWithSelection"]; + setupOpenclaw?: ( + sandboxName: string, + model: string, + provider: string, + webSearchConfig: WebSearchConfig | null, + revalidateSandboxIdentity?: (operation: string) => void, + reconcileCustomOpenClawRoute?: boolean, + ) => Promise; }; function cloneSession(session: Session): Session { @@ -220,9 +228,11 @@ export function createPhases( skippedStepMessage: vi.fn(), recordStateSkipped: recorders.recordStateSkipped ?? vi.fn(async () => createSession()), startRecordedStep: recorders.startRecordedStep ?? vi.fn(async () => undefined), - setupOpenclaw: vi.fn(async () => { - order.push("openclaw"); - }), + setupOpenclaw: + recorders.setupOpenclaw ?? + vi.fn(async () => { + order.push("openclaw"); + }), configureOpenclawSandbox: vi.fn(async () => undefined), recordStepComplete: recorders.recordStepComplete ?? From 54ee35cccbadc584bd6fffc44a90573607e843f7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:08:23 -0700 Subject: [PATCH 34/34] fix(onboard): support OpenShell custom image builder Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...le-custom-openclaw-model-reconcile.test.ts | 26 +++++++++++-------- src/lib/onboard/dockerfile-patch.ts | 19 +++++++++++++- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts index 35fa0c2b332..9b58043395d 100644 --- a/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -16,6 +16,14 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { vi.unstubAllEnvs(); }); + function embeddedCustomRouteProgram(dockerfile: string): string { + const encoded = dockerfile.match( + /RUN printf '%s' '([A-Za-z0-9+/=]+)' \| \/usr\/bin\/base64 --decode \|/u, + )?.[1]; + expect(encoded).toBeDefined(); + return Buffer.from(encoded!, "base64").toString("utf8"); + } + function customRouteProgram(root: string): { configPath: string; program: string } { const dockerfilePath = path.join(root, "Dockerfile"); fs.writeFileSync( @@ -39,10 +47,7 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { [], { agentName: "openclaw", reconcileCustomOpenClawModel: true }, ); - const embedded = fs - .readFileSync(dockerfilePath, "utf8") - .match(/<<'PYNEMOCLAWCUSTOMROUTE'\n([\s\S]*?)\nPYNEMOCLAWCUSTOMROUTE/u)?.[1]; - expect(embedded).toBeDefined(); + const embedded = embeddedCustomRouteProgram(fs.readFileSync(dockerfilePath, "utf8")); const configPath = path.join(root, "openclaw.json"); fs.writeFileSync( configPath, @@ -59,7 +64,7 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { ); return { configPath, - program: embedded!.replace( + program: embedded.replace( 'config_path = "/sandbox/.openclaw/openclaw.json"', `config_path = ${JSON.stringify(configPath)}`, ), @@ -139,17 +144,16 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { expect(encodedModel).not.toBe(""); expect(encodedLimits).not.toBe(""); expect(patched).toContain("sha256sum openclaw.json > .config-hash"); - expect(patched).toContain(".nemoclaw-custom-route-pending"); + expect(patched).not.toContain("<<'PYNEMOCLAWCUSTOMROUTE'"); + expect(patched).toContain("/usr/bin/base64 --decode | /usr/bin/env"); expect(patched).toContain( "ENV NEMOCLAW_MODEL=provider/selected-model \\\n" + " NEMOCLAW_PRIMARY_MODEL_REF=inference/provider/selected-model", ); expect(patched.trimEnd().endsWith("USER 1001:1001")).toBe(true); - const embedded = patched.match( - /<<'PYNEMOCLAWCUSTOMROUTE'\n([\s\S]*?)\nPYNEMOCLAWCUSTOMROUTE/u, - )?.[1]; - expect(embedded).toBeDefined(); + const embedded = embeddedCustomRouteProgram(patched); + expect(embedded).toContain(".nemoclaw-custom-route-pending"); const configPath = path.join(root, "openclaw.json"); fs.writeFileSync( configPath, @@ -172,7 +176,7 @@ describe("custom OpenClaw Dockerfile model reconciliation", () => { }), ); fs.chmodSync(configPath, 0o640); - const program = embedded!.replace( + const program = embedded.replace( 'config_path = "/sandbox/.openclaw/openclaw.json"', `config_path = ${JSON.stringify(configPath)}`, ); diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 5255eea4cea..fada002b88c 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -217,7 +217,7 @@ function appendCustomOpenClawModelReconcile( const encodedLimits = Buffer.from(JSON.stringify(explicitLimits), "utf8").toString("base64"); const primaryModelRef = model.startsWith("inference/") ? model : `inference/${model}`; - return `${dockerfile.trimEnd()} + const rendered = `${dockerfile.trimEnd()} # Reconcile inherited OpenClaw model metadata with this custom image's route. ARG NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=${encodedModel} @@ -335,6 +335,23 @@ RUN if [ -f /sandbox/.openclaw/openclaw.json ]; then \\ chmod --reference=openclaw.json .config-hash; \\ fi${restoreUser} `; + const heredoc = + /RUN NEMOCLAW_CUSTOM_ROUTE_MODEL_B64=.*?<<'PYNEMOCLAWCUSTOMROUTE'\n([\s\S]*?)\nPYNEMOCLAWCUSTOMROUTE/u.exec( + rendered, + ); + if (heredoc === null) { + throw new Error("Custom OpenClaw route reconciliation program is missing."); + } + // The OpenShell gateway builds custom Dockerfiles through Docker's legacy + // builder, which accepts heredoc syntax as an empty RUN. Publish the readable + // program as encoded stdin so both legacy and BuildKit builders execute it. + const encodedProgram = Buffer.from(heredoc[1]!, "utf8").toString("base64"); + const legacyCompatibleRun = + `RUN printf '%s' '${encodedProgram}' | /usr/bin/base64 --decode | ` + + `/usr/bin/env NEMOCLAW_CUSTOM_ROUTE_MODEL_B64="\${NEMOCLAW_CUSTOM_ROUTE_MODEL_B64}" ` + + `NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64="\${NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64}" ` + + `/usr/bin/python3 -`; + return rendered.replace(heredoc[0], legacyCompatibleRun); } function openClawRuntimeUserArg(dockerfile: string): DockerfileInstruction | null {