Add gateway overrides and quick sandbox deploy
This commit is contained in:
@@ -160,20 +160,49 @@ function bootstrapScriptResponse(proxyPrefix: string) {
|
||||
|
||||
try {
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const gatewayHost = wsProxyPort ? window.location.hostname + ':' + wsProxyPort : window.location.host;
|
||||
const gatewayUrl = protocol + '//' + gatewayHost + proxyPrefix;
|
||||
const pageGatewayUrl = protocol + '//' + window.location.host + proxyPrefix;
|
||||
const sidecarHost = wsProxyPort ? window.location.hostname + ':' + wsProxyPort : window.location.host;
|
||||
const sidecarGatewayUrl = protocol + '//' + sidecarHost + proxyPrefix;
|
||||
const settingsKey = 'openclaw.control.settings.v1';
|
||||
const settingsPrefix = 'openclaw.control.settings.v1:';
|
||||
const tokenKey = 'openclaw.control.token.v1';
|
||||
const tokenPrefix = 'openclaw.control.token.v1:';
|
||||
const tokenScope = gatewayUrl;
|
||||
const hashParams = new URLSearchParams(window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash);
|
||||
const gatewayUrl = (hashParams.get('gatewayUrl') || '').trim() || sidecarGatewayUrl;
|
||||
const token = (hashParams.get('token') || '').trim();
|
||||
const rawSettings = window.localStorage.getItem(settingsKey);
|
||||
const settings = rawSettings ? JSON.parse(rawSettings) : {};
|
||||
const storageScope = (value) => {
|
||||
try {
|
||||
const parsed = new URL(value, window.location.href);
|
||||
const path = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\\/+$/, '') || parsed.pathname;
|
||||
return parsed.protocol + '//' + parsed.host + path;
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
const uniqueScopes = (values) => Array.from(new Set(values.map(storageScope).filter(Boolean)));
|
||||
const gatewayScopes = uniqueScopes([gatewayUrl, sidecarGatewayUrl, pageGatewayUrl]);
|
||||
const settingsKeys = gatewayScopes.map((scope) => settingsPrefix + scope);
|
||||
const readSettings = () => {
|
||||
for (const key of [...settingsKeys, settingsPrefix + 'default', settingsKey]) {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(key);
|
||||
if (!raw) continue;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
|
||||
} catch {}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
const settings = readSettings();
|
||||
|
||||
settings.gatewayUrl = gatewayUrl;
|
||||
window.localStorage.setItem(settingsKey, JSON.stringify(settings));
|
||||
window.sessionStorage.removeItem('openclaw.control.token.v1');
|
||||
if (token) window.sessionStorage.setItem(tokenPrefix + tokenScope, token);
|
||||
const serializedSettings = JSON.stringify(settings);
|
||||
window.localStorage.setItem(settingsKey, serializedSettings);
|
||||
for (const key of settingsKeys) window.localStorage.setItem(key, serializedSettings);
|
||||
window.sessionStorage.removeItem(tokenKey);
|
||||
if (token) {
|
||||
for (const scope of gatewayScopes) window.sessionStorage.setItem(tokenPrefix + scope, token);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort compatibility bridge for OpenClaw's persisted UI settings.
|
||||
}
|
||||
|
||||
+417
-17
@@ -1,7 +1,9 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { promisify } from "node:util"
|
||||
import { inspectSandbox } from "@/app/lib/openshellHost"
|
||||
import { inspectSandbox, resolveSandboxRef } from "@/app/lib/openshellHost"
|
||||
import { repairOpenClawExecApprovalsFile } from "@/app/lib/sandboxPrivilegedFiles"
|
||||
import {
|
||||
commandExists,
|
||||
@@ -13,9 +15,14 @@ import {
|
||||
NEMOCLAW_SETUP_CANDIDATES,
|
||||
NODE_BIN,
|
||||
OPENSHELL_BIN,
|
||||
hostCommandEnv,
|
||||
} from "@/app/lib/hostCommands"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const DOCKER_BIN = process.env.DOCKER_BIN || "docker"
|
||||
const OPENSHELL_CLUSTER_CONTAINER = process.env.OPENSHELL_CLUSTER_CONTAINER || "openshell-cluster-nemoclaw"
|
||||
const OPENSHELL_NAMESPACE = process.env.OPENSHELL_SANDBOX_NAMESPACE || "openshell"
|
||||
const NEMOCLAW_REGISTRY_FILE = path.join(process.env.HOME || "/tmp", ".nemoclaw", "sandboxes.json")
|
||||
|
||||
function validateSandboxName(name: string) {
|
||||
if (!name || typeof name !== "string") throw new Error("sandbox name is required")
|
||||
@@ -67,6 +74,11 @@ type CreateInferenceSettings = {
|
||||
envSummary: string[]
|
||||
}
|
||||
|
||||
type NemoClawRegistryData = {
|
||||
sandboxes?: Record<string, { name?: string; createdAt?: string }>
|
||||
defaultSandbox?: string | null
|
||||
}
|
||||
|
||||
function parseCreateInferenceSettings(body: any): CreateInferenceSettings {
|
||||
const raw = body?.createInference && typeof body.createInference === "object" ? body.createInference : {}
|
||||
const requestedMode = typeof raw.mode === "string" ? raw.mode : "vllm"
|
||||
@@ -127,6 +139,178 @@ function buildNemoClawCreateCommand(): NemoClawCreateCommand {
|
||||
)
|
||||
}
|
||||
|
||||
function resolveNemoClawBasePolicyPath() {
|
||||
const home = process.env.HOME || ""
|
||||
const candidates = [
|
||||
process.env.NEMOCLAW_BASE_POLICY_PATH,
|
||||
path.join(NEMOCLAW_CWD, "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml"),
|
||||
home ? path.join(home, ".nemoclaw", "source", "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml") : undefined,
|
||||
].filter((candidate): candidate is string => Boolean(candidate))
|
||||
|
||||
const found = candidates.find((candidate) => existsSync(candidate))
|
||||
if (!found) {
|
||||
throw new Error(`NemoClaw base policy was not found. Searched: ${candidates.join(", ")}`)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
async function readPodImage(sandboxName: string, jsonpath: string) {
|
||||
const { stdout } = await execFileAsync(DOCKER_BIN, [
|
||||
"exec",
|
||||
OPENSHELL_CLUSTER_CONTAINER,
|
||||
"kubectl",
|
||||
"get",
|
||||
"pod",
|
||||
sandboxName,
|
||||
"-n",
|
||||
OPENSHELL_NAMESPACE,
|
||||
"-o",
|
||||
`jsonpath=${jsonpath}`,
|
||||
], {
|
||||
env: hostCommandEnv(),
|
||||
timeout: 10000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
})
|
||||
|
||||
return String(stdout).trim().split(/\s+/)[0] || null
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\u001b\[[0-9;]*m/g, "")
|
||||
}
|
||||
|
||||
function parseOpenShellSandboxNames(output: string) {
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry &&
|
||||
!/^name\s+/i.test(entry) &&
|
||||
!/^[\s\-=]+$/.test(entry) &&
|
||||
!/^no sandboxes found\.?$/i.test(entry)
|
||||
)
|
||||
.map((entry) => entry.split(/\s{2,}/)[0]?.trim())
|
||||
.filter((entry): entry is string => Boolean(entry))
|
||||
}
|
||||
|
||||
function readNemoClawRegistry(): NemoClawRegistryData {
|
||||
try {
|
||||
return existsSync(NEMOCLAW_REGISTRY_FILE)
|
||||
? JSON.parse(readFileSync(NEMOCLAW_REGISTRY_FILE, "utf8"))
|
||||
: {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
async function listOpenShellSandboxNames() {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(OPENSHELL_BIN, ["sandbox", "list"], {
|
||||
env: hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
}),
|
||||
timeout: 10000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
})
|
||||
return parseOpenShellSandboxNames(String(stdout))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveSourcePodImageFromRef(sourceSandboxRef: string) {
|
||||
const requested = sourceSandboxRef.trim()
|
||||
const source = await resolveSandboxRef(requested)
|
||||
const sourceName = validateSandboxName(source.name)
|
||||
const sourceImage = await readPodImage(sourceName, '{.spec.containers[?(@.name=="agent")].image}')
|
||||
.catch(() => null)
|
||||
|| await readPodImage(sourceName, "{.spec.containers[0].image}").catch(() => null)
|
||||
|
||||
if (!sourceImage) {
|
||||
throw new Error(`Could not resolve the running image for source sandbox '${sourceName}'.`)
|
||||
}
|
||||
|
||||
return {
|
||||
requested,
|
||||
name: sourceName,
|
||||
id: source.id,
|
||||
image: sourceImage,
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveSourcePodImage(sourceSandboxRef: string | null | undefined, targetSandboxName: string) {
|
||||
if (sourceSandboxRef && typeof sourceSandboxRef === "string" && sourceSandboxRef.trim()) {
|
||||
return await resolveSourcePodImageFromRef(sourceSandboxRef)
|
||||
}
|
||||
|
||||
const registry = readNemoClawRegistry()
|
||||
const registeredEntries = Object.entries(registry.sandboxes ?? {})
|
||||
const newestRegisteredNames = registeredEntries
|
||||
.sort(([, a], [, b]) => String(b?.createdAt ?? "").localeCompare(String(a?.createdAt ?? "")))
|
||||
.map(([key, value]) => value?.name || key)
|
||||
const liveNames = await listOpenShellSandboxNames()
|
||||
const candidates = Array.from(new Set([
|
||||
registry.defaultSandbox || undefined,
|
||||
...newestRegisteredNames,
|
||||
...liveNames,
|
||||
].filter((candidate): candidate is string => Boolean(candidate && candidate !== targetSandboxName))))
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
return await resolveSourcePodImageFromRef(candidate)
|
||||
} catch {
|
||||
// Try the next candidate; stale registry entries are common after manual cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("No running NemoClaw sandbox image was found for quick deploy. Create one Fresh NemoClaw Image first, or pass sourceSandboxName explicitly.")
|
||||
}
|
||||
|
||||
function registerNemoClawImageRedeploy(sourceName: string, sandboxName: string) {
|
||||
try {
|
||||
const current = existsSync(NEMOCLAW_REGISTRY_FILE)
|
||||
? JSON.parse(readFileSync(NEMOCLAW_REGISTRY_FILE, "utf8"))
|
||||
: {}
|
||||
const sandboxes = current && typeof current.sandboxes === "object" && current.sandboxes !== null
|
||||
? current.sandboxes
|
||||
: {}
|
||||
const sourceEntry = sandboxes[sourceName] && typeof sandboxes[sourceName] === "object"
|
||||
? sandboxes[sourceName]
|
||||
: { name: sourceName }
|
||||
|
||||
sandboxes[sandboxName] = {
|
||||
...sourceEntry,
|
||||
name: sandboxName,
|
||||
createdAt: new Date().toISOString(),
|
||||
nimContainer: null,
|
||||
policies: [],
|
||||
imageTag: null,
|
||||
}
|
||||
|
||||
const next = {
|
||||
...current,
|
||||
sandboxes,
|
||||
defaultSandbox: current.defaultSandbox || sandboxName,
|
||||
}
|
||||
mkdirSync(path.dirname(NEMOCLAW_REGISTRY_FILE), { recursive: true })
|
||||
const tempPath = `${NEMOCLAW_REGISTRY_FILE}.tmp.${process.pid}.${Date.now()}`
|
||||
writeFileSync(tempPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
|
||||
renameSync(tempPath, NEMOCLAW_REGISTRY_FILE)
|
||||
return {
|
||||
ok: true as const,
|
||||
registryFile: NEMOCLAW_REGISTRY_FILE,
|
||||
note: "Registered the image-redeployed sandbox in the local NemoClaw registry without assigning a host Docker image tag.",
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false as const,
|
||||
registryFile: NEMOCLAW_REGISTRY_FILE,
|
||||
error: error instanceof Error ? error.message : "Failed to update the local NemoClaw registry",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function verifySandboxCreation(sandboxName: string): Promise<SandboxVerification> {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] verify:start sandbox=${sandboxName}`)
|
||||
@@ -285,6 +469,131 @@ async function runCreateCommandBounded(file: string, args: string[], env: NodeJS
|
||||
})
|
||||
}
|
||||
|
||||
async function runCreateCommandUntilReady(file: string, args: string[], env: NodeJS.ProcessEnv, sandboxName: string, timeoutMs: number, intervalMs: number) {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] ready-command:start file=${file} args=${JSON.stringify(args)} timeoutMs=${timeoutMs}`)
|
||||
|
||||
return await new Promise<{
|
||||
completed: boolean
|
||||
timedOut: boolean
|
||||
forcedReady: boolean
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: string
|
||||
}>((resolve) => {
|
||||
const child = spawn(file, args, {
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
let settled = false
|
||||
let checkingReady = false
|
||||
|
||||
const finish = (result: {
|
||||
completed: boolean
|
||||
timedOut: boolean
|
||||
forcedReady: boolean
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: string
|
||||
}) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
clearInterval(readinessTimer)
|
||||
resolve(result)
|
||||
}
|
||||
|
||||
child.stdout?.on("data", (chunk) => {
|
||||
stdout += String(chunk)
|
||||
})
|
||||
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
stderr += String(chunk)
|
||||
})
|
||||
|
||||
child.on("error", (error) => {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "Command failed")
|
||||
console.log(`[sandbox/create] ready-command:error file=${file} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: false,
|
||||
forcedReady: false,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
error: message,
|
||||
})
|
||||
})
|
||||
|
||||
child.on("close", (code, signal) => {
|
||||
console.log(`[sandbox/create] ready-command:close file=${file} elapsedMs=${elapsedMs(startedAt)} code=${code} signal=${signal} stdoutBytes=${stdout.length} stderrBytes=${stderr.length}`)
|
||||
finish({
|
||||
completed: true,
|
||||
timedOut: false,
|
||||
forcedReady: false,
|
||||
exitCode: code,
|
||||
signal,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
...(code === 0 ? {} : { error: `Command exited with code ${code}${signal ? ` signal ${signal}` : ""}` }),
|
||||
})
|
||||
})
|
||||
|
||||
const readinessTimer = setInterval(() => {
|
||||
if (settled || checkingReady) return
|
||||
checkingReady = true
|
||||
verifySandboxCreation(sandboxName)
|
||||
.then((verification) => {
|
||||
if (!settled && verification.verified) {
|
||||
console.log(`[sandbox/create] ready-command:ready sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} sending=SIGTERM`)
|
||||
child.kill("SIGTERM")
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: false,
|
||||
forcedReady: true,
|
||||
exitCode: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
})
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
checkingReady = false
|
||||
})
|
||||
}, intervalMs)
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
console.log(`[sandbox/create] ready-command:timeout file=${file} elapsedMs=${elapsedMs(startedAt)} sending=SIGTERM`)
|
||||
child.kill("SIGTERM")
|
||||
setTimeout(() => {
|
||||
if (!settled) {
|
||||
console.log(`[sandbox/create] ready-command:timeout-escalate file=${file} elapsedMs=${elapsedMs(startedAt)} sending=SIGKILL`)
|
||||
child.kill("SIGKILL")
|
||||
}
|
||||
}, 2000)
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: true,
|
||||
forcedReady: false,
|
||||
exitCode: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
error: `Command exceeded timeout of ${timeoutMs}ms`,
|
||||
})
|
||||
}, timeoutMs)
|
||||
})
|
||||
}
|
||||
|
||||
async function approveOpenClawDeviceRequests(sandboxName: string) {
|
||||
const result = await runCreateCommandBounded(OPENSHELL_BIN, [
|
||||
"sandbox",
|
||||
@@ -295,14 +604,9 @@ async function approveOpenClawDeviceRequests(sandboxName: string) {
|
||||
"sh",
|
||||
"-lc",
|
||||
"openclaw devices approve --latest --json --timeout 10000",
|
||||
], {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
], hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}, 15000)
|
||||
}), 15000)
|
||||
|
||||
const combinedOutput = `${result.stdout}\n${result.stderr}`.trim()
|
||||
const noPending = NO_PENDING_DEVICE_REQUESTS.test(combinedOutput)
|
||||
@@ -359,7 +663,7 @@ export async function GET() {
|
||||
blueprints: [
|
||||
{
|
||||
id: "nemoclaw-blueprint",
|
||||
label: "New NemoClaw Sandbox",
|
||||
label: "Fresh NemoClaw Image",
|
||||
description: "Bootstraps a full NemoClaw sandbox using the nemoclaw-blueprint workflow.",
|
||||
type: "blueprint",
|
||||
source: "~/NemoClaw/nemoclaw-blueprint/blueprint.yaml",
|
||||
@@ -373,6 +677,14 @@ export async function GET() {
|
||||
source: "dashboard-custom",
|
||||
supportsTailscale: false,
|
||||
},
|
||||
{
|
||||
id: "redeploy-image",
|
||||
label: "Quick Deploy New NemoClaw Sandbox",
|
||||
description: "Create a default NemoClaw sandbox from the latest available running image without rebuilding it.",
|
||||
type: "image",
|
||||
source: "default-running-image",
|
||||
supportsTailscale: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
@@ -395,15 +707,13 @@ export async function POST(request: Request) {
|
||||
|
||||
if (blueprint === "nemoclaw-blueprint") {
|
||||
const createCommand = buildNemoClawCreateCommand()
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
const env: NodeJS.ProcessEnv = hostCommandEnv({
|
||||
NEMOCLAW_SANDBOX_NAME: sandboxName,
|
||||
NEMOCLAW_NON_INTERACTIVE: "1",
|
||||
NEMOCLAW_RECREATE_SANDBOX: "1",
|
||||
NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1",
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
}
|
||||
})
|
||||
|
||||
if (!enableTailscale) {
|
||||
env.NVIDIA_API_KEY = env.NVIDIA_API_KEY || "optional-local-mode"
|
||||
@@ -482,13 +792,12 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
if (blueprint === "custom-sandbox") {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
const env: NodeJS.ProcessEnv = hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
})
|
||||
const createAttempt = await runCreateCommandBounded(OPENSHELL_BIN, ["sandbox", "create", "--name", sandboxName], env, 15000)
|
||||
|
||||
if (createAttempt.completed && createAttempt.exitCode !== 0) {
|
||||
@@ -558,6 +867,97 @@ export async function POST(request: Request) {
|
||||
}, { status: created ? 200 : 502 })
|
||||
}
|
||||
|
||||
if (blueprint === "redeploy-image") {
|
||||
const sourceSandboxName = typeof body?.sourceSandboxName === "string" ? body.sourceSandboxName.trim() : ""
|
||||
const source = await resolveSourcePodImage(sourceSandboxName, sandboxName)
|
||||
const sourceImage = source.image
|
||||
const basePolicyPath = resolveNemoClawBasePolicyPath()
|
||||
const env: NodeJS.ProcessEnv = hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
})
|
||||
|
||||
const createAttempt = await runCreateCommandUntilReady(OPENSHELL_BIN, [
|
||||
"sandbox",
|
||||
"create",
|
||||
"--name",
|
||||
sandboxName,
|
||||
"--from",
|
||||
sourceImage,
|
||||
"--policy",
|
||||
basePolicyPath,
|
||||
"--auto-providers",
|
||||
"--",
|
||||
"nemoclaw-start",
|
||||
], env, sandboxName, 120000, 2000)
|
||||
|
||||
const readiness = await waitForSandboxReady(sandboxName, 90000, 2000)
|
||||
const verification = readiness.verification ?? {
|
||||
verified: false,
|
||||
summary: "Sandbox readiness polling produced no verification result.",
|
||||
error: "Sandbox readiness polling produced no verification result.",
|
||||
}
|
||||
const created = readiness.verified
|
||||
const registry = created ? registerNemoClawImageRedeploy(source.name, sandboxName) : null
|
||||
const execApprovalsRepair = created ? await repairOpenClawExecApprovalsFile(sandboxName).catch((error) => ({
|
||||
sandboxName,
|
||||
path: "/sandbox/.openclaw/exec-approvals.json",
|
||||
error: error instanceof Error ? error.message : "Failed to repair OpenClaw exec approvals file",
|
||||
})) : null
|
||||
const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null
|
||||
console.log(
|
||||
`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} mode=redeploy-image createTimedOut=${createAttempt.timedOut} readinessAttempts=${readiness.attempts} deviceApproval=${deviceApproval?.approved ?? false} elapsedMs=${elapsedMs(requestStartedAt)}`,
|
||||
)
|
||||
|
||||
const createFailed = createAttempt.completed && createAttempt.exitCode !== 0 && !created
|
||||
return NextResponse.json({
|
||||
ok: created,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
sourceSandboxName: source.name,
|
||||
sourceSandboxId: source.id,
|
||||
sourceImage,
|
||||
basePolicyPath,
|
||||
created,
|
||||
verified: verification.verified,
|
||||
verification,
|
||||
mode: "redeploy-image",
|
||||
stdout: createAttempt.stdout,
|
||||
stderr: createAttempt.stderr,
|
||||
createCommand: {
|
||||
completed: createAttempt.completed,
|
||||
timedOut: createAttempt.timedOut,
|
||||
forcedReady: createAttempt.forcedReady,
|
||||
exitCode: createAttempt.exitCode,
|
||||
signal: createAttempt.signal,
|
||||
error: createAttempt.error,
|
||||
},
|
||||
readiness: {
|
||||
attempts: readiness.attempts,
|
||||
elapsedMs: readiness.elapsedMs,
|
||||
},
|
||||
registry,
|
||||
execApprovalsRepair,
|
||||
deviceApproval,
|
||||
note: created
|
||||
? appendNote(
|
||||
`Sandbox created by redeploying the running image from '${source.name}' instead of rebuilding it.`,
|
||||
createAttempt.forcedReady
|
||||
? "The dashboard returned as soon as OpenShell reported the redeployed sandbox Ready."
|
||||
: false,
|
||||
createAttempt.timedOut
|
||||
? "The OpenShell create command stayed attached after the sandbox reached Ready, so the dashboard stopped waiting for the local command."
|
||||
: false,
|
||||
registry && !registry.ok ? `NemoClaw registry update failed: ${registry.error}` : false,
|
||||
execApprovalsRepair && "note" in execApprovalsRepair ? execApprovalsRepair.note : false,
|
||||
execApprovalsRepair && "error" in execApprovalsRepair ? `OpenClaw exec approvals repair failed: ${execApprovalsRepair.error}` : false,
|
||||
deviceApproval?.note,
|
||||
)
|
||||
: createFailed
|
||||
? "Image redeploy command failed and the sandbox never reached a ready verification state afterward."
|
||||
: "Image redeploy started, but the sandbox never reached a ready verification state afterward.",
|
||||
}, { status: created ? 200 : createFailed ? 500 : 502 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: false, error: `unknown blueprint: ${blueprint}` }, { status: 400 })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Sandbox creation failed"
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server"
|
||||
import { execFile } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { resolveSandboxRef } from "@/app/lib/openshellHost"
|
||||
import { HOST_PATH, NEMOCLAW_BIN, NEMOCLAW_CWD, OPENSHELL_BIN } from "@/app/lib/hostCommands"
|
||||
import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -54,14 +54,9 @@ async function deleteSandbox(sandboxName: string) {
|
||||
console.log(`[sandbox/delete] command:start sandbox=${sandboxName}`)
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, ["sandbox", "delete", sandboxName], {
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
env: hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
}),
|
||||
timeout: 60000,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
})
|
||||
@@ -83,53 +78,6 @@ function isSandboxNotFound(output: string) {
|
||||
return /sandbox not found|status:\s*NotFound|not present in the live OpenShell gateway/i.test(output)
|
||||
}
|
||||
|
||||
function isNemoClawSandboxNotRegistered(output: string, sandboxName: string) {
|
||||
return new RegExp(`Unknown command:\\s*${sandboxName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i").test(output)
|
||||
}
|
||||
|
||||
async function cleanupNemoClawSandbox(sandboxName: string) {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/delete] nemoclaw-cleanup:start sandbox=${sandboxName}`)
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(NEMOCLAW_BIN, [sandboxName, "destroy", "--yes"], {
|
||||
cwd: NEMOCLAW_CWD,
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
timeout: 90000,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
})
|
||||
console.log(`[sandbox/delete] nemoclaw-cleanup:done sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)}`)
|
||||
return { ok: true as const, stdout: String(stdout).trim(), stderr: String(stderr).trim() }
|
||||
} catch (error: any) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "NemoClaw cleanup failed")
|
||||
const stdout = String(error?.stdout || "").trim()
|
||||
const stderr = String(error?.stderr || "").trim()
|
||||
const output = [message, stdout, stderr].filter(Boolean).join("\n")
|
||||
if (isNemoClawSandboxNotRegistered(output, sandboxName)) {
|
||||
console.log(`[sandbox/delete] nemoclaw-cleanup:already-gone sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)}`)
|
||||
return {
|
||||
ok: true as const,
|
||||
stdout,
|
||||
stderr,
|
||||
note: "NemoClaw registry already had no matching sandbox.",
|
||||
}
|
||||
}
|
||||
console.log(`[sandbox/delete] nemoclaw-cleanup:error sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||
return {
|
||||
ok: false as const,
|
||||
stdout,
|
||||
stderr,
|
||||
error: message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForSandboxDeleted(sandboxName: string, timeoutMs: number, intervalMs: number) {
|
||||
const startedAt = Date.now()
|
||||
let attempts = 0
|
||||
@@ -179,7 +127,6 @@ export async function POST(request: Request) {
|
||||
const result = await deleteSandbox(target.sandboxName)
|
||||
const deleteOutput = [result.error, result.stdout, result.stderr].filter(Boolean).join("\n")
|
||||
const openShellAlreadyGone = !result.ok && isSandboxNotFound(deleteOutput)
|
||||
const cleanup = await cleanupNemoClawSandbox(target.sandboxName)
|
||||
|
||||
if (!result.ok && !openShellAlreadyGone) {
|
||||
return NextResponse.json({
|
||||
@@ -193,24 +140,6 @@ export async function POST(request: Request) {
|
||||
error: result.error,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
nemoclaw: cleanup,
|
||||
}, { status: 500 })
|
||||
}
|
||||
|
||||
if (!cleanup.ok) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
deleted: false,
|
||||
requested: target.requested,
|
||||
sandboxName: target.sandboxName,
|
||||
sandboxId: target.sandboxId,
|
||||
resolved: target.resolved,
|
||||
openShellAlreadyGone,
|
||||
openShell: result,
|
||||
error: cleanup.error,
|
||||
stdout: cleanup.stdout,
|
||||
stderr: cleanup.stderr,
|
||||
nemoclaw: cleanup,
|
||||
}, { status: 500 })
|
||||
}
|
||||
|
||||
@@ -224,13 +153,12 @@ export async function POST(request: Request) {
|
||||
sandboxName: target.sandboxName,
|
||||
sandboxId: target.sandboxId,
|
||||
resolved: target.resolved,
|
||||
stdout: [result.stdout, cleanup.stdout].filter(Boolean).join("\n\n"),
|
||||
stderr: [result.stderr, cleanup.stderr].filter(Boolean).join("\n\n"),
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
openShellAlreadyGone,
|
||||
openShell: result,
|
||||
nemoclaw: cleanup,
|
||||
deletion,
|
||||
note: deleted ? "Sandbox delete completed and NemoClaw registry cleanup ran." : "Sandbox delete command completed, but inventory still reports the sandbox.",
|
||||
note: deleted ? "Sandbox delete completed." : "Sandbox delete command completed, but inventory still reports the sandbox.",
|
||||
}, { status: deleted ? 200 : 202 })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Sandbox delete failed"
|
||||
|
||||
@@ -3,7 +3,7 @@ import { promisify } from "node:util"
|
||||
import { NextResponse } from "next/server"
|
||||
import { listActivity } from "@/app/lib/activityLog"
|
||||
import { listBackupCatalog } from "@/app/lib/backupCatalog"
|
||||
import { HOST_PATH, OPENSHELL_BIN } from "@/app/lib/hostCommands"
|
||||
import { HOST_PATH, OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -11,9 +11,12 @@ export const dynamic = "force-dynamic"
|
||||
|
||||
async function run(command: string, args: string[]) {
|
||||
try {
|
||||
const env = command === OPENSHELL_BIN
|
||||
? hostCommandEnv({ OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw" })
|
||||
: { ...process.env, PATH: HOST_PATH, NO_COLOR: "1", CLICOLOR: "0", CLICOLOR_FORCE: "0" }
|
||||
const { stdout, stderr } = await execFileAsync(command, args, {
|
||||
timeout: 10000,
|
||||
env: { ...process.env, PATH: HOST_PATH, NO_COLOR: "1", CLICOLOR: "0", CLICOLOR_FORCE: "0" },
|
||||
env,
|
||||
})
|
||||
return { ok: true, stdout: stdout.trim(), stderr: stderr.trim() }
|
||||
} catch (error) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server"
|
||||
import { execFile } from "node:child_process"
|
||||
import { hostname, networkInterfaces } from "node:os"
|
||||
import { promisify } from "node:util"
|
||||
import { HOST_PATH, NEMOCLAW_BIN, NODE_BIN, OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
|
||||
import { NEMOCLAW_BIN, NODE_BIN, OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
|
||||
import { resolveRuntimeAuthority } from "@/app/lib/runtimeAuthority"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
@@ -146,13 +146,9 @@ function buildNemoClawSummary(output: string | null, defaultSandboxNames: Set<st
|
||||
}
|
||||
|
||||
async function execNemoclaw(args: string[]) {
|
||||
const env = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
const env = hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
})
|
||||
|
||||
const command = /\.(?:c?m?js|ts)$/i.test(NEMOCLAW_BIN)
|
||||
? execFileAsync(NODE_BIN, [NEMOCLAW_BIN, ...args], { env })
|
||||
|
||||
@@ -19,7 +19,7 @@ type BlueprintOption = {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
type: "blueprint" | "custom"
|
||||
type: "blueprint" | "custom" | "image"
|
||||
source: string
|
||||
supportsTailscale?: boolean
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
|
||||
const [message, setMessage] = useState("")
|
||||
const [selectedPreset, setSelectedPreset] = useState<SecurityPresetId | ''>('')
|
||||
const [blueprints, setBlueprints] = useState<BlueprintOption[]>([])
|
||||
const [selectedBlueprint, setSelectedBlueprint] = useState<string>('nemoclaw-blueprint')
|
||||
const [selectedBlueprint, setSelectedBlueprint] = useState<string>('redeploy-image')
|
||||
const [sandboxName, setSandboxName] = useState<string>('')
|
||||
const [enableTailscale, setEnableTailscale] = useState<boolean>(false)
|
||||
const [createInferenceMode, setCreateInferenceMode] = useState<CreateInferenceMode>("vllm")
|
||||
@@ -208,7 +208,7 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
|
||||
<button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span>
|
||||
<Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge>
|
||||
<Badge tone={bp.type === 'blueprint' ? 'dynamic' : 'static'}>{bp.type}</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p>
|
||||
</button>
|
||||
@@ -216,15 +216,20 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Lowercase letters, numbers, and hyphens only." /></label>
|
||||
<input value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
|
||||
<input value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : selectedBlueprint === 'redeploy-image' ? 'my-assistant-copy' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
|
||||
</div>
|
||||
{selectedBlueprint === 'redeploy-image' && (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4">
|
||||
<p className="text-xs text-[var(--foreground-dim)]">Quick Deploy uses the default running NemoClaw image and skips the Docker rebuild. Use Fresh NemoClaw Image when you need to rebuild the image layers.</p>
|
||||
</div>
|
||||
)}
|
||||
{activeBlueprint?.supportsTailscale && (
|
||||
<label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono">
|
||||
<input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale
|
||||
</label>
|
||||
)}
|
||||
{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-4">
|
||||
{selectedBlueprint === 'nemoclaw-blueprint' && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-4">
|
||||
<div>
|
||||
<h6 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Inference at Create</h6>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Choose the provider NemoClaw should use while onboarding this sandbox.</p>
|
||||
@@ -257,7 +262,7 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>}
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-4">
|
||||
<label className="flex items-start gap-3">
|
||||
<input type="checkbox" checked={restoreFromBackup} onChange={(e) => setRestoreFromBackup(e.target.checked)} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" />
|
||||
|
||||
@@ -7,6 +7,7 @@ type BlueprintOption = {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
type?: "blueprint" | "custom" | "image"
|
||||
supportsTailscale?: boolean
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ export default function WizardPanel({
|
||||
const [sourceSandboxId, setSourceSandboxId] = useState("")
|
||||
const [targetName, setTargetName] = useState("")
|
||||
const [blueprints, setBlueprints] = useState<BlueprintOption[]>([])
|
||||
const [selectedBlueprint, setSelectedBlueprint] = useState("custom-sandbox")
|
||||
const [selectedBlueprint, setSelectedBlueprint] = useState("redeploy-image")
|
||||
const [enableTailscale, setEnableTailscale] = useState(false)
|
||||
const [backupPath, setBackupPath] = useState("/sandbox")
|
||||
const [restorePath, setRestorePath] = useState("/sandbox")
|
||||
@@ -161,13 +162,14 @@ export default function WizardPanel({
|
||||
setRunLog([])
|
||||
setActiveStep("run")
|
||||
|
||||
appendLog(`Creating target sandbox ${targetName}...`)
|
||||
appendLog(selectedBlueprint === "redeploy-image" ? `Redeploying ${sourceSandbox.name}'s image as ${targetName}...` : `Creating target sandbox ${targetName}...`)
|
||||
const createResponse = await fetch("/api/sandbox/create", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
blueprint: selectedBlueprint,
|
||||
sandboxName: targetName.trim(),
|
||||
sourceSandboxName: sourceSandbox.name,
|
||||
enableTailscale,
|
||||
policy: null,
|
||||
preset: null,
|
||||
@@ -533,11 +535,11 @@ export default function WizardPanel({
|
||||
</svg>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Clone Sandbox</h2>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Create a fresh sandbox, back up the source, then restore into the target.</p>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Start a fresh sandbox from the source image, then restore source files into the target.</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="status-chip shrink-0 border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]">
|
||||
backup + restore
|
||||
image + restore
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -604,7 +606,7 @@ export default function WizardPanel({
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Configure Target Sandbox</h3>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Choose the sandbox blueprint and target name.</p>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Choose how the target is created and set its sandbox name.</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
{blueprints.map((blueprint) => (
|
||||
@@ -673,7 +675,7 @@ export default function WizardPanel({
|
||||
{[
|
||||
["Source", sourceSandbox?.name || "-"],
|
||||
["Target", targetName || "-"],
|
||||
["Blueprint", activeBlueprint?.label || selectedBlueprint],
|
||||
["Create Path", activeBlueprint?.label || selectedBlueprint],
|
||||
["Backup Path", backupPath],
|
||||
["Restore Path", restorePath],
|
||||
["Restore Mode", replaceTarget ? "replace" : "merge"],
|
||||
|
||||
+62
-1
@@ -1,4 +1,4 @@
|
||||
import { existsSync, readdirSync, statSync } from "node:fs"
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
|
||||
const HOME = process.env.HOME || ""
|
||||
@@ -107,11 +107,72 @@ function pathEntries() {
|
||||
|
||||
export const HOST_PATH = unique(pathEntries()).join(":")
|
||||
|
||||
function nonEmptyEnv(name: string) {
|
||||
const value = process.env[name]?.trim()
|
||||
return value || undefined
|
||||
}
|
||||
|
||||
function gatewayUrlFromHost(host: string, port: string) {
|
||||
if (/^https?:\/\//i.test(host)) return host
|
||||
if (host.includes(":")) return `http://${host}`
|
||||
return `http://${host}:${port}`
|
||||
}
|
||||
|
||||
function stringConfigValue(value: unknown) {
|
||||
if (typeof value === "string") return value.trim() || undefined
|
||||
if (typeof value === "number" && Number.isFinite(value)) return String(value)
|
||||
return undefined
|
||||
}
|
||||
|
||||
function readOpenShellGatewayAddressConfig() {
|
||||
const configDir = OPENSHELL_XDG_CONFIG_HOME ? path.join(OPENSHELL_XDG_CONFIG_HOME, "openshell") : ""
|
||||
const candidates = unique([
|
||||
process.env.OPENSHELL_GATEWAY_CONFIG,
|
||||
configDir ? path.join(configDir, "gateway.json") : undefined,
|
||||
configDir ? path.join(configDir, "config.json") : undefined,
|
||||
])
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!existsSync(candidate)) continue
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(candidate, "utf8"))
|
||||
const gateway = parsed?.gateway && typeof parsed.gateway === "object" ? parsed.gateway : {}
|
||||
const host = stringConfigValue(parsed?.gatewayHost) || stringConfigValue(gateway.host)
|
||||
const port = stringConfigValue(parsed?.gatewayPort) || stringConfigValue(gateway.port)
|
||||
const url = stringConfigValue(parsed?.gatewayUrl) || stringConfigValue(gateway.url)
|
||||
if (host || port || url) return { host, port, url }
|
||||
} catch {
|
||||
// Ignore malformed optional config; explicit env vars remain authoritative.
|
||||
}
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
|
||||
export function openshellGatewayAddressEnv() {
|
||||
const config = readOpenShellGatewayAddressConfig()
|
||||
const host = nonEmptyEnv("OPENSHELL_GATEWAY_HOST") || config.host
|
||||
const configuredPort = nonEmptyEnv("OPENSHELL_GATEWAY_PORT") || config.port
|
||||
const port = configuredPort || "8080"
|
||||
const explicitUrl = nonEmptyEnv("OPENSHELL_GATEWAY_URL") || config.url
|
||||
|
||||
return {
|
||||
...(host ? { OPENSHELL_GATEWAY_HOST: host } : {}),
|
||||
...(configuredPort || host || explicitUrl ? { OPENSHELL_GATEWAY_PORT: port } : {}),
|
||||
...(explicitUrl
|
||||
? { OPENSHELL_GATEWAY_URL: explicitUrl }
|
||||
: host
|
||||
? { OPENSHELL_GATEWAY_URL: gatewayUrlFromHost(host, port) }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function hostCommandEnv(extra: Record<string, string | undefined> = {}) {
|
||||
return {
|
||||
...process.env,
|
||||
...(OPENSHELL_HOME ? { HOME: OPENSHELL_HOME } : {}),
|
||||
...(OPENSHELL_XDG_CONFIG_HOME ? { XDG_CONFIG_HOME: OPENSHELL_XDG_CONFIG_HOME } : {}),
|
||||
...openshellGatewayAddressEnv(),
|
||||
PATH: HOST_PATH,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
|
||||
@@ -8,6 +8,10 @@ const execFileAsync = promisify(execFile)
|
||||
const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "0.0.0.0", "host.docker.internal", "host.openshell.internal"])
|
||||
const FALLBACK_SANDBOX_PROXY_ORIGIN = "http://10.200.0.1:3128"
|
||||
|
||||
function shouldUseProxyWrappedBrokerUrl() {
|
||||
return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_MCP_BROKER_PROXY_URL || "")
|
||||
}
|
||||
|
||||
async function discoverOpenShellDockerGateway() {
|
||||
const container = process.env.OPEN_SHELL_CONTAINER || "openshell-cluster-nemoclaw"
|
||||
const { stdout } = await execFileAsync("docker", ["inspect", container], {
|
||||
@@ -67,10 +71,11 @@ export async function brokerBaseUrlForSandbox(
|
||||
}
|
||||
|
||||
const hostBrokerUrl = `${publicOrigin.toString().replace(/\/+$/, "")}/api/mcp/broker`
|
||||
if (!shouldUseProxyWrappedBrokerUrl()) return hostBrokerUrl
|
||||
|
||||
const proxyOrigin = sandbox
|
||||
? await discoverSandboxProxyOrigin(sandbox.id, sandbox.name).catch(() => null)
|
||||
: null
|
||||
|
||||
if (proxyOrigin) return `${proxyOrigin}/${hostBrokerUrl}`
|
||||
if (LOCAL_HOSTNAMES.has(new URL(origin).hostname)) return `${FALLBACK_SANDBOX_PROXY_ORIGIN}/${hostBrokerUrl}`
|
||||
return hostBrokerUrl
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { HOST_PATH, OPENCLAW_BIN, OPENSHELL_BIN } from "./hostCommands"
|
||||
import { HOST_PATH, OPENCLAW_BIN, OPENSHELL_BIN, hostCommandEnv } from "./hostCommands"
|
||||
import { getDefaultOpenClawInstance, getOpenClawDashboardPortForSandbox, resolveOpenClawInstance } from "./openclawInstances"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
@@ -44,13 +44,12 @@ export type DashboardProbe = {
|
||||
|
||||
export async function execOpenShell(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
env: hostCommandEnv({
|
||||
OPENSHELL_GATEWAY,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
}),
|
||||
})
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
@@ -61,6 +61,30 @@ export async function buildSandboxMcpBrokerHandoff(
|
||||
token,
|
||||
"```",
|
||||
"",
|
||||
"## Quick Check",
|
||||
"",
|
||||
"Run this inside the sandbox to verify that you are using the current broker token without pasting it into your shell history:",
|
||||
"",
|
||||
"```sh",
|
||||
"node - <<'NODE'",
|
||||
"const fs = require('fs')",
|
||||
`const url = ${JSON.stringify(`${brokerBaseUrl}/mcp`)}`,
|
||||
"const manifest = fs.readFileSync('/sandbox/openshell_control_mcp.md', 'utf8')",
|
||||
"const token = manifest.match(/```\\n(osmcp_[^\\n]+)\\n```/)?.[1]",
|
||||
"if (!token) throw new Error('MCP broker token not found in /sandbox/openshell_control_mcp.md')",
|
||||
"const payload = { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }",
|
||||
"fetch(url, {",
|
||||
" method: 'POST',",
|
||||
" headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },",
|
||||
" body: JSON.stringify(payload),",
|
||||
"})",
|
||||
" .then(async (response) => {",
|
||||
" const body = await response.json()",
|
||||
" console.log(JSON.stringify({ status: response.status, tools: body.result?.tools?.map((tool) => tool.name) || [], error: body.error || null }, null, 2))",
|
||||
" })",
|
||||
"NODE",
|
||||
"```",
|
||||
"",
|
||||
"## Rules",
|
||||
"",
|
||||
"- Do not assume any MCP server exists unless the broker returns it as available.",
|
||||
|
||||
@@ -75,12 +75,40 @@ function parseNetworkRules(output: string): SandboxNetworkRule[] {
|
||||
.filter((rule) => rule.chunkId)
|
||||
}
|
||||
|
||||
function hostPortForUrl(parsed: URL) {
|
||||
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80")
|
||||
return `${parsed.hostname}:${port}`
|
||||
}
|
||||
|
||||
function addEndpointCandidate(candidates: Set<string>, parsed: URL) {
|
||||
const hostPort = hostPortForUrl(parsed)
|
||||
candidates.add(hostPort)
|
||||
if (parsed.hostname === "host.docker.internal") {
|
||||
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80")
|
||||
candidates.add(`0.0.0.0:${port}`)
|
||||
}
|
||||
}
|
||||
|
||||
function extractProxiedTargetUrl(brokerBaseUrl: string) {
|
||||
try {
|
||||
const parsed = new URL(brokerBaseUrl)
|
||||
const rawPath = parsed.pathname.replace(/^\/+/, "")
|
||||
const decodedPath = decodeURIComponent(rawPath)
|
||||
if (!/^https?:\/\//i.test(decodedPath)) return null
|
||||
return new URL(decodedPath)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function brokerEndpointCandidates(brokerBaseUrl: string) {
|
||||
const parsed = new URL(brokerBaseUrl)
|
||||
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80")
|
||||
const hostPort = `${parsed.hostname}:${port}`
|
||||
const candidates = new Set([hostPort])
|
||||
if (parsed.hostname === "host.docker.internal") candidates.add(`0.0.0.0:${port}`)
|
||||
const candidates = new Set<string>()
|
||||
addEndpointCandidate(candidates, parsed)
|
||||
|
||||
const proxiedTarget = extractProxiedTargetUrl(brokerBaseUrl)
|
||||
if (proxiedTarget) addEndpointCandidate(candidates, proxiedTarget)
|
||||
|
||||
return candidates
|
||||
}
|
||||
|
||||
@@ -153,13 +181,23 @@ async function probeBrokerEndpoint(sandboxName: string, brokerBaseUrl: string) {
|
||||
}
|
||||
const script = [
|
||||
"node",
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`
|
||||
fetch(${JSON.stringify(mcpUrl)}, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: ${JSON.stringify(JSON.stringify(payload))},
|
||||
}).catch(() => {});
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 8000);
|
||||
try {
|
||||
await fetch(${JSON.stringify(mcpUrl)}, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: ${JSON.stringify(JSON.stringify(payload))},
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch {
|
||||
// The probe only exists to let OpenShell create a policy chunk.
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
`,
|
||||
]
|
||||
await runOpenShell(["sandbox", "exec", "-n", sandboxName, "--", ...script], 15000).catch(() => null)
|
||||
|
||||
Reference in New Issue
Block a user