UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

541 lines (540 loc) • 22 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as markOpenClawExecEnv } from "./openclaw-exec-env-BPYcT7Dr.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { u as observeDiagnosticsTimelinePhases } from "./diagnostics-timeline-CSwiG24r.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { r as withContainerEnvFile } from "./container-env-file-Ce7uAK1w.mjs"; import { C as SANDBOX_DOCKER_CREATE_ARGS_EPOCH, u as DEFAULT_SANDBOX_IMAGE } from "./constants-Dxjr8D5t.mjs"; import { o as computeSandboxConfigHash, r as sanitizeExplicitSandboxEnvVars, t as resolveDockerEnvPolicyEpoch } from "./sanitize-env-vars-DJC8I4rj.mjs"; import "./workspace-mounts-CKCN0wG6.mjs"; import { i as execContainerRaw, r as execContainer, t as DOCKER_SANDBOX_ENGINE } from "./container-engine-CscrTTHa.mjs"; import { a as resolvePodmanSandboxCreatePolicy, c as admitSandboxContainerSource, f as releaseSandboxContainerSource, g as containerState, i as resolvePodmanSandboxContainerPrefix, l as bindSandboxContainerSource, m as withSandboxContainerLifecycle, n as bindPodmanSandboxEngine, o as resolvePodmanSandboxRuntimeInfo, r as resolvePodmanSandboxConfigHash, t as assertPodmanSandboxTarget, x as recordedPodmanContainerState } from "./podman-runtime-CUqzctoD.mjs"; import { a as dockerPersistentTargetToEngineTarget, i as dockerPersistentTargetFromEngineTarget } from "./docker-persistent-target-CUAQLHHF.mjs"; import { r as validateSandboxSecurity } from "./validate-sandbox-security-BOPMGSpZ.mjs"; import { i as slugifySessionKey, n as resolveSandboxAgentId, t as buildSandboxContainerName } from "./shared-BfMYtWUR.mjs"; import { c as readRegistryEntry, h as updateRegistry, i as completeSandboxRegistryReservation, u as removeRegistryEntry } from "./registry-kRRGa9R8.mjs"; import { n as prepareSandboxMountPlan, t as compareSandboxMountPlan } from "./mount-plan-BFKvm-c8.mjs"; //#region src/agents/sandbox/container-image.ts /** Container image admission and Docker daemon availability diagnostics. */ const DOCKER_DAEMON_UNAVAILABLE_MARKERS = [ "cannot connect to the docker daemon", "dial unix", "docker daemon is not running", "connection refused" ]; function isDockerDaemonUnavailable(e) { return DOCKER_DAEMON_UNAVAILABLE_MARKERS.some((t) => e.toLowerCase().includes(t)); } function formatDockerDaemonUnavailableError(e) { const t = e.trim(); return [ "Sandbox mode requires Docker, but the Docker daemon is not available.", "Start Docker, or set `agents.defaults.sandbox.mode=off` to disable sandboxing.", t ? `Docker said: ${t}` : void 0 ].filter((e) => Boolean(e)).join(" "); } async function inspectContainerImage(e, t) { const n = await execContainer(e, [ "image", "inspect", t ], { allowFailure: true }); if (n.code === 0) return "exists"; const r = n.stderr.trim(); if (e.id === "docker" ? r.toLowerCase().includes("no such image") : /no such image|image not known|image .* not found/iu.test(r)) return "missing"; if (e.id === "docker" && isDockerDaemonUnavailable(r)) throw new Error(formatDockerDaemonUnavailableError(r)); if (e.id === "docker") throw new Error(`Failed to inspect sandbox image: ${r}`); throw new Error(`Failed to inspect sandbox image with ${e.displayName}: ${r}`); } async function ensureContainerImage(e, t) { if (await inspectContainerImage(e, t) === "exists") return; const n = e.id === "docker" ? `Sandbox image not found: ${t}.` : `Sandbox image not found in ${e.displayName}: ${t}.`; if (t === "openclaw-sandbox:trixie-slim") { const r = e.id === "docker" ? "Run openclaw doctor --fix to build it before enabling Docker sandboxing" : `Build it with podman build -t ${t} -f scripts/docker/sandbox/Dockerfile . before enabling container sandboxing`; throw new Error(`${n} ${r}. The default image includes python3 for sandbox write/edit helpers; OpenClaw will not substitute plain debian:trixie-slim.`); } throw new Error(`${n} Build or pull it first.`); } //#endregion //#region src/agents/sandbox/container-allocation.ts /** Canonical container flags and stopped allocation for sandbox lifecycles. */ const log = createSubsystemLogger("docker"); function normalizeDockerLimit(e) { if (typeof e === "number") return Number.isFinite(e) ? String(e) : void 0; return normalizeOptionalString(e); } function normalizeFiniteDockerNumber(e, t) { return typeof e === "number" && Number.isFinite(e) ? Math.max(t, e) : void 0; } function formatUlimitValue(e, t) { if (!e.trim()) return null; if (typeof t === "number") { const n = normalizeFiniteDockerNumber(t, 0); return n === void 0 ? null : `${e}=${n}`; } if (typeof t === "string") { const n = t.trim(); return n ? `${e}=${n}` : null; } const n = [normalizeFiniteDockerNumber(t.soft, 0), normalizeFiniteDockerNumber(t.hard, 0)].filter((e) => e !== void 0); return n.length ? `${e}=${n.join(":")}` : null; } function buildSandboxCreateArgs(e) { validateSandboxSecurity({ ...e.cfg, allowedSourceRoots: e.bindSourceRoots, allowSourcesOutsideAllowedRoots: e.cfg.dangerouslyAllowExternalBindSources === true, allowReservedContainerTargets: e.cfg.dangerouslyAllowReservedContainerTargets === true }); const t = Date.now(); const n = [ "create", "--name", e.name ]; n.push("--init"); n.push("--label", "openclaw.sandbox=1"); n.push("--label", `openclaw.sessionKey=${e.scopeKey}`); n.push("--label", `openclaw.createdAtMs=${t}`); n.push("--label", `openclaw.mountFormatVersion=${4}`); n.push("--label", `openclaw.createArgsEpoch=${SANDBOX_DOCKER_CREATE_ARGS_EPOCH}`); if (e.configHash) n.push("--label", `openclaw.configHash=${e.configHash}`); for (const [t, r] of Object.entries(e.labels ?? {})) if (t && r) n.push("--label", `${t}=${r}`); if (e.cfg.readOnlyRoot) n.push("--read-only"); for (const t of e.cfg.tmpfs) { const [e, r = ""] = t.split(":", 2); const i = e === "/tmp/openclaw-deps" ? "4g" : e === "/tmp" ? "1g" : "256m"; n.push("--tmpfs", /(?:^|,)size=/u.test(r) ? t : `${e}:${r ? `${r},` : ""}size=${i}`); } if (e.cfg.network) n.push("--network", e.cfg.network); if (e.cfg.user) n.push("--user", e.cfg.user); const r = sanitizeExplicitSandboxEnvVars(e.cfg.env ?? {}); if (r.blocked.length > 0) log.warn(`Blocked invalid configured sandbox environment variables: ${r.blocked.join(", ")}`); if (r.warnings.length > 0) log.warn(`Suspicious configured sandbox environment variables: ${r.warnings.join(", ")}`); const i = markOpenClawExecEnv(r.allowed); for (const t of e.cfg.capDrop) n.push("--cap-drop", t); n.push("--security-opt", "no-new-privileges"); if (e.cfg.seccompProfile) n.push("--security-opt", `seccomp=${e.cfg.seccompProfile}`); if (e.cfg.apparmorProfile) n.push("--security-opt", `apparmor=${e.cfg.apparmorProfile}`); for (const t of e.cfg.dns ?? []) if (t.trim()) n.push("--dns", t); for (const t of e.cfg.extraHosts ?? []) if (t.trim()) n.push("--add-host", t); const a = normalizeFiniteDockerNumber(e.cfg.pidsLimit, 0); if (a !== void 0 && a > 0) n.push("--pids-limit", String(a)); const o = normalizeDockerLimit(e.cfg.memory); if (o) n.push("--memory", o); const s = normalizeDockerLimit(e.cfg.memorySwap); if (s) n.push("--memory-swap", s); const c = normalizeFiniteDockerNumber(e.cfg.cpus, 0); if (c !== void 0 && c > 0) n.push("--cpus", String(c)); const l = e.cfg.gpus?.trim(); if (l) n.push("--gpus", l); for (const [t, r] of Object.entries(e.cfg.ulimits ?? {})) { const e = formatUlimitValue(t, r); if (e) n.push("--ulimit", e); } return { argv: n, env: i }; } function appendCustomBinds(e, t) { for (const n of t ?? []) e.push("-v", n); } /** Allocate inertly; the caller records custody before starting any container process. */ async function allocateSandboxContainer(e) { const { engine: t, name: n, workspaceDir: r, scopeKey: i } = e; const a = e.command?.env ? { ...e.cfg, env: { ...e.cfg.env, ...e.command.env } } : e.cfg; const o = t.id === "podman" && e.podmanRuntimeInfo ? resolvePodmanSandboxCreatePolicy({ cfg: a, dockerTmpfsSource: e.dockerTmpfsSource, workspaceDir: r, workspaceAccess: e.workspaceAccess, agentWorkspaceDir: e.agentWorkspaceDir, readOnlyWorkspaceSkillMounts: e.mountPlan.readOnlyWorkspaceSkillMounts, runtimeInfo: e.podmanRuntimeInfo }) : void 0; const s = o?.cfg ?? a; if (t.id === "podman") await ensureContainerImage(t, a.image); const { argv: c, env: l } = buildSandboxCreateArgs({ name: n, cfg: s, scopeKey: i, configHash: e.configHash, labels: e.labels, bindSourceRoots: [r, e.agentWorkspaceDir] }); if (o) c.push(...o.extraCreateArgs); if (t.id === "docker") c.push("--pull=never"); c.push("--workdir", a.workdir); for (const t of e.mountPlan.skippedBinds) log.warn(`sandbox: skipping user bind "${t}" — container path conflicts with a protected read-only skill mount`); appendCustomBinds(c, e.mountPlan.binds); const u = e.command ? [ "-c", [ "set -e", "setup_command=$1; workload_cwd=$2; shift 2", "if [ -n \"$setup_command\" ]; then /bin/sh -lc \"$setup_command\" >&2; fi", "cd -- \"$workload_cwd\"", "exec \"$@\"" ].join("\n"), "openclaw-sandbox-stream", a.setupCommand?.trim() ? a.setupCommand : "", e.command.cwd ?? a.workdir, ...e.command.argv ] : ["sleep", "infinity"]; if (e.command) c.push("--entrypoint", "/bin/sh", "--log-driver", "none"); const d = (await withContainerEnvFile(l, async (n) => { c.push("--env-file", n, a.image, ...u); e.assertCurrent?.(); try { return await execContainer(t, c, { assertCurrent: e.assertCurrent }); } catch (e) { if (t.id === "docker") await ensureContainerImage(t, a.image); throw e; } })).stdout.trim(); if (!/^[a-f0-9]{64}$/u.test(d)) throw new Error("Container creation did not return an immutable container ID."); return d; } //#endregion //#region src/agents/sandbox/current-config.ts function formatSandboxRecreateHint(e) { const t = `openclaw sandbox recreate${e.browser ? " --browser" : ""}`; if (e.scope === "session") return formatCliCommand(`${t} --session ${e.sessionKey}`); if (e.scope === "agent") { const n = resolveSandboxAgentId(e.sessionKey) ?? "main"; return formatCliCommand(`${t} --agent ${n}`); } return formatCliCommand(`${t} --all`); } function handleHotSandboxConfigMismatch(e) { const t = formatSandboxRecreateHint(e); if (e.mountsChanged) throw new Error(`Sandbox mounts changed for ${e.containerName}; the running container was preserved but cannot be reused with different filesystem sources or access modes. Recreate first: ${t}`); if (e.requireCurrentConfig) throw new Error(`Sandbox config changed for ${e.containerName}; restricted dispatch requires the current container config. Recreate first: ${t}`); defaultRuntime.log(`Sandbox config changed for ${e.containerName} (recently used). Recreate to apply: ${t}`); } //#endregion //#region src/agents/sandbox/docker-partial-cleanup.ts async function throwAfterPartialSandboxCleanup(e) { const t = []; let n = false; try { const r = await execContainer(e.engine, [ "rm", "-f", e.containerId ], { allowFailure: true }); const i = r.stderr.trim() || r.stdout.trim() || `exit ${r.code}`; n = r.code === 0 || /No such (container|object)|does not exist/iu.test(i); if (!n) t.push(/* @__PURE__ */ new Error(`Failed to remove partially created sandbox ${e.containerName}: ${i}`)); } catch (e) { t.push(e); } if (n) { e.onRemoved?.(); try { await removeRegistryEntry(e.containerName, { preserveRemovalIntent: true }); } catch (e) { t.push(e); } } if (t.length > 0) throw new AggregateError([e.creationError, ...t], `Sandbox ${e.containerName} creation and cleanup both failed.`, { cause: e.creationError }); throw e.creationError; } //#endregion //#region src/agents/sandbox/docker.ts async function execDockerRaw(e, t) { return await execContainerRaw(DOCKER_SANDBOX_ENGINE, e, t); } const HOT_CONTAINER_WINDOW_MS = 3e5; async function execDocker(e, t) { return await execContainer(DOCKER_SANDBOX_ENGINE, e, t); } async function ensureSandboxContainer(e) { try { var t = _usingCtx(); const n = t.u(observeDiagnosticsTimelinePhases("attempt.setup.sandbox.backend.lifecycle_wait")); const r = e.engine; const i = e.cfg.scope === "shared" ? "shared" : slugifySessionKey(e.scopeKey); const a = r.id === "podman" ? resolvePodmanSandboxContainerPrefix(e.cfg.docker.containerPrefix) : e.cfg.docker.containerPrefix; const o = buildSandboxContainerName(a, i); const assertCurrent = () => { e.operatorAuthority?.assertCurrent(); e.assertCurrent?.(); }; return await withSandboxContainerLifecycle(o, e.cfg.scope === "shared" ? void 0 : e.operatorAuthority, (t) => { n[Symbol.dispose](); return ensureSandboxContainerLifecycle({ ...e, assertCurrent }, o, t); }); } catch (e) { t.e = e; } finally { t.d(); } } async function ensureSandboxContainerLifecycle(e, t, n) { try { var r = _usingCtx(); const i = r.u(observeDiagnosticsTimelinePhases("attempt.setup.sandbox.backend.runtime_info")); const a = e.engine; const o = a.id === "podman" ? await resolvePodmanSandboxRuntimeInfo() : void 0; if (o) assertPodmanSandboxTarget(e.podmanTarget, o.target); const s = o ? bindPodmanSandboxEngine(o.target) : a; e.assertCurrent?.(); i.mark("attempt.setup.sandbox.backend.registry_read"); let c = await readRegistryEntry(t); if (s.id === "docker" && c?.backendTarget) { const t = dockerPersistentTargetFromEngineTarget(c.backendTarget); if (!e.dockerTarget || t.endpoint !== e.dockerTarget.endpoint || t.daemonId !== e.dockerTarget.daemonId) throw new Error("The Docker sandbox belongs to a different daemon; restore its recorded target or explicitly recreate it."); } if (c?.runtimeState === "removing" || c?.runtimeState === "removing-pending") throw new Error(`Sandbox ${t} is being removed; retry after sandbox recreate completes.`); if (s.id === "podman" && c) { if (!c.backendTarget) throw Object.assign(/* @__PURE__ */ new Error(`Podman sandbox runtime ${t} has no recorded engine target. Remove that unshipped runtime manually before recreating it.`), { code: "INVALID_CONFIG" }); try { assertPodmanSandboxTarget(c.backendTarget, o.target); } catch (e) { if (c.backendTarget.globalArgs.length === 0) throw e; const n = bindPodmanSandboxEngine(c.backendTarget); i.mark("attempt.setup.sandbox.backend.recorded_target_inspect"); if ((await recordedPodmanContainerState(n, t)).exists) throw e; i.mark("attempt.setup.sandbox.backend.stale_registry_remove"); await removeRegistryEntry(t); c = null; } } i.mark("attempt.setup.sandbox.backend.mount_prepare"); const l = await prepareSandboxMountPlan({ engine: s, workspaceDir: e.workspaceDir, workspaceSource: e.workspaceSource, assertCurrent: e.assertCurrent, agentWorkspaceDir: e.agentWorkspaceDir, skillsWorkspaceDir: e.skillsWorkspaceDir, workdir: e.cfg.docker.workdir, workspaceAccess: e.cfg.workspaceAccess, binds: e.cfg.docker.binds, tmpfs: e.cfg.docker.tmpfs, readOnlyResourceMounts: e.readOnlyResourceMounts }); i.mark("attempt.setup.sandbox.backend.config_hash"); const u = computeSandboxConfigHash({ docker: e.cfg.docker, dockerEnvPolicyEpoch: resolveDockerEnvPolicyEpoch(e.cfg.docker.env), workspaceAccess: e.cfg.workspaceAccess, workspaceDir: e.workspaceDir, agentWorkspaceDir: e.agentWorkspaceDir, mountFormatVersion: 4, createArgsEpoch: SANDBOX_DOCKER_CREATE_ARGS_EPOCH, managedMounts: l.binds }); const d = s.id === "podman" ? resolvePodmanSandboxConfigHash({ genericConfigHash: u, configuredUser: Boolean(e.cfg.docker.user), dockerTmpfsSource: e.cfg.dockerTmpfsSource }) : u; const f = Date.now(); const p = Boolean(e.cfg.docker.setupCommand?.trim()) || c?.runtimeState === "pending"; i.mark("attempt.setup.sandbox.backend.container_inspect"); const m = await containerState(s, t, { strict: p }); i.mark("attempt.setup.sandbox.backend.config_match"); let h = m.exists ? m.id : ""; const g = m.exists && m.readOnlyRoot; let _ = m.exists; let v = m.running; let y = null; let b = false; const x = c; if (m.exists) { if (x?.runtimeState === "pending") throw new Error(`Sandbox ${t} setup did not complete. Inspect the retained container and preserve needed data before explicitly recreating it.`); y = m.configHash ?? x?.configHash ?? null; b = !y || y !== d; if (b) { const n = x?.lastUsedAtMs; i.mark("attempt.setup.sandbox.backend.persistent_import"); const { hasSandboxPersistentExecCustody: r } = await import("./persistent-exec-exwRwzv3.mjs"); i.mark("attempt.setup.sandbox.backend.persistent_custody"); const a = await r({ containerName: t, containerId: h }); e.assertCurrent?.(); let o = a || v && (typeof n !== "number" || f - n < HOT_CONTAINER_WINDOW_MS); if (o) { i.mark("attempt.setup.sandbox.backend.mount_compare"); const r = e.requireCurrentConfig ? "match" : await compareSandboxMountPlan({ engine: s, containerName: h, plan: l }); if (r === "protected-mounts-added" && !a && g && typeof n === "number" && n < performance.timeOrigin) o = false; e.assertCurrent?.(); if (o) handleHotSandboxConfigMismatch({ containerName: t, scope: e.cfg.scope, sessionKey: e.scopeKey, mountsChanged: r !== "match", requireCurrentConfig: e.requireCurrentConfig }); } if (!o) { e.assertCurrent?.(); i.mark("attempt.setup.sandbox.backend.container_replace"); const n = await execContainer(s, [ "rm", "-f", h ], { allowFailure: true }); if (n.code !== 0 && !/no such (?:container|object)|does not exist/iu.test(n.stderr)) throw new Error(`Sandbox replacement failed; custody retained: ${n.stderr.trim()}`); releaseSandboxContainerSource(s, t, h); _ = false; v = false; } } } i.mark("attempt.setup.sandbox.backend.registry_prepare"); const S = { containerName: t, backendId: s.id, ...o ? { backendTarget: o.target } : {}, ...e.dockerTarget ? { backendTarget: dockerPersistentTargetToEngineTarget(e.dockerTarget) } : {}, runtimeLabel: t, sessionKey: e.scopeKey, workspaceDir: x?.workspaceDir ?? e.workspaceDir, workspaceSource: x?.workspaceSource ?? e.workspaceSource, createdAtMs: x?.createdAtMs ?? f, lastUsedAtMs: f, image: e.cfg.docker.image, configLabelKind: "Image", configHash: d }; if (!_) { if (e.workspaceSource === "managed-worktree" || p) { e.assertCurrent?.(); i.mark("attempt.setup.sandbox.backend.registry_reserve"); await updateRegistry(p ? { ...S, runtimeState: "pending" } : S); } let r = false; try { i.mark("attempt.setup.sandbox.backend.container_allocate"); h = await allocateSandboxContainer({ engine: s, name: t, cfg: e.cfg.docker, dockerTmpfsSource: e.cfg.dockerTmpfsSource, workspaceDir: e.workspaceDir, workspaceAccess: e.cfg.workspaceAccess, agentWorkspaceDir: e.agentWorkspaceDir, scopeKey: e.scopeKey, configHash: d, mountPlan: l, podmanRuntimeInfo: o, assertCurrent: e.assertCurrent }); r = true; if (n) bindSandboxContainerSource({ engine: s, name: t, id: h, owner: n }); e.assertCurrent?.(); i.mark("attempt.setup.sandbox.backend.container_start"); await execContainer(s, ["start", h], { assertCurrent: e.assertCurrent }); const a = e.cfg.docker.setupCommand; if (a?.trim()) { e.assertCurrent?.(); i.mark("attempt.setup.sandbox.backend.setup_command"); await execContainer(s, [ "exec", "-i", h, "/bin/sh", "-lc", a ], { signal: e.operatorAuthority?.signal }); } e.assertCurrent?.(); S.lastUsedAtMs = Date.now(); i.mark("attempt.setup.sandbox.backend.registry_publish"); if (p) await completeSandboxRegistryReservation(S); else await updateRegistry(S); e.assertCurrent?.(); return { containerName: t, containerId: h, ...o ? { podmanTarget: o.target } : {}, configHash: d, mountPlan: l, currentConfig: true }; } catch (n) { if (!r) throw n; if (e.operatorAuthority?.signal?.aborted) { if (e.workspaceSource !== "managed-worktree" && !p) { i.mark("attempt.setup.sandbox.backend.cancelled_registry_publish"); await updateRegistry(S); } throw n; } i.mark("attempt.setup.sandbox.backend.partial_cleanup"); await throwAfterPartialSandboxCleanup({ engine: s, containerName: t, containerId: h, creationError: n, onRemoved: () => releaseSandboxContainerSource(s, t, h) }); } } else { e.assertCurrent?.(); i.mark("attempt.setup.sandbox.backend.source_admission"); if (await admitSandboxContainerSource({ engine: s, name: t, id: h, running: v, source: n })) v = false; e.assertCurrent?.(); if (!v) { i.mark("attempt.setup.sandbox.backend.container_start"); await execContainer(s, ["start", h], { assertCurrent: e.assertCurrent }); } } i.mark("attempt.setup.sandbox.backend.registry_publish"); await updateRegistry({ ...S, lastUsedAtMs: Date.now(), configHash: b ? y ?? void 0 : d }); e.assertCurrent?.(); return { containerName: t, containerId: h, ...o ? { podmanTarget: o.target } : {}, configHash: b ? y : d, mountPlan: l, currentConfig: !b }; } catch (e) { r.e = e; } finally { r.d(); } } //#endregion export { allocateSandboxContainer as a, isDockerDaemonUnavailable as c, handleHotSandboxConfigMismatch as i, execDocker as n, buildSandboxCreateArgs as o, execDockerRaw as r, formatDockerDaemonUnavailableError as s, ensureSandboxContainer as t };