UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

363 lines (362 loc) • 16.7 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { w as root } from "./fs-safe-BbWvmdVn.mjs"; import { t as decodeMountInfoPath } from "./mountinfo-path-CJN-JB-q.mjs"; import { a as splitSandboxBindSpec, i as resolveSandboxHostPathViaExistingAncestor, n as isSandboxHostPathAbsolute, r as normalizeSandboxHostPath, t as getSandboxHostPathPolicyKey } from "./host-paths-CAIcciVP.mjs"; import { n as MATERIALIZED_SANDBOX_SKILLS_WORKSPACE } from "./sandbox-workspace-paths-6ALUi8G2.mjs"; import { t as isPathInsideContainerRoot } from "./path-utils-B84QmnB8.mjs"; import { c as resolveSandboxTmpfsMounts, i as resolveProtectedMountAncestors, l as sandboxMountOptionsReadOnly, n as normalizeMountContainerPath, r as resolveMaterializedSandboxSkillsWorkspaceDir, s as resolveSandboxMountSelection } from "./workspace-mounts-CKCN0wG6.mjs"; import { r as execContainer } from "./container-engine-CscrTTHa.mjs"; import fs from "node:fs"; import path from "node:path"; import os from "node:os"; //#region src/agents/sandbox/docker-mount-source.ts const SELF_INSPECT_TIMEOUT_MS = 5e3; const MAX_SELF_CANDIDATES = 8; const SELF_IDENTITY_PROBE = "const fs=require(\"node:fs\");process.stdout.write(JSON.stringify([fs.readFileSync(\"/proc/sys/kernel/random/boot_id\",\"utf8\").trim(),fs.readlinkSync(\"/proc/self/ns/mnt\")]));"; let sourceNamespace; function parseInspectedSandboxMounts(e, t) { if (!Array.isArray(e)) throw new Error("Container inspect did not return a mount table."); const n = e.map((e) => { if (!isRecord(e) || typeof e.Type !== "string" || typeof e.Destination !== "string" || !path.posix.isAbsolute(e.Destination) || typeof e.RW !== "boolean" || e.Type === "bind" && (typeof e.Source !== "string" || !isSandboxHostPathAbsolute(e.Source))) throw new Error("Container inspect returned an invalid mount entry."); return { type: e.Type, source: typeof e.Source === "string" ? normalizeSandboxHostPath(e.Source) : "", destination: normalizeMountContainerPath(e.Destination), writable: e.RW }; }); if (t != null && !isRecord(t)) throw new Error("Container inspect returned invalid tmpfs destinations."); for (const [e, r] of Object.entries(t ?? {})) { if (!path.posix.isAbsolute(e) || typeof r !== "string") throw new Error("Container inspect returned an invalid tmpfs destination."); n.push({ type: "tmpfs", source: "", destination: normalizeMountContainerPath(e), writable: !sandboxMountOptionsReadOnly(r) }); } return [...new Map(n.map((e) => [e.destination, e])).values()]; } function readOptionalProcFile(e) { try { return fs.readFileSync(e, "utf8"); } catch { return ""; } } async function discoverSourceNamespace(e) { const t = readOptionalProcFile("/proc/self/cgroup"); const n = []; for (const e of t.matchAll(/(?:\/docker\/|docker-)([a-f0-9]{64})(?:\/|\.scope|$)/gm)) { const t = e[1]; if (t) n.push(t); } for (const e of readOptionalProcFile("/proc/self/mountinfo").split("\n")) { const t = e.split(" "); if (!/^\/etc\/(?:hosts|hostname|resolv\.conf)$/.test(t[4] ?? "")) continue; const r = t[3]?.match(/\/containers\/([a-f0-9]{64})\/(?:hosts|hostname|resolv\.conf)$/)?.[1]; if (r) n.push(r); } if (!fs.existsSync("/.dockerenv") && !fs.existsSync("/run/.containerenv") && n.length === 0) return; const r = [.../* @__PURE__ */ new Set([os.hostname(), ...n])].slice(0, MAX_SELF_CANDIDATES); const i = AbortSignal.timeout(SELF_INSPECT_TIMEOUT_MS); let a; try { const t = JSON.stringify([fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), fs.readlinkSync("/proc/self/ns/mnt")]); for (const n of r) try { const r = await execContainer(e, [ "inspect", "--type", "container", "--format", "{\"Id\":{{json .ID}},\"Mounts\":{{json .Mounts}},\"Tmpfs\":{{json .HostConfig.Tmpfs}}}", n ], { signal: i }); const a = JSON.parse(r.stdout); if (!isRecord(a) || typeof a.Id !== "string" || !/^[a-f0-9]{64}$/.test(a.Id)) throw new Error("Container inspect did not return a full container ID."); if ((await execContainer(e, [ "exec", a.Id, process.execPath, "-e", SELF_IDENTITY_PROBE ], { signal: i })).stdout !== t) throw new Error("The selected Docker daemon did not identify this Gateway container."); return parseInspectedSandboxMounts(a.Mounts, a.Tmpfs); } catch (e) { a = e; if (i.aborted) break; } } catch (e) { a = e; } throw new Error("Cannot resolve sandbox bind sources from this Gateway container. Connect Docker to the daemon that runs the Gateway and make its container inspectable, then restart the Gateway. A hostname alone cannot establish container identity.", { cause: a }); } async function resolveDockerSourceNamespace(e) { if (e.id !== "docker" || process.platform !== "linux") return; const t = JSON.stringify([ e, process.env.DOCKER_HOST, process.env.DOCKER_CONTEXT ]); if (sourceNamespace?.key === t) return await sourceNamespace.mounts; const n = { key: t, mounts: discoverSourceNamespace(e) }; sourceNamespace = n; try { return await n.mounts; } catch (e) { if (sourceNamespace === n) sourceNamespace = void 0; throw e; } } function translateSandboxMountSources(e) { const t = fs.realpathSync(e.source); if (!e.allowedRoots.some((e) => isPathInside(fs.realpathSync(e), t))) throw new Error(`Sandbox mount source ${e.source} escapes its Gateway workspace roots.`); const n = e.mounts.filter((e) => isPathInside(e.destination, t)).toSorted((e, t) => t.destination.length - e.destination.length)[0]; if (!n || n.type !== "bind") throw new Error(`Sandbox mount source ${e.source} ${n ? `uses an unsupported ${n.type} mount` : "is not backed by a Gateway bind mount"}. Bind-mount the workspace and OpenClaw state directories from the Docker host into the Gateway, then restart the Gateway.`); if (!n.writable && !e.readOnly) throw new Error(`Sandbox mount source ${e.source} is read-only in the Gateway. Use workspaceAccess=ro or make the Gateway bind writable before requesting a writable sandbox.`); const r = normalizeMountContainerPath(e.containerPath); const i = [{ hostPath: path.posix.join(n.source, path.posix.relative(n.destination, t)), containerPath: r, readOnly: e.readOnly }]; for (const n of e.mounts.toSorted((e, t) => e.destination < t.destination ? -1 : e.destination > t.destination ? 1 : 0)) { if (n.destination === t || !isPathInside(t, n.destination)) continue; const a = normalizeMountContainerPath(path.posix.join(r, path.posix.relative(t, n.destination))); if (e.shadowedTargets.some((e) => isPathInside(e, a))) continue; if (n.type !== "bind") throw new Error(`Sandbox mount source ${n.destination} uses an unsupported nested ${n.type} mount. Use Gateway bind mounts for this subtree or replace its sandbox destination with an explicit Docker bind, then restart the Gateway.`); if (!isPathInside(t, fs.realpathSync(n.destination))) throw new Error(`Sandbox mount source ${n.destination} escapes its Gateway workspace root.`); i.push({ hostPath: n.source, containerPath: a, readOnly: e.readOnly || !n.writable }); } return i; } //#endregion //#region src/agents/sandbox/mount-plan.ts /** Returns whether the Gateway sees a managed directory through a read-only bind. */ function gatewaySourceIsReadOnly(e, t) { const n = resolveSandboxHostPathViaExistingAncestor(path.resolve(t)); const r = e.filter((e) => isPathInside(e.destination, n)).toSorted((e, t) => t.destination.length - e.destination.length)[0]; return r !== void 0 && !r.writable; } async function prepareSandboxMountPlan(e) { const t = resolveSandboxMountSelection(e); const n = await resolveDockerSourceNamespace(e.engine); const r = `${MATERIALIZED_SANDBOX_SKILLS_WORKSPACE}/skills`; const i = normalizeMountContainerPath(`${e.workdir}/${r}`); if (e.workspaceSource === "managed-worktree" && t.readOnlyWorkspaceSkillMounts.some((e) => e.containerPath === i)) try { await (await root(e.workspaceDir, { mode: 493, mutationSymlinks: "reject", assertBeforeMutation: e.assertCurrent })).mkdir(r); } catch (t) { if (!collectNestedErrorCandidates(t).find((e) => hasErrnoCode(e, "EACCES") || hasErrnoCode(e, "EPERM"))) throw t; const n = path.join(e.workspaceDir, r); throw new Error(`Cannot prepare sandbox skills mountpoint "${n}": permission denied. Fix ownership or ACLs on the existing directory and its parents so the gateway user has search (execute) and write access, then retry.`, { cause: t }); } const a = resolveProtectedMountAncestors(t.mounts).filter((e) => !n || !gatewaySourceIsReadOnly(n, e.hostPath)); for (const t of a) await (await root(t.ownerHostPath, { mode: 493, mutationSymlinks: "reject", assertBeforeMutation: e.assertCurrent })).mkdir(t.relativePath); const o = new Map(t.mounts.filter((e) => e.source === "protectedSkill").map((e) => { const t = normalizeMountContainerPath(e.containerPath); return [t, a.filter((e) => isPathInsideContainerRoot(e.containerPath, t))]; })); const s = [ e.workspaceDir, e.agentWorkspaceDir, e.skillsWorkspaceDir ?? resolveMaterializedSandboxSkillsWorkspaceDir(e.agentWorkspaceDir), ...(e.readOnlyResourceMounts ?? []).map((e) => e.hostPath) ]; const c = [...t.mounts.map((e) => e.containerPath), ...a.map((e) => e.containerPath)]; const l = /* @__PURE__ */ new Map(); const u = []; const d = /* @__PURE__ */ new Set(); const f = /* @__PURE__ */ new Set(); const p = new Set(a.map((e) => normalizeMountContainerPath(e.containerPath))); for (const e of t.mounts) { for (const t of o.get(normalizeMountContainerPath(e.containerPath)) ?? []) if (!u.includes(t)) u.push(t); u.push(e); } for (const e of u) { const t = normalizeMountContainerPath(e.containerPath); if (e.source === "bind") continue; const r = n ? translateSandboxMountSources({ source: e.hostPath, containerPath: t, allowedRoots: s, mounts: n, readOnly: e.readOnly, shadowedTargets: c.filter((e) => e !== t && isPathInside(t, e)) }) : [{ ...e, containerPath: t }]; for (const n of r) { if (e.source === "protectedSkill") d.add(n.containerPath); if (p.has(t)) f.add(n.containerPath); l.set(n.containerPath, `${n.hostPath}:${n.containerPath}:${n.readOnly ? "ro,z" : "z"}`); } } for (const e of t.custom) { const t = splitSandboxBindSpec(e); const n = t ? normalizeMountContainerPath(t.container) : e; l.set(n, e); d.delete(n); } return { binds: [...l.values()], protectedTargets: [...d], pinnedAncestors: [...f], skippedBinds: t.skippedBinds, readOnlyWorkspaceSkillMounts: t.readOnlyWorkspaceSkillMounts, tmpfs: resolveSandboxTmpfsMounts(e.tmpfs) }; } async function inspectSandboxMounts(e) { const t = await execContainer(e.engine, [ "inspect", "--format", "{\"Mounts\":{{json .Mounts}},\"Tmpfs\":{{json .HostConfig.Tmpfs}}}", e.containerName ], { signal: AbortSignal.timeout(5e3) }); const n = JSON.parse(t.stdout); if (!isRecord(n)) throw new Error("Container inspect did not return mount metadata."); return parseInspectedSandboxMounts(n.Mounts, n.Tmpfs); } async function resolveSandboxContainerOnlyMounts(e) { e.assertCurrent?.(); const t = await inspectSandboxMounts(e); e.assertCurrent?.(); const { stdout: n } = await execContainer(e.engine, [ "exec", e.containerName, "cat", "/proc/self/mountinfo" ], { signal: AbortSignal.timeout(5e3) }); const r = /* @__PURE__ */ new Map(); for (const e of n.split("\n")) { if (!e) continue; const t = e.indexOf(" - "); const [n, i, a, o, s, c] = e.slice(0, t).split(" "); if (t < 0 || !n || !i || !a || !o || !s || !c) throw new Error("Container mountinfo returned an invalid mount entry."); r.set(n, { id: n, parent: i, destination: decodeMountInfoPath(s), backing: `${a}\0${decodeMountInfoPath(o)}`, writable: c.split(",").includes("rw") }); } if (r.size === 0) throw new Error("Container mountinfo did not return a mount table."); const i = /* @__PURE__ */ new Map(); const a = /* @__PURE__ */ new Map(); const o = /* @__PURE__ */ new Set(); for (const e of r.values()) { const t = i.get(e.destination) ?? []; t.push(e); i.set(e.destination, t); const n = a.get(e.parent) ?? []; n.push(e); a.set(e.parent, n); if (r.get(e.parent)?.destination === e.destination && e.parent !== e.id) o.add(e.parent); } const visible = (e) => { const t = /* @__PURE__ */ new Set(); for (let n = e; !t.has(n.id);) { t.add(n.id); const e = r.get(n.parent); if (!e || e.id === n.id) return true; if (e.destination !== n.destination && o.has(e.id)) return false; if (a.get(n.parent)?.some((t) => t.id !== e.id && t.destination !== n.destination && isPathInsideContainerRoot(t.destination, n.destination))) return false; n = e; } return false; }; const s = new Set(i.keys()); for (const e of t) { const t = i.get(e.destination) ?? []; const n = t.filter((e) => !o.has(e.id) && visible(e)); const r = n[0]; if (e.type === "bind" && n.length === 1 && r && r.writable === e.writable && t.every((e) => e.backing === r.backing)) s.delete(e.destination); else s.add(e.destination); } return [...s]; } async function compareSandboxMountPlan(e) { const t = await inspectSandboxMounts(e); const n = new Map(e.plan.binds.flatMap((e) => { const t = splitSandboxBindSpec(e); if (!t) return []; return [[normalizeMountContainerPath(t.container), t]]; })); const coversBind = (e) => [...n.keys()].some((t) => isPathInside(t, e)); const r = new Map(e.plan.tmpfs.filter((e) => coversBind(e.containerPath)).map((e) => [e.containerPath, e])); const i = t.filter((e) => e.type === "bind" || n.has(e.destination) || e.type === "tmpfs" && coversBind(e.destination)); const mountMatches = (e) => { if (e.type === "tmpfs") { const t = r.get(e.destination); return t !== void 0 && e.writable === !t.readOnly; } const t = n.get(e.destination); return t !== void 0 && e.type === "bind" && getSandboxHostPathPolicyKey(e.source) === getSandboxHostPathPolicyKey(t.host) && e.writable === !t.options.split(",").includes("ro"); }; if (i.length === n.size + r.size && i.every(mountMatches)) return "match"; const a = new Set(t.map((e) => e.destination)); const o = [...e.plan.protectedTargets, ...e.plan.pinnedAncestors ?? []].filter((e) => !a.has(e)); return t.every((e) => e.type === "bind" || e.type === "tmpfs") && i.length + o.length === n.size + r.size && i.every(mountMatches) ? "protected-mounts-added" : "changed"; } /** Read saved workspace bytes only when the existing runtime exposes that same bind. */ async function sandboxContainerShowsWorkspacePaths(e) { e.assertCurrent(); const t = await execContainer(e.engine, [ "inspect", "-f", "{{.Id}} {{.State.Running}} {{.State.Paused}}", e.containerName ], { signal: AbortSignal.timeout(5e3) }); e.assertCurrent(); const [n, r, i] = t.stdout.trim().split(/\s+/u); if (!n || !/^[a-f0-9]{64}$/u.test(n) || !["true", "false"].includes(r ?? "") || i !== "false") return false; const a = { ...e, containerName: n }; const o = await resolveDockerSourceNamespace(e.engine); e.assertCurrent(); const s = o ? translateSandboxMountSources({ source: e.workspaceDir, containerPath: e.containerRoot, allowedRoots: [e.workspaceDir], mounts: o, readOnly: true, shadowedTargets: [] }) : [{ hostPath: e.workspaceDir, containerPath: normalizeMountContainerPath(e.containerRoot) }]; const c = await inspectSandboxMounts(a); e.assertCurrent(); const l = r === "true" ? await resolveSandboxContainerOnlyMounts(a) : []; e.assertCurrent(); return e.targets.every((e) => { const t = normalizeMountContainerPath(e); const n = c.filter((e) => isPathInsideContainerRoot(e.destination, t)).toSorted((e, t) => t.destination.length - e.destination.length)[0]; const r = n === void 0 ? void 0 : s.filter((e) => isPathInsideContainerRoot(e.containerPath, n.destination)).toSorted((e, t) => t.containerPath.length - e.containerPath.length).map((e) => ({ hostPath: path.posix.join(e.hostPath, path.posix.relative(e.containerPath, n.destination)) }))[0]; return n?.type === "bind" && r !== void 0 && getSandboxHostPathPolicyKey(n.source) === getSandboxHostPathPolicyKey(r.hostPath) && !l.some((e) => isPathInsideContainerRoot(e, t) && e.length >= n.destination.length); }); } //#endregion export { sandboxContainerShowsWorkspacePaths as i, prepareSandboxMountPlan as n, resolveSandboxContainerOnlyMounts as r, compareSandboxMountPlan as t };