UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

567 lines (566 loc) • 20 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { h as resolveDatabasePathKey } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { t as SqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs"; import "./sqlite-worker-contract--dxXkOty.mjs"; import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { n as captureOpenClawStateReadWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { n as getOpenClawAgentDatabaseIfOpen } from "./openclaw-agent-db-borrower-BrziJlyo.mjs"; import { n as withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-COYfV-vn.mjs"; import { i as runOpenClawAgentWorkerWrite } from "./session-worker-execution-source-H3bdawqM.mjs"; import "./openclaw-agent-db-CwXW4hGa.mjs"; import { t as captureSessionTranscriptStorageEnvironment } from "./transcript-target-binding-BvjuRqS9.mjs"; import { u as withSessionStoreReaderInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { i as toDatabaseOptions } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import { t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { a as resolveSqliteReadScope } from "./session-accessor.sqlite-read-scope-7Z2ARJnl.mjs"; import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import { n as captureOpenClawAgentDatabaseExecution } from "./openclaw-agent-execution-C4FyHhb0.mjs"; import { r as retainSessionHistoryWorkerDatabase } from "./session-transcript-worker-runtime-DMpH3wlh.mjs"; import { a as withConversationPublication, r as readStagedConversationPublications, t as conversationPublication } from "./session-accessor.sqlite-conversation-publication-4m95G3qV.mjs"; import { t as memorySessionActorOwners } from "./session-actor-memory-owner-BkB9Vtu4.mjs"; import { t as normalizeStoredConversationRef } from "./conversation-record-policy-DT1Kg34H.mjs"; import { t as readSessionActorStorageResult } from "./session-actor-storage-result-BkDuCjds.mjs"; import { n as selectConversationRowsFromDatabase } from "./session-accessor.sqlite-conversation-read-kr7lcwOX.mjs"; import path from "node:path"; //#region src/config/sessions/conversation-binding-facts.ts const factKey = (...e) => JSON.stringify(e); function applyFacts(e, t) { for (const [n, r] of t) if (r.kind === "absent") { const t = e.get(n); e.delete(n); if (t?.kind === "window") { for (const [n, r] of e) if (r.kind === "association" && r.row.session_id === t.row.session_id) e.delete(n); } } else if (r.kind === "postimage") { if (r.value.kind === "rehome") { const t = r.value; for (const [n, r] of e) if (r.kind === "window" && (r.row.session_id === t.sessionId || t.previousKeys?.includes(r.row.session_key))) e.set(n, { kind: "window", row: { ...r.row, session_key: t.sessionKey } }); } else e.set(n, r.value); } } /** A request-scoped projection of the publication owner, retaining every possible winner. */ function retainConversationBindingFacts(e, t) { const n = resolveDatabasePathKey(t); const r = new Set(e); let i = /* @__PURE__ */ new Map(); let a; let o = true; let s = true; let c = true; const l = []; const u = /* @__PURE__ */ new Set(); const sameSource = (e) => a ? e.source.identity === a.identity : e.source.canonicalPath === n; const relevant = (e) => [...e.facts].some(([e, t]) => i.has(e) || t.kind === "postimage" && (t.value.kind === "catalogue" || t.value.kind === "association" ? r.has(t.value.row.conversation_id) : t.value.kind === "rehome")); const receive = (e) => { if (s) { l.push(e); return; } if ("facts" in e) { if (!sameSource(e)) return; a ??= e.source; if ([...e.facts.values()].some((e) => e.kind === "unknown")) o = false; applyFacts(i, e.facts); } else if (e.kind === "unknown") { if (sameSource(e)) o = false; } else if (e.kind === "pending") { if ((a ? e.databaseIdentity === a.identity : e.databasePath === n) && (e.receipts === void 0 || e.receipts.some(relevant))) u.add(e.operation); } else if (u.delete(e.operation) && e.outcome === "unknown") o = false; }; const prune = () => { const e = /* @__PURE__ */ new Set(); const t = /* @__PURE__ */ new Set(); for (const t of i.values()) if (t.kind === "association" && r.has(t.row.conversation_id)) e.add(t.row.session_id); for (const n of i.values()) if (n.kind === "window" && e.has(n.row.session_id)) t.add(n.row.session_key); for (const [n, a] of i) if (!(a.kind === "catalogue" || a.kind === "association" ? r.has(a.row.conversation_id) : a.kind === "window" ? e.has(a.row.session_id) : a.kind === "node" && t.has(a.row.session_key))) i.delete(n); }; const d = conversationPublication.subscribeFacts(receive); const f = conversationPublication.subscribe(prune); return { acknowledge(e) { a = e.source; const t = /* @__PURE__ */ new Map(); for (const n of e.catalogues) t.set(factKey("catalogue", n.conversation_id), { kind: "postimage", value: { kind: "catalogue", row: n } }); for (const n of e.associations) t.set(factKey("association", n.session_id, n.conversation_id, n.role), { kind: "postimage", value: { kind: "association", row: n } }); for (const n of e.windows) t.set(factKey("window", n.session_id), { kind: "postimage", value: { kind: "window", row: n } }); for (const n of e.nodes) t.set(factKey("node", n.session_key), { kind: "postimage", value: { kind: "node", row: n } }); i = /* @__PURE__ */ new Map(); applyFacts(i, t); s = false; for (const e of l) receive(e); l.length = 0; prune(); }, currentSessionKey(e) { if (!c || !o || s || u.size) throw new Error("Conversation binding publication is unavailable"); const t = readStagedConversationPublications().filter(sameSource); const n = t.length ? new Map(i) : i; for (const e of t) applyFacts(n, e.facts); const r = n.get(factKey("catalogue", e)); if (r?.kind !== "catalogue" || ![ "channel", "direct", "group" ].includes(r.row.kind)) return null; let a; for (const t of n.values()) { if (t.kind !== "association" || t.row.conversation_id !== e) continue; const r = t.row; const i = n.get(factKey("window", r.session_id)); if (i?.kind !== "window") continue; const o = n.get(factKey("node", i.row.session_key)); if (o?.kind !== "node" || o.row.entry_valid !== 1 || o.row.current_session_id !== r.session_id || o.row.entry_session_id !== r.session_id || !(r.role === "participant" || r.role === "primary" && i.row.primary_conversation_id === e)) continue; if (!a || r.last_seen_at > a.seen || r.last_seen_at === a.seen && o.row.updated_at > a.updated) a = { key: o.row.session_key, seen: r.last_seen_at, updated: o.row.updated_at }; } return a?.key ?? null; }, release() { c = false; d(); f(); i.clear(); l.length = 0; } }; } //#endregion //#region src/config/sessions/conversation-registry.ts const conversationAuthority = { assertCurrent() {}, authorize() {} }; async function prepareConversationRegistryScope(e) { const t = { agentId: e.agentId, storePath: resolveSessionStorePathCore(e.config.session?.store, { agentId: e.agentId }) }; const n = captureSessionActorStorageOwner(t, conversationAuthority); if (n) return { agentId: n.agentId, databaseAgentId: n.agentId, storePath: n.path, env: captureSessionTranscriptStorageEnvironment(process.env) }; return withConversationRead(t, async ({ database: e, logicalAgentId: t }) => ({ agentId: t, databaseAgentId: e.agentId, storePath: e.path, env: e.env })); } function withConversationRead(e, t) { const n = captureSessionTranscriptStorageEnvironment(e.env ?? process.env); const r = path.resolve(e.storePath ?? resolveSessionStorePathCore(void 0, { agentId: e.agentId, env: n })); const i = captureOpenClawStateReadWorkerContext({ env: n }); return withSessionStoreReaderInWorker({ agentId: e.agentId, storePath: r, env: n }, async (n) => { if (e.databaseAgentId && n.database.agentId !== e.databaseAgentId) throw new Error("Conversation database owner changed. Retry the request."); const r = await t(n); n.assertCurrent(); return r; }, { dataOnly: true, logical: { assertCurrent() { i.maintenanceScope?.assertAdmission(); i.admission.assertCurrent(); } } }); } function readConversationsAsync(e, t) { const n = captureSessionActorStorageOwner({ agentId: e.databaseAgentId ?? e.agentId, storePath: e.storePath, env: e.env }, conversationAuthority); if (n) { const e = structuredClone(t); if (n.binding && n.agentId === n.binding.agentId && n.path === n.binding.path) return n.binding.actor.storage.read({ type: "session.conversation.read", input: e }, n.authority); return n.owner?.readConversationAfterWrites({ type: "session.conversation.read", input: e }, n.authority) ?? Promise.resolve([]); } return withConversationRead(e, ({ reader: e, database: n }) => e.readConversations({ query: t, env: n.env })); } /** Capture once; final effects consume the conversation writer's published current bindings. */ async function captureConversationBindingFacts(e, t) { const n = [...new Set(t.map(normalizeStoredConversationRef))]; const r = captureSessionActorStorageOwner({ agentId: e.databaseAgentId ?? e.agentId, storePath: e.storePath, env: e.env }, conversationAuthority); if (r) { let e = true; return { currentSessionKey(t) { if (!e) throw new Error("Conversation binding reader was released"); const n = { conversationRef: t, currentBindingOnly: true, limit: 1 }; return (r.binding && r.agentId === r.binding.agentId && r.path === r.binding.path ? r.binding.actor.storage.readCurrent({ type: "session.conversation.read", input: n }, r.authority) : (r.owner ?? memorySessionActorOwners.read({ agentId: r.agentId, path: r.path }))?.readConversations(n, r.authority))?.[0]?.sessionKey ?? null; }, release() { e = false; } }; } let releaseFacts; let i; const release = () => { releaseFacts?.(); i?.release(); }; try { return await withConversationRead(e, async ({ reader: e, database: t, assertCurrent: r }) => { const a = retainConversationBindingFacts(n, t.path); releaseFacts = () => a.release(); i = retainSessionHistoryWorkerDatabase(t); const o = await e.readConversationBindings({ conversationRefs: n, env: t.env }); a.acknowledge(o); return { currentSessionKey(e) { r(); return a.currentSessionKey(e); }, release }; }); } catch (e) { release(); throw e; } } function pinConversationDatabaseScope(e) { const t = { ...e.env ?? process.env }; t.OPENCLAW_STATE_DIR = resolveStateDir(t); const n = e.databaseAgentId && e.storePath ? { agentId: e.databaseAgentId, path: e.storePath, env: t } : toDatabaseOptions(resolveSqliteReadScope({ ...e, env: t })); const r = resolveOpenClawAgentSqlitePath(n); return { options: { ...n, path: r }, scope: { ...e, databaseAgentId: n.agentId, storePath: r, env: t } }; } function selectConversationRows(e, t = {}) { const n = captureSessionActorStorageOwner({ agentId: e.databaseAgentId ?? e.agentId, storePath: e.storePath, env: e.env }, conversationAuthority); if (n) { if (n.binding && n.agentId === n.binding.agentId && n.path === n.binding.path) return n.binding.actor.storage.readCurrent({ type: "session.conversation.read", input: t }, n.authority); return n.owner?.readConversations(t, n.authority) ?? []; } const r = resolveSqliteReadScope({ agentId: e.agentId, ...e.env ? { env: e.env } : {}, ...e.storePath ? { storePath: e.storePath } : {} }); const i = toDatabaseOptions(r); const readRows = (e) => selectConversationRowsFromDatabase(e, t); const a = getOpenClawAgentDatabaseIfOpen(i); if (a?.db.isTransaction) return readRows(a); const o = withOpenClawAgentDatabaseReadOnly(readRows, i); return o.found ? o.value : []; } /** Catalogs routable addresses in the existing agent writer without creating sessions. */ async function registerConversationAddresses(e, t, n = Date.now(), r = (e) => e.map(() => true), i) { if (t.length === 0) return; const a = captureSessionActorStorageOwner({ agentId: e.databaseAgentId ?? e.agentId, storePath: e.storePath, env: e.env }, conversationAuthority); if (a) { const e = a.binding && a.binding.agentId === a.agentId && a.binding.path === a.path ? a.binding : void 0; if (!e) return (a.owner ?? memorySessionActorOwners.get({ agentId: a.agentId, path: a.path })).mutateConversation({ type: "session.conversation.register", input: { identities: t, discoveredAt: n, query: i } }, a.authority, r); return readSessionActorStorageResult(await e.actor.storage.mutate({ type: "session.conversation.register", input: { identities: t, discoveredAt: n, query: i } }, { ...a.authority, authorize(e, t, n) { a.authority.authorize(e, t, n); if (isRecord(n) && n.kind === "session.conversation.registration") { const e = n; e.eligible = r(structuredClone(e.identities)); } } })); } const { options: o } = pinConversationDatabaseScope(e); const s = { identities: t, discoveredAt: n, query: i }; const selectCurrent = () => { const e = r(s.identities); if (e.length !== s.identities.length) throw new Error("Conversation route owner returned an incomplete eligibility selection"); return e; }; const assertCurrent = () => { if (!selectCurrent().every(Boolean)) throw new Error("Conversation route ownership changed during discovery"); }; const c = { assertCurrent() {}, createAdmission(e) { return () => ({ nativeLocations: e.nativeLocations, admission: createSqliteWorkerOperationAdmission((t, n) => { e.authorize(t); if (t.stage === "transaction" || t.stage === "commit") assertCurrent(); if (!n()) throw new Error("Conversation registration authority expired"); }, e.attachment) }); } }; const l = captureOpenClawAgentDatabaseExecution(o); try { return await runOpenClawAgentWorkerWrite(o, async () => { const e = selectCurrent(); s.identities = s.identities.filter((t, n) => e[n]); if (s.identities.length === 0) return; if (!l.capturePreparedGenerationClaim()) await l.prepare(c); return await l.runExisting({ ...c, createAdmission(e) { return withConversationPublication(c.createAdmission(e), () => e.assertCurrent(), () => ({ ...l.captureGenerationClaim(), canonicalPath: l.fileIdentity.nativeLocation }), () => [...new Set(s.identities.map((e) => JSON.stringify(["catalogue", e.conversationRef])))]); } }, (e) => e.execute({ type: "conversation.register", input: s })); }); } finally { await l.release(); } } /** Initiate under the writer grant; settle network work after releasing its transaction and FIFO. */ async function withConversationAuthority(e, t, n) { const r = captureSessionActorStorageOwner({ agentId: e.databaseAgentId ?? e.agentId, storePath: e.storePath, env: e.env }, conversationAuthority); if (r) { const e = r.binding && r.binding.agentId === r.agentId && r.binding.path === r.path ? r.binding : void 0; const i = { type: "session.conversation.authority", input: structuredClone(t) }; return await n(e ? e.actor.storage.readCurrent(i, r.authority) : r.owner?.readConversation(i, r.authority) ?? { operation: void 0, conversation: void 0 })(); } const { options: i } = pinConversationDatabaseScope(e); const a = captureOpenClawAgentDatabaseExecution(i); let o; try { try { await runOpenClawAgentWorkerWrite(i, async () => { const e = await a.runExisting({ assertCurrent() {}, createAdmission(e) { return () => ({ nativeLocations: e.nativeLocations, admission: createSqliteWorkerOperationAdmission((t, r) => { e.authorize(t); let consume; if (t.stage === "commit") { const e = isRecord(t.facts) && t.facts.publication; if (o || !isRecord(e) || e.kind !== "conversation-authority" || !isRecord(e.facts)) throw new Error("Conversation authority omitted its transaction facts"); const r = e.facts; const i = n(r); consume = () => { o = new Promise((e) => { e(i()); }).then((e) => ({ ok: true, value: e }), (e) => ({ ok: false, error: e })); }; } if (!r(consume)) throw new Error("Conversation read authority expired"); }, e.attachment) }); } }, (e) => e.execute({ type: "conversation.authority", input: t })); if (!o && e !== void 0) throw new Error("Conversation authority omitted its transaction grant"); }); } finally { await a.release(); } } catch (e) { if (!o) throw e; await o; const t = new SqliteWorkerError("Conversation authority settlement failed after dispatch initiation", "outcome-unknown"); t.cause = e; throw t; } if (!o) return await n({ operation: void 0, conversation: void 0 })(); const s = await o; if (!s.ok) throw s.error; return s.value; } /** Lists stable external addresses for one agent, newest activity first. */ function listConversations(e, t = {}) { return readConversationsAsync(e, t); } async function readConversation(e, t) { return (await readConversationsAsync(e, { conversationRef: t, limit: 1 }))[0]; } /** Reads only an authoritative association on an address's current session window. */ function resolveCurrentConversationSession(e, t, n) { const [r] = selectConversationRows(e, { conversationRef: t, currentBindingOnly: true, currentSession: n, limit: 1 }); return r?.sessionKey && r.sessionId ? { sessionKey: r.sessionKey, sessionId: r.sessionId } : void 0; } /** Reads an address's current binding through the existing session reader worker. */ async function resolveCurrentConversationSessionAsync(e, t) { const [n] = await readConversationsAsync(e, { conversationRef: t, currentBindingOnly: true, limit: 1 }); return n?.sessionKey && n.sessionId ? { sessionKey: n.sessionKey, sessionId: n.sessionId } : void 0; } /** Finds an unambiguous live owner using recorded delivery coordinates, never inferred peer kind. */ async function resolveCurrentConversationByDelivery(e, t) { const n = await readConversationsAsync(e, { channel: t.channel, deliveryAddress: t, currentBindingOnly: true }); const r = n[0]; if (n.some((e) => e.sessionKey !== r?.sessionKey || e.sessionId !== r?.sessionId || e.conversationRef !== r?.conversationRef)) return { ambiguous: true }; return { conversation: r }; } /** Reads only the primary address bound to this exact current session window. */ async function resolveCurrentSessionPrimaryConversation(e) { const [t] = await readConversationsAsync(e, { primarySession: { sessionId: e.sessionId, sessionKey: e.sessionKey } }); return t?.sessionId === e.sessionId && t.sessionKey === e.sessionKey ? t : void 0; } //#endregion export { readConversation as a, resolveCurrentConversationSession as c, withConversationAuthority as d, prepareConversationRegistryScope as i, resolveCurrentConversationSessionAsync as l, listConversations as n, registerConversationAddresses as o, pinConversationDatabaseScope as r, resolveCurrentConversationByDelivery as s, captureConversationBindingFacts as t, resolveCurrentSessionPrimaryConversation as u };