UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

388 lines (387 loc) • 14.1 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs"; import { n as OpenClawStateLeaseError, r as createOpenClawStateLeaseAbortError } from "./openclaw-state-lease-error-Dq51JM59.mjs"; import "./sqlite-worker-contract--dxXkOty.mjs"; import { a as observeSqliteWorkerCommittedFacts } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs"; import { i as withOpenClawStateLeasesWorkerAdmission } from "./openclaw-state-lease-worker-owner-ByOat7YE.mjs"; import { n as withOpenClawStateLeaseAsync } from "./openclaw-state-lease-Cn13CM0c.mjs"; import { i as captureWorktreeRunEndContext, l as withWorktreeRunEnd, s as retainWorktreeRunEndFailure } from "./run-end-lifecycle-CvtGWdnp.mjs"; import { t as createKeyedFifoLeaseRegistry } from "./keyed-fifo-lease-lNbi_ByQ.mjs"; import { o as computeWorkspaceManifest } from "./workspace-manifest-worker-CfX0osDw.mjs"; import { r as prepareLocalWorkspaceSourcePathSet, t as localWorkspaceDigestBytes } from "./local-workspace-cas-DxFAvLyr.mjs"; import { deserialize, serialize } from "node:v8"; import { AsyncLocalStorage } from "node:async_hooks"; import { promisify } from "node:util"; import { deflateRaw, deflateRawSync, inflateRawSync } from "node:zlib"; //#region src/gateway/worker-environments/local-workspace-lease.ts const waitMs = 6e4; const queue = createKeyedFifoLeaseRegistry(Symbol.for("openclaw.localWorkspaceLeaseQueue")); const current = new AsyncLocalStorage(); /** Local hand-off orders callers; the persisted lease still owns exclusion and expiry. */ async function withLocalWorkspaceLease(e, t, n) { const r = JSON.stringify([t.admission.coordinationKey, e.worktreeId]); const i = current.getStore() ?? []; if (i.some((e) => e.active && e.key === r)) throw new OpenClawStateLeaseError(`Local sandbox operation already holds workspace.local-reconciliation/${e.worktreeId}; release execution custody before checkpointing this workspace`, { code: "OPENCLAW_STATE_LEASE_INVALID_INPUT" }); const a = new AbortController(); const o = e.signal ? AbortSignal.any([e.signal, a.signal]) : a.signal; const s = setTimeout(() => { a.abort(new OpenClawStateLeaseError(`Timed out after ${waitMs} ms waiting for local sandbox workspace workspace.local-reconciliation/${e.worktreeId}; retry the tool call after the current checkpoint or reconciliation finishes`, { code: "OPENCLAW_STATE_LEASE_HELD" })); }, waitMs); s.unref?.(); const c = queue.reserve([r]); const l = { key: r, active: true }; try { await racePromiseWithAbortSignal(c.wait(), o, (e) => createOpenClawStateLeaseAbortError(e, "acquisition", "local sandbox workspace")); o.throwIfAborted(); return await withOpenClawStateLeaseAsync({ scope: "workspace.local-reconciliation", key: e.worktreeId, leaseMs: 6e4, waitMs, signal: o, leaseLabel: "local sandbox workspace", operationLabel: "workspace.local-reconciliation" }, t, (e) => { clearTimeout(s); return current.run([...i, l], () => n(e)); }); } catch (e) { if (a.signal.aborted && !hasSqliteWorkerOutcomeUnknown(e)) throw a.signal.reason; throw e; } finally { clearTimeout(s); l.active = false; c.release(); } } //#endregion //#region src/gateway/worker-environments/local-workspace-publication.ts function freezeProjection(e) { const t = e.journal_pack; if (Buffer.isBuffer(t)) e.journal_pack = new Uint8Array(t.buffer, t.byteOffset, t.byteLength); return Object.freeze(e); } /** Reconstruct only the admitted mutation; caller-provided prior rows carry no authority. */ function readLocalWorkspaceCommit(e, t, n, r) { if (e === void 0) throw new Error("Local workspace commit coverage is incomplete"); if (n.kind === "delete" && e === null) return; if (isRecord(e) && e.worktree_id === t) { if (n.kind === "create" && e.revision === 0) return freezeProjection({ ...n.row, revision: 0 }); if (n.kind === "update" && r?.worktree_id === t && r.revision === n.revision && e.revision === n.revision + 1) return freezeProjection({ ...r, ...Object.fromEntries(Object.entries(n.patch).filter(([, e]) => e !== void 0)), ...n.manifest ? { baseline_ref: n.manifest.resultingRoot, baseline_json: null, ...n.manifest.treeRoot ? { tree_root_digest: localWorkspaceDigestBytes(n.manifest.treeRoot) } : {}, ...n.manifest.fingerprints ? { [`${n.manifest.fingerprints.target}_fingerprints`]: Uint8Array.from(Buffer.from(n.manifest.fingerprints.blob, "base64")) } : {} } : {}, worktree_id: t, revision: n.revision + 1 }); } throw new Error("Local workspace commit identity is invalid"); } //#endregion //#region src/gateway/worker-environments/local-workspace-store.ts const compressMutation = promisify(deflateRaw); async function hasLocalWorkspaceProjection(e, t) { return (await executeExistingOpenClawStateRead({ env: t }, { type: "localWorkspace.exists", input: { id: e } }, { current: true, live: true }))?.exists ?? false; } /** The reconciliation lease owns present and absent rows through effects and settlement. */ function withLocalWorkspaceStore(e, t) { const n = e.env ?? process.env; const r = captureWorktreeRunEndContext(n); const i = e.workerAuthority?.leaseSet; const a = i?.mutationWorktreeIds?.slice(); const o = i?.context ?? r; if (o.admission.coordinationKey !== r.admission.coordinationKey) throw new Error("Local workspace lease belongs to another database"); return withWorktreeRunEnd(n, () => withLocalWorkspaceLease({ worktreeId: e.worktreeId, signal: e.signal }, o, (n) => { const s = [...i?.leases ?? [], n]; return withOpenClawStateLeasesWorkerAdmission(s, o, async (i) => { let c = true; let l; const u = e.workerAuthority ? e.workerAuthority.assertCurrent : e.assertCurrent; const assertCustody = () => { r.admission.assertCurrent(); i.assertCurrent(); if (!c) throw new Error("Local workspace custody has ended"); }; const assertHost = () => { assertCustody(); u?.(); }; const assertCurrent = () => { assertHost(); if (e.assertCurrent !== u) e.assertCurrent?.(); }; try { return await runOpenClawStateWorkerOperation(o, async () => { const r = await executeExistingOpenClawStateRead({ path: o.admission.databasePath, env: o.environment }, { type: e.requireAbsent ? "localWorkspace.exists" : "localWorkspace.get", input: { id: e.worktreeId } }, { context: o, current: true, live: true }); assertCurrent(); if (r?.type === "localWorkspace.exists" && r.exists) throw new Error("Snapshot retains local workspace projection custody; preserve its recovery data"); l = r?.type === "localWorkspace.get" && r.row ? Object.freeze(r.row) : void 0; const pruneLegacy = async () => { if (!l?.tree_root_digest) return; let t; do { assertCurrent(); t = await runOpenClawStateWorkerOperation(o, (t) => t.execute({ type: "localWorkspace.pruneLegacy", input: { id: e.worktreeId } }), { assertCurrent }); } while (t); }; await pruneLegacy(); let i; const prepare = async (e) => { for (const t of e) { assertCurrent(); const e = await runOpenClawStateWorkerOperation(o, (e) => e.execute({ type: "localWorkspace.prepare", input: { preparation: t } }), { assertCurrent }); i = Math.min(i ?? e, e); } assertCurrent(); }; const mutate = async (t, n = e.workerAuthority ?? {}, r) => { assertCurrent(); if (t.kind === "update" && t.manifest) { const { previousRoot: e, resultingRoot: n, treeRoot: r, fingerprints: i } = t.manifest; t.manifest = { previousRoot: e, resultingRoot: n, treeRoot: r, fingerprints: i, records: [], removed: [] }; } let a = t; const d = t.kind === "create" ? t.row : t.kind === "update" ? t.patch : void 0; if (typeof d?.source_paths_json === "string") { const e = prepareLocalWorkspaceSourcePathSet(d.source_paths_json); await prepare([deflateRawSync(serialize({ paths: e }))]); d.source_paths_digest = localWorkspaceDigestBytes(e.digest); if (t.kind === "create") a = { ...t, row: { ...t.row, source_paths_json: "[]" } }; else if (t.kind === "update") a = { ...t, patch: { ...t.patch, source_paths_json: "[]" } }; } if (r && a.kind === "update") a = { ...a, patch: { ...a.patch, journal_pack: void 0 } }; let f = { mutation: t, previous: l }; const p = structuredClone(n.predicates); const m = serialize(a); const h = m.byteLength > 33554432 ? await compressMutation(m) : void 0; if (h && h.byteLength < m.byteLength) a = h; let g; let _; const assertWrite = () => { if (n.assertCurrent !== assertHost) assertHost(); if (n.assertCurrent !== u) n.assertCurrent?.(); }; try { const t = await withOpenClawStateLeasesWorkerAdmission(s, o, (t) => runOpenClawStateWorkerOperation(o, (n) => n.execute({ type: "localWorkspace.mutate", input: { id: e.worktreeId, mutation: a, preparationEpoch: i, predicates: p, leases: t.identities } }, r ? { transferredInput: { journalPack: r } } : void 0), { assertCurrent: assertWrite, createAdmission(n) { _ = n.settled; const r = t.createAdmission(n); g = r.admission; observeSqliteWorkerCommittedFacts(g, ({ facts: t }) => { (o.assertPublicationCurrent ?? o.admission.assertCurrent)(); if (t !== void 0) readLocalWorkspaceCommit(t, e.worktreeId, f.mutation, f.previous); }); return r; } }), { assertCurrent: assertWrite }); l = readLocalWorkspaceCommit(t, e.worktreeId, f.mutation, f.previous); if (!f.previous?.tree_root_digest) await pruneLegacy(); } catch (t) { if ((await _)?.kind === "completed" && g?.committed) try { l = readLocalWorkspaceCommit(g.committed.facts, e.worktreeId, f.mutation, f.previous); } catch (e) { c = false; retainWorktreeRunEndFailure(e); throw e; } else { c = false; retainWorktreeRunEndFailure(t); throw t; } } finally { f = void 0; a = void 0; } }; const readManifest = async (t, r) => { assertCurrent(); if (t.worktree_id !== e.worktreeId) throw new Error("Local workspace binding changed"); const i = await executeExistingOpenClawStateRead({ path: o.admission.databasePath, env: o.environment }, { type: "localWorkspace.manifest", input: { id: e.worktreeId, revision: t.revision, action: r } }, { context: o, current: true, live: true, signal: n.signal }); assertCurrent(); if (!i) throw new Error("Local workspace manifest is unavailable"); const a = await computeWorkspaceManifest({ type: "workspace.manifest.local", input: { snapshot: i.snapshot } }, n.signal); assertCurrent(); if (a.kind === "scan") { await prepare(a.preparations ?? []); const { preparations: e, ...t } = a; return t; } if (a.kind === "replace") { await prepare(a.update.preparations ?? []); a.update.preparations = void 0; } return a; }; const accept = async (e, t) => { await prepare(e.preparations ?? []); const n = inflateRawSync(e.mutation); const r = deserialize(n); await mutate(r, t); return l; }; return await t({ signal: n.signal, assertCurrent, workerAuthority: { ...e.workerAuthority, leaseSet: { context: o, leases: s, mutationWorktreeIds: a }, assertCurrent: assertHost }, get: () => { assertCustody(); return l; }, manifest: readManifest, accept, create: async (e, t) => { await mutate({ kind: "create", row: e }, t); return l; }, update: async (t, n, r, i, a) => { if (t.worktree_id !== e.worktreeId) throw new Error("Local workspace binding changed"); if (i && "rawManifest" in i) { const e = await readManifest(t, { kind: "replace", ...i, patch: n }); if (e.kind !== "replace") throw new Error("Local workspace baseline preparation is missing"); await accept(e.update, r); } else if (i && !i.treeRoot) { const e = await readManifest(t, { kind: "prepare", manifest: i, patch: n }); if (e.kind !== "replace") throw new Error("Local workspace checkpoint preparation is missing"); await accept(e.update, r); } else await mutate({ kind: "update", revision: t.revision, patch: n, manifest: i }, r, a); return l; }, delete: async (t, n) => { if (t.worktree_id !== e.worktreeId) throw new Error("Local workspace binding changed"); await mutate({ kind: "delete", revision: t.revision }, n); } }); }, { assertCurrent: assertHost }); } finally { c = false; l = void 0; } }); })); } //#endregion export { withLocalWorkspaceStore as n, hasLocalWorkspaceProjection as t };