openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
315 lines (314 loc) • 11.2 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { i as assertExistingDatabaseIdentity, m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { t as SqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { o as registerOpenClawAgentDatabaseAsyncResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { l as readSqliteWorkerMonotonicNs } from "./sqlite-worker-contract--dxXkOty.mjs";
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { b as registerOpenClawStateDatabaseAsyncResource, x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { c as onUserProfilesChanged } from "./user-profile-events-BhLFevt9.mjs";
import { t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { i as githubPublicationReceipts } from "./github-publication-receipts-DrGMcoy5.mjs";
import { n as observeUserGitHubConnectionAuthority } from "./user-github-connection-events-BNVmTSdt.mjs";
import { t as projectGitHubPublicationSessionFacts } from "./github-publication-session-facts-BJYxLm50.mjs";
import { randomUUID } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
//#region src/infra/sqlite-source-fence-admission.ts
const SOURCE_FENCE_WAITING = 0;
const SOURCE_FENCE_REVOKED = 3;
/**
* Each dispatch gets one revocable acceptance decision. Once accepted, the broker
* retains native settlement; cancellation cannot release SQLite reservations.
*/
function createSqliteSourceFenceAdmission(e) {
if (e.sources.length === 0) throw new Error("SQLite source fence requires an explicit source");
const t = [e.destination, ...e.sources];
const n = t.map(({ identity: e }) => {
if (!e.physical.key.startsWith("file:") || !e.incarnation) throw new Error("SQLite source fence requires retained durable owners");
return structuredClone(e);
});
const r = structuredClone(e.destination.identity);
return (i) => {
const a = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
const o = /* @__PURE__ */ new Set([e.signal, ...t.map((e) => e.signal)]);
const revoke = () => {
for (;;) {
const e = Atomics.load(a, 0);
if (e === 2 || e === SOURCE_FENCE_REVOKED) return;
if (Atomics.compareExchange(a, 0, e, SOURCE_FENCE_REVOKED) === e) return;
}
};
const assertCurrent = () => {
if ([...o].some((e) => e.aborted)) revoke();
if (Atomics.load(a, 0) === SOURCE_FENCE_REVOKED || readSqliteWorkerMonotonicNs() >= e.deadlineNs) throw new SqliteWorkerError("SQLite source fence authority expired", "closed");
for (const e of t) e.assertCurrent();
};
assertCurrent();
for (const e of t) e.retain(i);
for (const e of o) e.addEventListener("abort", revoke, { once: true });
const detach = () => {
revoke();
for (const e of o) e.removeEventListener("abort", revoke);
};
const s = {
kind: "sqlite-source-fence",
version: 1,
decision: a.buffer,
remainingNs: new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT),
destination: r,
sources: n.slice(1)
};
try {
const t = createSqliteWorkerOperationAdmission((t, n) => {
if (t.stage !== "prepare" || t.facts !== "sqlite-source-fence" || Atomics.load(a, 0) !== SOURCE_FENCE_WAITING) throw new SqliteWorkerError("SQLite source fence admission requested out of order", "closed");
assertCurrent();
Atomics.store(new BigInt64Array(s.remainingNs), 0, e.deadlineNs - readSqliteWorkerMonotonicNs());
if (!n(() => {
if (Atomics.compareExchange(a, 0, SOURCE_FENCE_WAITING, 1) !== SOURCE_FENCE_WAITING) throw new SqliteWorkerError("SQLite source fence authority expired", "closed");
})) revoke();
}, s);
i.settled.then(detach, detach);
return {
admission: t,
nativeLocations: n.map((e) => e.physical.canonicalPath)
};
} catch (e) {
detach();
throw e;
}
};
}
//#endregion
//#region src/gateway/github-publication-source.ts
const { bindings, destinationIncarnations } = resolveGlobalSingleton(Symbol.for("openclaw.githubPublicationSourceCapabilities"), () => ({
bindings: /* @__PURE__ */ new WeakMap(),
destinationIncarnations: /* @__PURE__ */ new WeakMap()
}));
/** Compose the publication runtime's lifetime before native admission captures its signals. */
function bindGitHubPublicationSourceLifetime(e, t) {
const n = bindings.get(e);
if (!n || n.admitted) throw new Error("GitHub publication source lifetime was already admitted.");
const r = AbortSignal.any([n.signal, t]);
r.throwIfAborted();
n.signal = r;
if (n.kind === "durable") {
n.source = {
...n.source,
signal: r
};
n.destination = {
...n.destination,
signal: r
};
}
return e;
}
function bindGitHubPublicationSource(e, t) {
const n = bindings.get(e);
if (!n) throw new Error("GitHub publication source capability is unavailable.");
n.signal.throwIfAborted();
return {
context: n.context,
predicate: n.predicate,
createAdmission: ((e) => {
n.admitted = true;
if (n.kind === "memory") {
n.retain(e);
return {
admission: createSqliteWorkerOperationAdmission((e, r) => {
if (e.stage !== "prepare") throw new Error("Memory publication authority requires a preparation grant.");
n.signal.throwIfAborted();
n.assertCurrent();
t?.();
r();
}),
nativeLocations: [n.context.admission.databasePath]
};
}
return createSqliteSourceFenceAdmission({
destination: {
...n.destination,
assertCurrent() {
n.destination.assertCurrent();
t?.();
}
},
sources: [n.source],
signal: n.signal,
deadlineNs: readSqliteWorkerMonotonicNs() + 120000000000n
})(e);
})
};
}
function readMemorySourceFacts(e, t) {
const n = e.owner ? e.owner.readSession(t, e.authority) : e.binding?.actor.storage?.readCurrent({
type: "session.members.read",
input: {}
}, e.authority);
return projectGitHubPublicationSessionFacts(n?.entry, n?.members ?? []);
}
async function prepareMemoryPublicationSource(e, t, n) {
const r = readMemorySourceFacts(n, e.selector.sessionKey);
const i = {
memory: r,
selector: structuredClone(e.selector)
};
const a = await runOpenClawStateWorkerOperation(t, (e) => e.execute({
type: "githubPublication.sourceFacts",
input: { source: i }
}), {
signal: e.signal,
assertCurrent: () => e.assertCurrent()
});
const o = /* @__PURE__ */ new Set();
let s = false;
const c = Object.freeze({
version: 1,
async release() {
s = true;
await Promise.allSettled(o);
}
});
bindings.set(c, {
kind: "memory",
context: t,
predicate: {
...i,
expected: a
},
signal: e.signal,
admitted: false,
assertCurrent() {
t.admission.assertCurrent();
e.assertCurrent();
if (s || !isDeepStrictEqual(readMemorySourceFacts(n, e.selector.sessionKey), r)) throw new Error("GitHub publication source authority changed.");
},
retain(e) {
o.add(e.settled);
e.settled.then(() => o.delete(e.settled), () => o.delete(e.settled));
}
});
return c;
}
/** Host policy executes before reservation; the worker rechecks every durable source fact. */
async function prepareGitHubPublicationSource(e) {
e.signal.throwIfAborted();
e.assertCurrent();
const t = captureOpenClawStateWorkerContext();
const n = captureSessionActorStorageOwner({
...e.selector,
storePath: e.sourcePath
}, {
assertCurrent() {},
authorize() {}
});
if (n) return prepareMemoryPublicationSource(e, t, n);
const r = readDatabasePathIdentitySync(e.sourcePath);
if (!r.key.startsWith("file:") || r.birthtime === void 0) throw new Error("GitHub publication requires an admitted durable source.");
const i = new AbortController();
const a = AbortSignal.any([e.signal, i.signal]);
const o = /* @__PURE__ */ new Set();
const s = [];
let c;
let l;
const revoke = () => i.abort(/* @__PURE__ */ new Error("GitHub publication source authority changed."));
const drain = async () => {
revoke();
await Promise.allSettled(o);
};
const release = () => c ??= (async () => {
await drain();
for (const e of s.splice(0).toReversed()) e();
})();
const assertCurrent = () => {
a.throwIfAborted();
t.admission.assertCurrent();
assertExistingDatabaseIdentity(e.sourcePath, r.key, r.birthtime);
};
const retain = (e) => {
assertCurrent();
o.add(e.settled);
e.settled.then(() => o.delete(e.settled), () => o.delete(e.settled));
};
const u = {
physical: r,
incarnation: randomUUID()
};
s.push(registerOpenClawAgentDatabaseAsyncResource({
agentId: e.selector.agentId,
path: e.sourcePath,
revoke,
close: drain
}), registerOpenClawStateDatabaseAsyncResource({ close: drain }), registerOpenClawStateDatabaseLifecycleListener((e) => {
if (e.kind !== "opened" && e.path === t.admission.databasePath) revoke();
}), onUserProfilesChanged(revoke), observeUserGitHubConnectionAuthority(({ databasePath: n, changedOwners: r }) => {
if (n === t.admission.databasePath && e.selector.personalOwnerProfileId !== void 0 && r.includes(e.selector.personalOwnerProfileId)) revoke();
}), githubPublicationReceipts.subscribeFacts((e, n) => {
if (e.kind === "pending" && n && e.identity === t.admission.identity.key && !l?.admitted || e.kind === "unknown" && e.identity === t.admission.identity.key || e.kind === "committed" && e.receipt.source.identity === t.admission.identity.key && [...e.receipt.facts.values()].some((e) => e.kind !== "postimage")) revoke();
}), sessionChanges.subscribeFacts((t) => {
if ("all" in t || t.sessionKey === e.selector.sessionKey) revoke();
}));
try {
let n = destinationIncarnations.get(t.admission);
if (!n) {
n = randomUUID();
destinationIncarnations.set(t.admission, n);
}
const r = {
source: u,
destination: {
physical: t.admission.identity,
incarnation: n
},
selector: structuredClone(e.selector)
};
const i = await runOpenClawStateWorkerOperation(t, (e) => e.execute({
type: "githubPublication.sourceFacts",
input: { source: r }
}), {
signal: a,
assertCurrent
});
r.destination.physical = t.admission.identity;
e.assertCurrent();
assertCurrent();
const o = Object.freeze({
version: 1,
release
});
l = {
kind: "durable",
context: t,
predicate: {
...r,
expected: i
},
source: {
identity: u,
signal: a,
assertCurrent: () => {
e.assertCurrent();
assertCurrent();
},
retain
},
destination: {
identity: r.destination,
signal: a,
assertCurrent,
retain
},
signal: a,
admitted: false
};
bindings.set(o, l);
return o;
} catch (e) {
await release();
throw e;
}
}
//#endregion
export { bindGitHubPublicationSourceLifetime as n, prepareGitHubPublicationSource as r, bindGitHubPublicationSource as t };