UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

612 lines (611 loc) • 21.2 kB
import "./kysely-sync-YJo2lmGV.mjs"; import "./sqlite-transaction-BHHu6P5-.mjs"; import { t as resolveZstdCodec } from "./zstd-codec-DyrkXXaa.mjs"; import { t as shellEscape } from "./shell-quote-DeRN90_2.mjs"; import { m as workspaceCtimeIsReusable } from "./workspace-hash-memo-BlDVl63Z.mjs"; import { b as workspacePathAncestors, g as buildCacheInputPaths, l as serializeWorkerWorkspaceManifest, s as parseWorkerWorkspaceManifest } from "./workspace-manifest-C118sSRH.mjs"; import { n as MAX_WORKSPACE_INVENTORY_ENTRIES } from "./workspace-inventory-limits-DfDQlGHa.mjs"; import { f as stagedInputPathDirectory } from "./staged-inputs-p_W1dPfN.mjs"; import { c as sameEntry } from "./workspace-manifest-comparison-BpzYeKoQ.mjs"; import { i as prepareLocalWorkspaceTreePacks, n as localWorkspaceDigestReference, t as localWorkspaceDigestBytes } from "./local-workspace-cas-DxFAvLyr.mjs"; import { a as readLocalWorkspaceGitExclusions, o as selectLocalWorkspaceCanonicalPaths, r as parseLocalWorkspaceSourcePaths } from "./local-workspace-inventory-BbL-ilhy.mjs"; import "./local-workspace-cas.kernel-BAdJRkgW.mjs"; import { a as scanActualWorkspaceManifest } from "./workspace-actual-manifest-DAi9l26a.mjs"; import { createHash } from "node:crypto"; import { serialize } from "node:v8"; import { deflateRawSync } from "node:zlib"; //#region src/gateway/worker-environments/local-workspace-fingerprints.ts const HEADER_BYTES = 45; const FILE_BYTES = 16; const FORMAT_VERSION = 1; const RACY_CTIME_NS = -1n; function filePaths(e) { const t = []; for (const { node: n } of e.values()) if (n.type === "file") t.push(n.path); t.sort(); return t; } /** Fingerprints belong to one scan and projection root; tree packs never carry stat facts. */ function prepareLocalWorkspaceFingerprints(e, t, n, r) { const i = n === null || Buffer.isBuffer(n) ? n : Buffer.from(n.buffer, n.byteOffset, n.byteLength); const a = filePaths(e); let o; if (n) try { const e = resolveZstdCodec().decompress(n, HEADER_BYTES + MAX_WORKSPACE_INVENTORY_ENTRIES * FILE_BYTES); if (e.length === HEADER_BYTES + a.length * FILE_BYTES && e.readUInt8(0) === FORMAT_VERSION && e.subarray(9, 41).equals(Buffer.from(t.slice(7), "hex")) && e.readUInt32LE(41) === a.length) o = e; } catch {} const s = /* @__PURE__ */ new Map(); for (let e = 0; e < a.length; e++) s.set(a[e], HEADER_BYTES + e * FILE_BYTES); const c = o?.readBigUInt64LE(1); const l = /* @__PURE__ */ new Map(); const u = /* @__PURE__ */ new Map(); let d = o !== void 0; let f = 0; return { reuseFile(t, n, i) { const a = s.get(t); const u = e.get(t)?.node; if (!o || a === void 0 || u?.type !== "file") { d = false; return; } if (i.dev === c && i.ino === o.readBigUInt64LE(a) && i.ctimeNs === o.readBigInt64LE(a + 8) && u.size === Number(i.size) && workspaceCtimeIsReusable(i.ctimeNs, r)) { l.set(t, n); return u; } d = false; }, observe(e, t) { if (l.get(e) === t) f++; else { d = false; l.delete(e); u.set(e, t); } }, encode(e, n) { if (n === t && d && f === a.length) return i; let p = a; if (n !== t) { const t = a.filter((t) => e.get(t)?.node.type === "file"); const n = []; for (const { node: t } of e.values()) if (t.type === "file" && !s.has(t.path)) n.push(t.path); n.sort(); p = []; let r = 0; for (const e of t) { while (r < n.length && n[r] < e) p.push(n[r++]); p.push(e); } while (r < n.length) p.push(n[r++]); } const m = Buffer.alloc(HEADER_BYTES + p.length * FILE_BYTES); m.writeUInt8(FORMAT_VERSION, 0); Buffer.from(n.slice(7), "hex").copy(m, 9); m.writeUInt32LE(p.length, 41); let h; for (let e = 0; e < p.length; e++) { const t = p[e]; const n = HEADER_BYTES + e * FILE_BYTES; if (l.has(t)) { const e = s.get(t); h ??= c; if (h !== c) return null; o.copy(m, n, e, e + FILE_BYTES); continue; } const i = u.get(t); if (!i) return null; const a = i.split(":"); const d = BigInt(a[1]); h ??= d; if (d !== h) return null; const f = BigInt(a[5]); m.writeBigUInt64LE(BigInt(a[2]), n); m.writeBigInt64LE(workspaceCtimeIsReusable(f, r) ? f : RACY_CTIME_NS, n + 8); } m.writeBigUInt64LE(h ?? 0n, 1); return resolveZstdCodec().compress(m); } }; } //#endregion //#region src/gateway/worker-environments/local-workspace-manifest-tree.ts function digest(e, ...t) { return `sha256:${createHash("sha256").update(JSON.stringify([`openclaw.local-workspace.${e}.v1`, ...t])).digest("hex")}`; } const EMPTY_REF = digest("empty"); function parentPath(e) { const t = e.lastIndexOf("/"); return t === -1 ? "" : e.slice(0, t); } function localWorkspaceManifestRootReference(e, t) { return digest("root", t, e.get("").treeRef); } function createLocalWorkspaceManifestTree(e) { const t = { node: { path: "", type: "directory" }, priority: "" }; const n = /* @__PURE__ */ new Map([["", t]]); const r = /* @__PURE__ */ new Map(); for (const t of e.toSorted((e, t) => e.path < t.path ? -1 : e.path > t.path ? 1 : 0)) { if (t.path === "") throw new Error("The workspace manifest root cannot be changed"); const e = parentPath(t.path); const i = n.get(e); if (i?.node.type !== "directory") throw new Error(`Missing workspace manifest directory: ${e}`); const a = { node: t, priority: digest("priority", t.path) }; const o = r.get(e) ?? []; while (o.length && o.at(-1).priority > a.priority) a.left = o.pop(); const s = o.at(-1); if (s) s.right = a; else i.children = a; o.push(a); r.set(e, o); n.set(t.path, a); } const i = /* @__PURE__ */ new Map(); const finish = (e) => { if (!e) return; const t = manifestRecord(e.node, finish(e.left), finish(e.right), finish(e.children)); i.set(e.node.path, t); return t; }; finish(t); return i; } function manifestRecord(e, t, n, r, i) { const a = e.type === "directory" ? digest("directory", e.path, r?.treeRef ?? EMPTY_REF) : i?.node === e ? i.contentRef : e.type === "file" ? digest("file", e.path, e.mode, e.size, e.sha256) : digest("symlink", e.path, e.mode, e.target); return { node: e, left: t?.node.path ?? null, right: n?.node.path ?? null, children: r?.node.path ?? null, contentRef: a, treeRef: digest("siblings", t?.treeRef ?? EMPTY_REF, a, n?.treeRef ?? EMPTY_REF) }; } /** Each directory owns a deterministic sibling treap, so a flat directory is incremental too. */ function updateLocalWorkspaceManifestTree(e, t) { const n = /* @__PURE__ */ new Map(); const r = /* @__PURE__ */ new Set(); const i = /* @__PURE__ */ new Map(); const recordAt = (t) => t === null ? void 0 : e.get(t); function write(t, i, a, o) { const s = manifestRecord(t, recordAt(i), recordAt(a), recordAt(o), e.get(t.path)); e.set(t.path, s); n.set(t.path, s); r.delete(t.path); } function priority(e) { let t = i.get(e); if (t === void 0) { t = digest("priority", e); i.set(e, t); } return t; } function precedes(e, t) { const n = priority(e); const r = priority(t); return n < r || n === r && e < t; } function insert(t, n) { if (t === null) { write(n, null, null, null); return n.path; } const r = e.get(t); if (n.path === t) { if (n.type !== "directory" && r.children !== null) throw new Error(`Cannot replace nonempty workspace directory: ${t}`); write(n, r.left, r.right, r.children); return t; } if (n.path < t) { const i = insert(r.left, n); if (precedes(i, t)) { const n = e.get(i); write(r.node, n.right, r.right, r.children); write(n.node, n.left, t, n.children); return i; } write(r.node, i, r.right, r.children); } else { const i = insert(r.right, n); if (precedes(i, t)) { const n = e.get(i); write(r.node, r.left, n.left, r.children); write(n.node, t, n.right, n.children); return i; } write(r.node, r.left, i, r.children); } return t; } function merge(t, n) { if (t === null || n === null) return t ?? n; if (precedes(t, n)) { const r = e.get(t); write(r.node, r.left, merge(r.right, n), r.children); return t; } const r = e.get(n); write(r.node, merge(t, r.left), r.right, r.children); return n; } function remove(t, i) { if (t === null) return null; const a = e.get(t); if (i === t) { if (a.children !== null) throw new Error(`Cannot remove nonempty workspace directory: ${t}`); const i = merge(a.left, a.right); e.delete(t); n.delete(t); r.add(t); return i; } if (i < t) write(a.node, remove(a.left, i), a.right, a.children); else write(a.node, a.left, remove(a.right, i), a.children); return t; } function refresh(t, n) { const r = e.get(t); write(r.node, n < t ? refresh(r.left, n) : r.left, n > t ? refresh(r.right, n) : r.right, r.children); return t; } if (!e.has("")) write({ path: "", type: "directory" }, null, null, null); const a = t.toSorted((e, t) => { if (Boolean(e.node) !== Boolean(t.node)) return e.node ? 1 : -1; const n = e.path < t.path ? -1 : e.path > t.path ? 1 : 0; return e.node ? n : -n; }); for (const t of a) { if (t.path === "") throw new Error("The workspace manifest root cannot be changed"); if (!t.node && !e.has(t.path)) continue; let n = parentPath(t.path); const r = e.get(n); if (r?.node.type !== "directory") throw new Error(`Missing workspace manifest directory: ${n}`); let i = t.node ? insert(r.children, t.node) : remove(r.children, t.path); while (true) { const t = e.get(n); write(t.node, t.left, t.right, i); if (n === "") break; const r = parentPath(n); i = refresh(e.get(r).children, n); n = r; } } return { records: [...n.values()], removed: [...r] }; } //#endregion //#region src/gateway/worker-environments/local-workspace-manifest-scan.ts function manifestDocument(e, t, n, r = "current") { const i = { version: 1, baseCommit: t, entries: [], directories: [], ...n ? { buildCacheInputs: n } : {} }; for (const t of e) if (t.type === "directory") i.directories.push(t.path); else i.entries.push(t); const a = serializeWorkerWorkspaceManifest(i, r); return { rawManifest: a, manifestRef: `sha256:${createHash("sha256").update(a).digest("hex")}` }; } function prepareUpdate(e, t = []) { const n = e.manifest; const r = { ...e.patch, ...n ? { baseline_ref: n.resultingRoot, baseline_json: null } : {}, ...n?.treeRoot ? { tree_root_digest: localWorkspaceDigestBytes(n.treeRoot) } : {}, ...n?.fingerprints ? { [n.fingerprints.target === "canonical" ? "canonical_fingerprints" : "projection_fingerprints"]: Buffer.from(n.fingerprints.blob, "base64") } : {} }; return { revision: e.revision, patch: r, mutation: deflateRawSync(serialize({ ...e, patch: r })), preparations: t }; } async function executeLocalWorkspaceManifestRead(e, t) { const { row: n } = e; if (t.kind === "repair") { if (!n.baseline_ref) throw new Error("Local workspace repair requires its saved baseline reference"); const r = n.tree_root_digest ? localWorkspaceDigestReference(n.tree_root_digest) : n.baseline_ref; const i = buildCacheInputPaths(parseLocalWorkspaceSourcePaths(n.source_paths_json)); const a = n.checkpoint_json ? JSON.parse(n.checkpoint_json) : void 0; const o = a ? [parseWorkerWorkspaceManifest(a.baseManifestRaw, a.baseManifestRef, [...i], "stored"), parseWorkerWorkspaceManifest(a.currentManifestRaw, a.currentManifestRef, [...i], "stored")].map((e) => new Map([...e.entries.map((e) => [e.path, e]), ...(e.directories ?? []).map((e) => [e, { path: e, type: "directory" }])])) : []; const s = new Set(e.records.keys()); s.delete(""); const c = new Set([...e.records.values()].filter(({ node: e }) => e.type === "directory" && e.path !== "").map(({ node: e }) => e.path)); for (const e of o[1]?.values() ?? []) if (e.type === "directory") c.add(e.path); let l; let u; for (const e of [false, true]) { let d; let f; for (const p of [ "projection", "canonical", "canonicalWithProjectionPaths" ]) { const m = p === "canonicalWithProjectionPaths"; if (m && !d) continue; const h = p === "projection" ? n.projection_path : t.canonicalRoot; const g = []; try { let t; const r = new Set(c); if (p !== "projection") { l ??= await selectLocalWorkspaceCanonicalPaths({ root: h, admittedPaths: n.source_paths_json, baselinePaths: s, assertCurrent: () => void 0 }); t = new Set(l); if (m) { for (const e of d) t.add(e); for (const e of f) r.add(e); } for (const e of o) for (const n of e.keys()) t.add(n); } await scanActualWorkspaceManifest({ root: h, baseCommit: n.base_commit, includePaths: t, preserveDirectories: r, buildCacheInputs: i, includeLegacyPnpmStore: e, onEntry: (e) => g.push(e) }); } catch (e) { u = e; continue; } if (p === "projection") { d = new Set(g.map((e) => e.path)); f = new Set(g.filter((e) => e.type === "directory").map((e) => e.path)); } const _ = createLocalWorkspaceManifestTree(g); if (a && _.get("").treeRef === a.treeRoot && r === a.previousTreeRoot) { const [e, t] = o; updateLocalWorkspaceManifestTree(_, [.../* @__PURE__ */ new Set([...e.keys(), ...t.keys()])].map((t) => ({ path: t, node: e.get(t) }))); } const v = _.get("").treeRef; const y = [..._.values()].map(({ node: e }) => e).filter((e) => e.path !== ""); if ((n.tree_root_digest ? v : n.baseline_json ? manifestDocument(y, n.base_commit, void 0, "stored").manifestRef : localWorkspaceManifestRootReference(_, n.base_commit)) === r) return { kind: "replace", update: prepareUpdate({ kind: "update", revision: n.revision, patch: { tree_root_digest: localWorkspaceDigestBytes(v), ...!n.tree_root_digest && !n.pending_ref ? { baseline_json: null } : {}, canonical_fingerprints: null, projection_fingerprints: null } }, prepareLocalWorkspaceTreePacks(_)) }; } } throw new Error(`Local workspace baseline nodes are missing and neither workspace matches the saved baseline or a verified checkpoint. Both workspaces were preserved: canonical ${t.canonicalRoot}; sandbox ${n.projection_path}. A Gateway administrator must recover the saved baseline inventory before retrying the session. Inspect the preserved changes with: diff -ru -- ${shellEscape(t.canonicalRoot)} ${shellEscape(n.projection_path)}. Do not recreate or delete either workspace; retrying cannot safely choose between divergent edits.`, { cause: u }); } if (t.kind === "replace") { const e = parseWorkerWorkspaceManifest(t.rawManifest, t.manifestRef, t.buildCacheInputs); const r = createLocalWorkspaceManifestTree([...e.entries, ...(e.directories ?? []).map((e) => ({ path: e, type: "directory" }))]); const i = localWorkspaceManifestRootReference(r, e.baseCommit); return { kind: "replace", update: prepareUpdate({ kind: "update", revision: n.revision, patch: t.patch, manifest: { previousRoot: n.baseline_ref, resultingRoot: i, records: [], removed: [], treeRoot: r.get("").treeRef, previousTreeRoot: n.tree_root_digest ? localWorkspaceDigestReference(n.tree_root_digest) : null, replace: true } }, prepareLocalWorkspaceTreePacks(r)) }; } if (t.kind === "materialize" && n.baseline_json && n.baseline_ref) return { kind: "materialize", rawManifest: n.baseline_json, manifestRef: n.baseline_ref }; let { records: r } = e; const i = t.kind === "prepare" && t.manifest.replace; if (i) r = new Map(t.manifest.records.map((e) => [e.node.path, e])); if (!i && !n.tree_root_digest && n.baseline_json && n.baseline_ref) { const e = parseWorkerWorkspaceManifest(n.baseline_json, n.baseline_ref, void 0, "stored"); r = createLocalWorkspaceManifestTree([...e.entries, ...(e.directories ?? []).map((e) => ({ path: e, type: "directory" }))]); } else if (r.size === 0) { if (n.baseline_ref) throw new Error("Local workspace baseline nodes are missing"); r = createLocalWorkspaceManifestTree([]); } if (t.kind === "convert") { const e = Array.from(r.values(), ({ node: e }) => e).filter((e) => e.path !== ""); if (!n.baseline_json) r = createLocalWorkspaceManifestTree(e); if ((n.baseline_json ? manifestDocument(e, n.base_commit, void 0, "stored").manifestRef : localWorkspaceManifestRootReference(r, n.base_commit)) !== n.baseline_ref) return { kind: "rescan" }; return { kind: "replace", update: prepareUpdate({ kind: "update", revision: n.revision, patch: { tree_root_digest: localWorkspaceDigestBytes(r.get("").treeRef), baseline_json: n.pending_ref ? n.baseline_json : null, baseline_ref: n.baseline_ref, source_paths_json: n.source_paths_json } }, prepareLocalWorkspaceTreePacks(r)) }; } if (t.kind === "prepare") { const e = t.manifest; if (!e.replace) { for (const t of e.removed) r.delete(t); for (const t of e.records) r.set(t.node.path, t); } return { kind: "replace", update: prepareUpdate({ kind: "update", revision: n.revision, patch: t.patch, manifest: { ...e, records: [], removed: [], treeRoot: r.get("").treeRef, previousTreeRoot: n.tree_root_digest ? localWorkspaceDigestReference(n.tree_root_digest) : null } }, prepareLocalWorkspaceTreePacks(r)) }; } if (t.kind === "materialize") return { kind: "materialize", ...manifestDocument(Array.from(r.values(), ({ node: e }) => e).filter((e) => e.path !== ""), n.base_commit, void 0, "stored") }; const a = await selectLocalWorkspaceCanonicalPaths({ root: t.canonicalRoot, admittedPaths: n.source_paths_json, assertCurrent: () => void 0 }); const o = [...buildCacheInputPaths(a)]; const s = /* @__PURE__ */ new Set(); for (const [e, { node: t }] of r) { if (e === "") continue; if (t.type === "directory") s.add(e); a.add(e); } const c = t.target === "canonical" ? "projection" : "canonical"; const l = c === "canonical" ? n.canonical_fingerprints : n.projection_fingerprints; const u = /* @__PURE__ */ new Set(); const d = []; const f = n.tree_root_digest ? localWorkspaceDigestReference(n.tree_root_digest) : null; const p = Date.now(); const m = prepareLocalWorkspaceFingerprints(r, f ?? r.get("").treeRef, f ? l : null, p); await scanActualWorkspaceManifest({ root: t.target === "canonical" ? n.projection_path : t.canonicalRoot, baseCommit: n.base_commit, includePaths: t.target === "projection" ? a : void 0, gitIgnore: t.target === "canonical" ? await readLocalWorkspaceGitExclusions(t.canonicalRoot, n.projection_path, a) : void 0, preserveDirectories: s, buildCacheInputs: new Set(o), reuseFile: m.reuseFile, onEntry(e, t) { u.add(e.path); const n = r.get(e.path); if (!sameEntry(n?.node, e)) d.push({ path: e.path, node: e }); if (t !== void 0) m.observe(e.path, t); } }); for (const e of r.keys()) if (e !== "" && !u.has(e)) d.push({ path: e }); const h = /* @__PURE__ */ new Set(); for (const e of d) { h.add(e.path); for (const t of workspacePathAncestors(e.path)) h.add(t); const t = stagedInputPathDirectory(e.path); if (t) { h.add(`${t}/.gitignore`); for (const e of workspacePathAncestors(`${t}/.gitignore`)) h.add(e); } } const g = []; for (const e of h) { const t = r.get(e); if (t) g.push(t.node); } const _ = updateLocalWorkspaceManifestTree(r, d); const v = []; for (const e of h) { const t = r.get(e); if (t) v.push(t.node); } const y = manifestDocument(g, n.base_commit, o, "stored"); const b = manifestDocument(v, n.base_commit, o); const x = n.tree_root_digest === null; const S = r.get("").treeRef; const C = localWorkspaceManifestRootReference(r, n.base_commit); const w = m.encode(r, S); const T = w !== null && w !== l && (!l || !w.equals(l)); const E = w && T ? { target: c, blob: w.toString("base64") } : void 0; const D = o.length ? parseLocalWorkspaceSourcePaths(n.source_paths_json) : []; const O = new Set(D); const k = o.filter((e) => !O.has(e)); const A = C === n.baseline_ref; const j = k.length || A && T ? prepareUpdate({ kind: "update", revision: n.revision, patch: { ...k.length ? { source_paths_json: JSON.stringify([...D, ...k]) } : {}, ...A && T ? { [c === "canonical" ? "canonical_fingerprints" : "projection_fingerprints"]: w } : {} } }) : void 0; return { version: 1, kind: "scan", previousRoot: n.baseline_ref, resultingRoot: C, treeRoot: S, previousTreeRoot: f, ...E ? { fingerprints: E } : {}, preparations: S === f ? [] : prepareLocalWorkspaceTreePacks(r, x ? void 0 : [..._.records.map(({ node: e }) => e.path), ..._.removed]), records: [], observation: j, removed: [], ...x ? { replace: true } : {}, baseManifestRaw: y.rawManifest, baseManifestRef: y.manifestRef, currentManifestRaw: b.rawManifest, currentManifestRef: b.manifestRef, buildCacheInputs: o }; } //#endregion export { executeLocalWorkspaceManifestRead };