UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 27.6 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{i as withEngineStoreAdmission}from"./admission-scope-Xl89MEui.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.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}from"./session-key-BPgKfU2m.mjs";import{i as listAgentIds,p as tryResolveSoleAgentId}from"./agent-roster-4XrgUgPK.mjs";import{n as createOpenClawAgentDatabasePathMatcher,o as isSameOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{a as resolveSessionArtifactDirectory,l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import"./agent-scope-config-CG9CFpGX.mjs";import{I as readSqliteDatabaseWriteRevision}from"./sqlite-database-admission-B3KDkUt-.mjs";import{i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{l as runOpenClawStateWriteTransaction}from"./openclaw-state-db-BlgxYkYw.mjs";import{i as isOpenClawAgentDatabasePathCurrent,o as readOpenClawAgentDatabaseIdentity}from"./openclaw-agent-db-identity-D6YwE2-y.mjs";import{n as resolveSessionStoreCompatibilityAgentId}from"./legacy.default-agent-owner-DUgZJ5NH.mjs";import{w as readAgentDatabaseAdmissionRefusal,y as listAgentDatabaseAdmissionRefusals}from"./agent-database-admission-DiJx9iIl.mjs";import{n as getOpenClawAgentDatabaseIfOpen}from"./openclaw-agent-db-borrower-CrL9dJmX.mjs";import{n as openOpenClawAgentDatabaseReadOnly,t as hasOpenClawAgentReadOnlySchema}from"./openclaw-agent-db-readonly-open-D1ygiMvy.mjs";import{n as withOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-BQsAKuqV.mjs";import{t as borrowOpenClawAgentDatabase}from"./openclaw-agent-db-BUym2U31.mjs";import{o as resolveSqliteTargetFromSessionStorePath}from"./session-sqlite-target-fDZeQkPI.mjs";import{t as getSessionKysely}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import{s as runExclusiveSqliteSessionWrite}from"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{a as readExactSessionEntryRow}from"./session-accessor.sqlite-entry-read-DBsgM_K3.mjs";import{i as resolveAllAgentSessionStoreCandidateTargetsSync,r as resolveAgentSessionStoreTargetsSync}from"./targets-DZpbOEi4.mjs";import{C as runSqliteSessionDeletionTransaction,E as withSqliteSessionDeletions,t as deleteLegacySessionEntryRows}from"./session-accessor.sqlite-entry-store-Cxqr6m6F.mjs";import{r as withSessionRetirementReaders,t as captureSessionRetirementReader}from"./session-retirement-read-CV1j7cn5.mjs";import{n as deleteSessionEntryLifecycle}from"./session-accessor.sqlite-lifecycle-B8uZRbgv.mjs";import{a as claimUnchanged,i as claimFullyCopied,n as copySessionClaimForRepair,o as claimsMatch,r as writeSessionClaimForRepair,s as readClaim,t as restoreColdSessionClaims}from"./legacy-main-session-migration-restore-xai-BwB2.mjs";import{t as selectSessionStoreMaintenanceTargets}from"./targets-maintenance-CUlm3hfI.mjs";import fs from"node:fs";import path from"node:path";import{resolvePathPrefixSync}from"@openclaw/fs-safe/advanced"; //!src/config/sessions/legacy-main-session-key-scan.ts function inspectSessionStorePath(e){let t;try{t=fs.lstatSync(e)}catch(e){if(hasErrnoCode(e,`ENOENT`))return`missing`;throw e}if(!(t.isSymbolicLink()?fs.statSync(e):t).isFile())throw new Error(`session store is not a regular file: ${e}`);return`present`}function resolveMissingPhysicalPath(e){const t=resolvePathPrefixSync(path.resolve(e));return path.join(t.existingPath,...t.unresolvedSegments)}function resolvePhysicalPathIdentity(e){try{const t=fs.statSync(e,{bigint:true});if(!t.isFile())throw new Error(`session store is not a regular file: ${e}`);return`file:${t.dev}:${t.ino}`}catch(t){if(!hasErrnoCode(t,`ENOENT`))throw t;return`missing:${resolveMissingPhysicalPath(e)}`}}function resolveSourceLayout(e){return[.../* @__PURE__ */ new Set([...e.stores.map(e=>`sqlite:${e.databaseAgentId}:${resolvePhysicalPathIdentity(e.path)}`),...e.jsonPaths.map(e=>`json:${resolvePhysicalPathIdentity(e)}`)])].toSorted()}function legacyAgentKeyPrefix(e,t){const n=parseAgentSessionKey(e);if(!n||normalizeAgentId(n.agentId)!==t)return null;const r=`agent:${n.agentId}:`;return e.startsWith(r)?r:null}function canonicalKeyFor(e,t,n){const r=legacyAgentKeyPrefix(e,t);return r?`agent:${n}:${e.slice(r.length)}`:null}function readClaimsFromStores(e){const t=/* @__PURE__ */ new Set;const n=/* @__PURE__ */ new Map;const readStore=(t,n)=>{try{if(inspectSessionStorePath(t.path)===`missing`)return;const r=withOpenClawAgentDatabaseReadOnly(n,{agentId:t.databaseAgentId,env:e.env,path:t.path});return r.found?r.value:void 0}catch(n){e.onUnreadable(t,n);return}};for(const r of e.stores){const i=readStore(r,e=>executeSqliteQuerySync(e.db,getSessionKysely(e.db).selectFrom(`session_nodes`).select(`session_key`)).rows);if(i)n.set(r,i.map(({session_key:n})=>{const r=canonicalKeyFor(n,e.legacyAgentId,e.ownerAgentId);if(r)t.add(r);return{key:n,canonicalKey:r??n}}))}const r=[];const i=[];for(const[e,a]of n){const n=a.filter(({canonicalKey:e})=>t.has(e));if(n.length===0)continue;const o=readStore(e,t=>n.flatMap(({key:n,canonicalKey:r})=>{const i=readClaim(t,e,n,r);return i?[i]:[]}));for(const e of o??[])(e.key===e.canonicalKey?r:i).push(e)}return{canonical:r,legacy:i}}function prepareComparisonClaimsFromStores(e){const t=e.stores.map(t=>{const n={...t};try{inspectSessionStorePath(n.path);return{store:n,reader:captureSessionRetirementReader(n,e.env)}}catch(e){return{store:n,error:e}}});const n=/* @__PURE__ */ new Set;const assertCurrent=()=>{for(const e of t){if(n.has(e.store))continue;if(!e.reader)throw e.error;e.reader.assertCurrent()}};const read=async()=>{const r=/* @__PURE__ */ new Set;const i=[];n.clear();const unreadable=(t,r)=>{n.add(t);e.onUnreadable(t,r)};for(const{store:n,reader:a,error:o}of t){if(!a){unreadable(n,o);continue}try{const t=(await a.read({operation:`keys`})).keys.map(t=>{const n=canonicalKeyFor(t,e.legacyAgentId,e.ownerAgentId);if(n)r.add(n);return{key:t,canonicalKey:n??t}});i.push({store:n,reader:a,keys:t})}catch(e){unreadable(n,e)}}const a=[];for(const{store:e,reader:t,keys:n}of i){const i=n.filter(({canonicalKey:e})=>r.has(e));if(i.length===0)continue;try{const n=await t.read({operation:`comparison-claims`,store:e,keys:i});for(const t of n.claims)a.push({store:e,claim:t})}catch(t){unreadable(e,t)}}for(const{store:e,reader:r}of t){if(!r||n.has(e))continue;try{r.assertCurrent()}catch(t){unreadable(e,t)}}const o=[];const s=[];for(const{store:e,claim:t}of a)if(!n.has(e))(t.key===t.canonicalKey?o:s).push(t);return{canonical:o,legacy:s}};return{assertCurrent,read:()=>withSessionRetirementReaders(t.flatMap(({reader:e})=>e?[e]:[]),read)}}async function storesHaveLegacyAgentSessionKey(e){const t=e.stores.map(t=>{inspectSessionStorePath(t.path);return captureSessionRetirementReader(t,e.env)});return withSessionRetirementReaders(t,async()=>{for(const n of t)if((await n.read({operation:`keys`})).keys.some(t=>legacyAgentKeyPrefix(t,e.legacyAgentId)!==null))return true;for(const e of t)e.assertCurrent();return false})}function readDeferredLegacyMainSessionInspection(e){const t=listAgentDatabaseAdmissionRefusals({env:e.env}).filter(t=>t.code===`agent-database-inspection-pending`&&readAgentDatabaseAdmissionRefusal(t.agentId,{env:e.env}));if(t.length===0)return;return{legacyAgentId:e.legacyAgentId,mainKey:e.mainKey,ownerAgentId:e.ownerAgentId,armed:e.ownerAgentId!==void 0,changes:[],complete:false,ledgerComplete:false,outcomes:t.map(e=>({kind:`store-unreadable`,detail:`Background agent database inspection is pending`,paths:e.paths})),warnings:[`session: legacy-main detection deferred while background agent database preparation is pending`]}} //!src/config/sessions/legacy-main-session-migration-operations.ts function samePhysicalStore(e,t){return isSameOpenClawAgentDatabasePath(e.path,t.path)}function freshestClaim(e){return e.toSorted((e,t)=>{return(t.entry.updatedAt??0)-(e.entry.updatedAt??0)||e.key.localeCompare(t.key)||e.store.path.localeCompare(t.store.path)})[0]}function warningForDivergence(e,t,n){return`session: ${e} for ${t}; preserved claims ${n.map(e=>`${e.store.path}#${e.key}`).join(`, `)}. Run openclaw doctor --fix to quarantine the losing claims.`}function mutateLegacySessionClaims(e,t){const n={agentId:e.store.databaseAgentId,env:e.env,path:e.store.path,ownerStorePath:e.store.ownerStorePath};return withSqliteSessionDeletions(n,e.claims.map(({key:e,entry:t})=>({sessionKey:e,entry:t})),async r=>runExclusiveSqliteSessionWrite(n,async()=>{r();e.beforePersistentApply?.();return runSqliteSessionDeletionTransaction(t,n,{operationLabel:e.operationLabel})},e.operationLabel))}function migrateClaimsInPlace(e){return mutateLegacySessionClaims({...e,claims:e.aliases.filter(t=>t.key!==e.canonicalKey),operationLabel:`session-migration.legacy-main-in-place`},t=>{const n=e.aliases.map(n=>readClaim(t,e.store,n.key,e.canonicalKey));const r=readClaim(t,e.store,e.canonicalKey,e.canonicalKey);if(n.some((t,n)=>!t||!claimUnchanged(t,e.aliases[n]))||(e.canonical?!r||!claimUnchanged(r,e.canonical):r!==void 0))return;if(!r)writeSessionClaimForRepair(t,e.canonicalKey,e.winner.entry);deleteLegacySessionEntryRows(t,e.aliases.map(e=>e.key),e.canonicalKey,{rehomeMembers:true,validatedEntries:new Map(n.map(e=>[e.key,e.entry]))});return readClaim(t,e.store,e.canonicalKey,e.canonicalKey)})}async function deleteExpectedClaim(e,t){return(await deleteSessionEntryLifecycle({commitGuard:t,agentId:e.store.databaseAgentId,archiveTranscript:false,deleteTranscriptWithoutArchive:true,expectedEntry:e.entry,expectedDatabaseIdentity:e.databaseIdentity,expectedGenerations:e.generations,expectedNodeArtifactFingerprint:e.nodeArtifactFingerprint,requireWriteSuccess:true,storePath:e.store.ownerStorePath,target:{canonicalKey:e.key,storeKeys:[e.key]}})).deleted}async function deleteCopiedClaims(e){const t=e.aliases.filter(t=>!samePhysicalStore(t.store,e.destination));if(t.length===0)return;const n={agentId:e.destination.databaseAgentId,env:e.env,path:e.destination.path};const changed=()=>/* @__PURE__ */ new Error(`Canonical session changed before legacy cleanup: ${e.canonicalKey}`);const r=getOpenClawAgentDatabaseIfOpen(n);if(!r)throw changed();const i=readOpenClawAgentDatabaseIdentity(r).identity;const a=borrowOpenClawAgentDatabase(n);let o;try{const s=openOpenClawAgentDatabaseReadOnly(n);if(!s.found)throw changed();o=s.database;const c=o;const assertCurrent=()=>{if(a.db!==r.db||t.some(e=>e.databaseIdentity===i)||getOpenClawAgentDatabaseIfOpen(n)!==r||!isOpenClawAgentDatabasePathCurrent(r)||r.db.isTransaction||!isOpenClawAgentDatabasePathCurrent(c)||readOpenClawAgentDatabaseIdentity(c).identity!==i)throw changed()};let l;const assertCopied=()=>{e.beforePersistentApply?.();assertCurrent();const t=readSqliteDatabaseWriteRevision(c.db);if(t!==void 0&&t===l)return;if(!hasOpenClawAgentReadOnlySchema(c))throw changed();const n=readClaim(c,e.destination,e.canonicalKey,e.canonicalKey);if(!n||!claimUnchanged(n,e.receipt))throw changed();assertCurrent();if(readSqliteDatabaseWriteRevision(c.db)!==t)throw changed();l=t};assertCopied();for(const e of t)if(!await deleteExpectedClaim(e,assertCopied))return e;return}finally{try{o?.close()}finally{a.release()}}}function quarantineClaim(e){return mutateLegacySessionClaims({beforePersistentApply:e.beforePersistentApply,store:e.claim.store,env:e.env,claims:[e.claim],operationLabel:`session-migration.legacy-main-quarantine`},t=>{const n=readClaim(t,e.claim.store,e.claim.key,e.claim.canonicalKey);if(!n||!claimUnchanged(n,e.claim))return;let r;for(let n=1;;n+=1){const i=`agent:${e.ownerAgentId}:legacy-main-conflict-${n}`;if(!readExactSessionEntryRow(t,i)){r=i;break}}writeSessionClaimForRepair(t,r,e.claim.entry);deleteLegacySessionEntryRows(t,[e.claim.key],r,{rehomeMembers:true,validatedEntries:/* @__PURE__ */ new Map([[n.key,n.entry]])});return r})}async function processIdenticalClaims(e){const completedOutcome=()=>describeIdenticalClaims(e);if(e.mode!==`doctor-fix`)return completedOutcome();const t=e.canonical??freshestClaim(e.aliases);let n=e.canonical;const r=e.aliases.filter(t=>samePhysicalStore(t.store,e.destination));if(r.length>0){n=await migrateClaimsInPlace({beforePersistentApply:e.beforePersistentApply,aliases:r,...n?{canonical:n}:{},canonicalKey:e.canonicalKey,env:e.env,store:e.destination,winner:n??freshestClaim(r)});if(!n)return{kind:`divergent-aliases`,canonicalKey:e.canonicalKey,detail:`source aliases changed during the in-place transaction`}}for(const t of e.aliases){if(samePhysicalStore(t.store,e.destination))continue;const r=await copySessionClaimForRepair({mode:`legacy-main`,beforePersistentApply:e.beforePersistentApply,canonicalKey:e.canonicalKey,destination:e.destination,...n?{expectedDestination:n}:{},env:e.env,source:t});const i=withOpenClawAgentDatabaseReadOnly(n=>readClaim(n,t.store,t.key,e.canonicalKey),{agentId:t.store.databaseAgentId,env:e.env,path:t.store.path});if(!r||!claimFullyCopied(t,r)||!i.found||!i.value||!claimUnchanged(i.value,t))return{kind:`divergent-canonical`,canonicalKey:e.canonicalKey,detail:`source or imported canonical changed during cross-store copy verification`};n=r}if(!n||!claimsMatch(n,t))return{kind:`divergent-canonical`,canonicalKey:e.canonicalKey,detail:`canonical content differs from the legacy claim`};const i=await deleteCopiedClaims({...e,receipt:n});if(i)return{kind:`divergent-canonical`,canonicalKey:e.canonicalKey,detail:`source changed before expected-entry cleanup: ${i.store.path}#${i.key}`};return completedOutcome()}function describeIdenticalClaims(e){return{kind:e.canonical?`canonical-exists-identical`:e.aliases.some(t=>!samePhysicalStore(t.store,e.destination))?`migrated-cross-store`:`migrated-in-place`,canonicalKey:e.canonicalKey,paths:[...new Set(e.aliases.map(e=>e.store.path))],sourceKeys:e.aliases.map(e=>e.key)}}async function repairDivergentClaims(e){const t=e.destinationCanonical??freshestClaim(e.claims);if(!e.destinationCanonical){const n=await processIdenticalClaims({beforePersistentApply:e.beforePersistentApply,aliases:[t],canonicalKey:e.canonicalKey,destination:e.destination,env:e.env,mode:`doctor-fix`});if(n.kind===`divergent-aliases`||n.kind===`divergent-canonical`)return{quarantinedKeys:[],resolved:false}}const n=withOpenClawAgentDatabaseReadOnly(t=>readClaim(t,e.destination,e.canonicalKey,e.canonicalKey),{agentId:e.destination.databaseAgentId,env:e.env,path:e.destination.path});const r=n.found?n.value:void 0;if(!r||!claimsMatch(r,t))return{quarantinedKeys:[],resolved:false};const i=e.claims.filter(n=>n!==t&&n!==e.destinationCanonical);const a=i.filter(e=>claimsMatch(e,r));if(a.length>0){const t=await processIdenticalClaims({beforePersistentApply:e.beforePersistentApply,aliases:a,canonical:r,canonicalKey:e.canonicalKey,destination:e.destination,env:e.env,mode:`doctor-fix`});if(t.kind===`divergent-aliases`||t.kind===`divergent-canonical`)return{quarantinedKeys:[],resolved:false}}const o=[];for(const t of i){if(a.includes(t))continue;const n=await quarantineClaim({beforePersistentApply:e.beforePersistentApply,claim:t,env:e.env,ownerAgentId:e.ownerAgentId});if(!n)return{quarantinedKeys:o,resolved:false};o.push(n)}return{quarantinedKeys:o,resolved:true}} //!src/config/sessions/legacy-main-session-migration.ts const SOURCE_KEY=`legacy-main-session-keys`;const MIGRATION_KIND=`legacy-main-session-keys-v1`;const REPORT_VERSION=1;function resolveArmingDecision(e,t){const n=new Set(listAgentIds(e).map(normalizeAgentId));if(n.has(t))return{armed:false,reason:`legacy-agent-present`};const r=tryResolveSoleAgentId(e);if(r&&n.has(normalizeAgentId(r)))return{armed:true,ownerAgentId:normalizeAgentId(r)};const i=e.agents?.defaults?.sessionStore?.agentId?.trim();if(i){const e=normalizeAgentId(i);if(n.has(e))return{armed:true,ownerAgentId:e}}return{armed:false,reason:`owner-unresolved`}}function resolvePhysicalStores(e){const t=[...resolveAllAgentSessionStoreCandidateTargetsSync(e.cfg,{env:e.env}),...resolveAgentSessionStoreTargetsSync(e.cfg,e.legacyAgentId,{env:e.env}),{agentId:e.legacyAgentId,storePath:resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.legacyAgentId,env:e.env})}];if(e.ownerAgentId)t.push({agentId:e.ownerAgentId,storePath:resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.ownerAgentId,env:e.env})});const n=e.ownerAgentId??resolveSessionStoreCompatibilityAgentId(e.cfg);const r=/* @__PURE__ */ new Map;const i=createOpenClawAgentDatabasePathMatcher();const a=i.createIndex();const o=/* @__PURE__ */ new Set;const s=[];const c=[];const recordUnreadable=(t,n)=>{if(e.mode===`doctor-fix`)throw new Error(`cannot inspect legacy session store ${t}: ${String(n)}`,{cause:n});s.push({kind:`store-unreadable`,detail:String(n),paths:[t]})};const l=t.flatMap(t=>{try{const r=resolveSqliteTargetFromSessionStorePath(t.storePath,{agentId:t.agentId,defaultAgentId:n,env:e.env,isSameDatabasePath:i});return[{target:t,resolved:r,sqlitePath:r.path}]}catch(e){recordUnreadable(t.storePath,e);return[]}});for(const{target:t,resolved:n}of selectSessionStoreMaintenanceTargets(l,{...e,onExcluded:e.mode===`doctor-fix`?e=>c.push(`session: skipped legacy-main scan of held session store ${e}; preserved any legacy rows for explicit agent restoration`):void 0}))try{if(!t.storePath.endsWith(`.sqlite`)&&inspectSessionStorePath(t.storePath)===`present`)o.add(path.resolve(t.storePath));const e={databaseAgentId:normalizeAgentId(n.agentId??t.agentId),ownerStorePath:t.storePath,path:n.path};resolvePhysicalPathIdentity(e.path);const i=a(e.path);if(!r.has(i))r.set(i,e)}catch(e){recordUnreadable(t.storePath,e)}return{jsonPaths:[...o],stores:[...r.values()],unreadable:s,warnings:[...new Set(c)]}}async function readLedger(e){const t=await executeExistingOpenClawStateRead({env:e},{type:`legacySessionMigration.readLedger`,input:void 0},{current:true});if(t&&(!t.ok||t.type!==`legacySessionMigration.readLedger`))throw new Error(`Unexpected legacy session migration ledger result`);const n=t?.row;if(!n)return;try{const e=JSON.parse(n.report_json);if(!isRecord(e)||e.version!==REPORT_VERSION||typeof e.legacyAgentId!==`string`||typeof e.mainKey!==`string`||typeof e.ownerAgentId!==`string`||!Array.isArray(e.outcomes)||!Array.isArray(e.sourceLayout)||e.sourceLayout.some(e=>typeof e!==`string`)||e.status!==`complete`)return;return{report:e,status:n.status}}catch{return}}function ledgerMatches(e,t){return e?.status===`completed`&&e.report.version===REPORT_VERSION&&e.report.status===`complete`&&e.report.legacyAgentId===t.legacyAgentId&&e.report.ownerAgentId===t.ownerAgentId&&e.report.mainKey===t.mainKey&&e.report.sourceLayout.length===t.sourceLayout.length&&e.report.sourceLayout.every((e,n)=>e===t.sourceLayout[n])}function writeLedger(e){const t={version:REPORT_VERSION,...e.identity,outcomes:e.outcomes,status:`complete`};const n=JSON.stringify(t);const r=sha256Hex(JSON.stringify(e.identity));const i=`${SOURCE_KEY}:${r.slice(0,24)}`;e.beforePersistentApply?.();runOpenClawStateWriteTransaction(({db:t})=>{const a=getNodeSqliteKysely(t);const o={finished_at:e.now,status:`completed`,report_json:n};executeSqliteQuerySync(t,a.insertInto(`migration_runs`).values({id:i,started_at:e.now,...o}).onConflict(e=>e.column(`id`).doUpdateSet(o)));const s={source_path:e.stateDir,source_sha256:r,source_record_count:e.outcomes.length,last_run_id:i,status:`completed`,imported_at:e.now,removed_source:1,report_json:n};executeSqliteQuerySync(t,a.insertInto(`migration_sources`).values({source_key:SOURCE_KEY,migration_kind:MIGRATION_KIND,target_table:`session_nodes`,source_size_bytes:null,...s}).onConflict(e=>e.column(`source_key`).doUpdateSet(s)))},{env:e.env},{operationLabel:`session-migration.legacy-main-ledger`})}function compareClaimGroup(e,t,n){const r=t.find(e=>samePhysicalStore(e.store,n));const i=t.some(e=>!samePhysicalStore(e.store,n));const a=e.every(t=>claimsMatch(t,e[0]));const o=r?e.every(e=>claimsMatch(e,r)):false;const s=i||r&&!o?`divergent-canonical`:!a?`divergent-aliases`:void 0;return{destinationCanonical:r,divergence:s,divergentClaims:s===`divergent-canonical`?[...t,...e]:e}}function describeDivergentClaims(e,t,n){return{kind:e,canonicalKey:t,paths:[...new Set(n.map(e=>e.store.path))],sourceKeys:n.map(e=>e.key)}}function isBlockingOutcome(e){return e.kind===`legacy-json-store`||e.kind===`store-unreadable`||(e.kind===`divergent-aliases`||e.kind===`divergent-canonical`)&&e.resolved!==true}async function migrateLegacyMainSessionKeysInternal(e){const{cfg:t,mode:n}=e;const r=e.env??process.env;const i=normalizeAgentId(e.legacyAgentId??`main`);const a=normalizeMainKey(e.cfg.session?.mainKey);const o=resolveArmingDecision(e.cfg,i);const s={changes:[],legacyAgentId:i,mainKey:a,warnings:[]};if(n===`detect`&&(o.armed||o.reason===`owner-unresolved`)){const e=readDeferredLegacyMainSessionInspection({env:r,legacyAgentId:i,mainKey:a,...o.armed?{ownerAgentId:o.ownerAgentId}:{}});if(e)return e}if(!o.armed){if(o.reason===`owner-unresolved`){let e;try{const a=withEngineStoreAdmission(()=>resolvePhysicalStores({cfg:t,env:r,legacyAgentId:i,mode:n}));s.warnings=a.warnings;e=a.unreadable.length>0||a.jsonPaths.length>0||await storesHaveLegacyAgentSessionKey({env:r,legacyAgentId:i,stores:a.stores})}catch{e=true}if(!e)return{...s,armed:false,complete:true,ledgerComplete:false,outcomes:[{kind:`no-legacy-rows`,detail:`no configured owner`}]}}const e=o.reason===`owner-unresolved`;return{...s,armed:false,complete:false,ledgerComplete:false,outcomes:[{kind:`not-armed`,detail:o.reason}],warnings:e?[...s.warnings,`session: legacy ${i} rows have no unambiguous configured owner; preserve them and run openclaw doctor --fix after assigning agents.defaults.sessionStore.agentId`]:s.warnings}}const c=o.ownerAgentId;const l=withEngineStoreAdmission(()=>resolvePhysicalStores({cfg:t,env:r,legacyAgentId:i,mode:n,ownerAgentId:c}));const u=[...l.jsonPaths.map(e=>({kind:`legacy-json-store`,paths:[e],detail:`Doctor must migrate JSON sessions to SQLite before legacy-main key migration`})),...l.unreadable];const d=[...s.warnings,...l.warnings];for(const e of l.unreadable)d.push(`session: could not inspect ${e.paths?.[0]??`session store`}: ${e.detail??`unknown error`}; run openclaw doctor --fix`);for(const e of l.jsonPaths)d.push(`session: deferred legacy-main session migration for JSON store ${e}; run openclaw doctor --fix`);const f={env:r,legacyAgentId:i,ownerAgentId:c,stores:l.stores,onUnreadable:(t,n)=>{if(e.mode===`doctor-fix`)throw new Error(`cannot read legacy session store ${t.path}: ${String(n)}`,{cause:n});u.push({kind:`store-unreadable`,detail:String(n),paths:[t.path]});d.push(`session: could not inspect ${t.path}: ${String(n)}; run openclaw doctor --fix`)}};const p=e.mode===`detect`?prepareComparisonClaimsFromStores(f):void 0;const m={legacyAgentId:i,mainKey:a,ownerAgentId:c};const h={...m,sourceLayout:resolveSourceLayout(l)};let g=false;if(e.mode!==`doctor-fix`&&u.length===0)try{const t=await readLedger(r);p?.assertCurrent();if(ledgerMatches(t,h)){g=true;if(!e.forceScan)return{...s,armed:true,complete:true,ledgerComplete:true,ownerAgentId:c,warnings:d,outcomes:[{kind:`no-legacy-rows`,detail:`matching completed ledger`}]}}}catch(e){return{...s,armed:true,complete:false,ledgerComplete:false,ownerAgentId:c,outcomes:[{kind:`store-unreadable`,detail:String(e)}],warnings:[`session: could not read the legacy-main migration ledger: ${String(e)}; run openclaw doctor --fix`]}}const _=resolveSessionStorePathCore(e.cfg.session?.store,{agentId:c,env:r});const v=resolveSqliteTargetFromSessionStorePath(_,{agentId:c,defaultAgentId:c,env:r});const y=l.stores.find(e=>isSameOpenClawAgentDatabasePath(e.path,v.path))??{databaseAgentId:normalizeAgentId(v.agentId??c),ownerStorePath:_,path:v.path};if(p){const{legacy:e,canonical:t}=await p.read();p.assertCurrent();if(e.length>0)d.push(`session: ${e.length} retained legacy ${i} session claim(s) require Doctor repair; run openclaw doctor --fix`);for(const[n,r]of groupPluginRecords(e,e=>e.canonicalKey)){const e=compareClaimGroup(r,t.filter(e=>e.key===n),y);if(e.divergence){u.push(describeDivergentClaims(e.divergence,n,e.divergentClaims));d.push(warningForDivergence(e.divergence,n,e.divergentClaims))}else u.push(describeIdenticalClaims({aliases:r,canonical:e.destinationCanonical,canonicalKey:n,destination:y}))}if(e.length===0&&u.length===0)u.push({kind:`no-legacy-rows`});const n=!u.some(isBlockingOutcome);return{...s,armed:true,complete:n,ledgerComplete:n&&g&&e.length===0,outcomes:u,ownerAgentId:c,warnings:d}}const{legacy:b,canonical:x}=readClaimsFromStores(f);const S=e.mode!==`doctor-fix`?void 0:resolveMissingPhysicalPath(path.join(resolveSessionArtifactDirectory(v.path),`cold`));for(const[t,n]of groupPluginRecords(b,e=>e.canonicalKey)){const i=x.filter(e=>e.key===t);if(e.mode===`doctor-fix`&&[...n,...i].some(e=>!samePhysicalStore(e.store,y)||resolveMissingPhysicalPath(path.join(resolveSessionArtifactDirectory(e.store.path),`cold`))!==S)){await restoreColdSessionClaims(n,r,e.beforePersistentApply);await restoreColdSessionClaims(i,r,e.beforePersistentApply)}const{destinationCanonical:a,divergence:o,divergentClaims:s}=compareClaimGroup(n,i,y);if(o){const n=describeDivergentClaims(o,t,s);if(e.mode===`doctor-fix`){const i=await repairDivergentClaims({beforePersistentApply:e.beforePersistentApply,canonicalKey:t,claims:s,destination:y,...o===`divergent-canonical`&&a?{destinationCanonical:a}:{},env:r,ownerAgentId:c});n.quarantinedKeys=i.quarantinedKeys;if(i.resolved)n.resolved=true}if(!n.resolved)d.push(warningForDivergence(o,t,s));u.push(n);continue}const l=await processIdenticalClaims({beforePersistentApply:e.beforePersistentApply,aliases:n,...a?{canonical:a}:{},canonicalKey:t,destination:y,env:r,mode:e.mode});u.push(l);if(l.kind===`divergent-aliases`||l.kind===`divergent-canonical`)d.push(warningForDivergence(l.kind,t,n))}if(b.length===0&&u.length===0)u.push({kind:`no-legacy-rows`});const C=!u.some(isBlockingOutcome);const w=e.mode!==`doctor-fix`?[]:u.flatMap(e=>e.kind===`migrated-in-place`||e.kind===`migrated-cross-store`||e.kind===`canonical-exists-identical`?[`Migrated legacy ${i} session claim ${e.canonicalKey}.`]:e.quarantinedKeys?.length?[`Quarantined ${e.quarantinedKeys.length} legacy ${i} session conflict(s).`]:[]);if(C&&e.mode===`doctor-fix`)writeLedger({beforePersistentApply:e.beforePersistentApply,env:r,identity:{...m,sourceLayout:resolveSourceLayout(l)},now:e.now?.()??Date.now(),outcomes:u,stateDir:resolveStateDir(r)});return{armed:true,changes:w,complete:C,ledgerComplete:C&&(e.mode===`doctor-fix`||g&&b.length===0),legacyAgentId:i,mainKey:a,outcomes:u,ownerAgentId:c,warnings:d}}async function migrateLegacyMainSessionKeys(e){try{return await migrateLegacyMainSessionKeysInternal(e)}catch(t){e.beforePersistentApply?.();if(e.mode===`doctor-fix`)throw t;const n=normalizeAgentId(e.legacyAgentId??`main`);const r=normalizeMainKey(e.cfg.session?.mainKey);const i=resolveArmingDecision(e.cfg,n);return{armed:i.armed,changes:[],complete:false,ledgerComplete:false,legacyAgentId:n,mainKey:r,outcomes:[{kind:`store-unreadable`,detail:String(t)}],...i.armed?{ownerAgentId:i.ownerAgentId}:{},warnings:[`session: legacy-main session migration deferred: ${String(t)}; run openclaw doctor --fix`]}}}export{migrateLegacyMainSessionKeys as t};