Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 10 additions & 12 deletions src/lib/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -343,6 +343,7 @@ const {
getBlueprintMinOpenshellVersion,
getInstalledOpenshellVersion,
isOpenshellDevVersion,
SUPPORTED_OPENSHELL_FALLBACK_VERSION,
shouldAllowOpenshellAboveBlueprintMax,
shouldUseOpenshellDevChannel,
versionGte,
Expand Down Expand Up @@ -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}`;
}

Expand Down Expand Up @@ -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");
}
Expand All @@ -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 ?? {
Expand All @@ -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;
Expand Down Expand Up @@ -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<string, { number: number; title: string }> = {
Expand Down Expand Up @@ -7446,6 +7443,7 @@ async function onboard(opts: OnboardOptions = {}): Promise<void> {
migratedLegacyKeys,
deps: {
ensureAgentDashboardForward,
recordPostVerifyStarted,
recordSessionComplete,
toSessionUpdates: (updates) => toSessionUpdates(updates as Parameters<typeof toSessionUpdates>[0]),
removeLegacyCredentialsFile,
Expand Down
35 changes: 34 additions & 1 deletion src/lib/onboard/docker-driver-gateway-launch.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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<string, string>;
Expand Down
14 changes: 12 additions & 2 deletions src/lib/onboard/known-hosts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
33 changes: 27 additions & 6 deletions src/lib/onboard/machine/handlers/finalization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type VerificationResult = { ok: boolean };
function createDeps(overrides: Partial<FinalizationStateOptions<Agent, VerifyChain, VerificationResult>["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(),
Expand All @@ -29,6 +30,7 @@ function createDeps(overrides: Partial<FinalizationStateOptions<Agent, VerifyCha
calls,
deps: {
ensureAgentDashboardForward: calls.ensureAgentDashboard,
recordPostVerifyStarted: calls.postVerify,
recordSessionComplete: calls.complete,
toSessionUpdates: (updates: Record<string, unknown>) => updates as SessionUpdates,
removeLegacyCredentialsFile: calls.removeLegacy,
Expand Down Expand Up @@ -69,19 +71,20 @@ 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",
model: "model",
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"]);
});

Expand All @@ -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();

Expand Down
11 changes: 7 additions & 4 deletions src/lib/onboard/machine/handlers/finalization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface FinalizationStateOptions<Agent, VerifyChain, VerificationResult
migratedLegacyKeys: ReadonlySet<string>;
deps: {
ensureAgentDashboardForward(sandboxName: string, agent: NonNullable<Agent>): number;
recordPostVerifyStarted(): Promise<Session>;
recordSessionComplete(updates: SessionUpdates): Promise<Session>;
toSessionUpdates(updates: Record<string, unknown>): SessionUpdates;
removeLegacyCredentialsFile(): void;
Expand Down Expand Up @@ -56,10 +57,6 @@ export async function handleFinalizationState<Agent, VerifyChain, VerificationRe
}: FinalizationStateOptions<Agent, VerifyChain, VerificationResult>): Promise<FinalizationStateResult> {
if (agent) deps.ensureAgentDashboardForward(sandboxName, agent as NonNullable<Agent>);

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));
Expand All @@ -79,6 +76,8 @@ export async function handleFinalizationState<Agent, VerifyChain, VerificationRe
// Policy application can restart the sandbox; recover OpenClaw before verification (#3573).
deps.checkAndRecoverSandboxProcesses(sandboxName, { quiet: true });

await deps.recordPostVerifyStarted();

// Confirm the delivered sandbox is reachable before printing the live dashboard (#2342).
const verifyChain = deps.buildVerifyChain(deps.getChatUiUrl());
const verificationResult = await deps.verifyDeployment(sandboxName, verifyChain);
Expand All @@ -87,5 +86,9 @@ export async function handleFinalizationState<Agent, VerifyChain, VerificationRe

deps.printDashboard(sandboxName, model, provider, nimContainer, agent);

const session = await deps.recordSessionComplete(
deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }),
);

return { session, unmigratedLegacyKeys, verificationDiagnostics };
}
3 changes: 1 addition & 2 deletions src/lib/onboard/messaging-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
82 changes: 80 additions & 2 deletions src/lib/onboard/model-router-process.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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<void> {
try {
process.kill(pid, "SIGTERM");
Expand All @@ -64,8 +139,11 @@ export async function stopModelRouterProcess(pid: number, port: number): Promise
export async function stopTrackedModelRouterForAgentChange(
session: Pick<Session, "routerPid"> | null,
port: number,
deps: ModelRouterProcessOwnershipDeps & {
stopProcess?: (pid: number, port: number) => Promise<void>;
} = {},
): Promise<void> {
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);
}
Loading
Loading