openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
462 lines • 164 kB
JavaScript
import{C as isRecord,S as asOptionalRecord,c as ignoreMissingPath,i as resolveGlobalSingleton,s as hasErrnoCode,v as normalizeOptionalString,w as isStringArray}from"./global-singleton-CTnqrmaI.js";import{a as syncDirectorySync,g as normalizeAgentId,i as requireDirectorySync,x as resolveIdentityPathViaExistingAncestorSync}from"./runtime-doctor-migrations-D8alsOFs.js";import{c as resolveStateDir,g as resolveUserPath,i as isPathInside,m as resolveRequiredHomeDir}from"./account-core-34NfXidI.js";import{G as truncateUtf16Safe,L as pruneMapToMaxSize,M as AsyncContext,S as isTruthyEnvValue,V as extractErrorCode,d as readConfigIncludeFileWithGuards,f as resolveConfigIncludeWritePath,g as parseJsonWithJson5Fallback,h as resolveConfigEnvVars,p as resolveConfigIncludes,t as createSubsystemLogger,u as hashConfigIncludeRaw,z as collectErrorGraphCandidates}from"./subsystem-ovCC_dQD.js";import{a as asSafeIntegerInRange,s as resolveNonNegativeIntegerOption,t as MAX_DATE_TIMESTAMP_MS$1}from"./number-coercion-BhEzZ9ku.js";import"./fs-safe-BnA-Wq_f.js";import{a as custom,c as literal,d as number,f as object,g as string,i as boolean,l as looseObject,m as record,r as array,t as _enum,u as never,v as union,y as unknown}from"./schemas-Bt_o0OU8.js";import{T as isArtifactPreservingStateRead,c as runSqliteReadOnlyWorkerSync}from"./sqlite-readonly-worker-6BW7upAM.js";import{$ as createSqliteWalReclamationResult,B as backfillCronRunLogEntryJson,Bt as withLegacyAgentIndexes,C as runStateSchemaMigrationTransaction,Ct as readStateSchemaContentVersion,Dt as ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS,E as resolveSchemaMigrationIntegrityTables,Et as CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS,F as StateSchemaMutationConflictError,Ft as withoutAgentToolUsage,G as coerceRequiredSqliteNumber,H as ensureOperatorApprovalResolutionRefs,I as withStateDatabaseSchemaMaintenance,J as migratePredicateColumnsV21,K as normalizeSqliteNumber,L as withStateDatabaseSchemaMaintenanceAsync,Lt as withLegacyAgentMemoryRevisionTriggers,M as assertOpenClawStateWriteAllowed,Mt as withoutTrajectoryPayloadColumns,Ot as createStateConfigMachineTable,P as isOpenClawStateWriteContentionError,Q as hasLegacyCronRunLogs,R as backfillAcpReplayEstimatedBytes,S as openClawStateMigrationAssertions,St as assertSupportedStateSchemaVersion,T as writeCurrentStateSchemaMetadata,Tt as CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS,U as repairLegacySubagentExecutionPayloads,V as backfillDeliveryQueueEntriesFromEntryJson,W as repairLegacySubagentRetainedResults,X as CLIENT_CREDENTIAL_SOURCE_TABLES,Y as CLIENT_CREDENTIAL_SCHEMA_SQL,Yt as SESSION_PARTICIPANTS_TABLE,Zt as withoutAgentCreationOperations,_ as assertOpenClawStateDatabaseForMaintenance,_t as repairLegacyGatewayRestartHandoffsForStrictMigration,a as withExistingOpenClawStateDatabaseReadOnly,an as withoutAgentActiveEventFacts,b as markCurrentStateSchemaVersion,bt as migrateSessionWatchCursorProvenance,c as prepareSqliteDatabaseDirectory,ct as readStateSchemaPublicationBlocker,d as assertExistingOpenClawStateRuntimeSchema,et as admitStatePostgres,f as assertStateDatabaseSchemaAdmission,fn as safeParseJson,ft as readRegisteredAgentDatabaseRows,g as assertMigratedStateTableIntegrity,gt as migrateWorkerPlacementExecutionModeSchema,h as isOpenClawStateSchemaFastPathEligible,ht as migrateAgentDatabaseRelativePaths,j as getOpenClawStateRuntimeSchema,kt as migrateSingletonStateFoldInV12,l as runManagedStateTransaction,lt as withPostgresSchemaAdmissionRetry,m as assertNoLegacyStateRuntimeRepair,mt as dropLegacyStateTables,nn as withoutAgentColdArchiveChunks,nt as ensureStatePostgresFragment,o as configureSqliteConnectionPragmas,ot as stateEngineSchema,p as assertCurrentStateRuntimeSchema,pn as safeParseJsonRecord,pt as assertCanonicalStateSchemaShape,q as migrateHistoricalStateImports,r as executeExistingOpenClawStateRead,rt as inspectStateSqlite,s as configureSqlitePreSchemaPragmas,st as advanceStateSchemaContentVersion,tt as assertStateFileSnapshotAllowed,u as readOnlyStateDatabase,ut as stateEngineInput,v as assertOpenClawStateDatabaseOwner,vt as logRetiredStateTableMigration,w as versionedStateMigrations,x as migrateBoundedStateSchema,xt as admitStateSchemaFacts,y as executeCanonicalStateSchema,yt as runRetiredStateTableMigrations,z as backfillCronJobsFromJobJson}from"./openclaw-agent-db-registry-listing-D7BjrkJC.js";import"./src-DtNToPzY.js";import{t as resolvePathViaExistingAncestorSync$1}from"./boundary-path-93ijeUSt.js";import{g as readAgentRosterProperty,l as resolveSessionStorePathCore,m as listAgentIds,o as observeOwnedDirectory,r as resolveEffectiveAgentDir,u as listSqliteTargetCandidatePathsForSessionStorePath}from"./agent-scope-config-DaUbqOtM.js";import"./agent-database-admission-CPNgo8tj.js";import{$ as getGatewayServiceInstallation,D as openTrackedStateDatabase,H as captureSqliteWorkerWalMaintenanceSuspension,I as ensureColumn,J as isExistingOpenClawStateSchema,M as migrateCronDefaultStoreIdentity,N as resolveCronIdentityMigrationDefaultStoreKey,R as tableExists,S as publishStateRuntimeSchemaAdmission,U as getSqliteWorkerExistingDatabaseIdentity,W as getSqliteWorkerStateIntegrityAdmission,Y as recordExistingOpenClawStateSchemaDatabase,_t as projectUpdateRehearsalDatabaseConfig,b as getStateRuntimeSchemaAdmission,bt as quarantineOrphanedSqliteSidecars,ct as assertSqliteIntegrity,dt as openSqliteReadOnlyDatabase,et as applyConfigEnvVars,g as assertStateDatabaseIntegrityOnce,i as captureOpenClawStateIntegrityAdmission,k as readTrackedStateDatabaseIdentity,l as recordOpenClawStateDatabaseOpenFailure,lt as assertSqliteTableIntegrity,mt as prepareSqliteReadOnlyLocationSync,o as openClawStateDatabaseCache,st as SqliteRepairableForeignKeyError,tt as cloneEnvWithPlatformSemantics,ut as isTerminalSqliteIntegrityError,w as readPublishedStateSchemaVersion,x as getStateSchemaVersionAdmission,xt as resolveSqliteDatabaseFilePaths,y as createStateSchemaAdmission,yt as SQLITE_SIDECAR_SUFFIXES,z as tableHasColumn}from"./openclaw-state-db-cache-BDxC5KuM.js";import{l as resolveIncludeRoots,n as openRootFileSync,o as resolveConfigPath}from"./boundary-file-read-D9ria5A8.js";import{o as resolveIncognitoOpenClawAgentSqlitePath,s as resolveOpenClawAgentSqlitePath}from"./openclaw-agent-db.paths-D0bfBkSQ.js";import"./runtime-worker-url-qeNVkG2b.js";import"./runtime-process-url-ZdotaiSy.js";import{i as getOpenClawDatabaseMaintenanceScope,s as observeOpenClawDatabaseMaintenanceResource}from"./openclaw-state-maintenance-context-2fT8FMwD.js";import{Ct as isSqliteCorruptionError,Fn as sqlPublicationAnchor,Kt as OPENCLAW_STATE_SCHEMA_SQL,Mn as resolveDatabasePathKey,Pn as isPostgresSqlConnection,Sn as assertDatabaseFileIdentity,U as publishSqliteDatabaseAdmission,Un as notifyListeners,Wn as registerListener,Xt as FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS,Zt as STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS,bt as stageSqliteTransactionState,g as captureSqliteReaderOwner,gt as hasSqlitePostCommitScope,kn as readDatabaseIdentityBirthtime,qt as OPENCLAW_AGENT_SCHEMA_SQL,un as createSqliteLifecycleAggregateError,vt as publishSqliteCommittedState,yt as stageSqliteCommittedPublication}from"./sqlite-worker-request-class-GkmU-e0P.js";import{n as getAsyncWorkSignal}from"./async-work-scope-C-A1TM9H.js";import{t as createConfigResolutionFacts}from"./resolution-facts-4OrA_JvN.js";import{n as hashFileDescriptorSync,t as flushAndHashFileSync}from"./file-descriptor-C8OEaEgp.js";import{At as enableNodeSqliteKyselyStatementCache,B as openNodeSqliteDatabase,Ct as runWithSqliteBusyTimeout,G as admitSqliteSchema,J as invalidateSqliteSchemaFacts,Q as runSqliteReadOperationSync,U as resolveReadOnlyShmSqliteFileUri,V as resolveExistingSqliteFileUri,_ as resolveSqliteInspectionSignal,c as resolveOpenClawRegisteredAgentDatabasePath,d as resolveQuarantineStorePath,f as warnAgentPathMigration,i as describeAgentPathMigration,l as resolveOpenClawStateDirForDatabasePath,o as resolveDatabasePath,ot as requireNativeDatabaseFile,q as getAdmittedSqliteSchemaFacts,rt as runSqliteSchemaReadSnapshotSync,u as resolveOpenClawStateSqlitePath,wt as setSqliteBusyTimeout}from"./openclaw-state-db-async-lifecycle-qylDsiRN.js";import{a as normalizeSchemaSql,c as quoteSqliteIdentifier,t as extractSqliteTableSchema}from"./sqlite-schema-sql-D2HdV_QG.js";import{t as formatErrorMessage}from"./errors-DKa3Vi4q.js";import{S as readGeneratedSqliteFingerprint,_ as runUpdateSqliteMigrationAsync,b as MEMORY_PATH_FTS_TRIGGER_DEFINITIONS,c as getCanonicalSqliteTableNames,d as openEngineStore,f as readEngineAnchor,g as runUpdateSqliteMigration,h as getUpdateDoctorMigrationSource,l as hasCanonicalSqliteSchemaFingerprint,m as getDoctorMigrationBackup,n as assertSqliteSchemaContains,o as getCanonicalSqliteNamedIndexContracts,p as beginUpdateSqliteCompanion,s as getCanonicalSqliteNamedIndexNames,v as MEMORY_CHUNK_FTS_TRIGGER_DEFINITIONS,x as readGeneratedSqliteCatalog,y as MEMORY_INDEX_SOURCES_TABLE}from"./sqlite-source-handle-BXW8n4TV.js";import{D as StateDatabaseOfflineMaintenanceError,T as StateDatabaseAdmissionPendingError,r as SQLITE_WORKER_MAX_MESSAGE_BYTES}from"./sqlite-worker-operation-settlement-BHzfCzIV.js";import{$ as createSqliteTableContractReader,A as executeSqliteQueryTakeFirstSync,E as withStateDatabaseColdAdmission,I as applyPrivateModeSync,b as assertStateDatabaseAccessAllowed,d as assertTransactionUsable,h as runSqliteReadSnapshotSync,j as getNodeSqliteKysely,k as executeSqliteQuerySync,m as runSqliteImmediateTransactionSync,p as runSqliteDeferredTransactionSync,r as isSqliteSchemaMismatchError,t as SqliteSchemaMismatchError,tt as createPrivateSqliteTempDirectorySync,u as withEngineStoreAdmission}from"./sqlite-schema-issues-BodSmpKH.js";import{d as isSqliteSchemaVersionError,f as readSqliteUserVersion,h as StartupMaintenanceRequiredError,m as writeSqliteUserVersion}from"./sqlite-snapshot-staging-owner-JEgCjxEj.js";import{s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS}from"./openclaw-state-db-contract-lz-66XzZ.js";import{n as readBackupEngine}from"./physical-store-7ZwlaWRd.js";import{t as listConfiguredSessionStoreAgentIds}from"./targets-configured-agents-NM3B56Py.js";import"./sqlite-worker-store-DLX_igHC.js";import{o as _usingCtx}from"./openclaw-process-census-eUZSajw_.js";import"./logger-file-worker-DsGWGQt0.js";import fsPromises,{rm,stat}from"node:fs/promises";import path from"node:path";import fs,{closeSync,constants,existsSync,fstatSync,lstatSync,mkdirSync,openSync,statSync}from"node:fs";import{isDeepStrictEqual}from"node:util";import{assertDirectoryIdentitySync,createDirectorySync,createFileSync}from"@openclaw/fs-safe/advanced";import{FsSafeError}from"@openclaw/fs-safe/errors";import crypto$1,{createHash,randomUUID}from"node:crypto";import os from"node:os";import{isMainThread}from"node:worker_threads";import{performance as performance$1}from"node:perf_hooks";import{serialize}from"node:v8";import{inspectDarwinAcl}from"@openclaw/fs-safe/permissions";import{expressionBuilder}from"kysely";import JSON5 from"json5";import{Value}from"typebox/value";import{Type}from"typebox";
//!packages/normalization-core/src/stable-stringify.ts
const preserveString=e=>e;function stableStringify(e,t=preserveString){return stringifyStableValue(e,/* @__PURE__ */ new WeakSet,t)}function stringifyStableValue(e,t,n,r){if(e===null||e===void 0)return String(e);if(typeof e===`number`&&!Number.isFinite(e))return JSON.stringify(String(e));if(typeof e===`bigint`)return JSON.stringify(e.toString());if(typeof e===`string`)return JSON.stringify(n(e));if(typeof e!==`object`)return JSON.stringify(e)??`null`;if(t.has(e))return JSON.stringify(`[Circular]`);t.add(e);try{if(e instanceof Date)return`Date(${Number.isNaN(e.getTime())?`null`:JSON.stringify(n(e.toISOString()))})`;if(e instanceof RegExp)return`RegExp(${JSON.stringify(n(e.toString()))})`;if(e instanceof Set||e instanceof Map){const r=Array.from(e,e=>stringifyStableValue(e,t,n)).toSorted(compareStableStrings);return`${e instanceof Set?`Set`:`Map`}([${r.join(`,`)}])`}if(e instanceof Error||e instanceof Uint8Array)return stringifyStableValue(e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{type:`Uint8Array`,data:encodeBase64(e)},t,n,r);if(Array.isArray(e)){if(r){r(`[`);let i=``;for(const a of e){r(i);r(stringifyStableValue(a,t,n,r));i=`,`}r(`]`);return``}return`[${Array.from(e,e=>stringifyStableValue(e,t,n)).join(`,`)}]`}const i=e;const a=Object.keys(i);const o=n===preserveString?a.sort():a.map(e=>({key:e,normalizedKey:n(e)})).sort((e,t)=>{return compareStableStrings(e.normalizedKey,t.normalizedKey)||compareStableStrings(e.key,t.key)});r?.(`{`);const s=n===preserveString?a:[];let c=``;let l=0;for(const e of o){const a=typeof e===`string`?e:e.key;const o=`${JSON.stringify(typeof e===`string`?e:e.normalizedKey)}:`;if(r){r(`${c}${o}`);r(stringifyStableValue(i[a],t,n,r));c=`,`}else s[l++]=`${o}${stringifyStableValue(i[a],t,n)}`}if(r){r(`}`);return``}return`{${s.join(`,`)}}`}finally{t.delete(e)}}function encodeBase64(e){let t=``;for(const n of e)t+=String.fromCharCode(n);return btoa(t)}function compareStableStrings(e,t){return e<t?-1:e>t?1:0}
//!src/templates/provenance-secondary-references.ts
const TEMPLATE_SECONDARY_REFERENCE_TABLES=[`template_package_refs`,`template_mcp_server_refs`,`template_cron_refs`];function readTemplateSecondaryReferenceTables(e,t){return TEMPLATE_SECONDARY_REFERENCE_TABLES.filter(n=>{if(!tableExists(e,n))return false;return Boolean(e.prepare(`SELECT 1 FROM ${n} WHERE agent_id = ? LIMIT 1`).get(t))})}
//!src/infra/sqlite-schema-ensure.ts
function createSqliteSchemaEnsurer(e,t){const present=e=>{const n=getAdmittedSqliteSchemaFacts(e);return n!==void 0&&t.tables.every(e=>n.tables.has(e))&&(t.indexes?.every(e=>n.indexes.has(e))??true)};return(t,n)=>{if(isPostgresSqlConnection(t))requireNativeDatabaseFile(`postgres`,`repair`);runSqliteReadOperationSync(t,()=>{if(present(t))return;const install=t=>t.exec(e());if(n)n(install);else if(t.isTransaction)install(t);else runSqliteImmediateTransactionSync(t,()=>install(t))})}}
//!src/state/openclaw-state-feature-schema.ts
const featureLocalSql={local_workspace_projections:[extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,`local_workspace_projections`),extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,`local_workspace_manifest_nodes`),extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,`local_workspace_tree_packs`),extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,`local_workspace_source_path_sets`)].join(`
`),user_profiles:`
CREATE TABLE IF NOT EXISTS user_profiles (
id TEXT NOT NULL PRIMARY KEY,
display_name TEXT,
primary_github_account_id INTEGER,
avatar BLOB,
avatar_mime TEXT,
avatar_sha256 TEXT,
merged_into TEXT,
role TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS user_profile_emails (
email TEXT NOT NULL PRIMARY KEY,
profile_id TEXT NOT NULL,
binding_id TEXT,
created_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_user_profile_emails_profile_id
ON user_profile_emails(profile_id);
${extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,`user_profile_identities`)}
`,operator_approval_standing_grants:`
CREATE TABLE IF NOT EXISTS operator_approval_standing_grants (
grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),
minted_by_approval_id TEXT NOT NULL
REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),
cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),
job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),
operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),
created_at_ms INTEGER NOT NULL,
expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),
revoked_at_ms INTEGER,
revoked_by TEXT,
last_used_at_ms INTEGER,
use_count INTEGER NOT NULL DEFAULT 0
) STRICT;
CREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding
ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);
CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
grant_id TEXT NOT NULL PRIMARY KEY
REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;
`,worker_environment_session_attachments:`
CREATE TABLE IF NOT EXISTS worker_environment_session_attachments (
session_id TEXT PRIMARY KEY,
session_key TEXT NOT NULL,
agent_id TEXT NOT NULL,
session_lifecycle_revision TEXT,
environment_id TEXT NOT NULL UNIQUE,
generation INTEGER NOT NULL CHECK (generation >= 1),
created_at_ms INTEGER NOT NULL,
last_used_at_ms INTEGER NOT NULL,
closed_at_ms INTEGER,
FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS worker_environment_session_attachments_session_key
ON worker_environment_session_attachments(agent_id, session_key);
`};function getOpenClawStateFeatureSchemaSql(e,t){if(t===void 0&&featureLocalSql[e])return featureLocalSql[e];if(e===`skill_library_entries`&&t===void 0)return extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,e,{endMarker:`-- End profile-owned skill library.`,includeEndMarker:false,errorMessage:`Canonical skill library schema missing.`});return extractSqliteTableSchema(e===`user_profile_emails`?featureLocalSql.user_profiles:OPENCLAW_STATE_SCHEMA_SQL,e,t)}
//!src/state/openclaw-state-db-schema-additive.ts
const tableEnsurers=/* @__PURE__ */ new Map;function ensureTable(e,t,n){if(isPostgresSqlConnection(e))return ensureStatePostgresFragment(e,t);let r=tableEnsurers.get(t);if(!r){const e=getOpenClawStateFeatureSchemaSql(t,n);r=createSqliteSchemaEnsurer(()=>e,{tables:getCanonicalSqliteTableNames(e),indexes:getCanonicalSqliteNamedIndexNames(e)});tableEnsurers.set(t,r)}r(e)}function ensureAgentDatabaseLeaseSchema(e){if(tableHasColumn(e,`agent_database_leases`,`provenance`))return;ensureTable(e,`agent_database_leases`);ensureColumn(e,`agent_database_leases`,`provenance TEXT`)}function ensureWorkerSessionToolStateSchema(e){ensureTable(e,`worker_turn_tool_authorities`);ensureTable(e,`worker_session_tool_operations`)}function ensureFirstUseAdditiveStateColumnsForStrictMigration(e){for(const{columnName:t,dataType:n,tableName:r}of CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS)ensureColumn(e,r,`${t} ${n}`)}function ensureColumns(e,t){const n=[];for(const[r,i]of t){const t=i.trim().split(/\s+/,1)[0];if(t&&ensureColumn(e,r,i))n.push({tableName:r,columnName:t})}return n}function ensureAdditiveStateColumns(e,t){const n=t===`repair`;ensureWorkerSessionToolStateSchema(e);for(const{columnName:t,dataType:n,tableName:r}of CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS)ensureColumn(e,r,`${t} ${n}`);if(ensureColumn(e,...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageUpdatedAt[0]))e.exec(`UPDATE template_package_refs SET updated_at_ms = installed_at_ms;`);ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageIntegrity);const r=ensureColumn(e,...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.diagnosticSequence[0]);if(r)e.exec(`
WITH ranked AS (
SELECT
rowid AS event_rowid,
ROW_NUMBER() OVER (
PARTITION BY scope
ORDER BY created_at ASC, rowid ASC
) AS sequence
FROM diagnostic_events
)
UPDATE diagnostic_events
SET sequence = (
SELECT ranked.sequence
FROM ranked
WHERE ranked.event_rowid = diagnostic_events.rowid
);
`);if(r||n)e.exec(`DROP INDEX IF EXISTS idx_diagnostic_events_scope_created;`);const i=ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.cronRunLogs);if(n||i.some(({tableName:e})=>e===`cron_run_logs`))backfillCronRunLogEntryJson(e);const a=ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.acpReplay).length>0;if(a||n)backfillAcpReplayEstimatedBytes(e,a);const o=ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.cronJobs);if(n||o.some(({columnName:e})=>[`name`,`enabled`,`agent_id`,`payload_kind`,`runtime_updated_at_ms`].includes(e)))backfillCronJobsFromJobJson(e);const s=ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.deliveryQueue);if(n||s.some(({tableName:e})=>e===`delivery_queue_entries`))backfillDeliveryQueueEntriesFromEntryJson(e);ensureColumn(e,...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.originalMediaRoot[0]);ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.beforeTaskAttribution);ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.taskRequester);ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.taskRunDetails);if(n){repairLegacySubagentExecutionPayloads(e);repairLegacySubagentRetainedResults(e)}ensureColumns(e,ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.workerEnvironments);if(n||!tableHasColumn(e,`operator_approvals`,`resolution_ref`))ensureOperatorApprovalResolutionRefs(e)}
//!src/state/agent-deletion-journal-authority.worker.ts
function hasTemplateDeletionOwnership(e,t){const n=getNodeSqliteKysely(e.db);return[`template_installs`,`template_workspace_files`].some(r=>tableExists(e.db,r)&&executeSqliteQueryTakeFirstSync(e.db,n.selectFrom(r).select(`agent_id`).where(`agent_id`,`=`,t).limit(1))!==void 0)||readTemplateSecondaryReferenceTables(e.db,t).length>0}
//!src/infra/sqlite-commit-receipt.ts
function createSqliteCommitReceipt(e){return{version:1,operationId:randomUUID(),source:e.source,domain:e.domain,facts:new Map([...new Set(e.keys)].map(t=>[t,e.readFact(t)]))}}function hasSqliteCommitReceiptCoverage(e,t){if(!isRecord(e)||e.version!==1||typeof e.operationId!==`string`||!e.operationId||e.domain!==t.domain||!isRecord(e.source)||e.source.identity!==t.source.identity||e.source.incarnation!==t.source.incarnation||!(e.facts instanceof Map))return false;const n=new Set(t.keys);const r=e.facts;return r.size===n.size&&[...n].every(e=>{const t=r.get(e);return isRecord(t)&&(t.kind===`absent`||t.kind===`unchanged`||t.kind===`unknown`||t.kind===`postimage`&&`value`in t)})}function readSqliteCommitReceipt(e,t){if(!isRecord(e)||!isRecord(e.source)||typeof e.source.identity!==`string`||typeof e.source.incarnation!==`string`||!(e.facts instanceof Map)||!hasSqliteCommitReceiptCoverage(e,{source:t.source??{identity:e.source.identity,incarnation:e.source.incarnation},domain:t.domain,keys:t.keys??[...e.facts.keys()]})||![...e.facts].every(([e,n])=>typeof e===`string`&&t.isFact(e,n)))throw new Error(t.invalidReceiptMessage??`State domain commit receipt is invalid`);return e}
//!src/state/state-domain-publication.ts
const batch=resolveGlobalSingleton(Symbol.for(`openclaw.stateDomainPublicationBatch`),()=>({current:void 0}));function createStateDomainPublication(e){const t=createKeyedStateDomainPublication({domain:e.domain,sourceIdentity:e.sourceIdentity,isFact:(t,n)=>n.kind===`absent`||n.kind===`postimage`&&e.isValue(n.value)&&e.keyOf(n.value)===t});return{...t,stagePostimages(n,r){t.stagePostimages(n,r.map(t=>[e.keyOf(t),t]))}}}function createKeyedStateDomainPublication(e){const t=resolveGlobalSingleton(Symbol.for(`openclaw.stateDomainPublication.${e.domain}`),()=>({sources:/* @__PURE__ */ new WeakMap,facts:/* @__PURE__ */ new Set,installingFacts:0}));const sourceFor=n=>{const r=sqlPublicationAnchor(n);let i=t.sources.get(r);if(!i){i={identity:e.sourceIdentity?.(n)??readTrackedStateDatabaseIdentity(n)?.key??Symbol(e.domain),incarnation:randomUUID()};t.sources.set(r,i)}return i};const receiptFor=(t,n)=>createSqliteCommitReceipt({source:sourceFor(t),domain:e.domain,keys:[...n.keys()],readFact:e=>n.get(e)});const install=n=>{const r=[];t.installingFacts++;try{notifyListeners(t.facts,n,e=>r.push(e))}finally{t.installingFacts--}if(r.length)throw new AggregateError(r,e.installFailureMessage??`State domain fact installation failed`)};const publication=e=>{let t={kind:`committed`,receipt:e};return{installFacts:()=>install(t),invalidate(){t={kind:`unknown`,identity:e.source.identity};install(t)},notify(){}}};const stage=(n,r)=>{if(e.mutationDuringInstallMessage&&t.installingFacts)throw new Error(e.mutationDuringInstallMessage);if(!r.size)return;const i=t.capture;if(i&&sqlPublicationAnchor(i.db)===sqlPublicationAnchor(n)){const e=new Map([...r.keys()].map(e=>[e,i.facts.get(e)]));if(!stageSqliteTransactionState(n,{stage(){for(const[e,t]of r)i.facts.set(e,t)},commit(){},rollback(){for(const[t,n]of e)if(n)i.facts.set(t,n);else i.facts.delete(t)}}))throw new Error(`State domain capture requires its owning transaction`)}const a=publication(receiptFor(n,r));if(!stageSqliteCommittedPublication(n,a)&&!n.isTransaction)publishSqliteCommittedState(a)};const readReceipt=(t,n=e.isFact)=>readSqliteCommitReceipt(t,{domain:e.domain,isFact:n,invalidReceiptMessage:e.invalidReceiptMessage});return{receipt:receiptFor,readReceipt,stageFacts:stage,stagePostimages(e,t){stage(e,new Map(t.map(([e,t])=>[e,{kind:`postimage`,value:structuredClone(t)}])))},stageDeletions(e,t){stage(e,new Map(t.map(e=>[e,{kind:`absent`}])))},capture(e,n){const r=t.capture;const i=r&&sqlPublicationAnchor(r.db)===sqlPublicationAnchor(e)?r:{db:e,facts:/* @__PURE__ */ new Map};t.capture=i;try{return{result:n(),receipt:receiptFor(e,i.facts)}}finally{t.capture=r}},bound(e){return serialize(e).byteLength<=33554432/4?e:{kind:`unknown`,identity:e.source.identity}},subscribeFacts:e=>registerListener(t.facts,e),begin(n,r=e.isFact){const i=randomUUID();const a=/* @__PURE__ */ new Set;let o=false;let s=false;let c=false;let l=false;const u=registerListener(t.facts,e=>{if(o)return;if(e.kind===`committed`&&e.receipt.source.identity===n.identity)for(const t of e.receipt.facts.keys())a.add(t);else if(e.kind===`unknown`&&e.identity===n.identity)s=true});try{if(n.publishPending!==false)install({kind:`pending`,identity:n.identity,operationId:i})}catch(e){u();try{install({kind:`settled`,identity:n.identity,operationId:i})}catch{}throw e}return{committed(t,i){try{n.assertCurrent();if(l)throw new Error(e.closedMessage??`State domain publication owner is closed`);if(isRecord(t)&&t.kind===`unknown`&&t.identity===n.identity)install({kind:`unknown`,identity:n.identity});else{const i=readReceipt(t,r);if(i.source.identity!==n.identity)throw new Error(e.changedOwnerMessage??`State domain commit receipt changed owner`);const c=publication({...i,facts:new Map([...i.facts].map(([e,t])=>[e,s||a.has(e)?{kind:`unknown`}:t]))});const l={...c,installFacts(){o=true;try{c.installFacts()}finally{o=false}}};if(batch.current)batch.current.push(l);else publishSqliteCommittedState(l)}c=true;i?.()}catch(e){install({kind:`unknown`,identity:n.identity});throw e}finally{o=false}},finish(e,t=false){if(l)return;l=true;u();try{if(!e||!c&&!t)install({kind:`unknown`,identity:n.identity})}finally{if(n.publishPending!==false)install({kind:`settled`,identity:n.identity,operationId:i})}}}}}}
//!src/state/agent-provenance-publication.ts
const agentProvenancePublication=createStateDomainPublication({domain:`agent-provenance`,keyOf:e=>e.agentId,isValue:e=>isRecord(e)&&typeof e.agentId===`string`&&(e.createdVia===`operator`||e.createdVia===`agent`||e.createdVia===`template`)&&(e.creatorAgentId===null||typeof e.creatorAgentId===`string`)&&typeof e.createdAtMs===`number`});
//!src/state/agent-deletion-journal-publication.ts
const agentDeletionJournalPublication=createStateDomainPublication({domain:`agent-deletion-journal`,keyOf:e=>e.agentId,isValue:e=>isRecord(e)&&typeof e.agentId===`string`&&typeof e.operationId===`string`&&typeof e.cleanupCompleted===`boolean`});
//!src/utils/chunk-items.ts
function chunkItems(e,t){if(t<=0)return[Array.from(e)];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}
//!src/infra/ed25519-signature.ts
const ED25519_RAW_KEY_LENGTH=32;const ED25519_SPKI_PREFIX=Buffer.from(`302a300506032b6570032100`,`hex`);const ED25519_PKCS8_PRIVATE_PREFIX=Buffer.from(`302e020100300506032b657004220420`,`hex`);function pemEncode(e,t){return`-----BEGIN ${e}-----\n${t.toString(`base64`).match(/.{1,64}/g)?.join(`
`)??``}\n-----END ${e}-----\n`}function decodeCanonicalPem(e,t){const n=`-----BEGIN ${e}-----\n`;const r=`\n-----END ${e}-----\n`;if(!t.startsWith(n)||!t.endsWith(r))throw new Error(`${e} must use canonical PEM framing`);const i=t.slice(n.length,-r.length);if(!i||!/^[A-Za-z0-9+/=\n]+$/.test(i))throw new Error(`${e} contains invalid PEM body bytes`);const a=Buffer.from(i.replaceAll(`
`,``),`base64`);if(pemEncode(e,a)!==t)throw new Error(`${e} must use canonical PEM base64 encoding`);return a}function assertEd25519KeyType(e,t){if(e.asymmetricKeyType!==`ed25519`)throw new Error(`${t} must be an Ed25519 key`)}function deriveRawKeyFromDer(e,t,n){const r=n.length+ED25519_RAW_KEY_LENGTH;if(e.length!==r||!e.subarray(0,n.length).equals(n))throw new Error(`${t} has a noncanonical Ed25519 encoding`);return e.subarray(n.length)}function deriveCanonicalEd25519PublicKeyRaw(e){const t=decodeCanonicalPem(`PUBLIC KEY`,e);assertEd25519KeyType(crypto$1.createPublicKey({key:t,type:`spki`,format:`der`}),`public key`);return deriveRawKeyFromDer(t,`public key`,ED25519_SPKI_PREFIX)}function deriveCanonicalEd25519PrivateKeyRaw(e){const t=decodeCanonicalPem(`PRIVATE KEY`,e);assertEd25519KeyType(crypto$1.createPrivateKey({key:t,type:`pkcs8`,format:`der`}),`private key`);return deriveRawKeyFromDer(t,`private key`,ED25519_PKCS8_PRIVATE_PREFIX)}
//!src/infra/device-identity-material.ts
const PRIMARY_DEVICE_IDENTITY_KEY=`primary`;var DeviceIdentityStorageError=class extends Error{constructor(e,t){super(e,t);this.name=`DeviceIdentityStorageError`}};function invalidStoredIdentityError(e,t){return new DeviceIdentityStorageError(`SQLite contains an invalid persisted device identity "${e}". Run "openclaw doctor --fix" before starting the gateway or connecting this client.`,t===void 0?void 0:{cause:t})}function fingerprintPublicKey(e){const t=deriveCanonicalEd25519PublicKeyRaw(e);return crypto$1.createHash(`sha256`).update(t).digest(`hex`)}function keyPairMatches(e,t){try{deriveCanonicalEd25519PublicKeyRaw(e);deriveCanonicalEd25519PrivateKeyRaw(t);return crypto$1.createPublicKey(t).export({type:`spki`,format:`pem`})===e}catch{return false}}function parseCreatedAtMs(e){return asSafeIntegerInRange(e,{min:0})??null}function validateStoredDeviceIdentity(e,t=PRIMARY_DEVICE_IDENTITY_KEY){try{if(!e.deviceId||!/^[a-f0-9]{64}$/.test(e.deviceId)||!e.publicKeyPem||!e.privateKeyPem||parseCreatedAtMs(e.createdAtMs)===null||!keyPairMatches(e.publicKeyPem,e.privateKeyPem))throw invalidStoredIdentityError(t);if(fingerprintPublicKey(e.publicKeyPem)!==e.deviceId)throw invalidStoredIdentityError(t);return{deviceId:e.deviceId,publicKeyPem:e.publicKeyPem,privateKeyPem:e.privateKeyPem}}catch(e){if(e instanceof DeviceIdentityStorageError)throw e;throw invalidStoredIdentityError(t,e)}}function storedDeviceIdentityFromRow(e,t){if(e.identity_key!==t||typeof e.device_id!==`string`||typeof e.public_key_pem!==`string`||typeof e.private_key_pem!==`string`||parseCreatedAtMs(e.created_at_ms)===null||parseCreatedAtMs(e.updated_at_ms)===null)throw invalidStoredIdentityError(t);const n={deviceId:e.device_id,publicKeyPem:e.public_key_pem,privateKeyPem:e.private_key_pem,createdAtMs:e.created_at_ms};validateStoredDeviceIdentity(n,t);return n}function salvageStoredIdentityRow(e,t,n){if(e.identity_key!==t||typeof e.public_key_pem!==`string`||typeof e.private_key_pem!==`string`)return null;try{const r=crypto$1.createPublicKey(e.public_key_pem);const i=crypto$1.createPrivateKey(e.private_key_pem);if(r.asymmetricKeyType!==`ed25519`||i.asymmetricKeyType!==`ed25519`)return null;const a=r.export({type:`spki`,format:`pem`});const o=i.export({type:`pkcs8`,format:`pem`});if(crypto$1.createPublicKey(o).export({type:`spki`,format:`pem`})!==a)return null;const s=parseCreatedAtMs(e.created_at_ms)??parseCreatedAtMs(e.updated_at_ms)??n;const c={deviceId:fingerprintPublicKey(a),publicKeyPem:a,privateKeyPem:o,createdAtMs:s};validateStoredDeviceIdentity(c,t);return c}catch{return null}}function storedDeviceIdentityToRow(e,t,n=t.createdAtMs){return{identity_key:e,device_id:t.deviceId,public_key_pem:t.publicKeyPem,private_key_pem:t.privateKeyPem,created_at_ms:t.createdAtMs,updated_at_ms:n}}
//!src/infra/exec-approvals-config.ts
const execSecuritySchema=_enum([`allowlist`,`full`,`deny`]);const execAskSchema=_enum([`always`,`off`,`on-miss`]);const persistedExecApprovalPolicySchema=looseObject({security:execSecuritySchema.optional(),ask:execAskSchema.optional(),askFallback:execSecuritySchema.optional(),autoAllowSkills:boolean().optional()});function normalizePersistedAllowlistSource(e){return e===`allow-always`?e:void 0}const persistedExecAllowlistEntrySchema=looseObject({pattern:string().refine(e=>e.trim().length>0),id:string().min(1),source:literal(`allow-always`).optional(),commandText:never().optional(),argPattern:string().optional(),lastUsedAt:number().finite().optional(),lastUsedCommand:string().optional(),lastResolvedPath:string().optional()});const legacyExecAllowlistEntrySchema=union([string().trim().min(1),persistedExecAllowlistEntrySchema.extend({id:string().optional(),source:string().transform(normalizePersistedAllowlistSource).optional(),commandText:string().optional()})]).transform(e=>typeof e===`string`?{pattern:e}:e);function createExecApprovalsSchema(e,t){const n=persistedExecApprovalPolicySchema.extend({allowlist:array(e).optional(),mcpTools:array(looseObject({server:string().refine(e=>e.trim().length>0),tool:string().refine(e=>e.trim().length>0),source:literal(`allow-always`),addedAt:number().finite().nonnegative(),lastUsedAt:number().finite().nonnegative().optional()})).optional()});const r=unknown().refine(e=>!isRecord(e)||!Object.hasOwn(e,`__proto__`)).pipe(record(string(),n)).refine(e=>t||!Object.hasOwn(e,`default`));return looseObject({version:literal(1),socket:looseObject({path:string().optional(),token:string().optional()}).optional(),defaults:persistedExecApprovalPolicySchema.optional(),agents:r.optional()})}const persistedExecApprovalsSchema=createExecApprovalsSchema(persistedExecAllowlistEntrySchema,false);const legacyExecApprovalsSchema=createExecApprovalsSchema(legacyExecAllowlistEntrySchema,true);function stripExecApprovalsRawSocketCredentials(e){let t;try{t=JSON.parse(e)}catch{return e}if(!isRecord(t)||!isRecord(t.socket)||!Object.hasOwn(t.socket,`path`)&&!Object.hasOwn(t.socket,`token`))return e;const{path:n,token:r,...i}=t.socket;if(Object.keys(i).length)t.socket=i;else delete t.socket;return`${JSON.stringify(t,null,2)}\n`}
//!src/infra/client-credential-migration-data.ts
function resolveClientCredentialLegacyImportClaims(e,t){const n={};for(const e of t.identities)if(e.identity_key===`primary`||e.identity_key===`node`||e.identity_key===`shareExtension`){n[`identity:${e.identity_key}`]={sha256:null};if(t.authTablePresent)n[`auth:${e.identity_key}`]={sha256:null}}if(!t.nativeBootstrap&&tableExists(e,`migration_sources`)&&e.prepare(`SELECT 1 FROM migration_sources WHERE migration_kind = 'legacy-device-identity-json' LIMIT 1`).get())n[`identity:primary`]={sha256:null};return n}function sourceRows(e,t){const n=getNodeSqliteKysely(e);const r={identities:t&&!tableExists(e,`device_identities`)?[]:executeSqliteQuerySync(e,n.selectFrom(`device_identities`).selectAll()).rows,tokens:t&&!tableExists(e,`device_auth_tokens`)?[]:executeSqliteQuerySync(e,n.selectFrom(`device_auth_tokens`).selectAll()).rows,origins:t&&!tableExists(e,`gateway_origin_device_tokens`)?[]:executeSqliteQuerySync(e,n.selectFrom(`gateway_origin_device_tokens`).selectAll()).rows,approvals:t&&!tableExists(e,`exec_approvals_config`)?[]:executeSqliteQuerySync(e,n.selectFrom(`exec_approvals_config`).selectAll()).rows};const compare=(e,t)=>Buffer.compare(Buffer.from(e),Buffer.from(t));r.identities.sort((e,t)=>compare(e.identity_key,t.identity_key));r.tokens.sort((e,t)=>compare(e.device_id,t.device_id)||compare(e.role,t.role));r.origins.sort((e,t)=>compare(e.gateway_scope,t.gateway_scope)||compare(e.device_id,t.device_id)||compare(e.role,t.role));r.approvals.sort((e,t)=>compare(e.config_key,t.config_key));return r}function validateSource(e,t=`require-valid`){if(t===`require-valid`)for(const t of e.identities){validateStoredDeviceIdentity({deviceId:t.device_id,publicKeyPem:t.public_key_pem,privateKeyPem:t.private_key_pem,createdAtMs:t.created_at_ms},t.identity_key);if(!Number.isSafeInteger(t.updated_at_ms)||t.updated_at_ms<0)throw new Error(`Client credential migration found an invalid identity timestamp.`)}for(const t of[...e.tokens,...e.origins]){let e;try{e=JSON.parse(t.scopes_json)}catch{throw new Error(`Client credential migration found invalid token scopes.`)}if(!Array.isArray(e)||!e.every(e=>typeof e===`string`)||!Number.isSafeInteger(t.updated_at_ms)||t.updated_at_ms<0)throw new Error(`Client credential migration found an invalid token record.`)}if(e.approvals.some(e=>e.config_key!==`current`)||e.approvals.length>1)throw new Error(`Client credential migration found a noncanonical approval singleton.`)}function hashClientCredentialRows(e,t){return createHash(`sha256`).update(stableStringify(t?{authTablePresent:t.authTablePresent,identities:e.identities,tokens:e.tokens}:e)).digest(`hex`)}function extractSocket(e){if(!e)return{socket:void 0,policy:void 0};const invalid=()=>Object.assign(/* @__PURE__ */ new Error(`Client credential migration found invalid socket credentials or projections.`),{code:`CLIENT_CREDENTIAL_SOCKET_INVALID`});let t;try{t=JSON.parse(e.raw_json)}catch{throw new Error(`Client credential migration found invalid approval JSON.`)}const n=isRecord(t)?t.socket:void 0;if(n!==void 0&&!isRecord(n))throw invalid();const r=isRecord(n)?n.path:void 0;const i=isRecord(n)?n.token:void 0;if(r!==void 0&&typeof r!==`string`||i!==void 0&&typeof i!==`string`)throw invalid();if(r===void 0&&i===void 0)return{socket:void 0,policy:e.raw_json};return{socket:{socket_key:`current`,socket_path:r??null,socket_token:i??null,updated_at_ms:e.updated_at_ms},policy:stripExecApprovalsRawSocketCredentials(e.raw_json)}}
//!src/infra/client-credential-paths.ts
function resolveClientCredentialStorePath(e){return path.join(resolveStateDir(e),`client`,`credentials.sqlite`)}function resolveStateClientCredentialEnvironment(e){const t=resolveDatabasePath({path:e.path});const n={...e.env,OPENCLAW_STATE_DIR:resolveOpenClawStateDirForDatabasePath(t)};return t===resolveOpenClawStateSqlitePath(n)?n:void 0}
//!src/infra/client-credential-receipt.ts
const CLIENT_CREDENTIAL_LEGACY_KEYS=[`identity:primary`,`identity:node`,`identity:shareExtension`,`auth:primary`,`auth:node`,`auth:shareExtension`];function readClientCredentialFileIdentity(e){const t=fs.statSync(e,{bigint:true,throwIfNoEntry:false});if(!t){if(SQLITE_SIDECAR_SUFFIXES.some(t=>fs.existsSync(`${e}${t}`)))throw new Error(`Client credential source is unavailable; restore the matching main database before using this client.`);return null}if(!t.isFile())throw new Error(`Client credential source is not a regular file.`);return{path:fs.realpathSync.native(e),dev:String(t.dev),ino:String(t.ino)}}function emptyClientCredentialReceipt(e=null){return{format:1,source:null,sharedFile:e,legacyImports:{}}}function digest(e){return typeof e===`string`&&/^[a-f0-9]{64}$/u.test(e)}function parseClientCredentialReceipt(e,t){const invalid=()=>/* @__PURE__ */ new Error(`Client credential migration receipt is invalid; run openclaw doctor --fix.`);let n;try{n=JSON.parse(e)}catch{throw invalid()}if(!isRecord(n)||n.format!==1||!isRecord(n.legacyImports))throw invalid();let r=null;if(n.source!==null){const e=n.source;if(!isRecord(e)||e.kind!==`canonical`&&e.kind!==`independent`||e.engine!==`sqlite`&&e.engine!==`postgres`&&e.engine!==`native-v0`||typeof e.identity!==`string`||e.identity.length===0||typeof e.generation!==`string`||e.generation.length===0||!digest(e.sha256)||e.destinationVersion!==1)throw invalid();r={kind:e.kind,engine:e.engine,identity:e.identity,generation:e.generation,sha256:e.sha256,destinationVersion:e.destinationVersion}}let i=null;if(n.sharedFile!==null){const e=n.sharedFile;if(!isRecord(e)||typeof e.path!==`string`||typeof e.dev!==`string`||!/^-?\d+$/u.test(e.dev)||typeof e.ino!==`string`||!/^-?\d+$/u.test(e.ino))throw invalid();i={path:e.path,dev:e.dev,ino:e.ino}}if(r?.kind===`independent`&&(r.engine!==`native-v0`||!i))throw invalid();const a={};for(const[e,t]of Object.entries(n.legacyImports)){const n=CLIENT_CREDENTIAL_LEGACY_KEYS.find(t=>t===e);if(!n||!isRecord(t)||t.sha256!==null&&!digest(t.sha256))throw invalid();a[n]={sha256:t.sha256}}return rebaseCanonicalReceipt({format:1,source:r,sharedFile:i,legacyImports:a},t,false)}function rebaseCanonicalReceipt(e,t,n){const r=e.sharedFile;if(!r||e.source?.kind===`independent`)return e;const i=!path.isAbsolute(r.path);if(i&&(!t||!r.path.startsWith(`./`)||r.path.slice(2).split(`/`).some(e=>!e||e===`.`||e===`..`||e.includes(`\\`))))throw new Error(`Client credential receipt has an invalid relative shared binding.`);if(!t)return e;const a=resolvePathViaExistingAncestorSync$1(t);const o=path.resolve(a,r.path);const s=path.relative(a,o);const c=s&&!path.isAbsolute(s)&&s!==`..`&&!s.startsWith(`..${path.sep}`);const l=n&&c?`./${s.split(path.sep).join(`/`)}`:o;let u=e.source;if(u?.engine===`sqlite`){const e=`${r.path}:`;if(u.identity.startsWith(e))u={...u,identity:`${l}:${u.identity.slice(e.length)}`};else if(i)throw new Error(`Client credential receipt has an invalid relative source identity.`)}return{...e,source:u,sharedFile:{...r,path:l}}}function serializeClientCredentialReceipt(e,t){return JSON.stringify(rebaseCanonicalReceipt(e,t,true))}
//!src/infra/client-credential-native-bootstrap.ts
function isNativeClientCredentialBootstrap(e){admitSqliteSchema(e);const t=getAdmittedSqliteSchemaFacts(e);if(t.userVersion!==0)return false;const n=[...[...t.tables].map(e=>({type:`table`,name:e})),...[...t.indexes].map(e=>({type:`index`,name:e})),...[...t.views].map(e=>({type:`view`,name:e})),...[...t.triggers.keys()].map(e=>({type:`trigger`,name:e}))].filter(({name:e})=>!e.startsWith(`sqlite_`));const r=/* @__PURE__ */ new Set([`table:device_identities`,`index:idx_device_identities_device`,`table:device_auth_tokens`,`index:idx_device_auth_tokens_updated`,`table:macos_port_guardian_records`,`index:idx_macos_port_guardian_records_port`]);if(!n.length||n.some(e=>!r.has(`${e.type}:${e.name}`)))return false;if(t.tables.has(`macos_port_guardian_records`)||t.indexes.has(`idx_macos_port_guardian_records_port`)){const t=readGeneratedSqliteCatalog(OPENCLAW_STATE_SCHEMA_SQL)?.tables.filter(({name:e})=>e===`macos_port_guardian_records`);if(!t?.length)throw new Error(`Native PortGuardian companion has no canonical schema catalog.`);assertSqliteSchemaContains(e,`Native PortGuardian companion`,{tables:t,views:[]})}assertSqliteSchemaContains(e,`Native client credential bootstrap`,CLIENT_CREDENTIAL_SCHEMA_SQL,{allowedMissingTables:[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`,`client_credential_migration`]});return true}function readIndependentClientCredentialSource(e){try{var t=_usingCtx();const n=readClientCredentialFileIdentity(e);if(!n)throw new Error(`Independent client credential source is missing; restore its matching backup.`);const r=fs.openSync(e,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);try{const e=Buffer.alloc(100);if(fs.readSync(r,e,0,e.length,0)!==e.length||e.subarray(0,16).toString(`binary`)!==`SQLite format 3\0`||e[18]!==1||e[19]!==1)throw new Error(`Independent client credentials require DELETE journal mode; stop the old client and restore a compatible source.`)}finally{fs.closeSync(r)}const i=t.u(openNodeSqliteDatabase(e,{readOnly:true}));if(!isNativeClientCredentialBootstrap(i))throw new Error(`Independent client credential source is not a native credential-only database.`);i.exec(`BEGIN`);try{const e=getAdmittedSqliteSchemaFacts(i).tables.has(`device_auth_tokens`);const t=sourceRows(i,true);validateSource(t);const r=hashClientCredentialRows(t,{authTablePresent:e});return{file:n,identity:`${n.dev}:${n.ino}`,sha256:r,rows:t,authTablePresent:e}}finally{i.exec(`ROLLBACK`)}}catch(e){t.e=e}finally{t.d()}}
//!src/infra/client-credential-readiness.ts
var ClientCredentialMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e=`Client credential migration is incomplete or stale; run openclaw doctor --fix before using this client.`){super(`state-migrations`,e);this.name=`ClientCredentialMigrationRequiredError`}};function notReady(){return new ClientCredentialMigrationRequiredError}function assertSupportedVersion(e){if(e!==1)throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`)}function readClientCredentialAdmission(e){let t;try{t=e.prepare(`
SELECT header.user_version, receipt.source_store, receipt.phase
FROM pragma_user_version AS header
LEFT JOIN client_credential_migration AS receipt ON receipt.version = 1
`).get()}catch(t){assertSupportedVersion(readSqliteUserVersion(e));throw t}if(!t||typeof t.user_version!==`number`)throw notReady();assertSupportedVersion(t.user_version);const n=e.location();return{stored:t.source_store===null?null:{phase:t.phase===`complete`?`complete`:`copied`,receipt:parseClientCredentialReceipt(String(t.source_store),n?path.dirname(path.dirname(n)):void 0)}}}function readClientCredentialReceipt(e,t){const n=getNodeSqliteKysely(e);const r=executeSqliteQueryTakeFirstSync(e,n.selectFrom(`client_credential_migration`).selectAll().where(`version`,`=`,1));const i=e.location();return r?{phase:r.phase,receipt:parseClientCredentialReceipt(r.source_store,t??(i?path.dirname(path.dirname(i)):void 0))}:null}function writeClientCredentialReceipt(e,t,n,r=Date.now()){const i=getNodeSqliteKysely(e);const a=e.location();const o={version:1,source_store:serializeClientCredentialReceipt(t,a?path.dirname(path.dirname(a)):void 0),phase:n,updated_at_ms:r};executeSqliteQuerySync(e,i.insertInto(`client_credential_migration`).values(o).onConflict(e=>e.column(`version`).doUpdateSet(o)))}function assertClientCredentialLegacyReady(e,t,n=false,r){let i=false;const a=e?getNodeSqliteKysely(e):void 0;const o=r??(e?readClientCredentialReceipt(e)?.receipt:void 0);const s={primary:`device`,node:`node-device`,shareExtension:`share-device`};for(const r of[`primary`,`node`,`shareExtension`])for(const c of[`identity`,`auth`]){if(o?.legacyImports[`${c}:${r}`])continue;const l=`${s[r]}${c===`auth`?`-auth`:``}.json`;const u=path.join(resolveStateDir(t),`identity`,l);if([u,`${u}.doctor-importing`,`${u}.native-importing`].some(e=>fs.existsSync(e))){if(c===`identity`&&e&&a&&executeSqliteQueryTakeFirstSync(e,a.selectFrom(`device_identities`).select(`identity_key`).where(`identity_key`,`=`,r)))continue;throw new ClientCredentialMigrationRequiredError(`Legacy client credentials require migration; run openclaw doctor --fix before using this client.`)}if(n&&o){o.legacyImports[`${c}:${r}`]={sha256:null};i=true}}if(i&&o&&e)writeClientCredentialReceipt(e,o,`complete`)}function assertMissingClientCredentialStoreReady(e){assertClientCredentialLegacyReady(null,e);if(readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(e)))throw notReady()}function prepareClientCredentialReceipt(e,t,n,r=false,i=readClientCredentialReceipt(e)){let a=i;const o=readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(t));if(!a&&n&&!o){assertClientCredentialLegacyReady(null,t);const n=emptyClientCredentialReceipt();for(const e of CLIENT_CREDENTIAL_LEGACY_KEYS)n.legacyImports[e]={sha256:null};writeClientCredentialReceipt(e,n,`complete`);a={phase:`complete`,receipt:n}}if(!a||a.phase!==`complete`)throw notReady();if(a.receipt.source?.kind===`independent`){const t=a.receipt.sharedFile;const n=readIndependentClientCredentialSource(t.path);if(n.identity!==a.receipt.source.identity||n.file.path!==t.path||n.file.dev!==t.dev||n.file.ino!==t.ino||n.sha256!==a.receipt.source.sha256){if(r)throw new Error(`Independent client credentials changed; open the client or run openclaw doctor --fix before read-only inspection.`);const t=getNodeSqliteKysely(e);executeSqliteQuerySync(e,t.deleteFrom(`device_auth_tokens`));executeSqliteQuerySync(e,t.deleteFrom(`device_identities`));executeSqliteQuerySync(e,t.deleteFrom(`gateway_origin_device_tokens`));for(const r of chunkItems(n.rows.identities,500))executeSqliteQuerySync(e,t.insertInto(`device_identities`).values(r));for(const r of chunkItems(n.rows.tokens,500))executeSqliteQuerySync(e,t.insertInto(`device_auth_tokens`).values(r));a.receipt.source={kind:`independent`,engine:`native-v0`,identity:n.identity,generation:`0`,sha256:n.sha256,destinationVersion:1};a.receipt.sharedFile=n.file;writeClientCredentialReceipt(e,a.receipt,`complete`)}}else{const e=a.receipt.sharedFile;if(e===null?o!==null:o===null||e.path!==o.path||e.dev!==o.dev||e.ino!==o.ino)throw notReady()}return a}function admitClientCredentialStore(e,t,n){const r=prepareClientCredentialReceipt(e,t,n.initialize,n.readOnly,n.stored);assertClientCredentialLegacyReady(e,t,!n.readOnly,r.receipt);return r.receipt}
//!src/infra/client-credential-operations.ts
function encodeClientNativeTokenRole(e,t){return`v2.${Buffer.from(t).toString(`base64url`)}.${Buffer.from(e.trim()).toString(`base64url`)}`}function decodeRole(e){const t=e.split(`.`);if(t.length===3&&t[0]===`v2`&&t[1]!==void 0&&t[2]!==void 0)try{const decode=e=>{if(!/^[A-Za-z0-9_-]*$/u.test(e)||e.length%4===1)throw new Error(`Invalid component`);return new TextDecoder(`utf-8`,{fatal:true}).decode(Buffer.from(e,`base64url`))};return{gateway:decode(t[1]),role:decode(t[2])}}catch{}return{role:e,gateway:null}}function clearClientNativeTokens(e,t,n){const r=getNodeSqliteKysely(e);if(n.kind===`all`)return Number(executeSqliteQuerySync(e,r.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t)).numAffectedRows);const i=executeSqliteQuerySync(e,r.selectFrom(`device_auth_tokens`).select(`role`).where(`device_id`,`=`,t)).rows.filter(({role:e})=>{const t=decodeRole(e);if(n.kind===`role`)return t.role===n.role.trim();if(n.kind===`gateway`)return t.gateway===n.gateway;return t.gateway===null}).map(({role:e})=>e);if(i.length===0)return 0;executeSqliteQuerySync(e,r.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t).where(`role`,`in`,i));return i.length}function claimClientNativeToken(e,t,n,r){const i=getNodeSqliteKysely(e);const a=n.trim();const o=executeSqliteQueryTakeFirstSync(e,i.selectFrom(`device_auth_tokens`).selectAll().where(`device_id`,`=`,t).where(`role`,`=`,a));if(!o)return false;executeSqliteQuerySync(e,i.insertInto(`device_auth_tokens`).values({...o,role:encodeClientNativeTokenRole(n,r)}).onConflict(e=>e.columns([`device_id`,`role`]).doNothing()));executeSqliteQuerySync(e,i.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t).where(`role`,`=`,a));return true}function performClientCredentialOperation(e,t,n){const r=getNodeSqliteKysely(e);switch(t.kind){case`identity.read`:case`identity.create`:case`identity.repair`:{const n=t.kind===`identity.read`?t.identity_key:t.identity.identity_key;const i=executeSqliteQueryTakeFirstSync(e,r.selectFrom(`device_identities`).selectAll().where(`identity_key`,`=`,n));if(t.kind===`identity.repair`){if(i)try{storedDeviceIdentityFromRow(i,n);return{kind:`identityRepair`,identity:i,repaired:false,rotated:false}}catch{}const a=i?salvageStoredIdentityRow(i,n,t.identity.updated_at_ms):null;const o=a?storedDeviceIdentityToRow(n,a,t.identity.updated_at_ms):t.identity;storedDeviceIdentityFromRow(o,n);executeSqliteQuerySync(e,r.insertInto(`device_identities`).values(o).onConflict(e=>e.column(`identity_key`).doUpdateSet(o)));return{kind:`identityRepair`,identity:o,repaired:true,rotated:a===null}}if(i){storedDeviceIdentityFromRow(i,n);return{kind:`identity`,identity:i}}if(t.kind===`identity.create`){storedDeviceIdentityFromRow(t.identity,n);executeSqliteQuerySync(e,r.insertInto(`device_identities`).values(t.identity));return{kind:`identity`,identity:t.identity}}return{kind:`identity`,identity:null}}case`native.tokens.clear`:return{kind:`cleared`,count:clearClientNativeTokens(e,t.device_id,t.selector)};case`native.token.claim`:return{kind:`changed`,changed:claimClientNativeToken(e,t.device_id,t.role,t.gateway)};case`token.list`:{const n=t.gateway_scope===void 0?`device_auth_tokens`:`gateway_origin_device_tokens`;let i=r.selectFrom(n).selectAll().where(`device_id`,`=`,t.device_id);if(t.gateway_scope!==void 0)i=i.where(`gateway_scope`,`=`,t.gateway_scope);if(t.afterRole!==void 0)i=i.where(`role`,`>`,t.afterRole);const a=Math.max(1,Math.min(32,Math.trunc(t.limit??32)));const o=executeSqliteQuerySync(e,i.orderBy(`role`).limit(a+1)).rows;const s=o.slice(0,a).map(({device_id:e,role:t,token:n,scopes_json:r,updated_at_ms:i})=>({device_id:e,role:t,token:n,scopes_json:r,updated_at_ms:i}));return{kind:`tokens`,tokens:s,nextRole:o.length>a?s.at(-1)?.role??null:null}}case`token.read`:case`token.replace`:case`token.remove`:{const{key:n}=t;const i=n.gateway_scope===void 0?`device_auth_tokens`:`gateway_origin_device_tokens`;const a=expressionBuilder();const o=a.and([a(`device_id`,`=`,n.device_id),a(`role`,`=`,n.role),...n.gateway_scope===void 0?[]:[a(`gateway_scope`,`=`,n.gateway_scope)]]);const s=r.selectFrom(i).selectAll().where(o);if(t.kind===`token.read`){const t=executeSqliteQueryTakeFirstSync(e,s);return{kind:`token`,token:t?{device_id:t.device_id,role:t.role,token:t.token,scopes_json:t.scopes_json,updated_at_ms:t.updated_at_ms}:null}}const c=executeSqliteQueryTakeFirstSync(e,s);const l=t.expectedToken===void 0?t.kind!==`token.remove`||t.observedToken===void 0:(c?.token??null)===t.expectedToken;const u=t.kind===`token.remove`&&t.observedToken!==void 0&&c?.token===t.observedToken&&(t.expectedToken===void 0||typeof t.expectedToken===`string`&&t.observedToken.trim()===t.expectedToken);if(!(l||u))return{kind:`changed`,changed:false};if(t.kind===`token.remove`){if(!c)return{kind:`changed`,changed:false};executeSqliteQuerySync(e,r.deleteFrom(i).where(o))}else{const i={...t.token,device_id:n.device_id,role:n.role};if(n.gateway_scope===void 0)executeSqliteQuerySync(e,r.insertInto(`device_auth_tokens`).values(i).onConflict(e=>e.columns([`device_id`,`role`]).doUpdateSet(i)));else executeSqliteQuerySync(e,r.insertInto(`gateway_origin_device_tokens`).values({...i,gateway_scope:n.gateway_scope}).onConflict(e=>e.columns([`gateway_scope`,`device_id`,`role`]).doUpdateSet(i)))}return{kind:`changed`,changed:true}}case`socket.read`:case`socket.ensure`:{const i=executeSqliteQueryTakeFirstSync(e,r.selectFrom(`native_exec_socket_credentials`).selectAll().where(`socket_key`,`=`,`current`))??null;if(t.kind===`socket.read`)return{kind:`socket`,socket:i};const a=t.requested?.path?.trim();const o=i?.socket_path;const s=!a&&o===path.join(n,`exec-approvals.sock`)&&o!==t.fallback.socket_path;const c={socket_key:`current`,socket_path:a||(s?t.fallback.socket_path:o)||t.fallback.socket_path,socket_token:t.requested?.token?.trim()||i?.socket_token||t.fallback.socket_token,updated_at_ms:t.fallback.updated_at_ms};if(i&&i.socket_path===c.socket_path&&i.socket_token===c.socket_token)return{kind:`socket`,socket:i};executeSqliteQuerySync(e,r.insertInto(`native_exec_socket_credentials`).values(c).onConflict(e=>e.column(`socket_key`).doUpdateSet(c)));return{kind:`socket`,socket:c}}default:throw new Error(`Unsupported client credential operation.`)}}
//!src/infra/private-store-file.ts
function createPrivateIfMissing(e){try{e();return true}catch(e){if(!(e instanceof FsSafeError&&e.code===`already-exists`))throw e;return false}}function createPrivateStoreDirectorySync(e){const t=path.dirname(e);const n=process.platform===`linux`?fs.lstatSync(t,{bigint:true}):void 0;try{createDirectorySync(e,{private:true})}catch(r){const i=r instanceof FsSafeError?r.details?.publication:void 0;if(process.platform!==`linux`||typeof process.getuid!==`function`||!n||!(r instanceof FsSafeError&&r.code===`helper-failed`)||!(r.cause instanceof FsSafeError&&r.cause.code===`insecure-permissions`)||r.details?.path!==e||!i||typeof i!==`object`||!(`status`in i&&i.status===`published`))throw r;let a;try{assertDirectoryIdentitySync(t,n);a=fs.openSync(e,fs.constants.O_RDONLY|fs.constants.O_DIRECTORY|fs.constants.O_NOFOLLOW);const i=fs.fstatSync(a,{bigint:true});const o=fs.lstatSync(e,{bigint:true});if(!i.isDirectory()||i.uid!==BigInt(process.getuid())||(i.mode&4095n)!==1472n||i.dev!==o.dev||i.ino!==o.ino)throw r;assertDirectoryIdentitySync(t,n);fs.fchmodSync(a,448);const s=fs.fstatSync(a,{bigint:true});const c=fs.lstatSync(e,{bigint:true});if((s.mode&4095n)!==448n||s.dev!==c.dev||s.ino!==c.ino)throw r;assertDirectoryIdentitySync(t,n)}catch{throw r}finally{if(a!==void 0)fs.closeSync(a)}}}function preparePrivateStoreFileSync(e,t){const n=path.dirname(e);if(!t)fs.mkdirSync(path.dirname(n),{recursive:true,mode:448});const r=path.join(fs.realpathSync.native(path.dirname(n)),path.basename(n));if(!t)createPrivateIfMissing(()=>createPrivateStoreDirectorySync(r));applyPrivateModeSync(n,448);if(!fs.existsSync(e))return createPrivateIfMissing(()=>createFileSync(path.join(r,path.basename(e)),{private:true}).close());return false}
//!src/infra/client-credential-store.ts
const retainedPaths=resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialCustody`),()=>/* @__PURE__ */ new Set);const admittedFiles=resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialAdmittedFiles`),()=>/* @__PURE__ */ new Map,e=>e.clear());var ClientCredentialBusyError=class extends Error{constructor(){super(`Client credential owner is busy.`);this.name=`ClientCredentialBusyError`}};const schemaAdmission={name:`client.credentials.schema-v1`,schemaDependent:true,read:e=>e===true?true:void 0};function assertPrivateAcl(e){if(process.platform===`darwin`&&inspectDarwinAcl(e).kind!==`none`)throw new Error(`Client credentials require a private directory and file without ACL entries.`)}function openClientCredentialCustody(...e){const t=openClientCredentialCustodySteps(...e);let n=t.next();while(!n.done)try{n.value.admit();n=t.next()}catch(e){n=t.throw(e)}return n.value}async function openClientCredentialCustodyAsync(...e){resolveSqliteInspectionSignal(getAsyncWorkSignal())?.throwIfAborted();const t=openClientCredentialCustodySteps(...e);let n=t.next();while(!n.done)try{const e=n.value;await runUpdateSqliteMigrationAsync(e.database,e.path,e.admit,{created:e.created,retainExclusive:true});n=t.next()}catch(e){n=t.throw(e)}return n.value}function*openClientCredentialCustodySteps(e,t={},n){const r=t.readOnly===true||t.inspect===true;const i=(t.createIfMissing??false)&&!r;const a=resolveClientCredentialStorePath(e);const o=t.inspect===true&&!fs.existsSync(`${a}-journal`);const s=path.dirname(a);const c=resolveDatabasePathKey(a);if(retainedPaths.has(c))throw new ClientCredentialBusyError;if(t.migration)admittedFiles.delete(c);if(!t.migration&&!fs.existsSync(a))assertMissingClientCredentialStoreReady(e);const l=fs.lstatSync(s,{throwIfNoEntry:false});if(l&&(!l.isDirectory()||process.getuid&&l.uid!==process.getuid()||process.platform!==`win32`&&(l.mode&63)!==0))throw new Error(`Client credential directory is unsafe.`);if(!l&&!i)return;if(l)assertPrivateAcl(s);let u=false;if(i)u=preparePrivateStoreFileSync(a,Boolean(l));const d=openRootFileSync({absolutePath:a,rootPath:s,boundaryLabel:`client credential store`,rejectSymlinks:true});if(!d.ok){if(hasErrnoCode(d.error,`ENOENT`)&&!i)return;throw new Error(`Client credential store cannot be safely opened.`,{cause:d.error})}retainedPaths.add(c);let f;let p=false;let physicalClose;try{const s=fs.fstatSync(d.fd,{bigint:true});if(process.getuid&&s.uid!==BigInt(process.getuid())||process.platform!==`win32`&&(s.mode&63n)!==0n)throw new Error(`Client credential store owner is unsafe.`);const l=`${s.dev}:${s.ino}:${readDatabaseIdentityBirthtime(s)}`;assertPrivateAcl(a);f=o?openNodeSqliteDatabase(resolveReadOnlyShmSqliteFileUri(a),{readOnly:true,timeout:t.timeoutMs??5e3}):openNodeSqliteDatabase(resolveExistingSqliteFileUri(a),{timeout:t.timeoutMs??5e3});const m=f;if(f.prepare(`PRAGMA journal_mode`).get()?.journal_mode!==`delete`)throw new Error(`Client credentials require DELETE journal mode for exclusive owner custody.`);physicalClose=()=>{if(!p){p=true;try{m.close()}finally{fs.closeSync(d.fd);retainedPaths.delete(c)}}};const transaction=e=>{if(p)throw new Error(`Client credential custody is closed.`);if(o)return runSqliteDeferredTransactionSync(m,e);if(r)return runSqliteImmediateTransactionSync(m,e);return runUpdateSqliteMigration(m,a,()=>runSqliteImmediateTransactionSync(m,e),{retainExclusive:true})};const h=admittedFiles.get(c);let g=false;let _=false;yield{database:m,path:a,created:u,admit:()=>transaction(()=>{if(!o)m.exec(`PRAGMA locking_mode=EXCLUSIVE`);if(t.migration||h?.identity!==l||h.version!==1){const e=readSqliteUserVersion(m);if(e===0&&!m.prepare(`SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'`).get()){if(!i)throw new Error(`Client credential store is empty; run openclaw doctor --fix.`);m.exec(CLIENT_CREDENTIAL_SCHEMA_SQL);g=true;writeSqliteUserVersion(m,1)}else{if(e!==1)throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`);assertSqliteSchemaContains(m,`Client credentials`,CLIENT_CREDENTIAL_SCHEMA_SQL);assertSqliteIntegrity(m,`Client credentials`)}publishSqliteDatabaseAdmission(m,schemaAdmission,true)}if(!t.migration){const t=readClientCredentialAdmission(m);const n=admitClientCredentialStore(m,e,{initialize:g,readOnly:r,stored:t.stored});_=n.sharedFile!==null&&n.source===null}if(!g)n?.(m)})};if(g&&n)yield{database:m,path:a,created:u,admit:()=>transaction(()=>n(m))};if(!t.migration)admittedFiles.set(c,{identity:l,version:1});return{database:m,path:a,created:u,needsMetadataUpgrade:_,transaction,run(t,n){if(p)throw new Error(`Client credential custody is closed.`);if(r&&isClientCredentialMutation(t))throw new Error(`Client credential custody is read-only.`);const run=()=>{const r=performClientCredentialOperation(m,t,resolveStateDir(e));n?.();return r};return transaction(run)},close:physicalClose,[Symbol.dispose]:physicalClose}}catch(e){admittedFiles.delete(c);if(physicalClose)physicalClose();else{f?.close();fs.closeSync(d.fd);retainedPaths.delete(c)}throw e}}function isClientCredentialMutation(e){return![`identity.read`,`token.read`,`token.list`,`socket.read`].includes(e.kind)}
//!src/infra/client-credential-migration.ts
function postgresBootstrapProvenance(e){const t=isPostgresSqlConnection(e);const n=readEngineAnchor(t?e.anchor:e,`identity`,t);if(!n)return;const r=n[0];if(n.length!==1||!r||r.engine!==`postgres`||typeof r.store_id!==`string`||!r.store_id.trim()||typeof r.schema!==`string`||!r.schema.trim())throw new Error(`Invalid PostgreSQL anchor identity during client credential bootstrap.`);return{kind:`canonical`,engine:`postgres`,identity:r.store_id,generation:`bootstrap:${r.store_id}`,sha256:hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]}),destinationVersion:1}}function readClientCredentialBootstrapSource(e,t){const n=postgresBootstrapProvenance(e);if(n)return n;const r=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(!r)throw new Error(`Shared credential source identity was not published.`);return{kind:`canonical`,engine:`sqlite`,identity:`${t}:${String(r.created_at)}`,generation:`bootstrap:${String(r.created_at)}`,sha256:hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]}),destinationVersion:1}}function isPristineSqliteBootstrap(e,t){const n=t?.receipt.source;const r=t?.receipt.sharedFile;if(t?.phase!==`complete`||n?.kind!==`canonical`||n.engine!==`sqlite`||!r||!n.generation.startsWith(`bootstrap:`)||n.generation===`bootstrap:`||n.identity!==`${r.path}:${n.generation.slice(10)}`||n.sha256!==hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]})||Object.keys(t.receipt.legacyImports).length!==0)return false;const i=getNodeSqliteKysely(e);return[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`].every(t=>!executeSqliteQueryTakeFirstSync(e,i.selectFrom(t).selectAll().limit(1)))}async function prepareClientCredentialMigrationCustody(e){const t=resolveStateClientCredentialEnvironment(e);return t?openClientCredentialCustodyAsync(t,{createIfMissing:e.fromVersion<29,migration:true}):void 0}function bindFreshClientCredentialStore(e,t){if(!e.isTransaction||!hasSqlitePostCommitScope(e))throw new Error(`Client credential bootstrap has no source commit lifecycle.`);const n=resolveStateClientCredentialEnvironment(t);if(!n)return;const r=postgresBootstrapProvenance(e);const i=t.custody===void 0?openClientCredentialCustody(n,{createIfMissing:true,migration:true}):t.custody;if(!i)throw new Error(`Cannot acquire local credentials during shared bootstrap.`);const close=()=>{if(t.custody===void 0)i.close()};try{const n=beginUpdateSqliteCompanion(i.database,i.path,i.created);const a=readClientCredentialReceipt(i.database);const o=getNodeSqliteKysely(i.database);const s=executeSqliteQueryTakeFirstSync(i.database,o.selectFrom(`client_credential_migration`).selectAll().where(`version`,`=`,1));const c=readClientCredentialFileIdentity(t.path);if(!c)throw new Error(`Shared credential source is missing during bootstrap.`);const l=a?.receipt.source;const u=a?.receipt.sharedFile;const d=u?.path===c.path&&u.dev===c.dev&&u.ino===c.ino;const f=r&&l?.kind===r.kind&&l.engine===r.engine&&l.identity===r.identity&&l.generation===r.generation&&l.sha256===r.sha256&&l.destinationVersion===r.destinationVersion&&d;const p=!r&&isPristineSqliteBootstrap(i.database,a);if(l&&!f&&!p||u&&!d&&!p)throw new Error(`Existing client credentials belong to a previous shared database; run openclaw doctor --fix.`);const m={format:1,source:p&&!d?null:a?.receipt.source??null,sharedFile:c,legacyImports:a?.receipt.legacyImports??{}};runSqliteImmediateTransactionSync(i.database,()=>writeClientCredentialReceipt(i.database,m,`copied`));if(!stageSqliteTransactionState(e,{stage(){},commit(){try{m.source=readClientCredentialBootstrapSource(e,c.path);runSqliteImmediateTransactionSync(i.database,()=>writeClientCredentialReceipt(i.database,m,`complete`));n?.complete()}finally{close()}},rollback(){try{runSqliteImmediateTransactionSync(i.database,()=>{if(s)executeSqliteQuerySync(i.database,o.insertInto(`client_credential_migration`).values(s).onConflict(e=>e.column(`version`).doUpdateSet(s)));else executeSqliteQuerySync(i.database,o.deleteFrom(`client_credential_migration`).where(`version`,`=`,1))});n?.complete()}finally{close()}},invalidate:close}))throw new Error(`Client credential bootstrap has no source commit lifecycle.`)}catch(e){close();throw e}}function prepareClientCredentialMigration(e,t){if(t.fromVersion>=29||isPostgresSqlConnection(e)&&t.fromVersion!==29-1)return;if(!e.isTransaction)throw new Error(`Client credential migration requires the shared owner's transaction.`);const n=t.fromVersion===0;if(n&&!CLIENT_CREDENTIAL_SOURCE_TABLES.some(t=>tableExists(e,t))){bindFreshClientCredentialStore(e,t);return}const r=resolveStateClientCredentialEnvironment(t);const i=getOpenClawDatabaseMaintenanceScope();const a=t.capture??getUpdateDoctorMigrationSource(t.path)??(isPostgresSqlConnection(e)?void 0:getDoctorMigrationBackup(e,{path:t.path,env:r??t.env,tables:[...CLIENT_CREDENTIAL_SOURCE_TABLES,`sqlite_stat1`,`sqlite_stat4`]})?.capture);if(!i?.ownsSchemaMaintenance||!a||a.path!==t.path||!a.generation)throw new Error(`Client credentials require backed-up migration custody; stop the app and run openclaw doctor --fix.`);if(!r)throw new Error(`Client credentials in an auxiliary shared database require explicit recovery; preserve the source database.`);assertStateDatabaseAccessAllowed(t.path);i.assertAdmission();a.assertCurrent();const o=sourceRows(e,n||t.fromVersion<29-1);const s=!n||tableExists(e,`device_auth_tokens`);validateSource(o,n?`require-valid`:`preserve-for-doctor`);const c=extractSocket(o.approvals[0]);const l=readClientCredentialFileIdentity(t.path);if(!l)throw new Error(`Client credential source disappeared before migration.`);const u=tableExists(e,`schema_meta`);const d=t.fromVersion===1&&!u;const f=(n||d)&&!u?void 0:e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();const p=isPostgresSqlConnection(e)?readEngineAnchor(e.anchor,`identity`,true)?.[0]:void 0;const m={format:1,source:{kind:`canonical`,engine:isPostgresSqlConnection(e)?`postgres`:n?`native-v0`:`sqlite`,identity:p?String(p.store_id):`${l.path}:${String(f?.created_at??0)}`,generation:a.generation,sha256:hashClientCredentialRows(o,n?{authTablePresent:s}:void 0),destinationVersion:1},sharedFile:l,legacyImports:resolveClientCredentialLegacyImportClaims(e,{identities:o.identities,nativeBootstrap:n,authTablePresent:s})};const h=t.custody===void 0?openClientCredentialCustody(r,{createIfMissing:true,migration:true}):t.custody;if(!h)throw new Error(`Client credential migration could not acquire local custody.`);const close=()=>{if(t.custody===void 0)h.close()};try{const t=beginUpdateSqliteCompanion(h.database,h.path,h.created);runSqliteImmediateTransactionSync(h.database,()=>{const e=h.database;const t=readClientCredentialReceipt(e);if(t)m.legacyImports={...m.legacyImports,...t.receipt.legacyImports};if(t?.phase===`complete`&&t.receipt.source?.kind===`independent`&&n&&t.receipt.source.identity===`${l.dev}:${l.ino}`&&t.receipt.source.sha256===m.source.sha256&&t.receipt.sharedFile?.path===l.path&&t.receipt.sharedFile.dev===l.dev&&t.receipt.sharedFile.ino===l.ino){writeClientCredentialReceipt(e,m,`copied`);return}const r=getNodeSqliteKysely(e);for(const t of[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`,`client_credential_migration`])executeSqliteQuerySync(e,r.deleteFrom(t));for(const t of chunkItems(o.identities,500))executeSqliteQuerySync(e,r.insertInto(`device_identities`).values(t));for(const t of chunkItems(o.tokens,500))executeSqliteQuerySync(e,r.insertInto(`device_auth_tokens`).values(t));for(const t of chunkItems(o.origins,500))executeSqliteQuerySync(e,r.insertInto(`gateway_origin_device_tokens`).values(t));if(c.socket)executeSqliteQuerySync(e,r.insertInto(`native_exec_socket_credentials`).values(c.socket));executeSqliteQuerySync(e,r.insertInto(`client_credential_migration`).values({version:1,source_store:serializeClientCredentialReceipt(m,path.dirname(path.dirname(h.path))),phase:`copied`,updated_at_ms:Date.now()}))});if(!stageSqliteTransactionState(e,{stage(){},prepareCommit(){if(!d)return;const t=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(!t||!m.source)throw new Error(`Historical client credential source identity was not published.`);m.source.identity=`${l.path}:${String(t.created_at)}`;runSqliteImmediateTransactionSync(h.database,()=>writeClientCredentialReceipt(h.database,m,`copied`))},commit(){try{if(n&&!isPostgresSqlConnection(e)&&tableExists(e,`schema_meta`)){const t=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(m.source){m.source.engine=`sqlite`;m.source.identity=`${l.path}:${String(t?.created_at??0)}`}}runSqliteImmediateTransactionSync(h.database,()=>writeClientCredentialReceipt(h.database,m,`complete`));t?.complete()}finally{close()}},rollback:close,invalidate:close}))throw new Error(`Client credential migration has no source commit lifecycle.`);i.assertAdmission();a.assertCurrent();if(o.approvals[0]&&c.policy!==void 0)executeSqliteQuerySync(e,getNodeSqliteKysely(e).updateTable(`exec_approvals_config`).set({raw_json:c.policy,socket_path:null,has_socket_token:0}).where(`config_key`,`=`,`current`));e.exec(`DROP TABLE IF EXISTS device_auth_tokens; DROP TABLE IF EXISTS device_identities; DROP TABLE IF EXISTS gateway_origin_device_tokens;`)}catch(e){close();throw e}}
//!src/config/legacy-workboard-database.ts
const log=createSubsystemLogger(`config`);function normalizeLegacyWorkboardDatabaseConfig(e,t){if(!isRecord(e)||!isRecord(e.database))return e;const n=e.database;if(resolveConfigEnvVars(n.engine,t)!==`postgres`||n.families!==void 0)return e;const r=resolveStateDir(t);const i=path.join(r,`state/openclaw.sqlite`);const a=path.join(r,`plugins/workboard/workboard.sqlite`);if(!fs.existsSync(i)||!fs.existsSync(a))return e;if(!runSqliteReadOnlyWorkerSync(i,void 0,`state-sqlite-populated`)||readBackupEngine(a).engine!==`postgres`)return e;log.warn(`Preserving the 2026.11.1 Workboard-only PostgreSQL setting: Workboard remains on PostgreSQL; shared state and other families remain on SQLite. The next config write records this explicitly.`);return{...e,database:{...n,engine:`sqlite`,families:{workboard:{engine:`postgres`}}}}}
//!src/config/io.read-helpers.ts
function coerceConfig(e){return asOptionalRecord(e)??{}}function normalizeConfigIoDeps(e={}){const t=e.env??process.env;return{fs:e.fs??fs,env:t,lowerPrecedenceEnv:e.lowerPrecedenceEnv??{},homedir:e.homedir??(()=>resolveRequiredHomeDir(t,os.homedir)),configPath:e.configPath??``,mapIncludePath:e.mapIncludePath??(e=>e),logger:e.logger??console,measure:e.measure??(async(e,t)=>await t()),suppressFutureVersionWarning:e.suppressFutureVersionWarning??(isTruthyEnvValue(t.OPENCLAW_UPDATE_IN_PROGRESS)||isTruthyEnvValue(t.OPENCLAW_UPDATE_POST_CORE)),observe:e.observe??true}}function parseConfigJson5(e){try{return{ok:true,parsed:parseJsonWithJson5Fallback(e,JSON5)}}catch(e){return{ok:false,error:String(e)}}}function resolveConfigIncludesForRead(e,t,n,r,i,a,o){const s=resolveIncludeRoots(n.env,n.homedir);const recordIncludeWatchPath=e=>{a?.add(path.normalize(e))};const recordIncludeTarget=(e,n)=>{if(!i)return;const r=path.normalize(e);try{i[r]=path.normalize(n??resolveConfigIncludeWritePath({configPath:t,includePath:e,allowedRoots:s}))}catch{}};return resolveConfigIncludes(e,t,{readFile:e=>n.fs.readFileSync(e,`utf-8`),mapPath:n.mapIncludePath,onLexicalPath:recordIncludeWatchPath,onIncludeResolved:o,readFileWithGuards:({includePath:e,resolvedPath:t,rootRealDir:i})=>{try{const a=readConfigIncludeFileWithGuards({includePath:e,resolvedPath:t,rootRealDir:i,ioFs:n.fs,onResolvedPath:e=>{recordIncludeWatchPath(e);recordIncludeTarget(t,e)}});if(r)r[path.normalize(t)]=hashConfigIncludeRaw(a);return a}catch(e){const n=collectErrorGraphCandidates(e,e=>[e.cause]).some(e=>extractErrorCode(e)===`ENOENT`);if(r&&n)r[path.normalize(t)]=hashConfigIncludeRaw(null);if(n)recordIncludeTarget(t);throw e}},parseJson:e=>JSON5.parse(e)},{allowedRoots:s})}function resolveConfigForRead(e,t,n={}){if(e&&typeof e===`object`&&`env`in e)applyConfigEnvVars(e,t,{lowerPrecedenceEnv:n});const r=[];const i=/* @__PURE__ */ new Map;const a=/* @__PURE__ */ new Map;const o=resolveConfigEnvVars(e,t,{onMissing:e=>r.push(e),onPendingEnvSecretRef:(e,t)=>i.set(t,e),onResolvedEnvSecretRef:(e,t)=>a.set(t,e)});return{resolvedConfigRaw:normalizeLegacyWorkboardDatabaseConfig(projectUpdateRehearsalDatabaseConfig(o,t),t),envSnapshotForRestore:cloneEnvWithPlatformSemantics(t),envWarnings:r,resolutionFacts:createConfigResolutionFacts(r,i,coerceConfig(o).secrets?.defaults?.env,a)}}
//!src/config/agent-store-source.ts
function readAgentStorePathsFromConfig(e,t){const n=cloneEnvWithPlatformSemantics(e);n.OPENCLAW_STATE_DIR=t;const r=resolveConfigPath(n,t);let i=`{}`;try{i=fs.readFileSync(r,`utf8`)}catch(e){ignoreMissingPath(e)}const a=parseConfigJson5(i);if(!a.ok)throw new Error(`Cannot parse agent storage configuration at ${r}.`);const o=normalizeConfigIoDeps({env:n,configPath:r,observe:false});const s=resolveConfigIncludesForRead(a.parsed,r,o);if(!isRecord(s)||[`agents`,`session`].some(e=>s[e]!==void 0&&!isRecord(s[e])))throw new Error(`Invalid agent storage configuration at ${r}.`);const c=readAgentRosterProperty(s);const hasValidStorageLocator=e=>isRecord(e)&&(e.agentDir===void 0||typeof e.agentDir===`string`);if(c&&(c.kind===`entries`?!isRecord(c.value)||Object.values(c.value).some(e=>!hasValidStorageLocator(e)):!Array.isArray(c.value)||c.value.some(e=>!hasValidStorageLocator(e)||typeof e.id!==`string`)))throw new Error(`Invalid agent roster at ${r}.`);if(isRecord(s.session)&&s.session.store!==void 0&&typeof s.session.store!==`string`)throw new Error(`Invalid session storage configuration at ${r}.`);const l=resolveConfigForRead(s,n);if(l.envWarnings.some(e=>e.configPath===`session.store`||e.configPath.endsWith(`.agentDir`)||e.configPath.startsWith(`agents.list[`)&&e.configPath.endsWith(`.id`)||e.configPath===`acp.defaultAgent`||e.configPath.startsWith(`acp.allowedAgents`)||e.configPath.endsWith(`.runtime.type`)||e.configPath.endsWith(`.runtime.acp.agent`)))throw new Error(`Unresolved environment reference in agent storage configuration at ${r}.`);const u=coerceConfig(l.resolvedConfigRaw);const d=listAgentIds(u);const f=new Set(d.map(e=>path.join(resolveEffectiveAgentDir(u,e,{env:n}),`openclaw-agent.sqlite`)));const p=new Set(listConfiguredSessionStoreAgentIds(u).map(e=>resolveSessionStorePathCore(u.session?.store,{agentId:e,env:n})));for(const e of p)for(const t of listSqliteTargetCandidatePathsForSessionStorePath(e))f.add(t);for(const e of[n.OPENCLAW_AGENT_DIR,n.PI_CODING_AGENT_DIR])if(e?.trim())f.add(path.join(resolveUserPath(e,n),`openclaw-agent.sqlite`));return[...f]}
//!src/state/openclaw-agent-db-discovery-paths.ts
function resolveOpenClawAgentDatabaseDiscoveryPaths(e){return[resolveOpenClawAgentSqlitePath(e),resolveIncognitoOpenClawAgentSqlitePath(e)].map(t=>path.join(e.agentDir,path.basename(t)))}
//!src/state/openclaw-state-db-initialization.ts
function prepareStateDatabaseInitialization(e,t,n=[]){try{if(resolveSqliteDatabaseFilePaths(resolveQuarantineStorePath(t)).some(e=>fs.lstatSync(e,{throwIfNoEntry:false})))return{kind:`existing`};const r=resolveOpenClawStateDirForDatabasePath(e);const i=/* @__PURE__ */ new Set([...n,...readAgentStorePathsFromConfig(t,r)]);const a=path.join(r,`agents`);if(fs.lstatSync(a,{throwIfNoEntry:false})?.isSymbolicLink())return{kind:`unavailable`};let o=[];try{o=fs.readdirSync(a,{withFileTypes:true})}catch(e){ignoreMissingPath(e)}for(const e of o){if(!e.isDirectory()&&!e.isSymbolicLink())continue;const n=path.join(a,e.name,`agent`);if(e.isSymbolicLink()||fs.lstatSync(n,{throwIfNoEntry:false})?.isSymbolicLink())return{kind:`unavailable`};for(const r of resolveOpenClawAgentDatabaseDiscoveryPaths({agentDir:n,agentId:e.name,env:t}))i.add(r)}for(const e of i){const t=resolveSqliteDatabaseFilePaths(e);const n=fs.lstatSync(e,{throwIfNoEntry:false});if(n&&(!n.isFile()||n.size>0)||t.slice(1).some(e=>fs.lstatSync(e,{throwIfNoEntry:false})))return{kind:`existing`}}if(resolveSqliteDatabaseFilePaths(e).some(e=>fs.lstatSync(e,{throwIfNoEntry:false})))return{kind:`existing`,nativeBootstrapEligible:true};return{kind:`fresh`}}catch{return{kind:`unavailable`}}}
//!src/infra/dedupe.ts
function createDedupeCache(e){const t=resolveNonNegativeIntegerOption(e.ttlMs,0);const n=resolveNonNegativeIntegerOption(e.maxSize,0);const r=/* @__PURE__ */ new Map;let i=Number.POSITIVE_INFINITY;let a=Number.NEGATIVE_INFINITY;let o=true;const prune=e=>{const a=t>0?e-t:void 0;if(a!==void 0&&a>=i){i=Number.POSITIVE_INFINITY;for(const[e,t]of r)if(t.recordedAt<=a)r.delete(e);else if(t.recordedAt<i){i=t.recordedAt;if(o)break}}if(n<=0){r.clear();i=Number.POSITIVE_INFINITY;return}pruneMapToMaxSize(r,n)};const hasUnexpired=(e,n,i)=>{const a=r.get(e);if(!a)return false;if(t>0&&n-a.recordedAt>=t){r.delete(e);return false}if(i){a.recordedAt=n;r.delete(e);r.set(e,a)}return true};return{check:(e,n,s)=>{if(!e)return false;const c=n??Date.now();if(t>0){if(c<i)i=c;if(o){o=c>=a;a=c}}if(hasUnexpired(e,c,true))return true;r.set(e,{recordedAt:c,...s?{ownerToken:s}:{}});prune(c);return false},peek:(e,t=Date.now())=>{if(!e)return false;return hasUnexpired(e,t,false)},delete:(e,t)=>{if(!e)return;if(t&&r.get(e)?.ownerToken!==t)return;r.delete(e)},clear:()=>{r.clear();i=Number.POSITIVE_INFINITY;a=Number.NEGATIVE_INFINITY;o=true},size:()=>r.size}}
//!src/state/openclaw-state-db-permissions.ts
const OPENCLAW_STATE_DIR_MODE=448;const OPENCLAW_STATE_FILE_MODE=384;const stateDbLog$2=createSubsystemLogger(`state/db`);const chmodWarnedTargets=createDedupeCache({ttlMs:0,maxSize:4096});function bestEffortChmodSync(e,t){let n;try{n=applyPrivateModeSync(e,t)}catch(t){if(!hasErrnoCode(t,`EPERM`)||!process.getuid||statSync(e).uid===process.getuid())throw t;n={applied:false,error:t}}if(n.applied||chmodWarnedTargets.check(e))return;stateDbLog$2.warn(`skipped permission hardening for ${e}: ${String(n.error)}`)}const PRIVATE_STATE_STORES=Object.freeze([[`client`,`credentials.sqlite`],[`control`,`services.sqlite`]]);function ensureOpenClawStatePermissions(e,t,n={}){const r=path.dirname(e);const i=resolveOpenClawStateSqlitePath(t);const a=path.dirname(i);const o=path.resolve(e)===path.resolve(i);if(o&&r!==a)throw new Error(`OpenClaw state database path resolved outside its state dir: ${e}`);const s=existsSync(r);if(n.createDirectory)mkdirSync(r,{recursive:true,mode:OPENCLAW_STATE_DIR_MODE});if(o||!s)bestEffortChmodSync(r,OPENCLAW_STATE_DIR_MODE);for(const t of resolveSqliteDatabaseFilePaths(e))if(existsSync(t))try{bestEffortChmodSync(t,OPENCLAW_STATE_FILE_MODE)}catch(n){if(t===e||!hasErrnoCode(n,`ENOENT`))throw n}}
//!src/state/openclaw-state-db-open.ts
const stateDbLog$1=createSubsystemLogger(`state/db`);function assertStateDatabaseIntegrityBeforeMutation(e,t){if(getStateRuntimeSchemaAdmission(e))return;const n=readStateSchemaContentVersion(e);if(n===40)return;if(n===0&&inspectStateSqlite(e).hasExistingData||n>0&&n<40)stateDbLog$1.info(`state database schema migration pending; verifying integrity first`,{fromVersion:n,path:t,toVersion:40});assertStateDatabaseIntegrityOnce(e,t)}function openUnpublishedStateDatabase(e){return runStateOpenSteps(openUnpublishedStateDatabaseSteps(e))}function runStateOpenSteps(e){let t=e.next();while(!t.done)try{t=e.next(t.value.run())}catch(n){t=e.throw(n)}return t.value}async function openUnpublishedStateDatabaseAsync(e){return runStateOpenStepsAsync(openUnpublishedStateDatabaseSteps(e))}async function runStateOpenStepsAsync(e){resolveSqliteInspectionSignal(getAsyncWorkSignal())?.throwIfAborted();let t=withEngineStoreAdmission(()=>e.next());while(!t.done)try{const n=await t.value.runAsync();t=withEngineStoreAdmission(()=>e.next(n))}catch(n){t=withEngineStoreAdmission(()=>e.throw(n))}return t.value}function*openUnpublishedStateDatabaseSteps(e,t=false){const n=getSqliteWorkerExistingDatabaseIdentity(e.pathname);const r=e.existingSchema||n?statSync(e.pathname,{bigint:true}):statSync(e.pathname,{bigint:true,throwIfNoEntry:false});if(n&&(!r||`file:${r.dev}:${r.ino}`!==n))throw new Error(`SQLite database file identity changed before existing-only open`);if(!r&&!t){let t;const n={databasePath:e.pathname,busyTimeoutMs:e.busyTimeoutMs};try{yield{run(){withStateDatabaseSchemaMaintenance(n,()=>{t=runStateOpenSteps(openUnpublishedStateDatabaseSteps(e,true))})},async runAsync(){await withStateDatabaseSchemaMaintenanceAsync(n,async()=>{t=await runStateOpenStepsAsync(openUnpublishedStateDatabaseSteps(e,true))})}};if(!t)throw new Error(`Shared-state acquisition did not return its native handle.`);return t}catch(n){const r=t?openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle(t):[];if(r.length>0)throw createSqliteLifecycleAggregateError([n,...r],`Fresh shared-state acquisition and cleanup failed for ${e.pathname}.`,n);throw n}}if(r&&!r.isFile())throw new Error(`Existing shared-state database must be a regular file: ${e.pathname}`);const i=prepareStateDatabaseInitialization(e.pathname,e.env,e.initializationAgentPaths);if(!r){quarantineOrphanedSqliteSidecars(e.pathname);ensureOpenClawStatePermissions(e.pathname,e.env,{createDirectory:true});prepareSqliteDatabaseDirectory(e.pathname)}return yield*openNativeStateDatabase(e,i,r)}function*openNativeStateDatabase(e,t,n){const{busyTimeoutMs:r,lockFailureReporting:i}=e;const assertSameFile=()=>{if(n){const t=statSync(e.pathname,{bigint:true});if(!t.isFile()||t.dev!==n.dev||t.ino!==n.ino||readDatabaseIdentityBirthtime(t)!==readDatabaseIdentityBirthtime(n))throw new Error(`Existing shared-state database generation changed: ${e.pathname}`)}};const a=openTrackedStateDatabase(e.pathname,{existingOnly:n!==void 0,expectedIdentity:n?`file:${n.dev}:${n.ino}`:void 0});let o;let s=a;let c;try{assertSameFile();enableNodeSqliteKyselyStatementCache(a);setSqliteBusyTimeout(a,r);const l=stateEngineInput();let u;const initializeSqliteSchema=()=>{e.ensureSchema(a,t,u);ensureOpenClawStatePermissions(e.pathname,e.env);assertSameFile()};const openSelected=(n=false)=>{if(c){runWithSqliteBusyTimeout(a,r,initializeSqliteSchema,{lockFailureReporting:i});return a}admitStateSchemaFacts(a,e.pathname);if(l&&isNativeClientCredentialBootstrap(a))throw new Error(`Native credential bootstrap cannot become a PostgreSQL anchor. Start the Gateway once on SQLite and run openclaw doctor --fix, then use openclaw database port before selecting PostgreSQL.`);return openEngineStore({anchor:a,schema:stateEngineSchema,input:l,existingOnly:e.existingSchema,inspectSqlite:()=>inspectStateSqlite(a),prepareAnchor:()=>{},onFreshAnchor:t=>bindFreshClientCredentialStore(t,{path:e.pathname,env:e.env,custody:u}),admitPostgres:(t,n)=>{admitStatePostgres(t,n);if(n){migrateCronDefaultStoreIdentity(t,{previousVersion:0,legacyDefaultStoreKey:resolveCronIdentityMigrationDefaultStoreKey(e.env),fresh:true});bindFreshClientCredentialStore(t,{path:e.pathname,env:e.env,custody:u})}},beforeMigrate:(t,n,r)=>{prepareClientCredentialMigration(t,{path:e.pathname,env:e.env,fromVersion:n,custody:u});if(n===29-1)advanceStateSchemaContentVersion(t,{fromVersion:n,toVersion:29});if(n===34-1)migrateCronDefaultStoreIdentity(t,{previousVersion:n,legacyDefaultStoreKey:resolveCronIdentityMigrationDefaultStoreKey(e.env),sourceTables:r})},closeOnFailure:(e,t)=>{s=e;throw t},openSqlite:()=>{assertOpenClawStateWriteAllowed({database:a,databasePath:e.pathname,env:e.env});if(e.existingSchema){assertSameFile();e.ensureSchema(a,t,u);assertSameFile();c={db:a,path:e.pathname,walMaintenance:{checkpoint:()=>false,stop:async()=>{},close:()=>true,reclaimFreePages:createSqliteWalReclamationResult}};return}ensureOpenClawStatePermissions(e.pathname,e.env);const s=runWithSqliteBusyTimeout(a,r,()=>{assertSupportedStateSchemaVersion(a,e.pathname);assertStateDatabaseIntegrityBeforeMutation(a,e.pathname);configureSqlitePreSchemaPragmas(a,{busyTimeoutMs:r});o=configureSqliteConnectionPragmas(a,{busyTimeoutMs:r,databaseLabel:`openclaw-state`,databasePath:e.pathname,onCheckpointError:t=>stateDbLog$1.warn(`Shared-state WAL maintenance failed`,{error:formatErrorMessage(t),path:e.pathname,checkpoint:o?.health}),runMaintenance:t=>{try{assertStateDatabaseAccessAllowed(e.pathname)}catch(t){if(!(t instanceof StateDatabaseAdmissionPendingError)&&!(t instanceof StateDatabaseOfflineMaintenanceError))throw t;stateDbLog$1.debug(`Shared-state WAL maintenance deferred during offline maintenance`,{path:e.pathname});return false}return t()},isScheduledMaintenanceSuspended:captureSqliteWorkerWalMaintenanceSuspension(),foreignKeys:true,synchronous:`NORMAL`});if(!n)initializeSqliteSchema();return o},{lockFailureReporting:i});c={db:a,path:e.pathname,walMaintenance:s}}})};const d=e.existingSchema?void 0:()=>{assertSameFile();openSelected(true)};yield{run(){s=l?openSelected():runUpdateSqliteMigration(a,e.pathname,openSelected,{beforeExclusive:d,created:n===void 0})},async runAsync(){let t=e.clientCredentialMigrationFromVersion;if(t===void 0){if(l&&inspectStateSqlite(a).hasEngineAnchor){const n=await executeExistingOpenClawStateRead({path:e.pathname,env:e.env},{type:`stateBootstrap.inspect`,input:{pathname:e.pathname,supportedVersion:40,purpose:`maintenance`,scope:`state`}},{signal:resolveSqliteInspectionSignal(getAsyncWorkSignal()),current:true});if(!n||n.inspection.schemas.indeterminate.length>0||n.inspection.schemas.incompatible.length>0)throw new Error(`Cannot prepare PostgreSQL credentials without its supported state schema. Restore the matching state schema and anchor before retrying Doctor.`);t=n.inspection.schemas.pendingMigrations?.[0]?.foundVersion??40}else t=l||!n?0:readStateSchemaContentVersion(a)}const r=await prepareClientCredentialMigrationCustody({path:e.pathname,env:e.env,fromVersion:t});u=r??null;try{if(l){const open=()=>{s=withEngineStoreAdmission(openSelected);return s};s=r?await runUpdateSqliteMigrationAsync(r.database,r.path,open,{created:r.created,retainExclusive:true}):open()}else s=await runUpdateSqliteMigrationAsync(a,e.pathname,()=>{assertSameFile();return openSelected()},{beforeExclusive:d,created:n===void 0,companions:r?[{database:r.database,path:r.path,created:r.created}]:[]})}finally{u=void 0;r?.close()}}};if(c)return c;assertOpenClawStateWriteAllowed({database:s,databasePath:e.pathname,env:e.env});return{db:s,path:e.pathname,walMaintenance:{checkpoint:()=>false,stop:async()=>{},close:()=>true,reclaimFreePages:createSqliteWalReclamationResult}}}catch(t){const n=openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle({db:s,path:e.pathname,walMaintenance:o});if(t instanceof Error&&(isSqliteSchemaVersionError(t)||isTerminalSqliteIntegrityError(t)))e.recordOpenFailure(e.pathname,t);if(n.length>0)throw createSqliteLifecycleAggregateError([t,...n],`OpenClaw state database acquisition and cleanup failed for ${e.pathname}.`,t);throw t}}
//!src/infra/sqlite-index-schema.ts
const SQLITE_IDENTIFIER_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/u;function foreignKeyMismatch(e){if(!(e instanceof Error)||e.name!==`SqliteIntegrityError`||!e.message.startsWith(`SQLite foreign_key_check failed for `)||!(e.cause instanceof Error)||!(`code`in e.cause)||e.cause.code!==`ERR_SQLITE_ERROR`)return;const t=/^foreign key mismatch - "[A-Za-z_][A-Za-z0-9_]*" referencing "([A-Za-z_][A-Za-z0-9_]*)"$/u.exec(e.cause.message);return t?.[1]?{error:e,parentTable:t[1]}:void 0}function repairCanonicalSqliteIndexes(e,t,n,r={}){const i=/* @__PURE__ */ new Set;let a=r.deferredForeignKeyMismatch;runSqliteSchemaReadSnapshotSync(e,()=>{const o=createSqliteTableContractReader(e);if(!hasCanonicalSqliteSchemaFingerprint(n,o)){const e=getCanonicalSqliteNamedIndexContracts(n);const a=/* @__PURE__ */ new Map;for(const t of e){assertSqliteIdentifier(t.name);assertSqliteIdentifier(t.tableName);const e=a.get(t.tableName)??[];e.push(t);a.set(t.tableName,e)}for(const e of getCanonicalSqliteTableNames(n)){assertSqliteIdentifier(e);const n=o(e);if(!n)continue;const s=a.get(e)??[];const c=new Set(s.map(e=>e.name));const l=n.indexes;const u=l.find(e=>e.unique===1&&e.origin===`c`&&e.name!==null&&!c.has(e.name));if(u)throw new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${t}: unexpected unique index ${u.name}`);for(const e of s){const t=l.find(t=>t.name===e.name);if(JSON.stringify(t)!==JSON.stringify(e.fingerprint)){if(r.nonUniqueOnly&&(e.unique||t?.unique===1))throw new SqliteSchemaMismatchError(`Canonical unique index ${e.name} requires full admission`);i.add(e)}}}}if(r.verifyPhysicalIntegrity!==false)try{assertSqliteIntegrity(e,t,r.integrity)}catch(e){a=foreignKeyMismatch(e);if(!a)throw e}if(a&&![...i].some(e=>e.unique&&e.tableName===a?.parentTable))throw a.error;if(i.size===0)r.validateUnchanged?.(o)});if(i.size===0)return[];const o=`repair_canonical_indexes`;let s;e.exec(`SAVEPOINT ${o};`);try{for(const t of i){s=t;e.exec(`SAVEPOINT repair_canonical_index;`);try{e.exec(`DROP INDEX IF EXISTS main.${t.name};`);const n=t.unique?`CREATE UNIQUE INDEX`:`CREATE INDEX`;e.exec(`${n} main.${t.name} ${t.definition};`)}catch(n){e.exec(`ROLLBACK TO SAVEPOINT repair_canonical_index;`);if(r.allowMissingColumns&&isMissingColumnError(n)){i.delete(t);continue}throw n}finally{e.exec(`RELEASE SAVEPOINT repair_canonical_index;`)}}if(i.size===0){if(a)throw a.error;r.validateUnchanged?.();e.exec(`RELEASE SAVEPOINT ${o};`);return[]}for(const n of new Set([...i].map(e=>e.tableName)))assertSqliteTableIntegrity(e,t,n);r.validateAfterRepair?.();if(a)assertSqliteIntegrity(e,t,{...r.integrity,schemaOnly:void 0});e.exec(`RELEASE SAVEPOINT ${o};`)}catch(n){try{e.exec(`ROLLBACK TO SAVEPOINT ${o};`)}finally{e.exec(`RELEASE SAVEPOINT ${o};`)}if(isSqliteSchemaMismatchError(n)||n instanceof Error&&isTerminalSqliteIntegrityError(n))throw n;const i=n instanceof Error?n.message:String(n);if(r.nonUniqueOnly&&isMissingColumnError(n))throw new SqliteSchemaMismatchError(i,{cause:n});throw new Error(`SQLite canonical index ${s?.name??`repair`} failed for ${t}: ${i}`,{cause:n})}return[...i].map(e=>e.name).toSorted()}function assertSqliteIdentifier(e){if(!SQLITE_IDENTIFIER_PATTERN.test(e))throw new Error(`invalid SQLite identifier: ${e}`)}function isMissingColumnError(e){return e instanceof Error&&e.code===`ERR_SQLITE_ERROR`&&/^no such column:/iu.test(e.message)}
//!src/infra/sqlite-strict.ts
const STRICT_MIGRATION_TABLE_PREFIX=`__openclaw_strict_migration_`;const SQLITE_ROWID_ALIASES=[`_rowid_`,`rowid`,`oid`];function readMainTableList(e,t={}){return e.prepare(`PRAGMA table_list`).all().filter(e=>e.schema===`main`&&typeof e.name===`string`&&(t.includeInternal===true||!e.name.startsWith(`sqlite_`)))}function hasNonStrictSqliteTables(e){return readMainTableList(e).some(e=>e.type===`table`&&Number(e.strict)!==1)}function readTableColumns(e,t){return e.prepare(`PRAGMA table_xinfo(${quoteSqliteIdentifier(t)})`).all()}function readVisibleColumns(e,t){return readTableColumns(e,t).filter(e=>Number(e.hidden??0)===0).map(e=>{if(typeof e.name!==`string`||e.name.length===0)throw new Error(`SQLite table ${t} has an invalid column name`);return e.name})}function readTableRowidModel(e,t,n){if(Number(n.wr??0)===1)return{alias:null,storage:`without-rowid`};const r=readTableColumns(e,t);const i=e.prepare(`SELECT 1 AS found FROM pragma_index_list(?) WHERE origin = 'pk' LIMIT 1`).get(t);return resolveTableRowidModel(t,r,Boolean(i))}function resolveTableRowidModel(e,t,n){const r=t.filter(e=>Number(e.pk??0)>0);const i=r[0]?.type;if(r.length===1&&typeof i===`string`&&i.toUpperCase()===`INTEGER`&&!n)return{alias:null,storage:`integer-primary-key`};const a=new Set(t.flatMap(e=>typeof e.name===`string`?[e.name.toLowerCase()]:[]));const o=SQLITE_ROWID_ALIASES.find(e=>!a.has(e))??null;if(!o)throw new Error(`SQLite table ${e} shadows every rowid alias; its implicit rowids cannot be migrated safely`);return{alias:o,storage:`implicit`}}function canonicalStrictTablesFromCatalog(e){return e.tables.map(e=>{if(e.sql===null)throw new Error(`Canonical SQLite table ${e.name} has no CREATE statement`);const t=e.withoutRowid===1?{alias:null,storage:`without-rowid`}:resolveTableRowidModel(e.name,e.columns,e.indexes.some(e=>e.origin===`pk`));return{columns:e.columns.filter(e=>e.hidden===0).map(e=>e.name),createSql:e.sql,name:e.name,rowidAlias:t.alias,rowidStorage:t.storage,usesAutoincrement:/\bAUTOINCREMENT\b/iu.test(e.sql)}}).toSorted((e,t)=>e.name.localeCompare(t.name))}function readCanonicalStrictTables(e){const t=openNodeSqliteDatabase(`:memory:`);try{t.exec(e);const n=readMainTableList(t).filter(e=>e.type===`table`);const r=n.filter(e=>Number(e.strict??0)!==1).map(e=>e.name);if(r.length>0)throw new Error(`Canonical SQLite schema contains non-STRICT tables: ${r.toSorted().join(`, `)}`);return n.map(e=>{const n=t.prepare(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`).get(e.name);if(typeof n?.sql!==`string`)throw new Error(`Canonical SQLite table ${e.name} has no CREATE statement`);const r=readTableRowidModel(t,e.name,e);return{columns:readVisibleColumns(t,e.name),createSql:n.sql,name:e.name,rowidAlias:r.alias,rowidStorage:r.storage,usesAutoincrement:/\bAUTOINCREMENT\b/iu.test(n.sql)}}).toSorted((e,t)=>e.name.localeCompare(t.name))}finally{t.close()}}function rewriteCreateTableName(e,t){const n=e.indexOf(`(`);if(n===-1)throw new Error(`Canonical SQLite table CREATE statement has no column list`);return`CREATE TABLE ${quoteSqliteIdentifier(t)} ${e.slice(n)}`}function readPreservedSchemaObjects(e,t){return e.prepare(`SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE type IN ('index', 'trigger', 'view')`).all().flatMap(e=>{if(e.type!==`index`&&e.type!==`trigger`&&e.type!==`view`||typeof e.name!==`string`||typeof e.tbl_name!==`string`||typeof e.sql!==`string`||e.type===`index`&&!t.has(e.tbl_name))return[];return[{name:e.name,sql:e.sql,type:e.type}]}).toSorted((e,t)=>{const n={view:0,index:1,trigger:2};return n[e.type]-n[t.type]||e.name.localeCompare(t.name)})}function readAutoincrementHighWater(e,t){if(!e.prepare(`SELECT 1 AS found FROM sqlite_schema WHERE type = 'table' AND name = 'sqlite_sequence'`).get())return null;const n=e.prepare(`SELECT CAST(seq AS TEXT) AS seq FROM sqlite_sequence WHERE name = ?`).get(t);if(n===void 0)return null;const r=typeof n.seq===`string`?/^(\d+)(?:\.0+)?$/u.exec(n.seq)?.[1]:null;if(!r)throw new Error(`SQLite table ${t} has an invalid AUTOINCREMENT high-water mark (${typeof n.seq}: ${String(n.seq)})`);return r}function restoreAutoincrementHighWater(e,t,n){if(n===null)return;const r=readAutoincrementHighWater(e,t);const i=r===null||BigInt(n)>BigInt(r)?n:r;e.prepare(`DELETE FROM sqlite_sequence WHERE name = ?`).run(t);e.prepare(`INSERT INTO sqlite_sequence (name, seq) VALUES (?, CAST(? AS INTEGER))`).run(t,i)}function assertMatchingColumns(e,t,n){const r=new Set(t);const i=new Set(n);const a=n.filter(e=>!r.has(e));const o=t.filter(e=>!i.has(e));if(a.length===0&&o.length===0)return;const s=[a.length>0?`missing ${a.join(`, `)}`:``,o.length>0?`extra ${o.join(`, `)}`:``].filter(Boolean).join(`; `);throw new Error(`SQLite table ${e} does not match its canonical columns (${s})`)}function readForeignKeysEnabled(e){const t=e.prepare(`PRAGMA foreign_keys`).get();return Number(t?.foreign_keys??0)===1}function migrateSqliteSchemaToStrictInTransaction(e,t,n={}){if(!e.isTransaction)throw new Error(`SQLite STRICT schema migration requires an active transaction`);const r=n.expectedSchema??t;const i=typeof r===`string`?readGeneratedSqliteFingerprint(r):void 0;const a=i?.tableNames??(typeof r===`string`?void 0:r.tables.map(e=>e.name));const readCurrentTables=()=>new Map(readMainTableList(e).filter(e=>e.type===`table`).map(e=>[e.name,e]));let o=n.expectedSchema!==void 0&&a?readCurrentTables():/* @__PURE__ */ new Map;if(n.expectedSchema!==void 0&&a?.every(e=>Number(o.get(e)?.strict??0)===1))return{migratedTables:[]};const s=typeof r===`string`?i&&readGeneratedSqliteCatalog(r):r;const c=s?.tables.every(e=>e.strict===1);const l=s&&c?canonicalStrictTablesFromCatalog(s):readCanonicalStrictTables(t);if(n.expectedSchema===void 0||!c||l.some(e=>!o.has(e.name))){e.exec(t);o=readCurrentTables()}const u=l.filter(e=>Number(o.get(e.name)?.strict??0)!==1);if(u.length===0)return{migratedTables:[]};if(readForeignKeysEnabled(e))throw new Error(`SQLite STRICT schema migration requires foreign_keys=OFF before BEGIN`);const d=readPreservedSchemaObjects(e,new Set(u.map(e=>e.name)));for(const t of[`trigger`,`view`])for(const n of d)if(n.type===t)e.exec(`DROP ${t.toUpperCase()} ${quoteSqliteIdentifier(n.name)};`);for(const[t,n]of u.entries()){const r=`${STRICT_MIGRATION_TABLE_PREFIX}${t}_${n.name}`;if(o.has(r))throw new Error(`SQLite STRICT migration table already exists: ${r}`);const i=readVisibleColumns(e,n.name);assertMatchingColumns(n.name,i,n.columns);const a=o.get(n.name);if(!a)throw new Error(`SQLite table ${n.name} disappeared during STRICT migration`);const s=readTableRowidModel(e,n.name,a);if(s.storage!==n.rowidStorage)throw new Error(`SQLite table ${n.name} changes rowid storage from ${s.storage} to ${n.rowidStorage}; refusing an identity-changing STRICT migration`);const c=n.usesAutoincrement?readAutoincrementHighWater(e,n.name):null;e.exec(rewriteCreateTableName(n.createSql,r));const l=n.columns.map(quoteSqliteIdentifier);if(n.rowidAlias)l.unshift(quoteSqliteIdentifier(n.rowidAlias));const u=l.join(`, `);try{e.exec(`INSERT INTO ${quoteSqliteIdentifier(r)} (${u}) SELECT ${u} FROM ${quoteSqliteIdentifier(n.name)};`)}catch(e){throw new Error(`Failed migrating SQLite table ${n.name} to STRICT`,{cause:e})}e.exec(`DROP TABLE ${quoteSqliteIdentifier(n.name)};`);e.exec(`ALTER TABLE ${quoteSqliteIdentifier(r)} RENAME TO ${quoteSqliteIdentifier(n.name)};`);restoreAutoincrementHighWater(e,n.name,c)}e.exec(t);const f=e.prepare(`SELECT 1 AS found FROM sqlite_schema WHERE type = ? AND name = ? LIMIT 1`);for(const t of d)if(!f.get(t.type,t.name))e.exec(t.sql);assertSqliteIntegrity(e,n.databaseLabel??`SQLite STRICT schema migration`,{check:n.integrityCheck??`quick`,tables:u.map(e=>e.name)});return{migratedTables:u.map(e=>e.name)}}
//!packages/gateway-protocol/src/failover-reasons.ts
const FAILOVER_REASONS=[`auth`,`auth_permanent`,`format`,`rate_limit`,`overloaded`,`billing`,`server_error`,`route_unavailable`,`timeout`,`tls_certificate`,`context_overflow`,`model_not_found`,`session_expired`,`empty_response`,`no_error_details`,`unclassified`,`unknown`];
//!packages/gateway-protocol/src/schema/closed-object.ts
const identityKey=`~openclawClosedObjectIdentity`;function closedObject(e){const t=Type.Object(e,{additionalProperties:false});Object.defineProperty(t,identityKey,{value:Symbol(`closedObject`)});return t}
//!packages/gateway-protocol/src/schema/cron-shared.ts
const MAX_DATE_TIMESTAMP_MS=864e13;const CronDateTimestampMsSchema=Type.Integer({minimum:0,maximum:MAX_DATE_TIMESTAMP_MS});
//!packages/gateway-protocol/src/schema/string-literal-union.ts
function stringLiteralUnion(e){const t=e.map(e=>Type.Literal(e));return Type.Union(t)}
//!packages/gateway-protocol/src/schema/cron-automation-result.ts
const AutomationMeaningfulOutcomeSchema=stringLiteralUnion([`progress`,`done`,`blocked`,`needs_attention`]);const AutomationOutcomeSchema=Type.Union([Type.Literal(`no_change`),AutomationMeaningfulOutcomeSchema]);const AutomationResultSummarySchema=Type.String({minLength:1,maxLength:2e3,pattern:`\\S`});const AutomationMeaningfulResultSchema=closedObject({outcome:AutomationMeaningfulOutcomeSchema,summary:AutomationResultSummarySchema});const AutomationResultSchema=Type.Union([closedObject({outcome:Type.Literal(`no_change`),summary:Type.Optional(AutomationResultSummarySchema)}),AutomationMeaningfulResultSchema]);const AutomationLastMeaningfulResultSchema=closedObject({...AutomationMeaningfulResultSchema.properties,atMs:CronDateTimestampMsSchema});
//!src/cron/automation-result.ts
function parseAutomationResult(e){if(!isRecord(e))return;const t=typeof e.summary===`string`?{...e,summary:e.summary.trim()}:{...e};return Value.Check(AutomationResultSchema,t)?t:void 0}
//!src/cron/completion-status.ts
function resolveCronCompletionStatus(e){if(e.status===`error`||e.status===`skipped`)return`failed`;if(e.status!==`ok`)return`unknown`;if(e.requiredDelivery===void 0)return e.delivered===true||e.deliveryStatus===`delivered`||e.deliveryStatus===`not-requested`?`succeeded`:`unknown`;if(!e.requiredDelivery||e.deliveryStatus===`delivered`||e.deliveryStatus===`not-delivered`&&e.deliverySuppressionReason!==void 0)return`succeeded`;return e.deliveryStatus===`not-delivered`?`failed`:`unknown`}
//!src/cron/execution-error-constants.ts
const CRON_JOB_EXECUTION_TIMEOUT_ERROR=`cron: job execution timed out`;const CRON_SETUP_TIMEOUT_ERROR=`cron: isolated agent setup timed out before runner start`;const CRON_PRE_EXECUTION_TIMEOUT_ERROR=`cron: isolated agent run stalled before execution start`;const CRON_TIMEOUT_ERROR_PREFIXES=[CRON_JOB_EXECUTION_TIMEOUT_ERROR,CRON_SETUP_TIMEOUT_ERROR,CRON_PRE_EXECUTION_TIMEOUT_ERROR];function isCronTimeoutErrorText(e){return typeof e===`string`&&CRON_TIMEOUT_ERROR_PREFIXES.some(t=>e===t||e.startsWith(`${t} `))}
//!src/cron/run-diagnostics-normalize.ts
const MAX_ENTRIES=10;const MAX_ENTRY_CHARS=1e3;const MAX_SUMMARY_CHARS=2e3;function normalizeSeverity(e){return e===`info`||e===`warn`||e===`error`?e:`error`}function normalizeSource(e){switch(e){case`cron-preflight`:case`cron-setup`:case`model-preflight`:case`agent-run`:case`tool`:case`exec`:case`delivery`:return e;default:return`agent-run`}}function normalizeTimestamp$1(e,t){return typeof e===`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t()}function normalizeDiagnosticMessage(e,t){if(typeof e!==`string`)return{};const n=normalizeOptionalString(e);if(!n)return{};const r=t(n);if(r.length<=MAX_ENTRY_CHARS)return{message:r};return{message:`${truncateUtf16Safe(r,999)}…`,truncated:true}}function normalizeCronRunDiagnosticSummary(e){const t=normalizeOptionalString(e);if(!t)return;if(t.length<=MAX_SUMMARY_CHARS)return t;return`${truncateUtf16Safe(t,1999)}…`}function normalizeCronRunDiagnosticsCore(e,t){if(!e||typeof e!==`object`)return;const n=e;const r=t?.nowMs??Date.now;const i=t?.redactText??(e=>e);const a=Array.isArray(n.entries)?n.entries:[];const o=[];for(const e of a){if(!e||typeof e!==`object`)continue;const t=e;const n=normalizeDiagnosticMessage(t.message,i);if(!n.message)continue;o.push({ts:normalizeTimestamp$1(t.ts,r),source:normalizeSource(t.source),severity:normalizeSeverity(t.severity),message:n.message,...typeof t.toolName===`string`&&t.toolName.trim()?{toolName:t.toolName.trim()}:{},...typeof t.exitCode===`number`&&Number.isFinite(t.exitCode)?{exitCode:t.exitCode}:t.exitCode===null?{exitCode:null}:{},...t.truncated===true||n.truncated?{truncated:true}:{}});if(o.length>MAX_ENTRIES)o.shift()}const s=normalizeCronRunDiagnosticSummary(typeof n.summary===`string`?i(n.summary):void 0);if(o.length===0&&!s)return;return{...s?{summary:s}:{},entries:o}}
//!src/cron/run-history-detail.ts
const CRON_RUN_DETAIL_KIND=`cron-run`;const cronRunStatusSchema=_enum([`ok`,`error`,`skipped`]);const cronCompletionStatusSchema=_enum([`succeeded`,`failed`,`unknown`]);const cronDeliveryStatusSchema=_enum([`delivered`,`not-delivered`,`unknown`,`not-requested`]);const optionalCronStringSchema=string().optional().catch(void 0);const optionalNonBlankCronStringSchema=string().refine(e=>e.trim().length>0).optional().catch(void 0);const optionalCronTimestampSchema=unknown().optional().transform(e=>normalizeTimestamp(e));const optionalCronNonnegativeIntegerSchema=unknown().optional().transform(e=>asSafeIntegerInRange(e,{min:0}));const cronUsageSchema=object({input_tokens:optionalCronNonnegativeIntegerSchema,output_tokens:optionalCronNonnegativeIntegerSchema,total_tokens:optionalCronNonnegativeIntegerSchema,cache_read_tokens:optionalCronNonnegativeIntegerSchema,cache_write_tokens:optionalCronNonnegativeIntegerSchema}).transform(e=>Object.values(e).some(e=>e!==void 0)?e:void 0).optional().catch(void 0);const cronFailureNotificationDeliverySchema=looseObject({status:cronDeliveryStatusSchema,delivered:boolean().optional().catch(void 0),error:optionalCronStringSchema}).transform(({status:e,delivered:t,error:n})=>({status:e,...t!==void 0?{delivered:t}:{},...n!==void 0?{error:n}:{}})).optional().catch(void 0);const cronRunLogEntrySchema=looseObject({action:literal(`finished`),jobId:string().refine(e=>e.trim().length>0),ts:unknown().transform(e=>normalizeTimestamp(e)).pipe(number()),status:cronRunStatusSchema.optional().catch(void 0),completionStatus:cronCompletionStatusSchema.optional().catch(void 0),error:optionalCronStringSchema,errorReason:_enum(FAILOVER_REASONS).optional().catch(void 0),summary:optionalCronStringSchema,result:unknown().optional().transform(parseAutomationResult),runId:optionalNonBlankCronStringSchema,diagnostics:unknown().optional(),runAtMs:optionalCronTimestampSchema,durationMs:optionalCronNonnegativeIntegerSchema,nextRunAtMs:optionalCronTimestampSchema,triggerFired:boolean().optional().catch(void 0),model:optionalNonBlankCronStringSchema,provider:optionalNonBlankCronStringSchema,usage:cronUsageSchema,delivered:boolean().optional().catch(void 0),deliveryStatus:cronDeliveryStatusSchema.optional().catch(void 0),deliveryError:optionalCronStringSchema,deliverySuppressionReason:_enum([`empty`,`silent`,`heartbeat`,`channel_transform`]).optional().catch(void 0),failureNotificationDelivery:cronFailureNotificationDeliverySchema,delivery:custom(isJsonObject).optional().catch(void 0),sessionId:optionalNonBlankCronStringSchema,sessionKey:optionalNonBlankCronStringSchema});function parseCronRunDetailJson(e){return safeParseJson(e)}function toJsonValue(e){const t=JSON.stringify(e);return t===void 0?void 0:parseCronRunDetailJson(t)}function isJsonObject(e){return isRecord(e)}function normalizeTimestamp(e){return asSafeIntegerInRange(e,{min:0,max:MAX_DATE_TIMESTAMP_MS$1})}function parseCronRunLogEntryObject(e,t){const n=normalizeOptionalString(t?.jobId);const r=cronRunLogEntrySchema.safeParse(e);if(!r.success)return null;const i=r.data;if(n&&i.jobId!==n)return null;return{ts:i.ts,jobId:i.jobId,action:`finished`,status:i.status,completionStatus:i.completionStatus??resolveCronCompletionStatus({status:i.status,delivered:i.delivered,deliveryStatus:i.deliveryStatus}),error:i.error,errorReason:i.errorReason,summary:i.summary,result:i.result,runId:i.runId,diagnostics:normalizeCronRunDiagnosticsCore(i.diagnostics),runAtMs:i.runAtMs,durationMs:i.durationMs,nextRunAtMs:i.nextRunAtMs,triggerFired:i.triggerFired,model:i.model,provider:i.provider,usage:i.usage,delivered:i.delivered,deliveryStatus:i.deliveryStatus,deliveryError:i.deliveryError,deliverySuppressionReason:i.deliverySuppressionReason,failureNotificationDelivery:i.failureNotificationDelivery,delivery:i.delivery,sessionId:i.sessionId,sessionKey:i.sessionKey}}function cronRunLogEntryToDetail(e,t){return toJsonValue({kind:CRON_RUN_DETAIL_KIND,status:e.status,completionStatus:e.completionStatus,error:e.error??null,summary:e.summary??null,result:e.result,storeKey:t.storeKey,errorReason:e.errorReason,diagnostics:e.diagnostics,delivered:e.delivered,deliveryStatus:e.deliveryStatus,deliveryError:e.deliveryError,deliverySuppressionReason:e.deliverySuppressionReason,failureNotificationDelivery:e.failureNotificationDelivery,delivery:e.delivery,sessionId:e.sessionId,runId:e.runId,runAtMs:e.runAtMs,durationMs:e.durationMs,nextRunAtMs:e.nextRunAtMs,triggerFired:e.triggerFired,triggerStateChanged:t.triggerEval?.fired===true?t.triggerEval.stateChanged:void 0,triggerState:t.triggerEval?.fired===true&&t.triggerEval.stateChanged?t.triggerEval.state:void 0,scriptStateChanged:t.scriptResult?.scriptStateChanged===true?true:void 0,scriptState:t.scriptResult?.scriptStateChanged===true?t.scriptResult.scriptState:void 0,model:e.model,provider:e.provider,usage:e.usage})??{kind:CRON_RUN_DETAIL_KIND}}function cronRunStorageStatus(e){if(e.status===`ok`)return(e.completionStatus??resolveCronCompletionStatus({status:e.status,delivered:e.delivered,deliveryStatus:e.deliveryStatus}))===`succeeded`?`succeeded`:`failed`;return e.status===`error`&&isCronTimeoutErrorText(e.error)?`timed_out`:`failed`}
//!src/infra/state-migrations.cron-run-logs.ts
const CRON_RUN_LOG_TASK_IMPORT_MIGRATION_ID=`state:cron-run-logs-to-task-runs:v1`;const CRON_RUN_LOG_IMPORT_BATCH_SIZE=500;function collectMirroredTasks(e){const t=e.prepare(`SELECT source_id, ended_at, detail_json
FROM task_runs
WHERE runtime = 'cron' AND source_id IS NOT NULL AND detail_json IS NOT NULL`).all();const n=/* @__PURE__ */ new Map;for(const e of t){const t=e.detail_json?safeParseJsonRecord(e.detail_json):void 0;if(!e.source_id||t?.kind!==`cron-run`)continue;const r=n.get(e.source_id)??[];r.push({endedAt:normalizeSqliteNumber(e.ended_at)??null,...typeof t.runId===`string`&&t.runId?{runId:t.runId}:{}});n.set(e.source_id,r)}return n}function hasMirroredIdentity(e,t,n){return e.some(e=>t&&e.runId?e.runId===t:e.endedAt===n)}function integerToBoolean(e){return e===null||e===void 0?void 0:coerceRequiredSqliteNumber(e)!==0}function parseLegacyRow(e){const t=parseCronRunLogEntryObject(safeParseJson(e.entry_json??``),{jobId:e.job_id});if(!t)return null;return{...t,ts:normalizeSqliteNumber(e.ts)??t.ts,jobId:e.job_id,status:e.status??t.status,error:e.error??t.error,summary:e.summary??t.summary,delivered:integerToBoolean(e.delivered)??t.delivered,deliveryStatus:e.delivery_status??t.deliveryStatus,deliveryError:e.delivery_error??t.deliveryError,sessionId:e.session_id??t.sessionId,sessionKey:e.session_key??t.sessionKey,runId:e.run_id??t.runId,runAtMs:normalizeSqliteNumber(e.run_at_ms??null)??t.runAtMs,durationMs:normalizeSqliteNumber(e.duration_ms??null)??t.durationMs,nextRunAtMs:normalizeSqliteNumber(e.next_run_at_ms??null)??t.nextRunAtMs,model:e.model??t.model,provider:e.provider??t.provider}}function migrateLegacyCronRunLogsToTaskRuns(e){if(!hasLegacyCronRunLogs(e))return{imported:0,alreadyMirrored:0,malformed:0,skipped:true};const t=collectMirroredTasks(e);const n=/* @__PURE__ */ new Map;const r=e.prepare(`
INSERT INTO task_runs (
task_id, runtime, task_kind, source_id, requester_session_key, owner_key, scope_kind,
child_session_key, parent_flow_id, parent_task_id, agent_id, requester_agent_id, run_id,
label, task, status, delivery_status, notify_policy, created_at, started_at, ended_at,
last_event_at, cleanup_after, error, progress_summary, terminal_summary, terminal_outcome,
detail_json
) VALUES (
@task_id, 'cron', NULL, @source_id, '', '', 'system', @child_session_key, NULL, NULL,
NULL, NULL, @run_id, NULL, @task, @status, 'not_applicable', 'silent', @created_at,
@started_at, @ended_at, @ended_at, NULL, @error, NULL, @terminal_summary,
@terminal_outcome, @detail_json
)
`);let i=0;let a=0;let o=0;let s=0;while(true){const c=e.prepare(`SELECT * FROM cron_run_logs
ORDER BY job_id, ts, store_key, seq
LIMIT ? OFFSET ?`).all(CRON_RUN_LOG_IMPORT_BATCH_SIZE,s);if(c.length===0)break;s+=c.length;for(const e of c){const s=parseLegacyRow(e);if(!s){o++;continue}const c=`${s.jobId}\0${s.ts}`;const l=(n.get(c)??0)+1;n.set(c,l);if(hasMirroredIdentity(t.get(s.jobId)??[],s.runId,s.ts)){a++;continue}const u=`cron-runlog-import:${s.jobId}:${s.ts}:${l}`;const d=cronRunStorageStatus(s);r.run({task_id:u,source_id:s.jobId,child_session_key:s.sessionKey?.trim()||null,run_id:u,task:s.jobId,status:d,created_at:s.runAtMs??s.ts,started_at:s.runAtMs??null,ended_at:s.ts,error:s.error??null,terminal_summary:s.summary??null,terminal_outcome:d===`succeeded`?`succeeded`:null,detail_json:JSON.stringify(cronRunLogEntryToDetail(s,{storeKey:e.store_key}))});i++}}e.exec(`
DROP INDEX IF EXISTS idx_cron_run_logs_store_ts;
DROP INDEX IF EXISTS idx_cron_run_logs_job_status;
DROP INDEX IF EXISTS idx_cron_run_logs_delivery;
DROP TABLE cron_run_logs;
`);const c={imported:i,alreadyMirrored:a,malformed:o,skipped:false};const l=Date.now();e.prepare(`INSERT INTO migration_runs (id, started_at, finished_at, status, report_json)
VALUES (?, ?, ?, 'completed', ?)
ON CONFLICT(id) DO UPDATE SET
finished_at = excluded.finished_at,
status = excluded.status,
report_json = excluded.report_json`).run(CRON_RUN_LOG_TASK_IMPORT_MIGRATION_ID,l,l,JSON.stringify(c));return c}
//!src/state/agent-deletion-journal-history.ts
function hasPreJournalStateSchema(e){if(isPostgresSqlConnection(e))return false;if(readStateSchemaContentVersion(e)!==1||tableExists(e,`config_machine_state`)||tableExists(e,`agent_database_leases`)||!tableExists(e,`agent_databases`)||!tableExists(e,`migration_sources`))return false;const t=getNodeSqliteKysely(e);const n=executeSqliteQueryTakeFirstSync(e,t.selectFrom(`schema_meta`).selectAll().where(`meta_key`,`=`,`primary`));return n?.role===`global`&&n.schema_version===1&&n.agent_id===null&&!executeSqliteQueryTakeFirstSync(e,t.selectFrom(`migration_sources`).select(`source_key`).where(`target_table`,`=`,`agent_deletion_journal`).limit(1))}
//!src/state/openclaw-state-db-startup-checkpoint.ts
const NATIVE_STARTUP_BOOTSTRAP_OBJECTS=/* @__PURE__ */ new Set([`table:device_auth_tokens`,`index:idx_device_auth_tokens_updated`,`table:device_identities`,`index:idx_device_identities_device`,`table:exec_approvals_config`,`table:macos_port_guardian_records`,`index:idx_macos_port_guardian_records_port`,`table:schema_meta`,`table:state_leases`,`index:idx_state_leases_expiry`,`index:idx_state_leases_owner`]);const checkpointAdmission=createStateSchemaAdmission(`state.startup-checkpoint`,e=>e===true?true:void 0);function isUninitializedNativeStartupDatabase(e,t){const n=getAdmittedSqliteSchemaFacts(e);if((t??getStateSchemaVersionAdmission(e)?.userVersion??n?.userVersion??readSqliteUserVersion(e))!==0)return false;const r=n?[...[...n.tables].map(e=>({type:`table`,name:e})),...[...n.indexes].map(e=>({type:`index`,name:e})),...[...n.views].map(e=>({type:`view`,name:e})),...[...n.triggers.keys()].map(e=>({type:`trigger`,name:e}))].filter(({name:e})=>!e.startsWith(`sqlite_`)):e.prepare(`SELECT type, name FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'`).all();if(r.some(({type:e,name:t})=>typeof e!==`string`||typeof t!==`string`||!NATIVE_STARTUP_BOOTSTRAP_OBJECTS.has(`${e}:${t}`)))return false;const i=new Set(r.filter(({type:e})=>e===`table`).map(({name:e})=>e));if(i.has(`schema_meta`)&&e.prepare(`SELECT 1 FROM schema_meta LIMIT 1`).get())return false;return!(i.has(`state_leases`)&&e.prepare(`SELECT 1 FROM state_leases LIMIT 1`).get())}
//!src/state/openclaw-state-service-installation.ts
function assertGatewayServiceSchemaMigrationAllowed(e,t,n){const r=getGatewayServiceInstallation();if(r&&t>0&&t<n&&r.databasePath===resolveIdentityPathViaExistingAncestorSync(e))throw new StartupMaintenanceRequiredError(`state-migrations`,`Refusing a forward database schema migration: this CLI is ${r.cliVersion} but the Gateway service runs ${r.version} from ${r.root}; run openclaw update (or the CLI from ${r.root}).`)}
//!src/state/schema-migration-backup-scope.ts
function resolveSchemaMigrationIntegrityCheck(e,t=`quick`){if(t===`full`)return{check:`full`};return{check:t,tables:resolveSchemaMigrationIntegrityTables(e),...e.kind===`agent`&&e.foundVersion>=38&&e.foundVersion<e.supportedVersion&&e.supportedVersion<=42?{schemaOnly:true}:{}}}
//!src/state/openclaw-state-db-schema-runtime.ts
const stateDbLog=createSubsystemLogger(`state/db`);function ensureOpenClawStateRuntimeSchema(e,t,n,r,i=OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,a=false,o,s){const c=getSqliteWorkerStateIntegrityAdmission()??(isMainThread?captureOpenClawStateIntegrityAdmission(t):void 0);if(isExistingOpenClawStateSchema(t,e)){assertExistingOpenClawStateRuntimeSchema(e,t,c);assertOpenClawStateWriteAllowed({database:e,databasePath:t,env:n});return[]}try{if(isOpenClawStateSchemaFastPathEligible(e,t,c)){assertOpenClawStateWriteAllowed({database:e,databasePath:t,env:n});return[]}}catch(t){if(!e.isOpen||t instanceof StartupMaintenanceRequiredError)throw t}return withStateDatabaseSchemaMaintenance({databasePath:t,busyTimeoutMs:i},()=>{const c=Date.now();const l=[];let u=false;const d=runStateSchemaMigrationTransaction(e,t,()=>{assertOpenClawStateWriteAllowed({database:e,databasePath:t,env:n});assertSupportedStateSchemaVersion(e,t);if(a&&!isUninitializedNativeStartupDatabase(e))return[];const i=readStateSchemaContentVersion(e);if(!getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance)assertGatewayServiceSchemaMigrationAllowed(t,i,40);if(i===0&&!isUninitializedNativeStartupDatabase(e))throw new Error(`Unrecognized native bootstrap database; preserve it and run openclaw doctor --fix.`);if(i>0)assertCanonicalStateSchemaShape(e,t);prepareClientCredentialMigration(e,{path:t,env:n,fromVersion:i,custody:s});const d=getAdmittedSqliteSchemaFacts(e);if(i===0&&d?.tables.size===0&&d.views.size===0){createStateConfigMachineTable(e);executeCanonicalStateSchema(e,{includeVersionLazyAdditiveTables:true,includeAgentDeletionJournal:r.kind===`fresh`||r.nativeBootstrapEligible===true});migrateCronDefaultStoreIdentity(e,{previousVersion:i,legacyDefaultStoreKey:o??resolveCronIdentityMigrationDefaultStoreKey(n),fresh:true,nowMs:c});writeCurrentStateSchemaMetadata(e,c);u=true;return[]}if(i===40){assertNoLegacyStateRuntimeRepair(e,t);assertStateDatabaseIntegrityOnce(e,t);const n=repairCanonicalSqliteIndexes(e,t,OPENCLAW_STATE_SCHEMA_SQL,{verifyPhysicalIntegrity:false,allowMissingColumns:true,validateAfterRepair:()=>{assertCanonicalStateSchemaShape(e,t);assertOpenClawStateDatabaseForMaintenance(e,{pathname:t})}});ensureAdditiveStateColumns(e,`runtime`);assertCurrentStateRuntimeSchema(e,t);writeCurrentStateSchemaMetadata(e,c);u=true;return n.length>0?[`Rebuilt canonical shared-state SQLite indexes (${n.length})`]:[]}openClawStateMigrationAssertions.get(i)?.(e,{pathname:t});const f=resolveSchemaMigrationIntegrityCheck({kind:`state`,foundVersion:i,supportedVersion:40});if(f.check===`quick`)assertSqliteIntegrity(e,t,f);else assertStateDatabaseIntegrityOnce(e,t);const p=migrateBoundedStateSchema(e,i,{env:n,legacyCronDefaultStoreKey:o});if(p){writeCurrentStateSchemaMetadata(e,c);assertCurrentStateRuntimeSchema(e,t);assertMigratedStateTableIntegrity(e,t,i);u=true;return p}const m=migrateHistoricalStateImports(e,i);const h=tableExists(e,`agent_deletion_journal`)||hasPreJournalStateSchema(e)||(r.kind===`fresh`||r.nativeBootstrapEligible===true)&&isUninitializedNativeStartupDatabase(e);dropLegacyStateTables(e);const g=runRetiredStateTableMigrations(e,i);l.push(...g);if(migrateSingletonStateFoldInV12(e,i))g.push(`Folded singleton state tables into config_machine_state (v12)`);if(migrateWorkerPlacementExecutionModeSchema(e,i))g.push(`Migrated cloud worker placements to execution modes`);const _=migrateAgentDatabaseRelativePaths(e,i,t);g.push(...describeAgentPathMigration(_));if(migratePredicateColumnsV21(e,i))g.push(`Derived meeting transcript selectors and bounded delivery retention columns (v21)`);ensureAdditiveStateColumns(e,i<20?`repair`:`runtime`);for(const t of versionedStateMigrations)if(t.migrate(e,i,{env:n,legacyCronDefaultStoreKey:o}))g.push(t.applied);migrateSessionWatchCursorProvenance(e);assertCanonicalStateSchemaShape(e,t);executeCanonicalStateSchema(e,{includeVersionLazyAdditiveTables:true,includeAgentDeletionJournal:h});migrateLegacyCronRunLogsToTaskRuns(e);if(i<3&&hasNonStrictSqliteTables(e)){repairLegacyGatewayRestartHandoffsForStrictMigration(e);ensureFirstUseAdditiveStateColumnsForStrictMigration(e);const n=migrateSqliteSchemaToStrictInTransaction(e,getOpenClawStateRuntimeSchema({includeVersionLazyAdditiveTables:true,includeAgentDeletionJournal:h}),{databaseLabel:t});if(n.migratedTables.length>0)g.push(`Migrated shared state tables to SQLite STRICT typing (${n.migratedTables.length})`)}repairCanonicalSqliteIndexes(e,t,OPENCLAW_STATE_SCHEMA_SQL,{verifyPhysicalIntegrity:false});writeCurrentStateSchemaMetadata(e,c);assertOpenClawStateDatabaseForMaintenance(e,{pathname:t});assertMigratedStateTableIntegrity(e,t,i,true);u=true;warnAgentPathMigration(stateDbLog,_,t);return[...m,...g]},{busyTimeoutMs:i,databaseLabel:t,operationLabel:`state.schema.ensure`});if(u)publishStateRuntimeSchemaAdmission(e,true);l.forEach(logRetiredStateTableMigration);return d})}
//!src/state/openclaw-state-db-task-delivery-recovery-preservation.ts
const ORPHAN_PREDICATE=`NOT EXISTS (SELECT 1 FROM task_runs WHERE task_runs.task_id = task_delivery_state.task_id)`;function orphanRows(e){const t=e.prepare(`SELECT rowid, * FROM task_delivery_state
WHERE ${ORPHAN_PREDICATE} ORDER BY rowid`);t.setReadBigInts(true);return t.iterate()}function encodeOrphanRow(e){if(typeof e.rowid!==`bigint`||typeof e.task_id!==`string`||e.requester_origin_json!==null&&typeof e.requester_origin_json!==`string`||e.last_notified_event_at!==null&&typeof e.last_notified_event_at!==`bigint`)throw new Error(`Orphan task delivery values do not match the supported recovery contract.`);return`${JSON.stringify(e,(e,t)=>typeof t===`bigint`?t.toString():t)}\n`}function assertOrphanTaskDeliveryRecoveryShape(e){const t=e.prepare(`PRAGMA table_xinfo(task_delivery_state)`).all();const n=[{cid:0,name:`task_id`,type:`TEXT`,notnull:1,dflt_value:null,pk:1,hidden:0},{cid:1,name:`requester_origin_json`,type:`TEXT`,notnull:0,dflt_value:null,pk:0,hidden:0},{cid:2,name:`last_notified_event_at`,type:`INTEGER`,notnull:0,dflt_value:null,pk:0,hidden:0}];const r=e.prepare(`PRAGMA foreign_key_list(task_delivery_state)`).all();const i=[{id:0,seq:0,table:`task_runs`,from:`task_id`,to:`task_id`,on_update:`NO ACTION`,on_delete:`CASCADE`,match:`NONE`}];const a=e.prepare(`SELECT 1 FROM sqlite_schema WHERE type = 'trigger' AND tbl_name = 'task_delivery_state'`).get();if(JSON.stringify(t)!==JSON.stringify(n)||JSON.stringify(r)!==JSON.stringify(i)||a)throw new Error(`Orphan task delivery recovery refused an unrecognized table, foreign key, or trigger.`)}function assertKnownOrphanTaskDeliveryIntegrity(e){try{assertSqliteIntegrity(e,`task delivery recovery database`);return 0}catch(e){if(e instanceof SqliteRepairableForeignKeyError)return e.repair.orphanCount;throw e}}function hasOrphanTaskDeliveryRows(e){return tableExists(e,`task_delivery_state`)&&tableExists(e,`task_runs`)&&Boolean(e.prepare(`SELECT 1 FROM task_delivery_state WHERE ${ORPHAN_PREDICATE} LIMIT 1`).get())}function hashOrphanRows(e){const t=createHash(`sha256`);let n=0;for(const r of orphanRows(e)){t.update(encodeOrphanRow(r));n+=1}return{count:n,payloadSha256:t.digest(`hex`)}}function applyOrphanTaskDeliveryRecovery(e,t,n,r){if(!e.isTransaction)throw new Error(`Orphan task delivery recovery requires the Doctor write transaction.`);assertOrphanTaskDeliveryRecoveryShape(e);const i=hashOrphanRows(e);if(i.count!==n.count||i.payloadSha256!==n.payloadSha256)throw new Error(`Orphan task delivery snapshot does not preserve the current payload.`);const a=e.prepare(`DELETE FROM task_delivery_state WHERE ${ORPHAN_PREDICATE}`).run();if(Number(a.changes)!==n.count)throw new Error(`Orphan task delivery recovery removed an unexpected number of rows.`);assertSqliteIntegrity(e,t);return[`Preserved and recovered ${n.count} orphan task delivery rows; backup and row export: ${r}`]}function preserveOrphanTaskDeliveryRecoveryInProcess(e,t,n){const r=openNodeSqliteDatabase(e);try{r.exec(`PRAGMA journal_mode = DELETE;`);assertOrphanTaskDeliveryRecoveryShape(r);const i=assertKnownOrphanTaskDeliveryIntegrity(r);if(i===0)throw new Error(`Orphan task delivery snapshot no longer contains orphan rows.`);const a=path.join(n,`database.sqlite`);const o=flushAndHashFileSync(e);fs.copyFileSync(e,a,fs.constants.COPYFILE_EXCL);fs.chmodSync(a,384);if(JSON.stringify(flushAndHashFileSync(a))!==JSON.stringify(o))throw new Error(`Orphan task delivery backup verification failed.`);const s=path.join(n,`orphan-rows.jsonl`);const c=fs.openSync(s,`wx+`,384);const l=createHash(`sha256`);let u=0;let d;try{for(const e of orphanRows(r)){const t=encodeOrphanRow(e);fs.writeFileSync(c,t);l.update(t);u+=1}fs.fsyncSync(c);d=l.digest(`hex`);if(hashFileDescriptorSync(c).sha256!==d)throw new Error(`Orphan task delivery export verification failed.`)}finally{fs.closeSync(c)}if(u!==i)throw new Error(`Orphan task delivery export did not account for every foreign-key violation.`);fs.writeFileSync(path.join(n,`manifest.json`),JSON.stringify({format:`openclaw.task-delivery-recovery.v1`,state:`preserved-before-repair`,sourcePath:t,backup:{file:`database.sqlite`,...o,integrity:`structural-ok-known-orphans`},export:{file:`orphan-rows.jsonl`,...flushAndHashFileSync(s),count:i,integerEncoding:`decimal-string`},relation:`task_delivery_state.task_id -> task_runs.task_id`,createdAt:(/* @__PURE__ */ new Date()).toISOString()},null,2),{flag:`wx`,mode:384,flush:true});requireDirectorySync(syncDirectorySync(n),`Task delivery recovery directory`);requireDirectorySync(syncDirectorySync(path.dirname(n)),`Task delivery recovery parent`);return{count:i,payloadSha256:d}}finally{r.close()}}
//!src/state/openclaw-state-db-task-delivery-recovery.ts
function recoveryFailure(e,t){return new Error(`Task delivery recovery failed without committing row removal${t?`; retained artifacts: ${t}`:``}: ${String(e)}`,{cause:e})}function recoverOrphanTaskDeliveryRows(e,t){if(!hasOrphanTaskDeliveryRows(e))return[];assertOpenClawStateDatabaseOwner(e,{pathname:t});assertOrphanTaskDeliveryRecoveryShape(e);const n=assertKnownOrphanTaskDeliveryIntegrity(e);if(!e.isTransaction)throw new Error(`Orphan task delivery recovery requires the Doctor write transaction.`);const r=prepareSqliteReadOnlyLocationSync(t);let i;try{i=createPrivateSqliteTempDirectorySync(path.dirname(t),`openclaw-task-delivery-recovery-`);const a=preserveOrphanTaskDeliveryRecoveryInProcess(r.location,t,i);if(a.count!==n)throw new Error(`Orphan task delivery snapshot changed before preservation.`);assertOpenClawStateDatabaseOwner(e,{pathname:t});return applyOrphanTaskDeliveryRecovery(e,t,a,i)}catch(e){throw recoveryFailure(e,i)}finally{r.cleanup()}}
//!src/state/openclaw-state-db.ts
const deferredStateDatabases=/* @__PURE__ */ new WeakSet;function openOpenClawStateDatabaseWithBusyTimeout(...e){return runStateOpenSteps(openStateDatabaseSteps(...e))}function*openStateDatabaseSteps(e={},t=OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,n=`report`,r){getOpenClawDatabaseMaintenanceScope()?.assertAdmission();const i=e.env??process.env;const a=e.database?.path??resolveDatabasePath(e);if(isArtifactPreservingStateRead(`agent`,a)){assertStateFileSnapshotAllowed();openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(a,i);const e=openSqliteReadOnlyDatabase(a,{timeout:t});assertSupportedStateSchemaVersion(e,a);return readOnlyStateDatabase({db:e,path:a},()=>{e.close();return true})}const o=!e.database&&isExistingOpenClawStateSchema(a);const s=e.database??openClawStateDatabaseCache.getCachedOpenClawStateDatabase(a);if(s&&(e.database||s.db.isOpen)){if(!e.database)openClawStateDatabaseCache.assertOpenClawStateDatabaseOpenAllowed(a);assertStateDatabaseSchemaAdmission(s);assertOpenClawStateWriteAllowed({database:s.db,databasePath:a,env:i,schemaReady:openClawStateDatabaseCache.isOpenClawStateDatabaseSchemaReady(s)});observeOpenClawDatabaseMaintenanceResource(s.db);if(e.database)openClawStateDatabaseCache.touchStateDatabase(s);else if(!o&&deferredStateDatabases.has(s.db)){reconcileOpenClawStateSchemaPublication(e);if(getStateSchemaVersionAdmission(s.db)?.userVersion===40)deferredStateDatabases.delete(s.db)}return s}let c;try{const open=(t,r)=>{getOpenClawDatabaseMaintenanceScope()?.assertAdmission();openClawStateDatabaseCache.assertOpenClawStateDatabaseOpenAllowed(a);openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(a,i);if(s)openClawStateDatabaseCache.closeStaleCachedOpenClawStateDatabase(s);return r({pathname:a,env:i,busyTimeoutMs:t(),lockFailureReporting:n,existingSchema:o,initializationAgentPaths:e.initializationAgentPaths,clientCredentialMigrationFromVersion:e.clientCredentialMigrationFromVersion,ensureSchema:(e,n,r)=>ensureOpenClawStateRuntimeSchema(e,a,i,n,t(),false,void 0,r),recordOpenFailure:recordOpenClawStateDatabaseOpenFailure})};const acquire=e=>r?open(r,e):withStateDatabaseColdAdmission({databasePath:a,busyTimeoutMs:t},t=>open(t,e));c=yield{run(){return acquire(openUnpublishedStateDatabase)},runAsync(){return acquire(openUnpublishedStateDatabaseAsync)}};resolveSqliteInspectionSignal(getAsyncWorkSignal())?.throwIfAborted();getOpenClawDatabaseMaintenanceScope()?.assertAdmission();if(!isPostgresSqlConnection(c.db))setSqliteBusyTimeout(c.db,t)}catch(e){if(n===`report`||!isOpenClawStateWriteContentionError(e))openClawStateDatabaseCache.recordOpenClawStateDatabaseLifecycleOpenError(a,e);if(c){const t=openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle(c);if(t.length>0)throw createSqliteLifecycleAggregateError([e,...t],`Fresh OpenClaw state database open failed releasing access and closing its unpublished handle for ${a}.`,e)}throw e}if(o)recordExistingOpenClawStateSchemaDatabase(c.db,a);const l=openClawStateDatabaseCache.publishOpenClawStateDatabase(c,i);try{if(!o&&readPublishedStateSchemaVersion(l.db)<40){deferredStateDatabases.add(l.db);reconcileOpenClawStateSchemaPublication(e)}return l}catch(e){if(l.db.isOpen&&!isPostgresSqlConnection(l.db))setSqliteBusyTimeout(l.db,OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);throw e}}function reconcileOpenClawStateSchemaPublication(e={}){if(isExistingOpenClawStateSchema(e.database?.path??resolveDatabasePath(e)))return;const t=withExistingOpenClawStateDatabaseReadOnly(({db:e})=>{if(readPublishedStateSchemaVersion(e)>=40||readStateSchemaContentVersion(e)<40)return;if(isPostgresSqlConnection(e))requireNativeDatabaseFile(`postgres`,`repair`);return{blocker:readStateSchemaPublicationBlocker(e)}},e);if(!t||t.blocker)return t?.blocker;const n=resolveDatabasePath(e);try{return withStateDatabaseSchemaMaintenance({databasePath:n},()=>runOpenClawStateWriteTransaction(({db:e})=>{if(isPostgresSqlConnection(e))requireNativeDatabaseFile(`postgres`,`repair`);const t=readStateSchemaPublicationBlocker(e);if(t)return t;assertOpenClawStateDatabaseForMaintenance(e,{pathname:n});markCurrentStateSchemaVersion(e)},e,{operationLabel:`state.schema.publish`}))}catch(e){if(e instanceof StateSchemaMutationConflictError)return;throw e}}function runOpenClawStateWriteTransaction(e,t={},n={}){if(isArtifactPreservingStateRead(`agent`,t.database?.path??resolveDatabasePath(t)))throw new Error(`Programming error: shared-state write during artifact-preserving inspection.`);getOpenClawDatabaseMaintenanceScope()?.assertAdmission();const r=t.database??getOpenClawStateDatabaseIfOpen(t);if(r){isExistingOpenClawStateSchema(r.path,r.db);if(t.database)assertStateDatabaseAccessAllowed(r.path)}let i=r;let a=false;let o;const execute=r=>{const o=i??openOpenClawStateDatabaseWithBusyTimeout(t,5e3,`report`,r);i=o;const write=()=>runManagedStateTransaction(o.db,()=>{if(isPostgresSqlConnection(o.db))admitStateSchemaFacts(o.db,o.path);assertStateDatabaseSchemaAdmission(o);if(!t.database)getOpenClawStateDatabaseIfOpen(t);assertOpenClawStateWriteAllowed({database:o.db,databasePath:o.path,env:t.env??process.env,schemaReady:openClawStateDatabaseCache.isOpenClawStateDatabaseSchemaReady(o)});observeOpenClawDatabaseMaintenanceResource(o.db);if(t.database)openClawStateDatabaseCache.touchStateDatabase(o);a=true;return e(o)},{databaseLabel:o.path,...n,...r?{busyTimeoutMs:r()}:{},operationLabel:n.operationLabel??captureSqliteReaderOwner()?.operation??`state.write`});return{database:o,value:isPostgresSqlConnection(o.db)?withPostgresSchemaAdmissionRetry(o.db,write,()=>!a):write()}};try{o=r?execute():withStateDatabaseColdAdmission({databasePath:resolveDatabasePath(t),busyTimeoutMs:n.busyTimeoutMs??5e3,canRetry(){if(a||i&&(!i.db.isOpen||i.db.isTransaction))return false;if(i){assertTransactionUsable(i.db);if(!isPostgresSqlConnection(i.db))invalidateSqliteSchemaFacts(i.db);openClawStateDatabaseCache.closeOpenClawStateDatabaseByPath(i.path);i=void 0}return true}},execute)}catch(e){if(i)openClawStateDatabaseCache.evictOpenClawStateDatabaseAfterCorruption(i,e);throw e}try{if(!isExistingOpenClawStateSchema(o.database.path,o.database.db))ensureOpenClawStatePermissions(o.database.path,t.env??process.env)}catch{}return o.value}function getOpenClawStateDatabaseIfOpen(e={}){const t=resolveDatabasePath(e);isExistingOpenClawStateSchema(t);const n=openClawStateDatabaseCache.getCachedOpenClawStateDatabase(t);if(n?.db.isOpen)isExistingOpenClawStateSchema(n.path,n.db);return n?.db.isOpen?n:void 0}
//!src/infra/state-migrations.receipts.ts
function readLegacyMigrationReceiptFromDatabase(e,t){const n=executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`migration_sources`).select([`source_sha256`,`removed_source`,`report_json`]).where(`source_key`,`=`,t));return n?{sourceKey:t,sourceSha256:n.source_sha256,removedSource:n.removed_source===1,reportJson:n.report_json}:null}
//!src/state/agent-deletion-journal-recovery.kernel.ts
const AGENT_DELETION_RECOVERY_SOURCE_KEY=`agent-deletion-journal-reconstruction`;const AGENT_DELETION_RECONSTRUCTION_DESCRIPTION=`Reconstructed the missing agent deletion journal; held databases require explicit agent restore or delete.`;function parseHolds(e){return e.map(e=>{if(!isRecord(e)||typeof e.agentId!==`string`||e.agentId!==normalizeAgentId(e.agentId)||typeof e.path!==`string`||!e.path.trim())throw new Error(`Invalid agent database hold in deletion journal reconstruction receipt.`);return{agentId:e.agentId,path:e.path}})}function readReport(e){const t=readLegacyMigrationReceiptFromDatabase(e.db,AGENT_DELETION_RECOVERY_SOURCE_KEY);if(!t)return;const n=JSON.parse(t.reportJson);if(!isRecord(n)||typeof n.description!==`string`||!Array.isArray(n.held))throw new Error(`Invalid agent deletion journal reconstruction receipt.`);const r=parseHolds(n.held);if(n.missingJournal!==void 0&&!Array.isArray(n.missingJournal))throw new Error(`Invalid missing-journal provenance in deletion journal reconstruction receipt.`);const i=Array.isArray(n.missingJournal)?parseHolds(n.missingJournal):n.description===`Reconstructed the missing agent deletion journal; held databases require explicit agent restore or delete.`?r:[];if(i.some(e=>!r.some(t=>t.agentId===e.agentId&&t.path===e.path)))throw new Error(`Missing-journal provenance refers to an unheld agent database.`);return{...n,description:n.description,held:r,missingJournal:i}}function decodeHolds(e,t){return t.map(t=>({agentId:t.agentId,path:resolveOpenClawRegisteredAgentDatabasePath(e.path,t.path)}))}function readAgentDeletionRecoveryHolds(e){return decodeHolds(e,readReport(e)?.held??[])}
//!src/state/agent-deletion-journal-status.ts
const pendingLoads=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionJournalStatusLoads`),()=>/* @__PURE__ */ new Map);
//!src/state/agent-deletion-journal.read.ts
function parseAgentDeletionDatabasePaths(e){const t=JSON.parse(e);if(isStringArray(t))return t;throw new Error(`Invalid agent deletion database path journal.`)}function readRetainedAgentDeletionsFromDatabase(e,t,n=`maintenance`,r){let i=[];let a=false;let o;try{a=!tableExists(e,`agent_deletion_journal`);if(!a){const t=expressionBuilder();const a=t.and([t(`cleanup_completed`,`=`,1),t(`delete_files`,`=`,0)]);const s=n!==`runtime`?t.or([a,t(`cleanup_completed`,`=`,0)]):a;i=executeSqliteQuerySync(e,getNodeSqliteKysely(e).selectFrom(`agent_deletion_journal`).select([`agent_id`,`cleanup_completed`]).select(tableHasColumn(e,`agent_deletion_journal`,`phase`)?`phase`:t.lit(null).as(`phase`)).select([t.case().when(s).then(t.ref(`agent_dir`)).else(null).end().as(`agent_dir`),t.case().when(s).then(t.ref(`database_paths_json`)).else(`[]`).end().as(`database_paths_json`)]).$if(!r,e=>e.where(s)).orderBy(`agent_id`,`asc`)).rows.flatMap(t=>{r?.push({agentId:t.agent_id,status:t.cleanup_completed===1?`complete`:`pending`});if(t.agent_dir===null)return[];let i=[];try{i=parseAgentDeletionDatabasePaths(t.database_paths_json)}catch(e){if(n===`maintenance`)o??=formatErrorMessage(e)}const a={agentId:t.agent_id,agentDir:t.agent_dir,databasePaths:[path.join(t.agent_dir,`openclaw-agent.sqlite`),...i],cleanupCompleted:t.cleanup_completed===1};if(t.cleanup_completed===0&&t.phase==null&&hasTemplateDeletionOwnership({db:e},t.agent_id))a.manualTemplateRemoval=true;return a})}}catch(e){if(isSqliteCorruptionError(e))throw e;o=formatErrorMessage(e)}let s=[];try{if(tableExists(e,`migration_sources`))s=readAgentDeletionRecoveryHolds({db:e,path:t})}catch(e){if(n===`maintenance`||isSqliteCorruptionError(e))throw e}if(a&&s.length===0&&hasPreJournalStateSchema(e))return{status:`empty`};if(a||o!==void 0)return{status:`unavailable`,cause:a?`missing`:`unreadable`,reason:a?`deletion journal missing`:`deletion journal unreadable: ${o}`,...i.length||s.length?{known:{entries:i,held:s}}:{}};return i.length||s.length?{status:`present`,entries:i,held:s}:{status:`empty`}}function readAgentDatabaseDeletionSnapshot(e,t=`maintenance`){return withExistingOpenClawStateDatabaseReadOnly(({db:e,path:n})=>runSqliteReadSnapshotSync(e,()=>({retainedDeletions:readRetainedAgentDeletionsFromDatabase(e,n,t),registeredAgentDatabases:readRegisteredAgentDatabaseRows(e,n,false)}),{operationLabel:`agentDeletionJournal.snapshot`}),{env:e})}
//!packages/memory-host-sdk/src/host/memory-schema-provenance.ts
const MEMORY_INDEX_CHUNK_PROVENANCE_TABLE=`memory_index_chunk_provenance`;const MEMORY_INDEX_CHUNK_PROVENANCE_SCHEMA_SQL=`
CREATE TABLE IF NOT EXISTS ${MEMORY_INDEX_CHUNK_PROVENANCE_TABLE} (
chunk_id TEXT PRIMARY KEY,
origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),
observed_at INTEGER NOT NULL,
supersedes_key TEXT,
FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;
`;const ensureProvenanceTable=createSqliteSchemaEnsurer(()=>MEMORY_INDEX_CHUNK_PROVENANCE_SCHEMA_SQL,{tables:[MEMORY_INDEX_CHUNK_PROVENANCE_TABLE]});
//!packages/memory-host-sdk/src/host/memory-schema-recall.ts
const MEMORY_INDEX_CHUNK_RECALL_METADATA_TABLE=`memory_index_chunk_recall_metadata`;
//!packages/memory-host-sdk/src/host/memory-schema-storage-migration.ts
const LEGACY_CHUNK_REVISION_TRIGGERS=[`insert`,`update`,`delete`].map(e=>({name:`memory_index_chunks_revision_after_${e}`,sql:`CREATE TRIGGER IF NOT EXISTS memory_index_chunks_revision_after_${e}
AFTER ${e.toUpperCase()} ON memory_index_chunks
BEGIN UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1; END;`}));
//!packages/memory-host-sdk/src/host/memory-schema.ts
const LEGACY_MEMORY_INDEX_SOURCE_COLUMNS=[`path`,`source`,`hash`,`mtime`,`size`];const MEMORY_INDEX_SOURCE_COLUMNS=[`id`,...LEGACY_MEMORY_INDEX_SOURCE_COLUMNS];
//!src/state/openclaw-agent-context-engine-turn-outbox-schema.ts
const CONTEXT_ENGINE_TURN_OUTBOX_TABLE=`context_engine_turn_outbox`;const ensureNativeContextEngineTurnOutboxSchema=createSqliteSchemaEnsurer(()=>extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,CONTEXT_ENGINE_TURN_OUTBOX_TABLE,{endMarker:`CREATE TABLE IF NOT EXISTS cache_entries (`,includeEndMarker:false,errorMessage:`OpenClaw context-engine turn outbox schema markers are missing.`}),{tables:[CONTEXT_ENGINE_TURN_OUTBOX_TABLE],indexes:[`idx_agent_context_engine_turn_outbox_engine`]});
//!src/state/openclaw-agent-goal-operations-schema.ts
const SESSION_GOAL_OPERATIONS_TABLE=`session_goal_operations`;const ensureNativeSessionGoalOperationsSchema=createSqliteSchemaEnsurer(()=>extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,SESSION_GOAL_OPERATIONS_TABLE,{endMarker:`CREATE TABLE IF NOT EXISTS transcript_events (`,includeEndMarker:false,errorMessage:`OpenClaw Goal operation schema markers are missing.`}),{tables:[SESSION_GOAL_OPERATIONS_TABLE],indexes:[`idx_agent_session_goal_operations_expiry`]});
//!src/state/openclaw-agent-pending-inputs-schema.ts
const SESSION_PENDING_INPUTS_TABLE=`session_pending_inputs`;const SESSION_INPUT_COMPLETIONS_TABLE=`session_input_completions`;const ensurePendingTable=createSqliteSchemaEnsurer(()=>extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,SESSION_PENDING_INPUTS_TABLE,{endMarker:`-- Processing completion`,includeEndMarker:false,errorMessage:`OpenClaw pending-input schema marker is missing.`}),{tables:[SESSION_PENDING_INPUTS_TABLE],indexes:[`idx_agent_session_pending_inputs_session`]});const ensureInputCompletionsTable=createSqliteSchemaEnsurer(()=>extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,SESSION_INPUT_COMPLETIONS_TABLE,{endMarker:`ON session_input_completions(session_key);`,errorMessage:`OpenClaw input-completion schema marker is missing.`}),{tables:[SESSION_INPUT_COMPLETIONS_TABLE],indexes:[`idx_agent_session_input_completions_session_key`]});
//!src/state/openclaw-agent-session-snapshots-schema.ts
function sessionEntrySnapshotsSchemaSql(e){return extractSqliteTableSchema(e,`session_entry_snapshots`,{endMarker:`CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at`,includeEndMarker:false})}function withoutSessionEntrySnapshotsSchema(e){if(!e.includes(`CREATE TABLE IF NOT EXISTS session_entry_snapshots (`))return e;return e.replace(` snapshot_revision INTEGER NOT NULL DEFAULT 0,
`,``).replace(sessionEntrySnapshotsSchemaSql(e),``)}
//!src/state/openclaw-agent-transcript-fts-schema-source.ts
const DEPLOYED_FTS_ROWS_SCHEMA=`CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (
session_id TEXT NOT NULL,
fts_rowid INTEGER NOT NULL PRIMARY KEY
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_transcript_fts_rows_session
ON session_transcript_fts_rows(session_id);
`;function withDeployedTranscriptFtsRowSchema(e){const t=extractSqliteTableSchema(e,`session_transcript_index_state`);return e.replace(t,t.replace(` updated_at INTEGER NOT NULL,`,` fts_row_count INTEGER,
updated_at INTEGER NOT NULL,`)).replace(`CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(`,`${DEPLOYED_FTS_ROWS_SCHEMA}\nCREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(`)}
//!src/state/openclaw-agent-storage-schema.ts
const LEGACY_STORAGE_TABLES={transcript_events:`CREATE TABLE IF NOT EXISTS transcript_events (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;`,memory_index_chunks:`CREATE TABLE IF NOT EXISTS memory_index_chunks (
id TEXT PRIMARY KEY,
path TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'memory',
start_line INTEGER NOT NULL,
end_line INTEGER NOT NULL,
hash TEXT NOT NULL,
model TEXT NOT NULL,
text TEXT NOT NULL,
embedding TEXT NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;`,memory_embedding_cache:`CREATE TABLE IF NOT EXISTS memory_embedding_cache (
provider TEXT NOT NULL,
model TEXT NOT NULL,
provider_key TEXT NOT NULL,
hash TEXT NOT NULL,
embedding TEXT NOT NULL,
dims INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (provider, model, provider_key, hash)
) STRICT;`};function withLegacyAgentStorageSchema(e,t=21){let n=withoutSessionEntrySnapshotsSchema(e);for(const[e,t]of Object.entries(LEGACY_STORAGE_TABLES))n=n.replace(extractSqliteTableSchema(n,e),t);if(n.includes(`CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (`))n=n.replace(extractSqliteTableSchema(n,`session_transcript_fts_rows`,{endMarker:`INSERT OR IGNORE INTO memory_index_state`,includeEndMarker:false}),``);return t===22?withDeployedTranscriptFtsRowSchema(n):n}
//!src/state/openclaw-agent-schema-history.ts
const LEGACY_ENTRY_VALIDITY_TRIGGERS_SQL=`
CREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_insert
AFTER INSERT ON session_nodes
BEGIN
UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;
END;
CREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_entry_update
AFTER UPDATE OF entry_json ON session_nodes
BEGIN
UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;
END;
CREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_identity_update
AFTER UPDATE OF current_session_id, updated_at ON session_nodes
BEGIN
UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;
END;
`;const LEGACY_CANONICAL_PENDING_TRIGGERS_SQL=`
-- Avoid trigger-local conflict clauses: SQLite inherits the outer writer's
-- conflict policy, including writers that predate this validation projection.
CREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_insert
AFTER INSERT ON session_nodes
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT NEW.session_key
WHERE NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending WHERE session_key = NEW.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_update
AFTER UPDATE OF session_key, current_session_id, entry_json, entry_valid,
parent_session_key, spawned_by, fork_source_session_key ON session_nodes
WHEN OLD.session_key IS NOT NEW.session_key
OR OLD.current_session_id IS NOT NEW.current_session_id
OR OLD.entry_json IS NOT NEW.entry_json
OR OLD.entry_valid IS NOT NEW.entry_valid
OR OLD.parent_session_key IS NOT NEW.parent_session_key
OR OLD.spawned_by IS NOT NEW.spawned_by
OR OLD.fork_source_session_key IS NOT NEW.fork_source_session_key
BEGIN
DELETE FROM session_canonical_validation_pending
WHERE session_key = OLD.session_key AND OLD.session_key IS NOT NEW.session_key;
INSERT INTO session_canonical_validation_pending (session_key)
SELECT NEW.session_key
WHERE NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending WHERE session_key = NEW.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_delete
AFTER DELETE ON session_nodes
BEGIN
DELETE FROM session_canonical_validation_pending WHERE session_key = OLD.session_key;
END;
CREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_insert
AFTER INSERT ON session_windows
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT node.session_key FROM session_nodes AS node
WHERE node.current_session_id = NEW.session_id
AND NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending AS pending
WHERE pending.session_key = node.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_update
AFTER UPDATE OF session_id, session_key ON session_windows
WHEN OLD.session_id IS NOT NEW.session_id OR OLD.session_key IS NOT NEW.session_key
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT node.session_key FROM session_nodes AS node
WHERE node.current_session_id IN (OLD.session_id, NEW.session_id)
AND NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending AS pending
WHERE pending.session_key = node.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_delete
AFTER DELETE ON session_windows
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT node.session_key FROM session_nodes AS node
WHERE node.current_session_id = OLD.session_id
AND NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending AS pending
WHERE pending.session_key = node.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_insert
AFTER INSERT ON session_key_contract
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT node.session_key FROM session_nodes AS node
WHERE NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending AS pending
WHERE pending.session_key = node.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_update
AFTER UPDATE OF main_key ON session_key_contract
WHEN OLD.main_key IS NOT NEW.main_key
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT node.session_key FROM session_nodes AS node
WHERE NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending AS pending
WHERE pending.session_key = node.session_key
);
END;
CREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_delete
AFTER DELETE ON session_key_contract
BEGIN
INSERT INTO session_canonical_validation_pending (session_key)
SELECT node.session_key FROM session_nodes AS node
WHERE NOT EXISTS (
SELECT 1 FROM session_canonical_validation_pending AS pending
WHERE pending.session_key = node.session_key
);
END;
`;function withLegacyCanonicalSessionValidationTriggers(e){return e.replace(`CREATE TABLE IF NOT EXISTS session_windows (`,`${LEGACY_ENTRY_VALIDITY_TRIGGERS_SQL}\nCREATE TABLE IF NOT EXISTS session_windows (`).replace(`CREATE TABLE IF NOT EXISTS conversations (`,`${LEGACY_CANONICAL_PENDING_TRIGGERS_SQL}\nCREATE TABLE IF NOT EXISTS conversations (`)}const LEGACY_CANONICAL_VALIDATION_TRIGGER_NAMES=Object.freeze([...`${LEGACY_ENTRY_VALIDITY_TRIGGERS_SQL}\n${LEGACY_CANONICAL_PENDING_TRIGGERS_SQL}`.matchAll(/CREATE TRIGGER IF NOT EXISTS (\w+)/gu)].map(e=>e[1]));function canonicalSessionValidationSchemaSql(e=OPENCLAW_AGENT_SCHEMA_SQL){return extractSqliteTableSchema(e,`session_canonical_validation_pending`,{endMarker:`CREATE TABLE IF NOT EXISTS conversations (`,includeEndMarker:false})}function withoutCanonicalSessionValidationSchema(e){if(!e.includes(`CREATE TABLE IF NOT EXISTS session_canonical_validation_pending (`))return e;return e.replace(canonicalSessionValidationSchemaSql(e),``)}const AGENT_JSON_PREDICATE_COLUMN_DECLARATIONS={session_started_at:`INTEGER`,has_optional_references:`INTEGER NOT NULL DEFAULT 0`,payload_state:`TEXT`,navigation_type:`TEXT`,navigation_custom_type:`TEXT`,navigation_display:`INTEGER NOT NULL DEFAULT 0`,message_role:`TEXT`,navigation_last_type:`TEXT`,navigation_last_custom_type:`TEXT`,navigation_valid:`INTEGER NOT NULL DEFAULT 1`};function withoutAgentJsonPredicateColumns(e){let t=e;for(const[e,n]of Object.entries(AGENT_JSON_PREDICATE_COLUMN_DECLARATIONS))t=t.replace(` ${e} ${n},\n`,``);return t}const LEGACY_PARTICIPANTS_SCHEMA=`CREATE TABLE IF NOT EXISTS session_participants (
session_key TEXT NOT NULL,
actor_type TEXT NOT NULL,
actor_id TEXT NOT NULL,
actor_source TEXT,
contribution_count INTEGER,
first_prompted_at INTEGER NOT NULL,
last_prompted_at INTEGER NOT NULL,
PRIMARY KEY (session_key, actor_type, actor_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;`;function sessionParticipantsSchemaSql(){return extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,SESSION_PARTICIPANTS_TABLE,{endMarker:`CREATE TABLE IF NOT EXISTS session_key_contract (`,includeEndMarker:false,errorMessage:`OpenClaw session participant schema markers are missing.`})}function withLegacySessionParticipantsSchema(e){return withoutCanonicalSessionValidationSchema(e).replace(sessionParticipantsSchemaSql().trim(),LEGACY_PARTICIPANTS_SCHEMA)}function withoutOutboxEnqueueSequence(e){return e.replace(` enqueue_sequence INTEGER PRIMARY KEY,
advancement_key TEXT NOT NULL UNIQUE,`,` advancement_key TEXT NOT NULL PRIMARY KEY,`)}const LEGACY_PARENT_INDEX=`CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_parent
ON transcript_event_identities(session_id, parent_id)
WHERE parent_id IS NOT NULL;
`;function withLegacyAgentWriteLayout(e){return e.replace(/(CREATE TABLE IF NOT EXISTS memory_entry_origins \([\s\S]*?\n\) STRICT), WITHOUT ROWID;/u,`$1;`).replace(`ON session_windows(primary_conversation_id)`,`ON session_windows(primary_conversation_id, updated_at DESC, session_id)`).replace(`CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence`,`${LEGACY_PARENT_INDEX}CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence`)}const AGENT_SCHEMA_BEFORE_TOOL_USAGE=withoutAgentToolUsage(OPENCLAW_AGENT_SCHEMA_SQL);const AGENT_SCHEMA_BEFORE_ACTIVE_EVENT_FACTS=withoutAgentActiveEventFacts(AGENT_SCHEMA_BEFORE_TOOL_USAGE);const AGENT_SCHEMA_BEFORE_CREATION_OPERATIONS=withoutAgentCreationOperations(AGENT_SCHEMA_BEFORE_ACTIVE_EVENT_FACTS);const AGENT_SCHEMA_BEFORE_SESSION_DELETION_INDEXES=AGENT_SCHEMA_BEFORE_CREATION_OPERATIONS.replace(/\nCREATE INDEX IF NOT EXISTS idx_agent_(?:session_input_completions_session_key|conversation_deliveries_source_session)\b[^;]*;\n/gu,``);const OPENCLAW_AGENT_BOARD_SCHEMA_SQL=extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,`board_tabs`,{endMarker:`CREATE TABLE IF NOT EXISTS session_progress_cards (`,includeEndMarker:false,errorMessage:`OpenClaw agent board schema markers are missing from the canonical schema.`});const OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL=withLegacyAgentIndexes(withoutTrajectoryPayloadColumns(withLegacyAgentMemoryRevisionTriggers(withoutAgentColdArchiveChunks(AGENT_SCHEMA_BEFORE_SESSION_DELETION_INDEXES)))).replace(OPENCLAW_AGENT_BOARD_SCHEMA_SQL,``);const SESSION_PROGRESS_CARDS_TABLE=`session_progress_cards`;const AGENT_PROGRESS_CARD_SCHEMA_SQL=extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL,SESSION_PROGRESS_CARDS_TABLE,{endMarker:`CREATE TABLE IF NOT EXISTS heartbeat_outcomes (`,includeEndMarker:false,errorMessage:`OpenClaw agent progress-card schema markers are missing.`});const AGENT_SCHEMA_WITHOUT_PROGRESS_CARD_SQL=OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL.replace(AGENT_PROGRESS_CARD_SCHEMA_SQL,``);const SUGGESTIONS_SCHEMA_START=`CREATE TABLE IF NOT EXISTS session_suggestions (`;const sessionSharingSchema=extractSqliteTableSchema(AGENT_SCHEMA_WITHOUT_PROGRESS_CARD_SQL,`session_members`,{endMarker:`CREATE TABLE IF NOT EXISTS heartbeat_outcomes (`,includeEndMarker:false,errorMessage:`OpenClaw agent session-sharing schema markers are missing.`});const sessionSuggestionsStart=sessionSharingSchema.indexOf(SUGGESTIONS_SCHEMA_START);if(sessionSuggestionsStart===-1)throw new Error(`OpenClaw agent session-suggestions schema marker is missing.`);const AGENT_V14_SESSION_SHARING_SCHEMA_SQL=sessionSharingSchema.slice(0,sessionSuggestionsStart);const AGENT_V14_ADDITIVE_SCHEMA_SQL=sessionSharingSchema.slice(sessionSuggestionsStart);const AGENT_V14_CORE_SCHEMA_SQL=withLegacySessionParticipantsSchema(withLegacyAgentStorageSchema(withLegacyCanonicalSessionValidationTriggers(withoutAgentJsonPredicateColumns(withoutOutboxEnqueueSequence(withLegacyAgentWriteLayout(AGENT_SCHEMA_WITHOUT_PROGRESS_CARD_SQL.replace(sessionSharingSchema,``)))))));
//!src/state/openclaw-agent-session-transcript-archive-schema.ts
const SESSION_TRANSCRIPT_ARCHIVES_TABLE=`session_transcript_archives`;const ensureNativeSessionTranscriptArchiveSchema=createSqliteSchemaEnsurer(()=>extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,SESSION_TRANSCRIPT_ARCHIVES_TABLE,{endMarker:`CREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (`,includeEndMarker:false,errorMessage:`OpenClaw session transcript archive schema markers are missing.`}),{tables:[SESSION_TRANSCRIPT_ARCHIVES_TABLE,`session_transcript_cold_archives`],indexes:[`idx_agent_session_transcript_archives_pending`,`idx_agent_session_transcript_archives_retention`]});
//!src/state/openclaw-agent-standing-intents-schema.ts
const STANDING_INTENTS_TABLE=`standing_intents`;const STANDING_INTENTS_FTS_TABLE=`standing_intents_fts`;const STANDING_INTENTS_FTS_SHADOW_TABLES=[`standing_intents_fts_config`,`standing_intents_fts_data`,`standing_intents_fts_docsize`,`standing_intents_fts_idx`];
//!src/state/openclaw-agent-db-schema-compatibility.ts
const AGENT_SCHEMA_COMPATIBILITY={allowCompatibleAdditiveColumns:true,allowedMissingTables:[`session_reactions`,`memory_entry_origins`,`memory_session_tombstones`,MEMORY_INDEX_CHUNK_PROVENANCE_TABLE,MEMORY_INDEX_CHUNK_RECALL_METADATA_TABLE,CONTEXT_ENGINE_TURN_OUTBOX_TABLE,`message_tool_run_outcomes`,SESSION_GOAL_OPERATIONS_TABLE,SESSION_PENDING_INPUTS_TABLE,SESSION_INPUT_COMPLETIONS_TABLE,SESSION_PARTICIPANTS_TABLE,SESSION_PROGRESS_CARDS_TABLE,SESSION_TRANSCRIPT_ARCHIVES_TABLE,STANDING_INTENTS_TABLE,STANDING_INTENTS_FTS_TABLE,...STANDING_INTENTS_FTS_SHADOW_TABLES],allowedMissingColumns:[...STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS.map(({columnName:e,tableName:t})=>`${t}.${e}`),`standing_intents.creator_sender`,...FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS.map(({columnName:e,tableName:t})=>`${t}.${e}`)],allowedColumnDefinitions:{"session_pending_inputs.recovery_intent_json":[`recovery_intent_json TEXT`],"conversations.delivery_target":[`delivery_target TEXT NOT NULL DEFAULT ''`]},allowedMissingIndexes:[`idx_agent_transcript_context_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_input_completions_session_key`,`idx_agent_conversation_deliveries_source_session`],optionalCanonicalTriggerGroups:[{tableName:`memory_index_chunks`,triggers:MEMORY_CHUNK_FTS_TRIGGER_DEFINITIONS},{tableName:MEMORY_INDEX_SOURCES_TABLE,triggers:MEMORY_PATH_FTS_TRIGGER_DEFINITIONS}]};
//!src/state/openclaw-agent-db-read-error.ts
const settledReadOpenFailures=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSettledReadOpenFailures`),()=>/* @__PURE__ */ new WeakSet);
//!src/state/openclaw-agent-canonical-validation-schema.ts
const validatedSchemas=resolveGlobalSingleton(Symbol.for(`openclaw.agentCanonicalValidationSchemas`),()=>/* @__PURE__ */ new WeakMap);const expectedDefinitions=/* @__PURE__ */ new Map([[`session_canonical_validation_pending`,normalizeSchemaSql(extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL,`session_canonical_validation_pending`))]]);
//!src/state/openclaw-agent-db-validation-facts.ts
const agentDatabaseValidationKey={name:`agent.completed-validation`,lifetime:`process`,read(e){return isRecord(e)?e:void 0}};
//!src/state/openclaw-agent-db-validation-observation.ts
const validationObservations=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseValidationObservations`),()=>/* @__PURE__ */ new Map);function createAgentValidationObservation(e,t){function releaseValidationObservation(e){validationObservations.get(e)?.close()}function observeValidationPath(n,r){const i=validationObservations.get(n);if(i)return r?i.revalidate():i.ready;const revalidate=async()=>{const r=e(n);if(!r||Atomics.load(new Int32Array(r.valid),0)!==1)return;try{assertDatabaseFileIdentity(await stat(n,{bigint:true}),{key:`file:${r.identity}`,birthtime:r.birthtime})}catch{if(e(n)===r)t(n,r.identity)}};const a=observeOwnedDirectory(path.dirname(n),(e,t)=>{if(t===`change`&&e!==void 0)return;if(e===void 0||(process.platform===`win32`?e.toLowerCase()===path.basename(n).toLowerCase():e===path.basename(n)))revalidate()});const o=revalidate();validationObservations.set(n,{revalidate,ready:o,close(){a.close();validationObservations.delete(n)}});return o.finally(()=>{const e=validationObservations.get(n);if(e?.ready===o)delete e.ready})}return{observe:observeValidationPath,release:releaseValidationObservation}}
//!src/state/openclaw-agent-db-validation-cache.ts
const validatedPaths=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseValidatedPaths`),()=>/* @__PURE__ */ new Map,()=>clearOpenClawAgentDatabaseValidationCache());const validationObservation=createAgentValidationObservation(e=>validatedPaths.get(e)?.validation,invalidatePathValidation);const validationBindings=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseValidationBindings`),()=>/* @__PURE__ */ new WeakMap);function invalidateOpenClawAgentDatabaseValidation(e,t){invalidatePathValidation(typeof e===`string`?resolveDatabasePathKey(e):e.canonicalPath,t)}function invalidatePathValidation(e,t=validatedPaths.get(e)?.validation?.identity){const n=/* @__PURE__ */ new Set([e]);if(t){for(const[e,r]of validatedPaths)if(r.validation?.identity===t)n.add(e)}for(const e of n){validationObservation.release(e);const t=validatedPaths.get(e);const n=t?.validation;if(n)Atomics.store(new Int32Array(n.valid),0,0);validatedPaths.set(e,{agentId:t?.agentId,validation:n,integrityVerified:false,revoked:true})}}function clearOpenClawAgentDatabaseValidationCache(e){const t=e===void 0?void 0:resolveDatabasePathKey(e);for(const e of validatedPaths.keys())if(t===void 0||isPathInside(t,e)){invalidateOpenClawAgentDatabaseValidation(e);validatedPaths.delete(e)}}
//!src/state/openclaw-agent-board-schema.ts
const ensureBoardTables=createSqliteSchemaEnsurer(()=>OPENCLAW_AGENT_BOARD_SCHEMA_SQL,{tables:[`board_tabs`,`board_widgets`],indexes:[`idx_agent_board_widgets_tab_position`]});
//!src/state/openclaw-agent-session-participants-schema.ts
const ensureNativeSessionParticipantsSchema=createSqliteSchemaEnsurer(sessionParticipantsSchemaSql,{tables:[SESSION_PARTICIPANTS_TABLE]});
//!src/state/agent-database-preparation-context.ts
const preparation=new AsyncContext(Symbol(`agentDatabasePreparation`));const inputRecovery=new AsyncContext(Symbol(`agentInputRecovery`));export{runOpenClawStateWriteTransaction as a,resolveOpenClawAgentDatabaseDiscoveryPaths as c,readRetainedAgentDeletionsFromDatabase as i,ensureAgentDatabaseLeaseSchema as l,agentDatabaseValidationKey as n,recoverOrphanTaskDeliveryRows as o,readAgentDatabaseDeletionSnapshot as r,resolveSchemaMigrationIntegrityCheck as s,invalidateOpenClawAgentDatabaseValidation as t,createSqliteSchemaEnsurer as u};