openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
570 lines (569 loc) • 20.4 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs";
import { u as observeDiagnosticsTimelinePhases } from "./diagnostics-timeline-CSwiG24r.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createContainerEnvFile } from "./container-env-file-Ce7uAK1w.mjs";
import { t as CLEARED_GITHUB_CREDENTIALS } from "./github-host-CjR25cOO.mjs";
import { w as SANDBOX_GITHUB_CONFIG_DIR } from "./constants-Dxjr8D5t.mjs";
import { i as resolveSandboxConfigForAgent } from "./config-WbZbWrF1.mjs";
import { t as bindSandboxPersistentExecCapability } from "./persistent-exec.types-DoJqKDH2.mjs";
import { t as stripGatewayAllocatorEnv } from "./child-env-CrZt0xN6.mjs";
import { t as createSandboxProcessCleanup } from "./process-cleanup-B7odWFkl.mjs";
import { n as createSshSandboxBackend, o as resolveRemoteShellRuntimePaths, r as sshSandboxBackendManager } from "./ssh-backend-BMXCHhdQ.mjs";
import { t as buildGitHubExecLaunchArgv } from "./github-exec-launch-BPrPEpvY.mjs";
import { i as execContainerRaw, n as PODMAN_SANDBOX_ENGINE, r as execContainer, t as DOCKER_SANDBOX_ENGINE } from "./container-engine-CscrTTHa.mjs";
import { g as containerState, h as containerHasTerminated, n as bindPodmanSandboxEngine, p as removeSandboxContainerRuntime, s as validateSandboxContainerEngineTarget, u as captureSandboxContainerTermination } from "./podman-runtime-CUqzctoD.mjs";
import { a as dockerPersistentTargetToEngineTarget, i as dockerPersistentTargetFromEngineTarget, n as bindDockerPersistentTarget, o as readDockerPersistentContainer, r as captureDockerPersistentTarget } from "./docker-persistent-target-CUAQLHHF.mjs";
import { a as allocateSandboxContainer, t as ensureSandboxContainer } from "./docker-DFBRw_yx.mjs";
import { g as withSandboxRegistryEntryLock, h as updateRegistry, i as completeSandboxRegistryReservation, n as assertSandboxRegistryEntryCurrent, o as readRegisteredSandboxRuntimeIds, p as reserveSandboxRegistryEntry } from "./registry-kRRGa9R8.mjs";
import { r as resolveSandboxContainerOnlyMounts } from "./mount-plan-BFKvm-c8.mjs";
import { n as createSandboxInputStager, t as bindSandboxInputStager } from "./input-staging-CTBgfklv.mjs";
import { t as SandboxRuntimeRetiredError } from "./provisioning-error-19aGMcmG.mjs";
//#region src/agents/sandbox/docker-backend.ts
async function createContainerSandboxBackend(e, t, n, r) {
try {
var i = _usingCtx();
const a = i.u(observeDiagnosticsTimelinePhases("attempt.setup.sandbox.backend.target"));
const assertCurrent = () => {
n?.assertCurrent();
t.assertRuntimeCurrent?.();
};
assertCurrent();
if (e.id === "podman" && t.cfg.browser.enabled) throw new Error("Podman sandboxing does not support browser sandboxes. Install Docker and select the docker backend, or disable sandbox.browser.enabled.");
const o = e.id === "docker" ? await captureDockerPersistentTarget() : void 0;
assertCurrent();
const s = o ? bindDockerPersistentTarget(o) : e;
a.mark("attempt.setup.sandbox.backend.container");
const { containerName: c, containerId: l, configHash: u, mountPlan: d, currentConfig: f, podmanTarget: p } = await ensureSandboxContainer({
engine: s,
...o ? { dockerTarget: o } : {},
scopeKey: t.scopeKey,
workspaceDir: t.workspaceDir,
workspaceSource: t.workspaceSource,
assertCurrent,
operatorAuthority: n,
agentWorkspaceDir: t.agentWorkspaceDir,
skillsWorkspaceDir: t.skillsWorkspaceDir,
readOnlyResourceMounts: t.readOnlyResourceMounts,
cfg: t.cfg,
...t.requireCurrentConfig !== void 0 ? { requireCurrentConfig: t.requireCurrentConfig } : {}
});
assertCurrent();
const m = p ? bindPodmanSandboxEngine(p) : s;
a.mark("attempt.setup.sandbox.backend.mount_snapshot");
const h = await resolveSandboxContainerOnlyMounts({
engine: m,
containerName: l,
assertCurrent
});
assertCurrent();
a.mark("attempt.setup.sandbox.backend.bridge_import");
const { createSandboxFsBridge: g } = await import("./fs-bridge-Db9oxBML.mjs");
assertCurrent();
a.mark("attempt.setup.sandbox.backend.handle");
const { workdir: _, env: v, image: y } = t.cfg.docker;
const b = p ?? (o ? dockerPersistentTargetToEngineTarget(o) : void 0);
const run = (e, t) => runContainerSandboxShellCommand({
engine: m,
containerName: l,
engineTarget: b,
...e,
assertCurrent: t
});
const x = {
id: m.id,
runtimeId: c,
runtimeLabel: c,
workdir: _,
env: v,
configLabel: y,
configLabelKind: "Image",
capabilities: {
browser: m.id === "docker",
readOnlyResourceMounts: true
},
async buildExecSpec({ command: e, workdir: t, env: n, usePty: i, stdin: a }) {
await validateSandboxContainerEngineTarget(m, b);
const o = r;
const s = o?.localIdentityEnv.GH_CONFIG_DIR;
const c = s && process.platform === "win32" ? (await import("./shell-utils-DIqvzqA2.mjs")).getShellConfig() : void 0;
assertCurrent();
const u = o ? {
...n,
...o.credentialScrubEnv,
...o.localIdentityEnv,
GH_CONFIG_DIR: SANDBOX_GITHUB_CONFIG_DIR
} : n;
const { PATH: d, ...f } = u;
if (d) f.OPENCLAW_PREPEND_PATH = d;
const p = await createContainerEnvFile(f);
try {
assertCurrent();
const n = [
m.command,
...m.globalArgs ?? [],
"exec",
"-i"
];
if (i) n.push("-t");
const r = t ?? _;
if (r) n.push("-w", r);
n.push("--env-file", p.path);
if (s) n.push(...Object.keys(CLEARED_GITHUB_CREDENTIALS).flatMap((e) => ["--env", e]));
const d = u.PATH ? "export PATH=\"${OPENCLAW_PREPEND_PATH}:$PATH\"; unset OPENCLAW_PREPEND_PATH; " : "";
n.push(l, "/bin/sh", "-lc", `${d}${e}`);
const f = { ...m.baseEnv ?? process.env };
stripGatewayAllocatorEnv(f);
return {
argv: s ? buildGitHubExecLaunchArgv(n, s, {
githubHost: o?.localIdentityEnv.GH_HOST,
externalCommandShell: c
}) : n,
env: f,
stdinMode: i || a ? "pipe-open" : "pipe-closed",
finalizeToken: p.cleanup
};
} catch (e) {
await p.cleanup();
throw e;
}
},
async finalizeExec({ token: e }) {
if (e === void 0) return;
if (typeof e !== "function") throw new Error("Invalid container sandbox execution cleanup token.");
await e();
},
prepareProcessCleanup(e) {
assertCurrent();
const t = captureSandboxContainerTermination(m, c, l);
return createSandboxProcessCleanup((e) => run(e, assertCurrent), e, async (e) => {
const n = {
code: 0,
stdout: Buffer.alloc(0),
stderr: Buffer.alloc(0)
};
try {
if (t()) return n;
const r = await run(e);
if (r.code === 0) return r;
if (t() || await containerHasTerminated(m, l, e.signal) || t()) return n;
return r;
} catch (e) {
if (t()) return n;
throw e;
}
});
},
runShellCommand(e) {
return run(e, assertCurrent);
}
};
x.createFsBridge = ({ sandbox: e }) => {
const n = g({
sandbox: {
...e,
backend: e.backend ?? x
},
containerOnlyMounts: h
});
bindSandboxInputStager(n, createSandboxInputStager({
root: t.workspaceDir,
bridge: n,
assertCurrent
}));
return n;
};
if (o && u && f) {
a.mark("attempt.setup.sandbox.backend.persistent_generation");
const e = await readDockerPersistentContainer(m, l, AbortSignal.timeout(3e4));
assertCurrent();
if (e.kind !== "running") throw new Error("The admitted Docker sandbox container ended during preparation.");
a.mark("attempt.setup.sandbox.backend.persistent_capability");
const n = structuredClone({
cfg: t.cfg.docker,
dockerTmpfsSource: t.cfg.dockerTmpfsSource,
workspaceDir: t.workspaceDir,
workspaceAccess: t.cfg.workspaceAccess,
agentWorkspaceDir: t.agentWorkspaceDir,
skillsWorkspaceDir: t.skillsWorkspaceDir,
scopeKey: t.scopeKey,
configHash: u,
mountPlan: d
});
let r;
const resolveImage = () => {
assertCurrent();
return r ??= (async () => {
const e = await execContainer(m, [
"image",
"inspect",
"--format",
"{{.Id}}",
n.cfg.image
], { signal: AbortSignal.timeout(3e4) });
assertCurrent();
const t = e.stdout.trim();
if (!/^sha256:[a-f0-9]{64}$/u.test(t)) throw new Error("Persistent sandbox execution requires an immutable Docker image ID.");
return t;
})();
};
const i = {
target: o,
containerId: l,
containerName: c,
containerStartedAt: e.startedAt,
workdir: t.cfg.docker.workdir,
configHash: u,
imageReference: n.cfg.image,
resolveImage,
assertCurrent,
async allocate(e) {
const assertAllocationCurrent = () => {
assertCurrent();
e.assertCurrent();
};
assertAllocationCurrent();
const t = await resolveImage();
assertAllocationCurrent();
return await allocateSandboxContainer({
...n,
cfg: {
...n.cfg,
image: t
},
engine: m,
name: e.name,
command: e.command,
labels: e.labels,
assertCurrent: assertAllocationCurrent
});
}
};
bindSandboxPersistentExecCapability(x, {
...i,
async prepare(e) {
const { createDockerPersistentExecCapability: t } = await import("./docker-persistent-exec-BfuhC4Tb.mjs");
assertCurrent();
return await t(i).prepare(e);
}
});
}
return x;
} catch (e) {
i.e = e;
} finally {
i.d();
}
}
async function createDockerSandboxBackend(e, t, n) {
return await createContainerSandboxBackend(DOCKER_SANDBOX_ENGINE, e, t, n);
}
async function createPodmanSandboxBackend(e, t, n) {
return await createContainerSandboxBackend(PODMAN_SANDBOX_ENGINE, e, t, n);
}
async function runContainerSandboxShellCommand(e) {
await validateSandboxContainerEngineTarget(e.engine, e.engineTarget);
const t = [
"exec",
"-i",
e.containerName,
"sh",
"-c",
e.script,
"openclaw-sandbox-fs"
];
if (e.args?.length) t.push(...e.args);
e.assertCurrent?.();
return execContainerRaw(e.engine, t, {
input: e.stdin,
allowFailure: e.allowFailure,
signal: e.signal
});
}
function createContainerSandboxBackendManager(e) {
const resolveTarget = (t) => {
if (e.id !== "podman") return t.backendTarget;
if (t.backendTarget) return t.backendTarget;
throw Object.assign(/* @__PURE__ */ new Error(`Podman sandbox runtime ${t.containerName} has no recorded engine target. Remove that unshipped runtime manually before managing it.`), { code: "INVALID_CONFIG" });
};
const bindTarget = (t) => t ? e.id === "podman" ? bindPodmanSandboxEngine(t) : bindDockerPersistentTarget(dockerPersistentTargetFromEngineTarget(t)) : e;
return {
async stopRuntime(t, n) {
const r = resolveTarget(t);
await validateSandboxContainerEngineTarget(e, r);
n();
const i = bindTarget(r);
const a = await containerState(i, t.containerName, {
strict: true,
includePaused: true
});
n();
if (a.exists && (a.running || a.paused)) {
const e = AbortSignal.timeout(3e4);
if (a.paused) await execContainer(i, ["unpause", a.id], {
assertCurrent: n,
signal: e
});
await execContainer(i, [
"stop",
"--time",
"0",
a.id
], {
assertCurrent: n,
signal: e
});
}
},
async describeRuntime({ entry: t, config: n, agentId: r }) {
const i = resolveTarget(t);
await validateSandboxContainerEngineTarget(e, i);
const a = bindTarget(i);
const o = await containerState(a, t.containerName);
let s = t.image;
let c;
if (o.exists) try {
const e = await execContainer(a, [
"inspect",
"-f",
a.id === "podman" ? "{{.ImageName}} {{.Image}}" : "{{.Config.Image}}",
t.containerName
], { allowFailure: true });
if (e.code === 0) {
const t = e.stdout.trim();
if (a.id === "podman") {
const [e, n] = t.split(" ", 2);
s = e || s;
c = n;
} else s = t || s;
}
} catch {}
const l = resolveSandboxConfigForAgent(n, r);
const u = t.configLabelKind === "BrowserImage" ? l.browser.image : l.docker.image;
let d = s === u;
if (a.id === "podman" && !d && c) try {
const e = await execContainer(a, [
"image",
"inspect",
"-f",
"{{.Id}}",
u
], { allowFailure: true });
if (e.code === 0) {
const normalizeImageId = (e) => e.trim().replace(/^sha256:/u, "");
d = normalizeImageId(c) === normalizeImageId(e.stdout);
}
} catch {}
return {
running: o.running,
actualConfigLabel: s,
configLabelMatch: d
};
},
async removeRuntime({ entry: t }) {
const n = resolveTarget(t);
await validateSandboxContainerEngineTarget(e, n);
const r = bindTarget(n);
await removeSandboxContainerRuntime(r, t.containerName);
}
};
}
const dockerSandboxBackendManager = createContainerSandboxBackendManager(DOCKER_SANDBOX_ENGINE);
const podmanSandboxBackendManager = createContainerSandboxBackendManager(PODMAN_SANDBOX_ENGINE);
//#endregion
//#region src/agents/sandbox/backend.ts
const SANDBOX_BACKEND_FACTORIES_STATE_KEY = Symbol.for("openclaw.sandboxBackendFactories");
function getSandboxBackendFactories() {
return resolveGlobalMap(SANDBOX_BACKEND_FACTORIES_STATE_KEY);
}
function normalizeSandboxBackendId(e) {
const t = normalizeOptionalLowercaseString(e);
if (!t) throw new Error("Sandbox backend id must not be empty.");
return t;
}
/** Register or replace a sandbox backend and return a restore callback. */
function registerSandboxBackend(e, t) {
const n = normalizeSandboxBackendId(e);
const r = typeof t === "function" ? { factory: t } : t;
const i = getSandboxBackendFactories();
const a = i.get(n) ?? [];
const o = { registration: r };
a.push(o);
i.set(n, a);
return () => {
const e = a.indexOf(o);
if (e < 0) return;
a.splice(e, 1);
if (a.length === 0) i.delete(n);
};
}
function getSandboxBackendFactory(e) {
const t = resolveSandboxBackendRegistration(e);
if (!t) return null;
if (!t.reserveRuntimeId) return t.factory;
const n = t.factory;
return async (t) => {
const { runtimeId: r, assertRuntimeCurrent: i } = t;
if (!r || !i) throw new Error(`Sandbox backend "${e}" requires a registry-reserved runtime and its current owner.`);
i();
return n({
...t,
runtimeId: r,
assertRuntimeCurrent: i
});
};
}
function getSandboxBackendManager(e) {
return resolveSandboxBackendRegistration(e)?.manager ?? null;
}
/** Include legacy rows in the lifecycle selected by the currently registered backend. */
function usesSandboxRuntimeReservations(e) {
return resolveSandboxBackendRegistration(e)?.reserveRuntimeId !== void 0;
}
function getSandboxBackendWorkdirResolver(e) {
return resolveSandboxBackendRegistration(e)?.resolveWorkdir ?? null;
}
/** Read static backend capabilities without provisioning a sandbox runtime. */
function getSandboxBackendCapabilities(e) {
return resolveSandboxBackendRegistration(e)?.capabilities;
}
function requireSandboxBackendFactory(e) {
const t = getSandboxBackendFactory(e);
if (t) return t;
throw new Error([`Sandbox backend "${e}" is not registered.`, "Load the plugin that provides it, or set agents.defaults.sandbox.backend=docker."].join("\n"));
}
/** Create and publish a backend, reserving provider IDs only for opted-in factories. */
async function createSandboxBackend(e, t, n, r) {
try {
var i = _usingCtx();
e.assertRuntimeCurrent?.();
let o = requireSandboxBackendFactory(e.cfg.backend);
if (n && o !== createDockerSandboxBackend && o !== createPodmanSandboxBackend) throw new Error("Sandbox GitHub identity requires the built-in Docker or Podman backend.");
let s = e;
if (o !== createDockerSandboxBackend && o !== createPodmanSandboxBackend && e.registeredRuntimeIds === void 0) try {
var a = _usingCtx();
a.u(observeDiagnosticsTimelinePhases("attempt.setup.sandbox.backend.runtime_ids"));
const t = await readRegisteredSandboxRuntimeIds({
backendId: e.cfg.backend,
scopeKey: e.scopeKey
});
e.assertRuntimeCurrent?.();
if (t.length > 0) s = {
...e,
registeredRuntimeIds: t
};
o = requireSandboxBackendFactory(e.cfg.backend);
} catch (e) {
a.e = e;
} finally {
a.d();
}
if (o === createDockerSandboxBackend) return await createDockerSandboxBackend(s, t, n);
if (o === createPodmanSandboxBackend) return await createPodmanSandboxBackend(s, t, n);
const c = resolveSandboxBackendRegistration(e.cfg.backend)?.reserveRuntimeId;
const l = i.u(observeDiagnosticsTimelinePhases("attempt.setup.sandbox.backend.factory"));
const toEntry = (t) => ({
containerName: t.runtimeId,
backendId: t.id,
runtimeLabel: t.runtimeLabel,
sessionKey: e.scopeKey,
createdAtMs: Date.now(),
lastUsedAtMs: Date.now(),
image: t.configLabel ?? e.cfg.docker.image,
configLabelKind: t.configLabelKind ?? "Image"
});
if (!c) {
const t = await o(s);
l.mark("attempt.setup.sandbox.backend.registry_publish");
await updateRegistry(toEntry(t), {
...r,
beforeLegacyApply: e.assertRuntimeCurrent
});
return t;
}
for (let t = 0;; t++) {
e.assertRuntimeCurrent?.();
l.mark("attempt.setup.sandbox.backend.reservation");
const n = await reserveSandboxRegistryEntry({
containerName: c(s),
backendId: e.cfg.backend,
sessionKey: e.scopeKey,
createdAtMs: Date.now(),
lastUsedAtMs: Date.now(),
image: e.cfg.docker.image,
workspaceDir: e.workspaceDir
}, {
...r,
beforeLegacyApply: e.assertRuntimeCurrent
});
try {
l.mark("attempt.setup.sandbox.backend.registry_lock_wait");
return await withSandboxRegistryEntryLock(n, async () => {
l.mark("attempt.setup.sandbox.backend.factory");
const assertCurrent = () => {
e.assertRuntimeCurrent?.();
assertSandboxRegistryEntryCurrent(n);
};
try {
const t = await o({
...s,
workspaceDir: n.workspaceDir ?? e.workspaceDir,
runtimeId: n.containerName,
assertRuntimeCurrent: assertCurrent
});
if (t.runtimeId !== n.containerName || t.id !== n.backendId) throw new Error("Sandbox backend returned a runtime outside its reserved generation.");
l.mark("attempt.setup.sandbox.backend.reservation_complete");
await completeSandboxRegistryReservation({
...n,
...toEntry(t),
createdAtMs: n.createdAtMs
}, false, {
...r,
beforeLegacyApply: e.assertRuntimeCurrent
});
return t;
} catch (t) {
if (t instanceof SandboxRuntimeRetiredError && t.runtimeId === n.containerName) {
l.mark("attempt.setup.sandbox.backend.reservation_retire");
await completeSandboxRegistryReservation(n, true, {
...r,
beforeLegacyApply: e.assertRuntimeCurrent
});
}
throw t;
}
});
} catch (e) {
if (!(e instanceof SandboxRuntimeRetiredError) || e.runtimeId !== n.containerName || t > 0) throw e;
}
}
} catch (e) {
i.e = e;
} finally {
i.d();
}
}
const builtinSandboxBackends = /* @__PURE__ */ new Map();
builtinSandboxBackends.set("docker", {
factory: createDockerSandboxBackend,
manager: dockerSandboxBackendManager,
resolveWorkdir: ({ cfg: e }) => e.docker.workdir,
capabilities: { readOnlyResourceMounts: true }
});
builtinSandboxBackends.set("podman", {
factory: createPodmanSandboxBackend,
manager: podmanSandboxBackendManager,
resolveWorkdir: ({ cfg: e }) => e.docker.workdir,
capabilities: { readOnlyResourceMounts: true }
});
builtinSandboxBackends.set("ssh", {
factory: createSshSandboxBackend,
manager: sshSandboxBackendManager,
resolveWorkdir: ({ cfg: e, scopeKey: t }) => resolveRemoteShellRuntimePaths(e.ssh.workspaceRoot, t).remoteWorkspaceDir
});
function resolveSandboxBackendRegistration(e) {
const t = normalizeSandboxBackendId(e);
return getSandboxBackendFactories().get(t)?.at(-1)?.registration ?? builtinSandboxBackends.get(t);
}
//#endregion
export { getSandboxBackendWorkdirResolver as a, usesSandboxRuntimeReservations as c, getSandboxBackendManager as i, dockerSandboxBackendManager as l, getSandboxBackendCapabilities as n, registerSandboxBackend as o, getSandboxBackendFactory as r, requireSandboxBackendFactory as s, createSandboxBackend as t, podmanSandboxBackendManager as u };