diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 67b359821c6..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, @@ -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,7 @@ 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 logFd = dockerDriverGatewayLaunch.openDockerDriverGatewayLog(logPath, { exitOnFailure }); console.log(" Starting OpenShell Docker-driver gateway..."); console.log(` Gateway log: ${logPath}`); const launch = gatewayLaunch ?? { @@ -2680,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", outFd, errFd], - env: launch.env, - }); + const child = dockerDriverGatewayLaunch.spawnDockerDriverGateway(launch, logFd); const childExit = trackChildExit(child); // #3111 zombie-safe liveness child.unref(); const childPid = child.pid ?? 0; @@ -6732,6 +6728,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 +7443,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/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/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/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 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"); @@ -64,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 new file mode 100644 index 00000000000..35a4019dec8 --- /dev/null +++ b/src/lib/onboard/model-router.test.ts @@ -0,0 +1,76 @@ +// 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, + readModelRouterProcessCommandLine, + stopTrackedModelRouterForAgentChange, +} from "../../../dist/lib/onboard/model-router-process"; + +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("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("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, { + 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..8d8ec43b433 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,15 @@ 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, + 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,58 +88,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; - } -} - -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, @@ -486,15 +437,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 { diff --git a/src/lib/onboard/openshell-version.ts b/src/lib/onboard/openshell-version.ts index e45a279130c..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; @@ -58,7 +60,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/runtime-boundary.ts b/src/lib/onboard/runtime-boundary.ts index f71d72cec6c..daa8a13367a 100644 --- a/src/lib/onboard/runtime-boundary.ts +++ b/src/lib/onboard/runtime-boundary.ts @@ -36,6 +36,7 @@ export class OnboardRuntimeBoundary { recordStateSkipped: this.recordStateSkipped.bind(this), recordRepairEvent: this.recordRepairEvent.bind(this), recordStepFailed: this.recordStepFailed.bind(this), + recordPostVerifyStarted: this.recordPostVerifyStarted.bind(this), recordSessionComplete: this.recordSessionComplete.bind(this), }; } @@ -90,6 +91,15 @@ export class OnboardRuntimeBoundary { return this.getRuntime().emitRepairEvent(type, options); } + async recordPostVerifyStarted(): Promise { + 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(); 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..."); }); });