diff --git a/docs/inference/configure-model-limits.mdx b/docs/inference/configure-model-limits.mdx index 9ea4c1e3066..671c713e61d 100644 --- a/docs/inference/configure-model-limits.mdx +++ b/docs/inference/configure-model-limits.mdx @@ -61,6 +61,13 @@ 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`, 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. ```bash @@ -69,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 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/docs/inference/switch-models.mdx b/docs/inference/switch-models.mdx index 0cff2d2d08b..eef78164bef 100644 --- a/docs/inference/switch-models.mdx +++ b/docs/inference/switch-models.mdx @@ -43,6 +43,20 @@ 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. +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 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. + + + For Hermes, the command recomputes the target model's context window before it updates the shared native configuration. 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/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index b6e9459713a..0266a7ca147 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -969,12 +969,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" @@ -985,6 +979,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:-}" @@ -1122,9 +1121,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 -# 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. # @@ -1141,49 +1139,171 @@ 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" + local custom_route_marker="/sandbox/.openclaw/.nemoclaw-custom-route-pending" [ -f "$config_file" ] || return 0 - if [ -L "$config_file" ] || [ -L "$hash_file" ]; then + 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 + + 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 + local model_source="gateway" + 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="$( - python3 - <<'PYPROBE' -import json, subprocess + /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", "--json"], + ["openshell", "inference", "get", "-g", gateway_name], 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 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 @@ -1218,8 +1338,9 @@ 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"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 @@ -1232,11 +1353,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 @@ -1257,7 +1387,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/") @@ -1274,8 +1404,12 @@ if os.environ.get("RECONCILE_SOURCE") == "gateway": if not isinstance(first, dict): first = {} models_list[0] = first + provider_model_unchanged = first.get("id") in (bare, provider_model) first["id"] = bare first["name"] = provider_model + 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/src/lib/onboard.ts b/src/lib/onboard.ts index 28425fc2a5d..4dd83f31d28 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"); @@ -1422,7 +1423,7 @@ const { getSandboxRuntimeRegistryFields, hasSandboxGpuDrift, updateReusedSandbox getInstalledOpenshellVersion, runCaptureOpenshell, }); -const sandboxCreateOrchestrationRuntime = { +const sandboxRuntime = { DASHBOARD_PORT, get GATEWAY_NAME() { return GATEWAY_NAME; @@ -1443,6 +1444,7 @@ const sandboxCreateOrchestrationRuntime = { confirmRecreateForSelectionDrift, createOnboardCreatedSandboxCompletion, createOnboardCreatedSandboxRegistration, + retireCustomOpenClawRouteReceiptAfterPolicies, createSandboxRecreateProtection, dashboardRuntime, dcodeAutoApprovalFlow, @@ -1539,11 +1541,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(), + afterVerified: () => sandboxCreate.retireRoute(sandboxRuntime, finalContext, agent), onContextUpdated: (context) => { liveFinalFlowContext = context; }, 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/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index c341360f14f..ef5dcf777e8 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"; @@ -92,6 +94,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 901f63709fa..9f14e47cebe 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -176,6 +176,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/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/dockerfile-custom-openclaw-model-reconcile.test.ts b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts new file mode 100644 index 00000000000..9b58043395d --- /dev/null +++ b/src/lib/onboard/dockerfile-custom-openclaw-model-reconcile.test.ts @@ -0,0 +1,309 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// 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"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { patchStagedDockerfile } from "./dockerfile-patch"; + +describe("custom OpenClaw Dockerfile model reconciliation", () => { + afterEach(() => { + 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( + 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 = embeddedCustomRouteProgram(fs.readFileSync(dockerfilePath, "utf8")); + 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", + 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: "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", + 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) => { + 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"); + 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"); + 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).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 = embeddedCustomRouteProgram(patched); + expect(embedded).toContain(".nemoclaw-custom-route-pending"); + const configPath = path.join(root, "openclaw.json"); + fs.writeFileSync( + configPath, + JSON.stringify({ + agents: { defaults: { model: { primary: "inference/baked-model" } } }, + models: { + providers: { + inference: { + models: [ + { + id: testCase.inheritedModelId, + name: `inference/${testCase.inheritedModelId}`, + contextWindow: 131_072, + maxTokens: 4_096, + }, + ], + }, + }, + }, + }), + ); + fs.chmodSync(configPath, 0o640); + 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: encodedModel, + NEMOCLAW_CUSTOM_ROUTE_LIMITS_B64: encodedLimits, + }, + }); + + 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", + ...testCase.expectedLimits, + }, + ], + }, + }, + }, + }); + const configBytes = fs.readFileSync(configPath); + 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 }); + } + }); + + 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 }); + } + }); + + 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 77fd399cbe0..fada002b88c 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -192,6 +192,166 @@ export interface PatchStagedDockerfileOptions { compatibleEndpointReasoning?: "true" | "false"; wslDashboardExposure?: boolean; rebuildPreservedEnv?: readonly PreservedEnvFile[]; + reconcileCustomOpenClawModel?: boolean; +} + +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), + -1, + ); + const finalUser = instructions + .slice(finalFromIndex + 1) + .reduce( + (last, instruction) => (/^USER(?:\s|$)/i.test(instruction.text) ? instruction : last), + null, + ); + 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"); + const primaryModelRef = model.startsWith("inference/") ? model : `inference/${model}`; + + const rendered = `${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 +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 + ).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: + 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 + 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") + 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") + 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() + os.fsync(marker_fd) + finally: + os.close(marker_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} +`; + 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 { @@ -704,6 +864,16 @@ export function patchStagedDockerfile( ); } } + if (options.reconcileCustomOpenClawModel) { + 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); return { dashboardRemoteBindPrepared }; 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..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,6 +355,98 @@ describe("final onboard flow runtime boundary", () => { expect(order).toEqual(["openclaw", "agent-forward", "policies"]); }); + it("waits for asynchronous route retirement after final verification", 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, + afterVerified: 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", + "set-default", + "verify", + "cleanup-start", + ]); + expect(harness.getSession().machine.state).toBe("post_verify"); + + releaseCleanup(); + await flow; + + expect(order).toEqual([ + "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 () => { const order: string[] = []; const harness = createRuntimeHarness(sessionAt("post_verify")); @@ -370,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({ @@ -378,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", @@ -415,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", @@ -444,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, @@ -458,6 +544,7 @@ describe("final onboard flow runtime boundary", () => { runtime: harness.boundary.getRuntime(), phases, recordRepairEvent: recorders.recordRepairEvent, + afterVerified, }); expect(first.session).toMatchObject({ @@ -465,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.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 cf60e40011d..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 { @@ -201,27 +202,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) | 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(); - 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 +337,6 @@ async function runFinalFlowPrerequisiteRepairs[]; recordRepairEvent: FinalFlowRepairEventRecorder; - afterPoliciesReady?(): void; onContextUpdated?(context: Context): void; }): Promise<{ context: Context; pause?: OnboardStatePauseResult }> { const entryIndex = options.phases.findIndex((phase) => phase.state === options.entryState); @@ -385,7 +392,6 @@ async function runFinalFlowPrerequisiteRepairs[]; recordRepairEvent: FinalFlowRepairEventRecorder; - afterPoliciesReady?(): void; + afterVerified?(): void | Promise; onContextUpdated?(context: Context): void; }) { const canonicalFlow = canonicalFinalFlowPhases(options.phases); @@ -430,7 +436,6 @@ export async function runFinalOnboardFlowSlice { }); }); + 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/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index 022d4bf06b6..075a37d0eba 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -787,6 +787,7 @@ describe("managed workload onboard orchestration", () => { fromDockerfile, preparedBuildContext, preResolvedBaseImageMetadata: resolutionMetadata, + model: "nvidia/selected-model", } as never; }); const resolveSandboxBuildPatch = vi.fn(async (input: Record) => { 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/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index cbeb580b180..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, @@ -685,7 +712,7 @@ describe("prepareSandboxCreateLaunchWithPrebuild", () => { agent: null, chatUiUrl: "", createArgs: ["--from", dockerfile, "--name", "demo"], - env: {}, + env: { NEMOCLAW_MODEL: "provider/generated-model" }, extraPlaceholderKeys: [], getDashboardForwardPort: () => "0", hermesDashboardState: disabledHermesDashboardState, diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index 7856fb6e33a..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, }); @@ -215,7 +217,10 @@ export async function prepareSandboxCreateLaunchWithPrebuild( sandboxName: input.sandboxName, }); return { - ...prepareSandboxCreateLaunch({ ...launchInput, createArgs: prebuild.createArgs }), + ...prepareSandboxCreateLaunch({ + ...launchInput, + createArgs: prebuild.createArgs, + }), prebuild, }; } 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 cc551bd820f..0fa9b7fc2d2 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; @@ -2631,6 +2664,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/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-config-io.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-config-io.test.ts index cb5c34944f6..c1fa187c6d8 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"; @@ -24,7 +25,10 @@ describe("runtime model override (#759)", () => { return extractShellFunctionFromSource(src, name); } - function runApplyModelOverride(env: Record = {}) { + 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 }); @@ -56,17 +60,28 @@ 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.fstatSync(configFd).mode & 0o777, + 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 0; }", + ...(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, @@ -75,23 +90,30 @@ 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 config = JSON.parse(fs.readFileSync(configPath, "utf-8")); - 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, hash, modes }; + 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", () => { - 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,20 +132,37 @@ 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.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); + }, + ); + 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..5e86f12897c 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"; @@ -17,19 +18,28 @@ const START_SCRIPT = path.join( interface RunReconcileOptions { /** - * Output the stubbed `openshell inference get --json` 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 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; + gatewayName?: string; + userId?: number; + useActualUser?: boolean; + symlink?: "config" | "hash" | "marker"; + configWritable?: boolean; + hashFailure?: boolean | "once"; + customRoutePending?: boolean | "directory" | "invalid"; + retireCustomRouteAfterProtectedCommands?: boolean; env?: Record; } @@ -52,26 +62,66 @@ 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, 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); + }, + 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(); const binDir = path.join(root, "bin"); fs.mkdirSync(binDir); const installStub = options.gatewayRawOutput !== undefined || options.gatewayModel !== undefined; if (installStub) { + const gatewayName = options.gatewayName ?? "nemoclaw"; const payload = 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 4 ] && [ "$3" = "-g" ] && [ "$4" = ${JSON.stringify(gatewayName)} ] || exit 64`, + options.gatewayDelaySeconds ? ` sleep ${options.gatewayDelaySeconds}` : " :", + ` printf '%b' ${JSON.stringify(payload)}`, + ` exit ${options.gatewayExitCode ?? 0}`, "fi", "exit 1", "", @@ -79,10 +129,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() { :; }", - 'run_openclaw_config_as_owner() { "$@"; }', - `ensure_mutable_openclaw_config_hash() { (cd ${JSON.stringify(openclawDir)} && sha256sum openclaw.json >.config-hash); }`, + options.useActualUser + ? extractShellFunction("run_openclaw_config_as_owner") + : 'run_openclaw_config_as_owner() { "$@"; }', + hashHelper, ].join("\n"); const fn = extractShellFunction("reconcile_agent_model_with_provider").replaceAll( "/sandbox", @@ -91,9 +156,23 @@ describe("agent identity reconciliation with provider (#3175)", () => { const wrapper = [ "#!/usr/bin/env bash", "set -euo pipefail", - "id() { echo 0; }", + ...(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', + ] + : []), + ...(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"); const script = path.join(root, "run.sh"); @@ -117,12 +196,20 @@ 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 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 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 }; + return { result, config, hash, expectedHash, customRoutePending }; } it("aligns agents.defaults.model.primary to inference provider's first model when they drift", () => { @@ -145,7 +232,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" } }, }, @@ -161,7 +248,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", () => { @@ -204,6 +291,128 @@ 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("protects startup and smoke boundaries before host-observed receipt retirement", () => { + 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", + retireCustomRouteAfterProtectedCommands: 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("preserves an explicit model override when the live gateway reports a conflicting model", () => { const initial = { agents: { @@ -233,7 +442,103 @@ 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.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, + }, + ], + }, + }, + }, + }, + { + gatewayModel: "nvidia/nemotron-3-super-120b-a12b", + 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("preserves a later model switch when the live gateway probe is unavailable", () => { + 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, expectedHash } = runReconcile(switched); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(config).toEqual(switched); + expect(hash).toBe(expectedHash); + }); + + 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", + 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( { agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, @@ -241,7 +546,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, + }, + ], }, }, }, @@ -259,38 +571,30 @@ 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"); }); - it("patches primary AND models[0] to the live gateway model when both file fields are stale", () => { - const { result, config, hash } = runReconcile( + it("queries the selected nondefault OpenShell gateway", () => { + const { result, config } = runReconcile( { - agents: { defaults: { model: { primary: "inference/nvidia-routed" } } }, + agents: { defaults: { model: { primary: "inference/old-model" } } }, models: { providers: { inference: { api: "openai-completions", - models: [{ id: "nvidia-routed", name: "inference/nvidia-routed" }], + models: [{ id: "old-model", name: "inference/old-model" }], }, }, }, }, - { gatewayModel: "nvidia/nemotron-3-super-120b-a12b" }, + { gatewayModel: "new-model", gatewayName: "nemoclaw-18081" }, ); 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"); + expect(config.agents.defaults.model.primary).toBe("inference/new-model"); }); it("accepts an inference-qualified gateway model without double-prefixing", () => { @@ -319,14 +623,21 @@ 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: { 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,7 +647,76 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(result.status).toBe(0); expect(config.agents.defaults.model.primary).toBe("inference/nvidia/synced"); - expect(hash).toBe("oldhash\n"); + expect(config.models.providers.inference.models[0]).toMatchObject({ + contextWindow: 131072, + maxTokens: 4096, + }); + expect(hash).toBe(expectedHash); + }); + + 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("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", () => { @@ -458,12 +838,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 +859,134 @@ 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, hash, or receipt 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"); + }); + + 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); }); }); diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 6c336a5f6ea..136692af18d 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -7,8 +7,49 @@ // 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 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 4b09974ae32..fee53051f9a 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -49,14 +49,21 @@ import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import { approveOpenClawAdminScope } from "./openclaw-admin-scope.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, + BAKED_STALE_CONTEXT_WINDOW, + BAKED_STALE_MAX_TOKENS, classifyOpenClawPostSwitchInferenceAttempt, MOCK_BASELINE_API_KEY, MOCK_BASELINE_MODEL, mockBaselineInference, parseOpenClawGatewayModelRun, + stageNonRootCustomOpenClawImageDockerfile, } from "./openclaw-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_MODEL, @@ -109,7 +116,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; + }>; } >; }; @@ -161,7 +173,7 @@ function proveMockBaselineAuthentication( ): Promise { return baseline ? proveSelectedMockBaselineAuthentication(baseline, sandbox, home, artifacts) - : Promise.resolve(expect(baseline).toBeUndefined()); + : Promise.resolve(); } async function proveSelectedMockBaselineAuthentication( @@ -463,8 +475,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); @@ -515,7 +530,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(); @@ -540,7 +554,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); @@ -588,7 +601,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( @@ -601,7 +613,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 { @@ -928,6 +939,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", @@ -945,9 +957,11 @@ 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 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", + "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", @@ -956,11 +970,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", @@ -983,6 +992,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 @@ -993,6 +1003,16 @@ test( ); const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-switch-home-")); + 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}`, @@ -1036,6 +1056,12 @@ test( cwd: REPO_ROOT, env: commandEnv(home, { ...baseline.env, + ...(customImageDockerfile === null + ? {} + : { + NEMOCLAW_FROM_DOCKERFILE: customImageDockerfile, + NEMOCLAW_SANDBOX_PREBUILD: "1", + }), NEMOCLAW_RECREATE_SANDBOX: "1", }), redactionValues, @@ -1053,6 +1079,89 @@ 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"], + { + 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( + 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, + [ + "openclaw", + "infer", + "model", + "inspect", + "--model", + `inference/${baselineModel}`, + "--json", + ], + { + artifactName: "inspect-effective-model-after-custom-image-startup", + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }, + ); + 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", + 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"); @@ -1114,6 +1223,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); @@ -1163,6 +1287,7 @@ test( installCompleted: install.exitCode === 0, inferenceSetCompleted: switchResult.exitCode === 0, gatewayRestartExpected: true, + switchedModelSurvivedSandboxRestart: true, gatewayPidStable, routeChecked: true, configChecked: true, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index d7e60cb2de3..dbbe9a7ef27 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -835,6 +835,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", "test/security/admin-approval-helper.test.ts", "test/e2e/support/hosted-inference.test.ts" diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index 9981402d2be..702ced1e871 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -18,8 +18,10 @@ describe("inference-switch catalogue boundary", () => { expect(openclaw).toMatchObject({ profile: "standard", testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + gatewayRuntimes: ["docker", "podman"], environment: { NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_CUSTOM_IMAGE_RUNTIME: "docker", NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", }, }); 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 }); + } + }); +}); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index e0eb4ae97b8..17d7a8ffceb 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -159,6 +159,7 @@ describe("E2E workflow plan", () => { ]); expect(plan.testMatrix).toEqual([]); expect(catalogueIds).toHaveLength(46); + expect(catalogueIds).toContain("openclaw-inference-switch"); expect(catalogueIds).not.toEqual( expect.arrayContaining([ "bootstrap-install-smoke", @@ -810,6 +811,38 @@ describe("E2E workflow plan", () => { }, ); + 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", + "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", + ); + }); + + 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/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 ?? diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 2fefa087603..3e425612156 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1172,6 +1172,16 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: true, 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", + "src/lib/onboard/sandbox-dockerfile-patch-flow.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", "scripts/patch-openclaw-device-self-approval.mts", "test/e2e/live/openclaw-admin-scope.ts", @@ -1188,6 +1198,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", }, }),