UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

702 lines (701 loc) • 28.9 kB
import { l as isRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { c as resolveOpenClawAgentSqlitePath } from "../../openclaw-agent-db.paths-DJxv80ws.mjs"; import { r as sqlPublicationAnchor } from "../../sql-connection-Beiyg5Dt.mjs"; import { m as readDatabasePathIdentitySync } from "../../sqlite-worker-identity-BH8ZkJU9.mjs"; import { G as withSqliteDatabaseWriteScope } from "../../sqlite-database-admission-DQIqro3d.mjs"; import { c as withSqlitePostCommitPublications, i as prepareSqliteTransactionCommit, s as stageSqliteTransactionState } from "../../sqlite-post-commit-BrUVQObC.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "../../kysely-sync-YJo2lmGV.mjs"; import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "../../openclaw-state-db-contract-DfPjvL0M.mjs"; import { c as runSqliteSingleStatementSync, l as runSqliteWorkerTransactionSync, t as assertTransactionUsable } from "../../sqlite-transaction-BHHu6P5-.mjs"; import { a as deferSqliteWorkerCommitReceipt } from "../../sqlite-worker-operation-settlement-OZQM-wtd.mjs"; import "../../sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { m as withExistingOpenClawStateDatabaseReadOnly } from "../../openclaw-state-db-readonly-B6YHb1oF.mjs"; import { a as readOpenClawAgentDatabaseIdentity } from "../../openclaw-agent-db-identity-C8MGU8lp.mjs"; import { t as captureSessionRowChanges } from "../../session-row-changes-BA4BqVwF.mjs"; import { t as createSqliteCommitReceipt } from "../../sqlite-commit-receipt-LVED9ktS.mjs"; import { n as getOpenClawAgentDatabaseIfOpen } from "../../openclaw-agent-db-borrower-BrziJlyo.mjs"; import { d as deferOpenClawAgentPostCommitPublication } from "../../openclaw-agent-db-lifecycle-DqaZZnYh.mjs"; import { g as ensureSessionParticipantsSchema } from "../../openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs"; import { s as runOpenClawAgentWriteTransaction } from "../../openclaw-agent-db-CwXW4hGa.mjs"; import "../../user-profile-list-D7DDbqt5.mjs"; import { t as MAX_SESSION_PARTICIPANTS } from "../../session-entry-provenance-01l9mXT0.mjs"; import { n as emitSessionLifecycleEvent } from "../../session-lifecycle-events-DWKmeEvQ.mjs"; import { t as isInternalSessionEffectsKey } from "../../internal-session-key-DySyL5iT.mjs"; import { i as toDatabaseOptions, t as getSessionKysely } from "../../session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import { o as resolveSqliteScope } from "../../session-accessor.sqlite-read-scope-7Z2ARJnl.mjs"; import "../../session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import { r as assertCanonicalSqliteSessionKeysCurrent } from "../../session-canonical-key-q6kSkP3K.mjs"; import { n as parseSessionEntryJson, r as selectSessionEntryRows } from "../../session-accessor.sqlite-status-CVbyujpN.mjs"; import { r as sessionEntryCaches } from "../../session-accessor.sqlite-entry-cache-state-ChUHgtCJ.mjs"; import { D as readSqliteSessionParticipantProjection, M as readSessionActorParticipants, i as prepareExactSessionEntryRowReads, j as prepareSessionActorParticipantUpdate, o as readExactSessionEntryRow, v as validateDeliveryCanonicalSessionEntry } from "../../session-accessor.sqlite-entry-read-csOyyi3K.mjs"; import { n as participantIdentityNamespace, r as readParticipantIdentity, t as mergeParticipantAggregate } from "../../session-participant-identity-DU0KZOpY.mjs"; import { i as publishSessionEntryCacheParticipantUpdate, t as prepareSessionEntryCacheWrite } from "../../session-accessor.sqlite-entry-cache-l5776yJA.mjs"; import { p as publishSessionSharingMemberChange } from "../../communication-admission-SSbnAHIW.mjs"; import { t as SESSION_SUGGESTION_DISPATCH_CLAIM_TTL_MS } from "../../session-suggestion-policy-D8gImch7.mjs"; import { r as SessionWorkStartInvalidatedError } from "../../work-start-error-DaHE71YG.mjs"; import { c as writeSessionEntry } from "../../session-accessor.sqlite-entry-store-DmqxH0lm.mjs"; import { r as sessionMetadataExpectedEntryMatches, t as assignSessionOwner } from "../../session-accessor.sqlite-owner-BfpcingM.mjs"; import { n as mergeSessionProfileInvolvement, t as isNewerSessionMention } from "../../session-involvement-YG_J8kQp.mjs"; import { t as bindSqliteWorkerDatabase } from "../../sqlite-worker-binding-B4BB5u5i.mjs"; import { r as readUserProfileAliasesNative } from "../../user-profile-list.native-CZgRgV7X.mjs"; import { n as captureSessionEntryMetadataReceipts, t as boundSessionEntryMetadataReceipts } from "../../session-entry-metadata-receipt-C4aflF45.mjs"; import { n as readSessionGroupCatalogEntry } from "../../session-group-catalog.kernel-C-ERPwN3.mjs"; import { t as readSessionEntryInstanceId } from "../../session-accessor.sqlite-entry-identity-CU_RaeRK.mjs"; import { t as getSessionMemberKysely } from "../../session-sharing-store.kernel-BH4li9nE.mjs"; import { t as engineUnboundedRowLimit } from "../../row-limit-DxcIDYaA.mjs"; import { randomUUID } from "node:crypto"; import { isDeepStrictEqual, toUSVString } from "node:util"; //#region src/config/sessions/session-accessor.sqlite-involvement.worker.ts /** One logical-node owner for explicit personal choices and committed mentions. */ function updatePreparedSessionProfileInvolvement(e, t, n) { const r = resolveSqliteScope(e); return runOpenClawAgentWriteTransaction((e) => { t.assertCurrent?.(); const i = readExactSessionEntryRow(e, r.sessionKey)?.entry; if (!i || i.sessionId !== t.expectedSessionId || i.incognito) return { accepted: false, changed: false }; if (t.expectedEntry && !sessionMetadataExpectedEntryMatches(e, r.sessionKey, t.expectedEntry)) return { accepted: false, changed: false }; const a = { ...i.profileInvolvement?.profiles }; let o = false; for (const { profileId: e, aliases: r } of n) { const n = mergeSessionProfileInvolvement([...r].map((e) => a[e])); const i = n?.lastMention; const s = t.change; if (s.kind === "mention" && i && !isNewerSessionMention(s.source, i)) continue; const c = s.kind === "visibility" && s.hidden; if (s.kind === "visibility" && n?.hidden === c) continue; for (const e of r) delete a[e]; a[e] = { hidden: c, updatedAt: Math.max(Date.now(), (n?.updatedAt ?? 0) + 1), ...s.kind === "mention" ? { lastMention: s.source } : i ? { lastMention: i } : {} }; o = true; } if (o) { writeSessionEntry(e, r.sessionKey, i, { canonicalPreviousEntry: i, profileInvolvement: { key: r.sessionKey, profiles: a } }); deferOpenClawAgentPostCommitPublication(e, () => emitSessionLifecycleEvent({ agentId: r.agentId, sessionKey: r.sessionKey, reason: "involvement" })); } return { accepted: true, changed: o }; }, toDatabaseOptions(r), { operationLabel: "sessions.involvement" }); } //#endregion //#region src/config/sessions/session-accessor.sqlite-participants.native.ts /** The sharing worker already holds its agent transaction when resolving profile aliases. */ function recordSessionParticipantFromWorker(e, t, n) { return recordSessionParticipantWithAliasRead(t, n, () => readUserProfileAliasesNative(n.identity.id, { env: t.env }), e); } function recordSessionParticipantWithAliasRead(e, t, n, r) { const i = t.identity.id; if (!i || t.identity.type === "agent" && i === t.sessionAgentId) return { value: null, projectionChanged: false }; const a = resolveSqliteScope(e); const o = toDatabaseOptions(a); const s = t.promptedAt ?? Date.now(); const c = participantIdentityNamespace(t.identity); const write = (e) => { ensureSessionParticipantsSchema(e.db); const r = getSessionKysely(e.db); const o = readSessionActorParticipants(e, a.sessionKey); const l = prepareSessionActorParticipantUpdate(e, a.sessionKey); const u = o?.map((e) => ({ actor_id: e.identity.id, identity_namespace: participantIdentityNamespace(e.identity), contribution_count: e.contributionCount, first_prompted_at: e.firstPromptedAt, last_prompted_at: e.lastPromptedAt })); const d = r.selectFrom("session_participants").select([ "actor_id", "contribution_count", "first_prompted_at", "last_prompted_at" ]).where("session_key", "=", a.sessionKey).where("identity_namespace", "=", c); const f = u ? u.find((e) => e.actor_id === i && e.identity_namespace === c) : executeSqliteQueryTakeFirstSync(e.db, d.where("actor_id", "=", i)); let p = f?.actor_id === i ? f : void 0; if (!p && t.identity.type === "profile") { const t = n(); if (t && t.size > 1) p = (u ? u.filter((e) => e.identity_namespace === c).toSorted((e, t) => Buffer.compare(Buffer.from(e.actor_id), Buffer.from(t.actor_id))) : executeSqliteQuerySync(e.db, d.orderBy("actor_id")).rows).find((e) => t.has(e.actor_id)); } if (!p && o && o.length >= MAX_SESSION_PARTICIPANTS) return { value: "capped", projectionChanged: false }; const m = mergeParticipantAggregate(p, { contribution_count: 1, first_prompted_at: s, last_prompted_at: s }, "sum"); let h = r.selectNoFrom((e) => [ e.val(a.sessionKey).as("session_key"), e.val(c).as("identity_namespace"), e.val(p?.actor_id ?? i).as("actor_id"), e.val(m.contribution_count).as("contribution_count"), e.val(m.first_prompted_at).as("first_prompted_at"), e.val(m.last_prompted_at).as("last_prompted_at") ]); if (!p && !o) h = h.where((e) => e(e.selectFrom("session_participants").select((e) => e.fn.countAll().as("count")).where("session_key", "=", a.sessionKey), "<", MAX_SESSION_PARTICIPANTS)); const g = prepareSessionEntryCacheWrite(e); if (withSqliteDatabaseWriteScope(e.db, [a.sessionKey], () => executeSqliteQuerySync(e.db, r.insertInto("session_participants").columns([ "session_key", "identity_namespace", "actor_id", "contribution_count", "first_prompted_at", "last_prompted_at" ]).expression(h).onConflict((e) => e.columns([ "session_key", "identity_namespace", "actor_id" ]).doUpdateSet(m)))).numAffectedRows === 0n) return { value: "capped", projectionChanged: false }; const _ = g(); const v = !p || p.actor_id !== i || m.first_prompted_at !== p.first_prompted_at; if (o && l) { const e = readParticipantIdentity(c, p?.actor_id ?? i.toWellFormed()); l.publish([...o.filter((t) => t.identity.id !== e.id || participantIdentityNamespace(t.identity) !== c), { identity: e, contributionCount: m.contribution_count, firstPromptedAt: m.first_prompted_at, lastPromptedAt: m.last_prompted_at }]); } publishSessionEntryCacheParticipantUpdate(e, a.sessionKey, { writeGeneration: _, projectionChanged: v }); deferOpenClawAgentPostCommitPublication(e, () => emitSessionLifecycleEvent({ agentId: a.agentId, sessionKey: a.sessionKey, reason: "participants", scope: "session-entry" })); return { value: p ? "updated" : "inserted", projectionChanged: v }; }; if (r) { assertTransactionUsable(r.db); return write(r); } return runOpenClawAgentWriteTransaction(write, o, { operationLabel: "sessions.record-participant" }); } //#endregion //#region src/config/sessions/session-group-categories.kernel.ts const MIN_BATCHED_CATEGORY_KEYS = 10; function applySessionGroupCategoryMutation(e, t, n, r, i) { const a = /* @__PURE__ */ new Map(); const o = t.length >= MIN_BATCHED_CATEGORY_KEYS ? prepareExactSessionEntryRowReads(e, t) : void 0; for (const r of t) { const t = o ? o(r) : readExactSessionEntryRow(e, r); if (t?.entry.category?.trim() === n) a.set(r, t); } assertSessionGroupCategoryDestination(r, i); for (const [t, n] of a) { const i = { ...n.entry }; if (r === void 0) delete i.category; else i.category = r; writeSessionEntry(e, t, i, { canonicalPreviousEntry: n.entry, previousEntry: n.entry }); } return [...a].map(([e, { entry: t }]) => ({ sessionKey: e, sessionId: t.sessionId })); } function assertSessionGroupCategoryDestination(e, t) { if (e !== void 0 && !withExistingOpenClawStateDatabaseReadOnly(({ db: t }) => readSessionGroupCatalogEntry(t, e), { env: t })) throw new Error(`unknown session group: ${e}`); } //#endregion //#region src/config/sessions/session-group-categories.read.ts function readSessionGroupCategoryKeys(e, t) { assertCanonicalSqliteSessionKeysCurrent(e); return executeSqliteQuerySync(e.db, selectSessionEntryRows(e, "list").orderBy("session_key")).rows.flatMap((e) => { if (isInternalSessionEffectsKey(e.session_key)) return []; const n = parseSessionEntryJson(e, "list"); if (!n) return []; validateDeliveryCanonicalSessionEntry(e.session_key, n); return n.category?.trim() === t ? [e.session_key] : []; }); } //#endregion //#region src/config/sessions/session-participant-contribution.worker.ts /** A resident contribution changes one row; aliases, new participants and reordering keep the transaction. */ function prepareSessionParticipantContribution(e, t, n) { const r = resolveSqliteScope(t); const i = readSessionActorParticipants(e, r.sessionKey); const a = participantIdentityNamespace(n.identity); const o = i?.find((e) => e.identity.id === n.identity.id && participantIdentityNamespace(e.identity) === a); if (!i || !o || n.identity.type === "agent" && n.identity.id === n.sessionAgentId) return; const s = n.promptedAt ?? Date.now(); const c = mergeParticipantAggregate({ contribution_count: o.contributionCount, first_prompted_at: o.firstPromptedAt, last_prompted_at: o.lastPromptedAt }, { contribution_count: 1, first_prompted_at: s, last_prompted_at: s }, "sum"); if (c.first_prompted_at !== o.firstPromptedAt) return; const l = prepareSessionActorParticipantUpdate(e, r.sessionKey, true); if (!l) return; const u = i.map((e) => e === o ? { identity: e.identity, contributionCount: c.contribution_count, firstPromptedAt: c.first_prompted_at, lastPromptedAt: c.last_prompted_at } : e); const d = getSessionKysely(e.db).insertInto("session_participants").values({ session_key: r.sessionKey, identity_namespace: a, actor_id: o.identity.id, ...c }).onConflict((e) => e.columns([ "session_key", "identity_namespace", "actor_id" ]).doUpdateSet(c)); const f = prepareSessionEntryCacheWrite(e); return { result: { value: "updated", projectionChanged: false, participants: {}, records: u, actorVersion: l.version }, stage() { l.publish(u); stageSqliteTransactionState(e.db, { commit() { publishSessionEntryCacheParticipantUpdate(e, r.sessionKey, { writeGeneration: f(), projectionChanged: false }); }, invalidate: () => sessionEntryCaches.delete(e.db) }); deferOpenClawAgentPostCommitPublication(e, () => emitSessionLifecycleEvent({ agentId: r.agentId, sessionKey: r.sessionKey, reason: "participants", scope: "session-entry" })); }, statement: () => withSqliteDatabaseWriteScope(e.db, [r.sessionKey], () => executeSqliteQuerySync(e.db, d)) }; } //#endregion //#region src/config/sessions/session-sharing-store.native.ts function assertAuthorizedSessionInstance(e, t, n, r) { const i = r ? readExactSessionEntryRow(e, t, "list")?.entry : void 0; const a = r ? i?.sessionId : readSessionEntryInstanceId(e, t); if (a === void 0 || n !== void 0 && a !== n) throw new Error("session changed before sharing mutation"); if (r) { if (!i || !isDeepStrictEqual({ sessionId: i.sessionId, createdActor: i.createdActor, visibility: i.visibility, incognito: i.incognito }, r)) throw new Error("session ownership changed before sharing mutation"); } return a; } function publishCommittedSessionMembership(e, t, n, r, i, a) { publishSessionSharingMemberChange(e, n, { kind: "member", sessionId: r, identityId: toUSVString(i), present: a }, t); } function addSessionMember(e, t) { const n = t.identityId.trim(); const r = t.addedBy.trim(); if (!n || !r) throw new Error("session member identity and actor are required"); const i = resolveSqliteScope(e); const { agentId: a, sessionKey: o } = i; const s = t.addedAt ?? Date.now(); const c = runOpenClawAgentWriteTransaction((e) => { const i = assertAuthorizedSessionInstance(e, o, t.expectedSessionId, t.expectedEntry); const c = getSessionMemberKysely(e); const l = (withSqliteDatabaseWriteScope(e.db, [o], () => executeSqliteQuerySync(e.db, c.insertInto("session_members").values({ session_key: o, identity_id: n, added_by: r, added_at: s }).onConflict((e) => e.columns(["session_key", "identity_id"]).doNothing()))).numAffectedRows ?? 0n) > 0n; if (l) publishCommittedSessionMembership(e, a, o, i, n, true); return l; }, toDatabaseOptions(i), { operationLabel: "session.sharing.add-member" }); return { member: { identityId: n, addedBy: r, addedAt: s }, inserted: c }; } function removeSessionMember(e, t, n, r, i) { const a = t.trim(); if (!a) return null; const o = resolveSqliteScope(e); const { agentId: s, sessionKey: c } = o; return runOpenClawAgentWriteTransaction((e) => { const t = assertAuthorizedSessionInstance(e, c, r, i); const o = getSessionMemberKysely(e); if (n && n.addedBy !== toUSVString(n.addedBy)) return null; let l = o.deleteFrom("session_members").where("session_key", "=", c).where("identity_id", "=", a); if (n) l = l.where("added_by", "=", n.addedBy).where("added_at", "=", n.addedAt); const u = withSqliteDatabaseWriteScope(e.db, [c], () => executeSqliteQueryTakeFirstSync(e.db, l.returning([ "identity_id", "added_by", "added_at" ]))); if (!u) return null; publishCommittedSessionMembership(e, s, c, t, a, false); return { identityId: u.identity_id, addedBy: u.added_by, addedAt: u.added_at }; }, toDatabaseOptions(o), { operationLabel: "session.sharing.remove-member" }); } //#endregion //#region src/config/sessions/session-suggestion-store.kernel.ts function suggestionDb(e) { return getNodeSqliteKysely(e.db); } function toSuggestion(e) { return { id: e.id, authorId: e.author_id, ...e.author_label ? { authorLabel: e.author_label } : {}, text: e.text, createdAt: e.created_at, state: e.state }; } function assertSessionTarget(e, t, n) { if (n.expectedEntry) { if (n.expectedSessionId !== void 0 && n.expectedSessionId !== n.expectedEntry.sessionId || !sessionMetadataExpectedEntryMatches(e, t, n.expectedEntry)) throw new SessionWorkStartInvalidatedError("session changed before suggestion mutation"); return; } if (n.expectedSessionId !== void 0 && readSessionEntryInstanceId(e, t) !== n.expectedSessionId) throw new SessionWorkStartInvalidatedError("session changed before suggestion mutation"); } function pruneResolvedSessionSuggestions(e, t) { const n = suggestionDb(e); executeSqliteQuerySync(e.db, n.deleteFrom("session_suggestions").where("id", "in", n.selectFrom("session_suggestions").select("id").where("session_key", "=", t).where("state", "!=", "pending").orderBy("created_at", "desc").orderBy("id", "desc").limit(engineUnboundedRowLimit(e.db)).offset((e) => e.lit(200)))); } function addSessionSuggestionInDatabase(e, t, n) { const r = n.authorId.trim(); const i = n.authorLabel?.trim() || void 0; const a = n.text; if (!r || !a.trim()) throw new Error("suggestion author and text are required"); const o = { id: n.id ?? randomUUID(), authorId: r, ...i ? { authorLabel: i } : {}, text: a, createdAt: n.createdAt ?? Date.now(), state: "pending" }; assertSessionTarget(e, t, n); const s = suggestionDb(e); pruneResolvedSessionSuggestions(e, t); const c = executeSqliteQuerySync(e.db, s.selectFrom("session_suggestions").select((e) => ["author_id", e.fn.countAll().as("count")]).where("session_key", "=", t).where("state", "=", "pending").groupBy("author_id")).rows.reduce((e, t) => ({ session: e.session + t.count, author: e.author + (t.author_id === o.authorId ? t.count : 0) }), { session: 0, author: 0 }); if (c.session >= 100) throw new Error("session pending suggestion limit reached"); if (c.author >= 20) throw new Error("author pending suggestion limit reached"); executeSqliteQuerySync(e.db, s.insertInto("session_suggestions").values({ id: o.id, session_key: t, author_id: o.authorId, author_label: o.authorLabel ?? null, text: o.text, created_at: o.createdAt, state: o.state, dispatch_token: null, dispatch_started_at: null, dispatch_resolution: null })); return o; } function claimSessionSuggestionDispatchInDatabase(e, t, n) { assertSessionTarget(e, t, n); const r = suggestionDb(e); const i = executeSqliteQueryTakeFirstSync(e.db, r.selectFrom("session_suggestions").select([ "id", "author_id", "author_label", "text", "created_at", "state", "dispatch_token", "dispatch_started_at", "dispatch_resolution" ]).where("session_key", "=", t).where("id", "=", n.id).where("state", "=", "pending")); if (!i) return null; const a = n.now ?? Date.now(); if (i.dispatch_token && i.dispatch_started_at !== null && a - i.dispatch_started_at < 3e4) return { kind: "busy" }; if (i.dispatch_resolution && i.dispatch_resolution !== n.resolution) return { kind: "mismatch", resolution: i.dispatch_resolution }; const o = randomUUID(); executeSqliteQuerySync(e.db, r.updateTable("session_suggestions").set({ dispatch_token: o, dispatch_started_at: a, dispatch_resolution: n.resolution }).where("session_key", "=", t).where("id", "=", n.id).where("state", "=", "pending")); return { kind: "claimed", suggestion: toSuggestion(i), token: o }; } function releaseSessionSuggestionDispatchInDatabase(e, t, n) { assertSessionTarget(e, t, n); return (executeSqliteQuerySync(e.db, suggestionDb(e).updateTable("session_suggestions").set({ dispatch_token: null, dispatch_started_at: null, dispatch_resolution: null }).where("session_key", "=", t).where("id", "=", n.id).where("state", "=", "pending").where("dispatch_token", "=", n.token)).numAffectedRows ?? 0n) > 0n; } function finalizeSessionSuggestionClaimInDatabase(e, t, n) { assertSessionTarget(e, t, n); const r = suggestionDb(e); const i = executeSqliteQueryTakeFirstSync(e.db, r.updateTable("session_suggestions").set({ state: n.state, dispatch_token: null, dispatch_started_at: null, dispatch_resolution: null }).where("session_key", "=", t).where("id", "=", n.id).where("state", "=", "pending").where("dispatch_token", "=", n.token).returning([ "id", "author_id", "author_label", "text", "created_at", "state" ])); if (!i) return null; pruneResolvedSessionSuggestions(e, t); return toSuggestion(i); } //#endregion //#region src/config/sessions/session-sharing-store.worker.ts /** The canonical agent executor retains the connection and both live admission checks. */ function bindSqliteWorkerBackend(e, t) { const n = t.database; const r = readOpenClawAgentDatabaseIdentity({ db: n }); let i; const workerDatabase = (e) => { const r = getOpenClawAgentDatabaseIfOpen(toDatabaseOptions(resolveSqliteScope(e))); if (!r || r.db !== n || r.path !== t.databasePath) throw new Error("Session collaboration write lost its physical store owner"); return r; }; return bindSqliteWorkerDatabase(n, { execute(e) { const a = { ...e.input.scope }; const o = resolveOpenClawAgentSqlitePath(toDatabaseOptions(resolveSqliteScope(a))); if (!(sqlPublicationAnchor(n).location() ? readDatabasePathIdentitySync(o).canonicalPath === t.databasePath : o === t.databasePath && getOpenClawAgentDatabaseIfOpen(toDatabaseOptions(resolveSqliteScope(a)))?.db === n)) throw new Error("Session collaboration target changed its database owner"); a.storePath = t.databasePath; if (e.type === "category.prepare") { const t = workerDatabase(a); i = { from: e.input.from, storePath: t.path, keys: readSessionGroupCategoryKeys(t, e.input.from) }; return i.keys; } if (e.type === "participant" && typeof r.identity === "string") { const i = prepareSessionParticipantContribution(workerDatabase(a), a, e.input.params); if (i) { const o = { kind: "session-collaboration-committed", type: e.type, result: i.result, publication: createSqliteCommitReceipt({ source: r, domain: "session-collaboration", keys: [a.sessionKey], readFact: () => ({ kind: "unchanged" }) }) }; t.admit("transaction"); t.admit("commit", (e, t) => { if (!isRecord(e.facts)) throw new Error("Session collaboration commit omitted its facts"); t({ ...e, facts: { ...e.facts, publication: o } }); }); return runSqliteSingleStatementSync(n, () => { i.stage(); deferSqliteWorkerCommitReceipt(n, o); prepareSqliteTransactionCommit(sqlPublicationAnchor(n)); i.statement(); return i.result; }); } } let s; let c = [a.sessionKey]; let l; let u; let d; return withSqlitePostCommitPublications(sqlPublicationAnchor(n), () => runSqliteWorkerTransactionSync({ ...t, admit(e) { t.admit(e, e === "commit" && typeof r.identity === "string" ? (e, t) => { if (!s || !isRecord(e.facts)) throw new Error("Session collaboration commit omitted its candidate"); t({ ...e, facts: { ...e.facts, publication: s } }); } : void 0); } }, () => { const t = captureSessionRowChanges(n, () => { if (e.type === "involvement") return updatePreparedSessionProfileInvolvement(a, e.input.params, e.input.profiles); if (e.type === "owner.assign") { d = { value: assignSessionOwner(a, e.input.params) }; return d; } if (e.type === "suggestion.add") { const t = workerDatabase(a); return addSessionSuggestionInDatabase(t, a.sessionKey, e.input.params); } if (e.type === "suggestion.claim") { const t = workerDatabase(a); return claimSessionSuggestionDispatchInDatabase(t, a.sessionKey, e.input.params); } if (e.type === "suggestion.release") { const t = workerDatabase(a); return releaseSessionSuggestionDispatchInDatabase(t, a.sessionKey, e.input.params); } if (e.type === "suggestion.finalize") { const t = workerDatabase(a); return finalizeSessionSuggestionClaimInDatabase(t, a.sessionKey, e.input.params); } if (e.type === "category.apply") { const t = workerDatabase(a); if (!i || i.from !== e.input.from || i.storePath !== t.path) throw new Error("Session group category mutation has no matching prepared rows"); c = i.keys; return applySessionGroupCategoryMutation(t, i.keys, e.input.from, e.input.to, a.env ?? process.env); } if (e.type === "participant") { const t = recordSessionParticipantFromWorker(workerDatabase(a), a, e.input.params); l = { ...t, participants: t.projectionChanged ? readSqliteSessionParticipantProjection(n, a.sessionKey) : {} }; return l; } if (e.type === "add") { const t = { value: addSessionMember(a, e.input.params) }; u = t; return t; } const t = { value: removeSessionMember(a, e.input.identityId, e.input.expected, e.input.expectedSessionId, e.input.expectedEntry) }; u = t; return t; }); const o = /* @__PURE__ */ new Map(); const recordFact = (e, t) => { const n = o.get(e) ?? []; n.push(t); o.set(e, n); }; for (const n of t.changes) { if (!("sessionKey" in n) || !n.facts) continue; const t = n.facts; if (u && t.kind === "member") { u.facts = t; recordFact(n.sessionKey, t); } else if (d && t.kind === "owner") { d.facts = t; recordFact(n.sessionKey, t); } else if (l?.projectionChanged && t.kind === "participants") recordFact(n.sessionKey, { ...t, projection: l.participants }); else if (e.type === "category.apply" && t.kind === "entry") recordFact(n.sessionKey, { kind: "category", sessionId: t.sessionId, category: t.category }); else if (e.type === "involvement" && t.kind === "entry") recordFact(n.sessionKey, { kind: "unchanged" }); } if (typeof r.identity === "string") { const i = createSqliteCommitReceipt({ source: r, domain: "session-collaboration", keys: c, readFact: (e) => { const t = o.get(e); return t && t.length > 0 ? { kind: "postimage", value: t } : { kind: "unchanged" }; } }); const a = e.type === "involvement" ? captureSessionEntryMetadataReceipts(t.changes) : void 0; s = { kind: "session-collaboration-committed", type: e.type, result: t.result, publication: i, ...a ? { entryMetadata: a } : {} }; if (a) boundSessionEntryMetadataReceipts(a, s); deferSqliteWorkerCommitReceipt(n, s); } return t.result; }, { operationLabel: `sessions.${e.type}`, busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, databaseLabel: t.databasePath })); } }); } //#endregion export { bindSqliteWorkerBackend };