UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

82 lines • 46 kB
import{ct as isMissingPathError,ft as normalizeLowercaseStringOrEmpty,gt as asNullableRecord,ht as normalizeOptionalString,it as resolveGlobalSingleton,p as LruCache,s as shortenHomePath,yt as isRecord,z as runInDetachedAsyncContext}from"./paths--OfTlHNJ.js";import{j as escapeRegExp}from"./subsystem-ClzPkrHG.js";import"./path-existence-CCBbp2xL.js";import"./sqlite-readonly-worker-CJyn3oRb.js";import{t as resolveOpenClawPackageRootSync}from"./openclaw-root-DaTD-hFc.js";import{Gn as resolveRuntimeProcessEntrypointUrl,Gt as retainSqliteWorkerErrorCode,Ht as hasSqliteWorkerErrorCode,Ot as markSqliteNativeOpenFailure,Tt as isSqliteNativeOpenFailure,Vt as SqliteWorkerError,an as OpenClawStateOwnershipMetadataError,cn as SqliteSnapshotDirectoryBusyError,d as createRetainedOperation,f as finallyRetainedOperation,in as OpenClawStateOwnershipError,m as mapRetainedOperation,on as SqliteCoordinatorError,p as flatMapRetainedOperation,r as captureRuntimeWorkerSource,rn as OpenClawStateExternalOwnershipError,sn as SqliteSnapshotCleanupError,un as createSqliteLifecycleAggregateError,wt as isSqliteLockError}from"./sqlite-worker-request-class-l9sdQxsj.js";import{A as sealRetainedSnapshotTempDirectory,M as startRemoveTempDirectory,Nt as executeWithCachedStatement,w as registerRetainedSnapshotTempDirectory}from"./openclaw-state-db-async-lifecycle-DFpGMybR.js";import"./errors-Bn-s0XYn.js";import{C as GatewayStateOwnerContentionError,D as StateDatabaseOfflineMaintenanceError,E as StateDatabaseMaintenanceScopeError,T as StateDatabaseAdmissionPendingError,w as StateDatabaseAccessError,x as recordWorkerMessage}from"./sqlite-worker-operation-settlement-DUfe98Na.js";import{g as DEFAULT_WORKER_PENDING_BYTES}from"./worker-request-diagnostics-D8vk7d55.js";import{o as OPENCLAW_DATABASE_SCHEMA_DOCS_URL}from"./openclaw-state-db-contract-lz-66XzZ.js";import{h as captureRetainedNativeWorkerSource,n as createOwnedWorkerTaskPool}from"./worker-task-pool-D981bQaU.js";import{createRequire}from"node:module";import path from"node:path";import"@openclaw/fs-safe/path";import fs from"node:fs";import{readFileDescriptorBoundedSync,readFileWindowFullySync}from"@openclaw/fs-safe/advanced";import{createHash}from"node:crypto";import{fileURLToPath}from"node:url";import{MessageChannel,receiveMessageOnPort,threadId}from"node:worker_threads";import{isUtf8}from"node:buffer"; //!src/state/openclaw-quarantine-error.ts const DATABASE_QUARANTINE_READ_CLEANUP_ERROR_NAME=`OpenClawQuarantineReadCleanupError`;const OpenClawQuarantineReadCleanupError=resolveGlobalSingleton(Symbol.for(`openclaw.quarantineReadCleanupError`),()=>class QuarantineReadCleanupError extends AggregateError{constructor(e,t){super(e,`OpenClaw quarantine reader cleanup failed.`,{cause:e[0]});this.quarantine=t;this.name=DATABASE_QUARANTINE_READ_CLEANUP_ERROR_NAME}}); //!src/state/openclaw-state-db-failure.ts const failurePaths=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseFailurePaths`),()=>/* @__PURE__ */ new WeakMap);function markOpenClawStateDatabaseFailure(e,t){failurePaths.set(e,t)}function readOpenClawStateDatabaseFailurePath(e){return failurePaths.get(e)}function findOpenClawStateDatabaseFailure(e,t){const n=[e];const r=/* @__PURE__ */ new Set;for(const e of n){if(!(e instanceof Error)||r.has(e))continue;r.add(e);if(failurePaths.get(e)===t)return e;n.push(e.cause);if(e instanceof AggregateError)n.push(...e.errors)}} //!src/agents/agent-create-error.ts var DuplicateAgentError=class extends Error{}; //!src/agents/auth-profiles/store-unreadable-error.ts const AUTH_PROFILE_MIGRATION_COMMAND=`openclaw doctor --fix`;var AuthProfileStoreUnreadableError=class extends Error{constructor(e){super(`Auth profile store ${shortenHomePath(e)} is unreadable; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`);this.databasePath=e;this.code=`AUTH_PROFILE_STORE_UNREADABLE`;this.action=AUTH_PROFILE_MIGRATION_COMMAND;this.name=`AuthProfileStoreUnreadableError`}}; //!src/agents/mcp-oauth-store-error.ts var McpOAuthStoreCorruptionError=class extends Error{constructor(e,t,n){super(`MCP OAuth store ${e} is invalid: ${t}`,n);this.name=`McpOAuthStoreCorruptionError`}}; //!src/agents/sandbox/state-owner-path.ts var SandboxStateOwnerRequiredError=class extends Error{constructor(e){super(`Sandbox workspace preparation cannot run alongside a foreign live owner of the selected state root, or when that ownership cannot be verified. Run this SDK call inside the owning Gateway plugin/runtime, or stop the Gateway through its service owner and wait for any embedded run to finish, then retry offline. Inspect openclaw gateway status; this call does not acquire ownership or route remotely.`,{cause:e});this.code=`GATEWAY_STATE_OWNER_REQUIRED`;this.name=`SandboxStateOwnerRequiredError`}}; //!src/agents/workspace-state-identity.ts const WORKSPACE_ALIAS_REPOINTED_ERROR_CODE=`WORKSPACE_ALIAS_REPOINTED`;var WorkspaceAliasRepointedError=class extends Error{constructor(e){super(`workspace path alias points to a different current target: ${e.aliasPath} now resolves to ${e.currentWorkspacePath}, but its stored workspace state belongs to ${e.storedWorkspacePath}. Run \`openclaw doctor --fix\` and confirm the move, or use \`openclaw doctor --fix --force\`.`);this.code=WORKSPACE_ALIAS_REPOINTED_ERROR_CODE;this.name=`WorkspaceAliasRepointedError`;this.aliasPath=e.aliasPath;this.storedWorkspacePath=e.storedWorkspacePath;this.currentWorkspacePath=e.currentWorkspacePath}}; //!src/agents/worktrees/errors.ts var WorktreeRemovalContentionError=class extends Error{constructor(e,t,n){super(t);this.kind=e;this.blockedByRun=n;this.name=`WorktreeRemovalContentionError`}};var WorktreeRemovalLockError=class extends Error{constructor(e,t){super(t);this.kind=e;this.name=`WorktreeRemovalLockError`}};var SessionWorktreeSourceChangedError=class extends Error{};var SessionWorktreeLifecycleError=class extends Error{constructor(e,t){super(e);this.reason=t}}; //!src/config/sessions/goals-operations.types.ts var SessionGoalOperationError=class extends Error{constructor(e,t){super(t);this.code=e;this.name=`SessionGoalOperationError`}}; //!src/config/sessions/session-canonical-key-error.ts var SessionCanonicalKeyMigrationRequiredError=class extends Error{constructor(e){super(`${e}; stop the Gateway and run openclaw doctor --fix`);this.code=`SESSION_CANONICAL_KEY_MIGRATION_REQUIRED`;this.name=`SessionCanonicalKeyMigrationRequiredError`}}; //!src/config/sessions/session-mutation-conflict-error.ts var SqliteSessionMutationConflictError=class extends Error{constructor(e){super(`SQLite session state changed while preparing ${e}`);this.operationLabel=e;this.name=`SqliteSessionMutationConflictError`}};var SqliteTranscriptMutationConflictError=class extends Error{constructor(e){super(`SQLite transcript changed while preparing rewrite for ${e}`);this.sessionId=e;this.name=`SqliteTranscriptMutationConflictError`}};var SessionEntryLifecycleUpsertConflictError=class extends Error{constructor(e){super(`SQLite session entry changed before lifecycle upsert for ${e}`);this.sessionKey=e;this.name=`SessionEntryLifecycleUpsertConflictError`}}; //!src/config/sessions/session-pending-input-custody-error.ts var SessionPendingInputCustodyError=class extends Error{}; //!src/config/sessions/session-transcript-read-fence-error.ts var SessionTranscriptReadFenceError=class extends Error{constructor(e){super(e);this.name=`SessionTranscriptReadFenceError`}}; //!src/config/sessions/session-transcript-writer-claim-error.ts function isRedactedIdentifier(e){return typeof e===`string`&&/^(?:-|sha256:[0-9a-f]{12})$/.test(e)}function parseTranscriptAppendRefusal(e){if(!isRecord(e)||!isRedactedIdentifier(e.agentIdHash)||!isRedactedIdentifier(e.expectedSessionIdHash)||!isRedactedIdentifier(e.sessionKeyHash))return;const t={agentIdHash:e.agentIdHash,expectedSessionIdHash:e.expectedSessionIdHash,sessionKeyHash:e.sessionKeyHash};if(e.code===`session-entry-missing`)return{...t,code:e.code};if(e.code===`session-rebound`&&isRedactedIdentifier(e.actualSessionIdHash))return{...t,code:e.code,actualSessionIdHash:e.actualSessionIdHash}}var SessionTranscriptWriterClaimReboundError=class extends Error{constructor(e){super(`session writer claim changed before transcript persistence`,{cause:e});this.name=`SessionTranscriptWriterClaimReboundError`}}; //!src/gateway/model-account-connect-errors.ts var ModelAccountConnectAuthorityError=class extends Error{constructor(){super(`This account action requires a current authorized connection; reconnect and try again.`)}}; //!src/gateway/worker-environments/session-attachment.ts var WorkerSessionAlreadyAttachedError=class extends Error{constructor(e,t){super(`Session ${e} is already attached to worker environment ${t}`);this.sessionId=e;this.environmentId=t}}; //!src/infra/sqlite-jsonl-budget-error.ts var SqliteJsonlReadBudgetExceededError=class extends Error{}; //!scripts/lib/release-version.mjs const RELEASE_VERSION_REGEX=/^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/;function parseReleaseVersion(e){const t=e.trim();const n=RELEASE_VERSION_REGEX.exec(t)?.groups;if(!n)return null;const r=Number(n.year);const i=Number(n.month);const a=Number(n.patch);const o=n.prerelease===void 0?void 0:Number(n.prerelease);const s=n.correction===void 0?void 0:Number(n.correction);if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||!Number.isSafeInteger(a)||i<1||i>12||a<1||o!==void 0&&!Number.isSafeInteger(o)||s!==void 0&&!Number.isSafeInteger(s))return null;const c=n.channel===`alpha`?`alpha`:n.channel===`beta`?`beta`:`stable`;return{version:t,baseVersion:`${r}.${i}.${a}`,channel:c,year:r,month:i,patch:a,alphaNumber:c===`alpha`?o:void 0,betaNumber:c===`beta`?o:void 0,...s===void 0?{}:{correctionNumber:s}}}function compareReleaseVersions(e,t){const n=parseReleaseVersion(e);const r=parseReleaseVersion(t);if(n===null||r===null)return null;if(n.year!==r.year)return Math.sign(n.year-r.year);if(n.month!==r.month)return Math.sign(n.month-r.month);if(n.patch!==r.patch)return Math.sign(n.patch-r.patch);if(n.channel!==r.channel){const e={alpha:0,beta:1,stable:2};return Math.sign(e[n.channel]-e[r.channel])}if(n.channel===`alpha`&&r.channel===`alpha`)return Math.sign((n.alphaNumber??0)-(r.alphaNumber??0));if(n.channel===`beta`&&r.channel===`beta`)return Math.sign((n.betaNumber??0)-(r.betaNumber??0));return Math.sign((n.correctionNumber??0)-(r.correctionNumber??0))} //!src/infra/git-root.ts function walkUpFrom(e,t,n){let r=path.resolve(e);for(let e=0;t.maxDepth===void 0||e<t.maxDepth;e+=1){const e=n(r);if(e!==null&&e!==void 0)return e;const t=path.dirname(r);if(t===r)break;r=t}return null}function readGitMetadataFile(e,t=1048576){const n=fs.openSync(e,fs.constants.O_RDONLY|(fs.constants.O_NONBLOCK??0));try{const e=fs.fstatSync(n);if(!e.isFile()||e.size>t)throw new Error(`Git metadata is not a bounded regular file`);const r=readFileDescriptorBoundedSync(n,Math.min(e.size,t));if(r.length!==e.size)throw new Error(`Git metadata changed during its read`);return r}finally{fs.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){const n=readGitMetadataFile(e);const r=n.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!isUtf8(n)||!r.startsWith(t)||r.length===t.length||r.includes(`\0`))throw new Error(`Git directory pointer is incomplete or malformed`);const i=r.slice(t.length);return path.isAbsolute(i)?i:`${path.dirname(e)}${path.sep}${i}`}function readGitDirectoryPointer(e,t=``){return fs.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){const t=path.join(e,`.git`);try{const e=fs.statSync(t);if(e.isDirectory())return t;if(!e.isFile())return null;return readGitDirectoryPointer(t,`gitdir: `)}catch{return null}}function resolveGitHeadPath(e,t={}){return walkUpFrom(e,t,e=>{const t=resolveGitDirFromMarker(e);return t?path.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){const n=fs.openSync(e,fs.constants.O_RDONLY|(fs.constants.O_NONBLOCK??0));try{if(!fs.fstatSync(n).isFile())throw new Error(`Git metadata is not a regular file`);const e=Buffer.alloc(t);const r=readFileWindowFullySync(n,e,0);return e.subarray(0,r).toString(`utf-8`)}finally{fs.closeSync(n)}}function readGitHead(e,t={}){const n=resolveGitHeadPath(e,t);if(!n)return;const r=readGitMetadataFile(n).toString(`utf8`).trim();if(!r.startsWith(`ref:`))return{headPath:n,ref:null,value:r||null};const i=r.replace(/^ref:\s*/i,``).trim();const a=resolveGitRefsBase(n);return{headPath:n,ref:i,value:readGitRefs(a,[i]).get(i)??null,refsBase:a}}function resolveGitRefsBase(e){const t=path.dirname(e);const n=path.join(t,`commondir`);try{return readGitDirectoryPointer(n)}catch(e){if(!isMissingPathError(e)||fs.lstatSync(n,{throwIfNoEntry:false}))throw e}return t}function readGitRefs(e,t){const n=new Map(t.map(e=>[e,null]));const r=/* @__PURE__ */ new Set;for(const i of t){const t=resolveRefPath(e,i);if(!t)continue;try{n.set(i,readGitMetadataPrefix(t).trim())}catch(e){if(!isMissingPathError(e))throw e;r.add(i)}}if(r.size===0)return n;try{const t=readGitMetadataFile(path.join(e,`packed-refs`),Number.MAX_SAFE_INTEGER).toString(`utf8`);const i=new RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(escapeRegExp).join(`|`)})(?=\\s|$)`,`gm`);for(const[,e,a]of t.matchAll(i))if(r.delete(a))n.set(a,e)}catch(e){if(!isMissingPathError(e))throw e}return n}function resolveRefPath(e,t){if(!t.startsWith(`refs/`))return null;if(t.split(/[/]/).includes(`..`))return null;const n=path.resolve(e,t);const r=path.relative(e,n);if(!r||r.startsWith(`..`)||path.isAbsolute(r))return null;return n} //!src/infra/git-commit.ts const formatCommit=e=>{const t=e?.match(/[0-9a-fA-F]{7,40}/);return t?normalizeLowercaseStringOrEmpty(t[0].slice(0,7)):null};const cachedGitCommitBySearchDir=new LruCache(256);const resolveCommitSearchDir=e=>{if(e.cwd)return path.resolve(e.cwd);if(e.moduleUrl)try{return path.dirname(fileURLToPath(e.moduleUrl))}catch{}return process.cwd()};const cacheGitCommit=(e,t)=>{cachedGitCommitBySearchDir.set(e,t);return t};const resolveGitLookupDepth=(e,t)=>{if(!t)return;const n=path.relative(t,e);if(n.startsWith(`..`)||path.isAbsolute(n))return;return(n?n.split(path.sep).filter(Boolean).length:0)+1};const readCommitFromGit=(e,t)=>{const n=readGitHead(e,{maxDepth:resolveGitLookupDepth(e,t)});return n===void 0?void 0:formatCommit(n.value)};const readCommitFromPackageJson=()=>{try{const e=createRequire(import.meta.url)(`../../package.json`);return formatCommit(e.gitHead??e.githead??null)}catch{return null}};const readCommitProbe=(e,t,n)=>{try{for(const r of t){const t=fileURLToPath(new URL(r,e));let i;try{i=readGitMetadataPrefix(t,1024)}catch(e){if(isMissingPathError(e))continue;return null}try{const e=asNullableRecord(JSON.parse(i))?.[n];return typeof e===`string`?formatCommit(e):null}catch{return null}}}catch{}};const readCommitFromBuildInfo=(e=import.meta.url)=>{return readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)??null};const readLoadedCommit=e=>{const t=readCommitProbe(e,[`../.buildstamp`,`./.buildstamp`],`head`);const n=readCommitProbe(e,[`../.runtime-postbuildstamp`,`./.runtime-postbuildstamp`],`head`);if(t!==void 0||n!==void 0){if(t||n)return t&&t===n?t:null;return readCommitFromBuildInfo(e)}return readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)};const resolveCommitHash=(e={})=>{const t=e.env??process.env;const n=t.GIT_COMMIT?.trim()||t.GIT_SHA?.trim();const r=formatCommit(n);if(r)return r;const i=resolveCommitSearchDir(e);const a=cachedGitCommitBySearchDir.get(i);if(a!==void 0)return a;const o=resolveOpenClawPackageRootSync({cwd:e.cwd,moduleUrl:e.moduleUrl});try{const e=readCommitFromGit(i,o);if(e!==void 0)return cacheGitCommit(i,e)}catch{}const s=readCommitFromBuildInfo();if(s)return cacheGitCommit(i,s);const c=readCommitFromPackageJson();if(c)return cacheGitCommit(i,c);return cacheGitCommit(i,null)};function resolveLoadedCommitHash(e={}){const t=e.moduleUrl??import.meta.url;const n=readLoadedCommit(t);return n===void 0?resolveCommitHash({moduleUrl:t,...e.env?{env:e.env}:{}}):n} //!src/version.ts const CORE_PACKAGE_NAME=`openclaw`;const PACKAGE_JSON_CANDIDATES=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`];const BUILD_INFO_CANDIDATES=[`../build-info.json`,`../../build-info.json`,`./build-info.json`];function readStringFromJsonCandidates(e,t,n,r=false){try{const i=createRequire(e);for(const e of t)try{const t=i(e);const a=normalizeOptionalString(t[n]);if(!a)continue;if(r&&t.name!==CORE_PACKAGE_NAME)continue;return a}catch{}return null}catch{return null}}function firstNonEmpty(...e){for(const t of e){const e=normalizeOptionalString(t);if(e&&e.toLowerCase()!==`undefined`&&e.toLowerCase()!==`null`)return e}}function readVersionFromPackageJsonForModuleUrl(e){return readStringFromJsonCandidates(e,PACKAGE_JSON_CANDIDATES,`version`,true)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,BUILD_INFO_CANDIDATES,`version`)}function readBuildProvenanceForModuleUrl(e){try{const t=createRequire(e);for(const e of BUILD_INFO_CANDIDATES)try{const n=t(e);const r=normalizeOptionalString(n.buildId);if(r&&r.length<=96){const i={buildId:r};for(const e of[`version`,`commit`,`builtAt`]){const t=normalizeOptionalString(n[e]);if(t)i[e]=t}try{i.buildInfoPath=t.resolve(e)}catch{}return i}}catch{}}catch{}return null}function resolveVersionFromModuleUrl(e){return readVersionFromBuildInfoForModuleUrl(e)||readVersionFromPackageJsonForModuleUrl(e)}function resolveBinaryVersion(e){return resolveVersionFromModuleUrl(e.moduleUrl)||firstNonEmpty(e.bundledVersion)||`0.0.0`}const RUNTIME_SERVICE_BUILD=readBuildProvenanceForModuleUrl(import.meta.url);const RUNTIME_SERVICE_COMMIT=resolveLoadedCommitHash({moduleUrl:import.meta.url});function resolveRuntimeServiceCommit(){return RUNTIME_SERVICE_COMMIT}const VERSION=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION}); //!src/infra/startup-maintenance-required.ts const GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON=`gateway.maintenance_required`;const maintenanceReasons={"state-migrations":`state migration`,"newer-schema":`a newer OpenClaw build`,"agent-media":`offline media migration`,"audit-events-v2":`state database schema migration`,"legacy-workshop-review-index":`state database schema migration`,"legacy-cron-run-logs":`cron run history migration`,"legacy-workspace":`workspace setup state migration`,"legacy-session-store":`session store migration`};var StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n);this.kind=e;this.code=GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON;this.name=`StartupMaintenanceRequiredError`}get reason(){return maintenanceReasons[this.kind]}}; //!src/infra/sqlite-user-version.ts const SQLITE_SCHEMA_VERSION_ERROR_NAME=`SqliteSchemaVersionError`;var SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e);this.name=SQLITE_SCHEMA_VERSION_ERROR_NAME}};function isSqliteSchemaVersionError(e){return e instanceof SqliteSchemaVersionError||e instanceof Error&&e.name===SQLITE_SCHEMA_VERSION_ERROR_NAME}function readSqliteUserVersion(e){const t=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get());return Number(t?.user_version??0)}function readSqliteWriterAppVersion(e){try{const t=executeWithCachedStatement(e,`SELECT app_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`,[],e=>e.get());return typeof t?.app_version===`string`&&t.app_version.length>0?t.app_version:void 0}catch{return}}function writeSqliteUserVersion(e,t){if(!Number.isInteger(t)||t<0||t>2147483647)throw new RangeError(`SQLite user_version must be an integer from 0 through 2147483647.`);e.exec(`PRAGMA user_version = ${t}`)}function describeRunningOpenClawBuild(){const e=resolveRuntimeServiceCommit();const t=resolveOpenClawPackageRootSync({moduleUrl:import.meta.url});const n=e?`OpenClaw ${VERSION} (${e})`:`OpenClaw ${VERSION}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,VERSION)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){const o=isNewerSqliteWriterVersion(i);const s=o?`; it is newer than this Gateway (${VERSION}).`:a===`runtime`?`; run openclaw doctor --fix to inspect this database.`:`.`;return new SqliteSchemaVersionError(`This OpenClaw build cannot open your existing data. ${e} ${t} uses newer schema version ${n}; this build supports ${r}.\n`+(i&&(a===`runtime`||i!==VERSION)?`It was written by OpenClaw ${i}${s}\n`:``)+`Refused by ${describeRunningOpenClawBuild()}.\n`+(o?`Use the newer install that supports schema ${n} or newer, or run openclaw update to update this Gateway service before restarting. To use an older build, restore your pre-update backup created with openclaw backup create.\n`:`Use a build that supports schema ${n} or newer with this state directory. To use an older build, restore your pre-update backup created with openclaw backup create.\n`)+`See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`)} //!src/plugin-state/plugin-blob-store.types.ts var PluginBlobStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause});this.name=`PluginBlobStoreError`;this.code=t.code;this.operation=t.operation;if(t.path)this.path=t.path}}; //!src/plugin-state/plugin-state-error-cause.ts function capturePluginStateErrorCause(e,t,n=/* @__PURE__ */ new Set){if(e===void 0)return;const r=t?.(e);if(r)return{canonical:r};if(e===null||typeof e===`string`||typeof e===`number`||typeof e===`boolean`||typeof e===`bigint`||typeof e===`symbol`)return{name:`Error`,message:String(e)};if(typeof e!==`object`)return{name:`Error`,message:`Unknown SQLite error cause`};if(n.has(e)||n.size>=8)return{name:`Error`,message:`Additional SQLite error cause omitted`};n.add(e);const i=`name`in e&&typeof e.name===`string`?e.name:`Error`;const a=`message`in e&&typeof e.message===`string`?e.message:i;const o=`code`in e?e.code:void 0;const s=`errcode`in e?e.errcode:void 0;const c=`errno`in e?e.errno:void 0;return{name:i,message:a,...typeof o===`string`||typeof o===`number`?{errorCode:o}:{},...typeof s===`number`?{errcode:s}:{},...typeof c===`number`?{errno:c}:{},...`cause`in e?{cause:capturePluginStateErrorCause(e.cause,t,n)}:{},...e instanceof AggregateError?{errors:e.errors.slice(0,8).map(e=>capturePluginStateErrorCause(e,t,n))}:{}}} //!src/plugin-state/plugin-state-error.ts var PluginStateStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause});this.name=`PluginStateStoreError`;this.code=t.code;this.operation=t.operation;this.owner=t.owner??{pid:process.pid,threadId,version:VERSION};if(t.path)this.path=t.path}toJSON(){return{name:this.name,message:this.message,code:this.code,operation:this.operation,path:this.path,owner:this.owner,cause:capturePluginStateErrorCause(this.cause)}}}; //!src/secrets/store/secret-store-validation-error.ts var SecretStoreValidationError=class extends Error{constructor(e,t){super(t);this.code=e;this.name=`SecretStoreValidationError`}}; //!src/sessions/model-selection-error.ts const MODEL_SELECTION_LOCKED_MESSAGE=`Model selection is locked for this session.`;var ModelSelectionLockedError=class extends Error{constructor(e=MODEL_SELECTION_LOCKED_MESSAGE){super(e);this.name=`ModelSelectionLockedError`}}; //!src/skills/lifecycle/upload-store-error.ts var SkillUploadRequestError=class extends Error{constructor(...e){super(...e);this.name=`SkillUploadRequestError`}}; //!src/skills/skill-library-error.ts var SkillLibraryError=class extends Error{constructor(e,t,n,r){super(t,r);this.code=e;this.currentRevision=n;this.name=`SkillLibraryError`}}; //!src/state/openclaw-agent-db-migration-required.ts var OpenClawAgentDatabaseMediaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(`agent-media`,`OpenClaw agent database ${e} uses schema version ${t}; run openclaw doctor --fix to migrate persisted media before using it.`);this.pathname=e;this.schemaVersion=t;this.name=`OpenClawAgentDatabaseMediaMigrationRequiredError`}}; //!src/state/openclaw-state-db-schema-migration-required.ts const LEGACY_SKILL_WORKSHOP_COLLECTION_REVIEWS_INDEX=`idx_skill_workshop_collection_reviews_workspace_time`;var OpenClawStateDatabaseSchemaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(e,`OpenClaw state database schema migration required (${e}) at ${t}; run openclaw doctor --fix to migrate it.`);this.kind=e;this.pathname=t;this.name=`OpenClawStateDatabaseSchemaMigrationRequiredError`}};function normalizeOpenClawStateSchemaReadError(e,t){if(e instanceof Error&&e.message.startsWith(`malformed database schema (${`idx_skill_workshop_collection_reviews_workspace_time`})`)){const n=new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-workshop-review-index`,t);n.cause=e;return n}return e}function annotateStartupStateInspectionFailure(e,t,n){if(!n?.aborted&&e instanceof Error&&!e.message.includes(t))e.message=`OpenClaw state database ${t} failed startup inspection: ${e.message}`;return e} //!src/state/openclaw-state-lease-error.ts var OpenClawStateLeaseError=class extends Error{constructor(e,t){super(e,{cause:t.cause});this.name=`OpenClawStateLeaseError`;this.code=t.code;this.loss=t.loss}}; //!src/state/session-metadata-unavailable-error.ts var SessionMetadataUnavailableError=class extends Error{constructor(e,t,n=[]){super(`Session metadata unavailable (${[e,...n].join(`: `)}); retry after the agent store is ready.`,t);this.reason=e;this.missingTables=n;this.name=`SessionMetadataUnavailableError`}}; //!src/state/openclaw-state-worker-error-identity.ts const MESSAGE_ONLY_ERRORS={"worktree-source-changed":SessionWorktreeSourceChangedError,"model-account-authority":ModelAccountConnectAuthorityError,"duplicate-agent":DuplicateAgentError,"model-selection-locked":ModelSelectionLockedError,"session-canonical-key-migration":SessionCanonicalKeyMigrationRequiredError,"session-pending-input-custody":SessionPendingInputCustodyError,"session-transcript-read-fence":SessionTranscriptReadFenceError,"skill-upload-request":SkillUploadRequestError,"state-database-access":StateDatabaseAccessError,coordinator:SqliteCoordinatorError,ownership:OpenClawStateOwnershipError,"newer-schema":SqliteSchemaVersionError,"jsonl-read-budget":SqliteJsonlReadBudgetExceededError,"range-error":RangeError,"syntax-error":SyntaxError,"type-error":TypeError};function isMessageOnlyErrorIdentity(e){return typeof e.type===`string`&&Object.hasOwn(MESSAGE_ONLY_ERRORS,e.type)}function identifyError(e){if(e instanceof SandboxStateOwnerRequiredError)return{type:`sandbox-state-owner-required`};if(e instanceof AuthProfileStoreUnreadableError)return{type:`auth-profile-store-unreadable`,databasePath:e.databasePath};if(e instanceof SessionWorktreeLifecycleError&&e.reason===`owner-mismatch`)return{type:`session-worktree-owner-mismatch`};if(e instanceof WorktreeRemovalContentionError)return{type:`worktree-removal-contention`,kind:e.kind,...e.blockedByRun?{blockedByRun:{worktreeId:e.blockedByRun.worktreeId,pid:e.blockedByRun.pid}}:{}};if(e instanceof WorktreeRemovalLockError)return{type:`worktree-removal-lock`,kind:e.kind};if(e instanceof PluginStateStoreError)return{type:`plugin-state`,stateCode:e.code,operation:e.operation,path:e.path,owner:{pid:e.owner.pid,threadId:e.owner.threadId,version:e.owner.version}};if(e instanceof SkillLibraryError)return{type:`skill-library`,libraryCode:e.code,...e.currentRevision===void 0?{}:{currentRevision:e.currentRevision}};if(e instanceof SecretStoreValidationError)return{type:`secret-store-validation`,secretCode:e.code};if(e instanceof WorkerSessionAlreadyAttachedError)return{type:`worker-session-already-attached`,sessionId:e.sessionId,environmentId:e.environmentId};if(e instanceof PluginBlobStoreError)return{type:`plugin-blob`,blobCode:e.code,operation:e.operation,...e.path===void 0?{}:{path:e.path}};if(e instanceof WorkspaceAliasRepointedError)return{type:`workspace-alias-repointed`,aliasPath:e.aliasPath,storedWorkspacePath:e.storedWorkspacePath,currentWorkspacePath:e.currentWorkspacePath};if(e instanceof McpOAuthStoreCorruptionError)return{type:`mcp-oauth-corruption`};if(e instanceof SessionGoalOperationError)return{type:`session-goal-operation`,goalCode:e.code};if(e instanceof SessionEntryLifecycleUpsertConflictError)return{type:`session-lifecycle-upsert-conflict`,sessionKey:e.sessionKey};if(e instanceof SessionTranscriptWriterClaimReboundError){const t=parseTranscriptAppendRefusal(e.cause);return{type:`session-transcript-writer-claim-rebound`,...t?{refusal:t}:{}}}if(e instanceof SqliteSessionMutationConflictError)return{type:`session-mutation-conflict`,operationLabel:e.operationLabel};if(e instanceof SqliteTranscriptMutationConflictError)return{type:`session-transcript-mutation-conflict`,sessionId:e.sessionId};if(e instanceof SessionMetadataUnavailableError)return{type:`session-metadata`,reason:e.reason,missingTables:[...e.missingTables]};if(e instanceof GatewayStateOwnerContentionError)return{type:`state-owner-contention`,databasePath:e.databasePath};if(e instanceof StateDatabaseAdmissionPendingError)return{type:`state-admission-pending`,databasePath:e.databasePath};if(e instanceof StateDatabaseOfflineMaintenanceError)return{type:`state-offline-maintenance`,databasePath:e.databasePath};if(e instanceof StateDatabaseMaintenanceScopeError)return{type:`state-maintenance-scope`};if(e instanceof OpenClawStateLeaseError)return{type:`state-lease`,leaseCode:e.code,leaseLoss:e.loss};if(e instanceof OpenClawStateOwnershipMetadataError)return{type:`ownership-metadata`,databasePath:e.databasePath};if(e instanceof OpenClawStateExternalOwnershipError)return{type:`external-ownership`,databasePath:e.databasePath,managerId:e.managerId};if(e instanceof OpenClawStateDatabaseSchemaMigrationRequiredError)return{type:`state-migration`,kind:e.kind,pathname:e.pathname};if(e instanceof OpenClawAgentDatabaseMediaMigrationRequiredError)return{type:`agent-media-migration`,pathname:e.pathname,schemaVersion:e.schemaVersion};for(const[t,n]of Object.entries(MESSAGE_ONLY_ERRORS))if(e instanceof n)return{type:t};if(e instanceof StartupMaintenanceRequiredError)return{type:`maintenance`,kind:e.kind};return{type:e instanceof AggregateError?`aggregate`:`error`}}function createError(e){if(isMessageOnlyErrorIdentity(e)){const t=MESSAGE_ONLY_ERRORS[e.type];return new t(e.message)}switch(e.type){case`sandbox-state-owner-required`:return new SandboxStateOwnerRequiredError;case`session-worktree-owner-mismatch`:return new SessionWorktreeLifecycleError(e.message,`owner-mismatch`);case`worktree-removal-contention`:return new WorktreeRemovalContentionError(e.kind,e.message,e.blockedByRun);case`worktree-removal-lock`:return new WorktreeRemovalLockError(e.kind,e.message);case`plugin-state`:return new PluginStateStoreError(e.message,{code:e.stateCode,operation:e.operation,path:e.path,owner:e.owner});case`skill-library`:return new SkillLibraryError(e.libraryCode,e.message,e.currentRevision);case`secret-store-validation`:return new SecretStoreValidationError(e.secretCode,e.message);case`worker-session-already-attached`:return new WorkerSessionAlreadyAttachedError(e.sessionId,e.environmentId);case`workspace-alias-repointed`:return new WorkspaceAliasRepointedError(e);case`session-goal-operation`:return new SessionGoalOperationError(e.goalCode,e.message);case`session-lifecycle-upsert-conflict`:return new SessionEntryLifecycleUpsertConflictError(e.sessionKey);case`session-mutation-conflict`:return new SqliteSessionMutationConflictError(e.operationLabel);case`session-transcript-mutation-conflict`:return new SqliteTranscriptMutationConflictError(e.sessionId);case`session-transcript-writer-claim-rebound`:return new SessionTranscriptWriterClaimReboundError(e.refusal);case`session-metadata`:return new SessionMetadataUnavailableError(e.reason,void 0,e.missingTables);case`error`:return new Error(e.message);case`mcp-oauth-corruption`:return new McpOAuthStoreCorruptionError(``,``);case`aggregate`:return new AggregateError([],e.message);case`auth-profile-store-unreadable`:return new AuthProfileStoreUnreadableError(e.databasePath);case`state-owner-contention`:return new GatewayStateOwnerContentionError(e.databasePath);case`state-admission-pending`:return new StateDatabaseAdmissionPendingError(e.databasePath,e.message);case`state-offline-maintenance`:return new StateDatabaseOfflineMaintenanceError(e.databasePath,e.message);case`state-maintenance-scope`:return new StateDatabaseMaintenanceScopeError(``);case`ownership-metadata`:return new OpenClawStateOwnershipMetadataError(e.databasePath,``);case`external-ownership`:return new OpenClawStateExternalOwnershipError(e.databasePath,e.managerId);case`plugin-blob`:return new PluginBlobStoreError(e.message,{code:e.blobCode,operation:e.operation,...e.path===void 0?{}:{path:e.path}});case`state-lease`:return new OpenClawStateLeaseError(e.message,{code:e.leaseCode,loss:e.leaseLoss});case`maintenance`:return new StartupMaintenanceRequiredError(e.kind,e.message);case`state-migration`:return new OpenClawStateDatabaseSchemaMigrationRequiredError(e.kind,e.pathname)}return new OpenClawAgentDatabaseMediaMigrationRequiredError(e.pathname,e.schemaVersion)} //!src/state/openclaw-state-worker-error.ts function isScalar(e){return e===null||typeof e===`string`||typeof e===`boolean`||typeof e===`number`&&Number.isFinite(e)}function isNativeErrorCode(e){return typeof e===`number`&&Number.isInteger(e)&&e>=0&&e<=2147483647}function isWorkerOutcomeCode(e){return e===`outcome-unknown`||e===`unavailable`}function encodeOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return;const n=[];const r=[];const i=/* @__PURE__ */ new Map;let a=false;const encodeValue=e=>{if(!(e instanceof Error))return isScalar(e)?{value:e}:{undefined:true};const t=i.get(e);if(t!==void 0)return{ref:t};const n=r.length;i.set(e,n);r.push(e);return{ref:n}};try{encodeValue(e);for(const e of r){const{name:t,message:r}=e;if(typeof t!==`string`||typeof r!==`string`)return;const i=identifyError(e);if(Object.entries(i).some(([e,t])=>{return(e===`owner`||e===`blockedByRun`||e===`refusal`||e===`leaseLoss`&&t!==void 0?Object.values(t):e===`missingTables`&&Array.isArray(t)?t:[t]).some(e=>e!==void 0&&!isScalar(e))}))return;const o=isSqliteNativeOpenFailure(e);const s=hasSqliteWorkerErrorCode(e,`outcome-unknown`)||hasSqliteWorkerErrorCode(e,`unavailable`);const c=readOpenClawStateDatabaseFailurePath(e);const l=`errcode`in e?e.errcode:void 0;a||=s||c!==void 0||o||isNativeErrorCode(l)||isSqliteLockError(e)||e instanceof OpenClawQuarantineReadCleanupError||i.type!==`error`&&i.type!==`aggregate`;const u=`code`in e?e.code:void 0;const d=`errno`in e?e.errno:void 0;n.push({...i,name:s?`SqliteWorkerError`:t===`SqliteWorkerError`&&isWorkerOutcomeCode(u)?`Error`:t,message:r,...typeof u===`string`||typeof u===`number`&&Number.isFinite(u)?{code:u}:{},...isNativeErrorCode(l)?{errcode:l}:{},...typeof d===`number`&&Number.isInteger(d)?{errno:d}:{},...o?{nativeOpen:true}:{},...c===void 0?{}:{stateDatabasePath:c},...`cause`in e&&!(i.type===`session-transcript-writer-claim-rebound`&&i.refusal)?{cause:encodeValue(e.cause)}:{},...e instanceof AggregateError?{errors:e.errors.map(encodeValue)}:{}})}return a||t.includeOrdinary===true?{version:1,root:0,nodes:n}:void 0}catch{return}}function decodeErrorGraph(e,t){try{if(e.version!==1)return;const n=e.nodes;if(t.includeOrdinary!==true&&!n.some(e=>e.stateDatabasePath!==void 0||e.nativeOpen===true||e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)||isNativeErrorCode(e.errcode)||isSqliteLockError(e)||e.type===`aggregate`&&e.name===`OpenClawQuarantineReadCleanupError`||e.type!==`error`&&e.type!==`aggregate`))return;const r=n.map(e=>{if(e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)){const t=new SqliteWorkerError(e.message,e.code);return e.type===`error`?t:retainSqliteWorkerErrorCode(createError(e),t)}return createError(e)});const decodeValue=e=>`ref`in e?r[e.ref]:`value`in e?e.value:void 0;for(const[e,t]of n.entries()){const n=r[e];n.name=t.name;n.message=t.message;if(t.nativeOpen)markSqliteNativeOpenFailure(n);if(t.stateDatabasePath!==void 0)markOpenClawStateDatabaseFailure(n,t.stateDatabasePath);for(const[e,r]of Object.entries({...t.code!==void 0?{code:t.code}:{},...t.errcode!==void 0?{errcode:t.errcode}:{},...t.errno!==void 0?{errno:t.errno}:{},...t.cause?{cause:decodeValue(t.cause)}:{}}))Object.defineProperty(n,e,{value:r,configurable:true,writable:true});if(n instanceof AggregateError)n.errors=(t.errors??[]).map(decodeValue)}return{errors:r,root:e.root}}catch{return}}const retainedPayloads=resolveGlobalSingleton(Symbol.for(`openclaw.sharedStateWorkerErrorPayloads`),()=>/* @__PURE__ */ new WeakMap);function retainOpenClawStateWorkerErrorPayload(e,t){if(t)retainedPayloads.set(e,t)}function hydrateOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return e;const n=/* @__PURE__ */ new Map;const r=[{error:e,finish:false}];const replace=e=>e instanceof Error?n.get(e)??e:e;while(r.length>0){const e=r.pop();const{error:i}=e;if(!e.finish){if(n.has(i))continue;n.set(i,i);const e=retainedPayloads.get(i);const a=e===void 0?void 0:decodeErrorGraph(e,t);if(a){n.set(i,a.errors[a.root]);continue}r.push({error:i,finish:true});if(i.cause instanceof Error)r.push({error:i.cause,finish:false});if(i instanceof AggregateError){for(const e of i.errors)if(e instanceof Error)r.push({error:e,finish:false})}continue}const a=replace(i.cause);const o=i instanceof AggregateError?i.errors:void 0;const s=o?.map(replace);if(a===i.cause&&(!s||s.every((e,t)=>e===o?.[t])))continue;const c=i instanceof AggregateError?new AggregateError([],i.message):new Error(i.message);Object.setPrototypeOf(c,Object.getPrototypeOf(i));const l=Object.getOwnPropertyDescriptors(i);if(`cause`in i)l.cause={configurable:true,writable:true,...l.cause,value:a};if(s)l.errors={configurable:true,writable:true,...l.errors,value:s};Object.defineProperties(c,l);n.set(i,c)}return n.get(e)} //!src/infra/sqlite-readonly-native-resource.client.ts function createSqliteReadOnlyNativeResourceConnection(e){const{port1:t,port2:n}=new MessageChannel;let r=false;const receive=n=>{let r;try{e.receive(n);r={id:n.id,ok:true}}catch(e){const t=encodeOpenClawStateWorkerError(e,{includeOrdinary:true});if(!t)throw e;r={id:n.id,ok:false,error:t}}t.postMessage(r)};const fail=n=>{e.onFailure(n);t.close()};const onMessage=e=>{try{receive(e)}catch(e){fail(e)}};t.on(`message`,onMessage);t.on(`messageerror`,fail);return{port:n,service(){if(r)return;for(;;){const e=receiveMessageOnPort(t);if(!e)return;try{receive(e.message)}catch(e){fail(e);throw e}}},decodeCloseError(e){const t=/* @__PURE__ */ new Error(`SQLite snapshot staging failed`);retainOpenClawStateWorkerErrorPayload(t,e);const n=hydrateOpenClawStateWorkerError(t,{includeOrdinary:true});return n instanceof AggregateError?n:new SqliteSnapshotCleanupError(n.message,{cause:n})},dispose(){r=true;t.removeAllListeners();t.close();n.close()}}} //!src/infra/sqlite-readonly-native-resource.types.ts const SQLITE_NATIVE_RESOURCE_PORT=`sqliteSnapshotNativeResource`; //!src/infra/sqlite-snapshot-staging-error.ts function decodeSqliteSnapshotStagingError(e){const t=/* @__PURE__ */ new Error(`SQLite snapshot staging failed`);retainOpenClawStateWorkerErrorPayload(t,e);const n=hydrateOpenClawStateWorkerError(t,{includeOrdinary:true});return n.name===`SqliteSnapshotDirectoryBusyError`?new SqliteSnapshotDirectoryBusyError(n.message,{cause:n.cause}):n} //!src/infra/sqlite-snapshot-staging-owner.ts function completed(){const e=createRetainedOperation(()=>{});e.resolve(void 0);return e.operation}function createStagingOwner(e,t){const n=t.captureResource(resolveRuntimeProcessEntrypointUrl(`sqliteReadOnlyNativeResource`),SQLITE_NATIVE_RESOURCE_PORT,void 0,connectNativeResource);const r=createOwnedWorkerTaskPool({workerUrl:e,workerClass:`writer`,idleTimeoutMs:0,maxPendingTasks:128,maxPendingBytes:DEFAULT_WORKER_PENDING_BYTES},{retainedTransport:true,nativeSource:t,nativeResource:n,databaseAccess:`read-only`,decodeResourceError:e=>decodeSqliteSnapshotStagingError(e)});const i=/* @__PURE__ */ new Map;const a=/* @__PURE__ */ new Map;let o=0;const s=/* @__PURE__ */ new Set;let c=false;let l=0;let u=false;let d;let f;function connectNativeResource(){return createSqliteReadOnlyNativeResourceConnection({receive(e){const t=e.directory;if(e.type===`allocated`){const n=a.get(e.preparationId);if(!n)throw new SqliteSnapshotCleanupError(`SQLite snapshot preparation custody is unavailable`);n.directories.add(t);retainDirectory(t,e.preparationId)}else if(e.type===`retire`){if(!i.has(t))throw new SqliteSnapshotCleanupError(`SQLite snapshot native custody is unavailable`);sealRetainedSnapshotTempDirectory(t,{requireRequested:true})}},onFailure(e){f??={error:e}}})}const serviceRequests=()=>{if(c)return;c=true;try{for(const e of s)e.service();for(const e of Array.from(a.values()))e.serviceClose()}finally{c=false}};const closeWhenIdle=()=>{if(d?.read().status===`pending`)return d;if(l>0||i.size>0)return completed();return d=mapRetainedOperation(flatMapRetainedOperation(r.startCloseResources(),()=>l>0||i.size>0?completed():r.startRotate()),()=>{f=void 0})};const retainDirectory=(e,t)=>{const n=i.get(e);if(n)return n;let o;const startRetire=()=>{if(o&&o.read().status!==`rejected`)return o;try{sealRetainedSnapshotTempDirectory(e)}catch(e){const t=createRetainedOperation(()=>{});t.reject(e);return t.operation}return o=flatMapRetainedOperation(r.startCloseResources(e),()=>{i.delete(e);if(t!==void 0){const n=a.get(t);n?.directories.delete(e);n?.releaseIfComplete()}return closeWhenIdle()})};const s={directory:e,startRetire};i.set(e,s);registerRetainedSnapshotTempDirectory(e,startRetire);return s};const start=(e,t)=>{if(u)throw new Error(`SQLite snapshot staging owner is closing`);const n=++o;const i=Buffer.byteLength(JSON.stringify({...e,preparationId:n}));const c=e.type===`prepare`?new MessageChannel:void 0;const abort=()=>{if(c){c.port1.postMessage({type:`abort`});recordWorkerMessage(`resource`,`to_worker`)}};const d=e.type===`prepare`&&c?{...e,preparationId:n,abortPort:c.port2}:{...e,preparationId:n};l++;let p;const m={directories:/* @__PURE__ */ new Set,abort(){if(h.read().status===`pending`)abort()},startClose,serviceClose:()=>p?.service(),releaseIfComplete(){if(v?.read().status!==`pending`&&m.directories.size===0)a.delete(n)}};a.set(n,m);const h=r.startTask(()=>{if(f!==void 0)throw f.error;t?.throwIfAborted();t?.addEventListener(`abort`,abort,{once:true});return d},{inputBytes:i,transferList:()=>c?[c.port2]:[]});let g;const _=mapRetainedOperation(h,e=>{if(e.type===`failed`){const t=decodeSqliteSnapshotStagingError(e.error);throw e.cleanupFailure&&!(t instanceof AggregateError)?new SqliteSnapshotCleanupError(String(t),{cause:t}):t}return e});const v=finallyRetainedOperation(_,()=>g=finallyRetainedOperation(h.release(),()=>{t?.removeEventListener(`abort`,abort);c?.port1.close();c?.port2.close();l--;return closeWhenIdle()}),(e,t)=>createSqliteLifecycleAggregateError([e,t],`SQLite snapshot staging failed`,e));function startClose(){if(p?.read().status===`pending`)return p;let e;let t=false;const n=createRetainedOperation(()=>{if(t||n.operation.read().status!==`pending`)return;t=true;try{serviceRequests();v.service();if(v.read().status===`pending`)return;e??=[...m.directories].map(e=>{const t={};const r=startRemoveTempDirectory(e,e=>{t.cause=e});r.result.then(()=>n.operation.service(),()=>n.operation.service());return[e,r,t]});for(const[t,n,r]of e){n.service();const e=n.read();if(e.status===`pending`)return;if(e.status===`rejected`)throw e.error;if(!e.value)throw new SqliteSnapshotCleanupError(`SQLite staging preparation cleanup failed: ${t}`,r)}const t=g?.read();if(t?.status===`rejected`)throw t.error;m.releaseIfComplete();n.resolve(void 0)}catch(e){n.reject(e)}finally{t=false}});p=n.operation;v.result.then(()=>n.operation.service(),()=>n.operation.service());n.operation.service();return n.operation}const finish=()=>{s.delete(v);m.releaseIfComplete()};v.result.then(finish,finish);if(v.read().status===`pending`)s.add(v);else finish();return{...v,service:serviceRequests,startClose}};const p={start,retainDirectory};t.retain(p,async()=>{u=true;for(const e of a.values())e.abort();await Promise.allSettled([...s].map(e=>e.result));const e=Array.from(a.values()).map(e=>e.startClose());const t=(await Promise.allSettled(e.map(e=>e.result))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length)throw createSqliteLifecycleAggregateError(t,`SQLite snapshot generation cleanup failed`,t[0]);await closeWhenIdle().result;await r.close()});return p}function captureSqliteSnapshotStagingOwner(){const{moduleUrl:e,runtimeGeneration:t}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(`sqliteSnapshotStaging`));const n=captureRetainedNativeWorkerSource({runtimeGeneration:t});const r=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotStagingOwner`),()=>/* @__PURE__ */ new WeakMap);let i=r.get(n);if(!i){i=runInDetachedAsyncContext(()=>createStagingOwner(e,n));r.set(n,i)}return i}export{SqliteJsonlReadBudgetExceededError as _,annotateStartupStateInspectionFailure as a,markOpenClawStateDatabaseFailure as b,createNewerSqliteSchemaVersionError as c,isSqliteSchemaVersionError as d,readSqliteUserVersion as f,VERSION as g,StartupMaintenanceRequiredError as h,OpenClawStateDatabaseSchemaMigrationRequiredError as i,describeRunningOpenClawBuild as l,writeSqliteUserVersion as m,hydrateOpenClawStateWorkerError as n,normalizeOpenClawStateSchemaReadError as o,readSqliteWriterAppVersion as p,retainOpenClawStateWorkerErrorPayload as r,SqliteSchemaVersionError as s,captureSqliteSnapshotStagingOwner as t,isNewerSqliteWriterVersion as u,SessionTranscriptReadFenceError as v,OpenClawQuarantineReadCleanupError as x,findOpenClawStateDatabaseFailure as y};