openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
374 lines (373 loc) • 16.8 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { c as projectCrabboxLegacyWarmLeases, l as withoutCrabboxWarmImageOperation, o as isCrabboxWarmImageHeld, r as crabboxWarmImageCaptureStatus, s as legacyLeaseSelector } from "./crabbox-worker-warm-image-records-DeuyTta3.mjs";
import { isDeepStrictEqual } from "node:util";
//#region extensions/crabbox/src/crabbox-worker-warm-image-recipe.ts
function normalizeRecipePreparation(e) {
if (!isRecord(e) || e.source !== "devcontainer" && e.source !== "script" && e.source !== "detected" && e.source !== "none") return;
const t = { source: e.source };
if (typeof e.note === "string") t.note = e.note.slice(0, 1024);
if (typeof e.ignoredPropertiesNote === "string") t.ignoredPropertiesNote = e.ignoredPropertiesNote.slice(0, 1024);
if (isRecord(e.phaseDurationsMs)) {
const n = {};
for (const t of [
"onCreate",
"updateContent",
"detectedInstall"
]) {
const r = e.phaseDurationsMs[t];
if (typeof r === "number" && Number.isFinite(r) && r >= 0) n[t] = r;
}
t.phaseDurationsMs = n;
}
if (isRecord(e.failure) && typeof e.failure.reason === "string") {
t.failure = { reason: e.failure.reason.slice(0, 1024) };
if (typeof e.failure.outputTail === "string") {
let n = Buffer.from(e.failure.outputTail).subarray(-16384).toString("utf8");
while (Buffer.byteLength(n) > 16384) n = n.slice(1);
t.failure.outputTail = n;
}
}
return t;
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-store.ts
var CrabboxWarmImageRequestError = class extends Error {};
const WARM_IMAGE_MAX_ALLOCATIONS = 256;
const openLegacyLeases = (e, t) => e.openKeyedStoreV2({
namespace: "warm-leases",
maxEntries: 256,
overflowPolicy: "evict-oldest",
...t ? { env: t } : {}
});
async function listCrabboxLegacyWarmLeases(e, t) {
return projectCrabboxLegacyWarmLeases(await openLegacyLeases(e, t).entries());
}
async function assertCrabboxWarmImageMigrationReady(e) {
if (await openLegacyLeases(e).count() > 0) throw new Error("Crabbox has legacy worker allocations whose original image choices are unknown; run openclaw doctor --fix and follow its provider-cleanup recovery instructions before provisioning workers.");
}
function admitCrabboxWarmImageProfile(e) {
if (e && e.version !== 3) throw new Error("Crabbox warm-image state requires migration; run openclaw doctor --fix before provisioning workers.");
const preparationKey = (e) => e === null || typeof e === "string" && /^[a-f0-9]{64}$/u.test(e);
const demandAtMs = (e) => e === null || typeof e === "number" && Number.isSafeInteger(e) && e >= 0;
const cacheIdentity = (e) => preparationKey(e.cacheKey) && (e.cacheKey === null ? e.purpose === null : e.preparationKey !== null && (e.purpose === "session" || e.purpose === "reserve"));
const validImage = (e) => isRecord(e) && preparationKey(e.preparationKey) && cacheIdentity(e) && demandAtMs(e.lastDemandAtMs) && (e.pinned === void 0 || isRecord(e.pinned) && Number.isSafeInteger(e.pinned.atMs) && e.pinned.atMs >= 0);
const validGeneration = (e) => isRecord(e) && Object.keys(e).length === 2 && typeof e.checkpointId === "string" && Boolean(e.checkpointId.trim()) && typeof e.createdAtMs === "number" && Number.isSafeInteger(e.createdAtMs) && e.createdAtMs >= 0;
const validCaptureUnsupported = (e) => isRecord(e) && typeof e.atMs === "number" && Number.isSafeInteger(e.atMs) && e.atMs >= 0 && typeof e.provider === "string" && e.provider.length > 0 && e.provider.length <= 128 && typeof e.message === "string" && e.message.length > 0 && e.message.length <= 1024;
if (e && (!isRecord(e.allocations) || e.image && !validImage(e.image) || e.previous && !validImage(e.previous) || e.captureUnsupported !== void 0 && !validCaptureUnsupported(e.captureUnsupported) || Object.values(e.allocations).some((e) => !isRecord(e) || !preparationKey(e.preparationKey) || !cacheIdentity(e) || !demandAtMs(e.demandAtMs) || e.preparationKey !== null && e.demandAtMs === null || e.imageGeneration !== null && !validGeneration(e.imageGeneration) || e.publicationBase !== void 0 && !validGeneration(e.publicationBase) || e.captureSkipped !== void 0 && (typeof e.captureSkipped !== "string" || !e.captureSkipped || e.captureSkipped.length > 1024)))) throw new Error("Crabbox warm-image preparation state is invalid; run openclaw doctor --fix.");
if (!e || e.recipePreparation === void 0) return e;
const t = { ...e };
delete t.recipePreparation;
delete t.recipePreparationAtMs;
const n = normalizeRecipePreparation(e.recipePreparation);
if (n) {
t.recipePreparation = n;
if (e.recipePreparationAtMs !== void 0 && e.recipePreparationAtMs !== null && demandAtMs(e.recipePreparationAtMs)) t.recipePreparationAtMs = e.recipePreparationAtMs;
}
return t;
}
const isCrabboxCaptureRefusalRetained = (e, t) => e.captureUnsupported !== void 0 && Date.now() < e.captureUnsupported.atMs + t;
/** Crabbox diagnostics follow Go error style without a final period. */
const crabboxCaptureUnsupportedSentence = (e) => `${e.replace(/[.\s]+$/u, "")}.`;
const sameCrabboxWarmImageGeneration = (e, t) => e?.checkpointId === t?.checkpointId && e?.createdAtMs === t?.createdAtMs;
function withCrabboxWarmImageGeneration(e, t, n) {
if (!e || !t) return;
const r = sameCrabboxWarmImageGeneration(e.image, t) ? "image" : "previous";
const i = e[r];
if (!i || !sameCrabboxWarmImageGeneration(i, t)) return;
const a = n(i);
return a ? {
...e,
[r]: a
} : void 0;
}
function assertCrabboxWarmImagePreparation(e, t) {
if (e && (!t.projectKey || t.target !== "linux" || !/^[a-f0-9]{64}$/u.test(e.key) || !/^[a-f0-9]{64}$/u.test(e.cacheKey) || e.purpose !== "session" && e.purpose !== "reserve" || !Number.isSafeInteger(e.demandAtMs) || e.demandAtMs < 0)) throw new Error("Crabbox project preparation identity is invalid.");
}
/** A provision retry keeps the profile, project, and runtime identity its lease first recorded. */
function assertCrabboxWarmImageReplay(e, t) {
if (e.key !== t.key || e.machineClass !== t.machineClass || (e.os ?? "linux") !== t.os || e.preparationKey !== t.preparationKey || e.cacheKey !== t.cacheKey || e.purpose !== t.purpose || t.demandAtMs !== void 0 && e.demandAtMs !== t.demandAtMs) throw new Error("Crabbox provision retry changed its recorded profile or project identity.");
if (!isDeepStrictEqual(e.runtimeIdentity, t.runtimeIdentity)) throw new Error("Crabbox provision retry changed or lacks its recorded node runtime identity; stop the worker before reprovisioning");
}
function withCrabboxWarmImageDisplayFacts(e, t = {}) {
const n = {
...e,
...t
};
for (const e of [
"profileId",
"backend",
"machineClass",
"os",
"projectLabel",
"projectRoot"
]) if (n[e] === void 0) delete n[e];
return n;
}
async function compareProfile(e, t, n) {
let r = await e.observe(t);
for (;;) {
const i = await e.compareAndApply(t, r.comparison, n(r.value));
if (i.status !== "conflict") return i.status === "applied";
r = i.current;
}
}
function openCrabboxWarmImageStore(e, t) {
const n = e.openKeyedStoreV2({
namespace: "warm-images",
maxEntries: 128,
overflowPolicy: "reject-new",
...t ? { env: t } : {}
});
const r = {
count: () => n.count(),
deleteIf(e, t) {
return compareProfile(n, e, (e) => ({
operation: "delete",
action: e && t(admitCrabboxWarmImageProfile(e)) ? "delete" : "keep"
}));
},
async lookup(e) {
return admitCrabboxWarmImageProfile(await n.lookup(e));
},
async entries() {
const e = await n.entries();
for (const t of e) t.value = admitCrabboxWarmImageProfile(t.value);
return e;
},
update(e, t) {
return compareProfile(n, e, (e) => {
const n = t(admitCrabboxWarmImageProfile(e));
return n === void 0 ? {
operation: "update",
action: "keep"
} : {
operation: "update",
action: "set",
value: n
};
});
}
};
const lookupLease = async (e) => {
const t = (await r.entries()).filter(({ value: t }) => Object.hasOwn(t.allocations, e));
if (t.length > 1) throw new Error(`Crabbox lease ${e} has conflicting warm-image owners; run openclaw doctor --fix.`);
const n = t[0];
return n ? {
key: n.key,
projectKey: n.value.projectKey,
...n.value.allocations[e]
} : void 0;
};
const markPhase = async (e, t, n, i, a) => {
const o = normalizeRecipePreparation(a?.recipePreparation);
const s = await lookupLease(e);
if (!s) return;
if (t === "prepared" && (!n || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(n))) throw new Error("Crabbox project preparation requires a verified Git commit.");
let c;
await r.update(s.key, (r) => {
i?.();
c = void 0;
const s = r?.allocations[e];
if (!r || !s) {
c = "Crabbox allocation closed before preparation completed.";
return;
}
if (r.operation?.type === "capture" && r.operation.leaseId === e) {
c = "Crabbox allocation cannot enroll while its image capture is unresolved.";
return;
}
if (n && s.baseCommit && n !== s.baseCommit) {
c = "Crabbox provision retry changed its prepared Git commit.";
return;
}
if (t === "enrolled" && r.projectKey && s.phase === "pending") {
c = "Crabbox project allocation must be prepared before enrollment.";
return;
}
return {
...r,
...o ? {
recipePreparation: o,
recipePreparationAtMs: Date.now()
} : {},
allocations: {
...r.allocations,
[e]: {
...s,
phase: s.phase === "enrolled" ? "enrolled" : t,
...n ? { baseCommit: n } : {},
...a?.captureSkipped ? { captureSkipped: a.captureSkipped.slice(0, 1024) } : {}
}
}
};
});
if (c) throw new Error(c);
};
return {
...r,
lookupLease,
async noteRecipePreparation(e, t, n) {
const i = normalizeRecipePreparation(t);
const a = await lookupLease(e);
if (!a || !i) return;
await r.update(a.key, (t) => {
n();
return t?.allocations[e] ? {
...t,
recipePreparation: i,
recipePreparationAtMs: Date.now()
} : void 0;
});
},
async recordAllocation(e) {
let t;
let n;
await r.update(e.key, (r) => {
e.assertCurrent();
t = void 0;
n = void 0;
const i = withCrabboxWarmImageDisplayFacts(r ?? {
version: 3,
allocations: {},
...e.projectKey ? { projectKey: e.projectKey } : {}
}, e.displayFacts);
const a = Object.hasOwn(i.allocations, e.id) ? i.allocations[e.id] : void 0;
if (a) {
n = {
key: e.key,
projectKey: i.projectKey,
...a
};
return e.displayFacts ? i : void 0;
}
if (Object.keys(i.allocations).length >= WARM_IMAGE_MAX_ALLOCATIONS) {
t = "Crabbox warm-image allocation capacity is full; stop outstanding workers before retrying.";
return;
}
const o = e.availableImage && i.image && sameCrabboxWarmImageGeneration(i.image, e.availableImage) && !(i.operation?.type === "retire" && i.operation.checkpointId === i.image.checkpointId) ? {
kind: "checkpoint",
checkpointId: i.image.checkpointId
} : { kind: "cold" };
const s = {
choice: o,
...o.kind === "cold" ? { coldReason: e.coldReason ?? "snapshot-unavailable" } : {},
...e.allocation,
imageGeneration: o.kind === "checkpoint" ? {
checkpointId: o.checkpointId,
createdAtMs: i.image.createdAtMs
} : null,
...o.kind === "cold" && i.image?.pinned ? { publicationBase: {
checkpointId: i.image.checkpointId,
createdAtMs: i.image.createdAtMs
} } : {}
};
n = {
key: e.key,
projectKey: i.projectKey,
...s
};
return {
...i,
...o.kind === "cold" ? { latestColdReason: e.coldReason ?? "snapshot-unavailable" } : {},
allocations: {
...i.allocations,
[e.id]: s
}
};
});
if (t) throw new Error(t);
if (!n) throw new Error("Crabbox allocation was not recorded.");
return n;
},
markPrepared(e, t, n, r) {
return markPhase(e, "prepared", t, n, r);
},
markEnrolled: (e, t) => markPhase(e, "enrolled", void 0, t),
async notePreparedDemand(e, t) {
const n = await lookupLease(e);
const i = n?.imageGeneration;
if (!n || n.phase !== "enrolled" || n.preparationKey !== t.preparationKey || n.cacheKey === null || !i || !Number.isSafeInteger(t.demandAtMs) || t.demandAtMs < 0) return;
await r.update(n.key, (r) => r && r.allocations[e]?.preparationKey === n.preparationKey && r.allocations[e]?.cacheKey === n.cacheKey && r.allocations[e]?.purpose === n.purpose && r.allocations[e]?.phase === "enrolled" && sameCrabboxWarmImageGeneration(r.allocations[e]?.imageGeneration, i) ? withCrabboxWarmImageGeneration(r, i, (e) => e.cacheKey === n.cacheKey ? {
...e,
lastDemandAtMs: Math.max(e.lastDemandAtMs ?? 0, t.demandAtMs)
} : void 0) : void 0);
}
};
}
async function listCrabboxWarmImages(e, t) {
return (await openCrabboxWarmImageStore(e, t).entries()).map(({ key: e, value: t }) => projectCrabboxWarmImage(e, t));
}
function projectCrabboxWarmImage(e, t) {
return {
profileKey: e,
profileId: t.profileId,
backend: t.backend,
machineClass: t.machineClass,
os: t.os,
projectLabel: t.projectLabel,
projectRoot: t.projectRoot,
projectKey: t.projectKey,
recipePreparation: t.recipePreparation,
recipePreparationAtMs: t.recipePreparationAtMs,
checkpointId: t.image?.checkpointId,
state: t.image?.state ?? "no-image",
createdAtMs: t.image?.createdAtMs,
preparationKey: t.image?.preparationKey,
cacheKey: t.image?.cacheKey,
purpose: t.image?.purpose,
lastDemandAtMs: t.image?.lastDemandAtMs,
baseCommit: t.image?.baseCommit,
runtimeIdentity: t.image?.runtimeIdentity,
pinned: t.image?.pinned,
previous: t.previous ? {
checkpointId: t.previous.checkpointId,
createdAtMs: t.previous.createdAtMs,
baseCommit: t.previous.baseCommit,
runtimeIdentity: t.previous.runtimeIdentity,
pinned: t.previous.pinned,
held: isCrabboxWarmImageHeld(t, t.previous.checkpointId)
} : void 0,
allocations: t.allocations,
capture: crabboxWarmImageCaptureStatus(t),
captureUnsupported: t.captureUnsupported,
latestColdReason: t.latestColdReason,
retirement: t.operation?.type === "retire" ? { checkpointId: t.operation.checkpointId } : void 0
};
}
/** Normal capture completion retains allocations; confirmed source cleanup may release its hold. */
async function clearCrabboxWarmImageCapture(e, t, n, r = {}) {
const sourceLeaseId = (e) => r.releaseSourceAllocation && e.operation?.type === "capture" ? e.operation.leaseId : void 0;
const matches = (e) => {
r.assertCurrent?.();
return e.operation?.type === "capture" && e.operation.id === n;
};
if (await e.deleteIf(t, (e) => !e.image && !e.previous && Object.keys(e.allocations).every((t) => t === sourceLeaseId(e)) && matches(e))) return true;
return e.update(t, (e) => {
if (!e || !matches(e)) return;
const t = withoutCrabboxWarmImageOperation(e);
const n = sourceLeaseId(e);
if (n && t.allocations[n]) {
t.allocations = { ...t.allocations };
delete t.allocations[n];
}
return t;
});
}
async function recoverCrabboxWarmImageCapture(e, t, n) {
if (!n) throw new Error("Recovery requires --acknowledge-provider-cleanup: confirm the original Gateway/capture processes and any worker being recovered are stopped, and any untracked provider artifact has been resolved. No state was changed.");
if (t.startsWith("legacy-lease-")) {
const n = openLegacyLeases(e);
const r = (await n.entries()).find(({ key: e, value: n }) => legacyLeaseSelector(e, n) === t);
if (!r || !await compareProfile(n, r.key, (e) => ({
operation: "delete",
action: e !== void 0 && legacyLeaseSelector(r.key, e) === t ? "delete" : "keep"
}))) throw new Error("Legacy allocation selector is absent or changed; rerun openclaw crabbox warm-images --json. No state was changed.");
return;
}
const r = openCrabboxWarmImageStore(e);
const i = (await r.entries()).find(({ value: e }) => crabboxWarmImageCaptureStatus(e)?.selector === t);
if (!i || !await clearCrabboxWarmImageCapture(r, i.key, t, { releaseSourceAllocation: true })) throw new Error("Capture selector is absent or changed; rerun openclaw crabbox warm-images --json. No state was changed.");
}
//#endregion
export { assertCrabboxWarmImageReplay as a, isCrabboxCaptureRefusalRetained as c, openCrabboxWarmImageStore as d, projectCrabboxWarmImage as f, withCrabboxWarmImageGeneration as g, withCrabboxWarmImageDisplayFacts as h, assertCrabboxWarmImagePreparation as i, listCrabboxLegacyWarmLeases as l, sameCrabboxWarmImageGeneration as m, admitCrabboxWarmImageProfile as n, clearCrabboxWarmImageCapture as o, recoverCrabboxWarmImageCapture as p, assertCrabboxWarmImageMigrationReady as r, crabboxCaptureUnsupportedSentence as s, CrabboxWarmImageRequestError as t, listCrabboxWarmImages as u };