UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

37 lines • 46.6 kB
import{C as isRecord,i as resolveGlobalSingleton,s as hasErrnoCode}from"./global-singleton-CTnqrmaI.js";import{g as normalizeAgentId}from"./runtime-doctor-migrations-D8alsOFs.js";import{_ as tryProcessCwd,c as resolveStateDir,i as isPathInside$1}from"./account-core-34NfXidI.js";import{U as toErrorObject,W as sliceUtf16Safe,t as createSubsystemLogger}from"./subsystem-ovCC_dQD.js";import{c as resolveTimerTimeoutMs}from"./number-coercion-BhEzZ9ku.js";import{i as racePromiseWithAbortSignal}from"./fs-safe-BnA-Wq_f.js";import{d as expectDefined}from"./types.secrets-CpaxAqFj.js";import"./src-DtNToPzY.js";import{n as runInDetachedAsyncContext}from"./boundary-path-93ijeUSt.js";import"./openclaw-agent-db.paths-D0bfBkSQ.js";import{i as SQLITE_READONLY_CHILD_ARG}from"./runtime-binary-CSMtzJzW.js";import{t as resolveRuntimeWorkerArgv}from"./runtime-worker-url-qeNVkG2b.js";import{t as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-ZdotaiSy.js";import{c as readCustodiedDrainedSqliteSource,i as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-2fT8FMwD.js";import{A as getOrLoadSqliteDatabaseAdmissionForPath,Bn as getSqliteRuntimeCapabilities,In as isPromiseLike,M as getSqliteDatabaseAdmissionIdentityForPath,On as readDatabaseFileIdentity,Vn as withSelectedSqliteLibraryEnv,c as observeChildRuntime,fn as throwSqliteLifecycleErrors,i as resolveRuntimeWorkerGenerationUrl,l as prepareChildRuntimeFailure,o as assertChildRuntimeAvailable,r as captureRuntimeWorkerSource,s as classifyChildRuntimeFailure,sn as SqliteSnapshotCleanupError,t as classifyWorkerRequest,u as getSpawnBroker,un as createSqliteLifecycleAggregateError}from"./sqlite-worker-request-class-GkmU-e0P.js";import{i as createDeferredCore,r as throwSettledAggregate}from"./error-graph-internal-CWqvi3Vy.js";import{I as SqliteSnapshotCapacityError,g as readOnlyWorkerScope,h as createSqliteReadOnlyWorkerScope,k as retainSnapshotWork,m as SqliteReadOnlyWorkerScopeClosedError,p as recordChildProcessSpawn,tt as schemaAdmission,u as resolveOpenClawStateSqlitePath,z as markPrivateDirectoryCreationRefused}from"./openclaw-state-db-async-lifecycle-qylDsiRN.js";import{t as formatErrorMessage}from"./errors-DKa3Vi4q.js";import{a as registerAgentDatabaseReaderCloser,i as matchesAgentDatabaseReadCandidatePath,n as trackWorkerRequest,o as BrokerChild,p as isWorkerIdleForPressure,v as resolveNodeCompileCacheEnv}from"./worker-request-diagnostics-0mUBI4hH.js";import{isPathInside}from"@openclaw/fs-safe/path";import path from"node:path";import fs from"node:fs";import{toUSVString}from"node:util";import{createHash}from"node:crypto";import{tmpdir}from"node:os";import{Socket}from"node:net";import{isMainThread,threadId}from"node:worker_threads";import childProcess from"node:child_process";import{AsyncLocalStorage}from"node:async_hooks";import{deserialize,serialize}from"node:v8";import{channel}from"node:diagnostics_channel"; //!packages/normalization-core/src/stringified-error.ts function toStringifiedError(e){return e instanceof Error?e:new Error(String(e))} //!packages/normalization-core/src/format.ts const BYTE_SIZE_UNITS=[`byte`,`kilo`,`mega`,`giga`,`tera`];const BYTE_SIZE_STYLES={iec:{base:1024,labels:[`B`,`KiB`,`MiB`,`GiB`,`TiB`]},"legacy-binary":{base:1024,labels:[`B`,`KB`,`MB`,`GB`,`TB`]}};function formatByteSize(e,t){const{base:n,labels:r}=BYTE_SIZE_STYLES[t.style];const i=BYTE_SIZE_UNITS.indexOf(t.maxUnit);let a=0;let o=e;while(o>=n&&a<i){o/=n;a+=1}for(;;){const e=expectDefined(BYTE_SIZE_UNITS[a],`byte-size unit`);const s=expectDefined(r[a],`byte-size label`);const c=typeof t.fractionDigits===`function`?t.fractionDigits(o,e):t.fractionDigits;if(c===null)return`${o}${t.separator}${s}`;const l=t.floorUnits?.includes(e)?Math.floor(o*10**c)/10**c:o;if(a<i&&Number(l.toFixed(c))>=n){o/=n;a+=1;continue}return`${l.toFixed(c)}${t.separator}${s}`}} //!src/state/artifact-preserving-state-reads.ts const artifactPreservingReads=resolveGlobalSingleton(Symbol.for(`openclaw.artifactPreservingStateReads`),()=>new AsyncLocalStorage);const liveStateReads=resolveGlobalSingleton(Symbol.for(`openclaw.liveStateReads`),()=>new AsyncLocalStorage);function isLiveStateRead(){return liveStateReads.getStore()!==void 0}function isStartupConfigStateRead(){return liveStateReads.getStore()===`startup-config`}function withArtifactPreservingStateReads(e,t={}){if(isArtifactPreservingStateRead(`agent`))return e();const n={agentDatabases:t.agentDatabases===true,readers:/* @__PURE__ */ new Set,privateRoots:/* @__PURE__ */ new Set,snapshots:/* @__PURE__ */ new Map};const closeReaders=e=>{for(const t of n.readers)try{t()}catch(t){e.push(t)}};const finish=(e,t=[])=>{closeReaders(t);for(const e of n.snapshots.values())try{if(!e.cleanup())throw new SqliteSnapshotCleanupError(`SQLite inspection snapshot cleanup failed.`)}catch(e){t.push(e)}throwSqliteLifecycleErrors(t,`Artifact-preserving inspection and cleanup failed.`);return e};const finishAsync=async(e,t=[])=>{closeReaders(t);for(const e of n.snapshots.values())try{if(!await e.cleanupAsync())throw new SqliteSnapshotCleanupError(`SQLite inspection snapshot cleanup failed.`)}catch(e){t.push(e)}throwSqliteLifecycleErrors(t,`Artifact-preserving inspection and cleanup failed.`);return e};let r;try{r=artifactPreservingReads.run(n,e)}catch(e){return finish(void 0,[e])}return isPromiseLike(r)?Promise.resolve(r).then(finishAsync,e=>finishAsync(void 0,[e])):finish(r)}function isArtifactPreservingStateRead(e=`shared`,t){const n=artifactPreservingReads.getStore();return Boolean(n&&(e===`shared`||n.agentDatabases)&&(!t||![...n.privateRoots].some(e=>isPathInside(e,t))))} //!src/bootstrap/node-compiler-args.ts const COMPILER_FLAGS=/* @__PURE__ */ new Set([`--no-maglev`,`--maglev`,`--no-concurrent-sparkplug`,`--concurrent-sparkplug`]);function resolveForwardedNodeCompilerArgs(){return process.execArgv.filter(e=>COMPILER_FLAGS.has(e.replaceAll(`_`,`-`)))} //!src/state/openclaw-state-worker-memory-pressure.ts const memoryPressure=channel(`openclaw.memory.critical`);function createStateWorkerMemoryPressureSubscription(e,t){let n=false;const onPressure=e=>t(e===true);return()=>{const t=e();if(t===n)return;n=t;if(t)memoryPressure.subscribe(onPressure);else memoryPressure.unsubscribe(onPressure)}} //!src/infra/sqlite-readonly-operation-lifecycle.ts const sqliteReadOnlyOperationProcessLifecycle={"startupMetadata.readCurrent":`retire-after-result`,"startupMetadata.rollbackRecoveryRequired":`retire-after-result`};function sqliteReadOnlyOperationRequiresProcessRetirement(e){return e in sqliteReadOnlyOperationProcessLifecycle} //!src/state/agent-creation-claim.ts const creationClaim=resolveGlobalSingleton(Symbol.for(`openclaw.agentCreationClaim`),()=>new AsyncLocalStorage);const creationResources=resolveGlobalSingleton(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map);function getActiveAgentCreationClaim(e,t){const n=creationClaim.getStore();if(!n||n.kind!==`host`||!n.isActive()||n.agentId!==normalizeAgentId(e)||n.statePath!==path.resolve(t))return;return n}function reserveAgentCreationClaimAdmission(e,t,n){const r=getActiveAgentCreationClaim(t.agentId,resolveOpenClawStateSqlitePath(t.env??process.env));if(!r)return;creationResources.set(e,r);r.registerClose(async()=>{if(creationResources.get(e)!==r)return;await n();creationResources.delete(e)});return()=>{creationResources.delete(e)}}function releaseAgentCreationClaimHandle(e){creationResources.delete(e)} //!src/state/agent-database-admission-error.ts const AgentDatabaseExecutionAdmissionClosedError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class AdmissionClosedError extends Error{});const AgentDatabaseSchemaAdmissionChangedError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class SchemaAdmissionChangedError extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}});const AgentDatabaseSchemaAdmissionInvalidError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class SchemaAdmissionInvalidError extends Error{constructor(){super(`Invalid agent schema admission receipt`)}});const AgentDatabaseStartupPublicationError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class StartupPublicationError extends Error{constructor(e){super(formatErrorMessage(e),{cause:e})}}); //!src/state/agent-deletion-cleanup.ts const databaseCleanup=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new AsyncLocalStorage);const cleanupHandles=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map);const cleanupExecutions=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map);function captureAgentDeletionResourceOwner(e){const t=databaseCleanup.getStore();if(!t?.ownsDatabase||!e(t)&&(!t.canonicalPath||!e({agentId:t.agentId,path:t.canonicalPath})))return;t.assertCurrentHost();return t}function releaseAgentDeletionDatabaseCleanup(e){cleanupHandles.delete(e)} //!src/state/openclaw-agent-db-resources.ts const resources=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map}));function hasOpenClawAgentDatabaseAsyncResources(e){return e?[...resources.active,...resources.closing.keys()].some(t=>matchesAgentDatabaseClose(e,t)):resources.active.size>0||resources.closing.size>0}function registerAgentDatabaseResourceReleaseHandler(e){resources.onRelease=e}registerAgentDatabaseReaderCloser(async(e,t)=>{const n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...resources.active,...resources.closing.keys()])].filter(n=>!t?.has(path.resolve(n.path))&&e.some(e=>matchesAgentDatabaseReadCandidatePath(e,n.path))).map(e=>closeAgentDatabaseResource(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw new AggregateError(n,`Agent database resource cleanup failed`)});function matchesAgentDatabaseClose(e,t){return(e.path===void 0||e.path===t.path||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.path))&&(e.rootPath===void 0||isPathInside$1(e.rootPath,t.path)||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.rootPath))&&(e.agentId===void 0||t.ownership===`unresolved`||e.agentId===t.agentId)}function registerOpenClawAgentDatabaseAsyncResource(e,t){return registerAgentDatabaseResource({...e,ownership:`known`,agentId:normalizeAgentId(e.agentId)},t)}function registerOpenClawAgentDatabaseReadCandidateResource(e){return registerAgentDatabaseResource({...e,ownership:`unresolved`})}function registerAgentDatabaseResource(e,t){const n={...e,path:path.resolve(e.path)};n.cleanupOwner=captureAgentDeletionResourceOwner(e=>matchesAgentDatabaseClose(e,n));assertAgentDatabaseResourceAdmission(n);const r=t&&n.ownership===`known`?reserveAgentCreationClaimAdmission(n,t,()=>closeAgentDatabaseResource(n)):void 0;const unregister=()=>{resources.active.delete(n);r?.();resources.onRelease?.(n)};getOpenClawDatabaseMaintenanceScope()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n));resources.active.add(n);return unregister}function assertAgentDatabaseResourceAdmission(e){if([...resources.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...resources.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.path)||e.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new AgentDatabaseExecutionAdmissionClosedError(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,t){if(e.ownership===`known`&&e.closeSync){resources.closing.set(e,void 0);try{e.revoke();e.closeSync();resources.active.delete(e);resources.closing.delete(e);resources.onRelease?.(e);return Promise.resolve()}catch(n){if(t)t(e.path,n);const r=Promise.reject(toErrorObject(n,`Agent database cleanup failed`));r.catch(()=>{});return r}}let n=resources.closing.get(e);if(!n){n=Promise.resolve().then(()=>e.close());resources.closing.set(e,n);n.then(()=>{resources.active.delete(e);resources.closing.delete(e);resources.onRelease?.(e)},()=>{resources.closing.set(e,void 0)}).catch(()=>{})}if(t)n.catch(n=>t(e.path,n)).catch(()=>{});e.revoke();return n}function revokeAgentDatabaseResources(e,t){const n=/* @__PURE__ */ new Set([...resources.active,...resources.closing.keys()]);const r=[];for(const i of n){if(!matchesAgentDatabaseClose(e,i))continue;r.push(closeAgentDatabaseResource(i,t))}return r} //!src/infra/sqlite-readonly-auth-schema.ts function captureSqliteAuthSchema(e,t){if(getSqliteDatabaseAdmissionIdentityForPath(e)?.key!==t)return;const n=getOrLoadSqliteDatabaseAdmissionForPath(e,schemaAdmission,()=>void 0);if(!n)return;const kind=e=>n.tables.has(e)?`table`:n.views.has(e)||n.indexes.has(e)||n.triggers.has(e)?`other`:`missing`;return{userVersion:n.userVersion,store:kind(`auth_profile_store`),state:kind(`auth_profile_state`)}} //!src/infra/json-field-transfer.ts const JSON_FIELD_TRANSFER_BYTES=65536;function isJsonTransferField(e){if(!isRecord(e))return false;if(e.kind===`object`||e.kind===`array`||e.kind===`end`)return true;return(e.kind===`key`||e.kind===`value`)&&(e.append===void 0||e.append===true&&typeof e.value===`string`)&&(typeof e.value===`string`||e.kind===`value`&&(e.value===null||typeof e.value===`boolean`||typeof e.value===`number`))}function createJsonFieldReceiver(){let e;let t=false;const n=[];let r;const write=r=>{const i=n.at(-1);if(i){if(i.key===void 0)throw new Error(`JSON field has no property key`);Object.defineProperty(i.container,i.key,{value:r,writable:true,enumerable:true,configurable:true});i.key=void 0}else{if(t)throw new Error(`JSON transfer has more than one root`);e=r;t=true}};const flush=()=>{if(!r)return;const e=r.chunks.join(``);if(r.kind===`key`){const t=n.at(-1);if(!t||t.key!==void 0)throw new Error(`JSON property key has no value or container`);t.key=e}else write(e);r=void 0};return{accept(e){if(!isJsonTransferField(e))throw new Error(`Invalid JSON transfer field`);if(e.kind===`key`||e.kind===`value`){if(e.append){if(!r||r.kind!==e.kind||typeof e.value!==`string`)throw new Error(`Invalid JSON string continuation`);r.chunks.push(e.value);return}flush();if(typeof e.value===`string`)r={kind:e.kind,chunks:[e.value]};else write(e.value)}else{flush();if(e.kind===`end`){const e=n.pop();if(!e||e.key!==void 0)throw new Error(`JSON container ended with an incomplete field`)}else{const t=e.kind===`array`?[]:{};write(t);n.push({container:t})}}},finish(){flush();if(n.length)throw new Error(`JSON transfer ended with an incomplete container`);return e}}} //!src/infra/sqlite-worker-transfer.ts const SQLITE_WORKER_TRANSFER_FRAME_BYTES=8388608;function createSqliteWorkerTransferOwner(){let e=0;let t;const cleanup=e=>{const t=[];for(const[n,r]of[[`iteratorClosed`,()=>e.iterator.return?.()],[`cleaned`,()=>e.cleanup?.()]])if(!e[n])try{r();e[n]=true}catch(e){t.push(e)}throwSqliteLifecycleErrors(t,`SQLite read transfer cleanup failed`)};const cancel=()=>{if(t){cleanup(t);t=void 0}};const requireTransfer=e=>{if(!t||t.id!==e)throw new Error(`SQLite read transfer is no longer active`);return t};return{start(n,r){if(t)throw new Error(`The preceding SQLite read transfer was not released`);t={id:++e,iterator:n,cleanup:r.cleanup,iteratorClosed:false,cleaned:false,counts:new Map(r.kinds.map(e=>[e,0])),sequence:0,finished:false};return{id:t.id,kinds:[...t.counts.keys()]}},next(e){const t=requireTransfer(e);if(t.finished)throw new Error(`SQLite read transfer has already reached its end`);if(t.record&&t.record.offset===t.record.bytes.byteLength)t.record=void 0;if(!t.record){const n=t.iterator.next();if(n.done){cleanup(t);t.finished=true;return{id:e,sequence:t.sequence++,done:true,counts:[...t.counts]}}const{kind:r}=n.value;const i=t.counts.get(r);if(i===void 0)throw new Error(`SQLite read transfer returned an unexpected record kind`);t.record={kind:r,bytes:`serialized`in n.value?n.value.serialized:serialize(n.value.value),offset:0};t.counts.set(r,i+1)}const n=t.record;const r=n.offset;const i=Math.min(n.bytes.byteLength,r+SQLITE_WORKER_TRANSFER_FRAME_BYTES);n.offset=i;return{id:e,sequence:t.sequence++,done:false,kind:n.kind,recordBytes:n.bytes.byteLength,offset:r,recordDone:i===n.bytes.byteLength,bytes:new Uint8Array(n.bytes.subarray(r,i))}},end(e){if(!requireTransfer(e).finished)throw new Error(`SQLite read transfer ended before its complete result`);cancel()},cancel,close:cancel}}function createSqliteWorkerTransferReceiver(e,t){const n=new Map(e.kinds.map(e=>[e,0]));let r=0;let i=false;let a;return{accept(o){try{if(i||o.id!==e.id||o.sequence!==r++)throw new Error(`SQLite read transfer frame is out of order`);if(o.done){if(a||o.counts.length!==n.size||o.counts.some(([e,t])=>n.get(e)!==t)||new Set(o.counts.map(([e])=>e)).size!==n.size)throw new Error(`SQLite read transfer ended with an incomplete result`);i=true;return o.counts}const s=n.get(o.kind);if(s===void 0||!Number.isSafeInteger(o.recordBytes)||o.recordBytes<1||!Number.isSafeInteger(o.offset)||o.offset<0||o.bytes.byteLength<1||o.bytes.byteLength>8388608)throw new Error(`SQLite read transfer returned an invalid frame`);if(!a){if(o.offset!==0)throw new Error(`SQLite read transfer omitted the start of a record`);a={kind:o.kind,bytes:o.recordDone?o.bytes:new Uint8Array(o.recordBytes),offset:0}}const c=o.offset+o.bytes.byteLength;if(a.kind!==o.kind||a.bytes.byteLength!==o.recordBytes||a.offset!==o.offset||c>o.recordBytes||o.recordDone!==(c===o.recordBytes))throw new Error(`SQLite read transfer returned a discontinuous record`);if(a.bytes!==o.bytes)a.bytes.set(o.bytes,o.offset);a.offset=c;if(o.recordDone){const e=deserialize(a.bytes);const r=a.kind;a=void 0;t({kind:r,value:e});n.set(r,s+1)}return}catch(e){a=void 0;i=true;throw e}}}} //!src/infra/sqlite-readonly-auth-transfer.ts function decodeFrame(e,t){if(e.done)return e;if(e.bytes.length>4*Math.ceil(8388608/3))throw new Error(`Invalid ${t} transfer bytes`);const n=Buffer.from(e.bytes,`base64`);if(n.toString(`base64`)!==e.bytes)throw new Error(`Invalid ${t} transfer encoding`);return{...e,bytes:n}}function createSqliteReadOnlyTransferReceiver(e){let t;let n;let r=false;let i=false;return{accept(a){if(i)throw new Error(`Invalid ${e.label} transfer response`);if(a.type===`start`&&!t){const r=a.handle;if(!Number.isSafeInteger(r.id)||r.id<1||r.kinds.length!==e.kinds.length||r.kinds.some((t,n)=>t!==e.kinds[n]))throw new Error(`Invalid ${e.label} transfer handle`);n=r.id;t=createSqliteWorkerTransferReceiver({id:n,kinds:e.kinds},({kind:t,value:n})=>e.acceptRecord(t,n));return{request:{type:`next`,transferId:n}}}if(!t||n===void 0)throw new Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer has not started`);if(a.type===`frame`&&!r){const i=decodeFrame(a.frame,e.label);if(!i.done&&e.maxRecordBytes&&i.recordBytes>e.maxRecordBytes)throw new Error(`${e.label} transfer record exceeds its bound`);const o=t.accept(i);if(o){if(o.length!==e.kinds.length||o.some(([,e])=>e<1))throw new Error(`Incomplete ${e.label} transfer result`);r=true}return{request:{type:r?`end`:`next`,transferId:n}}}if(a.type===`complete`&&r){i=true;return{value:e.readResult()}}throw new Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer response is out of order`)}}}function createSqliteAuthTransferReceiver(){const e=createJsonFieldReceiver();return createSqliteReadOnlyTransferReceiver({kinds:[`fields`],label:`auth profile`,maxRecordBytes:JSON_FIELD_TRANSFER_BYTES,acceptRecord(t,n){if(!Array.isArray(n))throw new Error(`Invalid auth profile field batch`);for(const t of n)e.accept(t)},readResult(){const t=e.finish();if(!isRecord(t)||!(`store`in t)||!(`state`in t)||typeof t.cacheable!==`boolean`)throw new Error(`Invalid auth profile transfer rows`);return{store:t.store,state:t.state,cacheable:t.cacheable}}})}function createSqliteOperationTransferReceiver(e){let t;return createSqliteReadOnlyTransferReceiver({kinds:[`result`],label:`SQLite operation`,acceptRecord(n,r){if(t||!isRecord(r)||r.operation!==e||!(`value`in r))throw new Error(`SQLite read-only worker returned a different or duplicate operation`);t={operation:e,value:r.value}},readResult(){if(!t)throw new Error(`SQLite read-only worker returned no operation`);return t}})} //!src/infra/sqlite-readonly-worker-protocol.ts const SQLITE_READONLY_WORKER_MAX_BUFFER=1048576;function isSqliteSnapshotStagingMode(e){return e===`staging-create`||e===`staging-create-legacy`||e===`staging-reconcile`||e===`staging-retire`}var SqliteReadOnlyInspectionContentionError=class extends Error{};const SQLITE_INSPECTION_CONTENTION_PREFIX=`Retryable SQLite inspection contention: `;const SQLITE_SNAPSHOT_ALLOCATION_REFUSED_PREFIX=`SQLite snapshot directory creation refused: `;const SQLITE_SNAPSHOT_CAPACITY_PREFIX=`SQLite snapshot capacity unavailable: `;function sqliteReadOnlyWorkerRequestArgs(e,t){const n=[t.mode,path.resolve(e)];if(t.mode===`task-delivery-recovery`)return[...n,path.resolve(t.recoveryDirectory),path.resolve(t.sourcePath)];const r=t.stagingRoot&&path.resolve(t.stagingRoot);if(t.mode===`private-fork`)return[...n,r??``,JSON.stringify(t.family)];const i=t.mode===`auth-profile-rows`||t.mode===`operation`?void 0:t.expectedSourceIdentity;if(i!==void 0){if(t.mode!==`sync`&&t.mode!==`staged-sync`&&t.mode!==`metadata`)throw new Error(`SQLite source identity is supported only for sync or metadata snapshots`);n.push(r??``,JSON.stringify(readDatabaseFileIdentity(i)))}else if(r)n.push(r);return n}const SQLITE_READONLY_STDERR_TAIL_CHARS=4e3;function isSqliteReadOnlyWorkerResult(e){if(!e||typeof e!==`object`||Array.isArray(e))return false;if(`ok`in e&&e.ok===false&&`message`in e&&typeof e.message===`string`)return Object.keys(e).length===2||Object.keys(e).length===3&&`errcode`in e&&typeof e.errcode===`number`&&Number.isInteger(e.errcode)&&e.errcode>=0&&e.errcode<=2147483647;if(Object.keys(e).length!==2||!(`ok`in e))return false;return e.ok===true&&`engine`in e&&isRecord(e.engine)&&(e.engine.engine===`sqlite`||e.engine.engine===`postgres`&&typeof e.engine.storeId===`string`&&typeof e.engine.namespace===`string`)||e.ok===true&&`reclamation`in e&&isRecord(e.reclamation)&&[e.reclamation.removed,e.reclamation.bytes,e.reclamation.skipped].every(e=>typeof e===`number`&&Number.isFinite(e)&&e>=0)||e.ok===true&&`hasExistingData`in e&&typeof e.hasExistingData===`boolean`||e.ok===true&&`location`in e&&typeof e.location===`string`||e.ok===true&&`contentVersion`in e&&typeof e.contentVersion===`string`&&/^(?:[a-f0-9]{64})?$/.test(e.contentVersion)||e.ok===true&&`generation`in e&&typeof e.generation===`string`||e.ok===true&&`taskDeliveryRecovery`in e&&isRecord(e.taskDeliveryRecovery)&&Object.keys(e.taskDeliveryRecovery).length===2&&typeof e.taskDeliveryRecovery.count===`number`&&Number.isSafeInteger(e.taskDeliveryRecovery.count)&&e.taskDeliveryRecovery.count>0&&typeof e.taskDeliveryRecovery.payloadSha256===`string`&&/^[a-f0-9]{64}$/u.test(e.taskDeliveryRecovery.payloadSha256)}function createSqliteReadOnlyWorkerError(e,t,n){const r=toUSVString(sliceUtf16Safe(t.trim(),-4e3));return new Error(`SQLite read-only worker ${e}${r?`\nstderr (tail): ${r}`:``}`,n)}function parseSqliteReadOnlyWorkerResult(e,t){if(!e.trim())throw createSqliteReadOnlyWorkerError(`returned no JSON result`,t);let n;try{n=JSON.parse(e)}catch{throw createSqliteReadOnlyWorkerError(`returned invalid JSON`,t)}if(!isSqliteReadOnlyWorkerResult(n))throw createSqliteReadOnlyWorkerError(`returned an invalid result`,t);return n}function readSqliteReadOnlyWorkerValue(e,t){if(e.kind===`launch-failed`)throw e.error;let n;try{n=parseSqliteReadOnlyWorkerResult(e.stdout,e.stderr)}catch(t){if(e.failure)throw createSqliteReadOnlyWorkerError(e.failure,e.stderr,{cause:e.cause});throw t}if(e.status!==0||e.failure||!n.ok){const r=!n.ok&&(e.status===0||e.status===1)&&n.message.startsWith(`SQLite snapshot capacity unavailable: `);const i=!n.ok?r?n.message.slice(38):n.message:e.failure??`exited with code ${e.status}`;const a=!n.ok&&i.startsWith(`Retryable SQLite inspection contention: `);const o=a?i.slice(40):i;const s=e.failure===void 0&&!n.ok&&(t===`staging-create`||t===`staging-create-legacy`)&&o.startsWith(`SQLite snapshot directory creation refused: `);const c=createSqliteReadOnlyWorkerError(s?o.slice(44):o,e.stderr,{cause:e.cause});if(!n.ok&&n.errcode!==void 0&&(t===`backup-engine`||t===`backup-engine-preserving`||t===`state-sqlite-populated`)&&(e.status===0||e.status===1))Object.assign(c,{errcode:n.errcode});if(r)throw new SqliteSnapshotCapacityError(c.message,{cause:e.cause});if(a){const e=new SqliteReadOnlyInspectionContentionError(c.message);throw s?markPrivateDirectoryCreationRefused(e):e}throw c}if((t===`sync`||t===`private-fork`||t===`async`||t===`staged-sync`||t===`staged-async`||t===`metadata`||t===`consolidated`||isSqliteSnapshotStagingMode(t))&&`location`in n)return n.location;if(t===`staging-sweep`&&`reclamation`in n)return n.reclamation;if((t===`backup-engine`||t===`backup-engine-preserving`)&&`engine`in n)return n.engine;if(t===`state-sqlite-populated`&&`hasExistingData`in n)return n.hasExistingData;if(t===`content-version`&&`contentVersion`in n)return n.contentVersion;if((t===`file-generation`||t===`update-generation`)&&`generation`in n)return n.generation;if(t===`task-delivery-recovery`&&`taskDeliveryRecovery`in n)return n.taskDeliveryRecovery;throw createSqliteReadOnlyWorkerError(`returned a result for a different operation`,e.stderr)} //!src/infra/sqlite-readonly-worker-session.ts function isSameSqliteReadOnlyWorkerLaunch(e,t){const n=Object.keys(t.env);return e.runtimeGeneration===t.runtimeGeneration&&e.transport.kind===t.transport.kind&&(e.transport.kind===`native`||t.transport.kind===`broker`&&e.transport.owner===t.transport.owner)&&t.cwd===e.cwd&&n.length===Object.keys(e.env).length&&n.every(n=>t.env[n]===e.env[n])}function createSqliteReadOnlyWorkerSession(e){assertChildRuntimeAvailable();const t={...e.env};const n=e.cwd;const r=process.execPath;const i=e.transport.kind===`broker`?{kind:`broker`,owner:e.transport.owner}:{kind:`native`};const a={env:t,cwd:n,transport:i,runtimeGeneration:e.runtimeGeneration};const o=[...e.argv];const s={env:t,...i.kind===`native`&&n===tryProcessCwd()?{}:{cwd:n},stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:true};const c=i.kind===`broker`?i.owner.spawn(r,o,s):childProcess.spawn(r,o,s);recordChildProcessSpawn(r,c,e.pooledRead?`sqlite.scoped-read.${i.kind}`:`sqlite.session.${i.kind}`);const setIdle=e=>{if(i.kind!==`native`)return;const t=e?`unref`:`ref`;c[t]();c.channel?.[t]?.();for(const e of[c.stdout,c.stderr])if(e instanceof Socket)e[t]()};let l=false;let u=0;let d;let f=``;let p=0;let m;const{promise:h,resolve:g}=createDeferredCore();const _=/* @__PURE__ */ new Map;const v=h.then(async()=>{if(i.kind===`broker`&&c instanceof BrokerChild&&!c.notStarted&&c.exitCode===null&&c.signalCode===null)await i.owner.waitForCleanup();for(const e of _.values())e();_.clear()});const retire=e=>{setIdle(false);l=true;if(m&&e!==void 0)m.failure??=e;c.kill(`SIGKILL`)};const sendMessage=e=>c.send(e,e=>{if(e)retire(e)});const releasePending=t=>{m=void 0;d=void 0;t.cleanup();if(e.pooledRead){for(const e of _.values())e();_.clear()}return t};if(e.retainLifetime!==false)retainSnapshotWork(v,()=>retire(/* @__PURE__ */ new Error(`SQLite snapshot owner stopped`)));let y=false;let b=false;let x=false;c.once(`spawn`,()=>{b=true});c.on(`error`,e=>retire(b?e:Object.assign(new Error([[`EACCES`,`ENOENT`,`EPERM`].includes(e.code??``)?`SQLite read-only worker runtime binary not executable: ${r} (${e.code}, cwd ${n}). Check runtime execute permissions and access to the working directory`:`SQLite read-only worker failed to start (executable ${r}, cwd ${n})`,e.message].join(`: `),{cause:e}),{code:e.code,path:e.path})));const finishClose=async(e,t)=>{x=true;l=true;const n=m?.failure??createSqliteReadOnlyWorkerError(`exited with ${t?`signal ${t}`:`code ${e}`}`,f);const i=await prepareChildRuntimeFailure({execPath:r,error:n,stderr:f,signal:t,started:y}).catch(toStringifiedError);if(m){const e=releasePending(m);e.reject(i??e.failure??n)}g()};c.once(`close`,(e,t)=>{finishClose(e,t)});const captureOutput=(e,t)=>{p+=e.length;if(t)f=sliceUtf16Safe(f+e.toString(`utf8`),-SQLITE_READONLY_STDERR_TAIL_CHARS);if(p>1048576)retire(createSqliteReadOnlyWorkerError(`exceeded its output buffer`,f))};const attachOutput=()=>{c.stdout?.on(`data`,e=>captureOutput(e,false));c.stderr?.on(`data`,e=>captureOutput(e,true))};const S=c instanceof BrokerChild?c.ready().then(attachOutput).catch(retire):void 0;if(!S)attachOutput();c.on(`message`,t=>{y=true;if(l)return;if(!m||!t||typeof t!==`object`||Object.keys(t).length!==2||!(`id`in t)||t.id!==m.id||!(`result`in t)){retire(createSqliteReadOnlyWorkerError(`returned an unexpected response`,f));return}try{let e;if(m.transfer&&`type`in t.result){const n=m.transfer.accept(t.result);if(`request`in n){sendMessage({id:m.id,transfer:n.request});return}e=n.value}else e=readSqliteReadOnlyWorkerValue({kind:`launched`,stdout:JSON.stringify(t.result),stderr:f,status:0},m.mode);releasePending(m).resolve(e)}catch(n){if(m&&e.retainOnOperationError&&isSqliteSnapshotStagingMode(m.mode)&&isSqliteReadOnlyWorkerResult(t.result)&&!t.result.ok){releasePending(m).reject(n);return}retire(n)}});const C={closed:v,isRetired(){return l},get notStarted(){return c instanceof BrokerChild?c.notStarted:x&&!b},createNativeReplacement(){return runInDetachedAsyncContext(()=>createSqliteReadOnlyWorkerSession({...e,env:t,cwd:n,argv:o,transport:{kind:`native`}}))},compatible(e){return!l&&isSameSqliteReadOnlyWorkerLaunch(a,e)},run(t,n){if(l)return Promise.reject(/* @__PURE__ */ new Error(`SQLite read-only worker is closed`));if(n.mode===`auth-profile-rows`&&n.source===`canonical`&&!n.artifactPreserving){const e=path.resolve(t);if(!_.has(e))_.set(e,registerOpenClawAgentDatabaseReadCandidateResource({path:e,revoke:()=>retire(/* @__PURE__ */ new Error(`Auth profile reader owner was revoked`)),close:()=>C.close()}))}return d=new Promise((r,i)=>{f=``;p=0;const abort=()=>retire(n.signal?.reason);let a;const o=++u;m={id:o,mode:n.mode,...n.mode===`auth-profile-rows`?{transfer:createSqliteAuthTransferReceiver()}:n.mode===`operation`?{transfer:createSqliteOperationTransferReceiver(n.command.type)}:{},resolve:r,reject:i,cleanup:()=>{clearTimeout(a);n.signal?.removeEventListener(`abort`,abort)}};n.signal?.addEventListener(`abort`,abort,{once:true});if(n.signal?.aborted){abort();return}const send=async()=>{try{if(!e.deadlineOwnedByCaller()){const{timeoutMs:n,size:r}=await e.readBudget(t);if(l)return;a=setTimeout(()=>retire(e.timeoutError(t,n,r)),n)}if(S){await S;if(l)return}const r={id:o,args:e.requestArgs(t,n),...n.mode===`auth-profile-rows`||n.mode===`operation`?{[n.mode===`operation`?`operation`:`auth`]:{expectedIdentity:n.expectedIdentity,expectedBirthtime:n.expectedBirthtime,artifactPreserving:n.artifactPreserving,...n.mode===`operation`?{command:serialize(n.command).toString(`base64`)}:{immutable:n.immutable,retainReader:!e.pooledRead&&n.source===`canonical`&&!n.artifactPreserving,schema:n.source===`canonical`&&!n.artifactPreserving?captureSqliteAuthSchema(t,n.expectedIdentity):void 0}}}:{}};if(n.mode===`operation`&&Buffer.byteLength(JSON.stringify(r))>1048576)throw new Error(`SQLite read-only operation exceeded its request buffer`);sendMessage(r)}catch(e){retire(e)}};send()})},setIdle,async close(){C.setIdle(false);if(l){await v;return}l=true;const t=setTimeout(()=>retire(),e.closeTimeoutMs);try{sendMessage(`close`)}catch(e){retire(e)}try{await v}finally{clearTimeout(t)}}};e.runtimeGeneration?.retain(C,async()=>{await d?.catch(()=>void 0);return()=>C.close()});return C} //!src/infra/sqlite-readonly-worker-pool.ts const log$1=createSubsystemLogger(`state/sqlite`);function trackSqliteRead(e){return trackWorkerRequest(`sqlite_read`,classifyWorkerRequest(e.mode===`operation`?e.command.type:e.mode),e.signal)}function createSqliteReadOnlyWorkerPool(e){const t=[];const n=4;const r=6e4;const i=/* @__PURE__ */ new WeakMap;const a=/* @__PURE__ */ new Set;const o=/* @__PURE__ */ new WeakSet;const s=createStateWorkerMemoryPressureSubscription(()=>t.some(e=>e.idleSince!==void 0&&!e.session?.isRetired()),e=>{for(const n of t)if(n.session&&!n.leased&&!n.quarantined&&n.queued===0&&isWorkerIdleForPressure(n.idleSince,e))retireIdleSlot(n)});const assertBrokerOpen=e=>{if(e.transport.kind===`broker`&&o.has(e.transport.owner))throw new Error(`SQLite read-only worker broker is closing`)};async function closeSlot(e){const t=e.session;try{await t?.close();e.session=void 0}catch(t){e.quarantined={error:t};for(const e of a)e();throw t}}async function selectScopedReadWorker(e,r){assertBrokerOpen(r);const o=e.mode===`operation`&&(e.command.type===`pageCache.begin`||e.command.type===`pageCache.step`);const s=readOnlyWorkerScope.getStore();if(o){if(!s?.active)throw new Error(`Database page-cache warm requires an active read-only worker scope`);const t=i.get(s);if(t){if(!isSameSqliteReadOnlyWorkerLaunch(t.launch,r))throw new Error(`Database page-cache warm worker launch changed during its scope`);return t}if(e.command.type===`pageCache.step`)throw new Error(`Database page-cache warm is no longer active`)}for(;;){assertBrokerOpen(r);e.signal?.throwIfAborted();const c=t.filter(e=>!e.leased&&!e.quarantined);let l=c.find(e=>isSameSqliteReadOnlyWorkerLaunch(e.launch,r));if(!l&&t.length<n){l={launch:r,tail:Promise.resolve(),queued:0};t.push(l)}l??=c.find(e=>e.queued===0&&!e.session);l??=c.reduce((e,t)=>!e||t.queued<e.queued?t:e,void 0);if(l){if(o&&s){const e=l;const t={started:false};e.leased=t;i.set(s,e);s.releaseReadWorker=async()=>{try{if(t.started){await e.tail;await closeSlot(e)}}finally{e.leased=void 0;i.delete(s);s.releaseReadWorker=void 0;if(!e.quarantined&&e.queued===0&&e.session&&!e.session.isRetired()){e.session.setIdle(true);armScopedReadWorkerIdle(e)}for(const e of a)e()}}}return l}if(t.every(e=>e.quarantined))throw new AggregateError(t.map(e=>e.quarantined?.error),`SQLite read-only worker capacity is held by unconfirmed cleanup`);let u;const d=runInDetachedAsyncContext(()=>new Promise(e=>{u=e}));a.add(u);try{await racePromiseWithAbortSignal(d,e.signal,e=>e.reason)}finally{a.delete(u)}}}function retireIdleSlot(e){clearTimeout(e.idle);e.idleSince=void 0;s();const t=runInDetachedAsyncContext(()=>closeSlot(e));e.tail=t.catch(()=>{log$1.warn(`Idle SQLite read-only worker cleanup failed`)});return t}function armScopedReadWorkerIdle(e){if(e.launch.transport.kind===`broker`&&o.has(e.launch.transport.owner)){retireIdleSlot(e);return}e.idleSince=performance.now();s();e.idle=runInDetachedAsyncContext(()=>setTimeout(()=>{retireIdleSlot(e)},r));e.idle.unref()}return{run:async function runSqliteScopedReadWorker(t,n,r,i=trackSqliteRead(n)){const a=n.mode===`operation`&&(n.command.type===`pageCache.begin`||n.command.type===`pageCache.step`);let o;try{o=await selectScopedReadWorker(n,r);assertBrokerOpen(r)}catch(e){i.completed();throw e}clearTimeout(o.idle);o.idleSince=void 0;s();o.queued++;const c=o.tail;const l=runInDetachedAsyncContext(()=>racePromiseWithAbortSignal(c,n.signal,e=>e.reason)).then(async()=>{n.signal?.throwIfAborted();if(o.quarantined)throw o.quarantined.error;i.started();if(o.leased&&n.mode===`operation`&&n.command.type===`pageCache.begin`)o.leased.started=true;if(!isSameSqliteReadOnlyWorkerLaunch(o.launch,r)||o.session?.isRetired())await closeSlot(o);n.signal?.throwIfAborted();o.launch=r;if(!o.session){o.session=e({...r,pooledRead:true});const{closed:t}=o.session;runInDetachedAsyncContext(()=>t.then(s,s))}const c=o.session;c.setIdle(false);try{const e=await c.run(t,n);n.signal?.throwIfAborted();if(!a&&(n.mode===`operation`&&sqliteReadOnlyOperationRequiresProcessRetirement(n.command.type)||!getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources))await closeSlot(o);return e}catch(e){try{await closeSlot(o)}catch(t){throw createSqliteLifecycleAggregateError([e,t],`SQLite read and child cleanup failed`,e)}throw e}}).finally(()=>{i.completed();o.queued--;if(!o.leased&&!o.quarantined&&o.queued===0&&o.session&&!o.session.isRetired()){o.session?.setIdle(true);armScopedReadWorkerIdle(o)}});o.tail=runInDetachedAsyncContext(()=>Promise.allSettled([c,l]).then(()=>{}));return l},async closeBroker(e){o.add(e);const n=await Promise.allSettled(t.filter(t=>t.launch.transport.kind===`broker`&&t.launch.transport.owner===e&&t.session&&t.queued===0&&!t.leased&&!t.quarantined).map(retireIdleSlot));throwSettledAggregate(n,`SQLite read-only broker worker cleanup failed`)}}} //!src/infra/sqlite-readonly-worker.ts const SQLITE_INSPECTION_TIMEOUT_MS=3e5;const SQLITE_INSPECTION_BYTES_PER_SECOND=33554432;const log=createSubsystemLogger(`state/sqlite`);function resolveSqliteInspectionBudget(e,t,n){const r=resolveTimerTimeoutMs(SQLITE_INSPECTION_TIMEOUT_MS+Math.ceil(40*Number(n??0)/SQLITE_INSPECTION_BYTES_PER_SECOND)*1e3,SQLITE_INSPECTION_TIMEOUT_MS);const i=n===void 0?`unknown size`:formatByteSize(Number(n),{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:n<1024n?0:1});if(r>SQLITE_INSPECTION_TIMEOUT_MS)log.debug(`SQLite ${e} for ${t}: ${i}, budget ${r/1e3} seconds`);return{timeoutMs:r,size:i}}function readSqliteInspectionBudget(e,t,n){let r=n;try{r??=fs.statSync(t,{bigint:true}).size;for(const e of[`-wal`,`-shm`,`-journal`])try{r+=fs.statSync(t+e,{bigint:true}).size}catch(e){if(!hasErrnoCode(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}async function readSqliteInspectionBudgetAsync(e,t,n){let r=n;try{r??=(await fs.promises.stat(t,{bigint:true})).size;for(const e of[`-wal`,`-shm`,`-journal`])try{r+=(await fs.promises.stat(t+e,{bigint:true})).size}catch(e){if(!hasErrnoCode(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}function sqliteInspectionTimeoutError(e,t,n,r){return/* @__PURE__ */ new Error(`SQLite ${e} timed out after ${n/1e3} seconds (budget for ${r}) for ${t}. Stop the Gateway service and other OpenClaw processes using this database, then retry; if already stopped, check storage performance.`)}async function withSqliteReadOnlyWorkerScope(e,t){if(!t&&readOnlyWorkerScope.getStore()?.active)return e();const n=createSqliteReadOnlyWorkerScope(t);try{return await n.run(e)}finally{await n.close()}}function isSqliteInspectionDeadlineOwnedByCaller(){return readOnlyWorkerScope.getStore()?.deadlineOwnedByCaller===true}function runScopedSqliteInspection(e,t){const n=readOnlyWorkerScope.getStore();if(!n)return t(e);if(!n.active)return Promise.reject(new SqliteReadOnlyWorkerScopeClosedError);const r=t(e?AbortSignal.any([e,n.controller.signal]):n.controller.signal);n.pending.add(r);r.then(()=>n.pending.delete(r),()=>n.pending.delete(r));return r}function sqliteReadOnlyWorkerArgv(e){const{moduleUrl:t,runtimeGeneration:n}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(e[0]===`content-version`||e[0]===`file-generation`?`sqliteSourceRevision`:`sqliteReadOnly`));return{runtimeGeneration:n,argv:[...resolveForwardedNodeCompilerArgs(),...resolveRuntimeWorkerArgv(t),SQLITE_READONLY_CHILD_ARG,...e]}}function captureSqliteReadOnlyWorkerLaunch(e,t){const n=t===void 0?void 0:getSpawnBroker();return{runtimeGeneration:captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(`sqliteReadOnly`)).runtimeGeneration,env:{...withSelectedSqliteLibraryEnv(resolveNodeCompileCacheEnv(e)),OPENCLAW_STATE_DIR:resolveStateDir(e)},cwd:tryProcessCwd()??tmpdir(),transport:n?{kind:`broker`,owner:n}:{kind:`native`}}}function createScopedSqliteReadOnlyWorker(e){const t=resolveRuntimeProcessEntrypointUrl(`sqliteReadOnly`);return runInDetachedAsyncContext(()=>createSqliteReadOnlyWorkerSession({...e,argv:[...resolveForwardedNodeCompilerArgs(),...resolveRuntimeWorkerArgv(resolveRuntimeWorkerGenerationUrl(t,e.runtimeGeneration)),SQLITE_READONLY_CHILD_ARG,`session`],requestArgs:sqliteReadOnlyWorkerRequestArgs,readBudget:e=>readSqliteInspectionBudgetAsync(`read-only snapshot`,e),deadlineOwnedByCaller:e.retainLifetime===false?()=>false:isSqliteInspectionDeadlineOwnedByCaller,timeoutError:(e,t,n)=>sqliteInspectionTimeoutError(`read-only snapshot`,e,t,n),closeTimeoutMs:SQLITE_INSPECTION_TIMEOUT_MS}))}async function runSqliteReadOnlyOperation(e,t,n){const r=structuredClone(t);const i=await runSqliteReadOnlyWorker(e,{...n,mode:`operation`,command:r});return readOperationResult(r.type,i)}function readOperationResult(e,t){if(typeof t!==`object`||!(`operation`in t)||t.operation!==e)throw new Error(`SQLite read-only worker returned a different operation`);return t.value}function runSqliteReadOnlyWorker(e,t){const n=(t.mode===`auth-profile-rows`||t.mode===`operation`)&&t.source===`canonical`&&isArtifactPreservingStateRead(`agent`,e)?t.mode===`auth-profile-rows`&&readCustodiedDrainedSqliteSource(e)?{...t,artifactPreserving:true,immutable:true}:{...t,artifactPreserving:true}:t;return runScopedSqliteInspection(n.signal,t=>{const r=readOnlyWorkerScope.getStore();if(!r)return runSqliteReadOnlyWorkerOnce(e,n);const i={...n,signal:t};const a=n.mode===`sync`&&!r.busy;if(a)r.busy=true;if(i.mode===`auth-profile-rows`||i.mode===`operation`){const t=captureSqliteReadOnlyWorkerLaunch(i.env,i.source);return sqliteReadOnlyWorkerPool.run(e,i,t)}return(async()=>{if(!a)return runSqliteReadOnlyWorkerOnce(e,i);try{const t=captureSqliteReadOnlyWorkerLaunch();if(!r.worker?.compatible(t)){await r.worker?.close();i.signal?.throwIfAborted();r.worker=createScopedSqliteReadOnlyWorker(t)}return await r.worker.run(e,i)}finally{r.busy=false}})()})}const sqliteReadOnlyWorkerPool=createSqliteReadOnlyWorkerPool(createScopedSqliteReadOnlyWorker);function runSqliteReadOnlyWorkerOnce(e,t,n){if(t.mode===`auth-profile-rows`||t.mode===`operation`)return sqliteReadOnlyWorkerPool.run(e,t,captureSqliteReadOnlyWorkerLaunch(t.env,t.source));const{argv:r,runtimeGeneration:i}=sqliteReadOnlyWorkerArgv(sqliteReadOnlyWorkerRequestArgs(e,t));return runOneShotSqliteInspection({pathname:e,operation:`read-only snapshot`,argv:r,runtimeGeneration:i,signal:t.signal,deadlineOwnedByCaller:n?.deadlineOwnedByCaller??isSqliteInspectionDeadlineOwnedByCaller(),env:n?.env,cwd:n?.cwd,stoppedFailure:`snapshot owner stopped`,read:e=>{t.signal?.throwIfAborted();return readSqliteReadOnlyWorkerValue(e,t.mode)}})}function runOneShotSqliteInspection(e){assertChildRuntimeAvailable();const t=e.mode===`staging-sweep`?`snapshot staging`:e.pathname;const n=withSelectedSqliteLibraryEnv(e.env??resolveNodeCompileCacheEnv());const r=process.execPath;const i=e.cwd??tryProcessCwd();let a=false;let stop=()=>{a=true};const o=(async()=>{const{timeoutMs:o,size:s}=e.mode===`staging-sweep`?resolveSqliteInspectionBudget(e.operation,t,void 0):await readSqliteInspectionBudgetAsync(e.operation,t);e.signal?.throwIfAborted();if(a)throw new Error(e.stoppedFailure);return new Promise((c,l)=>{let u={kind:`launched`,stderr:``,stdout:``,status:null};let d=false;const f=childProcess.execFile(r,e.argv,{encoding:`utf8`,windowsHide:true,env:n,...i===tryProcessCwd()?{}:{cwd:i},maxBuffer:SQLITE_READONLY_WORKER_MAX_BUFFER,timeout:e.deadlineOwnedByCaller?void 0:o,killSignal:`SIGKILL`},(n,r,i)=>{const c=n?.killed&&n.signal===`SIGKILL`&&n.code==null;u={kind:`launched`,status:f.exitCode,failure:n?a?e.stoppedFailure:c?sqliteInspectionTimeoutError(e.operation,t,o,s).message:`exited unsuccessfully: ${n.message}`:void 0,stderr:i,stdout:r,cause:n??void 0}});const p=observeChildRuntime(f);const abort=()=>{if(!a&&!d){a=true;f.kill(`SIGKILL`)}};stop=abort;const finishClose=async()=>{d=true;try{const t=await p();if(t)throw t;c(e.read(u))}catch(e){l(e instanceof Error?e:new Error(String(e)))}finally{e.signal?.removeEventListener(`abort`,abort)}};f.once(`close`,()=>{finishClose()});e.signal?.addEventListener(`abort`,abort,{once:true});if(e.signal?.aborted)abort()})})();if(e.runtimeGeneration){const t=o.then(()=>void 0,()=>void 0);e.runtimeGeneration.retain(t,()=>t)}return retainSnapshotWork(o,()=>stop())}function runSqliteReadOnlyWorkerSync(e,t,n=`sync`,r){assertChildRuntimeAvailable();const{timeoutMs:i,size:a}=readSqliteInspectionBudget(`read-only snapshot`,e);const o=childProcess.spawnSync(process.execPath,sqliteReadOnlyWorkerArgv(sqliteReadOnlyWorkerRequestArgs(e,{mode:n,stagingRoot:t,expectedSourceIdentity:r})).argv,{encoding:`utf8`,windowsHide:true,stdio:`pipe`,env:withSelectedSqliteLibraryEnv(resolveNodeCompileCacheEnv()),maxBuffer:SQLITE_READONLY_WORKER_MAX_BUFFER,timeout:i,killSignal:`SIGKILL`});const s=classifyChildRuntimeFailure({error:o.error,stderr:o.stderr,signal:o.signal,started:Boolean(o.stdout)});if(s)throw s;const c=o.error?{kind:`launch-failed`,error:new Error(hasErrnoCode(o.error,`ETIMEDOUT`)?sqliteInspectionTimeoutError(`read-only snapshot`,e,i,a).message:`SQLite read-only worker failed to start for ${e}: ${o.error.message}`,{cause:o.error})}:{kind:`launched`,stdout:o.stdout,stderr:o.stderr,status:o.status,failure:o.status===0?void 0:`exited with ${o.signal?`signal ${o.signal}`:`code ${o.status}`}`};if(n===`backup-engine`||n===`backup-engine-preserving`)return readSqliteReadOnlyWorkerValue(c,n);if(n===`state-sqlite-populated`)return readSqliteReadOnlyWorkerValue(c,n);return readSqliteReadOnlyWorkerValue(c,n)}export{createStateWorkerMemoryPressureSubscription as C,isStartupConfigStateRead as D,isLiveStateRead as E,withArtifactPreservingStateReads as O,releaseAgentCreationClaimHandle as S,isArtifactPreservingStateRead as T,registerOpenClawAgentDatabaseAsyncResource as _,runSqliteReadOnlyOperation as a,releaseAgentDeletionDatabaseCleanup as b,runSqliteReadOnlyWorkerSync as c,createSqliteWorkerTransferOwner as d,createSqliteWorkerTransferReceiver as f,registerAgentDatabaseResourceReleaseHandler as g,matchesAgentDatabaseClose as h,readSqliteInspectionBudget as i,toStringifiedError as k,sqliteInspectionTimeoutError as l,hasOpenClawAgentDatabaseAsyncResources as m,createScopedSqliteReadOnlyWorker as n,runSqliteReadOnlyWorker as o,assertAgentDatabaseResourceAdmission as p,isSqliteInspectionDeadlineOwnedByCaller as r,runSqliteReadOnlyWorkerOnce as s,captureSqliteReadOnlyWorkerLaunch as t,withSqliteReadOnlyWorkerScope as u,registerOpenClawAgentDatabaseReadCandidateResource as v,artifactPreservingReads as w,AgentDatabaseStartupPublicationError as x,revokeAgentDatabaseResources as y};