Repository navigation
refactor(cli): extract sandbox create stream from onboard.js #1516
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7bc63a4
refactor(cli): extract HTTP probe helpers from onboard.js
cv 6e47348
refactor(cli): extract validation recovery helpers from onboard.js
cv f0072e4
refactor(cli): extract provider model helpers from onboard.js
cv 94b9430
refactor(cli): extract model prompt helpers from onboard.js
cv 937d0ce
refactor(cli): extract sandbox create stream from onboard.js
cv 192efe6
fix(cli): enforce curl probe timeouts in runCurlProbe
cv 4b6be62
merge: bring main into sandbox-create-stream branch
cv 6602f09
fix(repo): drop stale branch drift before sandbox stream review
cv 428667e
test(cli): point sandbox phase assertion at helper module
cv 0201d4e
Merge branch 'main' into refactor/onboard-sandbox-create-stream-ts
cv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() ?? ""); | ||
| } | ||
|
|
||
| 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"); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.