openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
373 lines (372 loc) • 13.8 kB
JavaScript
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { r as listAgentEntriesWithSource } from "./agent-roster-t1ooUdXp.mjs";
import "./agent-scope-config-DmXgFGKP.mjs";
import { i as resolveOpenClawPackageRootsSync } from "./openclaw-root-C-ayo09z.mjs";
import { n as resolveSandboxScope } from "./config-contract-D5fpm2xx.mjs";
import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import { n as runExec } from "./exec-aRIvS9s4.mjs";
import { S as SANDBOX_CONTAINERS_DIR, T as SANDBOX_REGISTRY_PATH, _ as SANDBOX_BROWSERS_DIR, r as DEFAULT_SANDBOX_BROWSER_IMAGE, s as DEFAULT_SANDBOX_COMMON_IMAGE, u as DEFAULT_SANDBOX_IMAGE, y as SANDBOX_BROWSER_REGISTRY_PATH } from "./constants-Dxjr8D5t.mjs";
import "./config-WbZbWrF1.mjs";
import { r as createRetiredStateInspectionError } from "./state-migrations.retired-files-CuvyprJk.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { n as PODMAN_SANDBOX_ENGINE, t as DOCKER_SANDBOX_ENGINE } from "./container-engine-CscrTTHa.mjs";
import { s as validateSandboxContainerEngineTarget } from "./podman-runtime-CUqzctoD.mjs";
import { c as isDockerDaemonUnavailable } from "./docker-DFBRw_yx.mjs";
import { t as archiveRetiredStateFiles } from "./state-migrations.retired-archive-CeUxFagC.mjs";
import fs from "node:fs";
import path from "node:path";
//#region src/commands/doctor-sandbox.ts
const SANDBOX_REGISTRY_FILES_CHECK_ID = "core/doctor/sandbox/registry-files";
function resolveSandboxScript(e) {
const t = resolveOpenClawPackageRootsSync({
cwd: process.cwd(),
argv1: process.argv[1]
});
for (const n of t) {
const t = path.join(n, e);
if (fs.existsSync(t)) return {
scriptPath: t,
cwd: n
};
}
return null;
}
async function runSandboxScript(e, t) {
const n = resolveSandboxScript(e);
if (!n) {
note(`Unable to locate ${e}. Run it from the repo root.`, "Sandbox");
return false;
}
t.log(`Running ${e}...`);
const r = await runCommandWithTimeout(["bash", n.scriptPath], {
timeoutMs: 12e5,
cwd: n.cwd
});
if (r.code !== 0) {
t.error(`Failed running ${e}: ${r.stderr.trim() || r.stdout.trim() || "unknown error"}`);
return false;
}
t.log(`Completed ${e}.`);
return true;
}
async function isContainerEngineAvailable(e) {
try {
await runExec(e, e === "docker" ? [
"version",
"--format",
"{{.Server.Version}}"
] : ["info"], { timeoutMs: 5e3 });
return true;
} catch {
return false;
}
}
function formatNamespaceProbeCommand(e) {
return ["unshare", ...e].join(" ");
}
async function runCodexBwrapNamespaceProbe(e) {
try {
await runExec("unshare", e, { timeoutMs: 5e3 });
return { ok: true };
} catch (t) {
const n = t?.stderr?.trim() || t?.stdout?.trim() || (t instanceof Error ? t.message : String(t));
return {
ok: false,
kind: "user",
command: formatNamespaceProbeCommand(e),
reason: n
};
}
}
function codexBwrapNeedsNetworkNamespaceProbe(e) {
const t = e.agents?.defaults?.sandbox?.docker?.network?.trim().toLowerCase();
return t === void 0 || t === "" || t === "none";
}
async function probeCodexBwrapNamespaces(e, t) {
const n = await runCodexBwrapNamespaceProbe([
"--user",
"--map-root-user",
"true"
]);
if (!n.ok || !codexBwrapNeedsNetworkNamespaceProbe(e)) return n;
try {
const { resolveCodexHealthApi: n } = await import("./bundled-health-checks-BJWxOv9V.mjs");
const r = n({
cfg: e,
...t
});
if (r.status === "not-configured") return { ok: true };
if (r.status === "unavailable") return {
ok: false,
kind: "unverified",
reason: r.reason
};
if (typeof r.api.probeCodexWorkspaceWriteSandbox !== "function") return {
ok: false,
kind: "unverified",
reason: "The selected Codex plugin does not provide a workspace-write sandbox check."
};
const i = await r.api.probeCodexWorkspaceWriteSandbox({
cfg: e,
env: t.env
});
if (i.status === "ok" || i.status === "skipped") return { ok: true };
if (i.status === "inconclusive") return {
ok: false,
kind: "unverified",
...i.command ? { command: i.command } : {},
reason: i.reason
};
return {
ok: false,
kind: i.denial.startsWith("bwrap: loopback:") ? "network" : "user",
command: i.command,
reason: i.denial
};
} catch (e) {
return {
ok: false,
kind: "unverified",
reason: e instanceof Error ? e.message : String(e)
};
}
}
/** Resolves the enabled sandbox backend and its local container engine, when it has one. */
function resolveEnabledSandboxBackend(e) {
const t = e.agents?.defaults?.sandbox;
const n = t?.mode ?? "off";
if (!t || n === "off") return;
const r = (t.backend?.trim() || "docker").toLowerCase();
return {
sandbox: t,
mode: n,
backend: r,
containerEngine: r === "podman" ? PODMAN_SANDBOX_ENGINE : r === "docker" ? DOCKER_SANDBOX_ENGINE : void 0
};
}
async function noteCodexBwrapNamespaceWarnings(e, t = {}) {
const n = resolveEnabledSandboxBackend(e)?.containerEngine;
if (process.platform !== "linux" || !n) return;
if (!await isContainerEngineAvailable(n.command)) return;
const r = n.displayName;
const i = await probeCodexBwrapNamespaces(e, t);
if (i.ok) return;
if (i.kind === "unverified") {
note([
"Doctor could not verify the Codex bwrap network sandbox.",
...i.command ? [`Check command: ${i.command}`] : [],
`Check result: ${i.reason}`,
`Resolve the check result above, then rerun ${formatCliCommand("openclaw doctor")} to check Codex's host namespace policy.`
].join("\n"), "Sandbox");
return;
}
const a = i.kind === "user" ? " bwrap: setting up uid map: Permission denied" : " bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted";
const o = codexBwrapNeedsNetworkNamespaceProbe(e) ? `With ${r} sandbox network egress disabled, it also needs an unprivileged network namespace.` : `${r} sandbox network egress is enabled, so doctor only checked the user namespace.`;
const s = [
`Codex bwrap ${i.kind} namespace check failed while ${r} sandbox mode is enabled.`,
`Codex app-server \`workspace-write\` shell execution needs unprivileged user namespaces. ${o}`,
"On Ubuntu/AppArmor hosts this usually appears as:",
a,
`Check command: ${i.command}`,
`Check result: ${i.reason}`,
"",
"Fix the host namespace policy for the OpenClaw service user, then restart the gateway.",
"Prefer an AppArmor profile that grants the required namespaces to the OpenClaw service process.",
"`kernel.apparmor_restrict_unprivileged_userns=0` is a host-wide fallback with security tradeoffs; use it only when that host posture is acceptable.",
"Do not add broad Docker container privileges just to satisfy nested bwrap; that weakens the outer sandbox."
];
note(s.join("\n"), "Sandbox");
}
async function containerImageExists(e, t) {
try {
await runExec(e, [
"image",
"inspect",
t
], { timeoutMs: 5e3 });
return true;
} catch (t) {
const n = t?.stderr || t?.message || "";
if ((e === "docker" ? n.includes("No such image") : /No such image|image not known|image .* not found/iu.test(n)) || e === "docker" && isDockerDaemonUnavailable(n)) return false;
throw t;
}
}
async function handleMissingSandboxImage(e, t, n) {
if (await containerImageExists(e.engineCommand, e.image)) return;
const r = e.buildScript === "scripts/sandbox-image-build.sh" ? `Run ${formatCliCommand("openclaw doctor --fix")} to build it with ${e.buildScript}.` : e.buildScript ? `Build it with ${e.buildScript}.` : "Build or pull it first.";
const i = `Sandbox ${e.kind} image missing: ${e.image}. ${r} Sandboxed turns will fail until the image is available.`;
note(i, "Sandbox");
if (e.buildScript) {
if (await n.confirmRuntimeRepair({
message: `Build ${e.kind} sandbox image now?`,
initialValue: true
}) && await runSandboxScript(e.buildScript, t)) return;
}
return i;
}
/**
* Checks configured sandbox images and optionally runs bundled build scripts for missing defaults.
*
* Non-container backends skip image checks.
*/
async function maybeRepairSandboxImages(e, t, n) {
const r = resolveEnabledSandboxBackend(e);
if (!r) return [];
const { sandbox: i, mode: a, backend: o, containerEngine: s } = r;
if (!s) {
if (i.browser?.enabled) note(`Sandbox backend "${o}" selected. Docker browser health checks are skipped; browser sandbox currently requires the docker backend.`, "Sandbox");
return [];
}
if (!await isContainerEngineAvailable(s.command)) {
const e = s.displayName;
const t = [
`Sandbox mode is enabled (mode: "${a}") but ${e} is not available.`,
s.id === "docker" ? "Docker is required for sandbox mode to function." : "Podman is required by the selected sandbox backend.",
`Isolated sessions (automations, sub-agents) will fail without ${e}.`,
"",
"Options:",
`- Install ${e} and restart the gateway`,
"- Disable sandbox mode: openclaw config set agents.defaults.sandbox.mode off"
];
note(t.join("\n"), "Sandbox");
return [t.join("\n")];
}
await validateSandboxContainerEngineTarget(s);
const c = i.docker?.image?.trim() || "openclaw-sandbox:trixie-slim";
const l = await handleMissingSandboxImage({
engineCommand: s.command,
kind: "base",
image: c,
buildScript: s.id !== "docker" ? void 0 : c === "openclaw-sandbox-common:trixie-slim" ? "scripts/sandbox-common-setup.sh" : c === "openclaw-sandbox:trixie-slim" ? "scripts/sandbox-image-build.sh" : void 0
}, t, n);
const u = l ? [l] : [];
if (i.browser?.enabled && s.id === "docker") {
const e = await handleMissingSandboxImage({
engineCommand: s.command,
kind: "browser",
image: i.browser.image?.trim() || "openclaw-sandbox-browser:trixie-slim",
buildScript: "scripts/sandbox-browser-setup.sh"
}, t, n);
if (e) u.push(e);
} else if (i.browser?.enabled) note("Podman sandbox selected. Browser sandbox health checks are skipped because browser sandboxing requires the Docker engine.", "Sandbox");
return u;
}
function formatLegacyRegistryInspectionLine(e) {
return `- ${e.kind} ${e.source}: ${shortenHomePath(e.path)} (retired)`;
}
function legacySandboxRegistryUpgradeHint() {
return `Run ${formatCliCommand("openclaw doctor --fix")} to archive retired registry files. Sandbox containers are recreated on demand; consult the archive for old container names before removing unused containers.`;
}
async function detectLegacySandboxRegistryFileIssues() {
return [
{
kind: "containers",
path: SANDBOX_REGISTRY_PATH,
source: "monolithic"
},
{
kind: "containers",
path: SANDBOX_CONTAINERS_DIR,
source: "sharded"
},
{
kind: "browsers",
path: SANDBOX_BROWSER_REGISTRY_PATH,
source: "monolithic"
},
{
kind: "browsers",
path: SANDBOX_BROWSERS_DIR,
source: "sharded"
}
].filter((e) => {
try {
fs.lstatSync(e.path);
return true;
} catch (t) {
if (hasErrnoCode(t, "ENOENT")) return false;
throw createRetiredStateInspectionError(e.path, t);
}
});
}
function legacySandboxRegistryInspectionToHealthFinding(e) {
return {
checkId: SANDBOX_REGISTRY_FILES_CHECK_ID,
severity: "warning",
message: `Retired sandbox registry file detected.
${formatLegacyRegistryInspectionLine(e)}`,
path: e.path,
fixHint: legacySandboxRegistryUpgradeHint()
};
}
function legacySandboxRegistryInspectionToRepairEffect(e) {
return {
kind: "state",
action: "archive-retired-sandbox-registry",
target: e.path,
dryRunSafe: false
};
}
async function maybeRepairSandboxRegistryFiles(e, t) {
const n = await detectLegacySandboxRegistryFileIssues();
if (n.length === 0) return;
if (e.shouldRepair) {
for (const e of n) {
const n = fs.lstatSync(e.path);
const r = n.isDirectory() && !n.isSymbolicLink();
const i = r ? fs.readdirSync(e.path).map((t) => path.join(e.path, t)) : [e.path];
const a = await archiveRetiredStateFiles({
label: "sandbox registry",
paths: i,
assertCurrent: t,
recoveryInstructions: "Sandbox containers are recreated on demand. Consult this archive for old container names before manually removing unused containers."
});
if (r) {
let n = `${e.path}.migrated`;
for (let t = 2;; t++) {
try {
fs.lstatSync(n);
} catch (e) {
if (hasErrnoCode(e, "ENOENT")) break;
throw e;
}
n = `${e.path}.migrated.${t}`;
}
t();
fs.renameSync(e.path, n);
a.warnings = a.warnings.map((t) => t.replaceAll(`${e.path}${path.sep}`, `${n}${path.sep}`));
a.warnings.push(`Retired sandbox registry directory archived at ${n}.`);
}
note(a.warnings.join("\n"), "Sandbox");
}
return;
}
note([
"Retired sandbox registry files detected.",
...n.map(formatLegacyRegistryInspectionLine),
legacySandboxRegistryUpgradeHint()
].join("\n"), "Sandbox");
}
function noteSandboxScopeWarnings(e) {
const t = e.agents?.defaults?.sandbox;
const n = [];
for (const { entry: r, source: i } of listAgentEntriesWithSource(e)) {
const e = r.id;
const a = r.sandbox;
if (!a) continue;
if (resolveSandboxScope({ scope: a.scope ?? t?.scope }) !== "shared") continue;
const o = [
"docker",
"browser",
"prune"
].filter((e) => a[e] && Object.keys(a[e]).length > 0);
if (o.length === 0) continue;
const s = i.kind === "entries" ? `agents.entries.${i.key}` : `agents.list (id "${e}")`;
n.push(`- ${s} sandbox ${o.join("/")} overrides ignored.\n scope resolves to "shared".`);
}
if (n.length > 0) note(n.join("\n"), "Sandbox");
}
//#endregion
export { detectLegacySandboxRegistryFileIssues, legacySandboxRegistryInspectionToHealthFinding, legacySandboxRegistryInspectionToRepairEffect, maybeRepairSandboxImages, maybeRepairSandboxRegistryFiles, noteCodexBwrapNamespaceWarnings, noteSandboxScopeWarnings };