openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
199 lines (198 loc) • 8.72 kB
JavaScript
import { n as sliceUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { s as redactSensitiveText, u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import "./logging-core-DxpUImpb.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import "./process-runtime-DcBPEA8Y.mjs";
import { l as CRABBOX_STOP_TIMEOUT_MS } from "./crabbox-worker-timeouts-pTo1LSUy.mjs";
import path from "node:path";
import { homedir } from "node:os";
import { setTimeout } from "node:timers/promises";
//#region extensions/crabbox/src/crabbox-process.ts
function runCrabboxProcess(e, t) {
const n = t.cwd === void 0 && e[0] && /[\\/]/u.test(e[0]) ? [path.resolve(e[0]), ...e.slice(1)] : e;
return runCommandWithTimeout(n, {
...t,
cwd: t.cwd ?? homedir()
});
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-command.ts
const MAX_OUTPUT_BYTES = 65536;
const MAX_COMMAND_DETAIL_CHARS = 512;
function sanitizeCrabboxNotice(e) {
return sliceUtf16Safe(redactToolPayloadText(e).replace(/\s+/gu, " ").trim(), 0, 512);
}
function leaseRunArgs(e, t = [], n) {
return [
"run",
"--provider",
e.provider,
"--network",
"public",
"--tailscale=false",
"--id",
e.id,
"--keep=true",
"--no-sync",
...t.flatMap((e) => ["--allow-env", e]),
...n ? ["--env-from-profile", n] : [],
"--script-stdin"
];
}
async function runCrabboxCommand(e) {
e.signal?.throwIfAborted();
let t;
try {
t = await runCrabboxProcess([e.binary, ...e.args], {
timeoutMs: e.timeoutMs,
maxOutputBytes: MAX_OUTPUT_BYTES,
killProcessTree: true,
...e.env === void 0 ? {} : { env: e.env },
...e.input === void 0 ? {} : { input: e.input },
...e.signal ? { signal: e.signal } : {}
});
} catch (t) {
e.signal?.throwIfAborted();
throw crabboxExecutionError(e.action, t);
}
e.signal?.throwIfAborted();
return t;
}
function crabboxExecutionError(e, t) {
const n = t instanceof Error ? t.message : typeof t === "string" ? t : "unknown runner failure";
const r = redactToolPayloadText(n).replace(/\s+/gu, " ").trim();
return /* @__PURE__ */ new Error(`Crabbox ${e} execution failed: ${sliceUtf16Safe(r, -512)}`);
}
function crabboxCommandDetail(e) {
const t = [e.stdout, e.stderr].filter(Boolean).join("\n").trim();
if (!t) return "";
const n = redactSensitiveText(t).replace(/\s+/gu, " ");
return n.length <= MAX_COMMAND_DETAIL_CHARS ? `: ${n}` : `: ... ${sliceUtf16Safe(n, -508)}`;
}
function crabboxCommandError(e, t) {
const n = t.coordinatorAttempts ? ` (after ${t.coordinatorAttempts} attempts)` : "";
const r = crabboxCommandDetail(t) || t.coordinatorDetail || "";
if (t.termination !== "exit") return /* @__PURE__ */ new Error(`Crabbox ${e} did not exit normally (${t.termination})${r}${n}`);
return /* @__PURE__ */ new Error(`Crabbox ${e} failed with exit code ${t.code ?? "unknown"}${r}${n}`);
}
function crabboxCommandOutput(e, t) {
if (t.termination !== "exit" || t.code !== 0) throw crabboxCommandError(e, t);
return t.stdout;
}
function parseCrabboxJson(e, t) {
try {
return JSON.parse(e);
} catch {
throw new Error(`Crabbox ${t} returned invalid JSON`);
}
}
function isCoordinatorTransportFailure(e) {
if (e.termination !== "exit" || e.code === null || e.code === 0) return false;
let t = false;
return `${e.stderr}\n${e.stdout}`.trim().split(/[\r\n]+/u).every((e) => {
const n = e.replace(/^warning: could not inspect lease before release: /u, "");
if (/^(?:context deadline exceeded\s+)?(?:Get|Post) "https:\/\/[^/\s"]+\/v1\/leases\/[^/\s"?]+(?:\/(?:release|heartbeat))?(?:\?[^\s"]*)?": context deadline exceeded$/u.test(n)) {
t = true;
return true;
}
return n === "context deadline exceeded" || /^coordinator read retry \d+\/\d+ reason=timeout$/u.test(n);
}) && t;
}
function isFixedLeaseIdUnsupported(e, t) {
return e.termination === "exit" && e.code === 2 && e.stdout.trim() === "" && e.stderr.trim() === `provider=${t} does not support fixed idempotent lease IDs`;
}
/** Only fixed-lease callers opt in; allocation keeps Gateway replay ownership. */
async function runCrabboxCommandWithCoordinatorRetry(e) {
const t = performance.now() + e.timeoutMs;
let n = e.timeoutMs;
let r;
for (let i = 1;; i += 1) {
const a = await runCrabboxCommand({
...e,
timeoutMs: n
});
const o = isCoordinatorTransportFailure(a) || e.action === "profile setup" && a.termination === "exit" && a.code === 4 && a.stdout.trim() === "" && /^lease_id_conflict:[^\r\n]*$/u.test(a.stderr.trim());
if (o) r = crabboxCommandDetail(a);
const s = o || i > 1 ? {
...a,
coordinatorAttempts: i,
coordinatorDetail: r
} : a;
const c = 1e3 * 2 ** (i - 1);
if (!o || i === 3 || t - performance.now() <= c) return s;
await setTimeout(c, void 0, { signal: e.signal });
e.signal?.throwIfAborted();
n = t - performance.now();
if (n <= 0) return s;
}
}
function isUnrecognizedLease(e, t, n, r = false) {
const i = `${e.stderr}\n${e.stdout}`;
if (e.termination !== "exit" || e.code === null || e.code === 0 || !new RegExp(`(?:^|[^\\w-])${escapeRegExp(t)}(?=$|[^\\w-])`, "u").test(i) || /\b(?:access\s+denied|auth|authentication|authorization|credentials?|forbidden|permission|token|unauthorized)\b/iu.test(i)) return false;
if (/\bcoordinator\b/iu.test(i)) {
const e = i.trim().split(/[\r\n]+/u).map((e) => e.match(/^(?:warning: could not inspect lease before release: )?coordinator (GET|POST) (?:https?:\/\/[^/\s]+)?\/v1\/leases\/([^/:?\s]+)(\/release)?(?:\?[^\s:]*)?:[ \t]*http (\d{3})\b([^\r\n]*)$/iu));
const r = e.some((e) => e?.[1] === "GET" && e[2] === t && !e[3] && e[4] === "404");
if (n === "inspect") return r;
return r && e.some((e) => e?.[1] === "POST" && e[3] === "/release") && e.every((e) => e?.[2] === t && e[4] === "404" && (e[1] === "GET" ? !e[3] : e[3] === "/release") && /^:\s*(?:not_found|\{\s*"error"\s*:\s*"not_found"\s*\})\s*$/u.test(e[5] ?? ""));
}
if (r) return e.code === 4 && i.trim() === `aws instance not found: ${t}`;
return e.code === 4 && (/\b(?:was\s+)?not found\b/iu.test(i) || /\bno longer exists\b/iu.test(i) || /\b(?:points to|is bound to) (?:a )?missing (?:instance|sandbox)\b/iu.test(i) || /\bdisappeared before release\b/iu.test(i) || /\bunknown blacksmith testbox(?:\s|:)/iu.test(i) || n === "inspect" && (/\bis not claimed by Crabbox\b/iu.test(i) || /\bwandb sandbox "[^"\r\n]+" has no matching local ownership claim\b/iu.test(i)) || /\bunknown lease(?:\s|:)/iu.test(i)) || n === "inspect" && e.code === 5 && /\bcoder workspace "[^"\r\n]+" not found\b/iu.test(i);
}
async function stopCrabboxLease(e) {
const t = performance.now() + CRABBOX_STOP_TIMEOUT_MS;
const stop = async (n) => {
const r = t - performance.now();
if (r <= 0) throw new Error("Crabbox stop exceeded its cleanup deadline");
let i = await runCrabboxCommandWithCoordinatorRetry({
action: "stop",
args: [
"stop",
"--provider",
e.provider,
"--id",
e.id,
...!n ? ["--wait=false"] : []
],
binary: e.binary,
timeoutMs: r,
signal: e.signal
});
if (!n && i.termination === "exit" && i.code === 2 && i.stdout.trim() === "" && i.stderr.trim() === "--wait=false requires an ordinary coordinator-backed stop") return "blocking";
const a = `${i.stderr}\n${i.stdout}`;
if (e.provider === "azure" && i.termination === "exit" && i.code === 4 && a.includes("Azure fixed lease cannot be adopted without its create intent")) {
const r = t - performance.now();
if (r <= 0) throw new Error("Crabbox stop timed out before Azure fixed-lease recovery", { cause: crabboxCommandError("stop", i) });
i = await runCrabboxCommandWithCoordinatorRetry({
action: "stop recovery",
args: [
"stop",
"--provider",
e.provider,
"--id",
e.id,
"--force",
...!n ? ["--wait=false"] : []
],
binary: e.binary,
timeoutMs: r,
signal: e.signal
});
}
if (isUnrecognizedLease(i, e.id, "stop")) {
e.warn(`Crabbox lease ${e.id} (provider ${e.provider}) is absent; treating stop as already released`);
return "released";
}
crabboxCommandOutput("stop", i);
return n ? "released" : "accepted";
};
if (e.onCleanupAccepted) {
const t = await stop(false);
if (t === "released") return;
if (t === "accepted") e.onCleanupAccepted();
}
await stop(true);
}
//#endregion
export { isUnrecognizedLease as a, runCrabboxCommand as c, stopCrabboxLease as d, runCrabboxProcess as f, isFixedLeaseIdUnsupported as i, runCrabboxCommandWithCoordinatorRetry as l, crabboxCommandOutput as n, leaseRunArgs as o, crabboxExecutionError as r, parseCrabboxJson as s, crabboxCommandError as t, sanitizeCrabboxNotice as u };