UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

389 lines (388 loc) • 11.7 kB
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs"; import { o as resolveExecutablePath } from "./executable-path-D8oWZRS5.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { Fn as object, Jn as string, Pn as number, Un as record } from "./schemas-Cy6abvsu.mjs"; import { E as GatewayProcessNamespaceSchema, N as readGatewayLockProcessNamespace, a as captureGatewayStateOwner, p as tryBorrowGatewayStateOwner } from "./gateway-state-owner-Bnv5owvG.mjs"; import { t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { i as runUtf8CommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import { n as runExec } from "./exec-aRIvS9s4.mjs"; import { watch } from "node:fs"; import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; import fs$1 from "node:fs/promises"; import os from "node:os"; import { readProcessIdentity } from "@openclaw/proc-safe/identity"; import { getDefaultEnvironment } from "@modelcontextprotocol/client/stdio"; //#region src/agents/mcp-docker-custody.ts const log = createSubsystemLogger("mcp/docker"); const STATE = "openclaw.mcp.state"; const GATEWAY = "openclaw.mcp.gateway"; const LAUNCH = "openclaw.mcp.launch"; const containerIdPattern = /^[a-f0-9]{64}$/u; const ownerSchema = object({ instance: string().min(1), namespace: GatewayProcessNamespaceSchema, process: object({ pid: number().int().positive(), startTimeMicros: number().finite(), startTimeSinceBootMicros: number().finite().optional() }), daemon: string().min(1) }); const containerSchema = object({ Id: string().regex(containerIdPattern), Config: object({ Labels: record(string(), string()) }) }); function custodyContext() { const e = captureGatewayStateOwner(resolveOpenClawStateSqlitePath()); if (!e?.ownerId) throw new Error("Docker MCP custody requires exclusive OpenClaw state ownership"); const t = readGatewayLockProcessNamespace(); const n = readProcessIdentity(process.pid); if (!t || !n || n.exited) throw new Error("Docker MCP custody could not establish the current Gateway process identity"); return { instance: e.ownerId, namespace: t, process: n, assertCurrent: e.assertCurrent }; } async function stateNamespace() { return createHash("sha256").update(await fs$1.realpath(resolveStateDir())).digest("hex"); } async function command(e, t, n) { return (await runExec(e.command, t, { baseEnv: e.env, cwd: e.cwd, timeoutMs: 1e4, logOutput: false, signal: n })).stdout.trim(); } async function engineFor(e, t, n, r) { const i = resolveExecutablePath(e, { env: t, cwd: r }); if (!i) throw new Error("Docker MCP executable is unavailable"); const a = { command: i, env: t, cwd: r }; const o = { ...t }; if (!t.DOCKER_CONTEXT && !t.DOCKER_HOST) { o.DOCKER_CONTEXT = await command(a, [ "context", "inspect", "--format", "{{.Name}}" ]); if (!o.DOCKER_CONTEXT) throw new Error("Docker MCP daemon context is unknown"); } const s = { command: i, env: o, cwd: r }; const c = await command(s, [ "info", "--format", "{{.ID}}" ]); if (!c || c === "<no value>") throw new Error("Docker MCP daemon identity is unknown"); n(); return { ...s, daemon: c, assertCurrent: n }; } async function assertDaemon(e) { if (await command(e, [ "info", "--format", "{{.ID}}" ]) !== e.daemon) throw new Error("Docker MCP daemon identity changed; container cleanup was refused"); e.assertCurrent(); } function isMissingContainer(e) { return Boolean(e && typeof e === "object" && "stderr" in e && typeof e.stderr === "string" && /no such (?:object|container)/iu.test(e.stderr)); } async function inspect(e, t) { try { const n = containerSchema.parse(JSON.parse(await command(e, [ "inspect", "--type", "container", "--format", "{{json .}}", t ]))); if (n.Id !== t) throw new Error("Docker MCP returned invalid container identity"); return n; } catch (e) { if (isMissingContainer(e)) return; throw e; } } async function confirmAbsent(e, t) { await assertDaemon(e); return await inspect(e, t) === void 0; } async function settleRemovalError(e, t, n) { if (isMissingContainer(n) || await confirmAbsent(e, t)) return true; if (!n || typeof n !== "object" || !("stderr" in n) || typeof n.stderr !== "string" || !n.stderr.includes(`removal of container ${t} is already in progress`)) return false; const r = new AbortController(); let i = ""; let a = false; const o = await runUtf8CommandWithTimeout([ e.command, "events", "--since", "0", "--filter", `container=${t}`, "--filter", "event=destroy", "--format", "{{.Actor.ID}}" ], { baseEnv: e.env, cwd: e.cwd, input: "", timeoutMs: 1e4, killProcessTree: true, requireProcessTreeExtinction: true, signal: r.signal, onOutputChunk(e, n) { if (n === "stdout") { i += e.toString("utf8"); if (i.split(/\r?\n/u).includes(t)) { a = true; r.abort(); } } } }); if (o.cleanup === "uncertain") throw new CommandProcessCleanupError(); if (!a || o.termination !== "signal" && !(o.termination === "exit" && o.code === 0)) throw new Error(`Docker MCP removal could not be confirmed: ${o.stderr.trim()}`); return await confirmAbsent(e, t); } async function remove(e, t, n, r) { await assertDaemon(e); const i = await inspect(e, t); if (!i) return; if (Object.entries(n).some(([e, t]) => i.Config.Labels[e] !== t)) throw new Error("Docker MCP container labels changed; cleanup was refused"); e.assertCurrent(); if (!r?.aborted) try { await command(e, [ "stop", "-t", "2", t ], r); } catch (n) { if (isMissingContainer(n)) return; if (!r?.aborted) { if (await settleRemovalError(e, t, n)) return; throw n; } } await assertDaemon(e); try { await command(e, [ "rm", "--force", t ]); } catch (n) { if (!await settleRemovalError(e, t, n)) throw n; } } async function list(e, t) { const n = await command(e, [ "ps", "--all", "--quiet", "--no-trunc", ...Object.entries(t).flatMap(([e, t]) => ["--filter", `label=${e}=${t}`]) ]); const r = n ? n.split(/\s+/u) : []; if (r.some((e) => !containerIdPattern.test(e))) throw new Error("Docker MCP returned invalid container IDs"); return r; } function ownerIsDead(e, t) { const n = e.namespace; const r = t.namespace; if (n.host !== r.host || n.platform !== r.platform) return false; if (n.identity !== r.identity) return true; if (n.platform === "linux" && r.platform === "linux" && n.pidNsInode !== r.pidNsInode) return false; const i = readProcessIdentity(e.process.pid); if (!i || i.exited) return true; return e.process.startTimeSinceBootMicros !== void 0 ? i.startTimeSinceBootMicros !== e.process.startTimeSinceBootMicros : i.startTimeMicros !== e.process.startTimeMicros; } function decodeOwner(e) { if (!e) return; try { return ownerSchema.safeParse(JSON.parse(e)).data; } catch { return; } } /** Recovery only inspects the configured daemon and never treats unknown owners as dead. */ async function recoverMcpDockerContainers(e, t, n) { try { const r = custodyContext(); const i = await engineFor(e, mergeProcessEnv([getDefaultEnvironment(), t]), r.assertCurrent, n); const a = await stateNamespace(); for (const e of await list(i, { [STATE]: a })) try { const t = await inspect(i, e); if (!t) continue; const n = t.Config.Labels; const o = decodeOwner(n[GATEWAY]); if (!o || !n[LAUNCH] || o.daemon !== i.daemon) { log.warn(`Docker MCP recovery retained ${e}: ownership or daemon identity could not be verified`); continue; } if (o.instance === r.instance) continue; if (!ownerIsDead(o, r)) { log.warn(`Docker MCP recovery retained ${e}: the previous process is alive or cannot be verified`); continue; } await remove(i, e, { [STATE]: a, [GATEWAY]: n[GATEWAY], [LAUNCH]: n[LAUNCH] }); } catch { log.warn(`Docker MCP recovery could not reclaim ${e}; inspect the Docker daemon and process owner`); } } catch { log.warn("Docker MCP recovery could not verify the daemon or process owner; containers were retained"); } } /** The CID file is Docker's external-tool contract; persistent custody lives in labels. */ async function prepareMcpDockerLaunch(e, t, n) { const r = custodyContext(); const i = tryBorrowGatewayStateOwner(resolveOpenClawStateSqlitePath()); if (!i) throw new Error("Docker MCP custody could not retain state ownership"); try { const a = await engineFor(e.command, t, i.assertCurrent, n); const o = await stateNamespace(); const s = randomUUID(); const c = { [STATE]: o, [GATEWAY]: JSON.stringify({ instance: r.instance, namespace: r.namespace, process: { pid: r.process.pid, startTimeMicros: r.process.startTimeMicros, startTimeSinceBootMicros: r.process.startTimeSinceBootMicros }, daemon: a.daemon }), [LAUNCH]: s }; const l = await fs$1.mkdtemp(path.join(os.tmpdir(), "openclaw-mcp-docker-")); const u = path.join(l, "container.cid"); let d; let f; let p = false; let m; const h = new AbortController(); return { assertCurrent: r.assertCurrent, command: a.command, env: a.env, args: [ "run", ...Object.entries(c).flatMap(([e, t]) => ["--label", `${e}=${t}`]), "--cidfile", u, ...e.hasName ? [] : ["--name", `openclaw-mcp-${s}`], ...e.args.slice(1) ], force() { if (p || h.signal.aborted) return; h.abort(); m?.(); }, close(e) { return f ??= (async () => { const changed = () => m?.(); let t; let n; let r; let o = false; let f = false; if (e) e.then(() => { f = true; changed(); }, changed); try { t = watch(l, changed); t.on("error", (e) => { r = e; changed(); }); while (!d) { const { promise: e, resolve: t } = Promise.withResolvers(); m = t; if (r) throw r; if (!n) try { n = watch(u, changed); n.on("error", (e) => { r = e; changed(); }); } catch (e) { if (extractErrorCode(e) !== "ENOENT") throw e; } const i = await fs$1.readFile(u, "utf8").catch((e) => { if (extractErrorCode(e) === "ENOENT") return ""; throw e; }); if (containerIdPattern.test(i.trim())) { d = i.trim(); break; } if (f) break; if (h.signal.aborted && !o) { o = true; log.warn(`Docker MCP launch ${s} has not published its container ID; retaining its client and exclusive state ownership until Docker settles. Inspect the Docker daemon if cleanup remains pending.`); } await e; } const e = d ? [d] : await list(a, c); for (const t of e) await remove(a, t, c, h.signal); p = true; } catch (e) { log.warn(`Docker MCP launch ${s} cleanup is unconfirmed; exclusive state ownership is retained: ${formatErrorMessage(e)}. Inspect Docker and restart this OpenClaw process before retrying.`); throw e; } finally { n?.close(); t?.close(); if (p) try { await fs$1.rm(l, { recursive: true, force: true }); } finally { i.release(); } } })(); } }; } catch (e) { i.release(); throw e; } } //#endregion export { prepareMcpDockerLaunch, recoverMcpDockerContainers };