Skip to content
Merged
630 changes: 10 additions & 620 deletions bin/lib/onboard.js

Large diffs are not rendered by default.

102 changes: 102 additions & 0 deletions src/lib/http-probe.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// 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 { describe, expect, it } from "vitest";

import {
getCurlTimingArgs,
runCurlProbe,
summarizeCurlFailure,
summarizeProbeError,
summarizeProbeFailure,
} from "./http-probe";

describe("http-probe helpers", () => {
it("returns explicit curl timeouts", () => {
expect(getCurlTimingArgs()).toEqual(["--connect-timeout", "10", "--max-time", "60"]);
});

it("summarizes curl failures from stderr or body", () => {
expect(summarizeCurlFailure(28, " timed out while connecting ")).toBe(
"curl failed (exit 28): timed out while connecting",
);
expect(summarizeCurlFailure(7, "", " connection refused ")).toBe(
"curl failed (exit 7): connection refused",
);
});

it("summarizes JSON and text HTTP probe failures", () => {
expect(summarizeProbeError('{"error":{"message":"bad key"}}', 401)).toBe(
"HTTP 401: bad key",
);
expect(summarizeProbeError(" plain text body ", 500)).toBe("HTTP 500: plain text body");
expect(summarizeProbeFailure("", 0, 28, "timeout")).toBe("curl failed (exit 28): timeout");
});

it("captures successful curl output, appends timing args, and cleans up the temp file", () => {
const countProbeDirs = () =>
fs
.readdirSync(os.tmpdir())
.filter((entry) => entry.startsWith("nemoclaw-curl-probe-"))
.sort();

const before = countProbeDirs();
let capturedArgs = [];
let capturedTimeout = 0;
const result = runCurlProbe(["-sS", "https://example.test/models"], {
spawnSyncImpl: (_command, args, options) => {
capturedArgs = [...args];
capturedTimeout = options.timeout ?? 0;
const outputPath = args[args.indexOf("-o") + 1];
fs.writeFileSync(outputPath, JSON.stringify({ data: [{ id: "foo" }] }));
return {
pid: 1,
output: [],
stdout: "200",
stderr: "",
status: 0,
signal: null,
};
},
});
const after = countProbeDirs();

expect(result).toMatchObject({
ok: true,
httpStatus: 200,
curlStatus: 0,
body: '{"data":[{"id":"foo"}]}',
});
expect(capturedArgs).toContain("--connect-timeout");
expect(capturedArgs).toContain("10");
expect(capturedArgs).toContain("--max-time");
expect(capturedArgs).toContain("60");
expect(capturedArgs.at(-1)).toBe("https://example.test/models");
expect(capturedTimeout).toBeGreaterThanOrEqual(60_000);
expect(after).toEqual(before);
});

it("reports spawn errors as curl failures", () => {
const result = runCurlProbe(["-sS", "https://example.test/models"], {
spawnSyncImpl: () => {
const error = Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" });
return {
pid: 1,
output: [],
stdout: "",
stderr: "curl missing",
status: null,
signal: null,
error,
};
},
});

expect(result.ok).toBe(false);
expect(result.curlStatus).toBe(1);
expect(result.message).toContain("curl failed");
expect(result.stderr).toContain("spawn ENOENT");
});
});
162 changes: 162 additions & 0 deletions src/lib/http-probe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// 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 {
spawnSync,
type SpawnSyncOptionsWithStringEncoding,
type SpawnSyncReturns,
} from "node:child_process";

import { compactText } from "./url-utils";

// runner.js is CJS — use require so we don't pull it into the TS build.
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { ROOT } = require("../../bin/lib/runner");

export interface CurlProbeResult {
ok: boolean;
httpStatus: number;
curlStatus: number;
body: string;
stderr: string;
message: string;
}

export interface CurlProbeOptions {
cwd?: string;
env?: NodeJS.ProcessEnv;
spawnSyncImpl?: (
command: string,
args: readonly string[],
options: SpawnSyncOptionsWithStringEncoding,
) => SpawnSyncReturns<string>;
}

function secureTempFile(prefix: string, ext = ""): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
return path.join(dir, `${prefix}${ext}`);
}

function cleanupTempDir(filePath: string, expectedPrefix: string): void {
const parentDir = path.dirname(filePath);
if (parentDir !== os.tmpdir() && path.basename(parentDir).startsWith(`${expectedPrefix}-`)) {
fs.rmSync(parentDir, { recursive: true, force: true });
}
}

export function getCurlTimingArgs(): string[] {
return ["--connect-timeout", "10", "--max-time", "60"];
}

function splitCurlArgs(argv: readonly string[]): { args: string[]; url: string } {
const args = [...argv];
return { args, url: String(args.pop() || "") };
}

export function summarizeCurlFailure(curlStatus = 0, stderr = "", body = ""): string {
const detail = compactText(stderr || body);
return detail
? `curl failed (exit ${curlStatus}): ${detail.slice(0, 200)}`
: `curl failed (exit ${curlStatus})`;
}

export function summarizeProbeError(body = "", status = 0): string {
if (!body) return `HTTP ${status} with no response body`;
try {
const parsed = JSON.parse(body) as {
error?: { message?: unknown; details?: unknown };
message?: unknown;
detail?: unknown;
details?: unknown;
};
const message =
parsed?.error?.message ||
parsed?.error?.details ||
parsed?.message ||
parsed?.detail ||
parsed?.details;
if (message) return `HTTP ${status}: ${String(message)}`;
} catch {
/* non-JSON body — fall through to raw text */
}
const compact = String(body).replace(/\s+/g, " ").trim();
return `HTTP ${status}: ${compact.slice(0, 200)}`;
}

export function summarizeProbeFailure(
body = "",
status = 0,
curlStatus = 0,
stderr = "",
): string {
if (curlStatus) {
return summarizeCurlFailure(curlStatus, stderr, body);
}
return summarizeProbeError(body, status);
}

// eslint-disable-next-line complexity
export function runCurlProbe(argv: string[], opts: CurlProbeOptions = {}): CurlProbeResult {
const bodyFile = secureTempFile("nemoclaw-curl-probe", ".json");
try {
const { args, url } = splitCurlArgs(argv);
const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync;
const result = spawnSyncImpl(
"curl",
[...args, ...getCurlTimingArgs(), "-o", bodyFile, "-w", "%{http_code}", url],
{
cwd: opts.cwd ?? ROOT,
encoding: "utf8",
timeout: 65_000,
env: {
...process.env,
...opts.env,
},
},
);
const body = fs.existsSync(bodyFile) ? fs.readFileSync(bodyFile, "utf8") : "";
if (result.error) {
const spawnError = result.error as NodeJS.ErrnoException;
const rawErrorCode = spawnError.errno ?? spawnError.code;
const errorCode = typeof rawErrorCode === "number" ? rawErrorCode : 1;
const errorMessage = compactText(
`${spawnError.message || String(spawnError)} ${String(result.stderr || "")}`,
);
return {
ok: false,
httpStatus: 0,
curlStatus: errorCode,
body,
stderr: errorMessage,
message: summarizeProbeFailure(body, 0, errorCode, errorMessage),
};
}
const status = Number(String(result.stdout || "").trim());
return {
ok: result.status === 0 && status >= 200 && status < 300,
httpStatus: Number.isFinite(status) ? status : 0,
curlStatus: result.status || 0,
body,
stderr: String(result.stderr || ""),
message: summarizeProbeFailure(body, status || 0, result.status || 0, String(result.stderr || "")),
};
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
return {
ok: false,
httpStatus: 0,
curlStatus: typeof error === "object" && error && "status" in error ? Number(error.status) || 1 : 1,
body: "",
stderr: detail,
message: summarizeCurlFailure(
typeof error === "object" && error && "status" in error ? Number(error.status) || 1 : 1,
detail,
),
};
} finally {
cleanupTempDir(bodyFile, "nemoclaw-curl-probe");
}
}
87 changes: 87 additions & 0 deletions src/lib/model-prompts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// 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 {
BACK_TO_SELECTION,
promptCloudModel,
promptInputModel,
promptManualModelId,
promptRemoteModel,
} from "./model-prompts";

function promptSequence(responses: string[]) {
const queue = [...responses];
return vi.fn(async () => queue.shift() ?? "");
}
Comment thread
cv marked this conversation as resolved.
Resolved

describe("model prompt helpers", () => {
it("returns the selected cloud model from the curated list", async () => {
const promptFn = promptSequence(["2"]);
const result = await promptCloudModel({
promptFn,
writeLine: vi.fn(),
cloudModelOptions: [
{ id: "nemotron", label: "Nemotron" },
{ id: "llama", label: "Llama" },
],
});

expect(result).toBe("llama");
});

it("validates manual cloud model ids against the saved NVIDIA key", async () => {
const promptFn = promptSequence(["9", "bad-model", "nemotron-custom"]);
const errorLine = vi.fn();
const result = await promptCloudModel({
promptFn,
errorLine,
writeLine: vi.fn(),
cloudModelOptions: [{ id: "nemotron", label: "Nemotron" }],
getCredentialFn: () => "nvapi-test",
validateNvidiaEndpointModelFn: (model) => ({
ok: model === "nemotron-custom",
message: `Model '${model}' is not available from NVIDIA Endpoints. Checked https://integrate.api.nvidia.com/v1/models.`,
}),
});

expect(result).toBe("nemotron-custom");
expect(errorLine).toHaveBeenCalledWith(
" Model 'bad-model' is not available from NVIDIA Endpoints. Checked https://integrate.api.nvidia.com/v1/models.",
);
});

it("returns back-to-selection for manual ids and input prompts", async () => {
await expect(
promptManualModelId(" Model: ", "Provider", null, { promptFn: promptSequence(["back"]) }),
).resolves.toBe(BACK_TO_SELECTION);
await expect(
promptInputModel("Provider", "default-model", null, { promptFn: promptSequence(["back"]) }),
).resolves.toBe(BACK_TO_SELECTION);
});

it("uses the default remote model choice when the user presses enter", async () => {
const result = await promptRemoteModel("OpenAI", "openai", "gpt-5.4-mini", null, {
promptFn: promptSequence([""]),
writeLine: vi.fn(),
});

expect(result).toBe("gpt-5.4-mini");
});

it("retries invalid input models until validation succeeds", async () => {
const promptFn = promptSequence(["bad model", "other", "candidate"]);
const errorLine = vi.fn();
const result = await promptInputModel(
"Custom",
"default-model",
(model) => ({ ok: model === "candidate", message: "try again" }),
{ promptFn, errorLine },
);

expect(result).toBe("candidate");
expect(errorLine).toHaveBeenCalledWith(" Invalid Custom model id.");
expect(errorLine).toHaveBeenCalledWith(" try again");
});
});
Loading