Integrate NemoClaw recovery and dashboard routing
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyPassword } from "@/app/lib/controlAuth"
|
||||
import { createSessionCookieValue, getAuthSettings, sessionCookieOptionsForRequest, verifyPassword } from "@/app/lib/controlAuth"
|
||||
import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit"
|
||||
|
||||
const AUTH_WINDOW_MS = 5 * 60 * 1000
|
||||
@@ -34,6 +34,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
clearRateLimit(limitKey)
|
||||
const response = NextResponse.json({ ok: true, next: nextPath })
|
||||
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions)
|
||||
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request))
|
||||
return response
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getAuthSettings } from "@/app/lib/controlAuth"
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { getAuthSettings, sessionCookieOptionsForRequest } from "@/app/lib/controlAuth"
|
||||
|
||||
export async function POST() {
|
||||
export async function POST(request: NextRequest) {
|
||||
const settings = getAuthSettings()
|
||||
const response = NextResponse.json({ ok: true })
|
||||
response.cookies.set(settings.cookieName, "", {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
path: "/",
|
||||
...sessionCookieOptionsForRequest(request),
|
||||
maxAge: 0,
|
||||
})
|
||||
return response
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyRecoveryToken } from "@/app/lib/controlAuth"
|
||||
import { createSessionCookieValue, getAuthSettings, sessionCookieOptionsForRequest, verifyRecoveryToken } from "@/app/lib/controlAuth"
|
||||
import { updateLocalAuthCredentials } from "@/app/lib/controlAuthConfig"
|
||||
import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit"
|
||||
|
||||
@@ -37,6 +37,6 @@ export async function POST(request: NextRequest) {
|
||||
recoveryToken: result.recoveryToken,
|
||||
note: "Password reset. Save the new recovery token from .env.local.",
|
||||
})
|
||||
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions)
|
||||
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request))
|
||||
return response
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server"
|
||||
import {
|
||||
createSessionCookieValue,
|
||||
getAuthSettings,
|
||||
sessionCookieOptions,
|
||||
sessionCookieOptionsForRequest,
|
||||
verifyPassword,
|
||||
verifyRecoveryToken,
|
||||
verifySessionCookieValue,
|
||||
@@ -54,6 +54,6 @@ export async function POST(request: NextRequest) {
|
||||
recoveryToken: result.recoveryToken,
|
||||
note: "Password updated. Save the new recovery token from .env.local.",
|
||||
})
|
||||
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions)
|
||||
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request))
|
||||
return response
|
||||
}
|
||||
|
||||
@@ -106,8 +106,12 @@ function isVllmEndpoint(name: string, baseUrl: string) {
|
||||
return [name, baseUrl].some((value) => /vllm/i.test(value))
|
||||
}
|
||||
|
||||
function isOllamaEndpoint(name: string, baseUrl: string) {
|
||||
return [name, baseUrl].some((value) => /ollama|11434/i.test(value))
|
||||
}
|
||||
|
||||
function normalizeProviderType(type: string, name: string, baseUrl: string) {
|
||||
return isVllmEndpoint(name, baseUrl) ? "openai" : type
|
||||
return isVllmEndpoint(name, baseUrl) || isOllamaEndpoint(name, baseUrl) ? "openai" : type
|
||||
}
|
||||
|
||||
function redactSecretOutput(value: string, secrets: string[] = []) {
|
||||
@@ -153,7 +157,7 @@ export async function POST(request: Request) {
|
||||
const credentialKey = optionalString(body?.credentialKey) || "OPENAI_API_KEY"
|
||||
const makeActive = body?.makeActive !== false
|
||||
const system = body?.route === "system" || body?.system === true
|
||||
const noVerify = body?.noVerify !== false || isVllmEndpoint(name, baseUrl)
|
||||
const noVerify = body?.noVerify !== false || isVllmEndpoint(name, baseUrl) || isOllamaEndpoint(name, baseUrl)
|
||||
const timeout = Number(body?.timeout ?? 0)
|
||||
|
||||
if (makeActive && !model) throw new Error("model is required when making the endpoint active")
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost'
|
||||
import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances'
|
||||
import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority'
|
||||
import { extractOpenClawDashboardToken, setOpenClawDashboardTokenCookie } from '../../../../lib/openclawDashboardToken'
|
||||
|
||||
function parseInventoryCount(requestUrl: URL) {
|
||||
const raw = requestUrl.searchParams.get('inventoryCount')
|
||||
@@ -14,12 +15,37 @@ function firstHeaderValue(value: string | null) {
|
||||
return value?.split(',')[0]?.trim() || null
|
||||
}
|
||||
|
||||
function getConfiguredBaseWsUrl() {
|
||||
return process.env.OPENCLAW_DASHBOARD_BASE_WS_URL?.trim() || process.env.BASE_WS_URL?.trim() || null
|
||||
}
|
||||
|
||||
function normalizeBrowserWebSocketBase(value: string | null, proxiedUrl: string) {
|
||||
if (!value) return null
|
||||
const parsed = new URL(value)
|
||||
if (parsed.protocol === 'http:') parsed.protocol = 'ws:'
|
||||
if (parsed.protocol === 'https:') parsed.protocol = 'wss:'
|
||||
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
|
||||
throw new Error('OPENCLAW_DASHBOARD_BASE_WS_URL/BASE_WS_URL must use ws://, wss://, http://, or https://')
|
||||
}
|
||||
|
||||
parsed.hash = ''
|
||||
if (parsed.pathname === '/' || parsed.pathname === '') {
|
||||
parsed.pathname = proxiedUrl
|
||||
} else {
|
||||
parsed.pathname = parsed.pathname.replace(/\/+$/, '') || '/'
|
||||
}
|
||||
return parsed.toString()
|
||||
}
|
||||
|
||||
function buildBrowserGatewayUrl(request: Request, requestUrl: URL, proxiedUrl: string) {
|
||||
const configuredBaseWsUrl = normalizeBrowserWebSocketBase(getConfiguredBaseWsUrl(), proxiedUrl)
|
||||
if (configuredBaseWsUrl) return configuredBaseWsUrl
|
||||
|
||||
const forwardedProtocol = firstHeaderValue(request.headers.get('x-forwarded-proto'))
|
||||
const forwardedHost = firstHeaderValue(request.headers.get('x-forwarded-host'))
|
||||
const host = forwardedHost || request.headers.get('host') || requestUrl.host
|
||||
const protocol = (forwardedProtocol || requestUrl.protocol.replace(/:$/, '')) === 'https' ? 'wss:' : 'ws:'
|
||||
const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '3001'
|
||||
const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || ''
|
||||
const gatewayHost = wsProxyPort
|
||||
? new URL(`${requestUrl.protocol}//${host}`).hostname + `:${wsProxyPort}`
|
||||
: host
|
||||
@@ -82,7 +108,7 @@ export async function GET(request: Request) {
|
||||
const proxiedUrl = authority.bridgeActive ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy'
|
||||
const launchUrl = buildLaunchUrl(request, requestUrl, proxiedUrl, probe.bootstrapUrl)
|
||||
|
||||
return NextResponse.json({
|
||||
const response = NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
sandboxInstanceId: mappedSandboxInstanceId,
|
||||
@@ -130,4 +156,6 @@ export async function GET(request: Request) {
|
||||
? 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
|
||||
: 'OpenClaw Dashboard is reachable directly for this instance.'
|
||||
})
|
||||
setOpenClawDashboardTokenCookie(response, request, proxiedUrl, extractOpenClawDashboardToken(probe.bootstrapUrl))
|
||||
return response
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost'
|
||||
import { OPENCLAW_DASHBOARD_TOKEN_COOKIE } from '@/app/lib/openclawDashboardToken'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
const LEGACY_PROXY_PREFIX = '/api/openshell/dashboard/proxy'
|
||||
const INSTANCES_PREFIX = '/api/openshell/instances/'
|
||||
const DASHBOARD_PROXY_SUFFIX = '/dashboard/proxy'
|
||||
const BOOTSTRAP_SCRIPT_NAME = '__nemoclaw_openclaw_bootstrap.js'
|
||||
const CONTROL_AUTH_COOKIE_NAME = 'openshell_control_session'
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'accept-encoding',
|
||||
'connection',
|
||||
@@ -95,6 +97,7 @@ function buildTargetUrl(requestUrl: URL) {
|
||||
|
||||
function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: string) {
|
||||
const headers = new Headers()
|
||||
const dashboardToken = readCookieValue(request.headers.get('cookie'), OPENCLAW_DASHBOARD_TOKEN_COOKIE)
|
||||
|
||||
request.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
@@ -104,16 +107,42 @@ function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: stri
|
||||
lowerKey !== 'origin' &&
|
||||
lowerKey !== 'referer'
|
||||
) {
|
||||
headers.set(key, value)
|
||||
const filteredValue = lowerKey === 'cookie' ? filterCookieHeader(value) : value
|
||||
if (filteredValue) headers.set(key, filteredValue)
|
||||
}
|
||||
})
|
||||
|
||||
headers.set('host', target.host)
|
||||
headers.set('origin', controlUiOrigin)
|
||||
headers.set('referer', `${controlUiOrigin}/`)
|
||||
if (dashboardToken && !headers.has('authorization')) {
|
||||
headers.set('authorization', `Bearer ${dashboardToken}`)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
function readCookieValue(value: string | null, name: string) {
|
||||
return String(value || '')
|
||||
.split(';')
|
||||
.map((part) => part.trim())
|
||||
.reduce<string | null>((found, part) => {
|
||||
if (found || !part.startsWith(`${name}=`)) return found
|
||||
try {
|
||||
return decodeURIComponent(part.slice(name.length + 1))
|
||||
} catch {
|
||||
return part.slice(name.length + 1)
|
||||
}
|
||||
}, null)
|
||||
}
|
||||
|
||||
function filterCookieHeader(value: string) {
|
||||
return value
|
||||
.split(';')
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part && !part.startsWith(`${CONTROL_AUTH_COOKIE_NAME}=`) && !part.startsWith(`${OPENCLAW_DASHBOARD_TOKEN_COOKIE}=`))
|
||||
.join('; ')
|
||||
}
|
||||
|
||||
function copyResponseHeaders(upstream: Response) {
|
||||
const headers = new Headers()
|
||||
|
||||
@@ -151,24 +180,46 @@ function isBootstrapScriptRequest(requestUrl: URL, proxyPrefix: string) {
|
||||
}
|
||||
|
||||
function bootstrapScriptResponse(proxyPrefix: string) {
|
||||
const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '3001'
|
||||
const baseWsUrl = process.env.OPENCLAW_DASHBOARD_BASE_WS_URL?.trim() || process.env.BASE_WS_URL?.trim() || ''
|
||||
const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || ''
|
||||
const script = `
|
||||
(() => {
|
||||
const proxyPrefix = ${JSON.stringify(proxyPrefix)};
|
||||
const baseWsUrl = ${JSON.stringify(baseWsUrl)};
|
||||
const wsProxyPort = ${JSON.stringify(wsProxyPort)};
|
||||
window.__OPENCLAW_CONTROL_UI_BASE_PATH__ = proxyPrefix;
|
||||
|
||||
try {
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const pageGatewayUrl = protocol + '//' + window.location.host + proxyPrefix;
|
||||
const sidecarHost = wsProxyPort ? window.location.hostname + ':' + wsProxyPort : window.location.host;
|
||||
const sidecarGatewayUrl = protocol + '//' + sidecarHost + proxyPrefix;
|
||||
const portGatewayUrl = wsProxyPort ? protocol + '//' + window.location.hostname + ':' + wsProxyPort + proxyPrefix : '';
|
||||
const normalizeGatewayUrl = (value) => {
|
||||
const raw = (value || '').trim();
|
||||
if (!raw) return '';
|
||||
try {
|
||||
const parsed = new URL(raw, window.location.href);
|
||||
if (parsed.protocol === 'http:') parsed.protocol = 'ws:';
|
||||
if (parsed.protocol === 'https:') parsed.protocol = 'wss:';
|
||||
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') return '';
|
||||
parsed.hash = '';
|
||||
if (parsed.pathname === '/' || parsed.pathname === '') {
|
||||
parsed.pathname = proxyPrefix;
|
||||
} else {
|
||||
parsed.pathname = parsed.pathname.replace(/\\/+$/, '') || '/';
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
const configuredGatewayUrl = normalizeGatewayUrl(baseWsUrl);
|
||||
const defaultGatewayUrl = configuredGatewayUrl || portGatewayUrl || pageGatewayUrl;
|
||||
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 hashParams = new URLSearchParams(window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash);
|
||||
const gatewayUrl = (hashParams.get('gatewayUrl') || '').trim() || sidecarGatewayUrl;
|
||||
const gatewayUrl = normalizeGatewayUrl(hashParams.get('gatewayUrl')) || defaultGatewayUrl;
|
||||
const token = (hashParams.get('token') || '').trim();
|
||||
const storageScope = (value) => {
|
||||
try {
|
||||
@@ -180,7 +231,7 @@ function bootstrapScriptResponse(proxyPrefix: string) {
|
||||
}
|
||||
};
|
||||
const uniqueScopes = (values) => Array.from(new Set(values.map(storageScope).filter(Boolean)));
|
||||
const gatewayScopes = uniqueScopes([gatewayUrl, sidecarGatewayUrl, pageGatewayUrl]);
|
||||
const gatewayScopes = uniqueScopes([gatewayUrl, configuredGatewayUrl, portGatewayUrl, pageGatewayUrl]);
|
||||
const settingsKeys = gatewayScopes.map((scope) => settingsPrefix + scope);
|
||||
const readSettings = () => {
|
||||
for (const key of [...settingsKeys, settingsPrefix + 'default', settingsKey]) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { execOpenShell, normalizeSandboxPhase, resolveSandboxRef } from "@/app/lib/openshellHost"
|
||||
import { listBackupCatalog } from "@/app/lib/backupCatalog"
|
||||
import { getNemoClawDoctorReport } from "@/app/lib/nemoclawCli"
|
||||
|
||||
function parseField(output: string, label: string) {
|
||||
const normalizedLabel = label.toLowerCase()
|
||||
@@ -23,6 +24,15 @@ export async function GET(
|
||||
const phase = normalizeSandboxPhase(parseField(resolved.details, "Phase"))
|
||||
const catalog = await listBackupCatalog()
|
||||
const relatedBackups = catalog.filter((backup) => backup.sandboxId === sandboxId || backup.sandboxName === resolved.name)
|
||||
const nemoclawDoctor = await getNemoClawDoctorReport(resolved.name).catch((error) => ({
|
||||
available: false,
|
||||
supported: false,
|
||||
attempted: false,
|
||||
version: null,
|
||||
minimumVersion: "0.0.37",
|
||||
report: null,
|
||||
error: error instanceof Error ? error.message : "NemoClaw doctor check failed",
|
||||
}))
|
||||
|
||||
let sshConfig = ""
|
||||
let sshConfigError = ""
|
||||
@@ -60,6 +70,16 @@ export async function GET(
|
||||
? `${relatedBackups.length} saved backup${relatedBackups.length === 1 ? "" : "s"} in catalog.`
|
||||
: "No saved catalog backups yet.",
|
||||
},
|
||||
{
|
||||
key: "nemoclaw-doctor",
|
||||
label: "NemoClaw doctor",
|
||||
ok: !nemoclawDoctor.supported || Boolean(nemoclawDoctor.report && nemoclawDoctor.report.status !== "fail"),
|
||||
detail: nemoclawDoctor.supported
|
||||
? nemoclawDoctor.report
|
||||
? `NemoClaw ${nemoclawDoctor.version || "unknown"} doctor reported ${nemoclawDoctor.report.status} (${nemoclawDoctor.report.failed} failed, ${nemoclawDoctor.report.warnings} warnings).`
|
||||
: nemoclawDoctor.error || "NemoClaw doctor did not return a report."
|
||||
: `Using OpenShell compatibility checks; NemoClaw doctor requires ${nemoclawDoctor.minimumVersion}+${nemoclawDoctor.version ? `, found ${nemoclawDoctor.version}` : ""}.`,
|
||||
},
|
||||
]
|
||||
|
||||
return NextResponse.json({
|
||||
@@ -71,6 +91,19 @@ export async function GET(
|
||||
phase,
|
||||
},
|
||||
checks,
|
||||
nemoclaw: {
|
||||
doctor: {
|
||||
available: nemoclawDoctor.available,
|
||||
supported: nemoclawDoctor.supported,
|
||||
attempted: nemoclawDoctor.attempted,
|
||||
version: nemoclawDoctor.version,
|
||||
minimumVersion: nemoclawDoctor.minimumVersion,
|
||||
status: nemoclawDoctor.report?.status ?? null,
|
||||
failed: nemoclawDoctor.report?.failed ?? null,
|
||||
warnings: nemoclawDoctor.report?.warnings ?? null,
|
||||
error: nemoclawDoctor.error ?? null,
|
||||
},
|
||||
},
|
||||
backupCount: relatedBackups.length,
|
||||
durationMs: Date.now() - startedAt,
|
||||
checkedAt: new Date().toISOString(),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server"
|
||||
import { execFile } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
|
||||
import { recoverSandboxWithNemoClaw } from "@/app/lib/nemoclawCli"
|
||||
import { inspectSandbox, resolveSandboxRef } from "@/app/lib/openshellHost"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
@@ -100,6 +101,21 @@ export async function POST(
|
||||
}, { status: 409 })
|
||||
}
|
||||
|
||||
const nemoclawRecover = await recoverSandboxWithNemoClaw(sandboxName)
|
||||
if (nemoclawRecover.attempted && nemoclawRecover.ok) {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
restarted: true,
|
||||
restartMode: "nemoclaw-recover",
|
||||
sandboxId: resolved.id,
|
||||
sandboxName,
|
||||
readiness,
|
||||
nemoclawRecover,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
note: "NemoClaw recover completed. The sandbox runtime and dashboard forward were checked without deleting the sandbox.",
|
||||
})
|
||||
}
|
||||
|
||||
const runtime = await runSandboxShell(sandboxName, restartOpenClawGatewayScript(), 45000)
|
||||
|
||||
return NextResponse.json({
|
||||
@@ -109,9 +125,12 @@ export async function POST(
|
||||
sandboxId: resolved.id,
|
||||
sandboxName,
|
||||
readiness,
|
||||
nemoclawRecover,
|
||||
runtime,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
note: "OpenClaw runtime restarted inside the sandbox. The sandbox pod was not deleted.",
|
||||
note: nemoclawRecover.attempted
|
||||
? "NemoClaw recover did not complete, so the dashboard fell back to restarting the in-sandbox OpenClaw runtime. The sandbox pod was not deleted."
|
||||
: "OpenClaw runtime restarted inside the sandbox. The sandbox pod was not deleted.",
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to restart sandbox runtime"
|
||||
|
||||
@@ -40,6 +40,9 @@ const providerTypeOptions = [
|
||||
{ value: "generic", label: "Generic" },
|
||||
]
|
||||
|
||||
const OLLAMA_PROVIDER_NAME = "ollama-local"
|
||||
const OLLAMA_BASE_URL = "http://host.docker.internal:11434/v1"
|
||||
|
||||
function emptyRoute(): InferenceRoute {
|
||||
return { configured: false, provider: null, model: null, version: null, timeout: null }
|
||||
}
|
||||
@@ -111,7 +114,7 @@ export default function InferenceEndpointPanel() {
|
||||
}
|
||||
const models = Array.isArray(data.models) ? data.models : []
|
||||
setOllamaModels(models)
|
||||
setOllamaMessage(models.length > 0 ? `${models.length} Ollama model${models.length === 1 ? "" : "s"} available.` : "Ollama is reachable but has no models installed.")
|
||||
setOllamaMessage(models.length > 0 ? `${models.length} Ollama model${models.length === 1 ? "" : "s"} available. Click one to load the Ollama endpoint preset.` : "Ollama is reachable but has no models installed.")
|
||||
if (models[0]?.name) setModel((current) => current || models[0].name)
|
||||
} catch (error) {
|
||||
setOllamaModels([])
|
||||
@@ -122,11 +125,22 @@ export default function InferenceEndpointPanel() {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOllamaEndpoint) return
|
||||
loadOllamaModels({ silent: true })
|
||||
const interval = window.setInterval(() => loadOllamaModels({ silent: true }), 10000)
|
||||
return () => window.clearInterval(interval)
|
||||
}, [isOllamaEndpoint, loadOllamaModels])
|
||||
}, [loadOllamaModels])
|
||||
|
||||
function applyOllamaModelPreset(modelName: string) {
|
||||
setName(OLLAMA_PROVIDER_NAME)
|
||||
setType("openai")
|
||||
setModel(modelName)
|
||||
setBaseUrl(OLLAMA_BASE_URL)
|
||||
setCredentialKey("OPENAI_API_KEY")
|
||||
setApiKey("")
|
||||
setRoute("gateway")
|
||||
setNoVerify(true)
|
||||
setMessage(`Ollama preset loaded for ${modelName}. Save to route sandbox inference through local Ollama.`)
|
||||
}
|
||||
|
||||
function selectProvider(provider: ProviderSummary) {
|
||||
if (!provider.name) return
|
||||
@@ -134,7 +148,7 @@ export default function InferenceEndpointPanel() {
|
||||
setType(provider.type || "openai")
|
||||
setCredentialKey(provider.credentialKeys[0] || "OPENAI_API_KEY")
|
||||
if (provider.name.toLowerCase().includes("ollama")) {
|
||||
setBaseUrl("http://host.docker.internal:11434/v1")
|
||||
setBaseUrl(OLLAMA_BASE_URL)
|
||||
setApiKey("")
|
||||
}
|
||||
setMessage(`Loaded ${provider.name}. Enter a model and save to make it active.`)
|
||||
@@ -252,6 +266,32 @@ export default function InferenceEndpointPanel() {
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_360px] gap-6">
|
||||
<section className="space-y-4">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Ollama Models</h3>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">{ollamaMessage || "Polling local Ollama every 10 seconds."}</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => loadOllamaModels()} disabled={ollamaLoading} className="px-3 py-2 rounded-sm bg-[var(--background)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)] disabled:opacity-50">
|
||||
{ollamaLoading ? "Polling..." : "Poll"}
|
||||
</button>
|
||||
</div>
|
||||
{ollamaModels.length > 0 ? (
|
||||
<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2">
|
||||
{ollamaModels.map((item) => (
|
||||
<button key={item.name} type="button" onClick={() => applyOllamaModelPreset(item.name)} className={`rounded-sm border p-3 text-left ${isOllamaEndpoint && model === item.name ? "border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]" : "border-[var(--border-subtle)] bg-[var(--background)] hover:border-[var(--nvidia-green)]"}`}>
|
||||
<div className="text-xs font-mono text-[var(--foreground)]">{item.name}</div>
|
||||
<div className="mt-1 text-[11px] text-[var(--foreground-dim)]">
|
||||
{[item.parameterSize, item.quantization, item.sizeLabel].filter(Boolean).join(" · ") || item.family || "local model"}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-3 text-xs text-[var(--foreground-dim)]">No local Ollama models reported.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<FieldLabel>Provider Name</FieldLabel>
|
||||
@@ -303,32 +343,6 @@ export default function InferenceEndpointPanel() {
|
||||
Skip provider verification while saving
|
||||
</label>
|
||||
|
||||
{isOllamaEndpoint && (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Ollama Models</h3>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">{ollamaMessage || "Polling local Ollama every 10 seconds."}</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => loadOllamaModels()} disabled={ollamaLoading} className="px-3 py-2 rounded-sm bg-[var(--background)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)] disabled:opacity-50">
|
||||
{ollamaLoading ? "Polling..." : "Poll"}
|
||||
</button>
|
||||
</div>
|
||||
{ollamaModels.length > 0 && (
|
||||
<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2">
|
||||
{ollamaModels.map((item) => (
|
||||
<button key={item.name} type="button" onClick={() => setModel(item.name)} className={`rounded-sm border p-3 text-left ${model === item.name ? "border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]" : "border-[var(--border-subtle)] bg-[var(--background)]"}`}>
|
||||
<div className="text-xs font-mono text-[var(--foreground)]">{item.name}</div>
|
||||
<div className="mt-1 text-[11px] text-[var(--foreground-dim)]">
|
||||
{[item.parameterSize, item.quantization, item.sizeLabel].filter(Boolean).join(" · ") || item.family || "local model"}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button onClick={saveEndpoint} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">
|
||||
{saving ? "Saving..." : "Save Endpoint"}
|
||||
|
||||
+46
-1
@@ -1,6 +1,13 @@
|
||||
const COOKIE_NAME = "openshell_control_session"
|
||||
const SESSION_TTL_SECONDS = 12 * 60 * 60
|
||||
|
||||
type CookieSecurityRequest = {
|
||||
headers: Pick<Headers, "get">
|
||||
nextUrl?: {
|
||||
protocol: string
|
||||
}
|
||||
}
|
||||
|
||||
type SessionPayload = {
|
||||
sub: string
|
||||
iat: number
|
||||
@@ -24,6 +31,37 @@ function isDisabled() {
|
||||
return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_AUTH_DISABLED || "")
|
||||
}
|
||||
|
||||
function envFlag(value: string | undefined) {
|
||||
if (!value) return null
|
||||
if (/^(1|true|yes|on)$/i.test(value)) return true
|
||||
if (/^(0|false|no|off)$/i.test(value)) return false
|
||||
return null
|
||||
}
|
||||
|
||||
function firstForwardedValue(value: string | null) {
|
||||
return value?.split(",")[0]?.trim().toLowerCase() || ""
|
||||
}
|
||||
|
||||
function publicBaseUsesHttps() {
|
||||
if (!process.env.PUBLIC_BASE_URL) return false
|
||||
try {
|
||||
return new URL(process.env.PUBLIC_BASE_URL).protocol === "https:"
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldUseSecureSessionCookie(request?: CookieSecurityRequest) {
|
||||
const forced = envFlag(process.env.OPENSHELL_CONTROL_COOKIE_SECURE)
|
||||
if (forced !== null) return forced
|
||||
|
||||
const forwardedProto = request ? firstForwardedValue(request.headers.get("x-forwarded-proto")) : ""
|
||||
if (forwardedProto) return forwardedProto === "https"
|
||||
|
||||
if (request?.nextUrl?.protocol === "https:") return true
|
||||
return publicBaseUsesHttps()
|
||||
}
|
||||
|
||||
async function hmac(payload: string) {
|
||||
const key = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
@@ -99,7 +137,14 @@ export async function verifyRecoveryToken(token: string) {
|
||||
export const sessionCookieOptions = {
|
||||
httpOnly: true,
|
||||
sameSite: "lax" as const,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
secure: shouldUseSecureSessionCookie(),
|
||||
path: "/",
|
||||
maxAge: SESSION_TTL_SECONDS,
|
||||
}
|
||||
|
||||
export function sessionCookieOptionsForRequest(request: CookieSecurityRequest) {
|
||||
return {
|
||||
...sessionCookieOptions,
|
||||
secure: shouldUseSecureSessionCookie(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,7 @@ function buildEnvBlock(input: {
|
||||
`CONTROLLER_NODE_ID=${input.controllerName}`,
|
||||
`CONTROLLER_NODE_PARENT_URL=${input.parentControllerUrl}`,
|
||||
`CONTROLLER_NODE_SHARED_SECRET=${input.token}`,
|
||||
`PORT=${input.dashboardPort}`,
|
||||
`NEXT_PUBLIC_DASHBOARD_PORT=${input.dashboardPort}`,
|
||||
"NEXT_PUBLIC_API_BASE=",
|
||||
"NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true",
|
||||
@@ -217,7 +218,7 @@ ENV_CONTROLLER_NODE
|
||||
|
||||
touch .env.local
|
||||
TMP_ENV="$(mktemp)"
|
||||
grep -Ev '^(CONTROLLER_NODE_ID|CONTROLLER_NODE_PARENT_URL|CONTROLLER_NODE_SHARED_SECRET|NEXT_PUBLIC_DASHBOARD_PORT|NEXT_PUBLIC_API_BASE|NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS|OPENSHELL_GATEWAY|OPEN_SHELL_CONTAINER|TERMINAL_SERVER_AUTOSTART|TERMINAL_SERVER_PORT|OPENCLAW_DASHBOARD_URL|OPENCLAW_INSTANCE_REGISTRY_JSON)=' .env.local > "$TMP_ENV" || true
|
||||
grep -Ev '^(CONTROLLER_NODE_ID|CONTROLLER_NODE_PARENT_URL|CONTROLLER_NODE_SHARED_SECRET|PORT|NEXT_PUBLIC_DASHBOARD_PORT|NEXT_PUBLIC_API_BASE|NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS|OPENSHELL_GATEWAY|OPEN_SHELL_CONTAINER|TERMINAL_SERVER_AUTOSTART|TERMINAL_SERVER_PORT|OPENCLAW_DASHBOARD_URL|OPENCLAW_INSTANCE_REGISTRY_JSON)=' .env.local > "$TMP_ENV" || true
|
||||
cat "$TMP_ENV" .env.controller-node > .env.local
|
||||
rm -f "$TMP_ENV"
|
||||
chmod 600 .env.local .env.controller-node
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { execFile } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { NEMOCLAW_BIN, NODE_BIN, commandExists, hostCommandEnv } from "./hostCommands"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const NEMOCLAW_RECOVERY_MIN_VERSION = "0.0.37"
|
||||
|
||||
type NemoClawInvocation = {
|
||||
file: string
|
||||
args: string[]
|
||||
display: string[]
|
||||
}
|
||||
|
||||
type NemoClawRunResult = {
|
||||
ok: boolean
|
||||
stdout: string
|
||||
stderr: string
|
||||
exitCode: number | null
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export type NemoClawDoctorCheck = {
|
||||
group: string
|
||||
label: string
|
||||
status: "ok" | "warn" | "fail" | "info"
|
||||
detail: string
|
||||
hint?: string
|
||||
}
|
||||
|
||||
export type NemoClawDoctorReport = {
|
||||
schemaVersion: number
|
||||
sandbox: string
|
||||
status: "ok" | "warn" | "fail" | "info"
|
||||
failed: number
|
||||
warnings: number
|
||||
checks: NemoClawDoctorCheck[]
|
||||
}
|
||||
|
||||
function buildNemoClawInvocation(args: string[]): NemoClawInvocation | null {
|
||||
if (!commandExists(NEMOCLAW_BIN)) return null
|
||||
if (/\.(?:c?m?js|ts)$/i.test(NEMOCLAW_BIN)) {
|
||||
return {
|
||||
file: NODE_BIN,
|
||||
args: [NEMOCLAW_BIN, ...args],
|
||||
display: [NODE_BIN, NEMOCLAW_BIN, ...args],
|
||||
}
|
||||
}
|
||||
return {
|
||||
file: NEMOCLAW_BIN,
|
||||
args,
|
||||
display: [NEMOCLAW_BIN, ...args],
|
||||
}
|
||||
}
|
||||
|
||||
function parseVersion(value: string) {
|
||||
return value.match(/v?(\d+\.\d+\.\d+)/)?.[1] ?? null
|
||||
}
|
||||
|
||||
function versionGte(left: string, right: string) {
|
||||
const leftParts = left.split(".").map((part) => Number.parseInt(part, 10) || 0)
|
||||
const rightParts = right.split(".").map((part) => Number.parseInt(part, 10) || 0)
|
||||
const length = Math.max(leftParts.length, rightParts.length)
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const a = leftParts[index] || 0
|
||||
const b = rightParts[index] || 0
|
||||
if (a > b) return true
|
||||
if (a < b) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function parseJsonObject(value: string) {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return null
|
||||
try {
|
||||
return JSON.parse(trimmed)
|
||||
} catch {
|
||||
const start = trimmed.indexOf("{")
|
||||
const end = trimmed.lastIndexOf("}")
|
||||
if (start === -1 || end === -1 || end <= start) return null
|
||||
return JSON.parse(trimmed.slice(start, end + 1))
|
||||
}
|
||||
}
|
||||
|
||||
async function runNemoClaw(args: string[], timeout = 30000): Promise<NemoClawRunResult & { command: string[] }> {
|
||||
const invocation = buildNemoClawInvocation(args)
|
||||
if (!invocation) {
|
||||
return {
|
||||
ok: false,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: null,
|
||||
error: "NemoClaw CLI is not available",
|
||||
command: [NEMOCLAW_BIN, ...args],
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(invocation.file, invocation.args, {
|
||||
env: hostCommandEnv({
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}),
|
||||
timeout,
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
})
|
||||
return {
|
||||
ok: true,
|
||||
stdout: String(stdout).trim(),
|
||||
stderr: String(stderr).trim(),
|
||||
exitCode: 0,
|
||||
error: null,
|
||||
command: invocation.display,
|
||||
}
|
||||
} catch (error: any) {
|
||||
return {
|
||||
ok: false,
|
||||
stdout: String(error?.stdout || "").trim(),
|
||||
stderr: String(error?.stderr || "").trim(),
|
||||
exitCode: typeof error?.code === "number" ? error.code : null,
|
||||
error: error instanceof Error ? error.message : String(error ?? "NemoClaw command failed"),
|
||||
command: invocation.display,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getNemoClawVersion() {
|
||||
const result = await runNemoClaw(["--version"], 10000)
|
||||
const version = parseVersion(`${result.stdout}\n${result.stderr}`)
|
||||
return {
|
||||
available: result.ok || Boolean(version),
|
||||
version,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
error: result.ok ? null : result.error,
|
||||
command: result.command,
|
||||
}
|
||||
}
|
||||
|
||||
async function hasModernNemoClawSurface() {
|
||||
const version = await getNemoClawVersion()
|
||||
return {
|
||||
...version,
|
||||
supported: version.version ? versionGte(version.version, NEMOCLAW_RECOVERY_MIN_VERSION) : false,
|
||||
minimumVersion: NEMOCLAW_RECOVERY_MIN_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getNemoClawDoctorReport(sandboxName: string) {
|
||||
const capability = await hasModernNemoClawSurface()
|
||||
if (!capability.supported) {
|
||||
return {
|
||||
available: capability.available,
|
||||
supported: false,
|
||||
attempted: false,
|
||||
version: capability.version,
|
||||
minimumVersion: capability.minimumVersion,
|
||||
report: null as NemoClawDoctorReport | null,
|
||||
error: capability.available
|
||||
? `NemoClaw ${capability.version || "unknown"} does not expose doctor --json`
|
||||
: capability.error || "NemoClaw CLI is not available",
|
||||
}
|
||||
}
|
||||
|
||||
const result = await runNemoClaw([sandboxName, "doctor", "--json"], 30000)
|
||||
const parsed = result.ok ? parseJsonObject(result.stdout) : null
|
||||
const report = parsed && typeof parsed === "object" ? parsed as NemoClawDoctorReport : null
|
||||
|
||||
return {
|
||||
available: true,
|
||||
supported: true,
|
||||
attempted: true,
|
||||
version: capability.version,
|
||||
minimumVersion: capability.minimumVersion,
|
||||
report,
|
||||
error: report ? null : result.error || result.stderr || "NemoClaw doctor did not return JSON",
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
exitCode: result.exitCode,
|
||||
}
|
||||
}
|
||||
|
||||
export async function recoverSandboxWithNemoClaw(sandboxName: string) {
|
||||
const capability = await hasModernNemoClawSurface()
|
||||
if (!capability.supported) {
|
||||
return {
|
||||
available: capability.available,
|
||||
supported: false,
|
||||
attempted: false,
|
||||
version: capability.version,
|
||||
minimumVersion: capability.minimumVersion,
|
||||
ok: false,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: null as number | null,
|
||||
error: capability.available
|
||||
? `NemoClaw ${capability.version || "unknown"} does not expose sandbox recover`
|
||||
: capability.error || "NemoClaw CLI is not available",
|
||||
}
|
||||
}
|
||||
|
||||
const result = await runNemoClaw([sandboxName, "recover"], 90000)
|
||||
return {
|
||||
available: true,
|
||||
supported: true,
|
||||
attempted: true,
|
||||
version: capability.version,
|
||||
minimumVersion: capability.minimumVersion,
|
||||
ok: result.ok,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
exitCode: result.exitCode,
|
||||
error: result.error,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { NextResponse } from "next/server"
|
||||
import { shouldUseSecureSessionCookie } from "./controlAuth"
|
||||
|
||||
export const OPENCLAW_DASHBOARD_TOKEN_COOKIE = "openclaw_dashboard_token"
|
||||
const DASHBOARD_TOKEN_TTL_SECONDS = 12 * 60 * 60
|
||||
|
||||
export function dashboardTokenCookieOptions(request: Request, path: string) {
|
||||
return {
|
||||
httpOnly: true,
|
||||
sameSite: "lax" as const,
|
||||
secure: shouldUseSecureSessionCookie({
|
||||
headers: request.headers,
|
||||
nextUrl: new URL(request.url),
|
||||
}),
|
||||
path,
|
||||
maxAge: DASHBOARD_TOKEN_TTL_SECONDS,
|
||||
}
|
||||
}
|
||||
|
||||
export function extractOpenClawDashboardToken(url: string | null | undefined) {
|
||||
if (!url) return null
|
||||
try {
|
||||
const parsed = new URL(url)
|
||||
const hash = parsed.hash.startsWith("#") ? parsed.hash.slice(1) : parsed.hash
|
||||
return new URLSearchParams(hash).get("token")?.trim() || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setOpenClawDashboardTokenCookie(response: NextResponse, request: Request, path: string, token: string | null) {
|
||||
if (!token) return
|
||||
response.cookies.set(OPENCLAW_DASHBOARD_TOKEN_COOKIE, token, dashboardTokenCookieOptions(request, path))
|
||||
}
|
||||
Reference in New Issue
Block a user