openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
62 lines • 33.9 kB
JavaScript
import{G as e,Jt as t,Lt as n}from"./sqlite-readonly-subsystem-Bfq7Sewc.mjs";import{Et as r}from"./sqlite-readonly-runtime-process-manifest-DDSkIpjb.mjs";import{hn as i,ht as a,on as o,wt as s,yt as c}from"./sqlite-readonly-sqlite-database-admission-Bj6bmeyX.mjs";import{o as l}from"./sqlite-readonly-openclaw-state-db-async-lifecycle-BwAy3Dr9.mjs";import"./sqlite-readonly-openclaw-state-db-contract-DiFTYPe3.mjs";import{c as u,l as d,m as f}from"./sqlite-readonly-node-sqlite-C-jA8uc4.mjs";import{c as p,t as m}from"./sqlite-readonly-sqlite-schema-sql-BnVx4b5A.mjs";import{A as h,L as g,M as _,j as v}from"./sqlite-readonly-location.worker.js";import{f as ee}from"./sqlite-readonly-pool-m9JiklDF.mjs";import{o as te}from"./sqlite-readonly-sqlite-user-version-BkFOLx6X.mjs";import{a as ne,i as y,n as b,r as re}from"./sqlite-readonly-openclaw-state-db-schema-helpers-CIpJmYmJ.mjs";import{t as x}from"./sqlite-readonly-openclaw-state-db-schema-version-Coirf-v2.mjs";import S from"node:path";import{realpathSync as C}from"node:fs";import{AsyncLocalStorage as w}from"node:async_hooks";const ie=n(Symbol.for(`openclaw.gatewayServiceInstallation`),()=>new w);function getGatewayServiceInstallation(){return ie.getStore()?.installation}function isGatewayExternallySupervised(e=process.env){return e.OPENCLAW_SUPERVISOR_MODE?.trim().toLowerCase()===`external`}function objectPath(e){return g`string_to_array(substr(${e}, 3), '.')`}function jsonPathValue(e,t,n,r=`text`){if(!o(e))return g`json_extract(${t}, ${n})`;let i=g`(${t}::jsonb ${g.raw(r===`json`?`#>`:`#>>`)} ${objectPath(n)})`;return g`${i}${g.raw(r===`number`?`::double precision`:r===`json`?`::text`:``)}`}function jsonValid(e,t){return o(e)?g`pg_input_is_valid(${t}, 'json')`:g`json_valid(${t})`}function jsonPickObject(e,t,n){return o(e)?g`(SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)::text
FROM jsonb_each(CASE WHEN jsonb_typeof(${t}::jsonb) = 'object' THEN ${t}::jsonb ELSE '{}'::jsonb END)
WHERE key IN (${g.join(n)}))`:g`(SELECT json_group_object(key, CASE type
WHEN 'object' THEN json(value) WHEN 'array' THEN json(value)
WHEN 'true' THEN json('true') WHEN 'false' THEN json('false')
ELSE value END) FROM json_each(${t}) WHERE key IN (${g.join(n)}))`}const T=n(Symbol.for(`openclaw.stateDatabaseSchemaPolicies`),()=>({scopes:new w,existingDatabases:/* @__PURE__ */ new WeakMap,hasAdmittedExistingDatabase:!1}));function canonicalPath(e){let t=l({path:e});try{return i(C.native(t))}catch(e){if(r(e,`ENOENT`))return t;throw e}}function assertSchemaScopeActive(e){if(e&&!e.active)throw Error(`Existing shared-state schema admission has ended.`)}function getExistingOpenClawStateSchemaPath(){let e=T.scopes.getStore();return assertSchemaScopeActive(e),e?.path}function captureOpenClawStateSchemaReadAdmission(e){let t=T.scopes.getStore();if(t)return isExistingOpenClawStateSchema(e),{path:t.path,assertCurrent:()=>assertSchemaScopeActive(t)}}function isExistingOpenClawStateSchema(e,t){let n=getExistingOpenClawStateSchemaPath(),r=T.scopes.getStore(),i=t&&T.existingDatabases.get(t);if(!r&&!i)return!1;let a=l({path:e}),o=n!==void 0&&(n===a||r?.canonicalPath===a||r?.canonicalPath===canonicalPath(a));if(n&&!o)throw Error(`Existing shared-state schema admission is bound to ${n}, not ${e}.`);if(i&&(!o||i!==r?.canonicalPath))throw Error(`Shared-state database ${e} was admitted without schema repair; close its existing handle before ordinary admission.`);return o}function recordExistingOpenClawStateSchemaDatabase(e,t){let n=T.scopes.getStore();if(!n||!isExistingOpenClawStateSchema(t,e))throw Error(`Existing shared-state schema admission requires its active path scope.`);T.existingDatabases.set(e,n.canonicalPath),T.hasAdmittedExistingDatabase=!0}function assertExistingOpenClawStateSchemaCacheAdmission(e,t){let n=getExistingOpenClawStateSchemaPath();if(!T.hasAdmittedExistingDatabase)return;let r=T.scopes.getStore(),i=r?l({path:e}):void 0,a=r&&(n===i||r.canonicalPath===i)?r.canonicalPath:void 0;for(let n of[t.cachedDatabases,t.retainedDatabaseHandles])for(let{db:t}of n.values()){let n=T.existingDatabases.get(t);n&&t.isOpen&&(a??=canonicalPath(e),n===a&&isExistingOpenClawStateSchema(e,t))}}function assertOpenClawStateSchemaRepairAllowed(e){if(isExistingOpenClawStateSchema(e))throw Error(`Shared-state schema repair is owned by the existing installation at ${e}; run openclaw doctor --fix with that installation. The managed node retries automatically.`)}function captureSqliteWorkerStateContext(e){return{databaseEngineSelection:e.databaseEngineSelection??ee(),environment:{...e.environment},initializationCronDefaultStoreKey:e.initializationCronDefaultStoreKey,...e.initializationEnvironment?{initializationEnvironment:{...e.initializationEnvironment}}:{},...e.initializationAgentPaths?{initializationAgentPaths:[...e.initializationAgentPaths]}:{},existingSchemaPath:e.existingSchemaPath,gatewayServiceInstallation:e.gatewayServiceInstallation,...e.stateIntegrity?{stateIntegrity:e.stateIntegrity}:{},artifactPreservingReads:e.artifactPreservingReads,liveStateReads:e.liveStateReads,...e.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.scheduledMaintenanceSuspension}:{}}}function sqliteWorkerRequestBytes(e,t,n){let r=t?.initializationAgentPaths?.reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0)??0;return[t?.environment,t?.initializationEnvironment].reduce((e,t)=>Object.entries(t??{}).reduce((e,[t,n])=>e+Buffer.byteLength(t,`utf8`)+Buffer.byteLength(n??``,`utf8`),e),e.byteLength+Buffer.byteLength(JSON.stringify(t?.databaseEngineSelection)??``,`utf8`)+Buffer.byteLength(JSON.stringify(t?.gatewayServiceInstallation)??``,`utf8`)+(n?.byteLength??0)+r+Buffer.byteLength(t?.initializationCronDefaultStoreKey??``,`utf8`)+(t?.scheduledMaintenanceSuspension?.byteLength??0))}const E=n(Symbol.for(`openclaw.sqliteWorkerStateContext`),()=>new w);function captureSqliteWorkerWalMaintenanceSuspension(){let e=E.getStore()?.scheduledMaintenanceSuspension;if(!e)return;let t=new Int32Array(e);return()=>Atomics.load(t,0)>0}function getSqliteWorkerCronDefaultStoreKey(){return E.getStore()?.initializationCronDefaultStoreKey}function getSqliteWorkerExistingDatabaseIdentity(e){let t=E.getStore()?.existingDatabase;return t?.databasePath===e?t.identity:void 0}function getSqliteWorkerStateIntegrityAdmission(){return E.getStore()?.stateIntegrity}const D=`cron.defaultStoreKey`;function resolveLegacyCronDefaultStoreKey(t){return S.resolve(e(t),`cron`,`jobs.json`)}function resolveCronIdentityMigrationDefaultStoreKey(e){return getSqliteWorkerCronDefaultStoreKey()??resolveLegacyCronDefaultStoreKey(e)}function readBindingRow(e,t){if(t?.has(`config_machine_state`)??y(e,`config_machine_state`))return v(e,_(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,D))}function resolveUnboundCronDefaultStoreKey(e,t){return e.length===0||e.some(e=>e.storeKey===t)?t:void 0}const O=[[`cron_jobs`,`jobs`],[`cron_job_scratch`,`scratch`],[`cron_run_receipts`,`receipts`]];function readCronStorePartitionInventoryInDatabase(e,n){let r=/* @__PURE__ */ new Map,add=(e,t,n)=>{if(typeof e!=`string`||e.length===0)return;let i=r.get(e);i||(i={storeKey:e,jobs:0,scratch:0,receipts:0,history:0,quarantine:0,proactiveReceipts:0},r.set(e,i)),i[t]+=n};for(let[t,r]of O)if(n?.has(t)??y(e,t)){let n=_(e).selectFrom(t).select(`store_key`).select(e=>e.fn.countAll().as(`count`)).groupBy(`store_key`);for(let t of h(e,n).rows)add(t.store_key,r,Number(t.count))}if(n?.has(`cron_run_logs`)??y(e,`cron_run_logs`)){let t=_(e).selectFrom(`cron_run_logs`).select(`store_key`).select(e=>e.fn.countAll().as(`count`)).groupBy(`store_key`);for(let n of h(e,t).rows)add(n.store_key,`history`,Number(n.count))}if(n?.has(`task_runs`)??y(e,`task_runs`)){let n=_(e).selectFrom(`task_runs`).select(t=>[g`CASE WHEN ${jsonValid(e,t.ref(`detail_json`))}
THEN ${jsonPickObject(e,t.ref(`detail_json`),[`storeKey`])} END`.as(`detail_json`)]).where(`runtime`,`=`,`cron`);for(let r of h(e,n).rows)if(typeof r.detail_json==`string`)try{let e=JSON.parse(r.detail_json);t(e)&&add(e.storeKey,`history`,1)}catch{}}if(n?.has(`diagnostic_events`)??y(e,`diagnostic_events`)){let t=_(e).selectFrom(`diagnostic_events`).select(`scope`).select(e=>e.fn.countAll().as(`count`)).where(`scope`,`like`,`cron.quarantine:%`).groupBy(`scope`);for(let n of h(e,t).rows)typeof n.scope==`string`&&add(n.scope.slice(16),`quarantine`,Number(n.count))}if(n?.has(`config_machine_state`)??y(e,`config_machine_state`)){let t=_(e).selectFrom(`config_machine_state`).select(`state_key`).where(`state_key`,`like`,`automation-default:%`);for(let n of h(e,t).rows)add(n.state_key.slice(19,n.state_key.lastIndexOf(`:`)),`proactiveReceipts`,1)}return[...r.values()].toSorted((e,t)=>e.storeKey<t.storeKey?-1:+(e.storeKey>t.storeKey))}const k={version:34,tables:[`config_machine_state`],columns:[],migrate:(e,t,n)=>migrateCronDefaultStoreIdentity(e,{previousVersion:t,legacyDefaultStoreKey:n.legacyCronDefaultStoreKey??resolveCronIdentityMigrationDefaultStoreKey(n.env)}),applied:`Introduced durable default cron partition selection (v34)`};function migrateCronDefaultStoreIdentity(e,t){if(t.previousVersion>=34||readBindingRow(e,t.sourceTables))return!1;let n=t.fresh?t.legacyDefaultStoreKey:void 0;if(!t.fresh){if(O.some(([n])=>(t.sourceTables?.has(n)??y(e,n))&&v(e,_(e).selectFrom(n).select(`store_key`).where(`store_key`,`=`,t.legacyDefaultStoreKey).limit(1))))n=t.legacyDefaultStoreKey;else{let r=readCronStorePartitionInventoryInDatabase(e,t.sourceTables);n=resolveUnboundCronDefaultStoreKey(r,t.legacyDefaultStoreKey)??(r.length===1?r[0]?.storeKey:void 0)}}return n!==void 0&&(h(e,_(e).insertInto(`config_machine_state`).values({state_key:D,value_json:JSON.stringify(n),updated_at_ms:t.nowMs??Date.now()})),!0)}const A=[`github_publication_requests`,`github_personal_publication_requests`,`github_repository_publication_requests`];function needsPublicationDraftMigration(e){return A.some(t=>y(e,t)&&!ne(e,t,`draft`))}const ae={version:28,tables:A,columns:A.map(e=>`${e}.draft`),migrate:e=>{let t=!1;for(let n of A)t=b(e,n,`draft INTEGER`)||t;return t},applied:`Retained the requested GitHub PR draft choice (v28)`};function withLegacyPublicationDraft(e){return e.replace(/(CREATE TABLE(?: IF NOT EXISTS)? "?github_(?:personal_|repository_)?publication_requests"? \([\s\S]*?)\n {2}(?:"draft" bigint|draft INTEGER),/gu,`$1`)}const j=[[`workspace_setup_state`,`bootstrap_deferred`,`INTEGER`,!0],[`agent_deletion_journal`,`phase`,`TEXT`,!0],[`agent_database_leases`,`provenance`,`TEXT`,!0],[`user_profile_identities`,`canonical_login`,`TEXT`],[`user_profile_identities`,`authorization_id`,`TEXT`],[`user_profile_identities`,`authorization_basis_json`,`TEXT`],[`user_profile_identities`,`verified_email_json`,`TEXT`,!0],[`template_installs`,`bootstrap_content_digest`,`TEXT`],[`template_installs`,`bootstrap_source_path`,`TEXT`],[`worker_environments`,`desktop_json`,`TEXT`],[`worker_environments`,`bootstrap_install_kind`,`TEXT`],[`worker_environments`,`preparation_purpose`,`TEXT`],[`template_package_refs`,`extension_adapter_identity`,`TEXT`],[`template_package_refs`,`extension_detected_format`,`TEXT`],[`template_package_refs`,`extension_format`,`TEXT`],[`template_package_refs`,`extension_id`,`TEXT`],[`template_package_refs`,`extension_mapped_json`,`TEXT`],[`template_package_refs`,`extension_unavailable_json`,`TEXT`],[`worker_environments`,`shared_host`,`INTEGER`],[`worker_environments`,`node_setup_id`,`TEXT`],[`worker_environments`,`node_device_id`,`TEXT`],[`worker_session_placements`,`terminal_reason`,`TEXT`],[`worker_session_placements`,`terminal_at_ms`,`INTEGER`],[`worker_workspace_pending_results`,`repository_workspace_id`,`TEXT`,!0],[`worker_session_placement_moves`,`abandon_source`,`INTEGER`,!0],[`worker_session_placement_moves`,`target_machine_class`,`TEXT`,!0],[`worker_session_placement_moves`,`target_os`,`TEXT`,!0],[`worktrees`,`run_end_cleanup_json`,`TEXT`],[`worktrees`,`gc_protection_json`,`TEXT`],[`device_bootstrap_tokens`,`setup_id`,`TEXT`,!0],[`session_groups`,`cwd`,`TEXT`,!0],[`session_groups`,`worktree`,`INTEGER`,!0],[`secret_store_entries`,`allowed_hosts`,`TEXT`],[`web_push_subscriptions`,`device_id`,`TEXT`,!0],[`web_push_subscriptions`,`user_profile_id`,`TEXT`,!0],[`web_push_subscriptions`,`preferences_json`,`TEXT`,!0],[`task_runs`,`execution_owner_host`,`TEXT`,!0],[`task_runs`,`execution_owner_pid`,`INTEGER`,!0],[`task_runs`,`execution_owner_start_identity`,`INTEGER`,!0],[`session_watch_cursors`,`watcher_store_path`,`TEXT`,!0],[`subagent_runs`,`requester_store_path`,`TEXT`,!0],[`subagent_runs`,`controller_store_path`,`TEXT`,!0],[`cron_jobs`,`grant_definition_revision`,`TEXT`],[`cron_jobs`,`grant_definition_generation`,`INTEGER`],[`cron_jobs`,`grant_definition_updated_at`,`INTEGER`]];function lazyColumnDefinitions(e){return j.filter(t=>e===void 0||!!t[3]===e).map(([e,t,n])=>({columnName:t,dataType:n,tableName:e}))}const M=lazyColumnDefinitions(),N=lazyColumnDefinitions(!1),P=lazyColumnDefinitions(!0),F={packageUpdatedAt:[[`template_package_refs`,`updated_at_ms INTEGER NOT NULL DEFAULT 0`]],packageIntegrity:[[`template_package_refs`,`package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'`]],diagnosticSequence:[[`diagnostic_events`,`sequence INTEGER NOT NULL DEFAULT 0`]],cronRunLogs:[[`worktrees`,`provisioned_paths_json TEXT`],[`apns_registrations`,`relay_origin TEXT`],[`device_pairing_pending`,`refreshed_at_ms INTEGER`],[`device_pairing_pending`,`browser_origin TEXT`],[`device_pairing_paired`,`approved_via TEXT`],[`device_pairing_paired`,`browser_origin TEXT`],[`device_pairing_paired`,`operator_label TEXT`],[`device_pairing_paired`,`node_surface_json TEXT`],[`device_pairing_paired`,`pending_node_surface_json TEXT`],[`cron_run_logs`,`status TEXT`],[`cron_run_logs`,`error TEXT`],[`cron_run_logs`,`summary TEXT`],[`cron_run_logs`,`diagnostics_summary TEXT`],[`cron_run_logs`,`delivery_status TEXT`],[`cron_run_logs`,`delivery_error TEXT`],[`cron_run_logs`,`delivered INTEGER`],[`cron_run_logs`,`session_id TEXT`],[`cron_run_logs`,`session_key TEXT`],[`cron_run_logs`,`run_id TEXT`],[`cron_run_logs`,`run_at_ms INTEGER`],[`cron_run_logs`,`duration_ms INTEGER`],[`cron_run_logs`,`next_run_at_ms INTEGER`],[`cron_run_logs`,`model TEXT`],[`cron_run_logs`,`provider TEXT`],[`cron_run_logs`,`total_tokens INTEGER`],[`cron_run_logs`,`entry_json TEXT NOT NULL DEFAULT '{}'`],[`cron_run_logs`,`created_at INTEGER NOT NULL DEFAULT 0`]],acpReplay:[[`acp_replay_events`,`estimated_bytes INTEGER NOT NULL DEFAULT 0`],[`acp_replay_sessions`,`estimated_bytes INTEGER NOT NULL DEFAULT 0`]],cronJobs:[[`cron_jobs`,`description TEXT`],[`cron_jobs`,`declaration_key TEXT`],[`cron_jobs`,`owner_agent_id TEXT`],[`cron_jobs`,`name TEXT NOT NULL DEFAULT ''`],[`cron_jobs`,`enabled INTEGER NOT NULL DEFAULT 1`],[`cron_jobs`,`agent_id TEXT`],[`cron_jobs`,`payload_kind TEXT NOT NULL DEFAULT 'message'`],[`cron_jobs`,`state_json TEXT NOT NULL DEFAULT '{}'`],[`cron_jobs`,`runtime_updated_at_ms INTEGER`],[`cron_jobs`,`schedule_identity TEXT`],[`cron_jobs`,`sort_order INTEGER NOT NULL DEFAULT 0`]],deliveryQueue:[[`sandbox_registry_entries`,`session_key TEXT`],[`sandbox_registry_entries`,`backend_id TEXT`],[`sandbox_registry_entries`,`runtime_label TEXT`],[`sandbox_registry_entries`,`image TEXT`],[`sandbox_registry_entries`,`created_at_ms INTEGER`],[`sandbox_registry_entries`,`last_used_at_ms INTEGER`],[`sandbox_registry_entries`,`config_label_kind TEXT`],[`sandbox_registry_entries`,`config_hash TEXT`],[`sandbox_registry_entries`,`cdp_port INTEGER`],[`sandbox_registry_entries`,`no_vnc_port INTEGER`],[`delivery_queue_entries`,`entry_kind TEXT`],[`delivery_queue_entries`,`session_key TEXT`],[`delivery_queue_entries`,`channel TEXT`],[`delivery_queue_entries`,`target TEXT`],[`delivery_queue_entries`,`account_id TEXT`],[`delivery_queue_entries`,`retry_count INTEGER NOT NULL DEFAULT 0`],[`delivery_queue_entries`,`last_attempt_at INTEGER`],[`delivery_queue_entries`,`last_error TEXT`],[`delivery_queue_entries`,`recovery_state TEXT`],[`delivery_queue_entries`,`platform_send_started_at INTEGER`]],originalMediaRoot:[[`managed_outgoing_image_records`,`original_media_root TEXT NOT NULL DEFAULT ''`]],beforeTaskAttribution:[[`managed_outgoing_image_records`,`agent_id TEXT`],[`managed_outgoing_image_records`,`cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))`],[`current_conversation_bindings`,`conversation_kind TEXT NOT NULL DEFAULT 'channel'`],[`device_bootstrap_tokens`,`pending_profile_json TEXT`],[`gateway_restart_handoff`,`restart_trace_started_at INTEGER`],[`gateway_restart_handoff`,`restart_trace_last_at INTEGER`],[`gateway_restart_intent`,`reason TEXT`],[`gateway_restart_sentinel`,`delivery_channel TEXT`],[`gateway_restart_sentinel`,`delivery_to TEXT`],[`gateway_restart_sentinel`,`delivery_account_id TEXT`],[`gateway_restart_sentinel`,`message TEXT`],[`gateway_restart_sentinel`,`continuation_json TEXT`],[`gateway_restart_sentinel`,`doctor_hint TEXT`],[`gateway_restart_sentinel`,`stats_json TEXT`],[`gateway_boot_lifecycle`,`startup_reason TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_mode TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_key_id TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_signature_count INTEGER`],[`official_external_plugin_catalog_snapshots`,`trust_threshold INTEGER`],[`official_external_plugin_catalog_snapshots`,`trust_verified_at TEXT`]],taskRequester:[[`task_runs`,`requester_agent_id TEXT`]],taskRunDetails:[[`task_runs`,`tool_use_count INTEGER`],[`task_runs`,`last_tool_name TEXT`],[`task_runs`,`detail_json TEXT`]],workerEnvironments:[[`worker_environments`,`bootstrap_bundle_hash TEXT`],[`worker_environments`,`bootstrap_openclaw_version TEXT`],[`worker_environments`,`bootstrap_protocol_features_json TEXT`],[`worker_environments`,`bootstrap_install_kind TEXT`],[`worker_environments`,`owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0)`],[`worker_environments`,`ssh_host_key TEXT`],[`worker_workspace_pending_results`,`staged_result_ref TEXT`],[`worker_environments`,`teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed'))`]]},I=[[`claw_installs`,`template_installs`],[`claw_workspace_files`,`template_workspace_files`],[`claw_package_refs`,`template_package_refs`],[`claw_cron_refs`,`template_cron_refs`],[`claw_mcp_server_refs`,`template_mcp_server_refs`]],L=[[`template_installs`,`claw_name`,`template_name`],[`template_installs`,`claw_version`,`template_version`],[`template_package_refs`,`claw_name`,`template_name`]],R=new Set(I.map(([,e])=>e)),z=N.filter(({tableName:e})=>R.has(e)),B=[...F.packageUpdatedAt,...F.packageIntegrity],V=[[`template_installs`,[1,2,3].map(e=>[`openclaw.clawInstallRecord.v${e}`,`openclaw.templateInstallRecord.v${e}`])],[`template_workspace_files`,[[`openclaw.clawWorkspaceFileRecord.v1`,`openclaw.templateWorkspaceFileRecord.v1`]]],[`template_package_refs`,[[`openclaw.clawPackageRef.v1`,`openclaw.templatePackageRef.v1`]]],[`template_cron_refs`,[[`openclaw.clawCronRef.v1`,`openclaw.templateCronRef.v1`]]],[`template_mcp_server_refs`,[[`openclaw.clawMcpServerRef.v1`,`openclaw.templateMcpServerRef.v1`]]]],literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function legacyTemplateStateIdentifier(e){for(let[t,n]of[...I,...L.map(([,e,t])=>[e,t])])if(e===n)return t;return e}function withLegacyTemplateStateSchema(e){return e.replace(/\btemplate_(?:installs|workspace_files|package_refs|cron_refs|mcp_server_refs|name|version)\b/gu,legacyTemplateStateIdentifier).replaceAll(`'template-introduced'`,`'claw-introduced'`).replaceAll(`'template'`,`'claw'`)}function withLegacyTemplateStateCompatibility(e){return{...e,excludedTables:e.excludedTables?.map(withLegacyTemplateStateSchema),allowedMissingTables:e.allowedMissingTables?.map(withLegacyTemplateStateSchema),allowedMissingColumns:e.allowedMissingColumns?.map(withLegacyTemplateStateSchema),allowedColumnDefinitions:e.allowedColumnDefinitions&&Object.fromEntries(Object.entries(e.allowedColumnDefinitions).map(([e,t])=>[withLegacyTemplateStateSchema(e),t.map(withLegacyTemplateStateSchema)]))}}function versionUpdates(e,t){return`UPDATE ${p(e)} SET schema_version = CASE schema_version
${t.map(([e,t])=>`WHEN ${literal(e)} THEN ${literal(t)}`).join(`
`)}
ELSE schema_version END WHERE schema_version IN (${t.map(([e])=>literal(e)).join(`, `)});`}function migrateTemplateStateNames(e,t){if(t>=36)return!1;let n=f(e),r=new Set(n.tables),i=/* @__PURE__ */ new Set([...I.flat(),`agent_provenance`]),a=new Map([...n.tableSql].flatMap(([e,t])=>t&&i.has(e)?[[e,new Set(s(t,e).columns.keys())]]:[])),addColumn=(t,n)=>{let r=n.trim().split(/\s+/,1)[0],i=a.get(t);return!r||!i||i.has(r)?!1:(e.exec(`ALTER TABLE ${p(t)} ADD COLUMN ${n};`),i.add(r),!0)},o=!1;for(let[t,n]of I)if(r.has(t)){if(r.has(n))throw Error(`Both ${t} and ${n} exist; preserve the store for Doctor inspection.`);e.exec(`ALTER TABLE ${p(t)} RENAME TO ${p(n)};`),r.delete(t),r.add(n);let i=a.get(t);if(!i)throw Error(`Missing predecessor column contract for ${t}`);a.set(n,i),a.delete(t),o=!0}for(let[t,n,r]of L)a.get(t)?.has(n)&&(e.exec(`ALTER TABLE ${p(t)} RENAME COLUMN ${p(n)} TO ${p(r)};`),a.get(t)?.delete(n),a.get(t)?.add(r),o=!0);for(let{tableName:e,columnName:t,dataType:n}of z)addColumn(e,`${t} ${n}`);let c=_(e);addColumn(...F.packageUpdatedAt[0])&&h(e,c.updateTable(`template_package_refs`).set(e=>({updated_at_ms:e.ref(`installed_at_ms`)})));for(let[e,t]of F.packageIntegrity)addColumn(e,t);let l=f(e),u={template_package_refs:[`origin`,`claw-introduced`,`template-introduced`],template_mcp_server_refs:[`origin`,`claw-introduced`,`template-introduced`],agent_provenance:[`created_via`,`claw`,`template`]};for(let t of[`template_installs`,...Object.keys(u)]){let n=l.tableSql.get(t);if(!n)continue;let r=n.slice(n.indexOf(`(`)),i=r;for(let[e,,n]of L)e===t&&(i=i.replaceAll(p(n),n));let a=u[t];if(a&&(i=i.replaceAll(literal(a[1]),literal(a[2]))),i===r)continue;let c=p(`${t}_migration_v36`),d=[...s(n,t).columns.keys()],f=/\bWITHOUT\s+ROWID\b/iu.test(n)?[]:[`rowid`],m=[...f,...d].map(p).join(`, `),h=[...f.map(p),...d.map(e=>a&&e===a[0]?`CASE ${p(e)} WHEN ${literal(a[1])} THEN ${literal(a[2])} ELSE ${p(e)} END`:p(e))].join(`, `);e.exec(`CREATE TABLE ${c} ${i};
INSERT INTO ${c} (${m}) SELECT ${h} FROM ${p(t)};
DROP TABLE ${p(t)};
ALTER TABLE ${c} RENAME TO ${p(t)};`);for(let n of[...l.indexDefinitions.values(),...l.triggers.values()])n.table===t&&typeof n.sql==`string`&&e.exec(n.sql);o=!0}for(let[t,n]of V)if(r.has(t))for(let[r,i]of n)h(e,c.updateTable(t).set({schema_version:i}).where(`schema_version`,`=`,r));return o}const H={version:36,tables:[...I.flat(),`agent_provenance`,`sqlite_stat1`,`sqlite_stat4`],columns:[...z.map(({tableName:e,columnName:t})=>`${e}.${t}`),...B.map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)],migrate:migrateTemplateStateNames,applied:`Migrated released starter tables and provenance to canonical Template names (v36)`},U=`DO $template_names_v36$
DECLARE item record; column_item record; constraint_name text; next_constraint_name text;
BEGIN
FOR item IN SELECT * FROM (VALUES
${I.map(([e,t])=>`(${literal(e)}, ${literal(t)})`).join(`,
`)}
) AS names(old_name, new_name) LOOP
EXECUTE format('ALTER TABLE %I RENAME TO %I', item.old_name, item.new_name);
FOR column_item IN SELECT * FROM (VALUES
${L.map(([e,t,n])=>`(${literal(e)}, ${literal(t)}, ${literal(n)})`).join(`,
`)}
) AS columns(table_name, old_name, new_name) WHERE table_name = item.new_name LOOP
EXECUTE format('ALTER TABLE %I RENAME COLUMN %I TO %I', item.new_name, column_item.old_name, column_item.new_name);
END LOOP;
FOR constraint_name IN SELECT conname FROM pg_constraint
WHERE conrelid = to_regclass(item.new_name) LOOP
next_constraint_name := constraint_name;
IF left(constraint_name, length(item.old_name) + 1) = item.old_name || '_' THEN
next_constraint_name := item.new_name || substr(constraint_name, length(item.old_name) + 1);
END IF;
next_constraint_name := replace(replace(next_constraint_name, '_claw_name_', '_template_name_'), '_claw_version_', '_template_version_');
IF next_constraint_name <> constraint_name THEN
EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', item.new_name, constraint_name, next_constraint_name);
END IF;
END LOOP;
END LOOP;
${[`template_package_refs`,`template_mcp_server_refs`].map(e=>`
ALTER TABLE ${p(e)} DROP CONSTRAINT ${p(`${e}_origin_check`)};
UPDATE ${p(e)} SET origin = 'template-introduced' WHERE origin = 'claw-introduced';
ALTER TABLE ${p(e)} ADD CONSTRAINT ${p(`${e}_origin_check`)}
CHECK (origin IN ('template-introduced', 'pre-existing'));`).join(`
`)}
IF to_regclass('agent_provenance') IS NOT NULL THEN
ALTER TABLE agent_provenance DROP CONSTRAINT agent_provenance_created_via_check;
UPDATE agent_provenance SET created_via = 'template' WHERE created_via = 'claw';
ALTER TABLE agent_provenance ADD CONSTRAINT agent_provenance_created_via_check
CHECK (created_via IN ('operator', 'agent', 'template'));
END IF;
${V.map(([e,t])=>versionUpdates(e,t)).join(`
`)}
END $template_names_v36$;`,W=[`local_workspace_tree_packs`,`local_workspace_source_path_sets`],G=[`tree_root_digest`,`source_paths_digest`,`canonical_fingerprints`,`projection_fingerprints`];function migrateLocalWorkspaceCas(e,t){if(t>=35||!y(e,`local_workspace_projections`))return!1;for(let t of G)b(e,`local_workspace_projections`,`${t} BLOB`);for(let t of W)e.exec(m(a,t));return!0}const K={version:35,tables:[`local_workspace_projections`,...W],columns:G.map(e=>`local_workspace_projections.${e}`),migrate:migrateLocalWorkspaceCas,applied:`Prepared shared content-addressed workspace trees and compact scan fingerprints (v35)`};function withLegacyLocalWorkspaceCas(e){return e.replace(/\n {2}(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints) BLOB,/gu,``).replace(/\n {2}"(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints)" bytea,/gu,``).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_(?:tree_packs|source_path_sets)"? \([\s\S]*?\n\)(?: STRICT(?:, WITHOUT ROWID)?)?;\n?/gu,``)}const q=`local_workspace_projections`,J=`local_workspace_manifest_nodes`,Y=`CHECK ((baseline_json IS NULL) = (baseline_ref IS NULL))`,X=`CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL)`;function migrateLocalWorkspaceManifests(e,t){if(t>=31||!y(e,q))return!1;b(e,q,`checkpoint_json TEXT`);let n=u(e)??f(e),r=n.tableSql.get(q);if(typeof r!=`string`)throw Error(`Local workspace projection migration schema is missing`);if(r.includes(Y)){let t=p(`${q}_migration_v31`),i=p(q),a=[...re(e,q)].map(p).join(`, `),o=r.slice(r.indexOf(`(`)).replace(Y,X);e.exec(`CREATE TABLE ${t} ${o};
INSERT INTO ${t} (rowid, ${a}) SELECT rowid, ${a} FROM ${i};
DROP TABLE ${i};
ALTER TABLE ${t} RENAME TO ${i};`);for(let t of[...n.indexDefinitions.values(),...n.triggers.values()])t.table===q&&typeof t.sql==`string`&&e.exec(t.sql)}else if(!r.includes(X))throw Error(`Local workspace baseline constraint is not recognized; preserve it for Doctor`);return e.exec(m(a,J)),!0}const oe={version:31,tables:[q,J],columns:[`${q}.checkpoint_json`],migrate:migrateLocalWorkspaceManifests,applied:`Prepared resumable per-path local workspace baselines and checkpoint deltas (v31)`};function withLegacyLocalWorkspaceManifests(e){return withLegacyLocalWorkspaceCas(e).replace(/\n {2}(?:checkpoint_json TEXT|"checkpoint_json" text COLLATE "C"),/gu,``).replace(/^ {2}CHECK \([^\n]*baseline_json[^\n]*baseline_ref[^\n]*\),$/gmu,e=>e.includes(`"`)?` CHECK ((("baseline_json" IS NULL) = ("baseline_ref" IS NULL))),`:` ${Y},`).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_manifest_nodes"? \([\s\S]*?\n\)(?: STRICT)?;\n?/gu,``).replace(/ALTER TABLE "local_workspace_manifest_nodes" ADD FOREIGN KEY[^;]*;\n?/gu,``)}const se={version:37,tables:[`worker_environments`],columns:[`worker_environments.resource_receipt_json`],migrate(e,t){return t>=37?!1:b(e,`worker_environments`,`resource_receipt_json TEXT`)},applied:`Retained immutable worker provider resource receipts (v37)`};function withLegacyWorkerResourceReceipts(e){return e.replace(/,\n {2}resource_receipt_json TEXT(?=\n\))|\n {2}"resource_receipt_json" text COLLATE "C",/gu,``)}const Z=[se,{version:38,tables:[`session_repository_workspaces`,`worker_workspace_pending_results`],columns:[`session_repository_workspaces.disk_authority_json`,`worker_workspace_pending_results.repository_disk_authority_json`],migrate(e,t){if(t>=38)return!1;let n=b(e,`session_repository_workspaces`,`disk_authority_json TEXT`),r=b(e,`worker_workspace_pending_results`,`repository_disk_authority_json TEXT`);return n||r},applied:`Retained repository disk authority and original pending-result authority (v38)`}];function withLegacyRepositoryDiskAuthority(e){return e.replace(/\n {2}(?:(?:disk_authority_json|repository_disk_authority_json) TEXT|"(?:disk_authority_json|repository_disk_authority_json)" text COLLATE "C"),/gu,``)}const ce={version:39,tables:[`worker_environments`],columns:[`worker_environments.retention_json`],migrate(e,t){return t>=39?!1:b(e,`worker_environments`,`retention_json TEXT`)},applied:`Retained worker acquisition policy, unfinished operation, and observations (v39)`};function withLegacyWorkerRetention(e){return e.replace(/,\n {2}retention_json TEXT(?=\n\))|\n {2}"retention_json" text COLLATE "C",/gu,``)}function withLegacyWorkspaceBootstrapDeferred(e){return e.replace(` bootstrap_deferred INTEGER,
`,``).replace(` "bootstrap_deferred" bigint,
`,``)}function withLegacyStateV40Additions(e){return withLegacyWorkspaceBootstrapDeferred(e).replace(/CREATE TABLE IF NOT EXISTS device_pairing_browser_requests \([\s\S]*?\) STRICT;\n\n/u,``)}const le={version:40,tables:[`worker_environments`],columns:[`worker_environments.provision_source_json`],migrate(e,t){if(t>=40||!y(e,`worker_environments`))return!1;let n=b(e,`worker_environments`,`provision_source_json TEXT`),r=e.prepare(`UPDATE worker_environments
SET provision_source_json = '{"kind":"unavailable"}'
WHERE (state IN ('requested', 'provisioning') AND lease_id IS NULL
OR state = 'bootstrapping' AND owner_epoch = 0)
AND provision_source_json IS NULL`).run();return n||Number(r.changes)>0},applied:`Original worker provisioning source retained across recovery (v40)`};function withLegacyWorkerProvisionSource(e){return e.replace(/,\n {2}provision_source_json TEXT(?=\n\))|\n {2}"provision_source_json" text COLLATE "C",/gu,``)}var ue=c();const Q=18e5,$=3e5;function isUnfencedUpdateDriver(e){let t=typeof e==`string`?(0,ue.parse)(e):null;return t!==null&&`${t.major}.${t.minor}.${t.patch}`==`2026.9.2`}function readStateSchemaPublicationBlocker(e,n=Date.now()){if(!y(e,`update_runs`))return;let r=h(e,_(e).selectFrom(`update_runs`).select([`run_id`,`before_json`,`status`,`updated_at_ms`,`finished_at_ms`]).where(e=>e.or([e.and([e(`status`,`=`,`running`),e(`updated_at_ms`,`>=`,n-Q)]),e.and([e(`status`,`!=`,`running`),e.or([e(`finished_at_ms`,`>`,n-$),e(`finished_at_ms`,`is`,null)])])])).orderBy(`run_id`)).rows,i;for(let e of r){let n=JSON.parse(e.before_json);if(!t(n)||typeof n.version!=`string`||!isUnfencedUpdateDriver(n.version))continue;let r=e.status===`running`?e.updated_at_ms+Q+1:e.finished_at_ms===null?null:e.finished_at_ms+$;(!i||r===null||i.publishAfterMs!==null&&r>i.publishAfterMs)&&(i={runId:e.run_id,updaterVersion:n.version,publishAfterMs:r})}return i}function resolveStateSchemaVersionToPublish(e){let t=te(e);if(t>=40||!readStateSchemaPublicationBlocker(e))return 40;if(!y(e,`config_machine_state`))throw Error(`Shared state schema publication cannot be deferred without config_machine_state.`);return writeStateSchemaContentVersion(e),d(e),t}function writeStateSchemaContentVersion(e){h(e,_(e).insertInto(`config_machine_state`).values({state_key:x,value_json:`40`,updated_at_ms:Date.now()}).onConflict(e=>e.column(`state_key`).doUpdateSet({value_json:`40`,updated_at_ms:Date.now()}).where(`config_machine_state.value_json`,`!=`,`40`)))}function advanceStateSchemaContentVersion(e,t){h(e,_(e).updateTable(`config_machine_state`).set({value_json:String(t.toVersion)}).where(`state_key`,`=`,x).where(`value_json`,`=`,String(t.fromVersion)))}export{needsPublicationDraftMigration as A,getSqliteWorkerStateIntegrityAdmission as B,H as C,M as D,P as E,resolveLegacyCronDefaultStoreKey as F,getExistingOpenClawStateSchemaPath as G,assertExistingOpenClawStateSchemaCacheAdmission as H,k as I,jsonPathValue as J,isExistingOpenClawStateSchema as K,captureSqliteWorkerStateContext as L,withLegacyPublicationDraft as M,migrateCronDefaultStoreIdentity as N,N as O,resolveCronIdentityMigrationDefaultStoreKey as P,captureSqliteWorkerWalMaintenanceSuspension as R,legacyTemplateStateIdentifier as S,withLegacyTemplateStateSchema as T,assertOpenClawStateSchemaRepairAllowed as U,sqliteWorkerRequestBytes as V,captureOpenClawStateSchemaReadAdmission as W,isGatewayExternallySupervised as X,jsonValid as Y,getGatewayServiceInstallation as Z,W as _,Q as a,U as b,withLegacyStateV40Additions as c,withLegacyWorkerRetention as d,Z as f,withLegacyLocalWorkspaceManifests as g,oe as h,writeStateSchemaContentVersion as i,ae as j,F as k,withLegacyWorkspaceBootstrapDeferred as l,withLegacyWorkerResourceReceipts as m,readStateSchemaPublicationBlocker as n,le as o,withLegacyRepositoryDiskAuthority as p,recordExistingOpenClawStateSchemaDatabase as q,resolveStateSchemaVersionToPublish as r,withLegacyWorkerProvisionSource as s,advanceStateSchemaContentVersion as t,ce as u,K as v,withLegacyTemplateStateCompatibility as w,I as x,withLegacyLocalWorkspaceCas as y,getSqliteWorkerExistingDatabaseIdentity as z};