fix: follow native OpenClaw config ownership (#53)

Route controller-managed OpenClaw MCP and inference updates through the native config patch boundary and retire stale config-hash writes.
This commit is contained in:
mmckeen-nv
2026-09-28 23:08:48 -07:00
committed by GitHub
parent 52fe7a2d83
commit 11840644c8
6 changed files with 101 additions and 139 deletions
+2
View File
@@ -229,6 +229,8 @@ The **Quick Deploy New NemoClaw Sandbox** path clones a registered image through
Sandbox gateway restarts use NemoClaw's native-agent lifecycle command. The controller does not kill or launch OpenClaw or Hermes gateway processes directly; if NemoClaw cannot verify the restart, the request fails without bypassing the agent-owned lifecycle boundary.
OpenClaw owns `openclaw.json` after first launch. Controller-managed MCP and inference updates use OpenClaw's native `config patch --stdin` boundary and do not replace the file or recreate NemoClaw's retired `.config-hash` ownership metadata.
OpenClaw dashboard access is loopback-only inside the host/sandbox context, so the UI uses local proxy routes:
- `/api/openshell/dashboard/proxy`
+65
View File
@@ -0,0 +1,65 @@
import { spawn } from "node:child_process"
import { OPENSHELL_BIN, hostCommandEnv } from "./hostCommands"
export type OpenClawConfigPatch = Record<string, unknown>
export function applyNativeOpenClawConfigPatch(
sandboxName: string,
patch: OpenClawConfigPatch,
timeoutMs = 60000,
) {
const payload = JSON.stringify(patch)
return new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve, reject) => {
const child = spawn(
OPENSHELL_BIN,
[
"sandbox",
"exec",
"-n",
sandboxName,
"--env",
"HOME=/sandbox",
"--",
"openclaw",
"config",
"patch",
"--stdin",
],
{
env: hostCommandEnv({
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY?.trim() || undefined,
}),
stdio: ["pipe", "pipe", "pipe"],
},
)
let stdout = ""
let stderr = ""
let settled = false
const timer = setTimeout(() => child.kill("SIGTERM"), timeoutMs)
child.stdout.on("data", (chunk) => { stdout += String(chunk) })
child.stderr.on("data", (chunk) => { stderr += String(chunk) })
child.on("error", (error) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(error)
})
child.on("close", (code) => {
if (settled) return
settled = true
clearTimeout(timer)
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code })
})
child.stdin.end(payload)
})
}
export async function writeNativeOpenClawConfigPatch(
sandboxName: string,
patch: OpenClawConfigPatch,
failureMessage: string,
) {
const result = await applyNativeOpenClawConfigPatch(sandboxName, patch)
if (result.code !== 0) throw new Error(result.stderr || failureMessage)
return result
}
+10 -52
View File
@@ -1,7 +1,8 @@
import { execFile, spawn } from "node:child_process"
import { execFile } from "node:child_process"
import { promisify } from "node:util"
import { OPENSHELL_BIN, hostCommandEnv } from "./hostCommands"
import { restartSandboxGatewayWithNemoClaw } from "./nemoclawCli"
import { writeNativeOpenClawConfigPatch } from "./openClawNativeConfig"
import { getSandboxInferenceConfig, type SandboxInferenceRoute } from "./sandboxInferenceStore"
const execFileAsync = promisify(execFile)
@@ -107,11 +108,9 @@ function resolveOpenClawRoute(route: SandboxInferenceRoute) {
}
}
function buildOpenClawConfig(current: any, routes: SandboxInferenceRoute[], primary: SandboxInferenceRoute) {
function buildOpenClawConfigPatch(routes: SandboxInferenceRoute[], primary: SandboxInferenceRoute) {
const providers: Record<string, any> = {}
let primaryModelRef = primary.model
const channelDefaults = { ...(current?.channels?.defaults || {}) }
delete channelDefaults.configWrites
for (const route of routes.filter((item) => item.enabled)) {
const resolved = resolveOpenClawRoute(route)
@@ -126,26 +125,20 @@ function buildOpenClawConfig(current: any, routes: SandboxInferenceRoute[], prim
}
return {
...current,
agents: {
...(current?.agents || {}),
defaults: {
...(current?.agents?.defaults || {}),
model: {
...(current?.agents?.defaults?.model || {}),
primary: primaryModelRef,
},
},
},
models: {
...(current?.models || {}),
mode: "merge",
providers,
},
channels: {
...(current?.channels || {}),
defaults: {
...channelDefaults,
configWrites: null,
},
},
}
@@ -162,53 +155,18 @@ async function runOpenShell(args: string[]) {
return { stdout: String(stdout).trim(), stderr: String(stderr).trim() }
}
async function runOpenShellExec(sandboxName: string, script: string, input?: string) {
return await new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve, reject) => {
const child = spawn(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
env: hostCommandEnv({
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY?.trim() || undefined,
}),
stdio: ["pipe", "pipe", "pipe"],
})
let stdout = ""
let stderr = ""
child.stdout.on("data", (chunk) => { stdout += String(chunk) })
child.stderr.on("data", (chunk) => { stderr += String(chunk) })
child.on("error", reject)
child.on("close", (code) => resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code }))
if (input) child.stdin.end(input)
else child.stdin.end()
})
}
async function readCurrentOpenClawConfig(sandboxName: string) {
const result = await runOpenShellExec(sandboxName, "cat /sandbox/.openclaw/openclaw.json")
if (result.code !== 0) throw new Error(result.stderr || "Failed to read OpenClaw config")
return JSON.parse(result.stdout)
}
async function writeOpenClawConfig(sandboxName: string, config: any) {
const payload = `${JSON.stringify(config, null, 2)}\n`
const script = [
"cat > /sandbox/.openclaw/openclaw.json",
"chmod 600 /sandbox/.openclaw/openclaw.json",
"sha256sum /sandbox/.openclaw/openclaw.json > /sandbox/.openclaw/.config-hash",
"chmod 600 /sandbox/.openclaw/.config-hash",
].join(" && ")
const result = await runOpenShellExec(sandboxName, script, payload)
if (result.code !== 0) throw new Error(result.stderr || "Failed to write OpenClaw config")
return result
}
export async function applySandboxInferenceProfile(sandboxId: string, sandboxName: string) {
const config = await getSandboxInferenceConfig(sandboxId)
const enabledRoutes = config.routes.filter((route) => route.enabled)
if (enabledRoutes.length === 0) throw new Error("No enabled inference routes are configured for this sandbox")
const primary = enabledRoutes.find((route) => route.id === config.primaryRouteId) || enabledRoutes[0]
const currentOpenClawConfig = await readCurrentOpenClawConfig(sandboxName)
const nextOpenClawConfig = buildOpenClawConfig(currentOpenClawConfig, enabledRoutes, primary)
await writeOpenClawConfig(sandboxName, nextOpenClawConfig)
const openClawPatch = buildOpenClawConfigPatch(enabledRoutes, primary)
await writeNativeOpenClawConfigPatch(
sandboxName,
openClawPatch,
"Failed to apply native OpenClaw inference config",
)
const routeResult = await runOpenShell(["inference", "set", "--no-verify", "--provider", primary.provider, "--model", primary.model])
const restartResult = await restartSandboxGatewayWithNemoClaw(sandboxName)
if (!restartResult.ok) {
+11 -81
View File
@@ -1,67 +1,13 @@
import { spawn } from "node:child_process"
import { OPENSHELL_BIN, hostCommandEnv } from "./hostCommands"
import { restartSandboxGatewayWithNemoClaw } from "./nemoclawCli"
import { writeNativeOpenClawConfigPatch } from "./openClawNativeConfig"
export const OPENSHELL_CONTROL_MCP_SERVER_NAME = "openshell-control"
export const OPENCLAW_CONFIG_PATH = "/sandbox/.openclaw/openclaw.json"
const OPENCLAW_CONFIG_HASH_PATH = "/sandbox/.openclaw/.config-hash"
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value)
}
function normalizeBrokerBaseUrl(value: string) {
return value.replace(/\/+$/, "")
}
function runSandboxShell(sandboxName: string, script: string, input?: string, timeoutMs = 60000) {
return new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve, reject) => {
const child = spawn(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
env: hostCommandEnv({
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY?.trim() || undefined,
}),
stdio: ["pipe", "pipe", "pipe"],
})
let stdout = ""
let stderr = ""
const timer = setTimeout(() => child.kill("SIGTERM"), timeoutMs)
child.stdout.on("data", (chunk) => { stdout += String(chunk) })
child.stderr.on("data", (chunk) => { stderr += String(chunk) })
child.on("error", (error) => {
clearTimeout(timer)
reject(error)
})
child.on("close", (code) => {
clearTimeout(timer)
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code })
})
if (input) child.stdin.end(input)
else child.stdin.end()
})
}
async function readOpenClawConfig(sandboxName: string) {
const result = await runSandboxShell(sandboxName, `cat ${OPENCLAW_CONFIG_PATH}`)
if (result.code !== 0) throw new Error(result.stderr || "Failed to read OpenClaw config")
const parsed = JSON.parse(result.stdout)
if (!isRecord(parsed)) throw new Error("OpenClaw config must be a JSON object")
return parsed
}
async function writeOpenClawConfig(sandboxName: string, config: Record<string, unknown>) {
const payload = `${JSON.stringify(config, null, 2)}\n`
const script = [
`cat > ${OPENCLAW_CONFIG_PATH}`,
`chmod 0660 ${OPENCLAW_CONFIG_PATH}`,
`chown sandbox:sandbox ${OPENCLAW_CONFIG_PATH} 2>/dev/null || chown 998:998 ${OPENCLAW_CONFIG_PATH}`,
`sha256sum ${OPENCLAW_CONFIG_PATH} > ${OPENCLAW_CONFIG_HASH_PATH}`,
`chmod 0660 ${OPENCLAW_CONFIG_HASH_PATH}`,
`chown sandbox:sandbox ${OPENCLAW_CONFIG_HASH_PATH} 2>/dev/null || chown 998:998 ${OPENCLAW_CONFIG_HASH_PATH}`,
].join(" && ")
const result = await runSandboxShell(sandboxName, script, payload)
if (result.code !== 0) throw new Error(result.stderr || "Failed to write OpenClaw MCP config")
}
async function restartNativeGateway(sandboxName: string) {
const result = await restartSandboxGatewayWithNemoClaw(sandboxName)
if (!result.ok) {
@@ -88,18 +34,13 @@ export async function syncSandboxOpenClawMcpConfig(
brokerBaseUrl: string,
token: string,
) {
const current = await readOpenClawConfig(sandboxName)
const mcp = isRecord(current.mcp) ? { ...current.mcp } : {}
const servers = isRecord(mcp.servers) ? { ...mcp.servers } : {}
const serverConfig = buildOpenClawMcpServerConfig(brokerBaseUrl, token)
servers[OPENSHELL_CONTROL_MCP_SERVER_NAME] = serverConfig
mcp.servers = servers
await writeOpenClawConfig(sandboxName, {
...current,
mcp,
})
await writeNativeOpenClawConfigPatch(
sandboxName,
{ mcp: { servers: { [OPENSHELL_CONTROL_MCP_SERVER_NAME]: serverConfig } } },
"Failed to apply native OpenClaw MCP config",
)
await restartNativeGateway(sandboxName)
return {
@@ -111,22 +52,11 @@ export async function syncSandboxOpenClawMcpConfig(
}
export async function revokeSandboxOpenClawMcpConfig(sandboxName: string) {
const current = await readOpenClawConfig(sandboxName)
const mcp = isRecord(current.mcp) ? { ...current.mcp } : {}
const servers = isRecord(mcp.servers) ? { ...mcp.servers } : {}
delete servers[OPENSHELL_CONTROL_MCP_SERVER_NAME]
const nextConfig: Record<string, unknown> = { ...current }
if (Object.keys(servers).length > 0) {
mcp.servers = servers
nextConfig.mcp = mcp
} else {
delete mcp.servers
if (Object.keys(mcp).length > 0) nextConfig.mcp = mcp
else delete nextConfig.mcp
}
await writeOpenClawConfig(sandboxName, nextConfig)
await writeNativeOpenClawConfigPatch(
sandboxName,
{ mcp: { servers: { [OPENSHELL_CONTROL_MCP_SERVER_NAME]: null } } },
"Failed to remove native OpenClaw MCP config",
)
await restartNativeGateway(sandboxName)
return {
+7 -2
View File
@@ -27,6 +27,7 @@ const brokerMcpRoutePath = path.join(root, 'app/api/mcp/broker/mcp/route.ts')
const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts')
const brokerUrlPath = path.join(root, 'app/lib/mcpBrokerUrl.ts')
const sandboxOpenClawMcpConfigPath = path.join(root, 'app/lib/sandboxOpenClawMcpConfig.ts')
const openClawNativeConfigPath = path.join(root, 'app/lib/openClawNativeConfig.ts')
const sandboxPermissionsPath = path.join(root, 'app/lib/sandboxPermissions.ts')
const preflightLibPath = path.join(root, 'app/lib/mcpPreflight.ts')
const preflightRepairLibPath = path.join(root, 'app/lib/mcpPreflightRepair.ts')
@@ -43,7 +44,7 @@ const interSandboxChatPath = path.join(root, 'scripts/inter-sandbox-chat-mcp.mjs
const interSandboxChatOpenClawDispatchPath = path.join(root, 'scripts/inter-sandbox-chat-openclaw-dispatch.mjs')
const interSandboxChatSidecarPath = path.join(root, 'scripts/inter-sandbox-chat-sidecar.mjs')
const [storeSource, brokerStoreSource, brokerClientSource, brokerProtocolSource, sandboxAutoSyncSource, manifestSource, privilegedFilesSource, routeSource, uploadRouteSource, preflightRouteSource, healthRouteSource, registryRouteSource, registriesRouteSource, registriesAssistRouteSource, installAssistRouteSource, registryStoreSource, inferenceModelSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, brokerMcpRouteSource, sandboxMcpRouteSource, brokerUrlSource, sandboxOpenClawMcpConfigSource, sandboxPermissionsSource, preflightLibSource, preflightRepairLibSource, mcpServerSpecsSource, middlewareSource, panelSource, helpSource, sidebarSource, sandboxListSource, pageSource, interSandboxChatCoreSource, interSandboxChatSource, interSandboxChatOpenClawDispatchSource, interSandboxChatSidecarSource, serverSource] = await Promise.all([
const [storeSource, brokerStoreSource, brokerClientSource, brokerProtocolSource, sandboxAutoSyncSource, manifestSource, privilegedFilesSource, routeSource, uploadRouteSource, preflightRouteSource, healthRouteSource, registryRouteSource, registriesRouteSource, registriesAssistRouteSource, installAssistRouteSource, registryStoreSource, inferenceModelSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, brokerMcpRouteSource, sandboxMcpRouteSource, brokerUrlSource, sandboxOpenClawMcpConfigSource, openClawNativeConfigSource, sandboxPermissionsSource, preflightLibSource, preflightRepairLibSource, mcpServerSpecsSource, middlewareSource, panelSource, helpSource, sidebarSource, sandboxListSource, pageSource, interSandboxChatCoreSource, interSandboxChatSource, interSandboxChatOpenClawDispatchSource, interSandboxChatSidecarSource, serverSource] = await Promise.all([
readFile(storePath, 'utf8'),
readFile(brokerStorePath, 'utf8'),
readFile(brokerClientPath, 'utf8'),
@@ -67,6 +68,7 @@ const [storeSource, brokerStoreSource, brokerClientSource, brokerProtocolSource,
readFile(sandboxMcpRoutePath, 'utf8'),
readFile(brokerUrlPath, 'utf8'),
readFile(sandboxOpenClawMcpConfigPath, 'utf8'),
readFile(openClawNativeConfigPath, 'utf8'),
readFile(sandboxPermissionsPath, 'utf8'),
readFile(preflightLibPath, 'utf8'),
readFile(preflightRepairLibPath, 'utf8'),
@@ -186,7 +188,10 @@ assert.match(brokerUrlSource, /if \(!shouldUseProxyWrappedBrokerUrl\(\)\) return
assert.match(brokerUrlSource, /discoverSandboxProxyOrigin/, 'Sandbox MCP broker handoff must discover each sandbox proxy endpoint')
assert.match(brokerUrlSource, /HTTP_PROXY/, 'Sandbox MCP broker handoff must derive the proxy endpoint from sandbox environment')
assert.match(brokerUrlSource, /FALLBACK_SANDBOX_PROXY_ORIGIN/, 'Sandbox MCP broker handoff may keep a fallback for older OpenShell layouts')
assert.match(sandboxOpenClawMcpConfigSource, /mcp\.servers = servers/, 'Sandbox MCP sync must write mcp.servers into OpenClaw config')
assert.match(sandboxOpenClawMcpConfigSource, /writeNativeOpenClawConfigPatch/, 'Sandbox MCP sync must use OpenClaw native config ownership')
assert.match(openClawNativeConfigSource, /"openclaw",[\s\S]*"config",[\s\S]*"patch",[\s\S]*"--stdin"/, 'OpenClaw config helper must use the native patch stdin command')
assert.match(sandboxOpenClawMcpConfigSource, /\[OPENSHELL_CONTROL_MCP_SERVER_NAME\]: null/, 'Sandbox MCP revoke must remove only the controller-owned native config entry')
assert.doesNotMatch(sandboxOpenClawMcpConfigSource, /config-hash|cat > .*openclaw\.json|chmod .*openclaw\.json/, 'Sandbox MCP sync must not replace OpenClaw native config or recreate retired ownership metadata')
assert.match(sandboxOpenClawMcpConfigSource, /streamable-http/, 'OpenClaw MCP broker config must use streamable HTTP transport')
assert.match(sandboxOpenClawMcpConfigSource, /Authorization: `Bearer \$\{token\}`/, 'OpenClaw MCP broker config must pass the sandbox broker token as bearer auth')
assert.match(sandboxOpenClawMcpConfigSource, /restartSandboxGatewayWithNemoClaw/, 'MCP config changes must restart through NemoClaw native agent lifecycle')
+6 -4
View File
@@ -16,6 +16,7 @@ const ollamaModelsRoutePath = path.join(root, 'app/api/ollama/models/route.ts')
const sandboxInferenceRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/inference/route.ts')
const sandboxInferenceApplyRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/inference/apply/route.ts')
const sandboxInferenceApplyLibPath = path.join(root, 'app/lib/sandboxInferenceApply.ts')
const openClawNativeConfigPath = path.join(root, 'app/lib/openClawNativeConfig.ts')
const sandboxInferenceStorePath = path.join(root, 'app/lib/sandboxInferenceStore.ts')
const sandboxRestartRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/restart/route.ts')
const gatewayRepairRoutePath = path.join(root, 'app/api/openshell/gateway/repair/route.ts')
@@ -46,6 +47,7 @@ const ollamaModelsRouteSource = await readFile(ollamaModelsRoutePath, 'utf8')
const sandboxInferenceRouteSource = await readFile(sandboxInferenceRoutePath, 'utf8')
const sandboxInferenceApplyRouteSource = await readFile(sandboxInferenceApplyRoutePath, 'utf8')
const sandboxInferenceApplyLibSource = await readFile(sandboxInferenceApplyLibPath, 'utf8')
const openClawNativeConfigSource = await readFile(openClawNativeConfigPath, 'utf8')
const sandboxInferenceStoreSource = await readFile(sandboxInferenceStorePath, 'utf8')
const sandboxRestartRouteSource = await readFile(sandboxRestartRoutePath, 'utf8')
const gatewayRepairRouteSource = await readFile(gatewayRepairRoutePath, 'utf8')
@@ -280,10 +282,10 @@ assert.match(sandboxInferencePanelSource, /\/api\/sandbox\/\$\{encodeURIComponen
assert.match(sandboxInferencePanelSource, /\/api\/ollama\/models/, 'selected sandbox UI must offer Ollama model selection')
assert.match(sandboxInferencePanelSource, /Enabled Routes/, 'selected sandbox UI must show multiple enabled inference routes')
assert.match(sandboxInferencePanelSource, /Add Route/, 'selected sandbox UI must allow adding provider/model routes')
assert.match(sandboxInferenceApplyLibSource, /\/sandbox\/\.openclaw\/openclaw\.json/, 'live apply must patch OpenClaw config inside the running sandbox')
assert.match(sandboxInferenceApplyLibSource, /sha256sum \/sandbox\/\.openclaw\/openclaw\.json > \/sandbox\/\.openclaw\/\.config-hash/, 'live apply must refresh the immutable OpenClaw config hash')
assert.match(sandboxInferenceApplyLibSource, /spawn\(OPENSHELL_BIN, \["sandbox", "exec", "-n", sandboxName/, 'live apply must use the supported OpenShell sandbox exec boundary')
assert.match(sandboxInferenceApplyLibSource, /OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY\?\.trim\(\) \|\| undefined/, 'live apply must respect the active gateway unless explicitly configured')
assert.match(sandboxInferenceApplyLibSource, /writeNativeOpenClawConfigPatch/, 'live apply must use OpenClaw native config ownership')
assert.doesNotMatch(sandboxInferenceApplyLibSource, /config-hash|cat > .*openclaw\.json|chmod .*openclaw\.json/, 'live apply must not replace OpenClaw native config or recreate retired ownership metadata')
assert.match(openClawNativeConfigSource, /\[\s*"sandbox",[\s\S]*"exec",[\s\S]*"-n",[\s\S]*sandboxName,[\s\S]*"--env",[\s\S]*"HOME=\/sandbox",[\s\S]*"openclaw",[\s\S]*"config",[\s\S]*"patch",[\s\S]*"--stdin"/, 'native config writes must use OpenShell sandbox exec and OpenClaw config patch stdin')
assert.match(openClawNativeConfigSource, /OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY\?\.trim\(\) \|\| undefined/, 'live apply must respect the active gateway unless explicitly configured')
assert.doesNotMatch(sandboxInferenceApplyLibSource, /docker[\s\S]*kubectl|OPENSHELL_CLUSTER_CONTAINER/, 'live apply must not depend on obsolete cluster containers or in-container kubectl')
assert.doesNotMatch(sandboxInferenceApplyLibSource, /chmod 444|chown root:root/, 'live apply must leave OpenClaw config writable by the sandbox owner for subsequent updates')
assert.match(sandboxInferenceApplyLibSource, /\["inference", "set", "--no-verify", "--provider", primary\.provider, "--model", primary\.model\]/, 'live apply must point OpenShell inference at the primary route')