openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
8 lines • 16.4 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{n as groupPluginRecords}from"./record-groups-BlmybP6F.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{i as normalizeMainKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,t as DEFAULT_AGENT_ID}from"./session-key-BPgKfU2m.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{n as createOpenClawAgentDatabasePathMatcher,o as isSameOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import"./agent-scope-config-CG9CFpGX.mjs";import{n as withOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-BQsAKuqV.mjs";import{i as openOpenClawAgentDatabase}from"./openclaw-agent-db-BUym2U31.mjs";import{l as preserveCreationStamp}from"./session-entry-provenance-DZd--atF.mjs";import{r as resolveAgentMainSessionKey}from"./main-session-C6FGqx0x.mjs";import{o as resolveDeliveryProvenCanonicalSessionKey}from"./store-entry-DbH6jRLn.mjs";import{i as resolveSqliteTranscriptArchiveDirectory}from"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{l as readStoredCanonicalSessionMainKey,p as setCanonicalSqliteSessionMainKey}from"./session-canonical-key-TC8_HgaF.mjs";import{x as withSessionTranscriptHydrationCaller}from"./session-transcript-worker-resources-BCJ3nyGg.mjs";import{a as resolveAllAgentSessionStoreTargetsSync}from"./targets-DZpbOEi4.mjs";import{s as writeTranscriptArchive}from"./session-accessor.sqlite-archive-artifact-nwgWozne.mjs";import{_ as loadCanonicalSessionRepairEntries,g as listCanonicalSessionRepairFacts}from"./session-accessor-CY8UYP4m.mjs";import{n as collectSessionStateIdsForEntry}from"./session-accessor.sqlite-references-B7aXsOVx.mjs";import{_ as deleteSessionMembersForRepair,h as copySessionNodeArtifactsForRepair}from"./session-accessor.sqlite-entry-store-Cxqr6m6F.mjs";import{i as resolveSessionStoreAgentId,s as resolveStoredSessionKeyForAgentStore}from"./session-store-key-DZXBwthg.mjs";import{d as listSqliteSessionGenerationIdsForCanonicalRepair,f as rehomeSqliteSessionDeliveryReferencesForCanonicalRepair,l as copySqliteSessionOwnedStateForCanonicalRepair,p as rehomeSqliteSessionDeliveryReferencesForCanonicalRepairBatch,u as ensureSqliteTranscriptGenerationsForCanonicalRepair}from"./session-accessor.entry-B1qUJ4E1.mjs";import{n as replaceSessionOwnerInTransaction}from"./session-accessor.sqlite-owner-BoYuTFnh.mjs";import{g as applySessionEntryLifecycleMutation}from"./session-accessor.entry-mutation-CQIwywNM.mjs";import{t as loadSessionTranscriptEvents}from"./session-transcript-events-C7eeuw86.mjs";import{d as resolveTargetSqliteOptions,f as resolveTargetSqlitePath,i as projectExistingAgentDatabaseTargets}from"./session-sqlite-migration-readers-Cc_cphZg.mjs";
//!src/config/sessions/transcript-jsonl.ts
function serializeJsonlLines(e){return e.length>0?`${e.join(`
`)}\n`:``}
//!src/commands/doctor-session-canonical-candidates.ts
function collectCanonicalSessionCandidateFacts(e,t){const n=!listAgentIds(e.cfg).includes(DEFAULT_AGENT_ID);const r=normalizeMainKey(e.cfg.session?.mainKey);const resolveStoredKey=(t,i)=>{const a=parseAgentSessionKey(i);const o=normalizeLowercaseStringOrEmpty(a?.rest);const s=n&&a?.agentId===`main`&&normalizeAgentId(t)!==`main`&&(o===`main`||o===r);return resolveStoredSessionKeyForAgentStore({cfg:e.cfg,agentId:t,sessionKey:i,preserveQualifiedAddress:!s})};const i=t.flatMap(t=>listCanonicalSessionRepairFacts({agentId:t.agentId,storePath:t.storePath}).map(n=>{const{canonicalOwnerSessionKey:r,sessionKey:i}=n;const a=resolveStoredKey(t.agentId,i);return{canonicalKey:a?resolveDeliveryProvenCanonicalSessionKey(a,n):resolveAgentMainSessionKey({cfg:e.cfg,agentId:t.agentId}),canonicalOwnerSessionKey:r,inventoryFact:n,sessionKey:i,storedKey:a,target:t}}));const a=new Map(i.map(e=>[`${e.target.sqlitePath}\0${e.sessionKey}`,e]));const o=/* @__PURE__ */ new Map;const resolveCanonicalKey=e=>{const t=/* @__PURE__ */ new Set;let n=e;let r;for(;;){const e=o.get(n);if(e!==void 0){r=e;break}if(t.has(n))return n.canonicalKey;t.add(n);const i=n.canonicalOwnerSessionKey?a.get(`${n.target.sqlitePath}\0${n.canonicalOwnerSessionKey}`):void 0;if(!i){r=n.canonicalKey;break}n=i}for(const e of t)o.set(e,r);return r};const s=/* @__PURE__ */ new Map;for(const e of i){e.canonicalKey=resolveCanonicalKey(e);const t=parseAgentSessionKey(e.storedKey)?.agentId??e.target.agentId;for(const n of[e.sessionKey,e.storedKey])for(const r of[e.target.sqlitePath,`*`]){const i=`${r}\0${t}\0${n}`;const a=s.get(i)??/* @__PURE__ */ new Set;a.add(e.canonicalKey);s.set(i,a)}}return i.map(({canonicalKey:t,canonicalOwnerSessionKey:n,inventoryFact:r,sessionKey:i,target:a})=>{const o=t===`global`||t===`unknown`?a.agentId:resolveSessionStoreAgentId(e.cfg,t);const canonicalizeLineageKey=e=>{if(!e)return;const t=resolveStoredKey(o,e);const n=parseAgentSessionKey(t)?.agentId??o;for(const r of[a.sqlitePath,`*`])for(const i of[e,t]){const e=s.get(`${r}\0${n}\0${i}`);if(e?.size===1)return[...e][0]}return t};const c=canonicalizeLineageKey(r.parentSessionKey);const l=canonicalizeLineageKey(r.spawnedBy);const u=canonicalizeLineageKey(r.forkSourceSessionKey);return Object.assign({agentId:a.agentId,canonicalKey:t,inventoryFact:r,lineageRepairRequired:c!==r.parentSessionKey||l!==r.spawnedBy||u!==r.forkSourceSessionKey,ownerEvidenceOnly:n!==void 0,sessionKey:i,sqlitePath:a.sqlitePath,storePath:a.storePath},u?{normalizedForkSourceSessionKey:u}:{},c?{normalizedParentSessionKey:c}:{},l?{normalizedSpawnedBy:l}:{})})}function resolveCanonicalSessionDestination(e){const t=e.canonicalKey===`global`||e.canonicalKey===`unknown`?normalizeAgentId(e.sourceAgentId??resolveSessionStoreAgentId(e.cfg,e.canonicalKey)):resolveSessionStoreAgentId(e.cfg,e.canonicalKey);const n=resolveSessionStorePathCore(e.cfg.session?.store,{agentId:t,env:e.env});return{agentId:t,storePath:n,sqlitePath:resolveTargetSqlitePath({agentId:t,storePath:n})}}function collectCanonicalSessionRepairGroups(e,t){const n=collectCanonicalSessionCandidateFacts(e,t);const r=createOpenClawAgentDatabasePathMatcher();return[...groupPluginRecords(n,e=>{const t=e.canonicalKey===`global`||e.canonicalKey===`unknown`?e.agentId:``;return`${e.canonicalKey}\0${t}`}).values()].flatMap(t=>{const n=t[0];const i=resolveCanonicalSessionDestination({canonicalKey:n.canonicalKey,cfg:e.cfg,env:e.env,sourceAgentId:n.agentId});if(!(t.length>1||t.some(e=>e.inventoryFact.rawCompareRequired||e.lineageRepairRequired||e.sessionKey!==e.canonicalKey||!r(e.sqlitePath,i.sqlitePath))))return[];const a=t.some(e=>r(e.sqlitePath,i.sqlitePath)&&e.sessionKey===e.canonicalKey);return[{candidates:t,removedRows:t.length-(a?1:0)}]})}
//!src/commands/doctor-session-canonical-keys.ts
function createCanonicalRepairRemoval(e,t){const n={archiveRemovedTranscript:t.archiveRemovedTranscript,deleteOwnedWindows:t.deleteOwnedWindows,...t.deliveryCleanupKeys?{deliveryCleanupKeys:t.deliveryCleanupKeys}:{},exactStoredKey:true,expectedEntry:e.expectedEntry,sessionKey:e.sessionKey};return e.rawEntryJson===void 0?n:Object.assign(n,{expectedRawEntryJson:e.rawEntryJson,expectedSnapshotRevision:e.rawSnapshotRevision})}const CANONICAL_SESSION_REPAIR_BATCH_GROUP_LIMIT=64;function hydrateCanonicalSessionCandidate(e,t){const n={...t.entry};if(e.normalizedParentSessionKey)n.parentSessionKey=e.normalizedParentSessionKey;else delete n.parentSessionKey;if(e.normalizedSpawnedBy)n.spawnedBy=e.normalizedSpawnedBy;else delete n.spawnedBy;if(n.forkSource&&e.normalizedForkSourceSessionKey)n.forkSource={...n.forkSource,sessionKey:e.normalizedForkSourceSessionKey};else if(n.forkSource?.sessionKey!==void 0){const{sessionKey:e,...t}=n.forkSource;n.forkSource=t}const r={agentId:e.agentId,canonicalKey:e.canonicalKey,entry:n,expectedEntry:t.entry,ownerEvidenceOnly:e.ownerEvidenceOnly,sessionKey:e.sessionKey,sqlitePath:e.sqlitePath,storePath:e.storePath};return t.rawEntryJson!==void 0?{...r,rawEntryJson:t.rawEntryJson,rawSnapshotRevision:t.rawSnapshotRevision}:r}function hydrateCanonicalSessionCandidates(e){const t=/* @__PURE__ */ new Map;const n=groupPluginRecords(e,e=>`${e.agentId}\0${e.storePath}`);for(const e of n.values()){const n=e[0];const r=loadCanonicalSessionRepairEntries({agentId:n.agentId,storePath:n.storePath},e.map(e=>e.inventoryFact));e.forEach((e,n)=>t.set(e,r[n]))}return e.map(e=>hydrateCanonicalSessionCandidate(e,t.get(e)))}function mergeCanonicalSessionEntryCandidates(e,t){let n;let r=false;for(const i of e){const e=typeof i.entry.updatedAt===`number`&&Number.isFinite(i.entry.updatedAt)?i.entry.updatedAt:0;const a=typeof n?.entry.updatedAt===`number`&&Number.isFinite(n.entry.updatedAt)?n.entry.updatedAt:0;const o=isSameOpenClawAgentDatabasePath(i.sqlitePath,t)&&i.sessionKey===i.canonicalKey;if(!n||e>a||e===a&&(o?!r:!r&&Buffer.compare(Buffer.from(JSON.stringify(i.entry),`utf8`),Buffer.from(JSON.stringify(n.entry),`utf8`))>0)){n=i;r=o}}return n?{entry:n.entry,winner:n}:void 0}function selectCanonicalSessionCandidate(e,t){const n=e[0];if(!n)return;const r=resolveCanonicalSessionDestination({canonicalKey:n.canonicalKey,cfg:t.cfg,env:t.env,sourceAgentId:n.agentId});const i=e.toSorted((e,t)=>Buffer.compare(Buffer.from(`${e.sqlitePath}\0${e.sessionKey}`,`utf8`),Buffer.from(`${t.sqlitePath}\0${t.sessionKey}`,`utf8`)));const a=i.filter(e=>!e.ownerEvidenceOnly);const o=mergeCanonicalSessionEntryCandidates(a.length>0?a:i,r.sqlitePath);if(!o)return;const s=i.filter(({entry:e})=>e.sandbox===`required`);const c=s.find(e=>isSameOpenClawAgentDatabasePath(e.sqlitePath,r.sqlitePath)&&e.sessionKey===e.canonicalKey)?.entry??mergeCanonicalSessionEntryCandidates(s,r.sqlitePath)?.entry;return{...o,entry:preserveCreationStamp(o.entry,c),destination:r}}function resolveSingleDatabaseCanonicalRepairGroup(e,t){const n=selectCanonicalSessionCandidate(e,t);if(!n||e.some(e=>!isSameOpenClawAgentDatabasePath(e.sqlitePath,n.destination.sqlitePath)))return;return{candidates:e,selected:n}}function createCanonicalDestinationRemovals(e,t){const n=new Set([t.entry.sessionId,t.entry.previousSessionId].filter(e=>typeof e===`string`&&e.length>0));return e.filter(e=>e.sessionKey!==t.winner.canonicalKey||e.rawEntryJson!==void 0).map(e=>createCanonicalRepairRemoval(e,{archiveRemovedTranscript:!n.has(e.entry.sessionId),deleteOwnedWindows:false}))}function listCanonicalDestinationAliasKeys(e,t){return e.map(e=>e.sessionKey).filter(e=>e!==t.canonicalKey)}function applyCanonicalDestinationArtifacts(e){replaceSessionOwnerInTransaction(e.database,e.winner.canonicalKey,e.winner.entry.owner);const t=listCanonicalDestinationAliasKeys(e.destinationStore,e.winner);if(t.length>0){if(e.rehomeDeliveries)rehomeSqliteSessionDeliveryReferencesForCanonicalRepair(e.database,e.winner.canonicalKey,t);copySessionNodeArtifactsForRepair(e.database,e.database,t,e.winner.canonicalKey,{includeMembers:false})}if(!e.copyWinnerAlias||e.winner.sessionKey===e.winner.canonicalKey)return;deleteSessionMembersForRepair(e.database,e.winner.canonicalKey);copySessionNodeArtifactsForRepair(e.database,e.database,[e.winner.sessionKey],e.winner.canonicalKey,{includeParticipants:false})}async function repairCanonicalSessionGroupsInSingleDatabase(e){const t=e[0];if(!t)return[];await ensureSqliteTranscriptGenerationsForCanonicalRepair(e.flatMap(e=>e.candidates));const n=t.selected.destination;return(await applySessionEntryLifecycleMutation({agentId:n.agentId,allowCanonicalRepair:true,afterUpsertsInTransaction:t=>{rehomeSqliteSessionDeliveryReferencesForCanonicalRepairBatch(t,e.map(e=>({canonicalKey:e.selected.winner.canonicalKey,previousKeys:listCanonicalDestinationAliasKeys(e.candidates,e.selected.winner)})));for(const n of e)applyCanonicalDestinationArtifacts({copyWinnerAlias:true,database:t,destinationStore:n.candidates,rehomeDeliveries:false,winner:n.selected.winner})},removals:e.flatMap(e=>createCanonicalDestinationRemovals(e.candidates,e.selected)),skipMaintenance:true,storePath:n.storePath,upserts:e.map(e=>({entry:e.selected.entry,sessionKey:e.selected.winner.canonicalKey}))})).archivedTranscriptDirectories}async function repairCanonicalSessionGroup(e,t){const n=selectCanonicalSessionCandidate(e,t);if(!n)return[];await ensureSqliteTranscriptGenerationsForCanonicalRepair(e);const r=n.winner;const i=n.destination;const a=createOpenClawAgentDatabasePathMatcher();const o=a.createIndex();const s=groupPluginRecords(e,e=>o(e.sqlitePath));const c=s.get(o(i.sqlitePath))??[];const l=/* @__PURE__ */ new Set;const u=a(r.sqlitePath,i.sqlitePath);if(!u){const e=/* @__PURE__ */ new Set([...listSqliteSessionGenerationIdsForCanonicalRepair({agentId:r.agentId,canonicalKey:r.canonicalKey,sourceKeys:[r.sessionKey],storePath:r.storePath}),...collectSessionStateIdsForEntry(r.entry)]);for(const n of e){if(!n)continue;const e=c.find(e=>e.entry.sessionId===n);const[a,o]=await Promise.all([withSessionTranscriptHydrationCaller(`doctor`,()=>loadSessionTranscriptEvents({agentId:e?.agentId??i.agentId,sessionId:n,sessionKey:e?.sessionKey??r.canonicalKey,storePath:e?.storePath??i.storePath})),withSessionTranscriptHydrationCaller(`doctor`,()=>loadSessionTranscriptEvents({agentId:r.agentId,sessionId:n,sessionKey:r.sessionKey,storePath:r.storePath}))]);const s=serializeJsonlLines(a.map(e=>JSON.stringify(e)));const u=serializeJsonlLines(o.map(e=>JSON.stringify(e)));if(!s||s===u)continue;const d=resolveSqliteTranscriptArchiveDirectory({agentId:i.agentId,env:t.env,path:i.sqlitePath});writeTranscriptArchive({archiveDirectory:d,content:s,sessionId:n});l.add(d)}}setCanonicalSqliteSessionMainKey(openOpenClawAgentDatabase(resolveTargetSqliteOptions(i,t.env)),t.cfg.session?.mainKey);const d=await applySessionEntryLifecycleMutation({agentId:i.agentId,allowCanonicalRepair:true,afterUpsertsInTransaction:e=>{applyCanonicalDestinationArtifacts({copyWinnerAlias:u,database:e,destinationStore:c,rehomeDeliveries:true,winner:r});if(!u)copySqliteSessionOwnedStateForCanonicalRepair({canonicalKey:r.canonicalKey,destinationDatabase:e,preferredEntry:n.entry,preferredSessionKey:r.sessionKey,source:r,sourceEntries:[r.entry],sourceKeys:[r.sessionKey]})},removals:createCanonicalDestinationRemovals(c,n),skipMaintenance:true,storePath:i.storePath,upserts:[{entry:n.entry,sessionKey:r.canonicalKey}]});for(const e of d.archivedTranscriptDirectories)l.add(e);for(const[e,t]of s){if(a(e,i.sqlitePath))continue;const n=t[0];const o=await applySessionEntryLifecycleMutation({agentId:n.agentId,allowCanonicalRepair:true,removals:t.map(e=>createCanonicalRepairRemoval(e,{archiveRemovedTranscript:true,deleteOwnedWindows:true,deliveryCleanupKeys:[r.canonicalKey]})),skipMaintenance:true,storePath:n.storePath});for(const e of o.archivedTranscriptDirectories)l.add(e)}return[...l]}async function repairCanonicalSessionKeys(e){const t=e.env??process.env;const n=projectExistingAgentDatabaseTargets(resolveAllAgentSessionStoreTargetsSync(e.cfg,{env:t}),t,e.cfg);const r=/* @__PURE__ */ new Set;let i=0;let a=0;if(e.apply)for(const r of n){const n=resolveTargetSqliteOptions(r,t);const i=withOpenClawAgentDatabaseReadOnly(readStoredCanonicalSessionMainKey,n);if(!i.found||i.value!==normalizeMainKey(e.cfg.session?.mainKey))setCanonicalSqliteSessionMainKey(openOpenClawAgentDatabase(n),e.cfg.session?.mainKey)}let o=collectCanonicalSessionRepairGroups({cfg:e.cfg,env:t},n);const s=o.length;const c=o.reduce((e,t)=>e+t.removedRows,0);if(e.apply)while(o.length>0){const s=o.slice(0,CANONICAL_SESSION_REPAIR_BATCH_GROUP_LIMIT);const c=hydrateCanonicalSessionCandidates(s.flatMap(e=>e.candidates));let l=0;const u=s.map(e=>{const t=c.slice(l,l+e.candidates.length);l+=e.candidates.length;return t});const d=u[0];const f=resolveSingleDatabaseCanonicalRepairGroup(d,{cfg:e.cfg,env:t});const p=f?[f]:[];if(f)for(const n of u.slice(1)){const r=resolveSingleDatabaseCanonicalRepairGroup(n,{cfg:e.cfg,env:t});if(!r||!isSameOpenClawAgentDatabasePath(r.selected.destination.sqlitePath,f.selected.destination.sqlitePath))break;p.push(r)}const m=f?await repairCanonicalSessionGroupsInSingleDatabase(p):await repairCanonicalSessionGroup(d,{cfg:e.cfg,env:t});for(const e of m)r.add(e);i+=1;a+=f?p.length:1;o=collectCanonicalSessionRepairGroups({cfg:e.cfg,env:t},n)}return{archivedTranscriptDirectories:[...r].toSorted(),foundGroups:s,repairBatches:i,removedRows:c,repairedGroups:a,scannedStores:n.length}}export{repairCanonicalSessionKeys as t};