openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
378 lines (377 loc) • 14.7 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as runWithSpawnBroker } from "./context-Btn9lVDh.mjs";
import { o as isPlainCommandExitFailure } from "./exec-result-DJMhztYN.mjs";
import { c as spawnCommand, d as waitForCommandSpawn, o as runOutsideCommandProcessScope } from "./exec-spawn-DMKoejF-.mjs";
import "./exec-aRIvS9s4.mjs";
import { a as parseDockerPersistentExecTarget, i as parseDockerPersistentExecReceipt, n as dockerPersistentExecContainerName } from "./persistent-exec.types-DoJqKDH2.mjs";
import { t as stripGatewayAllocatorEnv } from "./child-env-CrZt0xN6.mjs";
import { r as execContainer } from "./container-engine-CscrTTHa.mjs";
import { o as readDockerPersistentContainer, t as assertDockerPersistentTargetCurrent } from "./docker-persistent-target-CUAQLHHF.mjs";
import { withTimeout } from "@openclaw/fs-safe/advanced";
//#region src/agents/sandbox/docker-persistent-exec.ts
const CONTROL_TIMEOUT_MS = 3e4;
const START_POLL_INTERVAL_MS = 100;
const MAX_OUTPUT_CHUNK_BYTES = 1048576;
const ATTEMPT_LABEL = "openclaw.persistentExecAttempt";
const PARENT_LABEL = "openclaw.persistentExecParentId";
const STORE_LABEL = "openclaw.streamStore";
function captureCleanupTarget(e) {
dockerPersistentExecContainerName(e.attemptId);
if (!/^[a-f0-9]{64}$/u.test(e.parentContainerId)) throw new Error("Invalid original Docker sandbox identity; custody retained.");
if (e.containerId !== void 0) return parseDockerPersistentExecReceipt({
...e,
version: 1
});
return {
target: parseDockerPersistentExecTarget(e.target),
attemptId: e.attemptId,
parentContainerId: e.parentContainerId
};
}
function assertCustodyScope(e) {
if (!/^[a-f0-9]{64}$/u.test(e)) throw new Error("Invalid sandbox stream custody scope; cleanup is not permitted.");
}
const extinctionProofs = /* @__PURE__ */ new WeakMap();
function mintExtinctionProof(e) {
const t = Object.freeze({ kind: "docker-container-extinction" });
extinctionProofs.set(t, Object.freeze({
...e,
target: Object.freeze({ ...e.target })
}));
return t;
}
function readDockerPersistentExecExtinctionProof(e) {
const t = extinctionProofs.get(e);
if (!t) throw new Error("Container extinction was not confirmed by its original Docker custody owner.");
return t;
}
async function inspectChild(e, t, n, r) {
const i = await execContainer(e, [
"inspect",
"--format",
"{{json .}}",
n
], {
allowFailure: true,
signal: r
});
if (i.code !== 0) {
if (i.stderr.includes(n) && /no such (?:container|object)/iu.test(i.stderr)) return;
throw new Error("Original Docker stream container cannot be inspected; custody retained.");
}
const a = JSON.parse(i.stdout);
if (!isRecord(a) || !isRecord(a.Config) || !isRecord(a.Config.Labels) || !isRecord(a.State)) throw new Error("Docker stream container identity is unreadable; custody retained.");
const o = parseDockerPersistentExecReceipt({
version: 1,
target: t,
containerId: a.Id,
attemptId: a.Config.Labels[ATTEMPT_LABEL],
parentContainerId: a.Config.Labels[PARENT_LABEL]
});
const s = a.Config.Labels[STORE_LABEL];
if (typeof s !== "string") throw new Error("Docker stream container has no recorded custody scope; custody retained.");
assertCustodyScope(s);
if (typeof a.Name !== "string" || a.Name !== `/${dockerPersistentExecContainerName(o.attemptId)}` || typeof a.State.Status !== "string" || n !== o.containerId && n !== a.Name.slice(1)) throw new Error("Docker stream container identity changed; custody retained.");
return {
receipt: o,
custodyScope: s,
status: a.State.Status,
hasStarted: typeof a.State.StartedAt === "string" && a.State.StartedAt !== "0001-01-01T00:00:00Z" && Number.isFinite(Date.parse(a.State.StartedAt)),
exitCode: (a.State.Status === "exited" || a.State.Status === "dead") && typeof a.State.ExitCode === "number" && Number.isSafeInteger(a.State.ExitCode) ? a.State.ExitCode : null
};
}
function assertChildIdentity(e, t) {
if (e.receipt.attemptId !== t.attemptId || e.receipt.parentContainerId !== t.parentContainerId || t.containerId !== void 0 && e.receipt.containerId !== t.containerId) throw new Error("Docker stream container does not match its durable custody; cleanup refused.");
}
/** A stopped container remains startable. Only confirmed removal fences every late START. */
async function stopDockerPersistentExec(e, t = () => {}) {
const n = captureCleanupTarget(e);
return await runOutsideCommandProcessScope(async () => {
t();
const e = AbortSignal.timeout(CONTROL_TIMEOUT_MS);
const r = await assertDockerPersistentTargetCurrent(n.target, e);
const i = n.containerId ?? dockerPersistentExecContainerName(n.attemptId);
const a = await inspectChild(r, n.target, i, e);
t();
if (a) {
assertChildIdentity(a, n);
await execContainer(r, [
"rm",
"--force",
"--volumes",
a.receipt.containerId
], {
allowFailure: true,
signal: e
});
const i = await inspectChild(r, n.target, a.receipt.containerId, e);
t();
if (i) throw new Error("Original Docker stream container still exists; custody retained.");
}
await assertDockerPersistentTargetCurrent(n.target, e);
t();
return {
reason: a?.status === "exited" ? "source-exited" : "private stream container removed",
exitCode: a?.exitCode ?? null,
extinction: mintExtinctionProof(a?.receipt ?? n)
};
});
}
/** Reconciliation candidates remain scoped to this physical store and its original daemon. */
async function listDockerPersistentExecContainers(e, t) {
assertCustodyScope(t);
const n = parseDockerPersistentExecTarget(e);
return await runOutsideCommandProcessScope(async () => {
const e = AbortSignal.timeout(CONTROL_TIMEOUT_MS);
const r = await assertDockerPersistentTargetCurrent(n, e);
const i = await execContainer(r, [
"ps",
"--all",
"--no-trunc",
"--filter",
`label=${STORE_LABEL}=${t}`,
"--format",
"{{.ID}}"
], { signal: e });
const a = [];
for (const o of i.stdout.split(/\r?\n/u).filter(Boolean)) {
if (!/^[a-f0-9]{64}$/u.test(o)) throw new Error("Docker returned an invalid stream container identity; cleanup refused.");
const i = await inspectChild(r, n, o, e);
if (i?.custodyScope === t) a.push(i.receipt);
}
return a;
});
}
function createDockerPersistentExecCapability(e) {
const t = parseDockerPersistentExecTarget(e.target);
return {
target: t,
containerId: e.containerId,
containerName: e.containerName,
containerStartedAt: e.containerStartedAt,
workdir: e.workdir,
configHash: e.configHash,
imageReference: e.imageReference,
resolveImage: e.resolveImage,
async prepare(n) {
return await runOutsideCommandProcessScope(async () => {
assertCustodyScope(n.custodyScope);
const r = captureCleanupTarget({
target: t,
attemptId: n.attemptId,
parentContainerId: e.containerId
});
const assertCurrent = () => {
n.signal.throwIfAborted();
e.assertCurrent();
n.assertCurrent();
};
const assertParentCurrent = async (r = AbortSignal.timeout(CONTROL_TIMEOUT_MS)) => {
assertCurrent();
const i = AbortSignal.any([r, n.signal]);
const a = await assertDockerPersistentTargetCurrent(t, i);
const o = await readDockerPersistentContainer(a, e.containerId, i);
assertCurrent();
if (o.kind !== "running" || o.startedAt !== e.containerStartedAt) throw new Error("The admitted sandbox container generation has ended.");
return a;
};
await assertParentCurrent();
const i = n.command;
if (i.argv.length === 0 || i.argv.some((e) => e.includes("\0"))) throw new Error("Persistent sandbox execution requires a valid command argv.");
const a = await e.allocate({
name: dockerPersistentExecContainerName(r.attemptId),
command: i,
labels: {
[ATTEMPT_LABEL]: r.attemptId,
[PARENT_LABEL]: r.parentContainerId,
[STORE_LABEL]: n.custodyScope
},
assertCurrent
});
const o = parseDockerPersistentExecReceipt({
...r,
version: 1,
containerId: a
});
const s = await inspectChild(await assertParentCurrent(), t, a, AbortSignal.any([n.signal, AbortSignal.timeout(CONTROL_TIMEOUT_MS)]));
assertCurrent();
if (!s || s.status !== "created" || s.custodyScope !== n.custodyScope) throw new Error("Persistent sandbox preparation did not remain inert; custody retained.");
assertChildIdentity(s, o);
const c = createDeferredCore();
c.promise.catch(() => {});
let l = "prepared";
let u;
let d = Promise.resolve();
let f = Promise.resolve();
const p = [];
const m = /* @__PURE__ */ new Set();
let h;
let g;
let _;
let v = false;
let y = false;
let b;
const recordFailure = (e) => {
_ ??= (e instanceof Error ? e.message : String(e)).slice(0, 2048);
};
const stop = () => {
if (!v || y || _) b?.abort(new Error(_ ?? "Persistent sandbox execution was stopped during START."));
if (g) return Promise.resolve(g);
if (h) return h;
l = "stopping";
h = runOutsideCommandProcessScope(async () => {
await f;
const e = await stopDockerPersistentExec(o);
if (v && !y && e.reason !== "source-exited") recordFailure(/* @__PURE__ */ new Error("stream transport ended before the command exited"));
if (_) u?.kill("SIGKILL");
try {
await withTimeout(Promise.all([d, ...p]), CONTROL_TIMEOUT_MS, "persistent sandbox output drain");
} catch (e) {
recordFailure(e);
u?.kill("SIGKILL");
u?.nodeChildProcess.stdout?.destroy();
u?.nodeChildProcess.stderr?.destroy();
throw e;
}
await withTimeout(Promise.allSettled(m), CONTROL_TIMEOUT_MS, "persistent sandbox pending output settlement");
g = _ ? {
...e,
reason: `stream transport/output failed: ${_}`
} : e;
l = "stopped";
c.resolve(g);
return g;
}).catch((e) => {
u?.kill("SIGKILL");
c.reject(e);
throw e;
}).finally(() => {
h = void 0;
});
return h;
};
const consume = async (e, t) => {
try {
for await (const r of t) {
const t = Buffer.isBuffer(r) ? r : Buffer.from(r);
if (t.byteLength > MAX_OUTPUT_CHUNK_BYTES) throw new Error("Persistent sandbox output exceeded its bounded chunk size.");
const i = Promise.resolve(n.onOutput(e, t));
m.add(i);
i.then(() => m.delete(i), () => m.delete(i));
await withTimeout(i, CONTROL_TIMEOUT_MS, "persistent sandbox output consumer");
}
} catch (e) {
recordFailure(e);
stop().catch(() => {});
}
};
return {
receipt: o,
async checkCurrent() {
await assertParentCurrent();
},
stopped: c.promise,
async start(e) {
if (l !== "prepared") throw new Error("Persistent sandbox START is only valid for its admitted prepared owner.");
l = "starting";
const r = (async () => {
const r = await inspectChild(await assertParentCurrent(), t, a, AbortSignal.any([n.signal, AbortSignal.timeout(CONTROL_TIMEOUT_MS)]));
assertCurrent();
if (l !== "starting" || !r || r.status !== "created") throw new Error("The prepared sandbox stream is no longer available for START.");
assertChildIdentity(r, o);
await e();
const i = await assertParentCurrent();
if (l !== "starting") throw new Error("Persistent sandbox execution was stopped during START admission.");
const s = runOutsideCommandProcessScope(() => runWithSpawnBroker(void 0, () => {
const e = { ...i.baseEnv ?? process.env };
stripGatewayAllocatorEnv(e);
assertCurrent();
return spawnCommand([
i.command,
...i.globalArgs ?? [],
"start",
"--attach",
a
], {
baseEnv: e,
buffer: false,
cancelSignal: n.signal,
reject: false,
stdio: [
"ignore",
"pipe",
"pipe"
]
});
}));
u = s;
d = Promise.resolve(s).then((e) => {
v = true;
if (e.failed && !isPlainCommandExitFailure(e)) recordFailure(/* @__PURE__ */ new Error("persistent sandbox Docker transport failed"));
stop().catch(() => {});
}, (e) => {
v = true;
recordFailure(e);
stop().catch(() => {});
});
await withTimeout(waitForCommandSpawn(s), CONTROL_TIMEOUT_MS, "persistent sandbox transport admission");
const c = s.nodeChildProcess.stdout;
const f = s.nodeChildProcess.stderr;
if (!c || !f) throw new Error("Persistent sandbox transport did not provide its output pipes.");
p.push(consume("stdout", c), consume("stderr", f));
b = new AbortController();
const m = AbortSignal.any([b.signal, n.signal]);
const h = setTimeout(() => b?.abort(/* @__PURE__ */ new Error(`Persistent sandbox command did not start within ${CONTROL_TIMEOUT_MS}ms.`)), CONTROL_TIMEOUT_MS);
try {
for (;;) {
m.throwIfAborted();
assertCurrent();
if (y || _) throw new Error(_ ?? "Persistent sandbox execution was stopped during START.");
const e = await inspectChild(i, t, a, m);
m.throwIfAborted();
assertCurrent();
if (!e || e.custodyScope !== n.custodyScope) throw new Error("Persistent sandbox START lost its original container custody.");
assertChildIdentity(e, o);
if (e.hasStarted) {
await assertParentCurrent(m);
m.throwIfAborted();
break;
}
if (v) throw new Error("Persistent sandbox transport ended before the command started.");
await sleep(START_POLL_INTERVAL_MS, m);
}
} catch (e) {
m.throwIfAborted();
throw e;
} finally {
clearTimeout(h);
b = void 0;
}
if (l === "starting") l = "running";
})();
f = r.then(() => {}, () => {});
try {
await r;
} catch (e) {
recordFailure(e);
try {
await stop();
} catch (t) {
throw new AggregateError([e, t], "Sandbox START failed and container cleanup remains unresolved.", { cause: t });
}
throw e;
}
},
stop() {
y = true;
return stop();
}
};
});
}
};
}
//#endregion
export { stopDockerPersistentExec as i, listDockerPersistentExecContainers as n, readDockerPersistentExecExtinctionProof as r, createDockerPersistentExecCapability as t };