From 32d8dd8eb5917391de8d549d721838eb92d09e01 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 23 May 2026 09:35:57 -0700 Subject: [PATCH 1/6] fix(cli): complete onboarding after final verification --- src/lib/onboard.ts | 2 ++ .../machine/handlers/finalization.test.ts | 33 +++++++++++++++---- .../onboard/machine/handlers/finalization.ts | 11 ++++--- src/lib/onboard/runtime-boundary.ts | 10 ++++++ 4 files changed, 46 insertions(+), 10 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 67b359821c6..d3fe2643a9d 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -6732,6 +6732,7 @@ const recordStepSkipped = onboardRuntimeBoundary.recordStepSkipped.bind(onboardR const recordStepFailed = onboardRuntimeBoundary.recordStepFailed.bind(onboardRuntimeBoundary); const recordStateSkipped = onboardRuntimeBoundary.recordStateSkipped.bind(onboardRuntimeBoundary); const recordRepairEvent = onboardRuntimeBoundary.recordRepairEvent.bind(onboardRuntimeBoundary); +const recordPostVerifyStarted = onboardRuntimeBoundary.recordPostVerifyStarted.bind(onboardRuntimeBoundary); const recordSessionComplete = onboardRuntimeBoundary.recordSessionComplete.bind(onboardRuntimeBoundary); const ONBOARD_STEP_INDEX: Record = { @@ -7446,6 +7447,7 @@ async function onboard(opts: OnboardOptions = {}): Promise { migratedLegacyKeys, deps: { ensureAgentDashboardForward, + recordPostVerifyStarted, recordSessionComplete, toSessionUpdates: (updates) => toSessionUpdates(updates as Parameters[0]), removeLegacyCredentialsFile, diff --git a/src/lib/onboard/machine/handlers/finalization.test.ts b/src/lib/onboard/machine/handlers/finalization.test.ts index 5ffcd4547a3..e3b44c10de4 100644 --- a/src/lib/onboard/machine/handlers/finalization.test.ts +++ b/src/lib/onboard/machine/handlers/finalization.test.ts @@ -13,6 +13,7 @@ type VerificationResult = { ok: boolean }; function createDeps(overrides: Partial["deps"]> = {}) { const calls = { ensureAgentDashboard: vi.fn(() => 18789), + postVerify: vi.fn(async () => createSession({ machine: { version: 1, state: "post_verify", stateEnteredAt: null, revision: 1 } })), complete: vi.fn(async () => createSession({ status: "complete" })), removeLegacy: vi.fn(), cleanupHost: vi.fn(), @@ -29,6 +30,7 @@ function createDeps(overrides: Partial) => updates as SessionUpdates, removeLegacyCredentialsFile: calls.removeLegacy, @@ -69,6 +71,13 @@ describe("handleFinalizationState", () => { const result = await handleFinalizationState(baseOptions(deps)); + expect(calls.cleanupHost).toHaveBeenCalledOnce(); + expect(calls.recoverProcesses).toHaveBeenCalledWith("my-assistant", { quiet: true }); + expect(calls.buildChain).toHaveBeenCalledWith("http://127.0.0.1:18789"); + expect(calls.verify).toHaveBeenCalledWith("my-assistant", { port: 18789 }); + expect(calls.log).toHaveBeenCalledWith(" ✓ verified"); + expect(calls.dashboard).toHaveBeenCalledWith("my-assistant", "model", "provider", null, null); + expect(calls.postVerify).toHaveBeenCalledOnce(); expect(calls.complete).toHaveBeenCalledWith({ sandboxName: "my-assistant", provider: "provider", @@ -76,12 +85,6 @@ describe("handleFinalizationState", () => { hermesAuthMethod: null, hermesToolGateways: [], }); - expect(calls.cleanupHost).toHaveBeenCalledOnce(); - expect(calls.recoverProcesses).toHaveBeenCalledWith("my-assistant", { quiet: true }); - expect(calls.buildChain).toHaveBeenCalledWith("http://127.0.0.1:18789"); - expect(calls.verify).toHaveBeenCalledWith("my-assistant", { port: 18789 }); - expect(calls.log).toHaveBeenCalledWith(" ✓ verified"); - expect(calls.dashboard).toHaveBeenCalledWith("my-assistant", "model", "provider", null, null); expect(result.verificationDiagnostics).toEqual([" ✓ verified"]); }); @@ -92,9 +95,27 @@ describe("handleFinalizationState", () => { await handleFinalizationState({ ...baseOptions(deps), agent }); expect(calls.ensureAgentDashboard).toHaveBeenCalledWith("my-assistant", agent); + expect(calls.complete).toHaveBeenCalled(); + expect(calls.ensureAgentDashboard.mock.invocationCallOrder[0]).toBeLessThan( + calls.complete.mock.invocationCallOrder[0], + ); expect(calls.dashboard).toHaveBeenCalledWith("my-assistant", "model", "provider", null, agent); }); + it("does not complete the session when deployment verification fails", async () => { + const { deps, calls } = createDeps({ + verifyDeployment: vi.fn(async () => { + throw new Error("verification failed"); + }), + }); + + await expect(handleFinalizationState(baseOptions(deps))).rejects.toThrow("verification failed"); + + expect(calls.postVerify).toHaveBeenCalledOnce(); + expect(calls.complete).not.toHaveBeenCalled(); + expect(calls.dashboard).not.toHaveBeenCalled(); + }); + it("removes legacy credentials only when all staged values migrated", async () => { const { deps, calls } = createDeps(); diff --git a/src/lib/onboard/machine/handlers/finalization.ts b/src/lib/onboard/machine/handlers/finalization.ts index 6684ee10db0..5f17d119722 100644 --- a/src/lib/onboard/machine/handlers/finalization.ts +++ b/src/lib/onboard/machine/handlers/finalization.ts @@ -15,6 +15,7 @@ export interface FinalizationStateOptions; deps: { ensureAgentDashboardForward(sandboxName: string, agent: NonNullable): number; + recordPostVerifyStarted(): Promise; recordSessionComplete(updates: SessionUpdates): Promise; toSessionUpdates(updates: Record): SessionUpdates; removeLegacyCredentialsFile(): void; @@ -56,10 +57,6 @@ export async function handleFinalizationState): Promise { if (agent) deps.ensureAgentDashboardForward(sandboxName, agent as NonNullable); - const session = await deps.recordSessionComplete( - deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), - ); - const allStagedMigrated = stagedLegacyKeys.length > 0 && stagedLegacyKeys.every((key) => migratedLegacyKeys.has(key)); const unmigratedLegacyKeys = stagedLegacyKeys.filter((key) => !migratedLegacyKeys.has(key)); @@ -79,6 +76,8 @@ export async function handleFinalizationState { + const runtime = this.getRuntime(); + const current = await runtime.session(); + if (current.machine.state === "finalizing") { + return runtime.transition("post_verify"); + } + return current; + } + async recordSessionComplete(updates: SessionUpdates = {}): Promise { const runtime = this.getRuntime(); const current = await runtime.session(); From ee4330bc0daf86af03c30854ce8a99c42d00db3a Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 23 May 2026 09:45:26 -0700 Subject: [PATCH 2/6] fix(cli): harden extracted onboard helpers Signed-off-by: Carlos Villela --- src/lib/onboard.ts | 26 ++++++++--- src/lib/onboard/known-hosts.ts | 14 +++++- src/lib/onboard/messaging-credentials.ts | 3 +- src/lib/onboard/openshell-version.ts | 2 +- src/lib/onboard/web-search-flow.ts | 3 +- test/credential-rotation.test.ts | 6 +-- test/onboard-brave-validation.test.ts | 56 ++++++++++++++++++++++++ test/onboard-openshell-version.test.ts | 20 +++++++++ test/ssh-known-hosts.test.ts | 14 +++--- 9 files changed, 123 insertions(+), 21 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index d3fe2643a9d..7be42f51367 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -532,6 +532,7 @@ const DIM = USE_COLOR ? "\x1b[2m" : ""; const RESET = USE_COLOR ? "\x1b[0m" : ""; let OPENSHELL_BIN: string | null = null; const GATEWAY_NAME = "nemoclaw"; +const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "0.0.44"; const OPENCLAW_LAUNCH_AGENT_PLIST = "~/Library/LaunchAgents/ai.openclaw.gateway.plist"; const BRAVE_SEARCH_HELP_URL = "https://brave.com/search/api/"; @@ -1407,7 +1408,7 @@ function getOpenShellDockerSupervisorImage(versionOutput: string | null = null): if (shouldUseOpenshellDevChannel() || isOpenshellDevVersion(versionOutput)) { return "ghcr.io/nvidia/openshell/supervisor:dev"; } - const supportedVersion = installedVersion ?? getBlueprintMaxOpenshellVersion() ?? "0.0.39"; + const supportedVersion = installedVersion ?? getBlueprintMaxOpenshellVersion() ?? SUPPORTED_OPENSHELL_FALLBACK_VERSION; return `ghcr.io/nvidia/openshell/supervisor:${supportedVersion}`; } @@ -2644,7 +2645,9 @@ async function startDockerDriverGateway({ exitOnFailure = true, skipSandboxBridg } if (!gatewayBin) { console.error(" OpenShell Docker-driver gateway binary not found."); - console.error(" Install OpenShell v0.0.39, or set NEMOCLAW_OPENSHELL_GATEWAY_BIN."); + console.error( + ` Install OpenShell v${SUPPORTED_OPENSHELL_FALLBACK_VERSION}, or set NEMOCLAW_OPENSHELL_GATEWAY_BIN.`, + ); if (exitOnFailure) process.exit(1); throw new Error("OpenShell gateway binary not found"); } @@ -2666,10 +2669,19 @@ async function startDockerDriverGateway({ exitOnFailure = true, skipSandboxBridg fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); const logPath = path.join(stateDir, "openshell-gateway.log"); - // The gateway state directory is NemoClaw-owned; creating it before opening - // the append-only log is intentional and safe for this local runtime file. - const outFd = fs.openSync(logPath, "a", 0o600); // codeql[js/file-system-race] - const errFd = fs.openSync(logPath, "a", 0o600); // codeql[js/file-system-race] + const appendNoFollow = + fs.constants.O_APPEND | + fs.constants.O_CREAT | + fs.constants.O_WRONLY | + fs.constants.O_NOFOLLOW; + let logFd: number; + try { + logFd = fs.openSync(logPath, appendNoFollow, 0o600); + } catch (error) { + console.error(` Failed to open OpenShell Docker-driver gateway log '${logPath}': ${String(error)}`); + if (exitOnFailure) process.exit(1); + throw error; + } console.log(" Starting OpenShell Docker-driver gateway..."); console.log(` Gateway log: ${logPath}`); const launch = gatewayLaunch ?? { @@ -2682,7 +2694,7 @@ async function startDockerDriverGateway({ exitOnFailure = true, skipSandboxBridg dockerDriverGatewayLaunch.prepareAndLogDockerDriverGatewayLaunch(launch); const child = spawn(launch.command, launch.args, { detached: true, - stdio: ["ignore", outFd, errFd], + stdio: ["ignore", logFd, logFd], env: launch.env, }); const childExit = trackChildExit(child); // #3111 zombie-safe liveness diff --git a/src/lib/onboard/known-hosts.ts b/src/lib/onboard/known-hosts.ts index 0b3a4cb6ac7..7453d192b26 100644 --- a/src/lib/onboard/known-hosts.ts +++ b/src/lib/onboard/known-hosts.ts @@ -5,14 +5,24 @@ * Remove known_hosts lines whose host field contains an openshell-* entry. * Preserves blank lines and comments. Returns the cleaned string. */ +function normalizeKnownHostToken(host: string): string { + const bracketed = host.match(/^\[([^\]]+)\](?::\d+)?$/); + if (bracketed) return bracketed[1]; + return host.replace(/:\d+$/, ""); +} + export function pruneKnownHostsEntries(contents: string): string { return contents .split("\n") .filter((line) => { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) return true; - const hostField = trimmed.split(/\s+/)[0]; - return !hostField.split(",").some((host) => host.startsWith("openshell-")); + const fields = trimmed.split(/\s+/); + const hostField = fields[0]?.startsWith("@") ? (fields[1] ?? "") : fields[0]; + return !hostField + .split(",") + .map(normalizeKnownHostToken) + .some((host) => host.startsWith("openshell-")); }) .join("\n"); } diff --git a/src/lib/onboard/messaging-credentials.ts b/src/lib/onboard/messaging-credentials.ts index fff0e7107b2..cb03f31dfc3 100644 --- a/src/lib/onboard/messaging-credentials.ts +++ b/src/lib/onboard/messaging-credentials.ts @@ -67,10 +67,9 @@ export function detectMessagingCredentialRotation( const storedHashes = sb?.providerCredentialHashes || {}; const changedProviders = []; for (const { name, envKey, token } of tokenDefs) { - if (!token) continue; const storedHash = storedHashes[envKey]; if (!storedHash) continue; - if (storedHash !== hashCredential(token)) { + if (!token || storedHash !== hashCredential(token)) { changedProviders.push(name); } } diff --git a/src/lib/onboard/openshell-version.ts b/src/lib/onboard/openshell-version.ts index e45a279130c..6de5273ff72 100644 --- a/src/lib/onboard/openshell-version.ts +++ b/src/lib/onboard/openshell-version.ts @@ -58,7 +58,7 @@ function getBlueprintVersionField(field: string, rootDir = ROOT): string | null const value = parsed && parsed[field]; if (typeof value !== "string") return null; const trimmed = value.trim(); - if (!/^[0-9]+\.[0-9]+\.[0-9]+/.test(trimmed)) return null; + if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(trimmed)) return null; return trimmed; } catch { return null; diff --git a/src/lib/onboard/web-search-flow.ts b/src/lib/onboard/web-search-flow.ts index 77004827042..3aaa002d5f8 100644 --- a/src/lib/onboard/web-search-flow.ts +++ b/src/lib/onboard/web-search-flow.ts @@ -179,7 +179,8 @@ export function createWebSearchFlowHelpers(deps: WebSearchFlowDeps): WebSearchFl } if (deps.isNonInteractive()) { - const braveApiKey = normalizeCredentialValue(process.env[BRAVE_API_KEY_ENV]); + const braveApiKey = + getCredential(BRAVE_API_KEY_ENV) || normalizeCredentialValue(process.env[BRAVE_API_KEY_ENV]); if (!braveApiKey) { return null; } diff --git a/test/credential-rotation.test.ts b/test/credential-rotation.test.ts index 6122584059d..8c89c7ca2a0 100644 --- a/test/credential-rotation.test.ts +++ b/test/credential-rotation.test.ts @@ -182,7 +182,7 @@ describe("credential rotation detection", () => { vi.restoreAllMocks(); }); - it("skips providers with null tokens", () => { + it("treats removed tokens as changed providers", () => { const hash = hashCredentialOrThrow("old-token"); vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "test-sandbox", @@ -193,8 +193,8 @@ describe("credential rotation detection", () => { { name: "test-telegram-bridge", envKey: "TELEGRAM_BOT_TOKEN", token: null }, ]); - expect(result.changed).toBe(false); - expect(result.changedProviders).toEqual([]); + expect(result.changed).toBe(true); + expect(result.changedProviders).toEqual(["test-telegram-bridge"]); vi.restoreAllMocks(); }); diff --git a/test/onboard-brave-validation.test.ts b/test/onboard-brave-validation.test.ts index 1f5f4b13785..054c532e644 100644 --- a/test/onboard-brave-validation.test.ts +++ b/test/onboard-brave-validation.test.ts @@ -314,6 +314,62 @@ const { loadAgent } = require(${agentDefsPath}); } }); + it("uses a saved Brave credential in non-interactive mode", () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-brave-saved-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "configure-web-search-saved.js"); + const outputPath = path.join(tmpDir, "outcome.json"); + const onboardPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "onboard.js")); + const credentialsPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "credentials", "store.js")); + setupBraveCurlShim(fakeBin, { status: "200", body: '{"web":{"results":[]}}' }); + fs.writeFileSync( + scriptPath, + ` +const fs = require("node:fs"); +const actualCredentials = require(${credentialsPath}); +const mockedCredentials = { + ...actualCredentials, + getCredential: (key) => (key === "BRAVE_API_KEY" ? "saved-brave-key" : actualCredentials.getCredential(key)), +}; +require.cache[require.resolve(${credentialsPath})] = { + id: require.resolve(${credentialsPath}), + filename: require.resolve(${credentialsPath}), + loaded: true, + exports: mockedCredentials, +}; +delete process.env.BRAVE_API_KEY; +process.env.NEMOCLAW_NON_INTERACTIVE = "1"; +const { configureWebSearch } = require(${onboardPath}); +(async () => { + const result = await configureWebSearch(null); + fs.writeFileSync(${JSON.stringify(outputPath)}, JSON.stringify({ result, braveKey: process.env.BRAVE_API_KEY || null })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`, + ); + + try { + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + }, + }); + expect(result.status).toBe(0); + const payload = JSON.parse(fs.readFileSync(outputPath, "utf-8")); + expect(payload.result).toEqual({ fetchEnabled: true }); + expect(payload.braveKey).toBe("saved-brave-key"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + it("skips Brave Web Search and returns null when key validation hits HTTP 429", () => { const { exitCode, payload } = runConfigureWebSearch({ status: "429", diff --git a/test/onboard-openshell-version.test.ts b/test/onboard-openshell-version.test.ts index 306d93a59ce..4ed31d9afdc 100644 --- a/test/onboard-openshell-version.test.ts +++ b/test/onboard-openshell-version.test.ts @@ -171,6 +171,26 @@ describe("OpenShell version helpers", () => { } }); + it("rejects OpenShell blueprint version constraints with suffixes", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-blueprint-bad-openshell-version-")); + const blueprintDir = path.join(tmpDir, "nemoclaw-blueprint"); + fs.mkdirSync(blueprintDir, { recursive: true }); + fs.writeFileSync( + path.join(blueprintDir, "blueprint.yaml"), + [ + 'version: "0.1.0"', + 'min_openshell_version: "0.0.44-dev"', + 'max_openshell_version: "0.0.44-dev"', + ].join("\n"), + ); + try { + expect(getBlueprintMinOpenshellVersion(tmpDir)).toBe(null); + expect(getBlueprintMaxOpenshellVersion(tmpDir)).toBe(null); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + it("returns null for missing or absent max_openshell_version", () => { expect(getBlueprintMaxOpenshellVersion(path.join(os.tmpdir(), `missing-${Date.now()}`))).toBe( null, diff --git a/test/ssh-known-hosts.test.ts b/test/ssh-known-hosts.test.ts index b85f9c94a3f..6afc3818b9c 100644 --- a/test/ssh-known-hosts.test.ts +++ b/test/ssh-known-hosts.test.ts @@ -116,10 +116,14 @@ describe("pruneKnownHostsEntries", () => { "[openshell-sandbox]:2222 ssh-ed25519 AAAA...", "github.com ssh-rsa AAAA...", ].join("\n"); - // The host field starts with "[openshell-" which starts with "[" - // not "openshell-", so this line would be preserved by current logic. - // Documenting current behavior — bracket-prefixed entries are kept. - const result = pruneKnownHostsEntries(input); - expect(result).toBe(input); + expect(pruneKnownHostsEntries(input)).toBe("github.com ssh-rsa AAAA..."); + }); + + it("removes marked openshell host entries", () => { + const input = [ + "@cert-authority openshell-sandbox ssh-ed25519 AAAA...", + "github.com ssh-rsa AAAA...", + ].join("\n"); + expect(pruneKnownHostsEntries(input)).toBe("github.com ssh-rsa AAAA..."); }); }); From 57cfff6ab4993bf59fa6d3fda7f9d76822620ed8 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 23 May 2026 09:48:13 -0700 Subject: [PATCH 3/6] fix(cli): verify model-router pid ownership before restart Signed-off-by: Carlos Villela --- src/lib/onboard/model-router.test.ts | 41 +++++++++++++++++++++++++++ src/lib/onboard/model-router.ts | 42 ++++++++++++++++++++++++++-- 2 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 src/lib/onboard/model-router.test.ts diff --git a/src/lib/onboard/model-router.test.ts b/src/lib/onboard/model-router.test.ts new file mode 100644 index 00000000000..589765badef --- /dev/null +++ b/src/lib/onboard/model-router.test.ts @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { + doesModelRouterProcessOwnPort, + isModelRouterCommandLineForPort, +} from "../../../dist/lib/onboard/model-router"; + +describe("model-router process ownership checks", () => { + it("recognizes model-router proxy command lines for the expected port", () => { + expect( + isModelRouterCommandLineForPort( + ["/tmp/router/bin/model-router", "proxy", "--host", "0.0.0.0", "--port", "44123"], + 44123, + ), + ).toBe(true); + expect( + isModelRouterCommandLineForPort( + ["/tmp/router/bin/model-router", "proxy", "--host", "0.0.0.0", "--port=44123"], + 44123, + ), + ).toBe(true); + }); + + it("rejects reused PIDs that do not look like the expected model-router proxy", () => { + expect( + doesModelRouterProcessOwnPort(1234, 44123, { + isRunning: () => true, + readCommandLine: () => ["/usr/bin/sleep", "999"], + }), + ).toBe(false); + expect( + doesModelRouterProcessOwnPort(1234, 44123, { + isRunning: () => true, + readCommandLine: () => ["/tmp/router/bin/model-router", "proxy", "--port", "44124"], + }), + ).toBe(false); + }); +}); diff --git a/src/lib/onboard/model-router.ts b/src/lib/onboard/model-router.ts index ec35e060634..52634211bb8 100644 --- a/src/lib/onboard/model-router.ts +++ b/src/lib/onboard/model-router.ts @@ -116,6 +116,43 @@ function isProcessRunning(pid: number | null | undefined): boolean { } } +export function isModelRouterCommandLineForPort(args: readonly string[], port: number): boolean { + const commandName = path.basename(args[0] || ""); + if (commandName !== "model-router") return false; + if (!args.includes("proxy")) return false; + return args.some((arg, index) => { + if (arg === "--port") return args[index + 1] === String(port); + return arg === `--port=${String(port)}`; + }); +} + +function readProcessCommandLine(pid: number): string[] | null { + try { + return fs + .readFileSync(`/proc/${pid}/cmdline`, "utf8") + .split("\0") + .filter(Boolean); + } catch { + return null; + } +} + +export function doesModelRouterProcessOwnPort( + pid: number | null | undefined, + port: number, + deps: { + isRunning?: (pid: number | null | undefined) => boolean; + readCommandLine?: (pid: number) => string[] | null; + } = {}, +): boolean { + if (!Number.isInteger(pid) || Number(pid) <= 0) return false; + const isRunning = deps.isRunning ?? isProcessRunning; + if (!isRunning(pid)) return false; + const readCommandLine = deps.readCommandLine ?? readProcessCommandLine; + const args = readCommandLine(Number(pid)); + return Array.isArray(args) && isModelRouterCommandLineForPort(args, port); +} + async function stopModelRouterProcess(pid: number, port: number): Promise { try { process.kill(pid, "SIGTERM"); @@ -486,15 +523,16 @@ export async function reconcileModelRouter(): Promise { const recordedCredentialHash = session?.routerCredentialHash ?? null; if (await isRouterHealthy(routerPort)) { + const recordedProcessOwnsRouter = doesModelRouterProcessOwnPort(recordedPid, routerPort); if ( routerCredentialHash && recordedCredentialHash === routerCredentialHash && - isProcessRunning(recordedPid) + recordedProcessOwnsRouter ) { console.log(` ✓ Model router is already healthy on port ${routerPort}`); return; } - if (isProcessRunning(recordedPid)) { + if (recordedProcessOwnsRouter) { console.log(" Restarting model router with updated credentials..."); await stopModelRouterProcess(requireValue(recordedPid, "Expected recorded router PID"), routerPort); } else { From 1912d83b0ada94f2617b0b11416e59d42be5766d Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 23 May 2026 10:24:27 -0700 Subject: [PATCH 4/6] fix(cli): resolve onboard follow-up review feedback Signed-off-by: Carlos Villela --- src/lib/onboard.ts | 24 +---- .../onboard/docker-driver-gateway-launch.ts | 35 ++++++- src/lib/onboard/model-router-process.ts | 75 ++++++++++++++ src/lib/onboard/model-router.test.ts | 12 ++- src/lib/onboard/model-router.ts | 97 ++----------------- src/lib/onboard/openshell-version.ts | 2 + 6 files changed, 132 insertions(+), 113 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 7be42f51367..25b7a98c010 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -107,7 +107,7 @@ const crypto = require("node:crypto"); const fs = require("fs"); const os = require("os"); const path = require("path"); -const { spawn, spawnSync } = require("child_process"); +const { spawnSync } = require("child_process"); const pRetry = require("p-retry"); /** Strip ANSI escape sequences before printing process output to the terminal. @@ -343,6 +343,7 @@ const { getBlueprintMinOpenshellVersion, getInstalledOpenshellVersion, isOpenshellDevVersion, + SUPPORTED_OPENSHELL_FALLBACK_VERSION, shouldAllowOpenshellAboveBlueprintMax, shouldUseOpenshellDevChannel, versionGte, @@ -532,7 +533,6 @@ const DIM = USE_COLOR ? "\x1b[2m" : ""; const RESET = USE_COLOR ? "\x1b[0m" : ""; let OPENSHELL_BIN: string | null = null; const GATEWAY_NAME = "nemoclaw"; -const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "0.0.44"; const OPENCLAW_LAUNCH_AGENT_PLIST = "~/Library/LaunchAgents/ai.openclaw.gateway.plist"; const BRAVE_SEARCH_HELP_URL = "https://brave.com/search/api/"; @@ -2669,19 +2669,7 @@ async function startDockerDriverGateway({ exitOnFailure = true, skipSandboxBridg fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); const logPath = path.join(stateDir, "openshell-gateway.log"); - const appendNoFollow = - fs.constants.O_APPEND | - fs.constants.O_CREAT | - fs.constants.O_WRONLY | - fs.constants.O_NOFOLLOW; - let logFd: number; - try { - logFd = fs.openSync(logPath, appendNoFollow, 0o600); - } catch (error) { - console.error(` Failed to open OpenShell Docker-driver gateway log '${logPath}': ${String(error)}`); - if (exitOnFailure) process.exit(1); - throw error; - } + const logFd = dockerDriverGatewayLaunch.openDockerDriverGatewayLog(logPath, { exitOnFailure }); console.log(" Starting OpenShell Docker-driver gateway..."); console.log(` Gateway log: ${logPath}`); const launch = gatewayLaunch ?? { @@ -2692,11 +2680,7 @@ async function startDockerDriverGateway({ exitOnFailure = true, skipSandboxBridg processGatewayBin: gatewayBin, }; dockerDriverGatewayLaunch.prepareAndLogDockerDriverGatewayLaunch(launch); - const child = spawn(launch.command, launch.args, { - detached: true, - stdio: ["ignore", logFd, logFd], - env: launch.env, - }); + const child = dockerDriverGatewayLaunch.spawnDockerDriverGateway(launch, logFd); const childExit = trackChildExit(child); // #3111 zombie-safe liveness child.unref(); const childPid = child.pid ?? 0; diff --git a/src/lib/onboard/docker-driver-gateway-launch.ts b/src/lib/onboard/docker-driver-gateway-launch.ts index 21eb2fb50d2..bf7155c64ee 100644 --- a/src/lib/onboard/docker-driver-gateway-launch.ts +++ b/src/lib/onboard/docker-driver-gateway-launch.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; +import { execFileSync, spawn, type ChildProcess } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; @@ -31,6 +31,39 @@ export type DockerDriverGatewayRuntimeIdentity = { identityGatewayBin: string | null; }; +export function openDockerDriverGatewayLog( + logPath: string, + options: { exitOnFailure?: boolean } = {}, +): number { + const appendNoFollow = + fs.constants.O_APPEND | + fs.constants.O_CREAT | + fs.constants.O_WRONLY | + fs.constants.O_NOFOLLOW; + try { + return fs.openSync(logPath, appendNoFollow, 0o600); + } catch (error) { + console.error(` Failed to open OpenShell Docker-driver gateway log '${logPath}': ${String(error)}`); + if (options.exitOnFailure) process.exit(1); + throw error; + } +} + +export function spawnDockerDriverGateway( + launch: DockerDriverGatewayLaunch, + logFd: number, +): ChildProcess { + try { + return spawn(launch.command, launch.args, { + detached: true, + stdio: ["ignore", logFd, logFd], + env: launch.env, + }); + } finally { + fs.closeSync(logFd); + } +} + type BuildGatewayLaunchOptions = { gatewayBin: string; gatewayEnv: Record; diff --git a/src/lib/onboard/model-router-process.ts b/src/lib/onboard/model-router-process.ts index b9f73fb57d6..4d653822774 100644 --- a/src/lib/onboard/model-router-process.ts +++ b/src/lib/onboard/model-router-process.ts @@ -1,11 +1,24 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; import * as http from "node:http"; +import path from "node:path"; import type { Session } from "../state/onboard-session"; export const ROUTER_HEALTH_TIMEOUT_MS = 3000; +export type ModelRouterProcessOwnershipDeps = { + isRunning?: (pid: number | null | undefined) => boolean; + readCommandLine?: (pid: number) => string[] | null; +}; + +type ModelRouterCommandLineReaderDeps = { + readProcCommandLine?: (pid: number) => string[] | null; + readPsCommandLine?: (pid: number) => string[] | null; +}; + export async function isRouterHealthy( port: number, timeoutMs = ROUTER_HEALTH_TIMEOUT_MS, @@ -40,6 +53,68 @@ export function isProcessRunning(pid: number | null | undefined): boolean { } } +export function isModelRouterCommandLineForPort(args: readonly string[], port: number): boolean { + const commandName = path.basename(args[0] || ""); + if (commandName !== "model-router") return false; + if (!args.includes("proxy")) return false; + return args.some((arg, index) => { + if (arg === "--port") return args[index + 1] === String(port); + return arg === `--port=${String(port)}`; + }); +} + +function splitCommandLine(commandLine: string): string[] | null { + const args = commandLine.trim().split(/\s+/).filter(Boolean); + return args.length > 0 ? args : null; +} + +function readProcCommandLine(pid: number): string[] | null { + try { + return fs + .readFileSync(`/proc/${pid}/cmdline`, "utf8") + .split("\0") + .filter(Boolean); + } catch { + return null; + } +} + +function readPsCommandLine(pid: number): string[] | null { + try { + const output = execFileSync("ps", ["-p", String(pid), "-o", "args="], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 2_000, + }); + return splitCommandLine(output); + } catch { + return null; + } +} + +export function readModelRouterProcessCommandLine( + pid: number, + deps: ModelRouterCommandLineReaderDeps = {}, +): string[] | null { + return ( + (deps.readProcCommandLine ?? readProcCommandLine)(pid) ?? + (deps.readPsCommandLine ?? readPsCommandLine)(pid) + ); +} + +export function doesModelRouterProcessOwnPort( + pid: number | null | undefined, + port: number, + deps: ModelRouterProcessOwnershipDeps = {}, +): boolean { + if (!Number.isInteger(pid) || Number(pid) <= 0) return false; + const isRunning = deps.isRunning ?? isProcessRunning; + if (!isRunning(pid)) return false; + const readCommandLine = deps.readCommandLine ?? readModelRouterProcessCommandLine; + const args = readCommandLine(Number(pid)); + return Array.isArray(args) && isModelRouterCommandLineForPort(args, port); +} + export async function stopModelRouterProcess(pid: number, port: number): Promise { try { process.kill(pid, "SIGTERM"); diff --git a/src/lib/onboard/model-router.test.ts b/src/lib/onboard/model-router.test.ts index 589765badef..8c296c8bdcc 100644 --- a/src/lib/onboard/model-router.test.ts +++ b/src/lib/onboard/model-router.test.ts @@ -6,7 +6,8 @@ import { describe, expect, it } from "vitest"; import { doesModelRouterProcessOwnPort, isModelRouterCommandLineForPort, -} from "../../../dist/lib/onboard/model-router"; + readModelRouterProcessCommandLine, +} from "../../../dist/lib/onboard/model-router-process"; describe("model-router process ownership checks", () => { it("recognizes model-router proxy command lines for the expected port", () => { @@ -24,6 +25,15 @@ describe("model-router process ownership checks", () => { ).toBe(true); }); + it("falls back to ps-style command lines when /proc is unavailable", () => { + expect( + readModelRouterProcessCommandLine(1234, { + readProcCommandLine: () => null, + readPsCommandLine: () => ["/tmp/router/bin/model-router", "proxy", "--port", "44123"], + }), + ).toEqual(["/tmp/router/bin/model-router", "proxy", "--port", "44123"]); + }); + it("rejects reused PIDs that do not look like the expected model-router proxy", () => { expect( doesModelRouterProcessOwnPort(1234, 44123, { diff --git a/src/lib/onboard/model-router.ts b/src/lib/onboard/model-router.ts index 52634211bb8..ab7721dc2ee 100644 --- a/src/lib/onboard/model-router.ts +++ b/src/lib/onboard/model-router.ts @@ -4,7 +4,6 @@ import { spawn, spawnSync } from "node:child_process"; import crypto from "node:crypto"; import fs from "node:fs"; -import http from "node:http"; import os from "node:os"; import path from "node:path"; import { requireValue } from "../core/require-value"; @@ -19,11 +18,16 @@ import type { Session } from "../state/onboard-session"; import * as onboardSession from "../state/onboard-session"; import { buildSubprocessEnv } from "../subprocess-env"; import { hydrateCredentialEnv } from "./credential-env"; +import { + doesModelRouterProcessOwnPort, + isProcessRunning, + isRouterHealthy, + stopModelRouterProcess, +} from "./model-router-process"; import { prepareModelRouterVenv } from "./model-router-python"; const ROUTER_HEALTH_RETRIES = 15; const ROUTER_HEALTH_INTERVAL_MS = 2000; -const ROUTER_HEALTH_TIMEOUT_MS = 3000; const MODEL_ROUTER_RELATIVE_DIR = path.join("nemoclaw-blueprint", "router", "llm-router"); const MODEL_ROUTER_VENV_DIR = path.join(os.homedir(), ".nemoclaw", "model-router-venv"); const MODEL_ROUTER_FINGERPRINT_FILE = ".nemoclaw-source-fingerprint"; @@ -85,95 +89,6 @@ export function loadBlueprintProfile( } } -async function isRouterHealthy(port: number, timeoutMs = ROUTER_HEALTH_TIMEOUT_MS): Promise { - return new Promise((resolve) => { - let settled = false; - const settle = (healthy: boolean) => { - if (settled) return; - settled = true; - resolve(healthy); - }; - const request = http - .get(`http://127.0.0.1:${port}/health`, (res: http.IncomingMessage) => { - res.resume(); - settle((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300); - }) - .on("error", () => settle(false)); - request.setTimeout(timeoutMs, () => { - request.destroy(); - settle(false); - }); - }); -} - -function isProcessRunning(pid: number | null | undefined): boolean { - if (!Number.isInteger(pid) || Number(pid) <= 0) return false; - try { - process.kill(Number(pid), 0); - return true; - } catch { - return false; - } -} - -export function isModelRouterCommandLineForPort(args: readonly string[], port: number): boolean { - const commandName = path.basename(args[0] || ""); - if (commandName !== "model-router") return false; - if (!args.includes("proxy")) return false; - return args.some((arg, index) => { - if (arg === "--port") return args[index + 1] === String(port); - return arg === `--port=${String(port)}`; - }); -} - -function readProcessCommandLine(pid: number): string[] | null { - try { - return fs - .readFileSync(`/proc/${pid}/cmdline`, "utf8") - .split("\0") - .filter(Boolean); - } catch { - return null; - } -} - -export function doesModelRouterProcessOwnPort( - pid: number | null | undefined, - port: number, - deps: { - isRunning?: (pid: number | null | undefined) => boolean; - readCommandLine?: (pid: number) => string[] | null; - } = {}, -): boolean { - if (!Number.isInteger(pid) || Number(pid) <= 0) return false; - const isRunning = deps.isRunning ?? isProcessRunning; - if (!isRunning(pid)) return false; - const readCommandLine = deps.readCommandLine ?? readProcessCommandLine; - const args = readCommandLine(Number(pid)); - return Array.isArray(args) && isModelRouterCommandLineForPort(args, port); -} - -async function stopModelRouterProcess(pid: number, port: number): Promise { - try { - process.kill(pid, "SIGTERM"); - } catch { - return; - } - for (let attempt = 0; attempt < 10; attempt++) { - await new Promise((resolve) => setTimeout(resolve, 500)); - if (!isProcessRunning(pid) && !(await isRouterHealthy(port, 1000))) return; - } - try { - process.kill(pid, "SIGKILL"); - } catch { - // already stopped - } - for (let attempt = 0; attempt < 5; attempt++) { - await new Promise((resolve) => setTimeout(resolve, 500)); - if (!isProcessRunning(pid) && !(await isRouterHealthy(port, 1000))) return; - } -} - function resolveHostCommandPath(commandName: string): string | null { const result = runCapture(["sh", "-c", 'command -v "$1"', "--", commandName], { ignoreError: true, diff --git a/src/lib/onboard/openshell-version.ts b/src/lib/onboard/openshell-version.ts index 6de5273ff72..642f5cad7d8 100644 --- a/src/lib/onboard/openshell-version.ts +++ b/src/lib/onboard/openshell-version.ts @@ -7,6 +7,8 @@ import path from "node:path"; import { resolveOpenshell } from "../adapters/openshell/resolve"; import { ROOT, runCapture } from "../runner"; +export const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "0.0.44"; + export function getInstalledOpenshellVersion(versionOutput: string | null = null): string | null { const openshellBin = resolveOpenshell(); if (!versionOutput && !openshellBin) return null; From 436376533ca01499b7d24631c41f91e13cd0449f Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 23 May 2026 10:43:44 -0700 Subject: [PATCH 5/6] fix(cli): guard agent-change router stop by ownership Signed-off-by: Carlos Villela --- src/lib/onboard/model-router-process.ts | 7 +++++-- src/lib/onboard/model-router.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/lib/onboard/model-router-process.ts b/src/lib/onboard/model-router-process.ts index 4d653822774..8886f038d41 100644 --- a/src/lib/onboard/model-router-process.ts +++ b/src/lib/onboard/model-router-process.ts @@ -139,8 +139,11 @@ export async function stopModelRouterProcess(pid: number, port: number): Promise export async function stopTrackedModelRouterForAgentChange( session: Pick | null, port: number, + deps: ModelRouterProcessOwnershipDeps & { + stopProcess?: (pid: number, port: number) => Promise; + } = {}, ): Promise { const recordedPid = session?.routerPid ?? null; - if (!recordedPid) return; - await stopModelRouterProcess(recordedPid, port); + if (!doesModelRouterProcessOwnPort(recordedPid, port, deps)) return; + await (deps.stopProcess ?? stopModelRouterProcess)(recordedPid as number, port); } diff --git a/src/lib/onboard/model-router.test.ts b/src/lib/onboard/model-router.test.ts index 8c296c8bdcc..35a4019dec8 100644 --- a/src/lib/onboard/model-router.test.ts +++ b/src/lib/onboard/model-router.test.ts @@ -7,6 +7,7 @@ import { doesModelRouterProcessOwnPort, isModelRouterCommandLineForPort, readModelRouterProcessCommandLine, + stopTrackedModelRouterForAgentChange, } from "../../../dist/lib/onboard/model-router-process"; describe("model-router process ownership checks", () => { @@ -34,6 +35,30 @@ describe("model-router process ownership checks", () => { ).toEqual(["/tmp/router/bin/model-router", "proxy", "--port", "44123"]); }); + it("skips agent-change stop when the recorded PID is not an owned model-router", async () => { + let stopped = false; + await stopTrackedModelRouterForAgentChange({ routerPid: 1234 }, 44123, { + isRunning: () => true, + readCommandLine: () => ["/usr/bin/sleep", "999"], + stopProcess: async () => { + stopped = true; + }, + }); + expect(stopped).toBe(false); + }); + + it("stops the recorded router on agent change only after ownership is established", async () => { + const stopped: Array<[number, number]> = []; + await stopTrackedModelRouterForAgentChange({ routerPid: 1234 }, 44123, { + isRunning: () => true, + readCommandLine: () => ["/tmp/router/bin/model-router", "proxy", "--port", "44123"], + stopProcess: async (pid, port) => { + stopped.push([pid, port]); + }, + }); + expect(stopped).toEqual([[1234, 44123]]); + }); + it("rejects reused PIDs that do not look like the expected model-router proxy", () => { expect( doesModelRouterProcessOwnPort(1234, 44123, { From 56698f42814f8811c146d88153ed698c542b571d Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 23 May 2026 10:50:43 -0700 Subject: [PATCH 6/6] Potential fix for pull request finding 'CodeQL / Unused variable, import, function or class' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- src/lib/onboard/model-router.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/onboard/model-router.ts b/src/lib/onboard/model-router.ts index ab7721dc2ee..8d8ec43b433 100644 --- a/src/lib/onboard/model-router.ts +++ b/src/lib/onboard/model-router.ts @@ -20,7 +20,6 @@ import { buildSubprocessEnv } from "../subprocess-env"; import { hydrateCredentialEnv } from "./credential-env"; import { doesModelRouterProcessOwnPort, - isProcessRunning, isRouterHealthy, stopModelRouterProcess, } from "./model-router-process";