UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

18 lines • 74.8 kB
import{m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{d as isStringRecord,l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings,v as normalizeUniqueTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{t as isBlockedObjectKey}from"./prototype-keys-Dc7Yq32J.mjs";import{a as coerceSecretRef}from"./types.secrets-UWdyCdE6.mjs";import{o as copyConfigResolutionFactsThroughRewrite}from"./resolution-facts-DYKtoyes.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{T as resolveOAuthDir}from"./paths-D_FOvGon.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{n as listAgentEntries}from"./agent-roster-4XrgUgPK.mjs";import"./agent-scope-config-CG9CFpGX.mjs";import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{i as assertExistingDatabaseIdentity,m as readDatabasePathIdentitySync}from"./sqlite-worker-identity-CikEUuqF.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{Fn as object,Jn as string,Nt as array,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{g as withExistingOpenClawStateDatabaseReadOnly}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{E as requireOpenClawStateDatabaseIdentity}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{a as createConfigRuntimeEnv}from"./config-env-vars-DCDGIBtT.mjs";import{l as runOpenClawStateWriteTransaction}from"./openclaw-state-db-BlgxYkYw.mjs";import{r as decodeUtf8Input}from"./utf8-input-CiFSnxL0.mjs";import{n as normalizeSecretInput}from"./normalize-secret-input-CEFJUjQX.mjs";import{P as isLegacyOAuthRef,p as coerceAuthProfileState}from"./user-model-account-authority-B8H7rvCb.mjs";import{o as readOpenClawAgentDatabaseIdentity}from"./openclaw-agent-db-identity-D6YwE2-y.mjs";import{r as collectConfiguredModelRefs}from"./configured-model-refs-BvslYBsZ.mjs";import{t as splitTrailingAuthProfile}from"./model-ref-profile-DFGpvDZX.mjs";import{n as isChannelConfigMetadataKey}from"./config-metadata-RS-_hyk8.mjs";import{a as recordLegacyMigrationReceipt,i as readLegacyMigrationReceiptFromDatabase,o as recordLegacyMigrationRun,r as readLegacyMigrationReceipt,s as recordLegacyMigrationSource}from"./state-migrations.receipts-DhYgpkdJ.mjs";import{t as OPENAI_PROVIDER_ID}from"./openai-routing-CkWt7Drz.mjs";import{f as acquireFileLockSyncWithRetry}from"./update-managed-service-handoff-database-H0kqm6Ol.mjs";import{n as hasMatchingOAuthIdentity,t as areOAuthCredentialsEquivalent}from"./oauth-shared-DTzAchzX.mjs";import{i as loadPersistedSharedAuthProfileStore,n as loadPersistedAuthProfileStore}from"./persisted-CpbPYi0y.mjs";import{B as resolveLegacyOAuthPath,C as writePersistedAuthProfileStateRaw,H as resolveNativeSharedAuthStorePath,L as listLegacyAuthProfileArchives,S as runAuthProfileWriteTransaction,V as prepareSharedAuthStoreOwnershipForNative,a as inspectPersistedAuthProfileStoreRaw,b as resolveAuthProfileDatabasePath,d as readAuthProfileStateJsonTextReadOnly,g as readPersistedSharedAuthProfileStoreRaw,h as readPersistedSharedAuthProfileStateRaw,i as inspectPersistedAuthProfileStateRaw,m as readPersistedAuthProfileStoreRaw,o as inspectPersistedSharedAuthProfileStateRaw,p as readPersistedAuthProfileStateRaw,s as inspectPersistedSharedAuthProfileStoreRaw,w as writePersistedAuthProfileStoreRaw}from"./sqlite-y_WDH-Xr.mjs";import{t as resolveSharedMainAuthAgentDir}from"./shared-main-dir-CnBJA5xX.mjs";import{c as readAuthProfileJsonCellText,s as inspectAuthProfileJsonCell}from"./sqlite-json-CUskHMsO.mjs";import{$ as isInheritedMainOAuthCredentialFromStores,_t as coerceLegacyFlatCredential,bt as normalizeLegacyCredentialFields,ft as readLegacyAuthProfileProviders,gt as coerceLegacyAuthStore,ht as coerceLegacyAuthProfileStore,mt as applyLegacyAuthStore,ot as clearAuthProfileMigrationDiagnostics,r as clearRuntimeAuthProfileStoreSnapshots,vt as hasUsableAuthProfileCredential,xt as parseLegacyCredentialEntry,yt as normalizeLegacyAuthProfileFields}from"./runtime-snapshots-DYK7vyJv.mjs";import{t as loadJsonFileThroughSymlink}from"./json-file-BedClo2t.mjs";import{m as renameUserProfileAuthLinks}from"./user-model-accounts-IUTOAdBk.mjs";import{r as resolveLegacyInheritedAuthAgentDir}from"./legacy-inherited-auth-dir-9LCjV4lR.mjs";import{S as saveAuthProfileStoreWithPreparedOwner}from"./store-runtime-GNz-2GjY.mjs";import{a as resolveLegacyAuthStatePath,n as listAuthProfileRepairCandidates,o as resolveLegacyFlatAuthPath,r as listReferencedLegacyOAuthSidecarPaths}from"./doctor-auth-legacy-paths-B65BBpsr.mjs";import{r as createVerifiedDatabaseMigrationBackup}from"./database-backup-yFN_P503.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{r as stripImportedConfigAuthProfileCredentials,t as ensureConfigAuthProfiles}from"./doctor-auth-profile-config-CWPdp-6v.mjs";import{t as listMutableCodexRouteAgentEntries}from"./codex-route-agent-entries-NAzn4UQF.mjs";import{a as repairModelRefAuthProfile,n as repairRetiredConfigModelRefs}from"./retired-model-ref-repair-DEPRKNGf.mjs";import{n as resolveLegacyRuntimeModelProviderAlias}from"./legacy-runtime-model-providers-BGH1r4rF.mjs";import{t as createAuthMigrationWarningRecorder}from"./auth-migration-findings-P6mrEQj_.mjs";import{t as inspectAuthDatabaseFiles}from"./stale-auth-order-store-CMT-2z5c.mjs";import fs from"node:fs";import path from"node:path";import{createDecipheriv,createHash,hash,randomUUID}from"node:crypto";import os from"node:os";import*as childProcess$1 from"node:child_process";import{isDeepStrictEqual}from"node:util";import{isPathInside}from"@openclaw/fs-safe/path";
//!src/plugins/auth-profile-config-refs.ts
function rewritePluginAuthProfileRefs(e,t){let n=false;const rewrite=e=>{if(Array.isArray(e)){e.forEach(rewrite);return}if(!isRecord(e))return;for(const[r,i]of Object.entries(e))if((r===`authProfileId`||r===`defaultAuthProfileId`)&&typeof i===`string`){const a=t.get(i.trim());if(a&&a!==i){e[r]=a;n=true}}else rewrite(i)};for(const t of Object.values(e.plugins?.entries??{}))rewrite(t.config);for(const[t,n]of Object.entries(e.channels??{}))if(!isChannelConfigMetadataKey(t))rewrite(n);return n}
//!src/commands/doctor-auth-migration-receipts.ts
const MIGRATION_KIND=`auth-profile-json-to-sqlite-v2`;function prepareAuthProfileSourceReceipt(e){const t=fs.readFileSync(e.pathname);const n=parseAuthProfileMigrationSource({sourceBytes:t,sourcePath:e.pathname});const r=isRecord(n)?Object.keys(n).length:0;const i=new Date(e.now());const a=path.resolve(e.pathname);const o=sha256Hex(t);const s=`auth-profile-v2:${sha256Hex(`${a}\0${o}`)}`;const c=i.toISOString().replaceAll(`:`,`-`);return{sourceKey:s,runId:`${s}:${randomUUID()}`,sourcePath:a,sourceSha256:o,sourceSizeBytes:t.byteLength,sourceRecordCount:r,sourceBytes:t,targetDatabasePath:path.resolve(e.targetDatabasePath),targetTable:e.targetTable,...e.targetStoreKey?{targetStoreKey:e.targetStoreKey}:{},archivePath:`${a}.migrated-${c}-${randomUUID()}`,...e.env?{env:e.env}:{}}}function assertAuthProfileMigrationSourcesUnchanged(e,t){const n=new Map(t.map(e=>[e.sourcePath,e]));for(const r of/* @__PURE__ */ new Set([...e,...t.map(e=>e.sourcePath)])){const e=n.get(path.resolve(r));if(fs.existsSync(r)!==Boolean(e))throw new Error(`legacy auth source set changed during migration; retry Doctor`);if(!e)continue;if(sha256Hex(fs.readFileSync(r))!==e.sourceSha256)throw new Error(`legacy auth source changed during migration; retry Doctor`)}}function parseAuthProfileMigrationSource(e){if(!e?.sourceBytes)return null;const t=decodeUtf8Input(e.sourceBytes,`Legacy auth source ${e.sourcePath}`);try{return JSON.parse(t)}catch{return null}}function reportJson(e){return JSON.stringify({format:MIGRATION_KIND,archivePath:e.archivePath,targetDatabasePath:e.targetDatabasePath,targetTable:e.targetTable,targetStoreKey:e.targetStoreKey??`primary`,expectedProfileSha256:e.expectedProfileSha256,expectedStateSha256:e.expectedStateSha256,completionStatus:e.completionStatus??`completed`})}function digestAuthProfileMigrationValue(e){return sha256Hex(JSON.stringify(e)??`<undefined>`)}function recordAuthProfileMigrationImported(e,t=Date.now()){runOpenClawStateWriteTransaction(({db:n})=>{const r=getNodeSqliteKysely(n);const i=executeSqliteQueryTakeFirstSync(n,r.selectFrom(`migration_sources`).select([`last_run_id`,`status`]).where(`source_key`,`=`,e.sourceKey));if(i&&i.last_run_id!==e.runId&&i.status!==`retryable`&&i.status!==`superseded`)throw new Error(`auth profile migration source already owned by ${i.status} receipt`);const a=reportJson(e);recordLegacyMigrationRun(n,{runId:e.runId,startedAt:t,finishedAt:null,status:`imported`,reportJson:a,upsert:true});recordLegacyMigrationSource(n,{sourceKey:e.sourceKey,migrationKind:MIGRATION_KIND,sourcePath:e.sourcePath,targetTable:e.targetTable,sourceSha256:e.sourceSha256,sourceSizeBytes:e.sourceSizeBytes,sourceRecordCount:e.sourceRecordCount,runId:e.runId,status:`imported`,importedAt:t,reportJson:a,upsert:true})},{env:e.env})}function updateAuthProfileMigrationReceipt(e,t,n,r=Date.now()){runOpenClawStateWriteTransaction(({db:i})=>{const a=getNodeSqliteKysely(i);let o=a.updateTable(`migration_runs`).set({status:t,finished_at:r}).where(`id`,`=`,e.runId);let s=a.updateTable(`migration_sources`).set({status:t,...t===`completed`||t===`archived-unparsed`?{removed_source:1}:{}}).where(`source_key`,`=`,e.sourceKey).where(`last_run_id`,`=`,e.runId);if(n){o=o.where(`status`,`=`,n);s=s.where(`status`,`=`,n)}executeSqliteQuerySync(i,o);executeSqliteQuerySync(i,s)},{env:e.env})}function restoreAuthProfileMigrationArchiveNoClobber(e){try{fs.linkSync(e.archivePath,e.sourcePath)}catch(e){if(e.code===`EEXIST`)return`source-exists`;throw e}fs.unlinkSync(e.archivePath);return`restored`}function archiveAuthProfileMigrationSource(e){if(fs.existsSync(e.sourcePath)){const t=fs.readFileSync(e.sourcePath);if(sha256Hex(t)!==e.sourceSha256)throw new Error(`legacy auth source changed after verification`);fs.renameSync(e.sourcePath,e.archivePath)}const t=fs.readFileSync(e.archivePath);if(sha256Hex(t)!==e.sourceSha256)throw new Error(`legacy auth archive verification failed`)}function acquireAuthProfileMigrationSourceLocks(e){const t=[];const releaseAll=()=>{for(const e of t.toReversed())e()};try{for(const n of[...new Set(e.map(e=>path.resolve(e)))].toSorted())t.push(acquireFileLockSyncWithRetry(n))}catch(e){releaseAll();throw e}return releaseAll}function verifyAuthProfileMigrationTarget(e){const t=Object.entries(e.expectedProfileSha256??{});if(t.length===0&&!e.expectedStateSha256)return;const n=openNodeSqliteDatabase(e.targetDatabasePath,{readOnly:true});try{const readTarget=t=>{const r=readAuthProfileJsonCellText(n,t,e.targetStoreKey===`shared`?`shared-state`:`agent`);return typeof r===`string`?JSON.parse(r):null};const r=t.length>0?readTarget(`store`):null;for(const[e,n]of t)if(digestAuthProfileMigrationValue(r?.profiles?.[e])!==n)throw new Error(`auth profile migration target verification failed`);if(e.expectedStateSha256&&digestAuthProfileMigrationValue(readTarget(`state`))!==e.expectedStateSha256)throw new Error(`auth profile migration target verification failed`)}finally{n.close()}}function finalizeAuthProfileMigrationSource(e,t=`completed`){e.completionStatus=t;recordAuthProfileMigrationImported(e);verifyAuthProfileMigrationTarget(e);archiveAuthProfileMigrationSource(e);updateAuthProfileMigrationReceipt(e,t)}function resumePendingAuthProfileMigrationArchives(e,t){const n=[];const r=withExistingOpenClawStateDatabaseReadOnly(({db:e})=>executeSqliteQuerySync(e,getNodeSqliteKysely(e).selectFrom(`migration_sources as source`).innerJoin(`migration_runs as run`,`run.id`,`source.last_run_id`).select([`source.source_key`,`source.source_path`,`source.source_sha256`,`source.source_size_bytes`,`source.source_record_count`,`source.target_table`,`source.last_run_id`,`source.report_json`,`source.status`]).where(`source.migration_kind`,`=`,MIGRATION_KIND).where(e=>e.or([e.and([e(`source.status`,`=`,`imported`),e(`source.removed_source`,`=`,0)]),e.and([e(`source.status`,`=`,`completed`),e(`source.removed_source`,`=`,1)])]))).rows,{env:e})??[];for(const i of r){const r=JSON.parse(i.report_json);const a=i.status===`completed`;if(a&&(!t||Object.hasOwn(r,`expectedProfileSha256`)||i.target_table===`auth_profile_state`||typeof r.archivePath!==`string`||!fs.existsSync(r.archivePath)))continue;if(typeof i.source_sha256!==`string`||typeof i.source_size_bytes!==`number`||typeof i.source_record_count!==`number`||typeof r.archivePath!==`string`||typeof r.targetDatabasePath!==`string`||i.target_table!==`auth_profile_store`&&i.target_table!==`auth_profile_stores`&&i.target_table!==`auth_profile_state`)throw new Error(`invalid pending auth profile migration receipt`);const o={sourceKey:i.source_key,runId:i.last_run_id,sourcePath:i.source_path,sourceSha256:i.source_sha256,sourceSizeBytes:i.source_size_bytes,sourceRecordCount:i.source_record_count,targetDatabasePath:r.targetDatabasePath,targetTable:i.target_table,targetStoreKey:r.targetStoreKey===`shared`?`shared`:`primary`,archivePath:r.archivePath,...isStringRecord(r.expectedProfileSha256)?{expectedProfileSha256:r.expectedProfileSha256}:{},...typeof r.expectedStateSha256===`string`?{expectedStateSha256:r.expectedStateSha256}:{},completionStatus:r.completionStatus===`archived-unparsed`?`archived-unparsed`:`completed`,...e?{env:e}:{}};if(!fs.existsSync(o.sourcePath)&&!fs.existsSync(o.archivePath))throw new Error(`pending auth profile migration has neither source nor archive`);const s=fs.existsSync(o.sourcePath)?o.sourcePath:o.archivePath;const c=acquireFileLockSyncWithRetry(s);try{const e=fs.existsSync(o.sourcePath);if(a){o.sourceBytes=fs.readFileSync(o.archivePath);if(sha256Hex(o.sourceBytes)!==o.sourceSha256||e&&sha256Hex(fs.readFileSync(o.sourcePath))!==o.sourceSha256||!t?.(o))continue;if(!e)fs.linkSync(o.archivePath,o.sourcePath);updateAuthProfileMigrationReceipt(o,`retryable`,`completed`);n.push(`Reset an inconsistent completed auth migration receipt for retry.`);continue}const r=fs.readFileSync(e?o.sourcePath:o.archivePath);if(sha256Hex(r)!==o.sourceSha256){if(!e)throw new Error(`legacy auth archive verification failed`);updateAuthProfileMigrationReceipt(o,`superseded`,`imported`);n.push(`Retired an interrupted auth migration receipt for a changed source.`);continue}try{verifyAuthProfileMigrationTarget(o)}catch{let t=`retryable`;if(!e){if(restoreAuthProfileMigrationArchiveNoClobber(o)===`source-exists`){const e=fs.readFileSync(o.sourcePath);t=sha256Hex(e)===o.sourceSha256?`retryable`:`superseded`}}updateAuthProfileMigrationReceipt(o,t,`imported`);n.push(t===`retryable`?`Reset an interrupted auth migration receipt for retry.`:`Retired an interrupted auth migration receipt for a changed source.`);continue}archiveAuthProfileMigrationSource(o);updateAuthProfileMigrationReceipt(o,o.completionStatus??`completed`)}finally{c()}n.push(`Finalized interrupted auth profile archive -> ${o.archivePath}`)}return n}function archivePreviouslyMigratedAuthProfileSource(e){const t=withExistingOpenClawStateDatabaseReadOnly(({db:t})=>executeSqliteQueryTakeFirstSync(t,getNodeSqliteKysely(t).selectFrom(`migration_sources`).select(`status`).where(`source_key`,`=`,e.sourceKey)),{env:e.env});if(t?.status!==`completed`&&t?.status!==`archived-unparsed`)return null;const n=path.dirname(e.sourcePath);const r=`${path.basename(e.sourcePath)}.migrated-`;for(const t of fs.readdirSync(n,{withFileTypes:true})){if(!t.isFile()||!t.name.startsWith(r))continue;const i=path.join(n,t.name);try{if(sha256Hex(fs.readFileSync(i))!==e.sourceSha256)continue}catch{continue}assertAuthProfileMigrationSourcesUnchanged([e.sourcePath],[e]);fs.unlinkSync(e.sourcePath);return i}archiveAuthProfileMigrationSource(e);return e.archivePath}if(process.env.VITEST||false)globalThis[Symbol.for(`openclaw.authProfileMigrationReceiptsTestApi`)]={recordAuthProfileMigrationImported,restoreAuthProfileMigrationArchiveNoClobber};
//!src/commands/doctor/auth-alias-receipt.ts
const SOURCE_KEY=`auth-profile-sqlite-alias-map:v1`;const receiptSchema=object({format:literal(SOURCE_KEY),mappings:array(object({from:string(),to:string(),credentials:array(object({databasePath:string(),beforeSha256:string().nullable(),afterSha256:string(),beforeCanonicalFieldsSha256:string().optional(),afterCanonicalFieldsSha256:string().optional()})).min(1),sources:array(object({path:string(),sha256:string()})).optional()}))});function profiles(e){return isRecord(e)&&isRecord(e.profiles)?e.profiles:{}}function recordAuthAliasMigration(e){const t=readLegacyMigrationReceipt(SOURCE_KEY,e.env);const n=t?receiptSchema.parse(JSON.parse(t.reportJson)).mappings:[];if(e.importedProfileIds){for(const{from:t}of n)if(e.importedProfileIds.has(t)&&!e.profileIdMap.has(t))throw new Error(`Recorded auth account ${t} could not be verified; its import source was preserved.`)}const r=[];for(const[t,i]of e.profileIdMap){if(t===i)continue;const a=e.stores.flatMap(({databasePath:r,store:a,migratedStore:o})=>{const s=profiles(a);const c=s[t];const l=profiles(o)[i];const u=c??s[i];const d=n.filter(e=>e.from===t&&e.to===i).flatMap(e=>e.credentials).find(e=>e.databasePath===r&&u!==void 0&&(c===void 0?[e.afterSha256,e.afterCanonicalFieldsSha256]:[e.beforeSha256,e.beforeCanonicalFieldsSha256]).includes(digestAuthProfileMigrationValue(u)));if(l===void 0||c===void 0&&!d&&!(e.importedProfileIds?.has(t)&&e.sources?.length))return[];if(e.importedProfileIds?.has(t)&&c!==void 0&&(!isRecord(c)||!isRecord(l)||digestAuthProfileMigrationValue({...c,provider:l.provider})!==digestAuthProfileMigrationValue(l)))throw new Error(`Legacy auth input conflicts with the existing account ${t}; its source was preserved.`);if(d){if(c===void 0&&(!isRecord(u)||digestAuthProfileMigrationValue(normalizeLegacyCredentialFields(u))!==digestAuthProfileMigrationValue(l)))throw new Error(`Recorded auth account ${t} changed during migration; its source was preserved.`);return[{...d,...c!==void 0?{beforeCanonicalFieldsSha256:digestAuthProfileMigrationValue(c)}:{},afterCanonicalFieldsSha256:digestAuthProfileMigrationValue(l)}]}return[{databasePath:r,beforeSha256:c===void 0?null:digestAuthProfileMigrationValue(c),afterSha256:digestAuthProfileMigrationValue(l)}]});if(a.length>0)r.push({from:t,to:i,credentials:a,...e.sources?.length?{sources:[...e.sources]}:{}})}if(r.length===0&&(!t||!e.normalizeCredentialFields))return t?.sourceSha256??void 0;return runOpenClawStateWriteTransaction(({db:t,path:n})=>{const i=readLegacyMigrationReceiptFromDatabase(t,SOURCE_KEY);const a=i?receiptSchema.parse(JSON.parse(i.reportJson)).mappings:[];const o=new Map(e.normalizeCredentialFields?[]:a.map(e=>[digestAuthProfileMigrationValue(e),e]));for(const t of e.normalizeCredentialFields?a:[]){for(const n of t.credentials){const r=e.stores.find(e=>e.databasePath===n.databasePath);if(!r)continue;const i=profiles(r.store);const a=profiles(r.migratedStore);for(const[e,r,o]of[[t.from,`beforeSha256`,`beforeCanonicalFieldsSha256`],[t.to,`afterSha256`,`afterCanonicalFieldsSha256`]]){const t=i[e];if(isRecord(t)&&a[e]!==void 0&&[n[r],n[o]].includes(digestAuthProfileMigrationValue(t))&&digestAuthProfileMigrationValue(normalizeLegacyCredentialFields(t))===digestAuthProfileMigrationValue(a[e]))n[o]=digestAuthProfileMigrationValue(a[e])}}o.set(digestAuthProfileMigrationValue(t),t)}for(const e of r)o.set(digestAuthProfileMigrationValue(e),e);const s={format:SOURCE_KEY,mappings:[...o.values()]};const c=JSON.stringify(s);const l=digestAuthProfileMigrationValue(s);if(i?.sourceSha256===l&&i.reportJson===c)return l;recordLegacyMigrationReceipt(t,{sourceKey:SOURCE_KEY,migrationKind:`auth-profile-sqlite-alias-map`,sourcePath:n,targetTable:`migration_sources`,sourceSha256:l,sourceSizeBytes:null,sourceRecordCount:s.mappings.length,runId:`${SOURCE_KEY}:${l}`,now:Date.now(),reportJson:c,upsert:true});return l},{env:e.env})}function runWithAuthAliasMigrationReceipt(e,t,n){if(e===void 0)return n();return runOpenClawStateWriteTransaction(t=>{if(readLegacyMigrationReceiptFromDatabase(t.db,SOURCE_KEY)?.sourceSha256!==e)throw new Error(`Auth alias migration receipt changed before repair; rerun Doctor.`);return n(t)},{env:t})}function recoverAuthAliasMigration(e){const t=/* @__PURE__ */ new Map;const n=/* @__PURE__ */ new Set;const r=readLegacyMigrationReceipt(SOURCE_KEY,e.env);if(!r)return{recovered:t,blocked:n};const i=receiptSchema.parse(JSON.parse(r.reportJson));const a=new Map(e.stores.map(e=>[e.databasePath,profiles(e.store)]));const o=/* @__PURE__ */ new Map;for(const t of i.mappings){const n=t.sources?.map(e=>e.path)??[];const r=n.length>0&&n.every(e=>!fs.existsSync(e));let s;if(r){const n=e.archivedMappings?.get(t.from);const r=i.mappings.filter(e=>e.from===t.from&&e.to===t.to).flatMap(e=>e.sources??[]);const o=new Set(n?.origins.filter(e=>r.some(t=>t.path===e.sourcePath&&t.sha256===e.sourceSha256)).map(e=>e.databasePath));s=n?.profileId===t.to&&o.size>0&&[...a].every(([e,n])=>n[t.from]===void 0&&(n[t.to]===void 0||o.has(e)))}else s=t.credentials.every(e=>{const n=a.get(e.databasePath);if(!n)return false;const r=n[t.from];const i=n[t.to];return r!==void 0&&i===void 0&&[e.beforeSha256,e.beforeCanonicalFieldsSha256].includes(digestAuthProfileMigrationValue(r))||r===void 0&&i!==void 0&&[e.afterSha256,e.afterCanonicalFieldsSha256].includes(digestAuthProfileMigrationValue(i))||r===void 0&&i===void 0&&e.beforeSha256===null&&t.sources!==void 0&&t.sources.length>0&&t.sources.every(e=>{try{return createHash(`sha256`).update(fs.readFileSync(e.path)).digest(`hex`)===e.sha256}catch(e){if(isRecord(e)&&e.code===`ENOENT`)return false;throw e}})})&&[...a].every(([e,n])=>t.credentials.some(t=>t.databasePath===e)||n[t.from]===void 0&&n[t.to]===void 0);if(s){const e=o.get(t.from)??/* @__PURE__ */ new Set;e.add(t.to);o.set(t.from,e)}}for(const e of new Set(i.mappings.map(e=>e.from))){const r=o.get(e);if(r?.size===1)for(const n of r)t.set(e,n);else n.add(e)}return{recovered:t,blocked:n}}
//!src/commands/doctor/auth-alias-transforms.ts
const LEGACY_OPENAI_CODEX_PROVIDER_ID=`openai-codex`;function isLegacyOpenAICodexProvider(e){return typeof e===`string`&&e.trim().toLowerCase()===LEGACY_OPENAI_CODEX_PROVIDER_ID}function isLegacyOpenAICodexProfileId(e){return e.trim().toLowerCase().startsWith(`${LEGACY_OPENAI_CODEX_PROVIDER_ID}:`)}function canonicalLegacyAuthProvider(e){const t=e.trim().toLowerCase();if(isLegacyOpenAICodexProvider(t))return OPENAI_PROVIDER_ID;const n=resolveLegacyRuntimeModelProviderAlias(t);return n?.legacyProvider===t?n.provider:t}function legacyAuthProfileTarget(e){if(e===`openai:codex-cli`)return{provider:OPENAI_PROVIDER_ID,suffix:`default`};const t=e.indexOf(`:`);if(t<=0)return null;const n=e.slice(0,t).trim().toLowerCase();const r=canonicalLegacyAuthProvider(n);return r===n?null:{provider:r,suffix:e.slice(t+1).trim()||`default`}}function isLegacyAuthProfileId(e){return legacyAuthProfileTarget(e)!==null}function collectRawAuthRotationProfileIds(e){if(!isRecord(e))return[];const t=[];for(const n of[`order`,`lastGood`,`usageStats`]){const r=e[n];if(!isRecord(r))continue;if(n===`usageStats`){t.push(...Object.keys(r));continue}for(const e of Object.values(r))for(const n of Array.isArray(e)?e:[e])if(typeof n===`string`)t.push(n)}return t}function isReadableAuthAliasState(e){if(!isRecord(e))return false;const readableEntries=(e,t)=>e===void 0||isRecord(e)&&Object.values(e).every(t);return readableEntries(e.order,e=>Array.isArray(e)&&e.every(e=>typeof e===`string`))&&readableEntries(e.lastGood,e=>typeof e===`string`)&&readableEntries(e.usageStats,isRecord)}function isReadableAuthAliasStore(e){if(!isRecord(e)||!isRecord(e.profiles)||!isReadableAuthAliasState(e))return false;return Object.values(e.profiles).every(e=>parseLegacyCredentialEntry(e)!==null)}function allocateLegacyAuthProfileId(e,t){const n=legacyAuthProfileTarget(e);if(!n)throw new Error(`Not a retired auth profile id: ${e}`);const{provider:r,suffix:i}=n;let a=`${r}:${i}`;const o=`${r}:${isLegacyOpenAICodexProfileId(e)?`chatgpt`:`cli`}-${i}`;for(let e=1;t.has(a);e+=1)a=e===1?o:`${o}-${e}`;t.add(a);return a}function canonicalizeLegacyAuthProfileEntries(e,t){const n=new Set(Object.keys(e).filter(e=>!isLegacyAuthProfileId(e)));const r=new Set(t?.profileIdMap?.values()??[]);const i=/* @__PURE__ */ new Map;let a=false;for(const[o,s]of Object.entries(e)){if(!isRecord(s))continue;const c=legacyAuthProfileTarget(o);const l=c!==null;const u=typeof s.provider===`string`?canonicalLegacyAuthProvider(s.provider):c?.provider;const d=typeof s.provider===`string`&&u!==s.provider.trim().toLowerCase();if(!l&&!d)continue;if(c&&u!==c.provider)continue;if(t?.preserveUnmappedLegacyIds&&!t.profileIdMap?.has(o))continue;const f=t?.profileIdMap?.get(o);const p=f&&!n.has(f)?f:l?allocateLegacyAuthProfileId(o,/* @__PURE__ */ new Set([...n,...r])):o;n.add(p);const m={...s,provider:u};if(p!==o){delete e[o];i.set(o,p)}e[p]=m;a=true}return{profileIdMap:i,changed:a}}function canonicalizeLegacyAuthOrder(e,t,n){if(!isRecord(e.order))return false;const r=e.order;const i={...r};const a=/* @__PURE__ */ new Set([...Object.values(r).flatMap(e=>Array.isArray(e)?e.filter(e=>typeof e===`string`&&!isLegacyAuthProfileId(e)):[]),...t.values()]);const unresolved=e=>typeof e!==`string`||Boolean(n?.preserveUnmappedLegacyIds&&!t.has(e));const rewrite=e=>{if(typeof e!==`string`)return e;const r=t.get(e);if(r)return r;if(!isLegacyAuthProfileId(e)||n?.preserveUnmappedLegacyIds)return e;const i=allocateLegacyAuthProfileId(e,a);t.set(e,i);return i};const o=/* @__PURE__ */ new Map;for(const e of Object.keys(r)){const t=canonicalLegacyAuthProvider(e);if(t!==e&&Array.isArray(r[e])){const n=o.get(t)??[];n.push(e);o.set(t,n)}}const s=new Set([...o.values()].flat());for(const[e,t]of Object.entries(r))if(Array.isArray(t)&&!s.has(e))r[e]=t.map(rewrite);for(const[e,t]of o){const n=r[e];if(n!==void 0&&!Array.isArray(n))continue;const i=[];let a=false;for(const e of t){const t=r[e];if(!Array.isArray(t))continue;const n=t.filter(unresolved);const o=t.filter(e=>!unresolved(e));if(o.length>0||t.length===0){a=true;i.push(...o.map(rewrite))}if(n.length>0)r[e]=n;else delete r[e]}if(a){const t=Array.isArray(n)&&n.length===0?[]:[...i,...n??[]];r[e]=[...new Set(t)]}}return!isDeepStrictEqual(i,r)}function canonicalizeLegacyAuthLastGood(e,t,n){const r={...e};for(const[i,a]of Object.entries(r)){const o=canonicalLegacyAuthProvider(i);const s=typeof a===`string`?t.get(a):void 0;if(o!==i&&n?.preserveUnmappedLegacyIds&&s===void 0)continue;if(o!==i){delete e[i];if(Object.hasOwn(r,o))continue}e[o]=s??a}return!isDeepStrictEqual(r,e)}function canonicalizeLegacyAuthStore(e,t,n){if(!isRecord(e)||!isRecord(e.profiles)){if(isRecord(t))canonicalizeLegacyAuthRotationState(t,new Map(n));return null}const r=canonicalizeLegacyAuthProfileEntries(e.profiles,{profileIdMap:n,preserveUnmappedLegacyIds:true});const i=new Map([...n,...r.profileIdMap]);const a=canonicalizeLegacyAuthRotationState(e,i);if(isRecord(t))canonicalizeLegacyAuthRotationState(t,i);return r.changed||a?r.profileIdMap.size:null}function canonicalizeLegacyAuthRotationState(e,t){const n={preserveUnmappedLegacyIds:true};const r=canonicalizeLegacyAuthOrder(e,t,n);let i=false;if(isRecord(e.usageStats)){const n=e.usageStats;for(const[e,r]of Object.entries(n)){const a=t.get(e);if(a&&a!==e){delete n[e];n[a]=r;i=true}}}const a=isRecord(e.lastGood)?canonicalizeLegacyAuthLastGood(e.lastGood,t,n):false;return r||i||a}
//!src/commands/doctor/auth-legacy-config-coercion.ts
function isSafeLegacyProviderKey(e){return e.trim().length>0&&!isBlockedObjectKey(e)}function extractProviderPrefix(e,t){const n=e.indexOf(t);return n>0?readNonBlankString(e.slice(0,n)):void 0}function extractProviderFromModelRef(e){return extractProviderPrefix(splitTrailingAuthProfile(e).model,`/`)}function collectLegacyConfigAuthProfileProviderHints(e){const t=/* @__PURE__ */ new Map;const addHint=(e,n)=>{const r=t.get(e);t.set(e,r===void 0||r===n?n:null)};const addModelHints=e=>{if(!isRecord(e))return;for(const[t,n]of Object.entries(e)){const e=extractProviderFromModelRef(t);if(!e||!isSafeLegacyProviderKey(e)||!isRecord(n))continue;const r=isRecord(n.agentRuntime)?n.agentRuntime:null;const i=r?readNonBlankString(r.authProfileId):void 0;if(i)addHint(i,e)}};for(const{value:t}of collectConfiguredModelRefs(e)){const{profile:e}=splitTrailingAuthProfile(t);const n=extractProviderFromModelRef(t);if(e&&n&&isSafeLegacyProviderKey(n))addHint(e,n)}const n=e;const r=isRecord(n.auth)?n.auth:null;const i=r&&isRecord(r.order)?r.order:null;if(i)for(const[e,t]of Object.entries(i)){if(!isSafeLegacyProviderKey(e)||!Array.isArray(t))continue;for(const n of t){const t=readNonBlankString(n);if(t)addHint(t,e)}}const a=isRecord(n.agents)?n.agents:null;addModelHints((a&&isRecord(a.defaults)?a.defaults:null)?.models);for(const t of listAgentEntries(e))addModelHints(t.models);return t}function coerceLegacyFlatAuthProfileStore(e){if(!isRecord(e)||`profiles`in e)return null;const t={version:1,profiles:{}};for(const[n,r]of Object.entries(e)){const e=n.trim();if(!isSafeLegacyProviderKey(e))continue;const i=coerceLegacyFlatCredential(e,r);if(!i)continue;t.profiles[`${e}:default`]=i}return Object.keys(t.profiles).length>0?t:null}const CONFIG_AUTH_VALUE_FIELDS={api_key:[`key`,`apiKey`,`api_key`],token:[`token`]};function readConfigAuthAlias(e,t,n){for(const r of t){const t=n(e[r]);if(t!=null)return t}}function inferLegacyConfigAuthProfileMode(e){const t=readNonBlankString(e.mode)??readNonBlankString(e.type);if(t===`api_key`||t===`token`||t===`oauth`)return t;for(const t of[`api_key`,`token`]){const n=CONFIG_AUTH_VALUE_FIELDS[t];if(readConfigAuthAlias(e,n,readNonBlankString)||readConfigAuthAlias(e,[`${n[0]}Ref`,...n],coerceSecretRef))return t}if(readNonBlankString(e.access)&&readNonBlankString(e.refresh)&&typeof e.expires===`number`)return`oauth`}function coerceLegacyConfigAuthProfileStore(e){const t=e;const n=isRecord(t.auth)?t.auth:null;const r=n&&isRecord(n.profiles)?n.profiles:null;if(!r)return null;const i=collectLegacyConfigAuthProfileProviderHints(e);const a={version:1,profiles:{}};for(const[e,t]of Object.entries(r)){if(!isRecord(t))continue;const n=inferLegacyConfigAuthProfileMode(t);if(!n)continue;const r=readNonBlankString(t.provider)??extractProviderPrefix(e,`:`)??i.get(e);if(!r||!isSafeLegacyProviderKey(r))continue;const o={...t,provider:r,mode:n};if(n===`api_key`||n===`token`){const e=CONFIG_AUTH_VALUE_FIELDS[n];const r=e[0];const i=`${r}Ref`;const a=readConfigAuthAlias(t,[i,...e],coerceSecretRef);const s=readConfigAuthAlias(t,e,readNonBlankString);if(a){o[i]=a;for(const t of e)delete o[t]}else if(s){o[r]=s;delete o[i]}else continue}else if(!readNonBlankString(t.access)||!readNonBlankString(t.refresh)||typeof t.expires!==`number`)continue;a.profiles[e]=o}const o=coerceLegacyAuthProfileStore(a);return o&&Object.keys(o.profiles).length>0?o:null}
//!src/commands/doctor/shared/legacy-oauth-sidecar.ts
const LEGACY_OAUTH_SECRET_DIRNAME=`auth-profiles`;const LEGACY_OAUTH_SECRET_VERSION=1;const LEGACY_OAUTH_SECRET_ALGORITHM=`aes-256-gcm`;const LEGACY_OAUTH_SECRET_KEYCHAIN_SERVICE=`OpenClaw Auth Profile Secrets`;const LEGACY_OAUTH_SECRET_KEYCHAIN_ACCOUNT=`oauth-profile-master-key`;const LEGACY_OAUTH_SECRET_KEY_FILE_NAME=`auth-profile-secret-key`;function resolveLegacyOAuthSidecarPath(e,t=process.env){return path.join(resolveOAuthDir(t),LEGACY_OAUTH_SECRET_DIRNAME,`${e.id}.json`)}function normalizeLegacyOAuthSecretMaterial(e){if(!isRecord(e))return null;const t={...readNonBlankString(e.access)?{access:readNonBlankString(e.access)}:{},...readNonBlankString(e.refresh)?{refresh:readNonBlankString(e.refresh)}:{},...readNonBlankString(e.idToken)?{idToken:readNonBlankString(e.idToken)}:{}};return Object.keys(t).length>0?t:null}function coerceLegacyOAuthEncryptedPayload(e){if(!isRecord(e))return null;return e.algorithm===LEGACY_OAUTH_SECRET_ALGORITHM&&typeof e.iv===`string`&&typeof e.tag===`string`&&typeof e.ciphertext===`string`?{algorithm:e.algorithm,iv:e.iv,tag:e.tag,ciphertext:e.ciphertext}:null}function uniquePaths(e){return uniqueStrings(e.filter(e=>Boolean(e)))}function resolveLegacyOAuthSecretKeyFileCandidates(e){const t=(process.platform===`win32`?e.USERPROFILE:e.HOME)?.trim()||os.homedir();let n;let r=`OpenClaw`;if(process.platform===`win32`)n=e.APPDATA?.trim()||(t?path.join(t,`AppData`,`Roaming`):void 0);else if(process.platform===`darwin`)n=t?path.join(t,`Library`,`Application Support`):void 0;else{n=e.XDG_CONFIG_HOME?.trim()||(t?path.join(t,`.config`):void 0);r=`openclaw`}return uniquePaths([n?path.join(n,r,LEGACY_OAUTH_SECRET_KEY_FILE_NAME):void 0,t?path.join(t,`.openclaw-auth-profile-secrets`,LEGACY_OAUTH_SECRET_KEY_FILE_NAME):void 0])}function resolveLegacyOAuthSecretKeyFiles(e){const t=resolveStateDir(e);return resolveLegacyOAuthSecretKeyFileCandidates(e).filter(e=>!isPathInside(t,e))}function readLegacyMacOAuthSecretKeychainKey(e){if(process.platform!==`darwin`||e.allowKeychainPrompt===false||e.env.VITEST===`true`||e.env.VITEST_WORKER_ID!==void 0)return;try{return childProcess$1.execFileSync(`security`,[`find-generic-password`,`-s`,LEGACY_OAUTH_SECRET_KEYCHAIN_SERVICE,`-a`,LEGACY_OAUTH_SECRET_KEYCHAIN_ACCOUNT,`-w`],{encoding:`utf8`,timeout:5e3,stdio:[`pipe`,`pipe`,`pipe`]}).trim()}catch{return}}function loadLegacyOAuthSidecarMaterial(e){const t=e.env??process.env;const n=e.raw;if(!isRecord(n))return null;if(n.version!==LEGACY_OAUTH_SECRET_VERSION||n.profileId!==e.profileId||n.provider!==e.provider)return null;const r=coerceLegacyOAuthEncryptedPayload(n.encrypted);if(r){const decryptLegacyOAuthSecretMaterialWithSeed=t=>{let n;try{const i=createDecipheriv(LEGACY_OAUTH_SECRET_ALGORITHM,hash(`sha256`,`openclaw:auth-profile-oauth:${t}`,`buffer`),Buffer.from(r.iv,`base64url`));i.setAAD(Buffer.from(`${e.ref.id}\0${e.profileId}\0${e.provider}`,`utf8`));i.setAuthTag(Buffer.from(r.tag,`base64url`));n=Buffer.concat([i.update(Buffer.from(r.ciphertext,`base64url`)),i.final()])}catch{return null}const i=decodeUtf8Input(n,`Decrypted legacy OAuth sidecar`);try{return normalizeLegacyOAuthSecretMaterial(JSON.parse(i))}catch{return null}};const n=normalizeUniqueTrimmedStringList(resolveLegacyOAuthSecretKeyFiles(t).flatMap(e=>{let t;try{t=fs.readFileSync(e)}catch{return[]}return[decodeUtf8Input(t,`Legacy OAuth key ${e}`)]}));for(const e of n){const t=decryptLegacyOAuthSecretMaterialWithSeed(e);if(t)return t}const i=readLegacyMacOAuthSecretKeychainKey({allowKeychainPrompt:e.allowKeychainPrompt,env:t});if(i&&!n.includes(i))return decryptLegacyOAuthSecretMaterialWithSeed(i);return null}return normalizeLegacyOAuthSecretMaterial(n)}function collectUnresolvedLegacyOAuthSidecarProfileIds(e){if(!isRecord(e)||!isRecord(e.profiles))return[];const t=[];for(const[n,r]of Object.entries(e.profiles)){if(!isRecord(r)||r.type!==`oauth`||!isRecord(r.oauthRef))continue;if(readNonBlankString(r.oauthRef.id)&&readNonBlankString(r.oauthRef.provider)&&(!readNonBlankString(r.access)||!readNonBlankString(r.refresh)))t.push(n)}return t}function prepareLegacyOAuthSidecarImport(e){const{rawStore:t,env:n,oauthEnv:r,targetDatabasePath:i,targetStoreKey:a,now:o}=e;const s=[];if(isRecord(t)&&isRecord(t.profiles))for(const[e,c]of Object.entries(t.profiles)){if(!isRecord(c)||c.type!==`oauth`||!isLegacyOAuthRef(c.oauthRef)||c.provider!==c.oauthRef.provider)continue;const t=resolveLegacyOAuthSidecarPath(c.oauthRef,r);if(!fs.existsSync(t))throw new Error(`Legacy OAuth sidecar is missing at ${t}. Restore that file or correct OPENCLAW_OAUTH_DIR, then rerun openclaw doctor --fix. The auth source remains unchanged for retry.`);const l=prepareAuthProfileSourceReceipt({pathname:t,targetDatabasePath:i,targetTable:a===`shared`?`auth_profile_stores`:`auth_profile_store`,targetStoreKey:a,now:o,env:n});const u=loadLegacyOAuthSidecarMaterial({profileId:e,provider:c.provider,ref:c.oauthRef,env:r,raw:parseAuthProfileMigrationSource(l),allowKeychainPrompt:process.stdin.isTTY});if(u){delete c.oauthRef;Object.assign(c,u)}s.push(l)}return s}function parseLegacyOAuthFile(e){const t=isRecord(e)?coerceLegacyAuthStore(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,isRecord(t)?{...t,type:`oauth`,provider:e}:t]))):null;return{store:t,rejectedEntries:isRecord(e)?Object.keys(e).length-Object.keys(t??{}).length:e===void 0?0:1}}function finalizeLegacyOAuthSidecarImports(e){const{cfg:t,env:n,receipts:r}=e;const i=[];const a=[];const o=new Set(listReferencedLegacyOAuthSidecarPaths(n,t));for(const e of r){if(o.has(e.sourcePath))continue;const t=acquireAuthProfileMigrationSourceLocks([e.sourcePath]);try{finalizeAuthProfileMigrationSource(e);i.push(`Archived legacy OAuth sidecar -> ${shortenHomePath(e.archivePath)}.`)}catch(t){a.push(`Could not archive legacy OAuth sidecar ${shortenHomePath(e.sourcePath)}: ${String(t)}`)}finally{t()}}return{changes:i,warnings:a}}
//!src/commands/doctor-auth-flat-profiles.ts
function resolveMigrationTargetDatabasePath(e,t=process.env){return e?resolveAuthProfileDatabasePath(e):resolveNativeSharedAuthStorePath(t)}function listAuthProfileMigrationTargets(e,t){const n=/* @__PURE__ */ new Map([[resolveNativeSharedAuthStorePath(t),void 0]]);for(const r of[resolveSharedMainAuthAgentDir(t),...e.flatMap(e=>e.agentDir?[e.agentDir]:[])]){const e=resolveAuthProfileDatabasePath(r);if(!n.has(e))n.set(e,r)}return n}var AuthProfileMigrationVerificationError=class extends Error{constructor(e){super(`auth profile SQLite verification failed`);this.detail=e;this.name=`AuthProfileMigrationVerificationError`}};function listAuthProfileSqliteMigrationCandidates(e,t){return listAuthProfileRepairCandidates(e,t).map(e=>({agentDir:e.agentDir,authPath:e.authPath,statePath:resolveLegacyAuthStatePath(path.dirname(e.authPath)),legacyPath:resolveLegacyFlatAuthPath(path.dirname(e.authPath))}))}function hasAuthProfileState(e){return Boolean(e.order||e.lastGood||e.usageStats)}function collectAuthProfileStateProfileIds(e){return[.../* @__PURE__ */ new Set([...Object.values(e.order??{}).flat(),...Object.values(e.lastGood??{}),...Object.keys(e.usageStats??{})])]}function collectAuthOwnerProfileIds(e,t){const n=isRecord(e)&&isRecord(e.profiles)?e.profiles:{};return/* @__PURE__ */ new Set([...Object.keys(n),...collectRawAuthRotationProfileIds(e),...collectRawAuthRotationProfileIds(t)])}function isDefaultAgentCandidate(e,t,n){return e.agentDir===void 0||path.resolve(e.agentDir)===path.resolve(resolveLegacyInheritedAuthAgentDir(t,n))}function mergeImportedAuthProfiles(e){const t={...e.store.profiles};for(const[n,r]of Object.entries(e.profiles)){const i=t[n];if(!e.existingProfileIds.has(n)||e.replaceExistingWithoutCredential&&i&&!hasUsableAuthProfileCredential(i)&&hasUsableAuthProfileCredential(r))t[n]=r}return{...e.store,profiles:t}}function mergeImportedAuthProfileState(e){const t={...e.store};for(const n of[`order`,`lastGood`,`usageStats`]){const r=e.state[n];if(!r)continue;const i=e.existingState[n]??{};Object.assign(t,{[n]:{...e.store[n],...Object.fromEntries(Object.entries(r).filter(([e])=>!Object.hasOwn(i,e)))}})}return t}function formatMissingAuthProfileSqliteVerification(e){const t=[...e.importedProfileIds].filter(t=>!e.loaded?.profiles[t]);const n=[];for(const t of[`order`,`lastGood`])for(const[r,i]of Object.entries(e.expected[t]??{}))if(!isDeepStrictEqual(e.loaded?.[t]?.[r],i))n.push(`${t}.${r}`);for(const t of Object.keys(e.expected.usageStats??{}))if(!e.loaded?.usageStats?.[t])n.push(`usageStats.${t}`);const r=[];if(t.length>0)r.push(`imported profile(s): ${t.toSorted().join(`, `)}`);if(n.length>0)r.push(`auth state field(s): ${n.toSorted().join(`, `)}`);return r.length>0?r.join(`; `):null}function hasImportableAuthProfileStore(e){return Boolean(e&&(Object.keys(e.profiles).length>0||hasAuthProfileState(e)))}function loadAuthProfileMigrationTargetStore(e,t,n=process.env){const r=e===void 0&&t===void 0;const i=r?inspectPersistedSharedAuthProfileStoreRaw(n):inspectPersistedAuthProfileStoreRaw(e,t);const a=r?loadPersistedSharedAuthProfileStore(n):loadPersistedAuthProfileStore(e,t?{database:t}:void 0);if(a)return a;if(i.status!==`missing`)throw new Error(`current auth profile store is unreadable; legacy source left in place`);if((r?inspectPersistedSharedAuthProfileStateRaw(n):inspectPersistedAuthProfileStateRaw(e,t)).status===`unreadable`)throw new Error(`current auth profile state is unreadable; legacy source left in place`);return{version:1,profiles:{},...coerceAuthProfileState(r?readPersistedSharedAuthProfileStateRaw(n):readPersistedAuthProfileStateRaw(e,t))}}async function maybeMigrateAuthProfileJsonStoresToSqlite(e){const t=e.now??Date.now;const n=e.env??process.env;const r=listAuthProfileSqliteMigrationCandidates(e.cfg,n);const i=createConfigRuntimeEnv(e.cfg,n);const a=resolveLegacyOAuthPath(i);const o=/* @__PURE__ */ new Set;let s=false;const recoverCompleted=e=>{const t=r.find(t=>[t.authPath,t.legacyPath].includes(e.sourcePath));if(!t)return false;const i=parseAuthProfileMigrationSource(e);normalizeLegacyAuthProfileFields(i);const a=coerceLegacyAuthProfileStore(i)??coerceLegacyFlatAuthProfileStore(i);if(!a||!Object.values(a.profiles).some(hasUsableAuthProfileCredential))return false;const c=t.agentDir?inspectPersistedAuthProfileStoreRaw(t.agentDir):inspectPersistedSharedAuthProfileStoreRaw(n);const l=c.status===`missing`?{profiles:{}}:c.status===`readable`?c.raw:null;if(!isRecord(l)||!isRecord(l.profiles))return false;const u=l.profiles;if(Object.entries(a.profiles).some(([e,t])=>Object.hasOwn(u,e)||(isLegacyOpenAICodexProfileId(e)||isLegacyOpenAICodexProvider(t.provider))&&Object.entries(u).some(([e,t])=>e.startsWith(`openai:`)||isRecord(t)&&t.provider===`openai`)))return false;o.add(e.sourcePath);return s};const c=[];const l=[];const u=createAuthMigrationWarningRecorder(c,l);const d=/* @__PURE__ */ new Set;const f=/* @__PURE__ */ new Set;const resume=()=>{try{return resumePendingAuthProfileMigrationArchives(n,recoverCompleted)}catch(t){e.openAICodexAuthProfileIdMap?.forEach((e,t)=>f.add(t));u(`Could not finalize an interrupted auth profile archive; legacy sources were left for recovery: ${String(t)}`,`archive-finalization`,`Keep the retained sources and archives. Check the reported filesystem error and access permissions, then rerun openclaw doctor --fix to finish archival. Verify current auth separately with openclaw models status.`,void 0,`historical`);return[]}};const p=resume();const m=coerceLegacyConfigAuthProfileStore(e.cfg);const candidateSources=t=>[t.authPath,t.statePath,t.legacyPath,...isDefaultAgentCandidate(t,e.cfg,n)?[a]:[]].filter(r=>fs.existsSync(r)||o.has(r)||m&&isDefaultAgentCandidate(t,e.cfg,n)&&r===t.authPath);const h=r.filter(e=>candidateSources(e).length>0);const g={detected:h.flatMap(candidateSources),changes:p,migratedProfileIds:d,blockedProfileIds:f,warnings:c,findings:l,aliasFindings:[]};if(c.length>0)return g;if(h.length===0)return g;note([...h.map(e=>{const t=fs.existsSync(e.authPath)||fs.existsSync(e.legacyPath);const n=readLegacyAuthProfileProviders([{kind:`auth-profiles`,path:e.authPath},...fs.existsSync(e.legacyPath)?[{kind:`legacy-auth`,path:e.legacyPath}]:[]]);return`- ${shortenHomePath(e.authPath)} / ${shortenHomePath(e.statePath)}${t?` (affected providers: ${n?.join(`, `)??`unknown; provider scope unavailable`})`:``}`}),`- ${formatCliCommand(`openclaw doctor --fix`)} imports legacy auth profile JSON into SQLite, verifies it, records a receipt, and archives the original bytes.`].join(`
`),`Auth profile SQLite migration`);if(!await e.prompter.confirmAutoFix({message:`Migrate auth profile JSON files into SQLite now?`,initialValue:true}))return g;if(o.size>0){s=true;const e=c.length;g.changes.push(...resume());if(c.length>e)return g}const _=e.openAICodexAuthProfileIdMap??collectOpenAICodexAuthProfileStoreIdMap({cfg:e.cfg,env:n});const v=await maybeRepairLegacyAuthProfileStores({cfg:e.cfg,env:n,profileIdMap:_,renameProfileIds:false});g.changes.push(...v.changes);c.push(...v.warnings);g.aliasFindings=v.findings;const y=v.profileIdMap;for(const[e,t]of _)if(y.get(e)!==t){f.add(e);f.add(t)}const b=listReferencedLegacyOAuthSidecarPaths(n,e.cfg);const x=/* @__PURE__ */ new Map;for(const r of h){const o=isDefaultAgentCandidate(r,e.cfg,n);const s=/* @__PURE__ */ new Set;let c=false;let l;try{const f=[r.authPath,r.statePath,r.legacyPath,...o?[a]:[]];for(const e of f)fs.mkdirSync(path.dirname(e),{recursive:true});l=acquireAuthProfileMigrationSourceLocks([...f,...b]);const p=resolveMigrationTargetDatabasePath(r.agentDir,n);const h=r.agentDir===void 0&&prepareSharedAuthStoreOwnershipForNative(n).location===`state-db`;const _=h||r.agentDir!==void 0?r.agentDir:resolveSharedMainAuthAgentDir(n);let v=f.filter(fs.existsSync).map(e=>prepareAuthProfileSourceReceipt({pathname:e,targetDatabasePath:p,targetTable:e===r.statePath?`auth_profile_state`:h?`auth_profile_stores`:`auth_profile_store`,targetStoreKey:h?`shared`:`primary`,now:t,env:n}));v=v.filter(e=>{const t=archivePreviouslyMigratedAuthProfileSource(e);if(!t)return true;g.changes.push(`Preserved a previously migrated legacy auth source without replaying credentials (${shortenHomePath(t)}).`);return false});assertAuthProfileMigrationSourcesUnchanged(f,v);if(v.length===0&&!m)continue;const S=new Map(v.map(e=>[e.sourcePath,e]));const C=parseAuthProfileMigrationSource(S.get(path.resolve(r.authPath)));const w=prepareLegacyOAuthSidecarImport({rawStore:C,env:n,oauthEnv:i,targetDatabasePath:p,targetStoreKey:h?`shared`:`primary`,now:t});const T=new Set(isRecord(C)&&isRecord(C.profiles)?Object.keys(C.profiles):[]);const E=parseAuthProfileMigrationSource(S.get(path.resolve(r.statePath)));for(const e of[...T,...collectRawAuthRotationProfileIds(C),...collectRawAuthRotationProfileIds(E),...o&&m?Object.keys(m.profiles):[]])s.add(e);const D=canonicalizeLegacyAuthStore(C,E,y);const O=new Set(collectUnresolvedLegacyOAuthSidecarProfileIds(C));const k=O.size>0?`Migrated ${O.size} legacy OAuth sidecar profile${O.size===1?``:`s`} from ${shortenHomePath(r.authPath)} into SQLite as configured-unavailable without credentials (archives: ${[...v,...w].map(e=>shortenHomePath(e.archivePath)).join(`, `)}). Doctor could not recover credentials using the historical key files (${resolveLegacyOAuthSecretKeyFiles(i).map(e=>shortenHomePath(e)).join(`, `)}) or macOS Keychain. The archives preserve the original material; sign in again with ${formatCliCommand(`openclaw models auth login --provider openai`)}.`:void 0;const A=isRecord(C)&&isRecord(C.profiles)?C.profiles:void 0;const j=A?readAwsSdkAuthProfileMarkers(r):null;if(A&&j)for(const{profileId:e}of j)delete A[e];const M=normalizeLegacyAuthProfileFields(C);const N=coerceLegacyAuthProfileStore(C)??coerceLegacyFlatAuthProfileStore(C)??null;const P=hasImportableAuthProfileStore(N)?N:null;const F=m&&o?structuredClone(m):null;if(F){Object.keys(F.profiles).forEach(e=>T.add(e));canonicalizeLegacyAuthStore(F,null,y)}const I=S.get(path.resolve(a));const{store:L,rejectedEntries:R}=parseLegacyOAuthFile(I?parseAuthProfileMigrationSource(I):void 0);const z={...L,...coerceLegacyAuthStore(parseAuthProfileMigrationSource(S.get(path.resolve(r.legacyPath))))};const B=Object.keys(z).length>0;const V=coerceAuthProfileState(E);if(!P&&!F&&!B&&!hasAuthProfileState(V)&&!j){if(v.length>0){const e=v.map(e=>{finalizeAuthProfileMigrationSource(e,`archived-unparsed`);return e.archivePath});u(k??`Archived unparseable auth profile input without import for ${shortenHomePath(r.authPath)} (${e.map(shortenHomePath).join(`, `)}).`,k?`missing-oauth-sidecar`:`archived-unparsed`,k?`Run openclaw models status to identify the unavailable profiles, then openclaw models auth login --provider <provider-id> for their configured providers. Keep the archived sources.`:`Keep the listed archives. Compare openclaw models status with your expected accounts; if credentials are missing, inspect the archive for manual recovery or sign in with openclaw models auth login --provider <provider-id>.`,r.authPath,k?`fix-now`:`historical`);continue}u(`Left auth profile JSON in place for ${shortenHomePath(r.authPath)} because no importable auth profiles or state were found.`,`unimportable-source`,`Inspect the retained source and compare openclaw models status with the accounts you expect. If credentials are unavailable, use openclaw models auth login --provider <provider-id>; keep the source for manual recovery.`,r.authPath,`recommended`);continue}const H=loadAuthProfileMigrationTargetStore(r.agentDir,void 0,n);const U=new Set(Object.keys(H.profiles));const W=coerceAuthProfileState(H);let G={...H};let K=H;const q=/* @__PURE__ */ new Set;const J={version:1,profiles:{}};if(B){applyLegacyAuthStore(J,z);Object.keys(J.profiles).forEach(e=>T.add(e));Object.keys(J.profiles).forEach(e=>s.add(e));canonicalizeLegacyAuthStore(J,null,y)}for(const e of[J,P,F]){if(!e)continue;Object.keys(e.profiles).forEach(e=>q.add(e));const t=e===F;G=mergeImportedAuthProfiles({store:G,profiles:e.profiles,existingProfileIds:t?new Set(Object.keys(G.profiles)):U,replaceExistingWithoutCredential:t});if(e===P){G.version=Math.max(G.version,e.version);G=mergeImportedAuthProfileState({store:G,state:coerceAuthProfileState(e),existingState:W})}}if(hasAuthProfileState(V))G=mergeImportedAuthProfileState({store:G,state:V,existingState:W});if(P||F||B||hasAuthProfileState(V)){const e=[V,P,F].flatMap(e=>e?collectAuthProfileStateProfileIds(coerceAuthProfileState(e)):[]);try{assertAuthProfileMigrationSourcesUnchanged(f,[...v,...w]);const t=recordAuthAliasMigration({profileIdMap:y,stores:[{databasePath:p,store:H,migratedStore:G}],importedProfileIds:T,sources:v.filter(e=>e.sourcePath!==path.resolve(r.statePath)).map(e=>({path:e.sourcePath,sha256:e.sourceSha256})),env:n});K=runWithAuthAliasMigrationReceipt(t,n,()=>runAuthProfileWriteTransaction(_,(t,i)=>{const a=loadAuthProfileMigrationTargetStore(r.agentDir,t);if(!isDeepStrictEqual(a,H))throw new Error(`current auth profile store changed during legacy migration`);saveAuthProfileStoreWithPreparedOwner(G,r.agentDir,{filterExternalAuthProfiles:false,preserveStateProfileIds:e,syncExternalCli:false},t,i);const o=loadPersistedAuthProfileStore(r.agentDir,{database:t});const s=resolveMigrationTargetDatabasePath(r.agentDir,n)===resolveNativeSharedAuthStorePath(n);const c={isMainStore:s,localStore:o,mainStore:s?o:loadPersistedSharedAuthProfileStore(n)};const l=new Set([...q].filter(e=>{const t=G.profiles[e];return!(t!==void 0&&!o?.profiles[e]&&isInheritedMainOAuthCredentialFromStores({profileId:e,credential:t,persistedStores:c}))}));const u=formatMissingAuthProfileSqliteVerification({expected:G,importedProfileIds:l,loaded:o});const d=[...l].some(e=>{if(U.has(e))return false;return!isDeepStrictEqual(o?.profiles[e],G.profiles[e])});if(u||d||!o)throw new AuthProfileMigrationVerificationError(u);return o},{env:n}))}catch(e){if(!(e instanceof AuthProfileMigrationVerificationError))throw e;u(`Left auth profile JSON in place for ${shortenHomePath(r.authPath)} because SQLite verification failed${e.detail?` (${e.detail})`:``}.`,`verification-failed`,`Keep the original JSON and recovery copy. Inspect the reported SQLite verification error and filesystem permissions; rerun openclaw doctor --fix after correcting the cause. Do not delete the credential database.`,r.authPath);continue}}const Y=Object.fromEntries([...q].flatMap(e=>{const t=K.profiles[e];return t?[[e,digestAuthProfileMigrationValue(t)]]:[]}));const X=digestAuthProfileMigrationValue(r.agentDir?readPersistedAuthProfileStateRaw(r.agentDir):readPersistedSharedAuthProfileStateRaw(n));const Z=P?hasAuthProfileState(coerceAuthProfileState(P)):false;for(const e of v){if(e.targetTable!==`auth_profile_state`)e.expectedProfileSha256=Y;if(e.targetTable===`auth_profile_state`||e.sourcePath===r.authPath&&Z)e.expectedStateSha256=X}assertAuthProfileMigrationSourcesUnchanged(f,[...v,...w]);for(const e of w){e.expectedProfileSha256=Y;x.set(e.sourcePath,e)}const Q=v.map(e=>{finalizeAuthProfileMigrationSource(e,`completed`);return e.archivePath});for(const e of[...T,...q,...collectAuthProfileStateProfileIds(V),...collectAuthProfileStateProfileIds(coerceAuthProfileState(P)),...collectAuthProfileStateProfileIds(coerceAuthProfileState(F))])d.add(e);if(m&&o&&stripImportedConfigAuthProfileCredentials(e.cfg,m))g.configChanged=true;if(j){const t=ensureConfigAuthProfiles(e.cfg);for(const e of j)t[e.profileId]={provider:e.provider,mode:`aws-sdk`,...e.email?{email:e.email}:{},...e.displayName?{displayName:e.displayName}:{}};g.configChanged=true}const $=Q.length>0?`archive${Q.length===1?``:`s`}: ${Q.map(shortenHomePath).join(`, `)}`:`no legacy JSON backup needed`;g.changes.push(`Migrated auth profile JSON for ${shortenHomePath(r.authPath)} into SQLite (${$}).`);if(M>0)g.changes.push(`Canonicalized ${M} auth SecretRef(s) to source/provider/id; unsupported fields are preserved in the verified source archives (${$}).`);c=true;if(R>0){const e=S.get(path.resolve(a))?.archivePath;g.warnings.push(`Could not import ${R} legacy OAuth credential entries; original bytes are preserved in ${shortenHomePath(e??a)}. Restore that archive to ${shortenHomePath(a)}, correct the entries, and rerun ${formatCliCommand(`openclaw doctor --fix`)}; alternatively re-authenticate with ${formatCliCommand(`openclaw models auth login --provider <provider>`)}.`)}if(k)u(k,`missing-oauth-sidecar`,`Run openclaw models status to identify the unavailable profiles, then openclaw models auth login --provider <provider-id> for their configured providers. Keep the archived sources.`,r.authPath);if(D!==null)g.changes.push(`Migrated retired auth profile identifiers in ${shortenHomePath(r.authPath)}.`);if(j)g.changes.push(`Moved aws-sdk profile metadata from ${shortenHomePath(r.authPath)} to auth.profiles before removing the legacy auth profile JSON.`)}catch(e){if(s.size===0)y.forEach((e,t)=>f.add(t));u(`Failed to migrate auth profile JSON for ${shortenHomePath(r.authPath)}: ${String(e)}`,`import-failed`,`Preserve the source and recovery copy. Restore valid UTF-8 JSON from a verified backup if unreadable; otherwise correct the reported source or database access error, then rerun ${formatCliCommand(`openclaw doctor --fix`)}. Use openclaw models status to identify credentials still requiring login.`,r.authPath)}finally{if(!c)s.forEach(e=>f.add(e));l?.()}}const S=finalizeLegacyOAuthSidecarImports({cfg:e.cfg,env:n,receipts:x.values()});g.changes.push(...S.changes);g.warnings.push(...S.warnings);clearRuntimeAuthProfileStoreSnapshots();clearAuthProfileMigrationDiagnostics();return g}function readAwsSdkAuthProfileMarkers(e){if(!fs.existsSync(e.authPath))return null;const t=loadJsonFileThroughSymlink(e.authPath);if(!isRecord(t)||!isRecord(t.profiles))return null;const n=[];for(const[e,r]of Object.entries(t.profiles)){if(!isRecord(r))continue;if((readNonBlankString(r.type)??readNonBlankString(r.mode))!==`aws-sdk`)continue;const t=readNonBlankString(r.provider)??extractProviderPrefix(e,`:`);if(!t||!isSafeLegacyProviderKey(t))continue;n.push({profileId:e,provider:t,...readNonBlankString(r.email)?{email:readNonBlankString(r.email)}:{},...readNonBlankString(r.displayName)?{displayName:readNonBlankString(r.displayName)}:{}})}return n.length>0?n:null}function rewriteMappedAuthProfileRefs(e,t){let n=false;const rewrite=(e,r)=>{if(!isRecord(e)||typeof e[r]!==`string`)return;let i=e[r];if(r===`apiKey`)i=normalizeSecretInput(i);else if(r===`authProfileId`)i=i.trim();const a=t.get(i);if(a&&a!==e[r]){e[r]=a;n=true}};for(const t of Object.values(e.models?.providers??{}))rewrite(t,`apiKey`);for(const t of e.tools?.media?.models??[]){rewrite(t,`profile`);rewrite(t,`preferredProfile`)}for(const t of Object.values(e.mcp?.servers??{}))rewrite(t.oauth,`authProfileId`);const r=[e.agents?.defaults,...listMutableCodexRouteAgentEntries(e).map(({agent:e})=>e)];for(const e of r){if(!isRecord(e)||!isRecord(e.models))continue;for(const t of Object.values(e.models))rewrite(isRecord(t)?t.agentRuntime:void 0,`authProfileId`)}return n}function maybeRepairOpenAICodexAuthConfig(e,t){let n=structuredClone(e);const r=isRecord(n.auth)?n.auth:void 0;const i=new Map(t?.profileIdMap);let a=false;if(isRecord(r?.profiles)){const e=canonicalizeLegacyAuthProfileEntries(r.profiles,{profileIdMap:i,preserveUnmappedLegacyIds:t?.profileIdMap!==void 0});e.profileIdMap.forEach((e,t)=>i.set(t,e));a||=e.changed}if(r){const e=canonicalizeLegacyAuthOrder(r,i,{preserveUnmappedLegacyIds:t?.profileIdMap!==void 0});a||=e}if(i.size>0&&rewriteMappedAuthProfileRefs(n,i))a=true;if(i.size>0){const e=repairRetiredConfigModelRefs(n,({modelRef:e})=>repairModelRefAuthProfile(e,i));n=e.config;a||=e.changes.length>0;a=rewritePluginAuthProfileRefs(n,i)||a}if(a)copyConfigResolutionFactsThroughRewrite(e,n);return{config:a?n:e,changes:a?[`Migrated legacy auth profile config to current providers.`]:[],warnings:[]}}async function maybeRepairLegacyAuthProfileStores(e){const t=e.env??process.env;const n=[];const r=[];const i=createAuthMigrationWarningRecorder(n,r);let a=false;const warnUnavailable=e=>{a=true;i(`Skipped auth-profile alias migration because ${shortenHomePath(e)} is unavailable.`,`owner-unavailable`,`Check that the credential owner path exists and is readable by the OpenClaw user, then rerun openclaw doctor --fix. Keep existing credentials and archives.`,e)};const o=listAuthProfileRepairCandidates(e.cfg,t,warnUnavailable);const s=[];const c=[];for(const[e,n]of listAuthProfileMigrationTargets(o,t)){let r;try{r=readDatabasePathIdentitySync(e)}catch{warnUnavailable(e);continue}const o=n?inspectPersistedAuthProfileStoreRaw(n):inspectPersistedSharedAuthProfileStoreRaw(t);const l=n?inspectPersistedAuthProfileStateRaw(n):inspectPersistedSharedAuthProfileStateRaw(t);if(o.status===`unreadable`||n!==void 0&&inspectAuthDatabaseFiles(n)===`unreadable`||o.status===`readable`&&(!isRecord(o.raw)||!isRecord(o.raw.profiles))){a=true;i(`Skipped auth-profile alias migration because ${shortenHomePath(e)} is unreadable or invalid.`,`owner-invalid`,`Keep the database and recovery copy. Correct access permissions or recover the credential store from a verified backup before rerunning openclaw doctor --fix; do not delete the database.`,e);continue}s.push({databasePath:e,store:o.status===`readable`?o.raw:null});if(o.status===`readable`||l.status===`readable`||l.status===`unreadable`){assertExistingDatabaseIdentity(e,r.key,r.birthtime);const s=l.status===`missing`||l.status===`readable`&&isReadableAuthAliasState(l.raw);const u=(o.status!==`readable`||isReadableAuthAliasStore(o.raw))&&s;if(!u)i(`Skipped auth-profile alias renames because ${shortenHomePath(e)} is unreadable or invalid; supported credential fields can still be repaired.`,`alias-state-invalid`,`Keep the credential database and recovery copy. Inspect the invalid auth or rotation state and restore a verified backup if needed, then rerun openclaw doctor --fix.`,e);const d=l.status===`unreadable`?readAuthProfileStateJsonTextReadOnly({path:e,kind:n===void 0&&prepareSharedAuthStoreOwnershipForNative(t).location===`state-db`?`shared-state`:`agent`,env:t}):void 0;assertExistingDatabaseIdentity(e,r.key,r.birthtime);if(l.status===`unreadable`&&d===void 0){a=true;i(`Skipped auth-profile field repair because ${shortenHomePath(e)} has no stable rotation-state source.`,`rotation-source-unavailable`,`Keep the database and recovery copy. Restore readable rotation state from a verified backup or correct the reported access problem before rerunning openclaw doctor --fix.`,e);continue}c.push({databasePath:e,identity:r,canRenameAliases:u,canReadRotationState:s,agentDir:n,store:o.status===`readable`?o.raw:null,state:l.status===`readable`?l.raw:null,...d!==void 0?{unreadableStateJson:d}:{}})}}const l=new Map(a?[]:e.profileIdMap);if(a&&e.profileIdMap.size>0)i(`Deferred auth profile aliases because an owner could not be inspected; repair that owner and rerun Doctor.`,`owner-inspection-incomplete`,`Resolve the credential-owner path or database finding shown above, then rerun openclaw doctor --fix. Keep all account credentials until every owner can be inspected.`);for(const e of c){if(e.canRenameAliases)continue;const t=collectAuthOwnerProfileIds(e.store,e.state);for(const[n,r]of l)if(!e.canReadRotationState||t.has(n)||t.has(r)){l.delete(n);i(`Deferred auth profile alias ${n} because ${shortenHomePath(e.databasePath)} cannot safely rename its credential owner.`,`alias-owner-unsafe`,`Keep this profile and its credential owner. Repair the reported unreadable auth or rotation state from a verified backup, then rerun openclaw doctor --fix.`,n)}}const u=recoverAuthAliasMigration({stores:s,env:t,archivedMappings:recoverArchivedAuthProfileMappings({candidates:o,env:t})});const d=e.renameProfileIds===false?/* @__PURE__ */ new Map:l;const f=new Set(Object.entries(e.cfg.auth?.profiles??{}).filter(([e,t])=>!l.has(e)&&(isLegacyAuthProfileId(e)||typeof t.provider===`string`&&canonicalLegacyAuthProvider(t.provider)!==t.provider)).map(([e])=>e));for(const e of c){for(const t of[...collectRawAuthRotationProfileIds(e.store),...collectRawAuthRotationProfileIds(e.state)])if(isLegacyAuthProfileId(t)&&!l.has(t))f.add(t);if(!isRecord(e.store)||!isRecord(e.store.profiles))continue;for(const[t,n]of Object.entries(e.store.profiles)){const e=isRecord(n)&&typeof n.provider===`string`?n.provider.trim().toLowerCase():void 0;if(!l.has(t)&&(isLegacyAuthProfileId(t)||e!==void 0&&canonicalLegacyAuthProvider(e)!==e))f.add(t)}}for(const e of f)i(`Kept auth profile ${e} unchanged because its provider realm or identity is unresolved.`,`identity-unresolved`,`Compare this profile and its configured provider realm with openclaw models status. Correct the provider/account selection before retrying openclaw doctor --fix; do not overwrite another account to force migration.`,e);for(const e of c){const t=collectAuthOwnerProfileIds(e.store,e.state);for(const[e,n]of l)if(e!==n&&t.has(n)&&(t.has(e)||u.recovered.get(e)!==n)){l.delete(e);i(`Deferred stale auth profile alias ${e}; the target is occupied.`,`alias-target-occupied`,`Compare the source and target accounts with openclaw models status; preserve both credential profiles and choose the intended account in auth.profiles/auth.order before rerunning openclaw doctor --fix.`,e)}}for(const e of l.keys())if(u.blocked.has(e)){l.delete(e);i(`Kept auth profile ${e} unchanged because its recorded account changed; reconcile the migration before retrying.`,`recorded-account-changed`,`Compare the retained migration archive with the current account shown by openclaw models status. Preserve both accounts and recovery data; reconcile the intended account and its config references before rerunning openclaw doctor --fix.`,e,`historical`)}const p=c.map(e=>{const t=structuredClone(e.store);const n=structuredClone(e.state);if(e.canRenameAliases)canonicalizeLegacyAuthStore(t,n,d);const r=normalizeLegacyAuthProfileFields(t);return Object.assign(e,{migratedStore:t,migratedState:n,canonicalizedSecretRefs:r})});const m=p.filter(e=>!isDeepStrictEqual(e.store,e.migratedStore)||!isDeepStrictEqual(e.state,e.migratedState));if(m.length===0&&d.size===0)return{changes:[],warnings:n,findings:r,profileIdMap:l};const h=getOpenClawDatabaseMaintenanceScope();const assertTargetCurrent=(e,t)=>{h?.assertOwnerCurrent();assertExistingDatabaseIdentity(e.databasePath,e.identity.key,e.identity.birthtime);if(t){const n=`agentId`in t?readOpenClawAgentDatabaseIdentity(t):void 0;const r=n?{key:`file:${n.identity}`,birthtime:n.birthtime}:requireOpenClawStateDatabaseIdentity(t);if(r.key!==e.identity.key)throw new Error(`Auth profile database generation changed after backup; retry Doctor.`);assertExistingDatabaseIdentity(t.path,r.key,r.birthtime)}};const g=[];const _=randomUUID();for(const n of m){assertTargetCurrent(n);const r=n.agentDir===void 0&&prepareSharedAuthStoreOwnershipForNative(t).location===`state-db`?`shared-state`:`agent`;const i=await createVerifiedDatabaseMigrationBackup({sourcePath:n.databasePath,targetPath:`${n.databasePath}.auth-profile-migration-${_}.bak`,config:e.cfg,assertCurrent:()=>assertTargetCurrent(n),validate:e=>{for(const t of[`store`,`state`]){if(t===`state`&&n.unreadableStateJson!==void 0){if(readAuthProfileJsonCellText(e,`state`,r)!==n.unreadableStateJson)throw new Error(`Auth profile backup differs from the planned rotation-state source; retry Doctor.`);continue}const i=inspectAuthProfileJsonCell(e,t,r);if(i.status===`unreadable`||!isDeepStrictEqual(i.status===`readable`?i.raw:null,n[t]))throw new Error(`Auth profile backup differs from the planned source; retry Doctor.`)}}});assertTargetCurrent(n);g.push(`Saved auth profile migration backup: ${shortenHomePath(i.path)}.`)}const assertSourceCurrent=(e,t)=>{assertTargetCurrent(e,t);if(e.unreadableStateJson!==void 0&&readAuthProfileJsonCellText(t.db,`state`,`agentId`in t?`agent`:`shared-state`)!==e.unreadableStateJson)throw new Error(`Auth profile rotation-state source changed during migration; retry Doctor.`);if(!isDeepStrictEqual(readPersistedAuthProfileStoreRaw(e.agentDir,t),e.store)||!isDeepStrictEqual(readPersistedAuthProfileStateRaw(e.agentDir,t),e.state))throw new Error(`auth profile store or rotation state changed during alias migration`)};for(const e of p)runAuthProfileWriteTransaction(e.agentDir,t=>assertSourceCurrent(e,t),{env:t});h?.assertOwnerCurrent();const v=recordAuthAliasMigration({profileIdMap:d,stores:p,env:t,normalizeCredentialFields:true});const y=[];const migrate=(e,n)=>{const r=p[e];if(r){runAuthProfileWriteTransaction(r.agentDir,t=>{assertSourceCurrent(r,t);y.push({database:t,target:r});migrate(e+1,n)},{env:t});return}h?.assertOwnerCurrent();const i=renameUserProfileAuthLinks(d,{env:t,database:n});if(i>0)g.push(`Updated renamed auth profiles in ${i} personal account selection record(s).`);for(const{database:e,target:t}of y){const n=t.migratedStore;const r=t.migratedState;const i=!isDeepStrictEqual(n,t.store);const a=!isDeepStrictEqual(r,t.state);if(i){writePersistedAuthProfileStoreRaw(n,t.agentDir,e);if(t.canonicalizedSecretRefs>0)g.push(`Canonicalized ${t.canonicalizedSecretRefs} auth SecretRef(s) in ${shortenHomePath(t.databasePath)} to source/provider/id; unsupported fields are preserved in the verified migration backup.`)}if(a)writePersistedAuthProfileStateRaw(r,t.agentDir,e);if(i||a)g.push(`Migrated stored auth profile aliases in ${shortenHomePath(t.databasePath)}.`)}};runWithAuthAliasMigrationReceipt(v,t,e=>migrate(0,e));if(g.length>0)clearRuntimeAuthProfileStoreSnapshots();return{changes:g,warnings:n,findings:r,profileIdMap:l}}function recoverArchivedAuthProfileMappings(e){const t=/* @__PURE__ */ new Map;const n=/* @__PURE__ */ new Set;const r=[resolveSharedMainAuthAgentDir(e.env),...e.candidates.flatMap(e=>e.agentDir?[e.agentDir]:[])];const i=listLegacyAuthProfileArchives({agentDirs:r,env:e.env}).filter(e=>e.kind===`auth-profiles`||e.kind===`legacy-auth`);for(const r of e.candidates){const a=coerceLegacyAuthProfileStore(r.agentDir?readPersistedAuthProfileStoreRaw(r.agentDir):readPersistedSharedAuthProfileStoreRaw(e.env))?.profiles;if(!a)continue;const o=[r.authPath,resolveLegacyFlatAuthPath(path.dirname(r.authPath))];for(const s of i){const i=o.find(e=>s.path.startsWith(`${e}.migrated-`));if(!i)continue;try{const o=fs.readFileSync(s.path);const c=createHash(`sha256`).update(o).digest(`hex`);const l=`auth-profile-v2:${createHash(`sha256`).update(`${path.resolve(i)}\0${c}`).digest(`hex`)}`;const u=readLegacyMigrationReceipt(l,e.env);if(!u?.removedSource||u.sourceSha256!==c)continue;const d=JSON.parse(u.reportJson);const f=r.agentDir===void 0&&prepareSharedAuthStoreOwnershipForNative(e.env).location===`state-db`;if(!isRecord(d)||d.format!==`auth-profile-json-to-sqlite-v2`||d.completionStatus!==`completed`||d.targetTable!==(f?`auth_profile_stores`:`auth_profile_store`)||typeof d.archivePath!==`string`||path.resolve(d.archivePath)!==path.resolve(s.path)||typeof d.targetDatabasePath!==`string`||path.resolve(d.targetDatabasePath)!==path.resolve(resolveMigrationTargetDatabasePath(r.agentDir,e.env))||!isRecord(d.expectedProfileSha256))continue;const p=parseAuthProfileMigrationSource({sourceBytes:o,sourcePath:i});const m=coerceLegacyAuthProfileStore(p)??coerceLegacyFlatAuthProfileStore(p);if(!m)continue;for(const[o,s]of Object.entries(m.profiles)){const l=legacyAuthProfileTarget(o);if(!l)continue;const u=parseLegacyCredentialEntry({...s,provider:l.provider},l.provider);if(!u)continue;const f=Object.entries(d.expectedProfileSha256).flatMap(([e,t])=>{const n=a[e];return typeof t===`string`&&n?.provider===l.provider&&(u.type===`oauth`&&n.type===`oauth`?hasMatchingOAuthIdentity(u,n)||areOAuthCredentialsEquivalent(u,n):isDeepStrictEqual(u,n))?[e]:[]});if(f.length!==1)continue;const p=f[0];const m=t.get(o);if(m&&m.profileId!==p){t.delete(o);n.add(o)}else if(!n.has(o))t.set(o,{profileId:p,origins:[...m?.origins??[],{sourcePath:path.resolve(i),sourceSha256:c,databasePath:resolveMigrationTargetDatabasePath(r.agentDir,e.env)}]})}}catch{}}}return t}function collectOpenAICodexAuthProfileStoreIdMap(e){const t=e.env??process.env;const n=/* @__PURE__ */ new Set([`openai:codex-cli`]);const r=/* @__PURE__ */ new Set;const i=/* @__PURE__ */ new Set;const a=/* @__PURE__ */ new Map;const o=[];let s=false;const c=listAuthProfileRepairCandidates(e.cfg,t,()=>{s=true});if(s)return a;const l=new Set(Object.keys(e.cfg.models?.providers??{}).map(e=>e.trim().toLowerCase()));const collectReferences=e=>{for(const t of collectRawAuthRotationProfileIds(e))n.add(t)};const collectProfiles=e=>{if(!isRecord(e)||!isRecord(e.profiles))return false;for(const[t,a]of Object.entries(e.profiles)){n.add(t);const e=legacyAuthProfileTarget(t);const o=isRecord(a)&&typeof a.provider===`string`?a.provider.trim().toLowerCase():void 0;const s=o===void 0?void 0:canonicalLegacyAuthProvider(o);if(!e&&s===o)continue;const c=t.slice(0,t.indexOf(`:`)).trim().toLowerCase();const u=o!==s;const d=isRecord(a)&&u&&[`enterpriseUrl`,`tokenEndpoint`,`deviceAuthorizationEndpoint`,`issuer`].some(e=>a[e]!==void 0);if(o===void 0||s===void 0||e!==null&&e.provider!==s||e!==null&&l.has(c)||u&&l.has(o)||d)i.add(t);else r.add(t)}collectReferences(e);return true};collectProfiles({profiles:e.cfg.auth?.profiles??{},order:e.cfg.auth?.order});for(const[e,n]of listAuthProfileMigrationTargets(c,t)){if(n&&inspectAuthDatabaseFiles(n)===`unreadable`)return a;const r=n?inspectPersistedAuthProfileStoreRaw(n):inspectPersistedSharedAuthProfileStoreRaw(t);const s=n?inspectPersistedAuthProfileStateRaw(n):inspectPersistedSharedAuthProfileStateRaw(t);if(r.status===`unreadable`||s.status===`unreadable`)return a;o.push({databasePath:e,store:r.status===`readable`?r.raw:null});if(r.status===`readable`){if(!collectProfiles(r.raw))return a;if(!isReadableAuthAliasStore(r.raw)&&isRecord(r.raw)&&isRecord(r.raw.profiles))Object.keys(r.raw.profiles).forEach(e=>i.add(e))}if(s.status===`readable`){if(!isRecord(s.raw))return a;collectReferences(s.raw);if(!isReadableAuthAliasState(s.raw)&&r.status===`readable`&&isRecord(r.raw)&&isRecord(r.raw.profiles))Object.keys(r.raw.profiles).forEach(e=>i.add(e))}}for(const e of c){if(fs.existsSync(e.authPath)&&!collectProfiles(loadJsonFileThroughSymlink(e.authPath)))return a;const t=resolveLegacyFlatAuthPath(path.dirname(e.authPath));if(fs.existsSync(t)){const e=coerceLegacyAuthStore(loadJsonFileThroughSymlink(t));if(!e)return a;const n={version:1,profiles:{}};applyLegacyAuthStore(n,e);collectProfiles(n)}const n=resolveLegacyAuthStatePath(path.dirname(e.authPath));if(fs.existsSync(n)){const e=loadJsonFileThroughSymlink(n);if(!isRecord(e))return a;collectReferences(e)}}const u=recoverArchivedAuthProfileMappings({candidates:c,env:t});const d=recoverAuthAliasMigration({stores:o,env:t,archivedMappings:u});for(const e of d.blocked)i.add(e);for(const[t,n]of d.recovered)if(!i.has(t)){a.set(t,n);if(u.get(t)?.profileId===n)e.recoveredProfileIds?.add(t)}for(const e of[...r].toSorted((e,t)=>e.localeCompare(t)))if(!i.has(e)&&!a.has(e))a.set(e,isLegacyAuthProfileId(e)?allocateLegacyAuthProfileId(e,n):e);for(const[t,n]of u)if(o.every(({databasePath:e,store:t})=>!isRecord(t)||!isRecord(t.profiles)||t.profiles[n.profileId]===void 0||n.origins.some(t=>t.databasePath===e))&&!a.has(t)&&!i.has(t)){a.set(t,n.profileId);e.recoveredProfileIds?.add(t)}return a}
//!src/commands/doctor/auth-profile-repair.ts
async function repairAuthProfileMigration(e){const t=e.env??process.env;const n=e.profileIdMap??collectOpenAICodexAuthProfileStoreIdMap({cfg:e.cfg,env:t});const r=structuredClone(e.cfg);const i=await maybeMigrateAuthProfileJsonStoresToSqlite({cfg:r,env:t,prompter:{confirmAutoFix:e.prompter.confirmAutoFix},openAICodexAuthProfileIdMap:n});const a=/* @__PURE__ */ new Set;const o=i.detected.length===0?collectOpenAICodexAuthProfileStoreIdMap({cfg:r,env:t,recoveredProfileIds:a}):/* @__PURE__ */ new Map;const s=new Map([...n,...[...o].filter(([e])=>a.has(e))].filter(([t,n])=>!i.blockedProfileIds.has(t)&&!i.blockedProfileIds.has(n)&&(e.prompter.shouldRepair||a.has(t)&&i.detected.length===0||i.migratedProfileIds.has(t)||i.migratedProfileIds.has(n))));const c=e.prompter.shouldRepair||s.size>0;const l=c?await maybeRepairLegacyAuthProfileStores({cfg:r,env:t,profileIdMap:s}):{profileIdMap:s,changes:[],warnings:[],findings:[]};const u=new Set(l.findings.map(e=>e.target));const d=c?i.aliasFindings.filter(e=>e.target!==void 0&&u.has(e.target)):i.aliasFindings;const f=new Set(d.map(e=>e.target));const p=[...d,...l.findings.filter(e=>e.checkId!==`core/doctor/auth-migration/identity-unresolved`||!f.has(e.target))];const m=[...new Map([...i.findings,...p].map(e=>[`${e.checkId}\0${e.target??``}`,e])).values()];const h=maybeRepairOpenAICodexAuthConfig(r,{profileIdMap:l.profileIdMap});const g=i.configChanged||h.changes.length>0;if(g)copyConfigResolutionFactsThroughRewrite(e.cfg,h.config);return{config:g?h.config:e.cfg,changes:[...h.changes,...i.configChanged?[`Auth profile SQLite migration updated auth.profiles.`]:[]],storeChanges:[...i.changes,...l.changes],warnings:[...i.warnings,...l.warnings,...h.warnings],findings:m,profileIdMap:l.profileIdMap}}async function refreshGatewayAuthStateAfterAuthProfileRepair(){const{callGateway:e}=await import(`./call-CggG9h6i.mjs`);for(const t of[{method:`secrets.reload`,params:{}},{method:`models.authStatus`,params:{refresh:true}}])try{await e({...t,timeoutMs:3e3,sharedStateMode:`read-only`})}catch{}}export{maybeRepairLegacyAuthProfileStores as i,repairAuthProfileMigration as n,collectOpenAICodexAuthProfileStoreIdMap as r,refreshGatewayAuthStateAfterAuthProfileRepair as t};