UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

13 lines • 24.4 kB
import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{o as openRootFileSync}from"./boundary-file-read-bB9An35K.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import{f as readDatabaseIdentityBirthtime,h as resolveDatabasePathKey}from"./sqlite-worker-identity-CikEUuqF.mjs";import{T as publishSqliteDatabaseAdmission,dt as OPENCLAW_STATE_SCHEMA_SQL}from"./sqlite-database-admission-B3KDkUt-.mjs";import{o as isSqliteLockError}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely,v as expressionBuilder}from"./kysely-sync-R08Pt8qn.mjs";import{o as getAdmittedSqliteSchemaFacts,t as admitSqliteSchema}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{c as writeSqliteUserVersion,o as readSqliteUserVersion}from"./sqlite-user-version-DaJ6mdUV.mjs";import{n as StartupMaintenanceRequiredError}from"./startup-maintenance-required-Cz4Y_ofl.mjs";import{n as openNodeSqliteDatabase,o as resolveReadOnlyShmSqliteFileUri,r as resolveExistingSqliteFileUri}from"./node-sqlite-DXyF1fBG.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{a as resolveSqliteInspectionSignal}from"./sqlite-readonly-worker-context-BjXXEC4m.mjs";import{a as runSqliteImmediateTransactionSync,r as runSqliteDeferredTransactionSync}from"./sqlite-transaction-CON-dGDv.mjs";import{i as assertSqliteIntegrity}from"./sqlite-integrity-BzUEDiX5.mjs";import{c as runUpdateSqliteMigrationAsync,s as runUpdateSqliteMigration}from"./update-doctor-migration-context-DWFAKZNL.mjs";import{t as readGeneratedSqliteCatalog}from"./sqlite-catalogs-Cqxc9n39.mjs";import{t as assertSqliteSchemaContains}from"./sqlite-schema-contract-Cb9-M55A.mjs";import{n as CLIENT_CREDENTIAL_SCHEMA_SQL,r as CLIENT_CREDENTIAL_SCHEMA_VERSION}from"./client-credential-schema-DfsAsx4-.mjs";import{t as chunkItems}from"./chunk-items-CsdD1uHV.mjs";import{a as salvageStoredIdentityRow,o as storedDeviceIdentityFromRow,s as storedDeviceIdentityToRow}from"./device-identity-material-CkS6RKfU.mjs";import{a as validateSource,i as sourceRows,n as hashClientCredentialRows}from"./client-credential-migration-data-CMSJJDjr.mjs";import{t as resolveClientCredentialStorePath}from"./client-credential-paths-D__QHGyH.mjs";import{a as serializeClientCredentialReceipt,i as readClientCredentialFileIdentity,n as emptyClientCredentialReceipt,r as parseClientCredentialReceipt,t as CLIENT_CREDENTIAL_LEGACY_KEYS}from"./client-credential-receipt-CEFy8dbp.mjs";import{t as preparePrivateStoreFileSync}from"./private-store-file-DXbtcyej.mjs";import fs from"node:fs";import path from"node:path";import{inspectDarwinAcl}from"@openclaw/fs-safe/permissions"; //!src/infra/client-credential-native-bootstrap.ts function isNativeClientCredentialBootstrap(e){admitSqliteSchema(e);const t=getAdmittedSqliteSchemaFacts(e);if(t.userVersion!==0)return false;const n=[...[...t.tables].map(e=>({type:`table`,name:e})),...[...t.indexes].map(e=>({type:`index`,name:e})),...[...t.views].map(e=>({type:`view`,name:e})),...[...t.triggers.keys()].map(e=>({type:`trigger`,name:e}))].filter(({name:e})=>!e.startsWith(`sqlite_`));const r=/* @__PURE__ */ new Set([`table:device_identities`,`index:idx_device_identities_device`,`table:device_auth_tokens`,`index:idx_device_auth_tokens_updated`,`table:macos_port_guardian_records`,`index:idx_macos_port_guardian_records_port`]);if(!n.length||n.some(e=>!r.has(`${e.type}:${e.name}`)))return false;if(t.tables.has(`macos_port_guardian_records`)||t.indexes.has(`idx_macos_port_guardian_records_port`)){const t=readGeneratedSqliteCatalog(OPENCLAW_STATE_SCHEMA_SQL)?.tables.filter(({name:e})=>e===`macos_port_guardian_records`);if(!t?.length)throw new Error(`Native PortGuardian companion has no canonical schema catalog.`);assertSqliteSchemaContains(e,`Native PortGuardian companion`,{tables:t,views:[]})}assertSqliteSchemaContains(e,`Native client credential bootstrap`,CLIENT_CREDENTIAL_SCHEMA_SQL,{allowedMissingTables:[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`,`client_credential_migration`]});return true}function readIndependentClientCredentialSource(e){try{var t=_usingCtx();const n=readClientCredentialFileIdentity(e);if(!n)throw new Error(`Independent client credential source is missing; restore its matching backup.`);const r=fs.openSync(e,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);try{const e=Buffer.alloc(100);if(fs.readSync(r,e,0,e.length,0)!==e.length||e.subarray(0,16).toString(`binary`)!==`SQLite format 3\0`||e[18]!==1||e[19]!==1)throw new Error(`Independent client credentials require DELETE journal mode; stop the old client and restore a compatible source.`)}finally{fs.closeSync(r)}const i=t.u(openNodeSqliteDatabase(e,{readOnly:true}));if(!isNativeClientCredentialBootstrap(i))throw new Error(`Independent client credential source is not a native credential-only database.`);i.exec(`BEGIN`);try{const e=getAdmittedSqliteSchemaFacts(i).tables.has(`device_auth_tokens`);const t=sourceRows(i,true);validateSource(t);const r=hashClientCredentialRows(t,{authTablePresent:e});return{file:n,identity:`${n.dev}:${n.ino}`,sha256:r,rows:t,authTablePresent:e}}finally{i.exec(`ROLLBACK`)}}catch(e){t.e=e}finally{t.d()}} //!src/infra/client-credential-readiness.ts var ClientCredentialMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e=`Client credential migration is incomplete or stale; run openclaw doctor --fix before using this client.`){super(`state-migrations`,e);this.name=`ClientCredentialMigrationRequiredError`}};function notReady(){return new ClientCredentialMigrationRequiredError}function assertSupportedVersion(e){if(e!==1)throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`)}function readClientCredentialAdmission(e){let t;try{t=e.prepare(` SELECT header.user_version, receipt.source_store, receipt.phase FROM pragma_user_version AS header LEFT JOIN client_credential_migration AS receipt ON receipt.version = 1 `).get()}catch(t){assertSupportedVersion(readSqliteUserVersion(e));throw t}if(!t||typeof t.user_version!==`number`)throw notReady();assertSupportedVersion(t.user_version);const n=e.location();return{stored:t.source_store===null?null:{phase:t.phase===`complete`?`complete`:`copied`,receipt:parseClientCredentialReceipt(String(t.source_store),n?path.dirname(path.dirname(n)):void 0)}}}function readClientCredentialReceipt(e,t){const n=getNodeSqliteKysely(e);const r=executeSqliteQueryTakeFirstSync(e,n.selectFrom(`client_credential_migration`).selectAll().where(`version`,`=`,1));const i=e.location();return r?{phase:r.phase,receipt:parseClientCredentialReceipt(r.source_store,t??(i?path.dirname(path.dirname(i)):void 0))}:null}function writeClientCredentialReceipt(e,t,n,r=Date.now()){const i=getNodeSqliteKysely(e);const a=e.location();const o={version:1,source_store:serializeClientCredentialReceipt(t,a?path.dirname(path.dirname(a)):void 0),phase:n,updated_at_ms:r};executeSqliteQuerySync(e,i.insertInto(`client_credential_migration`).values(o).onConflict(e=>e.column(`version`).doUpdateSet(o)))}function assertClientCredentialLegacyReady(e,t,n=false,r){let i=false;const a=e?getNodeSqliteKysely(e):void 0;const o=r??(e?readClientCredentialReceipt(e)?.receipt:void 0);const s={primary:`device`,node:`node-device`,shareExtension:`share-device`};for(const r of[`primary`,`node`,`shareExtension`])for(const c of[`identity`,`auth`]){if(o?.legacyImports[`${c}:${r}`])continue;const l=`${s[r]}${c===`auth`?`-auth`:``}.json`;const u=path.join(resolveStateDir(t),`identity`,l);if([u,`${u}.doctor-importing`,`${u}.native-importing`].some(e=>fs.existsSync(e))){if(c===`identity`&&e&&a&&executeSqliteQueryTakeFirstSync(e,a.selectFrom(`device_identities`).select(`identity_key`).where(`identity_key`,`=`,r)))continue;throw new ClientCredentialMigrationRequiredError(`Legacy client credentials require migration; run openclaw doctor --fix before using this client.`)}if(n&&o){o.legacyImports[`${c}:${r}`]={sha256:null};i=true}}if(i&&o&&e)writeClientCredentialReceipt(e,o,`complete`)}function assertMissingClientCredentialStoreReady(e){assertClientCredentialLegacyReady(null,e);if(readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(e)))throw notReady()}function prepareClientCredentialReceipt(e,t,n,r=false,i=readClientCredentialReceipt(e)){let a=i;const o=readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(t));if(!a&&n&&!o){assertClientCredentialLegacyReady(null,t);const n=emptyClientCredentialReceipt();for(const e of CLIENT_CREDENTIAL_LEGACY_KEYS)n.legacyImports[e]={sha256:null};writeClientCredentialReceipt(e,n,`complete`);a={phase:`complete`,receipt:n}}if(!a||a.phase!==`complete`)throw notReady();if(a.receipt.source?.kind===`independent`){const t=a.receipt.sharedFile;const n=readIndependentClientCredentialSource(t.path);if(n.identity!==a.receipt.source.identity||n.file.path!==t.path||n.file.dev!==t.dev||n.file.ino!==t.ino||n.sha256!==a.receipt.source.sha256){if(r)throw new Error(`Independent client credentials changed; open the client or run openclaw doctor --fix before read-only inspection.`);const t=getNodeSqliteKysely(e);executeSqliteQuerySync(e,t.deleteFrom(`device_auth_tokens`));executeSqliteQuerySync(e,t.deleteFrom(`device_identities`));executeSqliteQuerySync(e,t.deleteFrom(`gateway_origin_device_tokens`));for(const r of chunkItems(n.rows.identities,500))executeSqliteQuerySync(e,t.insertInto(`device_identities`).values(r));for(const r of chunkItems(n.rows.tokens,500))executeSqliteQuerySync(e,t.insertInto(`device_auth_tokens`).values(r));a.receipt.source={kind:`independent`,engine:`native-v0`,identity:n.identity,generation:`0`,sha256:n.sha256,destinationVersion:1};a.receipt.sharedFile=n.file;writeClientCredentialReceipt(e,a.receipt,`complete`)}}else{const e=a.receipt.sharedFile;if(e===null?o!==null:o===null||e.path!==o.path||e.dev!==o.dev||e.ino!==o.ino)throw notReady()}return a}function assertClientCredentialStoreReady(e,t,n){prepareClientCredentialReceipt(e,t,n)}function admitClientCredentialStore(e,t,n){const r=prepareClientCredentialReceipt(e,t,n.initialize,n.readOnly,n.stored);assertClientCredentialLegacyReady(e,t,!n.readOnly,r.receipt);return r.receipt} //!src/infra/client-credential-operations.ts function encodeClientNativeTokenRole(e,t){return`v2.${Buffer.from(t).toString(`base64url`)}.${Buffer.from(e.trim()).toString(`base64url`)}`}function decodeRole(e){const t=e.split(`.`);if(t.length===3&&t[0]===`v2`&&t[1]!==void 0&&t[2]!==void 0)try{const decode=e=>{if(!/^[A-Za-z0-9_-]*$/u.test(e)||e.length%4===1)throw new Error(`Invalid component`);return new TextDecoder(`utf-8`,{fatal:true}).decode(Buffer.from(e,`base64url`))};return{gateway:decode(t[1]),role:decode(t[2])}}catch{}return{role:e,gateway:null}}function clearClientNativeTokens(e,t,n){const r=getNodeSqliteKysely(e);if(n.kind===`all`)return Number(executeSqliteQuerySync(e,r.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t)).numAffectedRows);const i=executeSqliteQuerySync(e,r.selectFrom(`device_auth_tokens`).select(`role`).where(`device_id`,`=`,t)).rows.filter(({role:e})=>{const t=decodeRole(e);if(n.kind===`role`)return t.role===n.role.trim();if(n.kind===`gateway`)return t.gateway===n.gateway;return t.gateway===null}).map(({role:e})=>e);if(i.length===0)return 0;executeSqliteQuerySync(e,r.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t).where(`role`,`in`,i));return i.length}function claimClientNativeToken(e,t,n,r){const i=getNodeSqliteKysely(e);const a=n.trim();const o=executeSqliteQueryTakeFirstSync(e,i.selectFrom(`device_auth_tokens`).selectAll().where(`device_id`,`=`,t).where(`role`,`=`,a));if(!o)return false;executeSqliteQuerySync(e,i.insertInto(`device_auth_tokens`).values({...o,role:encodeClientNativeTokenRole(n,r)}).onConflict(e=>e.columns([`device_id`,`role`]).doNothing()));executeSqliteQuerySync(e,i.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t).where(`role`,`=`,a));return true}function performClientCredentialOperation(e,t,n){const r=getNodeSqliteKysely(e);switch(t.kind){case`identity.read`:case`identity.create`:case`identity.repair`:{const n=t.kind===`identity.read`?t.identity_key:t.identity.identity_key;const i=executeSqliteQueryTakeFirstSync(e,r.selectFrom(`device_identities`).selectAll().where(`identity_key`,`=`,n));if(t.kind===`identity.repair`){if(i)try{storedDeviceIdentityFromRow(i,n);return{kind:`identityRepair`,identity:i,repaired:false,rotated:false}}catch{}const a=i?salvageStoredIdentityRow(i,n,t.identity.updated_at_ms):null;const o=a?storedDeviceIdentityToRow(n,a,t.identity.updated_at_ms):t.identity;storedDeviceIdentityFromRow(o,n);executeSqliteQuerySync(e,r.insertInto(`device_identities`).values(o).onConflict(e=>e.column(`identity_key`).doUpdateSet(o)));return{kind:`identityRepair`,identity:o,repaired:true,rotated:a===null}}if(i){storedDeviceIdentityFromRow(i,n);return{kind:`identity`,identity:i}}if(t.kind===`identity.create`){storedDeviceIdentityFromRow(t.identity,n);executeSqliteQuerySync(e,r.insertInto(`device_identities`).values(t.identity));return{kind:`identity`,identity:t.identity}}return{kind:`identity`,identity:null}}case`native.tokens.clear`:return{kind:`cleared`,count:clearClientNativeTokens(e,t.device_id,t.selector)};case`native.token.claim`:return{kind:`changed`,changed:claimClientNativeToken(e,t.device_id,t.role,t.gateway)};case`token.list`:{const n=t.gateway_scope===void 0?`device_auth_tokens`:`gateway_origin_device_tokens`;let i=r.selectFrom(n).selectAll().where(`device_id`,`=`,t.device_id);if(t.gateway_scope!==void 0)i=i.where(`gateway_scope`,`=`,t.gateway_scope);if(t.afterRole!==void 0)i=i.where(`role`,`>`,t.afterRole);const a=Math.max(1,Math.min(32,Math.trunc(t.limit??32)));const o=executeSqliteQuerySync(e,i.orderBy(`role`).limit(a+1)).rows;const s=o.slice(0,a).map(({device_id:e,role:t,token:n,scopes_json:r,updated_at_ms:i})=>({device_id:e,role:t,token:n,scopes_json:r,updated_at_ms:i}));return{kind:`tokens`,tokens:s,nextRole:o.length>a?s.at(-1)?.role??null:null}}case`token.read`:case`token.replace`:case`token.remove`:{const{key:n}=t;const i=n.gateway_scope===void 0?`device_auth_tokens`:`gateway_origin_device_tokens`;const a=expressionBuilder();const o=a.and([a(`device_id`,`=`,n.device_id),a(`role`,`=`,n.role),...n.gateway_scope===void 0?[]:[a(`gateway_scope`,`=`,n.gateway_scope)]]);const s=r.selectFrom(i).selectAll().where(o);if(t.kind===`token.read`){const t=executeSqliteQueryTakeFirstSync(e,s);return{kind:`token`,token:t?{device_id:t.device_id,role:t.role,token:t.token,scopes_json:t.scopes_json,updated_at_ms:t.updated_at_ms}:null}}const c=executeSqliteQueryTakeFirstSync(e,s);const l=t.expectedToken===void 0?t.kind!==`token.remove`||t.observedToken===void 0:(c?.token??null)===t.expectedToken;const u=t.kind===`token.remove`&&t.observedToken!==void 0&&c?.token===t.observedToken&&(t.expectedToken===void 0||typeof t.expectedToken===`string`&&t.observedToken.trim()===t.expectedToken);if(!(l||u))return{kind:`changed`,changed:false};if(t.kind===`token.remove`){if(!c)return{kind:`changed`,changed:false};executeSqliteQuerySync(e,r.deleteFrom(i).where(o))}else{const i={...t.token,device_id:n.device_id,role:n.role};if(n.gateway_scope===void 0)executeSqliteQuerySync(e,r.insertInto(`device_auth_tokens`).values(i).onConflict(e=>e.columns([`device_id`,`role`]).doUpdateSet(i)));else executeSqliteQuerySync(e,r.insertInto(`gateway_origin_device_tokens`).values({...i,gateway_scope:n.gateway_scope}).onConflict(e=>e.columns([`gateway_scope`,`device_id`,`role`]).doUpdateSet(i)))}return{kind:`changed`,changed:true}}case`socket.read`:case`socket.ensure`:{const i=executeSqliteQueryTakeFirstSync(e,r.selectFrom(`native_exec_socket_credentials`).selectAll().where(`socket_key`,`=`,`current`))??null;if(t.kind===`socket.read`)return{kind:`socket`,socket:i};const a=t.requested?.path?.trim();const o=i?.socket_path;const s=!a&&o===path.join(n,`exec-approvals.sock`)&&o!==t.fallback.socket_path;const c={socket_key:`current`,socket_path:a||(s?t.fallback.socket_path:o)||t.fallback.socket_path,socket_token:t.requested?.token?.trim()||i?.socket_token||t.fallback.socket_token,updated_at_ms:t.fallback.updated_at_ms};if(i&&i.socket_path===c.socket_path&&i.socket_token===c.socket_token)return{kind:`socket`,socket:i};executeSqliteQuerySync(e,r.insertInto(`native_exec_socket_credentials`).values(c).onConflict(e=>e.column(`socket_key`).doUpdateSet(c)));return{kind:`socket`,socket:c}}default:throw new Error(`Unsupported client credential operation.`)}} //!src/infra/client-credential-store.ts const retainedPaths=resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialCustody`),()=>/* @__PURE__ */ new Set);const admittedFiles=resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialAdmittedFiles`),()=>/* @__PURE__ */ new Map,e=>e.clear());var ClientCredentialBusyError=class extends Error{constructor(){super(`Client credential owner is busy.`);this.name=`ClientCredentialBusyError`}};function isClientCredentialBusyError(e){return e instanceof ClientCredentialBusyError||isSqliteLockError(e)}const schemaAdmission={name:`client.credentials.schema-v1`,schemaDependent:true,read:e=>e===true?true:void 0};function assertPrivateAcl(e){if(process.platform===`darwin`&&inspectDarwinAcl(e).kind!==`none`)throw new Error(`Client credentials require a private directory and file without ACL entries.`)}function openClientCredentialCustody(...e){const t=openClientCredentialCustodySteps(...e);let n=t.next();while(!n.done)try{n.value.admit();n=t.next()}catch(e){n=t.throw(e)}return n.value}async function openClientCredentialCustodyAsync(...e){resolveSqliteInspectionSignal(getAsyncWorkSignal())?.throwIfAborted();const t=openClientCredentialCustodySteps(...e);let n=t.next();while(!n.done)try{const e=n.value;await runUpdateSqliteMigrationAsync(e.database,e.path,e.admit,{created:e.created,retainExclusive:true});n=t.next()}catch(e){n=t.throw(e)}return n.value}function runClientCredentialTransactionAsync(e,t){return runUpdateSqliteMigrationAsync(e.database,e.path,()=>e.transaction(t),{retainExclusive:true})}function*openClientCredentialCustodySteps(e,t={},n){const r=t.readOnly===true||t.inspect===true;const i=(t.createIfMissing??false)&&!r;const a=resolveClientCredentialStorePath(e);const o=t.inspect===true&&!fs.existsSync(`${a}-journal`);const s=path.dirname(a);const c=resolveDatabasePathKey(a);if(retainedPaths.has(c))throw new ClientCredentialBusyError;if(t.migration)admittedFiles.delete(c);if(!t.migration&&!fs.existsSync(a))assertMissingClientCredentialStoreReady(e);const l=fs.lstatSync(s,{throwIfNoEntry:false});if(l&&(!l.isDirectory()||process.getuid&&l.uid!==process.getuid()||process.platform!==`win32`&&(l.mode&63)!==0))throw new Error(`Client credential directory is unsafe.`);if(!l&&!i)return;if(l)assertPrivateAcl(s);let u=false;if(i)u=preparePrivateStoreFileSync(a,Boolean(l));const d=openRootFileSync({absolutePath:a,rootPath:s,boundaryLabel:`client credential store`,rejectSymlinks:true});if(!d.ok){if(hasErrnoCode(d.error,`ENOENT`)&&!i)return;throw new Error(`Client credential store cannot be safely opened.`,{cause:d.error})}retainedPaths.add(c);let f;let p=false;let physicalClose;try{const s=fs.fstatSync(d.fd,{bigint:true});if(process.getuid&&s.uid!==BigInt(process.getuid())||process.platform!==`win32`&&(s.mode&63n)!==0n)throw new Error(`Client credential store owner is unsafe.`);const l=`${s.dev}:${s.ino}:${readDatabaseIdentityBirthtime(s)}`;assertPrivateAcl(a);f=o?openNodeSqliteDatabase(resolveReadOnlyShmSqliteFileUri(a),{readOnly:true,timeout:t.timeoutMs??5e3}):openNodeSqliteDatabase(resolveExistingSqliteFileUri(a),{timeout:t.timeoutMs??5e3});const m=f;if(f.prepare(`PRAGMA journal_mode`).get()?.journal_mode!==`delete`)throw new Error(`Client credentials require DELETE journal mode for exclusive owner custody.`);physicalClose=()=>{if(!p){p=true;try{m.close()}finally{fs.closeSync(d.fd);retainedPaths.delete(c)}}};const transaction=e=>{if(p)throw new Error(`Client credential custody is closed.`);if(o)return runSqliteDeferredTransactionSync(m,e);if(r)return runSqliteImmediateTransactionSync(m,e);return runUpdateSqliteMigration(m,a,()=>runSqliteImmediateTransactionSync(m,e),{retainExclusive:true})};const h=admittedFiles.get(c);let g=false;let _=false;yield{database:m,path:a,created:u,admit:()=>transaction(()=>{if(!o)m.exec(`PRAGMA locking_mode=EXCLUSIVE`);if(t.migration||h?.identity!==l||h.version!==1){const e=readSqliteUserVersion(m);if(e===0&&!m.prepare(`SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'`).get()){if(!i)throw new Error(`Client credential store is empty; run openclaw doctor --fix.`);m.exec(CLIENT_CREDENTIAL_SCHEMA_SQL);g=true;writeSqliteUserVersion(m,1)}else{if(e!==1)throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`);assertSqliteSchemaContains(m,`Client credentials`,CLIENT_CREDENTIAL_SCHEMA_SQL);assertSqliteIntegrity(m,`Client credentials`)}publishSqliteDatabaseAdmission(m,schemaAdmission,true)}if(!t.migration){const t=readClientCredentialAdmission(m);const n=admitClientCredentialStore(m,e,{initialize:g,readOnly:r,stored:t.stored});_=n.sharedFile!==null&&n.source===null}if(!g)n?.(m)})};if(g&&n)yield{database:m,path:a,created:u,admit:()=>transaction(()=>n(m))};if(!t.migration)admittedFiles.set(c,{identity:l,version:1});return{database:m,path:a,created:u,needsMetadataUpgrade:_,transaction,run(t,n){if(p)throw new Error(`Client credential custody is closed.`);if(r&&isClientCredentialMutation(t))throw new Error(`Client credential custody is read-only.`);const run=()=>{const r=performClientCredentialOperation(m,t,resolveStateDir(e));n?.();return r};return transaction(run)},close:physicalClose,[Symbol.dispose]:physicalClose}}catch(e){admittedFiles.delete(c);if(physicalClose)physicalClose();else{f?.close();fs.closeSync(d.fd);retainedPaths.delete(c)}throw e}}function clientCredentialOperationCreatesStore(e){return[`identity.create`,`identity.repair`,`token.replace`,`socket.ensure`].includes(e.kind)}function isClientCredentialMutation(e){return![`identity.read`,`token.read`,`token.list`,`socket.read`].includes(e.kind)}function runClientCredentialOperation(e,t,n={}){try{var r=_usingCtx();if((n.readOnly||n.inspect)&&isClientCredentialMutation(t))throw new Error(`Client credential custody is read-only.`);let i;return r.u(openClientCredentialCustody(e,{createIfMissing:clientCredentialOperationCreatesStore(t),readOnly:n.readOnly,inspect:n.inspect},r=>{i=performClientCredentialOperation(r,t,resolveStateDir(e));n.beforeCommit?.()}))?i:missingClientCredentialResult(e,t)}catch(e){r.e=e}finally{r.d()}}async function runClientCredentialOperationForDoctor(e,t,n={}){try{var r=_usingCtx();if(n.readOnly&&isClientCredentialMutation(t))throw new Error(`Client credential custody is read-only.`);let i;return r.u(await openClientCredentialCustodyAsync(e,{createIfMissing:clientCredentialOperationCreatesStore(t),readOnly:n.readOnly},r=>{i=performClientCredentialOperation(r,t,resolveStateDir(e));n.beforeCommit?.()}))?i:missingClientCredentialResult(e,t)}catch(e){r.e=e}finally{r.d()}}function missingClientCredentialResult(e,t){assertMissingClientCredentialStoreReady(e);switch(t.kind){case`identity.read`:return{kind:`identity`,identity:null};case`token.read`:return{kind:`token`,token:null};case`token.list`:return{kind:`tokens`,tokens:[],nextRole:null};case`socket.read`:return{kind:`socket`,socket:null};case`native.tokens.clear`:return{kind:`cleared`,count:0};default:return{kind:`changed`,changed:false}}}export{runClientCredentialOperation as a,ClientCredentialMigrationRequiredError as c,writeClientCredentialReceipt as d,isNativeClientCredentialBootstrap as f,openClientCredentialCustodyAsync as i,assertClientCredentialStoreReady as l,isClientCredentialMutation as n,runClientCredentialOperationForDoctor as o,readIndependentClientCredentialSource as p,openClientCredentialCustody as r,runClientCredentialTransactionAsync as s,isClientCredentialBusyError as t,readClientCredentialReceipt as u};