openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
205 lines • 94.5 kB
JavaScript
import{C as isRecord,h as normalizeLowercaseStringOrEmpty,i as resolveGlobalSingleton,s as hasErrnoCode}from"./global-singleton-CTnqrmaI.js";import{x as resolveIdentityPathViaExistingAncestorSync}from"./runtime-doctor-migrations-D8alsOFs.js";import{c as resolveStateDir,i as isPathInside,l as LruCache,o as normalizeWindowsPathPreservingCase}from"./account-core-34NfXidI.js";import{F as runWithAsyncStore,M as AsyncContext,R as coerceErrorMessage,V as extractErrorCode,_ as areDiagnosticsEnabledForProcess,i as getChildLogger,n as registerSignalExitFinalizer,o as registerProcessExitCleanup}from"./subsystem-ovCC_dQD.js";import"./runtime-binary-CSMtzJzW.js";import"./openclaw-state-maintenance-context-2fT8FMwD.js";import{An as readDatabasePathIdentity,At as recordSqliteSnapshotFailure,B as prepareSqliteDatabaseAdmission,Bn as getSqliteRuntimeCapabilities,D as captureSqliteDatabaseDescriptorCustodyLocations,Dn as normalizeDatabasePath,E as bindSqliteDatabaseAdmission,En as inspectDatabasePathIdentitySync,Ft as withSqliteNativeOpen,I as invalidateLocalSqliteSchemaAdmissions,Mt as sqliteExtendedResultCode,N as getSqliteDatabaseSchemaRevision,O as discardSqliteDatabaseTransactionAdmissions,Pn as isPostgresSqlConnection,Sn as assertDatabaseFileIdentity,T as beginSqliteDatabaseWrite,Tn as findChangedDatabasePaths,U as publishSqliteDatabaseAdmission,W as publishSqliteDatabaseSchemaChange,Wn as registerListener,X as releaseSqliteDatabaseAdmission,Yt as requireNodeSqlite,at as suspendSqliteDatabaseAdmission,b as registerSqliteReaderConnection,bn as readSqliteDatabaseAdmissionIdentity,cn as SqliteSnapshotDirectoryBusyError,ct as observeSqliteTransactionState,d as createRetainedOperation,dt as observeSqliteNativeClose,et as retireSqliteDatabaseAdmissionForPath,fn as throwSqliteLifecycleErrors,ft as observeSqliteNativeOperations,it as settleSqliteDatabaseAdmissionPublication,j as getSqliteDatabaseAdmission,jn as readDatabasePathIdentitySync,jt as sqliteErrorCode,k as finishSqliteDatabaseWrite,ln as classifyRetiredSqliteSnapshotRemovalError,lt as postgresReadSnapshots,m as mapRetainedOperation,mn as captureSqliteDatabaseAdmissions,pt as canPreserveTransactionSnapshot,q as readSqliteDatabaseWriteRevision,sn as SqliteSnapshotCleanupError,st as finishSqliteReadScope,tn as beginSqliteDatabaseAdmissionOperation,un as createSqliteLifecycleAggregateError,ut as sqliteSchemaOwners,zt as withSqliteDatabaseAdmissionSettlement}from"./sqlite-worker-request-class-GkmU-e0P.js";import{n as materializeErrorStack,r as throwSettledAggregate,t as collectSynchronousErrors}from"./error-graph-internal-CWqvi3Vy.js";import{n as hashFileDescriptorSync,r as sameFileMutationFingerprint}from"./file-descriptor-C8OEaEgp.js";import{a as normalizeSchemaSql,c as quoteSqliteIdentifier}from"./sqlite-schema-sql-D2HdV_QG.js";import{o as _usingCtx}from"./openclaw-process-census-eUZSajw_.js";import fsPromises from"node:fs/promises";import path from"node:path";import fs,{statSync}from"node:fs";import{isDeepStrictEqual}from"node:util";import{copyRootFileSync,sameFileIdentity}from"@openclaw/fs-safe/advanced";import{createHash,randomUUID}from"node:crypto";import os from"node:os";import{pathToFileURL}from"node:url";import{isMainThread}from"node:worker_threads";import{spawn}from"node:child_process";import{AsyncLocalStorage}from"node:async_hooks";
//!src/infra/kysely-sync-cache-state.ts
const{kyselyByDatabase,queryErrorHandlerByDatabase}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap}));const statementCacheSymbol=Symbol.for(`openclaw.kyselySyncStatementCache`);const statementInvalidationSymbol=Symbol.for(`openclaw.kyselySyncStatementInvalidation`);const statementCacheEnabledSymbol=Symbol.for(`openclaw.kyselySyncStatementCacheEnabled`);const authorizerActiveSymbol=Symbol.for(`openclaw.kyselySyncAuthorizerActive`);const disposeCallbacksSymbol=Symbol.for(`openclaw.sqliteDisposeCallbacks`);const disposeGuardsSymbol=Symbol.for(`openclaw.sqliteDisposeGuards`);const statementCacheCapacity=64;const statementCacheEntryBytes=65536;function disposeSqliteStatement(e){e[Symbol.dispose]?.()}function clearStatementCache(e){const t=e[statementCacheSymbol];delete e[statementCacheSymbol];if(!t)return;for(const e of t.statements.values())if(!t.active.has(e))disposeSqliteStatement(e)}function registerNodeSqliteDisposeCallback(e,t){const n=e;installStatementInvalidation(n);return registerListener(n[disposeCallbacksSymbol]??=/* @__PURE__ */ new Set,t)}function registerNodeSqliteDisposeGuard(e,t){const n=e;installStatementInvalidation(n);return registerListener(n[disposeGuardsSymbol]??=/* @__PURE__ */ new Set,t)}function assertNodeSqliteDisposalAllowed(e){for(const t of e[disposeGuardsSymbol]??[])t()}function disposeNodeSqliteDependents(e,t=`close`){assertNodeSqliteDisposalAllowed(e);for(const n of e[disposeCallbacksSymbol]??[])n(t)}function registerNodeSqliteKyselyQueryErrorHandler(e,t){queryErrorHandlerByDatabase.set(e,t)}function clearNodeSqliteKyselyCacheForDatabase(e){clearStatementCache(e);kyselyByDatabase.delete(e);queryErrorHandlerByDatabase.delete(e)}function installStatementInvalidation(e){if(e[statementInvalidationSymbol])return;if(typeof e.setAuthorizer===`function`){const t=e.setAuthorizer.bind(e);Object.defineProperty(e,"setAuthorizer",{configurable:true,writable:true,value(e){t(e);this[authorizerActiveSymbol]=e!==null;clearStatementCache(this)}})}if(typeof e.deserialize===`function`){const t=e.deserialize.bind(e);Object.defineProperty(e,"deserialize",{configurable:true,writable:true,value(...e){disposeNodeSqliteDependents(this,`replace`);try{t(...e)}finally{clearStatementCache(this)}}})}for(const t of[`close`,Symbol.dispose])if(typeof e[t]===`function`){const n=e[t].bind(e);Object.defineProperty(e,t,{configurable:true,writable:true,value(){disposeNodeSqliteDependents(this);clearNodeSqliteKyselyCacheForDatabase(this);return n()}})}Object.defineProperty(e,statementInvalidationSymbol,{configurable:true,value:true})}function enableNodeSqliteKyselyStatementCache(e){const t=e;installStatementInvalidation(t);t[statementCacheEnabledSymbol]=true}function queryFitsStatementCache(e,t){let n=Buffer.byteLength(e);if(n>statementCacheEntryBytes)return false;for(const e of t){if(typeof e===`string`){if(e.length>statementCacheEntryBytes-n)return false;n+=Buffer.byteLength(e)}else if(ArrayBuffer.isView(e))n+=e.byteLength;if(n>statementCacheEntryBytes)return false}return true}function executeWithCachedStatement(e,t,n,r,i){if(isPostgresSqlConnection(e))return r(e.prepare(t));const a=e;const executeLeased=(e,t)=>{if(i){try{i(t)}catch(e){t();throw e}return r(e)}try{return r(e)}finally{t()}};if(!a[statementCacheEnabledSymbol]||a[authorizerActiveSymbol]||!queryFitsStatementCache(t,n)){const n=e.prepare(t);return executeLeased(n,()=>disposeSqliteStatement(n))}let o=a[statementCacheSymbol];if(!o){o={statements:/* @__PURE__ */ new Map,candidates:/* @__PURE__ */ new Set,active:/* @__PURE__ */ new WeakSet};Object.defineProperty(a,statementCacheSymbol,{configurable:true,value:o})}const s=o.statements.get(t);let c;if(s&&!o.active.has(s)){o.statements.delete(t);o.statements.set(t,s);c=s}else{c=e.prepare(t);if(!s&&o.candidates.delete(t)){o.statements.set(t,c);if(o.statements.size>statementCacheCapacity){const e=o.statements.entries().next().value;o.statements.delete(e[0]);if(!o.active.has(e[1]))disposeSqliteStatement(e[1])}}else if(!s){o.candidates.add(t);if(o.candidates.size>statementCacheCapacity){const e=o.candidates.values().next().value;if(e!==void 0)o.candidates.delete(e)}}}o.active.add(c);return executeLeased(c,()=>{o.active.delete(c);if(a[statementCacheSymbol]!==o||o.statements.get(t)!==c)disposeSqliteStatement(c)})}
//!src/infra/sqlite-busy-timeout.ts
const lockFailureReportingByDatabase=/* @__PURE__ */ new WeakMap;const{busyTimeoutByDatabase,trackedDatabases}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}));function rememberSqliteBusyTimeout(e,t){if(!trackedDatabases.has(e)){trackedDatabases.add(e);registerNodeSqliteDisposeCallback(e,()=>busyTimeoutByDatabase.delete(e))}busyTimeoutByDatabase.set(e,t)}function normalizeSqliteNonNegativeInteger(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function readSqliteBusyTimeout(e){const t=busyTimeoutByDatabase.get(e);if(t!==void 0)return t;const n=e.prepare(`PRAGMA busy_timeout`).get();const r=n?.busy_timeout??n?.timeout;const i=typeof r===`bigint`?Number(r):Number(r??0);rememberSqliteBusyTimeout(e,i);return i}function setSqliteBusyTimeout(e,t){const n=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`);if(busyTimeoutByDatabase.get(e)===n)return;e.exec(`PRAGMA busy_timeout = ${n}`);rememberSqliteBusyTimeout(e,n)}function shouldReportSqliteLockFailure(e){return lockFailureReportingByDatabase.get(e)!==`suppress`}function runWithSqliteBusyTimeout(e,t,n,r={}){const i=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`);const a=readSqliteBusyTimeout(e);const o=lockFailureReportingByDatabase.get(e);if(r.lockFailureReporting)lockFailureReportingByDatabase.set(e,r.lockFailureReporting);setSqliteBusyTimeout(e,i);let s=false;const restore=()=>{if(s)return;if(e.isOpen&&a!==i)setSqliteBusyTimeout(e,a);if(o)lockFailureReportingByDatabase.set(e,o);else lockFailureReportingByDatabase.delete(e);s=true};try{return n(restore)}finally{restore()}}
//!src/infra/database-engine/physical-facts-contract.ts
const postgresPhysicalFactsKey={name:`database.engine.schema`,schemaDependent:true};
//!src/infra/database-engine/postgres-catalog.ts
function hasPostgresCatalogColumn(e,t,n){return e.some(e=>e.table===t&&e.kind===`column`&&e.value!==null&&typeof e.value===`object`&&`name`in e.value&&e.value.name===n)}function canonical(e){return JSON.stringify(e,(e,t)=>t!==null&&typeof t===`object`&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).toSorted(([e],[t])=>e.localeCompare(t,`en`))):t)}function assertPostgresCatalog(e,t){if(!isDeepStrictEqual(e.map(canonical).toSorted(),t.map(canonical).toSorted()))throw new Error(`PostgreSQL catalog differs from its generated contract; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`)}function readPostgresCatalog(e){if(!Array.isArray(e)||!e.every(e=>e!==null&&typeof e===`object`&&typeof e.table===`string`&&typeof e.kind===`string`&&`value`in e))throw new Error(`PostgreSQL did not return catalog facts`);return e}function postgresCatalogQuery(e,t=false){const n=`'${e.replaceAll(`'`,`''`)}'`;const columns=(e,t)=>`(SELECT jsonb_agg(a.attname ORDER BY k.ordinality) FROM unnest(${t}) WITH ORDINALITY k(num, ordinality) JOIN pg_catalog.pg_attribute a ON a.attrelid = ${e} AND a.attnum = k.num)`;const action=e=>`CASE ${e} WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END`;return`WITH relations AS (
SELECT c.oid, c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = ${n} AND c.relkind IN ('r', 'p')
), attributes AS (
SELECT r.relname, a.attname, a.atttypid, a.atttypmod, a.attnotnull,
a.attidentity, a.attnum, a.attgenerated, a.attcollation,
pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS default_expression
FROM relations r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid
LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = r.oid AND d.adnum = a.attnum
WHERE a.attnum > 0 AND NOT a.attisdropped
), facts AS (
SELECT r.relname AS "table", 'table' AS kind, 'null'::jsonb AS value FROM relations r
UNION ALL SELECT a.relname, 'column', jsonb_build_object(
'name', a.attname, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod),
'nullable', NOT a.attnotnull, 'identity', a.attidentity = 'd', 'position', a.attnum,
'default', regexp_replace(a.default_expression, '::(text|bigint|double precision)$', ''))
FROM attributes a
UNION ALL SELECT r.relname, CASE c.contype WHEN 'p' THEN 'primaryKey' ELSE 'unique' END,
${columns(`r.oid`,`c.conkey`)} FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid WHERE c.contype IN ('p', 'u')
UNION ALL SELECT r.relname, 'foreignKey', jsonb_build_object(
'columns', ${columns(`r.oid`,`c.conkey`)}, 'target', target.relname,
'targetColumns', ${columns(`c.confrelid`,`c.confkey`)},
'onUpdate', ${action(`c.confupdtype`)}, 'onDelete', ${action(`c.confdeltype`)},
'deferrable', c.condeferrable, 'deferred', c.condeferred)
FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
JOIN pg_catalog.pg_class target ON target.oid = c.confrelid WHERE c.contype = 'f'
UNION ALL SELECT r.relname, 'indexes', to_jsonb((SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = r.oid)) FROM relations r
UNION ALL SELECT r.relname, 'checks', to_jsonb((SELECT count(*) FROM pg_catalog.pg_constraint c WHERE c.conrelid = r.oid AND c.contype = 'c')) FROM relations r
${t?`UNION ALL SELECT r.relname, 'constraintDefinition', jsonb_build_object('name', c.conname, 'definition', pg_catalog.pg_get_constraintdef(c.oid)) FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid
UNION ALL SELECT a.relname, 'columnDefinition', jsonb_build_object('name', a.attname, 'default', a.default_expression, 'generated', a.attgenerated, 'identity', a.attidentity, 'collation', a.attcollation::regcollation::text) FROM attributes a
UNION ALL SELECT r.relname, 'triggerDefinition', jsonb_build_object('name', t.tgname, 'definition', pg_catalog.pg_get_triggerdef(t.oid), 'enabled', t.tgenabled, 'function', pg_catalog.pg_get_functiondef(t.tgfoid)) FROM relations r JOIN pg_catalog.pg_trigger t ON t.tgrelid = r.oid WHERE NOT t.tgisinternal
UNION ALL SELECT c.relname, 'viewDefinition', to_jsonb(pg_catalog.pg_get_viewdef(c.oid)) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${n} AND c.relkind IN ('v', 'm')
UNION ALL SELECT c.cfgname, 'textSearchDefinition', jsonb_build_object('token', m.maptokentype, 'order', m.mapseqno, 'dictionary', d.dictname, 'namespace', dn.nspname)
FROM pg_catalog.pg_ts_config c JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace
JOIN pg_catalog.pg_ts_config_map m ON m.mapcfg = c.oid JOIN pg_catalog.pg_ts_dict d ON d.oid = m.mapdict
JOIN pg_catalog.pg_namespace dn ON dn.oid = d.dictnamespace WHERE n.nspname = ${n} AND c.cfgname = 'openclaw_simple_unaccent'
UNION ALL SELECT p.proname, 'functionDefinition', to_jsonb(pg_catalog.pg_get_functiondef(p.oid)) FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${n} AND p.proname = 'openclaw_vector' AND p.prokind = 'f'`:``}
) SELECT coalesce(jsonb_agg(facts), '[]'::jsonb) AS catalog FROM facts`}
//!src/infra/database-engine/capability-unavailable.ts
var DatabaseSearchCapabilityUnavailableError=class extends Error{constructor(e,t){super(t??`Database ${e} search capability is unavailable.`);this.capability=e;this.code=`DATABASE_SEARCH_CAPABILITY_UNAVAILABLE`;this.name=`DatabaseSearchCapabilityUnavailableError`}};
//!src/infra/database-engine/postgres-search-schema.ts
const pgSearchName=e=>`"${e.replaceAll(`"`,`""`)}"`;const searchConfig=`openclaw_simple_unaccent`;const postgresSearchTokenSeparators=`[[:punct:]]+`;function postgresSearchVectorSql(e,t,n=1){const r=`coalesce(${t}, '')`;return`to_tsvector(${e}::regconfig, ${n===2?`regexp_replace(${r}, '${postgresSearchTokenSeparators}', ' ', 'g')`:r})`}function postgresSearchTextTriggerSql(e){const{table:t,field:n,sync:r}=e;return`CREATE FUNCTION ${r}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.openclaw_search := ${postgresSearchVectorSql(`format('%I.%I', TG_TABLE_SCHEMA, '${searchConfig}')`,`NEW.${n}`,2)};
RETURN NEW;
END $$;
CREATE TRIGGER ${r} BEFORE INSERT OR UPDATE OF ${n} ON ${t} FOR EACH ROW EXECUTE FUNCTION ${r}();`}function postgresVectorDimensions(e){if(typeof e!==`number`||!Number.isInteger(e)||e<1||e>16e3)throw new Error(`PostgreSQL vector capability unavailable: dimensions must be 1–16000; choose a supported embedding dimension and rebuild the derived index.`);return e}const key={name:`database.postgres.search`,schemaDependent:true};function admitPostgresSearch(e,t,n,r=1){const i=JSON.stringify(t);if(getSqliteDatabaseAdmission(e,key)?.some(e=>e.signature===i&&e.vectorSearchVersion>=r))return;const a=/* @__PURE__ */ new Set;if(Object.keys(t.text??{}).length)a.add(`unaccent`);if(Object.values(t.text??{}).some(e=>e.postgres?.mode===`trigram`))a.add(`pg_trgm`);if(t.mode!==`keyword-only`&&Object.keys(t.vector??{}).length)a.add(`vector`);for(const e of t.mode===`keyword-only`?[]:Object.values(t.vector??{}))postgresVectorDimensions(e.postgres?.dimensions);const o=t.extensionSchema??`public`;const s=e.prepare(`SELECT a.name, e.extname, e.extversion, n.nspname FROM pg_catalog.pg_available_extensions a
LEFT JOIN pg_catalog.pg_extension e ON e.extname = a.name
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
WHERE a.name IN ('unaccent', 'pg_trgm', 'vector')`).all();for(const e of a){const t=s.find(t=>t.name===e);if(!t?.extname||t.nspname!==o){const n=!t?`Install the server extension package for ${e}, then have a database administrator run`:t.extname?`Configure the store's extensionSchema as ${String(t.nspname)}, or have a database administrator relocate the extension; installation SQL is`:`Have a database administrator run`;throw new DatabaseSearchCapabilityUnavailableError(e===`vector`?`vector`:`fullText`,`PostgreSQL ${e} capability unavailable. ${n}: CREATE EXTENSION IF NOT EXISTS ${pgSearchName(e)} WITH SCHEMA ${pgSearchName(o)};${e===`vector`?` For keyword-only memory explicitly set memory.search.provider to "none".`:``}`)}if(e===`vector`&&r===2){const e=/^(\d+)\.(\d+)/.exec(String(t.extversion));if(!e||Number(e[1])===0&&Number(e[2])<7)throw new DatabaseSearchCapabilityUnavailableError(`vector`,`PostgreSQL binary vector search requires pgvector 0.7 or newer. Upgrade the server extension package, then have a database administrator run ALTER EXTENSION vector UPDATE before reopening the store.`)}}if(e.prepare(`SELECT coalesce(has_schema_privilege(to_regnamespace(?), 'CREATE'), has_database_privilege(current_database(), 'CREATE'))::int AS allowed`).get(n)?.allowed!==1)throw new Error(`PostgreSQL search capability unavailable: insufficient CREATE privilege. Have the database owner grant CREATE on schema ${pgSearchName(n)} (or on the database before initial admission).`);return()=>publishPostgresSearch(e,t,r)}function publishPostgresSearch(e,t,n=1){const r=JSON.stringify(t);const i=getSqliteDatabaseAdmission(e,key)??[];const a=i.find(e=>e.signature===r);publishSqliteDatabaseAdmission(e,key,[...i.filter(e=>e.signature!==r),{signature:r,vectorSearchVersion:a?.vectorSearchVersion===2?2:n}])}function postgresVectorDecoderSql(e,t=1,n=false){const r=pgSearchName(e);if(t===1)return`CREATE ${n?`OR REPLACE `:``}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE vals real[] := '{}'; bits bigint; exponent integer; fraction double precision; value double precision;
BEGIN
IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF;
FOR i IN 0..dimensions-1 LOOP
bits := 0;
FOR j IN 0..7 LOOP bits := bits | (get_byte(bytes, i*8+j)::bigint << (j*8)); END LOOP;
exponent := ((bits >> 52) & 2047)::integer;
IF exponent = 2047 THEN RAISE EXCEPTION 'embedding must be finite'; END IF;
fraction := (bits & 4503599627370495)::double precision / 4503599627370496;
IF exponent < 873 OR (exponent = 873 AND fraction = 0) THEN value := 0;
ELSE value := (1 + fraction) * power(2::double precision, exponent - 1023); END IF;
IF bits < 0 THEN value := -value; END IF;
vals := array_append(vals, value::real);
END LOOP;
RETURN vals::${r}.vector;
END $$;`;return`CREATE ${n?`OR REPLACE `:``}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE vals double precision[]; first_nonfinite integer;
BEGIN
IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF;
-- Flatten TOAST once: repeated get_byte calls otherwise detoast the entire embedding.
bytes := bytes || '\\x'::bytea;
WITH bits AS MATERIALIZED (
SELECT i,
get_byte(bytes, i*8)::bigint |
(get_byte(bytes, i*8+1)::bigint << 8) |
(get_byte(bytes, i*8+2)::bigint << 16) |
(get_byte(bytes, i*8+3)::bigint << 24) |
(get_byte(bytes, i*8+4)::bigint << 32) |
(get_byte(bytes, i*8+5)::bigint << 40) |
(get_byte(bytes, i*8+6)::bigint << 48) |
(get_byte(bytes, i*8+7)::bigint << 56) AS b
FROM generate_series(0, dimensions-1) AS i
), parts AS (
SELECT i, b, ((b >> 52) & 2047)::integer AS exponent,
(b & 4503599627370495)::double precision / 4503599627370496 AS fraction
FROM bits
)
SELECT coalesce(array_agg(
CASE WHEN b < 0 THEN -1::double precision ELSE 1::double precision END *
CASE WHEN exponent = 2047 OR exponent < 873 OR (exponent = 873 AND fraction = 0)
THEN 0::double precision
ELSE (1 + fraction) * power(2::double precision, exponent - 1023)
END ORDER BY i
), ARRAY[]::double precision[]), min(i) FILTER (WHERE exponent = 2047)
INTO vals, first_nonfinite FROM parts;
IF first_nonfinite IS NOT NULL THEN
-- Preserve the old left-to-right overflow versus nonfinite error precedence.
PERFORM vals[1:first_nonfinite]::real[];
RAISE EXCEPTION 'embedding must be finite';
END IF;
RETURN vals::real[]::${r}.vector;
END $$;`}function postgresSearchSql(e,t,n={},r=1,i=1,a=1){const o=pgSearchName(e.extensionSchema??`public`);const s=`${pgSearchName(t)}.${pgSearchName(searchConfig)}`;const c=`'${s.replaceAll(`'`,`''`)}'`;const l=[];if(Object.keys(e.text??{}).length&&!n.text)l.push(`CREATE TEXT SEARCH CONFIGURATION ${s} (COPY = pg_catalog.simple);
ALTER TEXT SEARCH CONFIGURATION ${s} ALTER MAPPING FOR hword, hword_part, word, numword, numhword, hword_numpart WITH ${o}.unaccent, pg_catalog.simple;`);for(const t of Object.values(e.text??{})){if(!t.postgres||t.fields.length!==1)throw new Error(`PostgreSQL text index requires one field and a declared source identity`);const e=pgSearchName(t.table),n=pgSearchName(t.fields[0]);l.push(a===2?`ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector;
${postgresSearchTextTriggerSql({table:e,field:n,sync:pgSearchName(`${t.table}_search_sync`)})}
UPDATE ${e} SET openclaw_search = ${postgresSearchVectorSql(c,n,2)};`:`ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector GENERATED ALWAYS AS (${postgresSearchVectorSql(c,n)}) STORED;`);l.push(`CREATE INDEX ${pgSearchName(`${t.table}_search_gin`)} ON ${e} USING gin(openclaw_search);`);if(t.postgres.mode===`trigram`)l.push(`CREATE INDEX ${pgSearchName(`${t.table}_trgm_gin`)} ON ${e} USING gin(${n} ${o}.gin_trgm_ops);`)}if(e.mode===`keyword-only`)return l.join(`
`);if(Object.keys(e.vector??{}).length&&!n.vector)l.push(postgresVectorDecoderSql(e.extensionSchema??`public`,r));for(const t of Object.values(e.vector??{})){const e=t.postgres;if(!e)throw new Error(`PostgreSQL vector index requires a canonical embedding source`);const n=pgSearchName(t.table),r=pgSearchName(e.source),a=pgSearchName(e.key),s=pgSearchName(e.embedding),c=postgresVectorDimensions(e.dimensions);const u=`INSERT INTO ${n}(id, embedding) SELECT ${a}, openclaw_vector(${s}, ${c}) FROM ${r} WHERE octet_length(${s}) > 0`;const d=i===2?`, embedding_bits bit(${c}) GENERATED ALWAYS AS (CASE WHEN ${o}.vector_norm(embedding) > 0 THEN ${o}.binary_quantize(embedding)::bit(${c}) ELSE NULL END) STORED`:``;l.push(`CREATE TABLE ${n} (id TEXT PRIMARY KEY REFERENCES ${r}(${a}) ON UPDATE CASCADE ON DELETE CASCADE, embedding ${o}.vector(${c}) NOT NULL${d});
CREATE FUNCTION ${pgSearchName(`${t.table}_sync`)}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' AND OLD.${s} IS NOT DISTINCT FROM NEW.${s} THEN RETURN NEW; END IF;
IF octet_length(NEW.${s}) > 0 THEN
INSERT INTO ${n}(id, embedding) VALUES (NEW.${a}, openclaw_vector(NEW.${s}, ${c}))
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;
ELSE
DELETE FROM ${n} WHERE id = NEW.${a};
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER ${pgSearchName(`${t.table}_sync`)} AFTER INSERT OR UPDATE OF ${s} ON ${r} FOR EACH ROW EXECUTE FUNCTION ${pgSearchName(`${t.table}_sync`)}();
${u};`)}return l.join(`
`)}
//!src/infra/database-engine/postgres-schema.ts
function postgresStoreNamespace(e,t,n){return`${e}_${t}_${n.replaceAll(`-`,``).slice(0,16)}`}const postgresSchemaMetadataSql=`CREATE TABLE openclaw_schema_meta (
store TEXT PRIMARY KEY, version BIGINT NOT NULL, store_id TEXT NOT NULL,
fingerprint TEXT, ddl_hash TEXT, server_major BIGINT)`;const recovery$1=`Use a compatible OpenClaw binary or restore the matching PostgreSQL schema and anchor; do not edit schema metadata.`;const canonicalNamespace=`openclaw_schema`;const quote=e=>`"${e.replaceAll(`"`,`""`)}"`;const hash$1=e=>createHash(`sha256`).update(e).digest(`hex`);const capabilities=/* @__PURE__ */ new WeakMap;const admittedSchemaKey={name:`database.postgres.schema`,schemaDependent:true};const getAdmittedPostgresSchema=e=>getSqliteDatabaseAdmission(e,admittedSchemaKey);const retainPostgresSchema=(e,t)=>{const{postgresMigrations:n,...r}=t;publishSqliteDatabaseAdmission(e,admittedSchemaKey,r)};function admitPostgresCapabilities(e){const t=capabilities.get(e);if(t)return t;const n=e.prepare(`SELECT current_setting('server_version_num')::int AS version, current_setting('server_encoding') AS server_encoding, current_setting('client_encoding') AS client_encoding`).get();if(!n||typeof n.version!==`number`||n.version<16e4||n.server_encoding!==`UTF8`||n.client_encoding!==`UTF8`)throw new Error(`PostgreSQL requires version 16 or newer and UTF8 server/client encoding; upgrade the server or port to a UTF8 database and set client_encoding=UTF8.`);const r={serverMajor:Math.floor(n.version/1e4),serverEncoding:`UTF8`,clientEncoding:`UTF8`};capabilities.set(e,r);return r}function readPostgresSchema(e,t,n){const r=e.query(`WITH captured AS (${postgresCatalogQuery(t,true)})
SELECT catalog::text, to_jsonb(meta)::text AS metadata FROM captured
CROSS JOIN ${quote(t)}.openclaw_schema_meta meta WHERE meta.store = ?`,[n]).rows[0];if(!r||typeof r.catalog!==`string`||typeof r.metadata!==`string`)throw new Error(`Missing PostgreSQL catalog or metadata. ${recovery$1}`);const i=JSON.parse(r.metadata);return{catalog:readPostgresCatalog(JSON.parse(r.catalog)),metadata:i}}function withPostgresSearchExtensions(e,t){return{...e,searchExtensions:JSON.parse(t.metadata.search_extensions??`{}`)}}function postgresSchemaFingerprint(e,t){const n=e.filter(e=>e.table!==`openclaw_schema_meta`).map(e=>JSON.stringify(e)).toSorted().join(`
`);if(!t)return hash$1(n);const r=JSON.stringify(t.from).slice(1,-1);const i=JSON.stringify(quote(t.from)).slice(1,-1);const a=JSON.stringify(t.to).slice(1,-1);return hash$1(n.replaceAll(`${i}.`,`${r}.`).replaceAll(r,a))}function postgresSchemaSql(e,t,n){const r=new Set(n?.filter(e=>e.kind===`table`).map(e=>e.table));const i=e.postgresFragments?.filter(e=>n?e.tables.some(e=>r.has(e)):e.activation===`version-additive`)??[];const a=/* @__PURE__ */ new Map;const add=t=>{if(a.has(t.id))return;for(const n of t.dependencies){const t=e.postgresFragments?.find(e=>e.id===n);if(!t)throw new Error(`Missing PostgreSQL fragment dependency ${n}`);add(t)}a.set(t.id,t.sql)};i.forEach(add);const o=[e.search,...Object.values(e.searchExtensions??{})].filter(e=>e!==void 0);const s={text:false,vector:false};const c=o.map(n=>{const r=postgresSearchSql(n,t,s,e.postgresVectorDecoderVersion,e.postgresVectorSearchVersion,e.postgresTextSearchVersion);s.text||=Object.keys(n.text??{}).length>0;s.vector||=n.mode!==`keyword-only`&&Object.keys(n.vector??{}).length>0;return`;\n${r}`});const l=e.postgresWithoutOptionalColumn;return[(l&&n&&!hasPostgresCatalogColumn(n,l.table,l.column)?l.sql:e.postgres)??``,...a.values(),...c].join(`
`)}function postgresSchemaHash(e,t){return hash$1(postgresSchemaSql(e,canonicalNamespace,t))}function recordPostgresSchema(e,t,n,r){if(!e.isTransaction)throw new Error(`PostgreSQL schema publication requires the owner's writer transaction`);const i=r??readPostgresSchema(e,t,n.id);const a=postgresSchemaHash(n,i.catalog);e.prepare(`UPDATE openclaw_schema_meta SET fingerprint = ?, ddl_hash = ?, server_major = ? WHERE store = ?`).run(postgresSchemaFingerprint(i.catalog),a,admitPostgresCapabilities(e).serverMajor,n.id);return a}function verifyPostgresSchema(e,t,n,r,i=false,a=false){const o=postgresSchemaFingerprint(r.catalog);const s=postgresSchemaHash(n,r.catalog);const{metadata:c}=r;const l=admitPostgresCapabilities(e).serverMajor;if(c.server_major===l&&c.fingerprint&&c.fingerprint!==o)throw new Error(`PostgreSQL schema drift detected. ${recovery$1}`);if(c.server_major===l&&c.fingerprint&&c.ddl_hash===s)return s;if(a)throw new Error(`Read-only PostgreSQL admission requires a matching schema seal. ${recovery$1}`);if(i){e.runTransaction(()=>verifyPostgresSchemaDefinition(e,t,n,r));return}verifyAndRecordPostgresSchema(e,t,n,r);return s}function verifyPostgresSchemaDefinition(e,t,n,r){const i=postgresSchemaFingerprint(r.catalog,{from:t,to:t});const a=`openclaw_check_${randomUUID().replaceAll(`-`,``)}`;e.exec(`CREATE SCHEMA ${quote(a)}`);try{e.exec(`SET LOCAL search_path TO ${quote(a)}`);e.exec(postgresSchemaSql(n,a,r.catalog));const o=e.query(`SELECT catalog::text FROM (${postgresCatalogQuery(a,true)}) captured`).rows[0];if(postgresSchemaFingerprint(readPostgresCatalog(JSON.parse(String(o?.catalog))),{from:a,to:t})!==i)throw new Error(`PostgreSQL schema drift detected against generated DDL. ${recovery$1}`)}finally{e.exec(`SET LOCAL search_path TO ${quote(t)}`);e.exec(`DROP SCHEMA ${quote(a)} CASCADE`)}}function verifyAndRecordPostgresSchema(e,t,n,r=readPostgresSchema(e,t,n.id)){e.runTransaction(()=>{verifyPostgresSchemaDefinition(e,t,n,r);if(!r.metadata.ddl_hash)e.exec(`ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS fingerprint TEXT, ADD COLUMN IF NOT EXISTS ddl_hash TEXT, ADD COLUMN IF NOT EXISTS server_major BIGINT`);recordPostgresSchema(e,t,n,r)});return r}
//!src/infra/database-engine/physical-facts.ts
const recovery=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`;function getPostgresPhysicalFacts(e,t){if(isPostgresSqlConnection(e)&&e.isTransaction&&!t?.refresh){const t=postgresReadSnapshots.get(e);if(t?.schema.store===`agent`)return e.isOpen&&e.anchor.isOpen?t.schema:void 0}return getSqliteDatabaseAdmission(e,postgresPhysicalFactsKey,t)}function admitPostgresPhysicalFacts(e){const t=getPostgresPhysicalFacts(e.db);if(t){if(t.version!==e.version||t.storeId!==e.storeId||t.namespace!==e.namespace||t.store!==e.store)throw new Error(`PostgreSQL metadata identity or version mismatch. ${recovery}`);if(e.requireSealedSchema){const n=e.schema;const r=getAdmittedPostgresSchema(e.db);if(!n||!t.schemaHash||t.schemaHash!==postgresSchemaHash({...n,searchExtensions:r?.searchExtensions},t.catalog))throw new Error(`Read-only PostgreSQL admission requires a matching schema seal. ${recovery}`)}return t}const n=admitPostgresCapabilities(e.db);let r;try{r=readPostgresSchema(e.db,e.namespace,e.store)}catch(e){throw new Error(`Cannot read PostgreSQL catalog or metadata. ${recovery}`,{cause:e})}const{metadata:i,catalog:a}=r;if(i.version!==e.version||i.store_id!==e.storeId)throw new Error(`PostgreSQL metadata identity or version mismatch. ${recovery}`);let o;if(e.schema){const t=withPostgresSearchExtensions(e.schema,r);if(e.recordSchema)o=recordPostgresSchema(e.db,e.namespace,t,r);else o=verifyPostgresSchema(e.db,e.namespace,t,r,e.preserveSchemaSeal,e.requireSealedSchema);retainPostgresSchema(e.db,t)}const s={engine:`postgres`,admissionId:randomUUID(),store:e.store,namespace:e.namespace,storeId:i.store_id,version:i.version,schemaHash:o,capabilities:n,catalog:a};publishSqliteDatabaseAdmission(e.db,postgresPhysicalFactsKey,s);return s}function requireNativeDatabaseFile(e,t){if(e===`postgres`)throw new Error(`PostgreSQL cannot use SQLite ${t}; stop the Gateway and back up/restore the PostgreSQL schema with its matching anchor (P3-6 export support pending).`)}
//!src/infra/sqlite-pinned-read-snapshot.ts
const snapshots=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap);function getSqlitePinnedReadSnapshot(e){return snapshots.get(e)}function runSqliteSchemaReadSnapshotSync(e,t){const n=snapshots.get(e);for(let r=0;;r+=1){snapshots.set(e,n??{});try{const n=executeWithCachedStatement(e,`PRAGMA schema_version`,[],e=>{let n;try{let i;try{n=e.iterate();i=n.next()}catch(e){if(!isMainThread&&r<4&&(sqliteExtendedResultCode(e)===261||sqliteErrorCode(e)===`SQLITE_BUSY_RECOVERY`))return{retry:true};throw e}if(i.done)throw new Error(`SQLite schema_version query returned no row`);return{retry:false,value:t(Number(i.value.schema_version))}}finally{n?.return?.()}});if(!n.retry)return n.value}finally{if(!n)snapshots.delete(e)}}}
//!src/infra/sqlite-schema-admission.ts
const schemaAdmission={name:`sqlite-schema`,writer:`connection`,lifetime:`process`,schemaDependent:true,read:e=>{return isRecord(e)?e:void 0}};const textEncodingAdmission={name:`sqlite-text-encoding`,writer:`connection`,lifetime:`process`,read:e=>typeof e===`string`?e:void 0};function readSqliteTextEncoding(e){const t=getSqliteDatabaseAdmission(e,textEncodingAdmission);if(t!==void 0)return t;const n=executeWithCachedStatement(e,`PRAGMA encoding`,[],e=>e.get());if(typeof n?.encoding!==`string`)throw new Error(`SQLite did not report its text encoding`);return n.encoding}function readSqliteSchemaObjects(e){return executeWithCachedStatement(e,`SELECT type, name, tbl_name, sql FROM main.sqlite_schema WHERE type IN ('table', 'view', 'index', 'trigger')`,[],e=>e.all())}function captureSqliteSchemaFacts(e,t=0,n){const r=getSqliteDatabaseAdmission(e,textEncodingAdmission);const i=runSqliteSchemaReadSnapshotSync(e,i=>{const a=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get());const o=Number(a?.user_version??0);n?.(o);const s=r??readSqliteTextEncoding(e);const c=readSqliteSchemaObjects(e);const l={admissionId:randomUUID(),revision:t,userVersion:o,textEncoding:s,schemaVersion:i,tables:/* @__PURE__ */ new Set,views:/* @__PURE__ */ new Set,tableSql:/* @__PURE__ */ new Map,indexes:/* @__PURE__ */ new Set,indexDefinitions:/* @__PURE__ */ new Map,triggers:/* @__PURE__ */ new Map};for(const e of c){if(typeof e.name!==`string`)continue;const t=typeof e.sql===`string`?e.sql:null;switch(e.type){case`table`:l.tables.add(e.name);l.tableSql.set(e.name,t);break;case`view`:l.views.add(e.name);break;case`index`:l.indexes.add(e.name);if(typeof e.tbl_name===`string`)l.indexDefinitions.set(e.name,{table:e.tbl_name,sql:t});break;case`trigger`:if(typeof e.tbl_name===`string`)l.triggers.set(e.name,{table:e.tbl_name,sql:t})}}return l});if(r===void 0&&(i.tables.size>0||i.views.size>0))publishSqliteDatabaseAdmission(e,textEncodingAdmission,i.textEncoding);return i}function captureTrackedSqliteSchemaFacts(e,t,n){t.capturing=true;try{return captureSqliteSchemaFacts(e,t.revision,n)}finally{t.capturing=false}}function invalidateTrackedSqliteSchemaFacts(e){e.revision+=1;e.facts=void 0}
//!src/infra/sqlite-schema-lifetime.ts
function observeSchemaLifetime(e,t,n){if(t.snapshot&&t.snapshot!==n){if(!e.isTransaction||!t.transactionCatalogBound)invalidateTrackedSqliteSchemaFacts(t);t.snapshot=void 0;t.qualifiedSnapshot=void 0}const r=getSqliteDatabaseSchemaRevision(e);const i=t.processRevision!==void 0&&t.processRevision!==r;if(i&&!t.transactionalSchema&&(e.isTransaction&&t.transactionCatalogBound||t.facts&&n&&t.qualifiedSnapshot===n)){t.transactionalFacts||=e.isTransaction;t.snapshot=n;return false}t.processRevision=r;if(i)invalidateTrackedSqliteSchemaFacts(t);if((t.transactionalSchema||t.transactionalTempSchema||t.transactionalFacts)&&!e.isTransaction){if(t.transactionalSchema)publishSqliteDatabaseSchemaChange(e);invalidateTrackedSqliteSchemaFacts(t);t.transactionalSchema=false;t.transactionalTempSchema=false;t.transactionalFacts=false}return i}
//!src/infra/sqlite-temp-generation-schema.ts
function prepareSqliteTempTrackingSchema(e,t){const{createSql:n,objects:r}=prepareTranscriptIndexSchema(t);const i=new Map(r.map(e=>[e.name.toLowerCase(),e]));const a=r.map(e=>e.name);const o=r.filter(e=>e.type===`table`).map(e=>e.name);const s=[...a,...o];const c=executeWithCachedStatement(e,`SELECT type, name, tbl_name, sql FROM temp.sqlite_schema
WHERE name COLLATE NOCASE IN (${a.map(()=>`?`).join(`,`)})
OR (type = 'trigger' AND tbl_name COLLATE NOCASE IN (${o.map(()=>`?`).join(`,`)}))`,s,e=>e.all(...s));const l=c.some(e=>{const t=typeof e.name===`string`?i.get(e.name.toLowerCase()):void 0;return!t||e.type!==t.type||e.tbl_name!==t.table||typeof e.sql!==`string`||normalizeSchemaSql(e.sql)!==normalizeSchemaSql(t.sql)});return{sql:n(new Set(c.flatMap(e=>e.type===`trigger`&&typeof e.name===`string`?[e.name.toLowerCase()]:[]))),unexpected:l}}function prepareTranscriptIndexSchema(e){const t=quoteSqliteIdentifier(e.statusTable);const n=quoteSqliteIdentifier(e.pendingTable);const r=quoteSqliteIdentifier(e.pendingIndex);const i=`${t} (
id INTEGER PRIMARY KEY CHECK (id = 1), sibling_write_revision INTEGER NOT NULL,
schema_version INTEGER NOT NULL, complete INTEGER NOT NULL, after_session TEXT,
completed_traversals INTEGER NOT NULL
) STRICT`;const a=`${n} (session_id TEXT PRIMARY KEY, state INTEGER NOT NULL) STRICT`;const o=`${r} ON ${n}(state, session_id)`;const s=e.observedTables.flatMap(e=>[`INSERT`,`UPDATE`,`DELETE`].map(t=>{const r=`openclaw_${e}_projection_${t.toLowerCase()}`;const i=t===`UPDATE`?[`OLD`,`NEW`]:[t===`DELETE`?`OLD`:`NEW`];return{name:r,table:e,definition:`TRIGGER ${quoteSqliteIdentifier(r)} AFTER ${t} ON main.${quoteSqliteIdentifier(e)}
WHEN ${i.map(e=>`NOT EXISTS (
SELECT 1 FROM ${n}
WHERE session_id = ${e}.session_id AND state = 0
)`).join(` OR `)} BEGIN
${i.map(e=>`
UPDATE ${n} SET state = 0 WHERE session_id = ${e}.session_id;
INSERT INTO ${n}
SELECT ${e}.session_id, 0 WHERE NOT EXISTS (
SELECT 1 FROM ${n} WHERE session_id = ${e}.session_id
);`).join(`
`)}
END`}}));const createSql=e=>`
CREATE TEMP TABLE IF NOT EXISTS ${i};
INSERT INTO temp.${t} VALUES (1, -1, -1, 0, NULL, 0)
ON CONFLICT(id) DO UPDATE SET sibling_write_revision = -1;
CREATE TEMP TABLE IF NOT EXISTS ${a};
CREATE INDEX IF NOT EXISTS temp.${o};
${s.map(({name:t,definition:n})=>{return`${e.has(t.toLowerCase())?`DROP TRIGGER IF EXISTS temp.${quoteSqliteIdentifier(t)};`:``}CREATE TEMP ${n};`}).join(`
`)}
`;return{createSql,objects:[{name:e.statusTable,type:`table`,table:e.statusTable,sql:`CREATE TABLE ${i}`},{name:e.pendingTable,type:`table`,table:e.pendingTable,sql:`CREATE TABLE ${a}`},{name:e.pendingIndex,type:`index`,table:e.pendingTable,sql:`CREATE INDEX ${o}`},...s.map(e=>({name:e.name,type:`trigger`,table:e.table,sql:`CREATE ${e.definition}`}))]}}
//!src/infra/sqlite-schema-facts.ts
function beginPostgresReadSnapshotScope(e){const t=getPostgresPhysicalFacts(e);const n=readSqliteDatabaseWriteRevision(e);if(t&&n!==void 0)postgresReadSnapshots.set(e,{schema:t,writeRevision:n,mutationRevision:e.mutationRevision,snapshot:{}});return()=>postgresReadSnapshots.delete(e)}function invalidateSqliteSchemaFacts(e){getSqliteDatabaseSchemaRevision(e);invalidateSchemaFacts(e,true)}function invalidateSchemaFacts(e,t,n=`main`,r=n!==`temp`){const i=sqliteSchemaOwners.get(e);if(i){const a=n===`main`;i.isolatedTempTables.clear();if(e.isTransaction)i.transactionMutationRevision=void 0;if(a)invalidateLocalSqliteSchemaAdmissions(e);if(a&&e.isTransaction&&!i.transactionalSchema)i.transactionBaseFacts=i.facts;if(r)for(const e of i.mutationListeners??[])e(void 0);invalidateTrackedSqliteSchemaFacts(i);i.transactionalSchema||=a&&e.isTransaction;i.transactionalTempSchema||=n===`temp`&&e.isTransaction;i.pendingSchema||=a&&i.nativeDepth>0;if(t&&a&&!e.isTransaction&&i.nativeDepth===0)publishSqliteDatabaseSchemaChange(e)}}function registerSqliteSchemaMutationListener(e,t){const n=sqliteSchemaOwners.get(e);if(!n)throw new Error(`SQLite schema observation requires a tracked connection`);const r=n.mutationListeners??=/* @__PURE__ */ new Set;r.add(t);return()=>r.delete(t)}function trackSchemaChanges(e,t,n,r){const settle=(n=false,r=false)=>{if(r){const n=getSqlitePinnedReadSnapshot(e);const r=n&&(t.transactionalSchema?t.transactionBaseFacts:t.facts);discardSqliteDatabaseTransactionAdmissions(e);invalidateTrackedSqliteSchemaFacts(t);t.transactionalSchema=false;t.transactionalTempSchema=false;t.transactionalFacts=false;if(n&&t.admitted&&!t.authorizerActive){t.facts=r?{...r,revision:t.revision}:captureTrackedSqliteSchemaFacts(e,t);t.snapshot=n;t.qualifiedSnapshot=n}t.transactionBaseFacts=void 0;return}if((n||!e.isTransaction)&&(t.transactionalSchema||t.transactionalTempSchema||t.transactionalFacts)){if(t.transactionalSchema)publishSqliteDatabaseSchemaChange(e);invalidateTrackedSqliteSchemaFacts(t);t.transactionalSchema&&=e.isTransaction;t.transactionalTempSchema&&=e.isTransaction;t.transactionalFacts=false}};const i=observeSqliteNativeOperations(e,n,(n,i)=>{if(t.settling)return{finish:()=>{}};const{control:a,dataChange:o}=n;const s=a?.outerRollback===true?false:n.schemaChange;const c=n.mainSchemaChange&&a?.outerRollback!==true;observeSqliteTransactionState(e,t);const l=i===`bind`?void 0:getSqlitePinnedReadSnapshot(e);const u=i!==`bind`&&!l&&!t.capturing?{}:void 0;if(l&&l!==t.snapshot&&!t.capturing){if(e.isTransaction&&(t.transactionRead||t.transactionCatalogBound)&&t.processRevision!==getSqliteDatabaseSchemaRevision(e)){if(!t.transactionCatalogBound)invalidateTrackedSqliteSchemaFacts(t);t.transactionalFacts=true}else{observeSchemaLifetime(e,t,void 0);if(!t.facts&&!t.transactionalSchema){const n=getSqliteDatabaseAdmission(e,schemaAdmission);if(n)t.facts={...n,revision:t.revision}}}t.snapshot=l;t.qualifiedSnapshot=l}if(t.nativeDepth===0)settle();const d=e.isTransaction;if((r||t.processRevision===void 0)&&!d&&(a?.kind===`BEGIN`||a?.kind===`SAVEPOINT`)){const n=getSqliteDatabaseSchemaRevision(e);t.processRevision??=n}const f=!d&&a?.kind===`BEGIN`&&a.single?t.mutationRevision:void 0;if(!d&&a?.kind===`BEGIN`&&t.admitted)getAdmittedSqliteSchemaFacts(e);const p=Boolean(a)&&!canPreserveTransactionSnapshot(a,d);const m=a?.kind===`ROLLBACK`;const h=m&&t.transactionalSchema&&!a.outerRollback;const g=s&&!n.temporaryTableSchemaChange||m&&t.transactionalSchema;const _=c||h?`main`:m?t.transactionalTempSchema&&!t.transactionalSchema?`temp`:`rollback`:n.temporaryTableSchemaChange?`temp`:`local`;if(m)discardSqliteDatabaseTransactionAdmissions(e);if(s||m)invalidateSchemaFacts(e,false,_,g);if(o||n.temporaryTableSchemaChange||a?.kind===`ROLLBACK`)t.mutationRevision+=1;if(i!==`bind`&&d&&!a&&!t.transactionCatalogBound)t.transactionRead=true;const v=s||o||a!==void 0;const y=n.temporaryWriteTables?.every(e=>t.isolatedTempTables.has(e));if(o&&!y||c)beginSqliteDatabaseWrite(e,c||t.nativeDepth>0);if(v)t.mutationDepth+=1;t.nativeDepth+=1;const b=beginSqliteDatabaseAdmissionOperation(e);const x=t.schemaMutationRevision;if(c)t.schemaMutationRevision+=1;t.pendingSchema||=c;if(u)t.unmanagedSnapshots.add(u);return{stepped:()=>{if(l&&t.facts&&e.isTransaction)t.transactionCatalogBound=true},finish:(n,r,i)=>{if(u&&t.unmanagedSnapshots.delete(u)&&t.iteratorFacts){invalidateTrackedSqliteSchemaFacts(t);t.iteratorFacts=false}b();t.nativeDepth-=1;if(v)t.mutationDepth-=1;if(!e.isOpen)return;if(s||m){if(m)discardSqliteDatabaseTransactionAdmissions(e);invalidateSchemaFacts(e,false,_,g)}const o=n&&d&&a?.outerRollback===true&&!e.isTransaction&&!c&&t.schemaMutationRevision===x;if(o){settle(false,true);t.pendingSchema=false}if(t.nativeDepth===0){t.settling=true;try{const i=t.pendingSchema||t.transactionalSchema;if(!o&&t.pendingSchema&&!e.isTransaction&&!t.transactionalSchema)publishSqliteDatabaseSchemaChange(e);if(!o)settle(p);if(i&&!e.isTransaction&&!o){invalidateTrackedSqliteSchemaFacts(t);if(!n)discardSqliteDatabaseTransactionAdmissions(e);if(t.admitted&&!t.authorizerActive&&!r){getAdmittedSqliteSchemaFacts(e);t.transactionBaseFacts=void 0}}t.pendingSchema=false}finally{t.settling=false}}finishSqliteReadScope(e,t,d,p,n,f);if(t.mutationDepth===0&&!e.isTransaction)finishSqliteDatabaseWrite(e,i);t.transactionRead||=e.isTransaction&&Boolean(a&&!a.single)}}});observeSqliteNativeClose(e,()=>{finishSqliteDatabaseWrite(e);releaseSqliteDatabaseAdmission(e)});t.installTempTrackingSchema=r=>{const{sql:a,unexpected:o}=prepareSqliteTempTrackingSchema(e,r);try{i(()=>n.DatabaseSync.prototype.exec.call(e,a),{schemaChange:o,mainSchemaChange:o,temporaryTableSchemaChange:false,dataChange:true,temporaryWriteTables:[],control:void 0});if(!o)for(const e of[r.statusTable,r.pendingTable])t.isolatedTempTables.add(e.toLowerCase())}catch(t){invalidateSqliteSchemaFacts(e);throw t}};if(typeof e.setAuthorizer===`function`)e.setAuthorizer=r=>{n.DatabaseSync.prototype.setAuthorizer.call(e,r);t.authorizerActive=r!==null;suspendSqliteDatabaseAdmission(e,t.authorizerActive);invalidateTrackedSqliteSchemaFacts(t)};registerNodeSqliteDisposeCallback(e,()=>{invalidateTrackedSqliteSchemaFacts(t);t.readRevision=void 0;t.transactionSnapshot=void 0})}function readSqliteNativeMutationRevision(e){return isPostgresSqlConnection(e)?e.mutationRevision:sqliteSchemaOwners.get(e)?.mutationRevision}function runSqliteReadOperationSync(e,t){if(isPostgresSqlConnection(e))return t();const n=sqliteSchemaOwners.get(e);if(!n||n.authorizerActive)return t();n.readDepth+=1;try{if(n.admitted)getAdmittedSqliteSchemaFacts(e);return t()}finally{n.readDepth-=1}}function trackSqliteSchema(e,t,n=true){if(!sqliteSchemaOwners.has(e)){const r={admitted:false,publicationReady:false,revision:0,readDepth:0,mutationRevision:0,mutationDepth:0,transactionOpen:e.isOpen&&e.isTransaction,transactionRead:false,transactionCatalogBound:false,nativeDepth:0,pendingSchema:false,schemaMutationRevision:0,settling:false,capturing:false,transactionalSchema:false,transactionalTempSchema:false,transactionalFacts:false,authorizerActive:false,unmanagedSnapshots:/* @__PURE__ */ new Set,isolatedTempTables:/* @__PURE__ */ new Set,iteratorFacts:false};sqliteSchemaOwners.set(e,r);trackSchemaChanges(e,r,t,n);const i=getSqliteDatabaseSchemaRevision(e,{existingOnly:true});const a=getSqliteDatabaseAdmission(e,schemaAdmission,{existingOnly:true});if(a){r.admitted=true;r.facts={...a,revision:r.revision};r.processRevision=i}}}function isSqliteSchemaAdmissionCold(e){const t=sqliteSchemaOwners.get(e);return Boolean(t&&!t.admitted&&!t.authorizerActive)}function admitSqliteSchema(e,t){const n=sqliteSchemaOwners.get(e);if(!n)throw new Error(`SQLite schema admission requires a connection tracked from native open`);n.admitted=true;const r=getAdmittedSqliteSchemaFacts(e,t);if(!n.publicationReady&&r&&n.unmanagedSnapshots.size===0&&!getSqlitePinnedReadSnapshot(e))n.publicationReady=settleSqliteDatabaseAdmissionPublication(e)}function getAdmittedSqliteSchemaFacts(e,t){if(isPostgresSqlConnection(e))return;const n=sqliteSchemaOwners.get(e);if(!n?.admitted||n.authorizerActive)return;const r=getSqlitePinnedReadSnapshot(e);const i=e.isTransaction&&(n.transactionRead||n.transactionCatalogBound)&&n.processRevision!==getSqliteDatabaseSchemaRevision(e)||n.unmanagedSnapshots.size>0;const a=observeSchemaLifetime(e,n,r);if(!n.facts){n.snapshot=r;n.transactionalFacts||=e.isTransaction&&(n.readDepth===0||a);const o=i||Boolean(r)||n.transactionalSchema;const s=n.transactionalSchema||o?void 0:getSqliteDatabaseAdmission(e,schemaAdmission);if(s){t?.(s.userVersion);n.facts={...s,revision:n.revision};return n.facts}const c=getSqliteDatabaseSchemaRevision(e);n.facts=captureTrackedSqliteSchemaFacts(e,n,t);n.iteratorFacts||=n.unmanagedSnapshots.size>0;n.qualifiedSnapshot=r;n.transactionCatalogBound||=e.isTransaction;if(!o)publishSqliteDatabaseAdmission(e,schemaAdmission,n.facts,{schemaRevision:c})}else t?.(n.facts.userVersion);return n.facts}
//!src/infra/node-sqlite.ts
let bunSqliteNativeCleanupPending=false;function resolveSqliteFilesystemPath(e){if(process.platform!==`win32`)return e;return path.toNamespacedPath(path.resolve(e))}function resolveNodeSqliteLocation(e){if(e===``||e===`:memory:`||e.startsWith(`file:`))return e;return resolveSqliteFilesystemPath(e)}function resolveSqliteFileUriPath(e,t){if(t===`win32`){const t=path.win32.toNamespacedPath(path.win32.resolve(e));return`file:${encodeURIComponent(t)}`}return pathToFileURL(path.resolve(e)).href}function resolveReadOnlyShmSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=ro&readonly_shm=1`}function resolveExistingSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=rw`}function resolveImmutableSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=ro&immutable=1`}function openNodeSqliteDatabase(e,t,n){const r=requireNodeSqlite();const i=resolveNodeSqliteLocation(e);const a=t?.open===false?void 0:prepareSqliteDatabaseAdmission(i,{create:t?.readOnly!==true});if(t?.open!==false&&n!==void 0&&a!==n)throw new Error(`SQLite staging database changed before native open`);const o=new r.DatabaseSync(i,t??{});if(o.isOpen)try{bindSqliteDatabaseAdmission(o,a)}catch(e){o.close();throw e}o.open=()=>{const e=prepareSqliteDatabaseAdmission(i,{create:t?.readOnly!==true});if(n!==void 0&&e!==n)throw new Error(`SQLite staging database changed before native open`);r.DatabaseSync.prototype.open.call(o);try{bindSqliteDatabaseAdmission(o,e)}catch(e){o.close();throw e}};trackSqliteSchema(o,{DatabaseSync:r.DatabaseSync,StatementSync:r.StatementSync},t?.readOnly!==true);if(o.isOpen&&t?.timeout!==void 0)rememberSqliteBusyTimeout(o,Math.max(0,t.timeout));if(!getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources)registerNodeSqliteDisposeCallback(o,()=>{bunSqliteNativeCleanupPending=true});registerSqliteReaderConnection(o);return o}
//!src/infra/private-directory-creation.ts
const refusedCreations=/* @__PURE__ */ new WeakSet;function markPrivateDirectoryCreationRefused(e){if(e!==null&&typeof e===`object`)refusedCreations.add(e);return e}function isPrivateDirectoryCreationRefused(e){return e!==null&&typeof e===`object`&&refusedCreations.has(e)}
//!src/infra/sqlite-snapshot-capacity-error.ts
const SQLITE_SNAPSHOT_CAPACITY_ERROR_NAME=`SqliteSnapshotCapacityError`;var SqliteSnapshotCapacityError=class extends Error{constructor(e,t){super(e,t);this.name=SQLITE_SNAPSHOT_CAPACITY_ERROR_NAME}};function hasSqliteSnapshotCapacityCode(e){const{code:t,errcode:n}=e;return t===`ENOSPC`||t===`EDQUOT`||n===13}
//!src/infra/sqlite-snapshot-file.ts
function assertExpectedContent(e,t,n){if(e.sizeBytes!==t.sizeBytes)throw new Error(`SQLite snapshot size mismatch for ${n}: expected ${t.sizeBytes}, got ${e.sizeBytes}`);if(e.sha256!==t.sha256)throw new Error(`SQLite snapshot hash mismatch for ${n}: expected ${t.sha256}, got ${e.sha256}`)}function assertOpenFileIdentitySync(e,t,n){const r=fs.fstatSync(e,{bigint:true});const i=fs.lstatSync(t,{bigint:true});if(!r.isFile()||!i.isFile()||!sameFileIdentity(n,r)||!sameFileIdentity(n,i))throw new Error(`SQLite snapshot file changed: ${t}`)}function hashPublishedFileSync(e,t,n=hashFileDescriptorSync){const r=fs.openSync(e,`r`);try{assertOpenFileIdentitySync(r,e,t);const i=fs.fstatSync(r,{bigint:true});const a=n(r);const o=fs.fstatSync(r,{bigint:true});if(!sameFileMutationFingerprint(i,o)){if(!sameFileStatFingerprint(i,o))throw new Error(`SQLite snapshot file changed while reading: ${e}`);assertExpectedContent(n(r),a,e)}assertOpenFileIdentitySync(r,e,t);return a}finally{fs.closeSync(r)}}function sameFileStatFingerprint(e,t){return sameFileIdentity(e,t)&&e.size===t.size}
//!src/infra/sqlite-staging-token.ts
const SQLITE_STAGING_TOKEN_FILES=[`owner.sqlite`,`owner.sqlite-journal`,`owner.sqlite-wal`,`owner.sqlite-shm`];var SqliteStagingRetiredError=class extends Error{constructor(){super(`SQLite snapshot parent retired; aborting snapshot allocation`)}};function acquireSqliteStagingToken(e,t,n={}){const r=withSqliteDatabaseAdmissionSettlement;const acquire=()=>acquireStagingToken(e,t,n);const i=t===`create`?acquire():r(acquire);const a=Object.assign(e=>r(()=>i(e)),{beginRetirement:()=>{r(()=>i.beginRetirement());return a}});return a}function acquireStagingToken(e,t,n){const r=path.join(e,SQLITE_STAGING_TOKEN_FILES[0]);const readIdentity=(e,t)=>{const n=fs.lstatSync(e,{bigint:true});if(!(t===`directory`?n.isDirectory():n.isFile())||process.platform===`win32`&&(n.dev===0n||n.ino===0n))throw new Error(`SQLite staging ownership is unknown`);return n};const i=readIdentity(e,`directory`);const a=SQLITE_STAGING_TOKEN_FILES.map(t=>fs.lstatSync(path.join(e,t),{throwIfNoEntry:false}));const o=a[0];if(a.some(e=>e&&(!e.isFile()||process.getuid&&e.uid!==process.getuid()))||!o&&t!==`create`&&!n.allowMissing)throw new Error(`SQLite snapshot token ownership is unknown`);if(t===`create`&&!o)fs.writeFileSync(r,``,{flag:`wx`,mode:420});const s=o!==void 0||t===`create`;const c=s?readIdentity(r,`file`):void 0;if(n.expectedIdentity){if(!c)throw new Error(`SQLite staging ownership is unknown`);assertDatabaseFileIdentity(c,n.expectedIdentity)}const l=withSqliteNativeOpen(()=>openNodeSqliteDatabase(s?resolveExistingSqliteFileUri(r):r,{timeout:0},c&&readSqliteDatabaseAdmissionIdentity(c)));let u;const read=e=>executeWithCachedStatement(l,e,[],e=>e.get());let d=t===`reclaim`||t===`create`&&n.exclusiveCreate===true;let f=false;const assertIdentity=()=>{const t=readIdentity(e,`directory`);if(i.dev!==t.dev||i.ino!==t.ino)throw new Error(`SQLite staging ownership changed before retirement`);const n=readIdentity(r,`file`);if(u.dev!==n.dev||u.ino!==n.ino)throw new Error(`SQLite staging ownership changed before retirement`)};const beginRetirement=()=>{assertIdentity();if(!l.isTransaction||!d){if(l.isTransaction)l.exec(`ROLLBACK`);l.exec(`BEGIN EXCLUSIVE`);d=true}return p};const release=(e=false)=>{if(!l.isOpen)return;if(e){beginRetirement();if(!f)l.exec(`PRAGMA user_version=1`);l.exec(`COMMIT`);f=true}else if(l.isTransaction)l.exec(`ROLLBACK`);l.close();if(e)retireSqliteDatabaseAdmissionForPath(r)};const p=Object.assign(release,{beginRetirement});try{u=c??readIdentity(r,`file`);if(d)l.exec(`BEGIN EXCLUSIVE`);else if(t===`create`)l.exec(`BEGIN IMMEDIATE`);else l.exec(`BEGIN`);if(t!==`create`||o){const e=read(`PRAGMA journal_mode`);if(!isRecord(e)||e.journal_mode!==`delete`)throw new Error(`SQLite snapshot token journal mode is unknown`);const n=read(`PRAGMA user_version`);const r=isRecord(n)?n.user_version:void 0;if(r!==0&&(t!==`reclaim`||r!==1))throw new SqliteStagingRetiredError;f=r===1}assertIdentity();return p}catch(e){release();throw e}}
//!src/infra/sqlite-snapshot-retirement.ts
const SQLITE_SNAPSHOT_PREFIX=`openclaw-sqlite-readonly-v2-`;const SCHEMA_DISCOVERY_OWNERSHIP_FILENAME=`schema-discovery-ownership.json`;const suffix=`(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$`;const SQLITE_SNAPSHOT_LEGACY_MARKER=new RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${suffix}`,`u`);const tokenMarker=new RegExp(`^${SQLITE_SNAPSHOT_PREFIX}${suffix}`,`u`);const fsSafeTemporaryPayload=/^\.fs-safe-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.tmp$/u;const SQLITE_SNAPSHOT_LEGACY_AGE_MS=864e5;function releaseTokens(e){const t=collectSynchronousErrors(e,e=>e());if(t.length)throw new AggregateError(t,`SQLite snapshot retirement token release failed`)}const isSqliteSnapshotStagingName=e=>SQLITE_SNAPSHOT_LEGACY_MARKER.test(e)||tokenMarker.test(e);function acquireSqliteSnapshotToken(e,t){return acquireSqliteStagingToken(e,t,{allowMissing:SQLITE_SNAPSHOT_LEGACY_MARKER.test(path.basename(e))})}function beginSqliteSnapshotRetirement(e,t={}){const n=[];const r=[];const release=()=>releaseTokens(n.filter(e=>e!==t.token));if(!fs.existsSync(e)){t.token?.();return{bytes:0,payload:r,release,retire:()=>{}}}function inspect(i,a,o=``,s=true){const c=fs.lstatSync(i);if(!c.isDirectory()||process.getuid&&c.uid!==process.getuid())throw new Error(`Snapshot directory ownership is unknown`);const l=!o&&SQLITE_SNAPSHOT_LEGACY_MARKER.test(path.basename(i));if(!o&&t.allowLegacy===false&&!tokenMarker.test(path.basename(i)))throw new Error(`Legacy or unrecognized snapshot requires offline operator cleanup`);const u=t.cutoff!==void 0&&l?Math.min(a,Date.now()-SQLITE_SNAPSHOT_LEGACY_AGE_MS):a;const d=l?`Legacy snapshot contains activity newer than 24 hours`:`Snapshot contains activity within the reclamation grace period`;if(c.mtimeMs>=u)throw new Error(d);if(l&&s&&t.cutoff!==void 0)inspect(i,u,o,false);if(!o&&s)n.push(i===e&&t.token?t.token.beginRetirement():acquireSqliteSnapshotToken(i,`reclaim`));let f=0;let p=c.mtimeMs;for(const e of fs.readdirSync(i,{withFileTypes:true})){const n=path.join(i,e.name);const a=fs.lstatSync(n);if(process.getuid&&a.uid!==process.getuid())throw new Error(`Snapshot file ownership is unknown`);if((!o||t.cutoff===void 0)&&a.isFile()&&SQLITE_STAGING_TOKEN_FILES.some(t=>t===e.name))continue;p=Math.max(p,a.mtimeMs);if(a.isDirectory()){const r=isSqliteSnapshotStagingName(e.name);const i=r?``:[o,e.name].filter(Boolean).join(`/`);if(t.cutoff!==void 0&&(!r&&![`openclaw`,`openclaw-state`,`openclaw-state/state`].includes(i)&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(i)||r&&o!==``&&o!==`openclaw`&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(o)))throw new Error(`Unrecognized snapshot directory`);const a=inspect(n,u,i,s);f+=a.bytes;p=Math.max(p,a.newest)}else if(t.cutoff===void 0||a.isFile()&&(o===`openclaw-state/state`?/^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(e.name):!o&&(/^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(e.name)||e.name===`schema-discovery-ownership.json`||fsSafeTemporaryPayload.test(e.name)||/^inspection-result-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.json$/u.test(e.name)))){f+=a.size;if(s)r.push(n)}else throw new Error(`Unrecognized snapshot artifact`)}if(p>=u)throw new Error(d);return{bytes:f,newest:p}}try{const{bytes:i}=inspect(e,t.cutoff??Number.POSITIVE_INFINITY);return{bytes:i,payload:r,release,retire:()=>{for(const e of n)e(true)}}}catch(e){release();throw e}}
//!src/infra/sqlite-readonly-location-cleanup.ts
function deferSqliteSnapshotCleanupAfterRead(e,t){const n=e instanceof SqliteSnapshotDirectoryBusyError?e:e instanceof SqliteSnapshotCleanupError?e.cause:void 0;if(!(n instanceof SqliteSnapshotDirectoryBusyError))return false;try{getChildLogger({subsystem:`infra/sqlite-snapshot`}).warn({path:t,errorCode:extractErrorCode(n.cause)},`SQLite snapshot cleanup deferred until open files are released.`)}catch{}return true}function settleSqliteSnapshotRequest(e){return e.result.catch(async t=>{let n=t;try{await e.startClose().result}catch(e){if(e!==t){const r=createSqliteLifecycleAggregateError([t,e],`SQLite snapshot allocation and cleanup failed`,t);n=t instanceof SqliteSnapshotCleanupError?new SqliteSnapshotCleanupError(t.message,{cause:r}):r}}recordSqliteSnapshotFailure(n);throw n})}const cleanupState=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotCleanup`),()=>({directories:/* @__PURE__ */ new Map,activeWork:/* @__PURE__ */ new Map,exitHandlerInstalled:false,pendingSignalCleanup:void 0,signalCleanup:cleanupSnapshotOperations}));const snapshotDirectories=cleanupState.directories;const activeSnapshotWork=cleanupState.activeWork;function snapshotDirectory(e){let t=snapshotDirectories.get(e);if(!t){t={readers:/* @__PURE__ */ new Set};snapshotDirectories.set(e,t)}return t}function completeSnapshotDirectoryRemoval(e){snapshotDirectories.delete(e);return true}function cleanupSnapshotOperations(){cleanupState.pendingSignalCleanup??=(async()=>{const e=snapshotDirectories.entries();while(true){while(activeSnapshotWork.size>0){for(const e of activeSnapshotWork.values())e();await Promise.allSettled(activeSnapshotWork.keys())}const t=e.next();if(t.done)break;const[n]=t.value;await removeTempDirectoryAsync(n,e=>emitSnapshotCleanupFailure({cleanupRoot:n,operation:`rm`,code:extractErrorCode(e)}))}})().finally(()=>{cleanupState.pendingSignalCleanup=void 0});return cleanupState.pendingSignalCleanup}function retainSnapshotWork(e,t=()=>{}){registerSnapshotCleanup();activeSnapshotWork.set(e,t);const release=()=>activeSnapshotWork.delete(e);e.then(release,release);return e}function registerSnapshotTempDirectory(e,t){const n=snapshotDirectory(e);n.release=t??n.release;registerSnapshotCleanup()}function registerSnapshotCleanup(){if(!cleanupState.exitHandlerInstalled){cleanupState.exitHandlerInstalled=true;registerProcessExitCleanup(()=>{for(const e of activeSnapshotWork.values())e();if(activeSnapshotWork.size===0)for(const e of snapshotDirectories.keys())removeTempDirectory(e)})}registerSignalExitFinalizer(cleanupState.signalCleanup)}function registerRetainedSnapshotTempDirectory(e,t){snapshotDirectory(e).releaseRetained=t;registerSnapshotCleanup()}function retainSnapshotTempDirectory(e){registerSnapshotTempDirectory(e);const t=snapshotDirectory(e);if(t.retirementStarted)throw new SqliteSnapshotCleanupError(`SQLite snapshot retirement has started`);const n=Symbol(`sqlite.snapshot.reader`);t.readers.add(n);return()=>t.readers.delete(n)}const tempDirectoryRemovalOptions={force:true,maxRetries:3,recursive:true,retryDelay:20};function emitSnapshotCleanupFailure(e,t){if(t)try{t(e);return}catch{}try{getChildLogger({subsystem:`infra/sqlite-snapshot`}).warn({path:e.cleanupRoot,operation:e.operation,errorCode:e.code},`SQLite read-only snapshot cleanup failed. Check directory permissions and available storage before retrying.`)}catch{}}function assertSnapshotReadersRetired(e){if(e?.readers.size)throw new SqliteSnapshotCleanupError(`SQLite snapshot still belongs to an active reader`)}function prepareSnapshotRetirement(e,t){assertSnapshotReadersRetired(t);if(t?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot requires asynchronous cleanup`);if(t?.retired||!t?.release&&!fs.existsSync(path.join(e,SQLITE_STAGING_TOKEN_FILES[0])))return;if(t)t.retirementStarted=true;return beginSqliteSnapshotRetirement(e,{token:t?.release})}function*shrinkSnapshotPayload(e){const t=fs.lstatSync(e,{throwIfNoEntry:false});if(t?.isDirectory())for(const t of fs.readdirSync(e))yield*shrinkSnapshotPayload(path.join(e,t));else if(t?.isFile()&&t.nlink>1)fs.unlinkSync(e);else if(t?.isFile()&&t.nlink===1&&t.size>64*1024**2){const n=fs.openSync(e,fs.constants.O_RDWR|fs.constants.O_NOFOLLOW);try{for(let e=t.size;e>64*1024**2;){e-=64*1024**2;yield{fd:n,size:e}}}finally{fs.closeSync(n)}}}async function shrinkSnapshotPayloadAsync(e){for(const{fd:t,size:n}of shrinkSnapshotPayload(e))await retainSnapshotWork(new Promise((e,r)=>{fs.ftruncate(t,n,t=>t?r(t):e())}))}function*retireSqliteSnapshotPayload(e){for(const t of e.payload){retireSqliteDatabaseAdmissionForPath(t);for(const{fd:e,size:n}of shrinkSnapshotPayload(t)){fs.ftruncateSync(e,n);yield}fs.rmSync(t,tempDirectoryRemovalOptions)}e.retire()}function removeTempDirectory(e,t){let n=snapshotDirectories.get(e);if(n)n.cleanupFailure=void 0;try{const t=prepareSnapshotRetirement(e,n);try{if(t){for(const e of retireSqliteSnapshotPayload(t));n=snapshotDirectory(e);n.release=void 0;n.retired=true}else if(!n?.retired)for(const{fd:t,size:n}of shrinkSnapshotPayload(e))fs.ftruncateSync(t,n);try{fs.rmSync(e,tempDirectoryRemovalOptions)}catch(t){throw classifyRetiredSqliteSnapshotRemovalError(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){registerSnapshotTempDirectory(e);snapshotDirectory(e).cleanupFailure=n;t?.(n);return false}}async function removeTempDirectoryAsync(e,t){let n=snapshotDirectories.get(e);if(n?.releaseRetained){const r=await startRemoveTempDirectory(e,t,n).result;if(r)snapshotDirectories.delete(e);return r}if(n)n.cleanupFailure=void 0;try{const t=prepareSnapshotRetirement(e,n);try{for(const e of t?.payload??[]){retireSqliteDatabaseAdmissionForPath(e);await shrinkSnapshotPayloadAsync(e);await retainSnapshotWork(fs.promises.rm(e,tempDirectoryRemovalOptions))}if(t){t.retire();n=snapshotDirectory(e);n.release=void 0;n.retired=true}else if(!n?.retired)await shrinkSnapshotPayloadAsync(e);try{await retainSnapshotWork(fs.promises.rm(e,tempDirectoryRemovalOptions))}catch(t){throw classifyRetiredSqliteSnapshotRemovalError(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){registerSnapshotTempDirectory(e);snapshotDirectory(e).cleanupFailure=n;t?.(n);return false}}function startRemoveTempDirectory(e,t,n=snapshotDirectories.get(e)){if(n?.retiringRetained)return n.retiringRetained;let r;const i=createRetainedOperation(()=>{if(!r||i.operation.read().status!==`pending`)return;r.service();const a=r.read();if(a.status===`pending`)return;if(n)n.retiringRetained=void 0;if(a.status===`rejected`){snapshotDirectory(e).cleanupFailure=a.error;t?.(a.error);i.resolve(false)}else i.resolve(completeSnapshotDirectoryRemoval(e))});try{if(n)n.cleanupFailure=void 0;sealRetainedSnapshotTempDirectory(e);if(!n?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot has no retained cleanup owner`);n.retiringRetained=i.operation;r=n.releaseRetained();r.result.then(()=>i.operation.service(),()=>i.operation.service());i.operation.service()}catch(r){snapshotDirectory(e).cleanupFailure=r;if(n)n.retiringRetained=void 0;t?.(r);i.resolve(false)}return i.operation}function sealRetainedSnapshotTempDirectory(e,t){const n=snapshotDirectories.get(e);if(!n?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot has no retained cleanup owner`);if(t?.requireRequested&&!n.retirementStarted)throw new SqliteSnapshotCleanupError(`SQLite snapshot is still owned; cleanup has not been requested`);const r=[...snapshotDirectories].filter(([t])=>isPathInside(e,t));for(const[,e]of r)assertSnapshotReadersRetired(e);for(const[,e]of r)e.retirementStarted=true;const i=/* @__PURE__ */ new Set([...captureSqliteDatabaseAdmissions().map(({location:e})=>e),...captureSqliteDatabaseDescriptorCustodyLocations()]);for(const t of i)if(isPathInside(e,t))retireSqliteDatabaseAdmissionForPath(t)}function preparationCleanupError(e,t){return createSqliteLifecycleAggregateError(e,`${t} and cleanup failed: ${coerceErrorMessage(e[0])}`,e[0])}function discardPreparedCopyPayload(e,t){try{for(const t of[`database.sqlite`,`database.sqlite.partial`])for(const n of[``,`-wal`,`-shm`,`-journal`]){const r=path.join(e,`${t}${n}`);retireSqliteDatabaseAdmissionForPath(r);for(const{fd:e,size:t}of shrinkSnapshotPayload(r))fs.ftruncateSync(e,t);fs.rmSync(r,{force:true})}}catch(e){throw preparationCleanupError([t,e],`SQLite snapshot preparation`)}}async function cleanupFailedSnapshotPreparation(e,t,n,r){if(r)discardPreparedCopyPayload(e,t);else{const r=[t];if(!await removeTempDirectoryAsync(e,e=>r.push(e)))throw preparationCleanupError(r,n)}throw t}function publishPreparedCopy(e,t){const n=path.join(e,`database.sqlite`);for(const t of[`-wal`,`-shm`,`-journal`,``]){const i=`${n}.partial${t}`;if(fs.existsSync(i)){const a=`${n}${t}`;try{fs.renameSync(i,a)}catch(t){try{var r=_usingCtx();if(!hasErrnoCode(t,`EXDEV`))throw t;const n=r.u(copyRootFileSync({source:{rootPath:e,absolutePath:i},destination:{rootPath:e,absolutePath:a},mode:384}));fs.fsyncSync(n.fd);for(const{fd:e,size:t}of shrinkSnapshotPayload(i))fs.ftruncateSync(e,t);fs.rmSync(i,{force:true})}catch(e){r.e=e}finally{r.d()}}}}let i;if(t){const e=fs.lstatSync(n,{bigint:true});assertExpectedContent(hashPublishedFileSync(n,e),t,n);i={...t,identity:e}}return{...adoptPreparedLocation(n,e),journalFreeContent:i}}function adoptPreparedLocation(e,t,n=false,r){const i=t??path.dirname(e);registerSnapshotTempDirectory(i);let a=true;let o;let s;let c=false;const reportFailure=e=>{if(!n&&!c){c=true;emitSnapshotCleanupFailure({cleanupRoot:i,operation:`rm`,code:extractErrorCode(e)},r)}};const complete=e=>{if(e){a=false;snapshotDirectories.delete(i)}else if(n)throw new SqliteSnapshotCleanupError(`SQLite read-only worker snapshot cleanup failed: ${i}`,{cause:snapshotDirectories.get(i)?.cleanupFailure});return e};const startCleanup=()=>{if(s?.read().status===`pending`)return s;if(!a){const e=createRetainedOperation(()=>{});e.resolve(complete(true));return s=e.operation}return s=mapRetainedOperation(startRemoveTempDirectory(i,reportFailure),complete)};return{location:e,cleanupRoot:i,cleanup:()=>{if(o||s?.read().status===`pending`)return n?complete(false):false;if(!a)return complete(true);return complete(removeTempDirectory(i,reportFailure))},cleanupAsync:()=>{if(snapshotDirectories.get(i)?.releaseRetained||s)return startCleanup().result;if(o)return o;if(!a)return Promise.resolve(complete(true));o=Promise.resolve().then(()=>removeTempDirectoryAsync(i,reportFailure)).then(complete).finally(()=>{o=void 0});return o},startCleanup}}
//!src/infra/sqlite-readonly-worker-context.ts
const readOnlyWorkerScope=new AsyncContext(Symbol(`sqliteReadOnlyWorkerScope`));function resolveSqliteInspectionSignal(e){const t=readOnlyWorkerScope.getStore();return t?e?AbortSignal.any([e,t.controller.signal]):t.controller.signal:e}var SqliteReadOnlyWorkerScopeClosedError=class extends Error{constructor(){super(`SQLite read-only worker scope closed`);this.code=`SQLITE_READONLY_WORKER_SCOPE_CLOSED`}};function createSqliteReadOnlyWorkerScope(e){const t={active:true,busy:false,controller:new AbortController,pending:/* @__PURE__ */ new Set,deadlineOwnedByCaller:e?.deadlineOwnedByCaller??false};const abort=()=>t.controller.abort(e?.signal.reason);e?.signal.addEventListener(`abort`,abort,{once:true});if(e?.signal.aborted)abort();let n;return{run(e){return runWithAsyncStore(readOnlyWorkerScope,t,e)},close(){n??=(async()=>{e?.signal.removeEventListener(`abort`,abort);t.active=false;t.controller.abort(new SqliteReadOnlyWorkerScopeClosedError);materializeErrorStack(t.controller.signal.reason);await Promise.allSettled(t.pending);const n=await Promise.allSettled([t.worker?.close(),t.releaseReadWorker?.()]);throwSettledAggregate(n,`SQLite read-only worker scope cleanup failed`)})();return n}}}
//!src/infra/exec-wrapper-tokens.ts
function normalizeExecutableToken(e){const t=path.win32.basename(e);const n=path.posix.basename(e);const r=t.length<n.length?t:n;return normalizeLowercaseStringOrEmpty(r).replace(/\.(?:exe|cmd|bat|com)$/,``)}
//!src/infra/shell-inline-command.ts
const POSIX_INLINE_COMMAND_FLAGS=/* @__PURE__ */ new Set([`-lc`,`-c`,`--command`,`--commands`,`--cmdline`]);const NUSHELL_INLINE_COMMAND_FLAGS=/* @__PURE__ */ new Set([...POSIX_INLINE_COMMAND_FLAGS,`-e`,`--execute`]);function expandPowerShellSwitchPrefixForms(e,t){const n=[];for(let r=t.length;r<=e.length;r+=1){const t=e.slice(0,r);n.push(`-${t}`,`--${t}`,`/${t}`)}return n}function expandPowerShellSwitchForms(e){return e.flatMap(e=>{const t=normalizeLowercaseStringOrEmpty(e);return[`-${t}`,`--${t}`,`/${t}`]})}const POWERSHELL_COMMAND_FLAGS=[...expandPowerShellSwitchPrefixForms(`command`,`c`),...expandPowerShellSwitchPrefixForms(`commandwithargs`,`cwa`),...expandPowerShellSwitchForms([`cwa`])];const POWERSHELL_FILE_FLAGS=expandPowerShellSwitchPrefixForms(`file`,`f`);const POWERSHELL_INLINE_FILE_FLAGS=new Set(POWERSHELL_FILE_FLAGS);const POWERSHELL_NO_PROFILE_FLAGS=new Set(expandPowerShellSwitchPrefixForms(`noprofile`,`nop`));const POWERSHELL_UNREVIEWED_STARTUP_FLAGS=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchForms([`ea`]),...expandPowerShellSwitchPrefixForms(`interactive`,`i`),...expandPowerShellSwitchPrefixForms(`login`,`l`),...expandPowerShellSwitchPrefixForms(`namedpipeservermode`,`nam`),...expandPowerShellSwitchPrefixForms(`noexit`,`noe`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchForms([`pscf`]),...expandPowerShellSwitchPrefixForms(`servermode`,`s`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`socketservermode`,`so`),...expandPowerShellSwitchPrefixForms(`sshservermode`,`ssh`),...expandPowerShellSwitchPrefixForms(`v2socketservermode`,`v2so`)]);const POWERSHELL_INLINE_ENCODED_COMMAND_FLAGS=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`encodedcommand`,`e`),...expandPowerShellSwitchPrefixForms(`ec`,`e`)]);const POWERSHELL_INLINE_COMMAND_FLAGS=/* @__PURE__ */ new Set([...POWERSHELL_COMMAND_FLAGS,...POWERSHELL_FILE_FLAGS,...POWERSHELL_INLINE_ENCODED_COMMAND_FLAGS]);const POWERSHELL_INLINE_REST_COMMAND_FLAGS=new Set(POWERSHELL_COMMAND_FLAGS);const POWERSHELL_OPTIONS_WITH_SEPARATE_VALUES=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchPrefixForms(`executionpolicy`,`ex`),...expandPowerShellSwitchPrefixForms(`inputformat`,`inp`),...expandPowerShellSwitchPrefixForms(`outputformat`,`o`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`token`,`to`),...expandPowerShellSwitchPrefixForms(`utctimestamp`,`utc`),...expandPowerShellSwitchPrefixForms(`version`,`v`),...expandPowerShellSwitchPrefixForms(`windowstyle`,`w`),...expandPowerShellSwitchPrefixForms(`workingdirectory`,`w`),...expandPowerShellSwitchForms([`ea`,`ep`,`if`,`of`,`pscf`,`wd`])]);const POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES=/* @__PURE__ */ new Set([`--init-file`,`--rcfile`]);function countSeparateValueOptionChars(e,t){let n=0;for(let r=1;r<e.length;r+=1){const i=e[r];if(i===`o`||i===`O`&&t!==`zsh`)n+=1}return n}function parseCombinedCommandFlag(e,t){if(e.length<2||e[0]!==`-`||e[1]===`-`)return null;const n=e.slice(1);const r=n.indexOf(`c`);if(r===-1||n.includes(`-`))return null;const i=n.slice(r+1);if(i&&!/^[A-Za-z]+$/.test(i))return{attachedCommand:i,separateValueCount:0};return{attachedCommand:null,separateValueCount:countSeparateValueOptionChars(e,t)}}function combinedSeparateValueOptionCount(e,t){if(e.length<2||e[0]!==`-`&&e[0]!==`+`||e[1]===`-`||e.slice(1).includes(`-`))return 0;return countSeparateValueOptionChars(e,t)}function advancePosixInlineOptionScan(e,t){const n=combinedSeparateValueOptionCount(e,t);if(n>0)return 1+n;if(POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES.has(e))return 2;return 1}function isPowerShellOptionToken(e){return e.startsWith(`-`)||/^\/[A-Za-z][A-Za-z0-9]*$/.test(e)}function resolveInlineCommandMatch(e,t,n={}){const r=normalizeExecutableToken(e[0]??``);for(let i=1;i<e.length;){const a=e[i]?.trim();if(!a){i+=1;continue}const o=normalizeLowercaseStringOrEmpty(a);if(o===`--`)break;const s=n.allowCombinedC?a:o;const c=t.has(s);const l=!c&&n.allowCombinedC?parseCombinedCommandFlag(a,r):null;if(c||l){if(l&&l.attachedCommand!==null)return{command:l.attachedCommand.trim()||null,valueTokenIndex:i};const t=i+1+(l?.separateValueCount??0);const r=!l&&t>=e.length?null:t;const a=c&&n.restValueFlags?.has(s)?e.slice(i+1).map(e=>e.trim()).join(` `).trim():e[t]?.trim();return{command:a?a:null,valueTokenIndex:r}}if(n.valueOptions?.has(o)){i+=2;continue}const u=n.isOptionToken?.(a)??(a.startsWith(`-`)||a.startsWith(`+`));if(n.stopAtFirstNonOption&&!u)break;if(n.allowCombinedC&&!a.startsWith(`-`)&&!a.startsWith(`+`))break;i+=n.allowCombinedC?advancePosixInlineOptionScan(a,r):1}return{command:null,valueTokenIndex:null}}function resolvePowerShellInlineCommandMatch(e){return resolveInlineCommandMatch(e,POWERSHELL_INLINE_COMMAND_FLAGS,{isOptionToken:isPowerShellOptionToken,restValueFlags:POWERSHELL_INLINE_REST_COMMAND_FLAGS,stopAtFirstNonOption:true,valueOptions:POWERSHELL_OPTIONS_WITH_SEPARATE_VALUES})}function isPowerShellInlineFileCommandFlag(e){return POWERSHELL_INLINE_FILE_FLAGS.has(normalizeLowercaseStringOrEmpty(e))}
//!src/process/linux-oom-score-spawn.ts
const OOM_SCORE_WRAP_SHELL=`/bin/sh`;const OOM_SCORE_WRAP_SCRIPT=`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`;const OOM_SCORE_RESTORE_EXEC_ENV_SCRIPT=['echo 1000 > /proc/self/oom_score_adj 2>/dev/null; if [ "${OC_INTERNAL_OOM_EXEC_BASH_ENV+x}" = x ]; then BASH_ENV="$OC_INTERNAL_OOM_EXEC_BASH_ENV"; export BASH_ENV; fi; unset OC_INTERNAL_OOM_EXEC_BASH_ENV','if [ "${OC_INTERNAL_OOM_EXEC_ENV+x}" = x ]; then ENV="$OC_INTERNAL_OOM_EXEC_ENV"; export ENV; fi; unset OC_INTERNAL_OOM_EXEC_ENV','if [ "${OC_INTERNAL_OOM_EXEC_CDPATH+x}" = x ]; then CDPATH="$OC_INTERNAL_OOM_EXEC_CDPATH"; export CDPATH; fi; unset OC_INTERNAL_OOM_EXEC_CDPATH','if [ "${OC_INTERNAL_OOM_EXEC_PS4+x}" = x ]; then PS4="$OC_INTERNAL_OOM_EXEC_PS4"; export PS4; fi; unset OC_INTERNAL_OOM_EXEC_PS4; exec "$0" "$@"'].join(`; `);function resolveOomScoreWrappedCommand(e,t){return e===`/bin/sh`&&t[0]===`-c`&&(t[1]===`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`||t[1]===OOM_SCORE_RESTORE_EXEC_ENV_SCRIPT)&&t[2]?t[2]:void 0}
//!src/process/spawn-diagnostics.ts
const spawnCounts=resolveGlobalSingleton(Symbol.for(`openclaw.childProcessSpawnCounts`),()=>({counts:/* @__PURE__ */ new Map,sampledAt:performance.now()}));const COMMAND_FAMILIES=/^(node|bun|git|ps|pgrep|lsof|sh|bash|zsh|cmd|powershell|pwsh|npm|pnpm|python|python3|uv|ssh|openclaw)$/;const gitOperation=resolveGlobalSingleton(Symbol.for(`openclaw.gitSpawnOperation`),()=>new AsyncLocalStorage);const childOperation=resolveGlobalSingleton(Symbol.for(`openclaw.childSpawnOperation`),()=>new AsyncLocalStorage);function unscopedProcessOperation(e,t,n){if(n[0]===`--version`||n[0]===`-v`&&(e===`node`||e===`bun`||t===`gh`))return`unscoped.version`;if(e===`powershell`||e===`pwsh`){const e=[t,...n];const{command:r,valueTokenIndex:i}=resolvePowerShellInlineCommandMatch(e);return r!==null&&i!==null&&!isPowerShellInlineFileCommandFlag(e[i-1]??``)?`unscoped.shell-command`:`unscoped.shell`}if(/^(sh|bash|zsh)$/.test(e))return resolveInlineCommandMatch([t,...n],POSIX_INLINE_COMMAND_FLAGS,{allowCombinedC:true}).command!==null?`unscoped.shell-command`:`unscoped.shell`;if(e===`cmd`)return n.some(e=>/^-[a-z]*c$/.test(e)||/^\/(?:c|k)$/i.test(e))?`unscoped.shell-command`:`unscoped.shell`;if(e===`node`||e===`bun`)return`unscoped.runtime`;if(e===`other`&&/^(gh|docker|podman|which|uname|sw_vers|sysctl|curl|tar)$/.test(t))return`unscoped.${t}`;return`unscoped.command`}function unscopedGitOperation(e){let t=0;while(t<e.length){const n=e[t];if([`-C`,`-c`,`--git-dir`,`--work-tree`,`--namespace`,`--config-env`].includes(n))t+=2;else if(/^--(?:git-dir|work-tree|namespace|config-env|attr-source)=/u.test(n))t++;else if([`--no-pager`,`--no-optional-locks`,`--no-lazy-fetch`,`--literal-pathspecs`,`--bare`].includes(n))t++;else break}const n=e[t]??``;return/^(config|rev-parse|status|diff|ls-files|rev-list|merge-base|cat-file|symbolic-ref|for-each-ref|show-ref|remote|log|show|hash-object|update-ref|worktree|branch|fetch|clone|init|checkout|read-tree|write-tree|commit-tree|pack-objects|index-pack|maintenance|multi-pack-index|gc|fast-import|add|commit|push|reset|clean|merge|tag|describe|switch|ls-tree|update-index|check-ref-format|diff-tree|diff-index|diff-files|sparse-checkout|checkout-index|check-attr|mktree|var|apply|fsck|ls-remote|rebase|reflog)$/u.test(n)?`unscoped.${n}`:n===`--version`||n===`version`?`unscoped.version`:`unscoped.other`}function prepareChildProcessSpawnRecorder(e,t=[],n){if(!areDiagnosticsEnabledForProcess())return;const r=resolveOomScoreWrappedCommand(e,t);const i=r?t.slice(3):t;const a=path.win32.basename(r??e).toLowerCase().replace(/\.(exe|cmd)$/,``);const o=COMMAND_FAMILIES.test(a)?a:`other`;const s=o===`git`?gitOperation.getStore()??childOperation.getStore()??unscopedGitOperation(i):n??childOperation.getStore()??unscopedProcessOperation(o,a,i);const c=`${o}:${s}`;return()=>{if(areDiagnosticsEnabledForProcess()){const e=spawnCounts.counts.get(c);spawnCounts.counts.set(c,{family:o,operation:s,count:(e?.count??0)+1})}}}function recordChildProcessSpawn(e,t,n,r=[]){const i=prepareChildProcessSpawnRecorder(e,r,n);if(i)t.once(`spawn`,i)}
//!src/state/openclaw-state-db.paths.ts
const stateSqlitePaths=new LruCache(64);function resolveDatabasePath(e={}){return e.path===void 0?resolveOpenClawStateSqlitePath(e.env??process.env):normalizeDatabasePath(path.resolve(e.path))}function existingPathOrUndefined(e){try{statSync(e);return e}catch(e){if(hasErrnoCode(e,`ENOENT`))return;throw e}}function resolveOpenClawStateSqliteDir(e=process.env){return path.dirname(resolveOpenClawStateSqlitePath(e))}function resolveOpenClawStateSqlitePath(e=process.env){const t=resolveStateDir(e);const n=stateSqlitePaths.peek(t);if(n!==void 0)return n;const r=normalizeDatabasePath(path.join(t,`state`,`openclaw.sqlite`));stateSqlitePaths.set(t,r);return r}function resolveOpenClawStateDirForDatabasePath(e){const t=path.dirname(path.resolve(e));return path.basename(t)===`state`?path.dirname(t):t}function resolveQuarantineStorePath(e){return path.join(resolveOpenClawStateSqliteDir(e),`openclaw-quarantine.sqlite`)}function resolveOpenClawAgentDatabaseStoredPath(e,t){const n=process.platform===`win32`;const r=resolveOpenClawStateDirForDatabasePath(e);let i=n?normalizeWindowsPathPreservingCase(r):r;const a=n&&path.isAbsolute(t)?t:path.resolve(t);const o=n?normalizeWindowsPathPreservingCase(a):a;if(!path.isAbsolute(i)||!path.isAbsolute(o))return a;let s=path.relative(i,o);const c=s.startsWith(`..`)||path.isAbsolute(s)||n&&!isPathInside(r,a);if(c){const e=resolveIdentityPathViaExistingAncestorSync(i);if(n&&!isPathInside(e,a))return a;i=n?normalizeWindowsPathPreservingCase(e):e;if(!path.isAbsolute(i))return a;s=path.relative(i,o)}if(s.startsWith(`..`)||path.isAbsolute(s))return a;if(c&&!n)return s;const l=[i,path.toNamespacedPath(i)].map(e=>`${e}${e.endsWith(path.sep)?``:path.sep}`).find(e=>t.startsWith(e));return path.isAbsolute(t)&&l!==void 0?t.slice(l.length):s}function resolveOpenClawRegisteredAgentDatabasePath(e,t){return path.isAbsolute(t)?t:`${resolveOpenClawStateDirForDatabasePath(e)}${path.sep}${t}`}function describeAgentPathMigration(e){const{relativized:t,reanchored:n,deleted:r}=e;if(t===0&&n.length===0&&r.length===0)return[];const i=n.length+r.length;const a=[`${t} relativized`,n.length>0&&`${n.length} re-anchored`,r.length>0&&`${r.length} removed`].filter(Boolean);return[`Migrated agent database registry paths to state-relative storage${i>0?` (${a.join(`, `)})`:``}`,...n.map(e=>`Re-anchored agent database registry path ${e} to the current state directory`),...r.map(e=>`Removed duplicate agent database registry path ${e}`)]}function warnAgentPathMigration(e,t,n){if(t.reanchored.length===0&&t.deleted.length===0)return;e.warn(`agent database registry rows re-anchored or removed during v9 migration`,{reanchored:t.reanchored,deleted:t.deleted,path:n})}
//!src/state/openclaw-state-db-async-lifecycle.ts
const STATE_DATABASE_READ_ADMISSION_INVALIDATED=`STATE_DATABASE_READ_ADMISSION_INVALIDATED`;var StateDatabaseReadAdmissionInvalidatedError=class extends Error{constructor(...e){super(...e);this.code=STATE_DATABASE_READ_ADMISSION_INVALIDATED}};function isStateDatabaseReadAdmissionInvalidatedError(e){return extractErrorCode(e)===STATE_DATABASE_READ_ADMISSION_INVALIDATED}function createOpenClawStateDatabaseAsyncLifecycle(){const e=/* @__PURE__ */ new Set;const t=/* @__PURE__ */ new Map;const n=/* @__PURE__ */ new Map;const r=/* @__PURE__ */ new Set;const i=/* @__PURE__ */ new Map;let a=Promise.resolve();const proofFor=()=>{const e=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);new BigInt64Array(e)[0]=-1n;return e};const generationFor=e=>{const t=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return{integrity:{identity:e,lifetime:{revision:new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT),epoch:0n},revision:t,epoch:0n,proof:proofFor()}}};const publishCreatedIdentity=(e,n)=>{Atomics.add(new BigInt64Array(e.generation.integrity.revision),0,1n);Atomics.add(new BigInt64Array(e.generation.integrity.lifetime.revision),0,1n);t.delete(e.identity.key);e.identity=n;e.generation.integrity.identity=n;t.set(n.key,e)};const known=e=>n.get(e)??n.get(resolveDatabasePath({path:e}));const bindPath=(e,t)=>{e.paths.add(t);if(!n.has(t))n.set(t,e)};const overlaps=(e,t)=>{if(e.identity.key===t.identity.key)return true;for(const n of e.paths)if(t.paths.has(n))return true;return false};const isSealed=e=>{if(r.size===0)return false;for(const t of r)if(t.record===void 0||overlaps(t.record,e))return true;return false};const hasCloseCustody=e=>isSealed(e)||i.has(e);const assertOpen=e=>{if(isSealed(e))throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission is closed`)};const findPhysicalRecord=e=>{const r=t.get(e.key);if(!r||!e.key.startsWith(`file:`)||hasCloseCustody(r))return r;for(const t of findChangedDatabasePaths(r.paths,e)){r.admissions.delete(t);r.paths.delete(t);if(n.get(t)===r)n.delete(t)}if(r.paths.size>0){if(!r.paths.has(r.identity.canonicalPath)){r.identity=e;r.generation.integrity.identity=e}return r}invalidate(r);forget(r)};const resolve=(e,r)=>{const i=n.get(e);if(i&&(!r||i.identity.key===r.key))return!r&&i.identity.key.startsWith(`path:`)?resolve(e,readDatabasePathIdentitySync(e)):i;const a=r??readDatabasePathIdentitySync(e);let o=findPhysicalRecord(a);if(!o&&a.key.startsWith(`file:`)){o=[...t.values()].find(e=>{if(!e.identity.key.startsWith(`path:`))return false;try{return readDatabasePathIdentitySync(e.identity.canonicalPath).key===a.key}catch{return false}});if(o)publishCreatedIdentity(o,a)}if(!o){o={coordinationKey:a.key,identity:a,paths:/* @__PURE__ */ new Set,generation:generationFor(a),admissions:/* @__PURE__ */ new Map};t.set(a.key,o)}bindPath(o,e);bindPath(o,a.canonicalPath);return o};const resolveForNative=e=>{const t=resolveDatabasePath({path:e});const r=n.get(t);if(r)return r;const i=inspectDatabasePathIdentitySync(t);return i?resolve(t,i):void 0};const invalidate=e=>{for(const n of e?[e]:t.values()){Atomics.store(new BigInt64Array(n.generation.integrity.revision),0,-1n);Atomics.store(new BigInt64Array(n.generation.integrity.lifetime.revision),0,-1n);n.generation=generationFor(n.identity);n.admissions.clear()}};const seal=e=>{invalidate(e);const t={record:e};r.add(t);return t};const release=e=>{if(e.seal){r.delete(e.seal);e.seal=void 0}};const forget=e=>{if(!hasCloseCustody(e)&&t.get(e.identity.key)===e){t.delete(e.identity.key);for(const r of e.paths)if(n.get(r)===e){n.delete(r);for(const e of t.values())if(e.paths.has(r)){n.set(r,e);break}}}};const retireReplacedRecord=e=>{const t=i.get(e);if(t){t.superseded=true;t.seal??=seal(e)}else invalidate(e);forget(e)};const captureRecord=(e,n)=>{const r=e.admissions.get(n);if(r)return r;const i=e.generation;const a=Object.freeze({databasePath:n,coordinationKey:e.coordinationKey,get identity(){return e.identity},captureIntegrity(){a.assertCurrent();const t=i.integrity;const n=Atomics.load(new BigInt64Array(t.revision),0);const r=Atomics.load(new BigInt64Array(t.lifetime.revision),0);if(n!==t.epoch||r!==t.lifetime.epoch)i.integrity={...t,identity:e.identity,lifetime:{revision:t.lifetime.revision,epoch:r},epoch:n,proof:proofFor()};return i.integrity},assertCurrent(){assertOpen(e);if(t.get(e.identity.key)!==e||e.generation!==i||e.admissions.get(n)!==a)throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission changed`)}});e.admissions.set(n,a);return a};return{identity(e){return known(e)?.identity??inspectDatabasePathIdentitySync(e)},knownIdentity(e){return known(e)?.identity},integrity(e){const t=resolveForNative(e);return t&&!isSealed(t)?captureRecord(t,resolveDatabasePath({path:e})).captureIntegrity?.():void 0},publish(e,r){const i=resolveDatabasePath({path:e});const a=r??readDatabasePathIdentitySync(i);const o=n.get(i);let s=r&&o?.identity.key===a.key?t.get(a.key):findPhysicalRecord(a);if(o&&o.identity.key!==a.key){if(o.identity.key.startsWith(`path:`)&&!s){publishCreatedIdentity(o,a);s=o}else retireReplacedRecord(o)}if(!s)s=resolve(i,a);bindPath(s,i);bindPath(s,r?s.identity.canonicalPath:a.canonicalPath);return{identity:a,admission:captureRecord(s,i)}},async retireChangedAdmission(e){e.assertCurrent();const n=t.get(e.identity.key);const r=await readDatabasePathIdentity(e.databasePath);e.assertCurrent();if(n&&n.identity.key!==r.key)retireReplacedRecord(n)},invalidate(e){if(e===void 0)invalidate();else{const t=known(e);if(t)invalidate(t)}},register(t){e.add(t);for(const e of i.values())e.queue?.add(t);return()=>{e.delete(t)}},capture(e,t){const r=n.get(e);const i=r?.admissions.get(e);if(r&&i&&r.identity.key.startsWith(`file:`)){i.assertCurrent();return i}const a=resolveDatabasePath({path:e});const o=resolve(a,t);assertOpen(o);return captureRecord(o,a)},holdExclusion(e){const n=resolve(resolveDatabasePath({path:e}));const i=seal(n);return()=>{r.delete(i);for(const e of t.values())if(overlaps(n,e))forget(e)}},close(n,r){const o=n===void 0?void 0:resolveForNative(n);if(n!==void 0&&!o)return Promise.resolve(r());let s=i.get(o);if(s?.pending)return s.pending;if(!s){s={retained:/* @__PURE__ */ new Set};i.set(o,s)}s.seal??=seal(o);const c=s;const l=a.then(async()=>{const n=/* @__PURE__ */ new Set([...e,...c.retained]);for(const e of i.values())for(const t of e.retained)n.add(t);c.queue=n;const a=[];while(c.queue.size){const e=[...c.queue].filter(e=>e.phase!==`after-resources`);if(!e.length&&a.length){for(const e of c.queue)c.retained.add(e);break}const t=e.length?e:[...c.queue];for(const e of t)c.queue.delete(e);await Promise.all(t.map(async e=>{try{const t=o?.identity;if(!t||!e.admission||t.key===e.admission.identity.key)await e.close(t);c.retained.delete(e)}catch(t){c.retained.add(e);a.push(t)}}))}if(a.length&&!c.superseded)release(c);throwSqliteLifecycleErrors(a,`OpenClaw state resource drainage failed`);const s=await r(o?.identity);i.delete(o);release(c);if(o===void 0){for(const[e,t]of i)if(!t.pending){i.delete(e);release(t)}for(const e of t.values())forget(e)}else forget(o);return s}).finally(()=>{c.queue=void 0});c.pending=l;a=l.then(()=>void 0,()=>void 0);l.catch(()=>{c.pending=void 0});return l}}}export{captureSqliteSchemaFacts as $,sealRetainedSnapshotTempDirectory as A,enableNodeSqliteKyselyStatementCache as At,openNodeSqliteDatabase as B,publishPreparedCopy as C,runWithSqliteBusyTimeout as Ct,removeTempDirectoryAsync as D,clearNodeSqliteKyselyCacheForDatabase as Dt,removeTempDirectory as E,assertNodeSqliteDisposalAllowed as Et,sameFileStatFingerprint as F,registerNodeSqliteDisposeCallback as Ft,admitSqliteSchema as G,resolveImmutableSqliteFileUri as H,SqliteSnapshotCapacityError as I,registerNodeSqliteDisposeGuard as It,invalidateSqliteSchemaFacts as J,beginPostgresReadSnapshotScope as K,hasSqliteSnapshotCapacityCode as L,registerNodeSqliteKyselyQueryErrorHandler as Lt,startRemoveTempDirectory as M,installStatementInvalidation as Mt,SQLITE_SNAPSHOT_PREFIX as N,kyselyByDatabase as Nt,retainSnapshotTempDirectory as O,disposeNodeSqliteDependents as Ot,acquireSqliteSnapshotToken as P,queryErrorHandlerByDatabase as Pt,runSqliteReadOperationSync as Q,isPrivateDirectoryCreationRefused as R,preparationCleanupError as S,readSqliteBusyTimeout as St,registerSnapshotTempDirectory as T,shouldReportSqliteLockFailure as Tt,resolveReadOnlyShmSqliteFileUri as U,resolveExistingSqliteFileUri as V,resolveSqliteFilesystemPath as W,readSqliteNativeMutationRevision as X,isSqliteSchemaAdmissionCold as Y,registerSqliteSchemaMutationListener as Z,resolveSqliteInspectionSignal as _,postgresSearchTextTriggerSql as _t,existingPathOrUndefined as a,getPostgresPhysicalFacts as at,deferSqliteSnapshotCleanupAfterRead as b,assertPostgresCatalog as bt,resolveOpenClawRegisteredAgentDatabasePath as c,getAdmittedPostgresSchema as ct,resolveQuarantineStorePath as d,postgresStoreNamespace as dt,readSqliteSchemaObjects as et,warnAgentPathMigration as f,readPostgresSchema as ft,readOnlyWorkerScope as g,admitPostgresSearch as gt,createSqliteReadOnlyWorkerScope as h,withPostgresSearchExtensions as ht,describeAgentPathMigration as i,admitPostgresPhysicalFacts as it,settleSqliteSnapshotRequest as j,executeWithCachedStatement as jt,retainSnapshotWork as k,disposeSqliteStatement as kt,resolveOpenClawStateDirForDatabasePath as l,postgresSchemaMetadataSql as lt,SqliteReadOnlyWorkerScopeClosedError as m,verifyPostgresSchema as mt,createOpenClawStateDatabaseAsyncLifecycle as n,getSqlitePinnedReadSnapshot as nt,resolveDatabasePath as o,requireNativeDatabaseFile as ot,recordChildProcessSpawn as p,verifyAndRecordPostgresSchema as pt,getAdmittedSqliteSchemaFacts as q,isStateDatabaseReadAdmissionInvalidatedError as r,runSqliteSchemaReadSnapshotSync as rt,resolveOpenClawAgentDatabaseStoredPath as s,admitPostgresCapabilities as st,StateDatabaseReadAdmissionInvalidatedError as t,schemaAdmission as tt,resolveOpenClawStateSqlitePath as u,postgresSchemaSql as ut,adoptPreparedLocation as v,postgresSearchVectorSql as vt,registerRetainedSnapshotTempDirectory as w,setSqliteBusyTimeout as wt,discardPreparedCopyPayload as x,normalizeSqliteNonNegativeInteger as xt,cleanupFailedSnapshotPreparation as y,postgresVectorDecoderSql as yt,markPrivateDirectoryCreationRefused as z};