UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

120 lines • 66 kB
import{i as e,o as t,s as n}from"./transcript-record-coerce-eN4p5mcq.mjs";import{i as r}from"./transcript-global-singleton-DIJgobpU.mjs";import{c as i,d as a}from"./transcript-openclaw-agent-search-schema-BQwqsKhe.mjs";import"./transcript-plugin-instance-invocation-7pP9ZY8b.mjs";import"./transcript-worker-cpu-DTToyx8O.mjs";import{t as o}from"./transcript-detached-async-context-BKXaSw-L.mjs";import{$ as s,Et as c,P as l,b as u,c as d,et as f,f as p,ht as m,l as h,mt as g,v as ee,z as _}from"./transcript-sqlite-database-admission-Cro6ZHgY.mjs";import{n as v}from"./transcript-path-guards-DYqTo0Vr.mjs";import{d as te,f as ne,m as re,r as ie,t as ae}from"./transcript-sqlite-worker-identity-C2ykgpDo.mjs";import{r as y}from"./transcript-sqlite-error-diagnostics-Bzt01wuM.mjs";import{t as b}from"./transcript-async-context-CWIqzhI4.mjs";import{t as oe}from"./transcript-sqlite-reader-lifecycle-D3Huvbzy.mjs";import{i as se,n as ce,t as x}from"./transcript-subsystem-er2pCebD.mjs";import{o as S,r as le}from"./transcript-string-coerce-BxRUqIXb.mjs";import{d as ue,n as C}from"./transcript-sqlite-table-layout-migration-6FYoXQ_h.mjs";import{n as de}from"./transcript-json-coercion-FJNyjMmt.mjs";import{n as fe}from"./transcript-state-dir-BTeq06tQ.mjs";import{r as pe}from"./transcript-src-DFL7yLCI.mjs";import{t as me}from"./transcript-errors-BSE2KXjf.mjs";import{t as he}from"./transcript-version-cakuJMg_.mjs";import{t as ge}from"./transcript-deferred-B75K7ut7.mjs";import"./transcript-async-work-scope-CAkmTBjq.mjs";import{n as _e,r as w}from"./transcript-sql-connection-CRz-dHXM.mjs";import{a as ve,l as ye,o as be,s as xe,t as Se,u as Ce}from"./transcript-sqlite-post-commit-BDZjIt2B.mjs";import{c as we,u as Te}from"./transcript-session-metadata-unavailable-error-DL1m1RWN.mjs";import"./transcript-openclaw-state-db-contract-DiFTYPe3.mjs";import{n as Ee,r as De,t as Oe}from"./transcript-kysely-sync-cache-state-9JTloBF9.mjs";import{c as ke,t as T}from"./transcript-sqlite-schema-sql-BnVx4b5A.mjs";import{t as Ae}from"./transcript-usingCtx-03vOGQ3v.mjs";import{h as je,o as E,t as Me}from"./transcript-sqlite-schema-facts-C4Tsn8VX.mjs";import{n as D}from"./transcript-agent-id-DmscQLD6.mjs";import{l as Ne}from"./transcript-openclaw-agent-db.paths-5mfY5--s.mjs";import{a as Pe,r as Fe,s as Ie}from"./transcript-openclaw-state-db.paths-DYRyvCKa.mjs";import{r as Le}from"./transcript-session-key-normalization-CxaUSpng.mjs";import"./transcript-session-key-DI46891-.mjs";import{n as Re,t as ze}from"./transcript-chat-type-CPEXaa5z.mjs";import{_ as Be,h as Ve}from"./session-transcript.worker.js";import{a as O,h as He,i as k,o as Ue,r as A}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import{a as We,t as Ge}from"./transcript-sqlite-transaction-BxeoS_ke.mjs";import{a as Ke}from"./transcript-sqlite-busy-timeout-DspDnAK7.mjs";import{d as j}from"./transcript-agent-scope-config-D354VjAZ.mjs";import{C as qe,D as Je,G as Ye,K as Xe,P as Ze,S as Qe,U as $e,W as et,b as tt,c as nt,d as rt,g as M,h as N,j as it,l as P,n as at,nt as ot,p as st,r as ct,tt as lt,u as F,x as ut}from"./transcript-openclaw-agent-db-schema-read-0j86l7zG.mjs";import{D as dt,E as ft,K as pt,W as mt,bt as ht,g as gt,k as _t,o as vt,tt as yt,v as bt,y as xt}from"./transcript-openclaw-state-db-cache-DY0tZ0IC.mjs";import{r as St,t as Ct}from"./transcript-openclaw-agent-db-borrower-CEWh9POj.mjs";import{b as wt,t as Tt}from"./transcript-openclaw-quarantine-store-Cpfq2f44.mjs";import{t as Et}from"./transcript-sqlite-schema-catalog-DeSRZE9G.mjs";import{a as Dt,i as Ot,m as kt,r as I,s as At}from"./transcript-worker-task-pool-xHbAfEur.mjs";import"./transcript-child-CaF3s4Mr.mjs";import{t as L}from"./transcript-pid-alive-CqZqK_fT.mjs";import{$ as R,A as jt,Ct as Mt,Q as Nt,St as Pt,Tt as Ft,W as It,_t as Lt,a as Rt,c as zt,et as Bt,gt as Vt,mt as Ht,rt as Ut,u as Wt,xt as Gt}from"./transcript-openclaw-state-db-readonly-wvpVS-us.mjs";import"./transcript-session-row-changes-DzgVgiDT.mjs";import{a as z,d as Kt,i as B,l as qt,n as V,s as H,u as Jt}from"./transcript-openclaw-state-db-schema-helpers-DTvLbSq6.mjs";import{i as Yt,o as Xt}from"./transcript-openclaw-agent-db-identity-BwKDyjmN.mjs";import{g as Zt}from"./transcript-sqlite-search-schema-6CT7CNVB.mjs";import{N as Qt}from"./transcript-openclaw-agent-trajectory-storage-migration-DjoMAPIY.mjs";import{F as $t,N as en,P as tn,R as nn,u as U,w as W}from"./transcript-openclaw-agent-db-validation-cache-CPj39b9d.mjs";import{t as rn}from"./transcript-sqlite-schema-ensure-CzveatKm.mjs";import{_ as an,a as G,c as on,d as sn,i as cn,l as ln,o as un,p as dn,r as fn,s as pn,u as mn}from"./transcript-openclaw-agent-schema-history-FA8O-tkY.mjs";import{t as hn}from"./transcript-openclaw-agent-progress-card-schema-CiZBJdzW.mjs";import{n as gn,t as _n}from"./transcript-conversation-ref-DKugNmX7.mjs";import{i as vn}from"./transcript-session-entry-json-Bunk1tNp.mjs";import{r as yn,t as bn}from"./transcript-sqlite-commit-receipt-B-xcw-Ul.mjs";import{a as xn,d as Sn,n as Cn,o as wn,r as Tn,t as En,u as Dn}from"./transcript-openclaw-state-db-DbakxDr-.mjs";import{d as On}from"./transcript-openclaw-agent-db-owner-read-DYchwk6B.mjs";import"./transcript-sqlite-worker-store-EaynLmvH.mjs";import{t as kn}from"./transcript-openclaw-agent-board-schema-c65OQI5T.mjs";import{channel as An}from"node:diagnostics_channel";import{serialize as jn}from"node:v8";import{isMainThread as Mn,threadId as K}from"node:worker_threads";import q from"node:path";import{createHash as Nn,randomUUID as Pn}from"node:crypto";import Fn,{statSync as In}from"node:fs";import{stat as Ln}from"node:fs/promises";import{performance as J}from"node:perf_hooks";import{addAbortListener as Rn,setMaxListeners as zn}from"node:events";new b(Symbol.for(`openclaw.gatewayWorkAdmissionState`)),new b(Symbol.for(`openclaw.gatewayReloadWaitingRoots`)),new b(Symbol(`gatewaySubscriptionRootWork`));function createShutdownCleanupController(){let e=new AbortController;return zn(0,e.signal),e}const Y=r(Symbol.for(`openclaw.gatewayWorkAdmissionState`),()=>({restartDrainReason:void 0,restartDrainController:new AbortController,shutdownCleanupController:createShutdownCleanupController(),restartSignalPending:!1,restartSignalGeneration:0,suspendPhase:`accepting`,suspendGeneration:0,activeRootWork:/* @__PURE__ */ new Set,rootWorkReleaseListeners:/* @__PURE__ */ new Set,suspendOpenWaiters:/* @__PURE__ */ new Set,suspendListeners:/* @__PURE__ */ new Set}));var GatewayDrainingError=class extends Error{constructor(e=gatewayWorkAdmissionMessage()){super(e),this.name=`GatewayDrainingError`}};x(`gateway/admission`);function gatewayWorkAdmissionMessage(){return Y.restartDrainReason?.startsWith(`stop (`)?`Gateway is shutting down. Please try again once it is back online.`:isGatewayRestartDraining()?`Gateway is restarting. Please try again shortly.`:Y.suspendPhase===`accepting`?`Gateway is temporarily unavailable. Please try again shortly.`:`Gateway is temporarily paused. Please try again shortly.`}function isGatewayRestartDraining(){return Y.restartDrainReason!==void 0||Y.restartSignalPending}function getGatewayRestartDrainSignal(){return Y.restartDrainController.signal}function getGatewayShutdownCleanupSignal(){return Y.shutdownCleanupController.signal}function isGatewayRestartDrainError(e){if(!isGatewayRestartDraining())return!1;try{return e instanceof GatewayDrainingError}catch{return!1}}const Bn=[`template_package_refs`,`template_mcp_server_refs`,`template_cron_refs`];function readTemplateSecondaryReferenceTables(e,t){return Bn.filter(n=>B(e,n)?!!e.prepare(`SELECT 1 FROM ${n} WHERE agent_id = ? LIMIT 1`).get(t):!1)}function hasTemplateDeletionOwnership(e,t){let n=O(e.db);return[`template_installs`,`template_workspace_files`].some(r=>B(e.db,r)&&k(e.db,n.selectFrom(r).select(`agent_id`).where(`agent_id`,`=`,t).limit(1))!==void 0)||readTemplateSecondaryReferenceTables(e.db,t).length>0}const Vn=r(Symbol.for(`openclaw.stateDomainPublicationBatch`),()=>({current:void 0}));function createStateDomainPublication(e){let 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){let n=r(Symbol.for(`openclaw.stateDomainPublication.${e.domain}`),()=>({sources:/* @__PURE__ */ new WeakMap,facts:/* @__PURE__ */ new Set,installingFacts:0})),sourceFor=t=>{let r=w(t),i=n.sources.get(r);return i||(i={identity:e.sourceIdentity?.(t)??_t(t)?.key??Symbol(e.domain),incarnation:Pn()},n.sources.set(r,i)),i},receiptFor=(t,n)=>bn({source:sourceFor(t),domain:e.domain,keys:[...n.keys()],readFact:e=>n.get(e)}),install=t=>{let r=[];n.installingFacts++;try{ye(n.facts,t,e=>r.push(e))}finally{n.installingFacts--}if(r.length)throw AggregateError(r,e.installFailureMessage??`State domain fact installation failed`)},publication=e=>{let t={kind:`committed`,receipt:e};return{installFacts:()=>install(t),invalidate(){t={kind:`unknown`,identity:e.source.identity},install(t)},notify(){}}},stage=(t,r)=>{if(e.mutationDuringInstallMessage&&n.installingFacts)throw Error(e.mutationDuringInstallMessage);if(!r.size)return;let i=n.capture;if(i&&w(i.db)===w(t)){let e=new Map([...r.keys()].map(e=>[e,i.facts.get(e)]));if(!xe(t,{stage(){for(let[e,t]of r)i.facts.set(e,t)},commit(){},rollback(){for(let[t,n]of e)n?i.facts.set(t,n):i.facts.delete(t)}}))throw Error(`State domain capture requires its owning transaction`)}let a=publication(receiptFor(t,r));!be(t,a)&&!t.isTransaction&&ve(a)},readReceipt=(t,n=e.isFact)=>yn(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,t){let r=n.capture,i=r&&w(r.db)===w(e)?r:{db:e,facts:/* @__PURE__ */ new Map};n.capture=i;try{return{result:t(),receipt:receiptFor(e,i.facts)}}finally{n.capture=r}},bound(e){return jn(e).byteLength<=8388608?e:{kind:`unknown`,identity:e.source.identity}},subscribeFacts:e=>Ce(n.facts,e),begin(r,i=e.isFact){let a=Pn(),o=/* @__PURE__ */ new Set,s=!1,c=!1,l=!1,u=!1,d=Ce(n.facts,e=>{if(!s){if(e.kind===`committed`&&e.receipt.source.identity===r.identity)for(let t of e.receipt.facts.keys())o.add(t);else e.kind===`unknown`&&e.identity===r.identity&&(c=!0)}});try{r.publishPending!==!1&&install({kind:`pending`,identity:r.identity,operationId:a})}catch(e){d();try{install({kind:`settled`,identity:r.identity,operationId:a})}catch{}throw e}return{committed(n,a){try{if(r.assertCurrent(),u)throw Error(e.closedMessage??`State domain publication owner is closed`);if(t(n)&&n.kind===`unknown`&&n.identity===r.identity)install({kind:`unknown`,identity:r.identity});else{let t=readReceipt(n,i);if(t.source.identity!==r.identity)throw Error(e.changedOwnerMessage??`State domain commit receipt changed owner`);let a=publication({...t,facts:new Map([...t.facts].map(([e,t])=>[e,c||o.has(e)?{kind:`unknown`}:t]))}),l={...a,installFacts(){s=!0;try{a.installFacts()}finally{s=!1}}};Vn.current?Vn.current.push(l):ve(l)}l=!0,a?.()}catch(e){throw install({kind:`unknown`,identity:r.identity}),e}finally{s=!1}},finish(e,t=!1){if(!u){u=!0,d();try{e&&(l||t)||install({kind:`unknown`,identity:r.identity})}finally{r.publishPending!==!1&&install({kind:`settled`,identity:r.identity,operationId:a})}}}}}}}createStateDomainPublication({domain:`agent-provenance`,keyOf:e=>e.agentId,isValue:e=>t(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`}),createStateDomainPublication({domain:`agent-deletion-journal`,keyOf:e=>e.agentId,isValue:e=>t(e)&&typeof e.agentId==`string`&&typeof e.operationId==`string`&&typeof e.cleanupCompleted==`boolean`});function resolveLegacyMigrationSourceKey(e,t,n){let r=Nn(`sha256`);return n!==void 0&&r.update(n).update(`\0`),`${e}:${r.update(q.resolve(t)).digest(`hex`)}`}function readLegacyMigrationReceiptFromDatabase(e,t){let n=k(e,O(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}function parseHolds(e){return e.map(e=>{if(!t(e)||typeof e.agentId!=`string`||e.agentId!==D(e.agentId)||typeof e.path!=`string`||!e.path.trim())throw Error(`Invalid agent database hold in deletion journal reconstruction receipt.`);return{agentId:e.agentId,path:e.path}})}function readReport(e){let n=readLegacyMigrationReceiptFromDatabase(e.db,`agent-deletion-journal-reconstruction`);if(!n)return;let r=JSON.parse(n.reportJson);if(!t(r)||typeof r.description!=`string`||!Array.isArray(r.held))throw Error(`Invalid agent deletion journal reconstruction receipt.`);let i=parseHolds(r.held);if(r.missingJournal!==void 0&&!Array.isArray(r.missingJournal))throw Error(`Invalid missing-journal provenance in deletion journal reconstruction receipt.`);let a=Array.isArray(r.missingJournal)?parseHolds(r.missingJournal):r.description===`Reconstructed the missing agent deletion journal; held databases require explicit agent restore or delete.`?i:[];if(a.some(e=>!i.some(t=>t.agentId===e.agentId&&t.path===e.path)))throw Error(`Missing-journal provenance refers to an unheld agent database.`);return{...r,description:r.description,held:i,missingJournal:a}}function decodeHolds(e,t){return t.map(t=>({agentId:t.agentId,path:Pe(e.path,t.path)}))}function readAgentDeletionRecoveryHolds(e){return decodeHolds(e,readReport(e)?.held??[])}function parseAgentDeletionDatabasePaths(e){let t=JSON.parse(e);if(n(t))return t;throw Error(`Invalid agent deletion database path journal.`)}function readRetainedAgentDeletionsFromDatabase(e,t,n=`maintenance`,r){let i=[],a=!1,o;try{if(a=!B(e,`agent_deletion_journal`),!a){let t=He(),a=t.and([t(`cleanup_completed`,`=`,1),t(`delete_files`,`=`,0)]),s=n===`runtime`?a:t.or([a,t(`cleanup_completed`,`=`,0)]);i=A(e,O(e).selectFrom(`agent_deletion_journal`).select([`agent_id`,`cleanup_completed`]).select(z(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=>{if(r?.push({agentId:t.agent_id,status:t.cleanup_completed===1?`complete`:`pending`}),t.agent_dir===null)return[];let i=[];try{i=parseAgentDeletionDatabasePaths(t.database_paths_json)}catch(e){n===`maintenance`&&(o??=me(e))}let a={agentId:t.agent_id,agentDir:t.agent_dir,databasePaths:[q.join(t.agent_dir,`openclaw-agent.sqlite`),...i],cleanupCompleted:t.cleanup_completed===1};return t.cleanup_completed===0&&t.phase==null&&hasTemplateDeletionOwnership({db:e},t.agent_id)&&(a.manualTemplateRemoval=!0),a})}}catch(e){if(y(e))throw e;o=me(e)}let s=[];try{B(e,`migration_sources`)&&(s=readAgentDeletionRecoveryHolds({db:e,path:t}))}catch(e){if(n===`maintenance`||y(e))throw e}return a&&s.length===0&&xn(e)?{status:`empty`}:a||o!==void 0?{status:`unavailable`,cause:a?`missing`:`unreadable`,reason:a?`deletion journal missing`:`deletion journal unreadable: ${o}`,...i.length||s.length?{known:{entries:i,held:s}}:{}}:i.length||s.length?{status:`present`,entries:i,held:s}:{status:`empty`}}function readAgentDatabaseDeletionSnapshot(e,t=`maintenance`){return Rt(({db:e,path:n})=>We(e,()=>({retainedDeletions:readRetainedAgentDeletionsFromDatabase(e,n,t),registeredAgentDatabases:On(e,n,!1)}),{operationLabel:`agentDeletionJournal.snapshot`}),{env:e})}var AgentDatabaseDeletionRefusedError=class extends Error{};function assertAgentDeletionIdentityClaimAllowed(e,t){if(t&&D(e)===D(t))throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database is unavailable while agent ${D(t)} is deleted.`)}function readAgentDeletionPathFenceRows(e,t=`runtime`,n){t===`maintenance`&&Dn(e);try{let r=O(e),i=!0,a=r.selectFrom(`agent_deletion_journal`).selectAll();n!==void 0&&(a=a.where(`agent_id`,`=`,D(n)));let o=A(e,a).rows.map(e=>{let n=[],r=[];try{n=parseAgentDeletionDatabasePaths(e.database_paths_json),r=parseCleanupPaths(e.cleanup_paths_json)}catch(e){if(t===`maintenance`)throw e;i=!1}return Object.assign(e,{databasePaths:n,cleanupPaths:r})});return{known:i,rows:o}}catch(e){if(t===`maintenance`||y(e))throw e;return{known:!1,rows:[]}}}function prepareAgentDeletionPathFence(e,t={},n=e.fenceAgentId?`maintenance`:`runtime`){let r=t.env??process.env;return{env:r,purpose:n,claimAgentId:D(e.agentId),claimPath:q.resolve(e.path),...e.fenceAgentId?{fenceAgentId:D(e.fenceAgentId)}:{},targetPaths:wt(e.path).map(e=>j(e,r))}}function assertAgentDeletionPathFence(e,t){let n=e.db,{rows:r,known:i}=readAgentDeletionPathFenceRows(n,t.purpose);if(!i&&r.length===0)return;let a=t.fenceAgentId?void 0:it({agentId:t.claimAgentId,path:t.claimPath,statePath:e.path});a?.assertCurrent();let o=a?.assertJournal(e.path,r.map(e=>({agentId:e.agent_id,operationId:e.operation_id,cleanupCompleted:e.cleanup_completed===1}))),s=t.fenceAgentId?void 0:Be(t.claimAgentId,e.path);for(let e of r){if(t.fenceAgentId&&t.fenceAgentId!==e.agent_id||e.agent_id===o||e.cleanup_completed===1&&e.agent_id===s||e.phase===`draining`&&e.cleanup_completed!==1&&e.agent_id===t.claimAgentId&&!t.fenceAgentId||(assertAgentDeletionIdentityClaimAllowed(t.claimAgentId,e.agent_id),e.cleanup_completed===1))continue;let n=[...[e.agent_dir,e.workspace_dir,e.sessions_dir,...e.databasePaths].map(e=>({path:e,canonicalPath:j(e,t.env)})),...e.cleanupPaths.map(e=>({path:e.path,canonicalPath:j(e.canonicalPath,t.env)}))];for(let r of n){let n=t.targetPaths.find(e=>e===r.canonicalPath||v(r.canonicalPath,e));if(n)throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database ${n} is unavailable while agent ${e.agent_id} deletion owns ${r.path}.`)}}}function parseCleanupPaths(e){let r=JSON.parse(e);if(!Array.isArray(r)||!r.every(e=>t(e)&&typeof e.path==`string`&&typeof e.canonicalPath==`string`&&typeof e.parentPath==`string`&&(e.kind===`target`||e.kind===`symlink`)&&(e.dev===null||typeof e.dev==`number`&&Number.isInteger(e.dev)||typeof e.dev==`string`&&/^(0|-?[1-9][0-9]*)$/u.test(e.dev))&&(e.ino===null||typeof e.ino==`number`&&Number.isInteger(e.ino)||typeof e.ino==`string`&&/^(0|-?[1-9][0-9]*)$/u.test(e.ino))&&typeof e.coversDescendants==`boolean`&&typeof e.done==`boolean`&&(e.note===void 0||typeof e.note==`string`)&&n(e.sourcePaths)))throw Error(`Invalid agent deletion cleanup path journal.`);return r}function assertExistingOpenClawStateSchemaMetadata(e,t,n){let r=jt(e,{pathname:t});if(n>=1&&r?.schema_version===n)return n;if(n>=1&&bt(e,r))return 40;throw Error(`Existing-state schema metadata is inconsistent.`)}function assertExistingOpenClawStateSchema(e,t,n,r,i=`full`){let a=assertExistingOpenClawStateSchemaMetadata(e,t,Mt(e,t));return i===`quick`?Ye(e,t,{check:`quick`,tables:n===void 0?void 0:M(n)}):gt(e,t),n!==void 0&&F(e,t,n,r),a}function runExistingOpenClawStateWriteTransaction(e,t,n){let r=prepareExistingOpenClawStateWriter(t,n),write=()=>{let i=createExistingOpenClawStateWriter(r,n);try{return i.run(e,t)}finally{i.close()}};return n.recoverTaskDeliveryOrphans?Ut({databasePath:r.pathname},write):write()}function prepareExistingOpenClawStateWriter(e,t){if(e.database||e.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let n=e.env??process.env,r=Fe({path:e.path,env:n});pt(r),t.recoverTaskDeliveryOrphans&&mt(r);let i=Fn.lstatSync(r);if(!i.isFile())throw Error(`Existing-state write requires a regular database file.`);return{env:n,pathname:r,original:i}}function createExistingOpenClawStateWriter({env:e,pathname:t,original:n},r){let assertSameFile=()=>{let e=Fn.lstatSync(t);if(!e.isFile()||e.dev!==n.dev||e.ino!==n.ino)throw Error(`Existing-state database generation changed.`)};if(assertSameFile(),vt.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t,e),Vt())return createExistingPostgresStateWriter(t,r,assertSameFile);let i=dt(t,{existingOnly:!0,...r.recoverTaskDeliveryOrphans?{enableForeignKeyConstraints:!1}:{}}),a=xt(`state.subset:${Nn(`sha256`).update(JSON.stringify([r.schemaSql,r.schemaCompatibility,r.integrityCheck])).digest(`hex`)}`,e=>typeof e==`number`?e:void 0,r.integrityCheck===void 0?`process`:void 0),o=r.initializeAdditiveSchema?rn(()=>r.schemaSql,{tables:M(r.schemaSql),indexes:N(r.schemaSql)}):void 0,s=!1,close=()=>{s=!0,Ee(i),ft(i)};return{run(e,n){if(s||!i.isOpen)throw Error(`Existing-state writer is closed.`);if(n.database||n.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let c=n.env??process.env;if(Fe({path:n.path,env:c})!==t)throw Error(`Existing-state writer cannot change its database path.`);assertSameFile();let l=pt(t),u=n.busyTimeoutMs??r.busyTimeoutMs??5e3;Ke(i,u),Pt(i,t),!r.recoverTaskDeliveryOrphans&&r.integrityCheck===void 0&&gt(i,t);let write=()=>zt(i,()=>{assertSameFile(),It({database:i,databasePath:t,env:c});let n=a.get(i),s=n===void 0;l&&Wt(i,t);let validate=()=>assertExistingOpenClawStateSchema(i,t,s&&r.initializeAdditiveSchema?void 0:r.schemaSql,r.schemaCompatibility,r.integrityCheck),u,d=[];if(r.recoverTaskDeliveryOrphans){try{validate()}catch(e){if(!(e instanceof $e))throw e}d=Tn(i,t),u=validate()}else u=n??validate();s&&r.initializeAdditiveSchema&&(F(i,t,r.schemaSql,{...r.schemaCompatibility,allowedMissingTables:M(r.schemaSql)}),Me(i),o?.(i),F(i,t,r.schemaSql,r.schemaCompatibility)),s&&(Me(i),a.publish(i,u));let f=e({db:i,path:t,recoveryChanges:d});return assertSameFile(),r.recoverTaskDeliveryOrphans&&Ye(i,t),f},{beginLockFailureReporting:r.beginLockFailureReporting,busyTimeoutMs:u,databaseLabel:t,operationLabel:r.operationLabel});return r.attributeUpdateWrite?ue(i,t,write,{close}):write()},assertSettled(){if(assertSameFile(),Ge(i),i.isOpen&&i.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`);i.isOpen&&oe(i,`Existing-state writer`)},close}}function createExistingPostgresStateWriter(e,t,n){let r=a(()=>Lt(e));if(!r)throw Error(`Existing PostgreSQL state writer requires its selected engine`);let{db:i}=r.database,o=M(t.schemaSql);return{run(r,s){if(!i.isOpen)throw Error(`Existing-state writer is closed.`);if(s.database||s.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let c=s.env??process.env;if(Fe({path:s.path,env:c})!==e)throw Error(`Existing-state writer cannot change its database path.`);let l=!1;return a(()=>Gt(i,()=>zt(i,()=>{n(),It({database:i,databasePath:e,env:c});let a=Ft(i).catalog;for(let e of o)if(t.initializeAdditiveSchema)Ht(i,e);else if(!a.some(t=>t.kind===`table`&&t.table===e))throw Error(`Existing PostgreSQL state schema is missing ${e}`);l=!0;let s=r({db:i,path:e,recoveryChanges:[]});return n(),s},{databaseLabel:e,operationLabel:t.operationLabel,beginLockFailureReporting:t.beginLockFailureReporting}),()=>!l))},assertSettled(){if(n(),Ge(i),!i.isOpen)throw Error(`Existing-state writer retained a closed PostgreSQL connection`);if(i.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`)},close(){r.close()}}}const Hn=[`schema_meta`,`state_leases`,`agent_database_leases`].map(e=>T(s,e,{endMarker:`) STRICT;`,errorMessage:`Existing agent lease schema is unavailable.`})).join(`
`);function withExistingAgentLeaseWrite(e,t,n){return runExistingOpenClawStateWriteTransaction(({db:t})=>{e.assertOwnedInTransaction(t);let r=n(t);return e.assertOwnedInTransaction(t),r},t,{operationLabel:`agent.database.maintenance.admission`,schemaSql:Hn,integrityCheck:ot()?.sqliteIntegrityCheck,schemaCompatibility:{allowedMissingColumns:[`agent_database_leases.provenance`]}})}const Un=x(`state/agent-db`),Wn=r(Symbol.for(`openclaw.agentDatabaseCloseReceipts`),()=>new fe(128),e=>e.clear()),Gn={scope:`core:agent-database-maintenance`,key:`global`};function readAgentDatabaseLeases(e,t){let n=O(e).selectFrom(`agent_database_leases`).selectAll();return A(e,t===void 0?n:n.where(`lease_id`,`=`,t)).rows}function hasAgentDatabaseMaintenanceAuthority(){return C.getStore()!==void 0}function assertAgentDatabaseMaintenanceAuthorityIfPresent(){C.getStore()?.assertScopeCurrent?.(),C.getStore()?.authority.assertOwned()}function renewAgentDatabaseMaintenanceAuthorityIfPresent(){let e=C.getStore()?.authority;if(e){if(!e.renew)throw Error(`Agent database maintenance authority cannot renew its lease.`);e.renew()}}function claimOpenClawAgentDatabaseLease(e,t=Pn(),n){let r=D(e.agentId),i=prepareAgentDeletionPathFence({agentId:r,path:e.path},{env:e.env}),a=L(process.pid);return Cn(o=>claimAgentDatabaseLeaseInDatabase(o,{leaseId:t,agentId:r,path:e.path,ownerPid:process.pid,ownerStartTime:a,provenance:Bt(e.path)},i,n),{env:e.env,initializationAgentPaths:[e.path]}),t}function claimAgentDatabaseLeaseInDatabase(e,t,n,r){Sn(e.db);let i=O(e.db),a=k(e.db,i.selectFrom(`state_leases`).select(`owner`).where(`scope`,`=`,Gn.scope).where(`lease_key`,`=`,Gn.key).where(`expires_at`,`>`,Date.now())),o=C.getStore();if(a||o)throw Error(`Agent database maintenance is in progress; retry after openclaw doctor --fix completes.`);assertAgentDeletionPathFence(e,n);let s=!1,c,l=Nt();for(let n of readAgentDatabaseLeases(e.db)){let r=R(n.path,t.path),a=r?l(n):void 0;a?(Un.info(`agent database stale lease: ${a}; previous release not observed`,{agentId:n.agent_id,leaseId:n.lease_id,path:n.path,staleReason:a,ownerPid:n.owner_pid,ownerStartTime:n.owner_start_time}),A(e.db,i.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,n.lease_id)),reportPriorBootLeaseRelease(e.db,n.lease_id,a)):r&&n.lease_id!==t.leaseId&&(t.ownerStartTime===null||n.owner_pid!==t.ownerPid||n.owner_start_time===null||n.owner_start_time!==t.ownerStartTime)&&(s=!0,n.path===t.path&&n.provenance!==null&&n.provenance===t.provenance&&n.opened_at>0&&n.owner_start_time!==null&&L(n.owner_pid)===n.owner_start_time&&(c=n.provenance))}r?.(!s,c),A(e.db,i.insertInto(`agent_database_leases`).values({lease_id:t.leaseId,provenance:t.provenance,agent_id:t.agentId,path:t.path,owner_pid:t.ownerPid,owner_start_time:t.ownerStartTime,opened_at:0}))}function releaseOpenClawAgentDatabaseLease(e,t={},n,r){let i=performance.now(),release=t=>{let a=O(t),o=k(t,n===void 0?a.selectFrom(`agent_database_leases`).select([`path`,`agent_id`]).where(`lease_id`,`=`,e):a.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,e).returning([`path`,`agent_id`]));n===void 0&&(o&&clearAgentDatabaseLeaseVerifications(t,o.path),A(t,a.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,e)));let s,c;o?typeof n==`object`?o.path===n.path?(c=findAgentDatabasePathLease(t,n.path),s=c?`active-leases`:n.publishSeal()?`written`:`verification-missing`):s=`path-mismatch`:s=n===`uncheckpointed`?`checkpoint-incomplete`:n??`close-unconfirmed`:s=`lease-not-held`;let publish=()=>{let t=r?performance.now()-r.startedAt:0,n=t>=500,a=n?{totalMs:Math.round(t),walStopMs:Math.round(r?.walStopMs??0),checkpointMs:Math.round(r?.checkpointMs??0),nativeCloseMs:Math.round(r?.nativeCloseMs??0),leaseReleaseMs:Math.round(performance.now()-i)}:void 0,l=a?Nn(`sha256`).update(o?.path??`unknown`).digest(`hex`).slice(0,16):void 0;if(o){let e=Wn.get(o.path);if(!n&&e?.agentId===o.agent_id&&e.receipt===s&&e.blockingLeaseId===c?.lease_id)return;Wn.set(o.path,{agentId:o.agent_id,receipt:s,blockingLeaseId:c?.lease_id})}Un.info(`agent database clean-close receipt: ${s}; agent=${o?.agent_id??`unknown`}${c?`; blockingLeaseId=${c.lease_id}; ownerPid=${c.owner_pid}`:``}${a?`; db=${l}; thread=${K}; close=${JSON.stringify(a)}`:``}`,{agentId:o?.agent_id,path:o?.path,leaseId:e,receipt:s,pid:process.pid,threadId:K,...a?{close:a}:{},...s===`checkpoint-incomplete`&&r?.checkpoint?{checkpoint:r.checkpoint}:{},blockingLease:c&&{leaseId:c.lease_id,ownerPid:c.owner_pid,ownerStartTime:c.owner_start_time,path:c.path,openedAt:c.opened_at}})};Se(t,publish)||publish()},o=C.getStore(),s=q.resolve(t.database?.path??t.path??Ie(t.env));if(o?.databasePath===s)return withExistingAgentLeaseWrite(o.authority,t,release);a(()=>Cn(e=>{Sn(e.db),release(e.db)},typeof n==`object`?{...t,initializationAgentPaths:[...t.initializationAgentPaths??[],n.path]}:t))}function agentDatabaseLeasePaths(e){let t=O(e);return A(e,t.selectFrom(`agent_database_leases`).select(`path`).distinct()).rows.map(e=>e.path)}function findAgentDatabasePathLease(e,t){return readAgentDatabaseLeases(e).find(e=>R(e.path,t))}function recordOpenClawAgentDatabaseAdmission(e,t){Cn(n=>{if(Tt(t.env??process.env),A(n.db,O(n.db).updateTable(`agent_database_leases`).set({opened_at:Date.now()}).where(`lease_id`,`=`,e).where(`agent_id`,`=`,t.agentId).where(`path`,`=`,t.path).where(`owner_pid`,`=`,process.pid)).numAffectedRows!==1n)throw Error(`Agent database open lost its runtime lease: ${t.path}`)},{env:t.env},{singleStatement:!0})}function clearAgentDatabaseLeaseVerifications(e,t){for(let n of/* @__PURE__ */ new Set([t,...agentDatabaseLeasePaths(e)]))R(n,t)&&(U(n),_(n))}function assertOpenClawAgentDatabaseLease(e,t){readOpenClawAgentDatabaseLeaseClaim(e,t)}function readOpenClawAgentDatabaseLeaseClaim(e,t){let n=L(process.pid),r=En({env:t.env,initializationAgentPaths:[t.path]}),i=readAgentDatabaseLeases(r.db,e)[0];if(!i||i.agent_id!==t.agentId||i.path!==t.path||i.owner_pid!==process.pid||i.owner_start_time!==null&&n!==null&&i.owner_start_time!==n)throw Error(`Agent database open lost its runtime lease: ${t.path}`);return{database:r,held:i}}function reportPriorBootLeaseRelease(e,t,n){if(n!==`owner-prior-boot`)return;let publish=()=>Un.warn(`Released legacy agent database lease ${t} from a prior boot.`);Se(e,publish)||publish()}async function stopAgentDatabaseWalMaintenance(e){let t=performance.now();await e.walMaintenance.stop(),e.closeTiming={startedAt:t,walStopMs:performance.now()-t}}function createAgentDatabaseHandleCloser(e){return function(t){try{var n=Ae();let r=t.closeTiming??{startedAt:performance.now()};delete t.closeTiming;let i=e.leases.get(t.path),a=!t.db.isOpen,o=t.walMaintenance.health?.state===`error`,s=_e(t.db),c=w(t.db);Oe(c);let l=n.u(!a&&!s?u(c):void 0),d,f;try{!a&&!s&&Ke(c,0),De(c);let n=performance.now();t.walMaintenance.close({checkpointMode:`TRUNCATE`}),r.checkpointMs=performance.now()-n;let i=!e.failures.has(t.path)&&!o&&t.walMaintenance.health?.state!==`error`,u=!a&&i&&Yt(t);r.checkpoint={alreadyClosed:a,pathCurrent:u,state:t.walMaintenance.health?.state,logFrames:t.walMaintenance.health?.logFrames,checkpointedFrames:t.walMaintenance.health?.checkpointedFrames},f=i&&(a||u);let p=performance.now();if(t.db.isOpen&&t.db.close(),s&&c.isOpen&&c.close(),r.nativeCloseMs=performance.now()-p,u&&!s){let{canonicalPath:e}=Xt(t),n=In(`${e}-wal`,{throwIfNoEntry:!1})?.size??0;r.checkpoint.walBytes=n,l&&n===0&&(d={path:t.path,publishSeal:l.publish})}}catch(e){throw i&&(U(t.path),_(t.path)),e}i&&(releaseOpenClawAgentDatabaseLease(i.leaseId,{env:i.env,initializationAgentPaths:[t.path]},d??(f?s?`postgres-closed`:`uncheckpointed`:void 0),r),e.leases.delete(t.path)),Ze(t),Ve(t),e.idleTimers.get(t.db)?.[Symbol.dispose](),e.idleTimers.delete(t.db)}catch(e){n.e=e}finally{n.d()}}}const X=x(`state/agent-db`),Kn=1e3,Z=r(Symbol.for(`openclaw.agentDatabaseLifecycle`),()=>({...Ct,leases:/* @__PURE__ */ new Map,terminal:yt({closeByPath:e=>closeOpenClawAgentDatabaseByPath(e)}),unregisterExitClose:null,pending:/* @__PURE__ */ new Map,activePending:/* @__PURE__ */ new Set,retainedCloses:/* @__PURE__ */ new Set}));Ct.refreshIdleTimer=refreshAgentDatabaseIdleTimer,qe(e=>{if(getGatewayShutdownCleanupSignal().aborted)for(let t of Z.databases.values())Qe({path:t.path},e)&&Z.idleTimers.get(t.db)?.refresh()});const Q=createAgentDatabaseHandleCloser(Z);function registerAgentDatabaseHandle(e,t,n){Z.leases.set(e.path,{leaseId:t,env:n}),Z.databases.set(e.path,e)}function logResourceCloseFailure(e,t){X.warn(`Agent database resource close failed`,{path:e,error:t})}function unregisterUnusedAgentDatabaseExitClose(){Z.databases.size===0&&Z.retainedCloses.size===0&&(Z.unregisterExitClose?.(),Z.unregisterExitClose=null)}function startAgentDatabaseOpenTiming(e,t,n,r){let i=J.now(),a=0,o={open:0,validation:0,configuration:0,schema:0,registration:0};return s=>{let c=Math.floor(J.now()-i);o[s]=c-a,a=c,s===`validation`&&r.integrityGateReason&&X.info(`agent database integrity gate for ${e}: reason=${r.integrityGateReason}, mode=${r.integrityGateMode}, outcome=${r.integrityGateOutcome}, elapsedMs=${r.integrityGateMs??o.validation}`,{agentId:e,path:t,pid:process.pid,threadId:K,isMainThread:Mn,admissionMode:n,...r}),s===`registration`&&a>=Kn&&X.warn(`slow OpenClaw agent database open`,{agentId:e,elapsedMs:a,path:t,pid:process.pid,threadId:K,isMainThread:Mn,admissionMode:n,phaseDurationsMs:o,...r,thresholdMs:Kn})}}function retainFailedAgentDatabaseClose(e,t,n){let r={agentId:e,path:t,close:()=>{n(),Z.retainedCloses.delete(r)}};Z.retainedCloses.add(r),ot()?.own(r,`agent-handles`,r.close),Z.unregisterExitClose??=se(closeOpenClawAgentDatabases)}function revokePendingAgentDatabaseOpen(e,t){for(let n of Z.activePending)n.path===e&&(t===void 0||n.agentId===t)&&n.controller.abort(/* @__PURE__ */ Error(`Agent database open was revoked: ${e}`))}function refreshAgentDatabaseIdleTimer(e){let t=Z.idleTimers.get(e.db);if(t){t.refresh();return}let n=getGatewayShutdownCleanupSignal(),closeIdle=()=>{if(Z.databases.get(e.path)!==e)Z.idleTimers.get(e.db)?.[Symbol.dispose](),Z.idleTimers.delete(e.db);else if(!lt(e.db)&&!(e.db.isOpen&&Z.borrowers.get(e.db)?.size)){if(e.db.isOpen&&e.db.isTransaction)r.refresh();else if(!(n.aborted&&ut({path:e.path})))try{Q(e),Z.databases.delete(e.path),Z.failures.delete(e.path),unregisterUnusedAgentDatabaseExitClose()}catch(t){logResourceCloseFailure(e.path,t),r.refresh()}}},refresh=()=>{n.aborted?o(()=>queueMicrotask(closeIdle)):r.refresh()},r=o(()=>setTimeout(closeIdle,i())),a=Rn(n,refresh);r.unref(),Z.idleTimers.set(e.db,{refresh,[Symbol.dispose](){clearTimeout(r),a[Symbol.dispose]()}})}async function closeMaintenanceAgentDatabase(e){await stopAgentDatabaseWalMaintenance(e),Z.databases.get(e.path)===e&&(Q(e),Z.databases.delete(e.path),Z.failures.delete(e.path))}function createAgentDatabaseScopeOwnedClose(e,t){let n=St(e.db);return async()=>{if(Z.databases.get(e.path)===e)await closeOpenClawAgentDatabaseByPathAsync(e.path,e.agentId);else if(e.db.isOpen)throw Error(`${t} lost its database close owner.`);n()}}function closeOpenClawAgentDatabaseByPath(e,t){let n=q.resolve(e);Je({path:n,agentId:t},logResourceCloseFailure),revokePendingAgentDatabaseOpen(n,t);for(let e of Z.retainedCloses)e.path===n&&(t===void 0||e.agentId===t)&&e.close();let r=Z.databases.get(n);return!r||t!==void 0&&r.agentId!==t?!1:(Q(r),Z.databases.delete(n),Z.failures.delete(n),unregisterUnusedAgentDatabaseExitClose(),!0)}function closeOpenClawAgentDatabases(e){Je({rootPath:e},logResourceCloseFailure);for(let t of Z.pending.keys())(e===void 0||v(e,t))&&revokePendingAgentDatabaseOpen(t);for(let t of Z.retainedCloses)(e===void 0||v(e,t.path))&&t.close();for(let t of Z.databases.keys())(e===void 0||v(e,t))&&closeOpenClawAgentDatabaseByPath(t)}function recordOpenClawAgentDatabaseOpenFailure(e,t){U(e),_(e),Z.terminal.record(e,t)}async function closeOpenClawAgentDatabaseByPathAsync(e,t){let n={path:q.resolve(e),agentId:t};return revokePendingAgentDatabaseOpen(n.path,t),tt(n,async()=>{let e=[...Z.activePending].filter(e=>Qe(n,e));for(let n of e)revokePendingAgentDatabaseOpen(n.path,t);await Promise.allSettled(e.map(e=>e.promise));let r=Z.databases.get(n.path);return r&&(t===void 0||r.agentId===t)&&await stopAgentDatabaseWalMaintenance(r),closeOpenClawAgentDatabaseByPath(n.path,t)})}function acquireAgentDatabaseWriter(e,t,n,r){let i=I.acquisition;if(e!==void 0&&!i)return r?.throwIfAborted(),n(e);let a=ge();return I.acquisition=a.promise,(async()=>{try{return i&&await i,r?.throwIfAborted(),{operation:n(e??await t())}}finally{I.acquisition===a.promise&&delete I.acquisition,a.resolve()}})().then(({operation:e})=>e)}function observeBlockingWriter(e,t){let n=I.queues.get(e)?.holder;if(n&&!t.holderAtEnqueue&&(t.blockingOperation=n?.operation,t.blockingCaller=n?.caller,t.blockingWorker=n?.worker,n?.startedAt!==void 0)){let e=n.worker?.active;t.holderAtEnqueue={operation:e?.requestClass??n.operationLabel??n.caller??n.operation??`unlabeled`,threadId:e?e.threadId:K,heldMs:Math.max(0,Math.round(J.now()-(e?.startedAt??n.startedAt)))}}}const qn=An(`openclaw.agent-database.reservation`);function observeWriteAdmission(e,t,n,r,i){let a=t??{};if(a.operation??=e,a.caller??=r,a.worker??=i,t)return n(a);let o=J.now(),report=t=>{if(a.reentrant!==!1||a.startedAt===void 0||a.finishedAt===void 0||a.finishedAt-o<1e3&&!qn.hasSubscribers)return;let n=J.now(),s={operation:e,...r?{caller:r}:{},...i?{workerOperations:[...i.operations],...i.transactionCount===void 0?{}:{transactionCount:i.transactionCount}}:{},...a.holderAtEnqueue?{holderAtEnqueue:a.holderAtEnqueue}:{},...a.blockingOperation?{blockingOperation:a.blockingOperation}:{},...a.blockingCaller?{blockingCaller:a.blockingCaller}:{},...a.blockingWorker?{blockingWorkerOperations:[...a.blockingWorker.operations]}:{},outcome:t,pid:process.pid,threadId:K,isMainThread:Mn,reentrant:!1,elapsedMs:Math.round(n-o),queueWaitMs:Math.round(a.startedAt-o),writerExecutionMs:Math.round(a.finishedAt-a.startedAt),completionDelayMs:Math.round(n-a.finishedAt)};if(qn.hasSubscribers&&qn.publish(s),!(a.finishedAt-o<1e3))try{ce({subsystem:`session-sqlite`}).warn(s,`slow agent database reservation`)}catch{}};return n(a).then(e=>(report(`ok`),e),e=>{throw report(`error`),e})}function runOpenClawAgentWriteAdmission(e,t,n=!1,r,i,a,o){return runOpenClawAgentPathWriteAdmission(Ne(e),t,n,r,i,a,o)}function runOpenClawAgentPathWriteAdmission(e,t,n=!1,r,i,a,o){return runAgentDatabasePathWriteAdmission(e,t,n,r,i,a,o)}async function runAgentDatabasePathWriteAdmission(e,t,n=!1,r,i,a,o,s=!1,u){let f=s&&c(),m=d(e),g=c()&&m&&p(m)?l(e):void 0,reserve=(r,a)=>{let c=r.canonicalPath,u=r,assertCurrent=()=>{if(i?.throwIfAborted(),g){if(!g.isCurrent())throw Error(`Agent database target changed before write admission`)}else if(!f&&r.key.startsWith(`file:`))try{ie(e,r.key,r.birthtime)}catch(e){throw Error(`Agent database target changed before write admission`,{cause:e})}else if(!f&&ne(e).canonicalPath!==c)throw Error(`Agent database target changed before write admission`)};return observeBlockingWriter(c,a),ht([e],()=>Dt({queues:I.queues,storePath:c,label:`agent database write admission`,keys:o?[`transcript`]:void 0,reentrant:n&&!I.queues.get(c)?.holder?.worker,fn:async()=>{let n=I.queues.get(c),o=n.holder;n.holder=a;try{if(s&&!g){if(r.key.startsWith(`file:`))try{ae(await Ln(e,{bigint:!0}),r)}catch(e){throw Error(`Agent database target changed before write admission`,{cause:e})}else if(u=await te(e),u.canonicalPath!==c)throw Error(`Agent database target changed before write admission`);if(f){let t=await ee({location:e,identity:u,expectedIdentity:r.key.startsWith(`file:`)?r:void 0,assertCurrent:()=>i?.throwIfAborted()});if(!t||t.canonicalPath!==c)throw Error(`Agent database target changed before write admission`);if(u=t,t.key.startsWith(`file:`)){let n=h(e);if(!n||n.identity.key!==t.key||n.identity.birthtime!==t.birthtime)throw Error(`Agent database target changed before write admission`);g=l(e)}}}return i?.throwIfAborted(),(!s||g)&&assertCurrent(),await t(u,assertCurrent)}finally{n.holder=o}},timing:a,signal:i}),[],i,g?void 0:{readIdentities:/* @__PURE__ */ new Map([[e,r]])})};try{if(u?.key.startsWith(`file:`)&&g&&(g.identity.key!==u.key||g.identity.birthtime!==u.birthtime))throw Error(`Agent database target changed before write admission`);return await observeWriteAdmission(`direct`,r,t=>{observeBlockingWriter(e,t);let r=n&&g&&!I.queues.get(g.identity.canonicalPath)?.holder?.worker&&Ot(I.queues,g.identity.canonicalPath,o?/* @__PURE__ */ new Set([`transcript`]):void 0)?g.identity:void 0,a=u??r;return a?reserve(g?.identity??a,t):acquireAgentDatabaseWriter(g?.identity,()=>te(e),e=>reserve(e,t),i)},a)}finally{g?.release()}}async function runOpenClawAgentWorkerWrite(e,t,n,r,i,a,o){if(i===`background`){let t=await re(Ne(e)),n;for(;(n=I.queues.get(t)?.drainPromise)&&(I.queues.get(t)?.holder?.worker||!Ot(I.queues,t));)await pe(n,r,e=>e.reason)}let s={operations:/* @__PURE__ */ new Set};return observeWriteAdmission(`worker`,n,n=>runAgentDatabasePathWriteAdmission(Ne(e),()=>At(s,t),!0,n,r,void 0,o,!0),a,s)}function ensureLegacySessionEntryValidityTriggers(e){e.exec(ln)}function migrateCanonicalSessionWriterValidation(e){for(let t of on)e.exec(`DROP TRIGGER IF EXISTS ${t}`);V(e,`session_key_contract`,`canonical_ready TEXT`),e.exec(`
    INSERT INTO session_canonical_validation_pending (session_key)
    SELECT session_key FROM session_nodes WHERE true
    ON CONFLICT (session_key) DO NOTHING;
    UPDATE session_key_contract SET canonical_ready = NULL WHERE id = 1;
  `)}function seedCanonicalSessionValidationPending(e){e.exec(`
    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
    );
  `)}function persistAgentSchemaMetadata(e,t,n){let r=Date.now(),i={role:`agent`,schema_version:n,agent_id:t,app_version:he};A(e,O(e).insertInto(`schema_meta`).values({meta_key:`primary`,...i,created_at:r,updated_at:r}).onConflict(e=>e.column(`meta_key`).doUpdateSet({...i,updated_at:r}).where(e=>e.or([e(`schema_meta.schema_version`,`!=`,n),e(`schema_meta.app_version`,`is`,null),e(`schema_meta.app_version`,`!=`,he),e(`schema_meta.agent_id`,`!=`,t)])))),nt(e,{role:`agent`,schemaVersion:n,agentId:t})}const Jn=/* @__PURE__ */ new Set([`direct`,`dm`,`group`,`channel`]);function isCanonicalPeerKind(e){return Jn.has(e??``)}function hasAmbiguousCanonicalSessionPeerShape(e){let t=e.split(`:`);return t[0]!==`agent`&&[!(t[0]!==`direct`&&t[0]!==`dm`||!t[1]),!!(t[0]&&isCanonicalPeerKind(t[1])&&t[2]),!!(t[0]&&t[1]&&isCanonicalPeerKind(t[2])&&t[3]),deriveBuiltInLegacySessionChatType(e)!==void 0].filter(Boolean).length>1}function parseCanonicalSessionPeerShape(e){let t=e.split(`:`);if(t[0]===`agent`||hasAmbiguousCanonicalSessionPeerShape(e))return;let n,r,i=0;if(t[0]===`direct`||t[0]===`dm`?(r=t[0],i=1):t[0]&&isCanonicalPeerKind(t[1])?(n=t[0],r=t[1],i=2):t[0]&&t[1]&&isCanonicalPeerKind(t[2])&&(n=t[0],r=t[2],i=3),!r||!t[i])return;let a=r===`direct`||r===`dm`?`direct`:r;return{...n?{channel:n}:{},chatType:a}}function deriveBuiltInLegacySessionChatType(e){if(/^group:[^:]+(?::.*)?$/u.test(e))return`group`;if(/^channel:[^:]+(?::.*)?$/u.test(e))return`channel`;if(/^(?:whatsapp:)?[^:]+@g\.us$/.test(e))return`group`;if(/^discord:(?:[^:]+:)?guild-[^:]+:channel-[^:]+$/.test(e))return`channel`}function deriveSessionChatTypeFromKey(e,t=[]){let n=le(e);if(!n)return`unknown`;let r=Le(n)?.rest??n,i=parseCanonicalSessionPeerShape(r)?.chatType;if(i)return i;let a=deriveBuiltInLegacySessionChatType(r);if(a)return a;for(let e of t){let t=e(r);if(t)return t}return`unknown`}function migrateLegacySessionCreator(e){let n=e,r=e.createdActor??(t(n.createdBy)?{...n.createdBy,type:`human`,source:`unknown`}:void 0);if(r?.type!==`human`)return e;let i=r.source===`profile`||r.source===`channel`||r.source===`unknown`?r.source:e.createdVia===`operator`||e.createdVia===`run`?`profile`:e.createdVia===`channel`?`channel`:`unknown`;if(r===e.createdActor&&i===r.source&&!n.createdBy)return e;let a={...n,createdActor:{...r,source:i}};return delete a.createdBy,a}function assertSupportedAgentMigrationSchemas(e,t,n){if(n<8&&[`sessions`,`session_entries`,`transcript_events`].some(t=>B(e,t))||B(e,`session_transcript_files`)||readSqliteTableColumns(e,`session_transcript_fts`)?.has(`session_key`))throw new H(`OpenClaw agent database ${t} contains an unreleased session schema (version ${n}). Preserve a complete copy of your state directory and configuration, including shared agent registration. Run "openclaw doctor --fix" with OpenClaw 2026.9.7 against that copy. If a store is held, follow Doctor's explicit agent-restoration instructions, then rerun Doctor before retrying the upgrade.`);let r=readSqliteTableColumns(e,`acp_parent_stream_events`),i=readSqliteTableColumns(e,`trajectory_runtime_events`),a=readSqliteTableColumns(e,`memory_index_sources`);if(r&&!r.has(`session_id`)||i?.has(`event_id`)||a?.has(`source_kind`))throw new H(`OpenClaw agent database ${t} has an unsupported legacy schema. Upgrades from pre-July-2026 state are no longer migrated; restore a backup produced by a July 2026 or newer release before retrying.`)}function migrateSessionTranscriptGenerations(e,t){if(t>=13)return;let n=e.prepare(`INSERT OR IGNORE INTO transcript_rewrite_watermarks (session_id, generation, updated_at)
     SELECT session_id, lower(hex(randomblob(16))), ?
     FROM transcript_events
     GROUP BY session_id`);n.setReadBigInts(!0),n.run(Date.now())}function migrateSessionTranscriptActiveProjection(e,t){if(t>=10)return;let n=readSqliteTableColumns(e,`session_transcript_index_state`);n&&!n.has(`active_event_count`)&&e.exec(`ALTER TABLE session_transcript_index_state ADD COLUMN active_event_count INTEGER NOT NULL DEFAULT 0;`),n&&!n.has(`active_message_count`)&&e.exec(`ALTER TABLE session_transcript_index_state ADD COLUMN active_message_count INTEGER NOT NULL DEFAULT 0;`),e.exec(`
    DELETE FROM session_transcript_active_events;
    UPDATE session_transcript_index_state
    SET needs_rebuild = 1,
        active_event_count = 0,
        active_message_count = 0,
        updated_at = ${Date.now()};
  `)}function inferMigratedChatType(e){let t=ze(S(e.entry.chatType))??ze(e.persistedChatType);if(t)return t;let n=deriveSessionChatTypeFromKey(e.sessionKey);if(n!==`unknown`)return n;let r=e.deliveryTarget?.toLowerCase();return r?.startsWith(`channel:`)||/^[^:]+:channel:/u.test(r??``)?`channel`:/^(?:[^:]+:)?(?:group|room):/u.test(r??``)||S(e.entry.groupId)?`group`:`direct`}function migratedConversation(t,n,r){let i=e(t.delivery),a=e(i?.context)??e(t.deliveryContext),o=e(i?.origin)??e(t.origin),s=S(a?.to),c=S(o?.from),l=inferMigratedChatType({entry:t,persistedChatType:n,sessionKey:r,deliveryTarget:s??c}),u=s??(l===`direct`?c:void 0);if(!u)return;let d=!!s,f=(d?S(a?.channel)??S(t.channel)??S(t.lastChannel)??S(o?.provider):S(o?.provider))?.toLowerCase(),p=Re(d?S(a?.accountId)??S(t.lastAccountId)??S(o?.accountId):S(o?.accountId)),m=d?a?.threadId:o?.threadId,h=typeof m==`number`&&Number.isFinite(m)?String(m):S(m),g=f?gn(f,u):void 0;if(f&&g)return{conversationRef:_n({channel:f,accountId:p,kind:l,peerId:g,threadId:h}),channel:f,accountId:p,kind:l,peerId:g,deliveryTarget:u,threadId:h,nativeChannelId:S(o?.nativeChannelId),nativeDirectUserId:S(o?.nativeDirectUserId),label:S(t.displayName)??S(t.label)??S(t.subject)??S(t.groupId)}}function backfillSessionConversations(e){if(!readSqliteTableColumns(e,`session_entries`)||!readSqliteTableColumns(e,`sessions`)||!readSqliteTableColumns(e,`conversations`))return;readSqliteTableColumns(e,`session_conversations`)||e.exec(`
      CREATE TABLE session_conversations (
        session_id TEXT NOT NULL,
        conversation_id TEXT NOT NULL,
        role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')),
        route_context_json TEXT,
        first_seen_at INTEGER NOT NULL,
        last_seen_at INTEGER NOT NULL,
        PRIMARY KEY (session_id, conversation_id, role),
        FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE,
        FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
      );
    `),e.exec(`
    UPDATE sessions
    SET primary_conversation_id = NULL
    WHERE primary_conversation_id IN (
      SELECT conversation_id FROM conversations WHERE delivery_target = ''
    );
    DELETE FROM session_conversations
    WHERE conversation_id IN (
      SELECT conversation_id FROM conversations WHERE delivery_target = ''
    );
    DELETE FROM conversations WHERE delivery_target = '';
  `);let t=e.prepare(`
        SELECT
          se.session_id,
          se.entry_json,
          se.session_key,
          se.updated_at,
          s.session_scope,
          CASE WHEN se.session_key = s.session_key THEN s.chat_type END AS persisted_chat_type
        FROM session_entries AS se
        INNER JOIN sessions AS s ON s.session_id = se.session_id
        ORDER BY se.updated_at ASC, se.session_key ASC;
      `).all(),n=e.prepare(`
    INSERT INTO conversations (
      conversation_id, channel, account_id, kind, peer_id, delivery_target,
      parent_conversation_id, thread_id, native_channel_id,
      native_direct_user_id, label, metadata_json, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, ?)
    ON CONFLICT(conversation_id) DO UPDATE SET
      channel = excluded.channel,
      account_id = excluded.account_id,
      kind = excluded.kind,
      peer_id = excluded.peer_id,
      delivery_target = excluded.delivery_target,
      thread_id = excluded.thread_id,
      native_channel_id = excluded.native_channel_id,
      native_direct_user_id = excluded.native_direct_user_id,
      label = excluded.label,
      updated_at = excluded.updated_at;
  `),r=e.prepare(`
    DELETE FROM session_conversations
    WHERE session_id = ? AND conversation_id = ? AND role = 'related';
  `),i=e.prepare(`
    UPDATE session_conversations SET role = 'related', last_seen_at = ?
    WHERE session_id = ? AND role = 'primary';
  `),a=e.prepare(`
    INSERT INTO session_conversations (
      session_id, conversation_id, role, first_seen_at, last_seen_at
    ) VALUES (?, ?, ?, ?, ?)
    ON CONFLICT(session_id, conversation_id, role) DO UPDATE SET
      last_seen_at = excluded.last_seen_at;
  `),o=e.prepare(`UPDATE sessions SET primary_conversation_id = ? WHERE session_id = ?`);for(let e of[n,r,i,a,o])e.setReadBigInts(!0);for(let e of t){let t=S(e.session_id),s=typeof e.entry_json==`string`?de(e.entry_json):void 0,c=typeof e.updated_at==`number`?e.updated_at:Date.now(),l=s?migratedConversation(s,S(e.persisted_chat_type),S(e.session_key)):void 0;if(!t||!l)continue;let u=e.session_scope===`shared-main`&&l.kind===`direct`?`participant`:`primary`;n.run(l.conversationRef,l.channel,l.accountId,l.kind,l.peerId,l.deliveryTarget,l.threadId??null,l.nativeChannelId??null,l.nativeDirectUserId??null,l.label??null,c,c),u===`primary`&&(i.run(c,t),r.run(t,l.conversationRef)),a.run(t,l.conversationRef,u,c,c),u===`primary`&&o.run(l.conversationRef,t)}}function readSqliteTableColumns(e,t){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`invalid SQLite table identifier: ${t}`);if(!B(e,t))return null;let n=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(n.flatMap(e=>typeof e.name==`string`?[e.name]:[]))}function ensureSessionAdditiveColumns(e){for(let{tableName:t,columnName:n,dataType:r}of g)V(e,t,`${n} ${r}`);B(e,`session_conversations`)&&!E(e)?.triggers.has(`session_conversations_route_context_invalidate_after_update`)&&e.exec(`
      CREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update
      AFTER UPDATE OF role, last_seen_at ON session_conversations
      WHEN NEW.route_context_json IS OLD.route_context_json
      BEGIN
        UPDATE session_conversations
        SET route_context_json = NULL
        WHERE session_id = NEW.session_id
          AND conversation_id = NEW.conversation_id
          AND role = NEW.role;
      END;
    `)}function migrateConversationDeliveryTargetColumn(e){V(e,`conversations`,`delivery_target TEXT NOT NULL DEFAULT ''`)}function ensureSessionEntryValidityProjection(e){let t=readSqliteTableColumns(e,`session_nodes`);if(!t)return;t.has(`entry_valid`)||e.exec(`ALTER TABLE session_nodes ADD COLUMN entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1))`);let n=e.prepare(`SELECT current_session_id, entry_json, session_key, updated_at FROM session_nodes WHERE entry_valid = 0 ORDER BY session_key LIMIT 256`),r=e.prepare(`UPDATE session_nodes SET entry_valid = ? WHERE session_key = ?`);for(r.setReadBigInts(!0);;){let e=n.all();if(e.length===0)break;for(let t of e)r.run(vn(t)?1:-1,t.session_key)}}function migrateSessionCreatorNamespaces(e,t){if(t>=19||!B(e,`session_nodes`))return;let n=e.prepare(`UPDATE session_nodes SET entry_json = ?, created_actor_type = ?, created_actor_id = ? WHERE session_key = ?`);n.setReadBigInts(!0);let r=e.prepare(`SELECT session_key, entry_json FROM session_nodes
    WHERE json_valid(entry_json) AND (json_extract(entry_json, '$.createdActor.type') = 'human'
      OR (json_type(entry_json, '$.createdActor') IS NULL AND json_type(entry_json, '$.createdBy') = 'object'))`);for(let e of r.all()){let t=migrateLegacySessionCreator(JSON.parse(e.entry_json));n.run(JSON.stringify(t),t.createdActor?.type??null,t.createdActor?.id??null,e.session_key)}}rn(an,{tables:[Qt]});const $=`session_participants_identity_migration`;function migrateSessionParticipantsSchema(e,t){if(!B(e,`session_participants`))return;if(F(e,t,mn,{allowedMissingColumns:sn}),B(e,$))throw Error(`Participant migration table already exists: ${$}`);if(e.prepare(`SELECT name FROM sqlite_schema
    WHERE (type IN ('trigger', 'index') AND tbl_name = 'session_participants' AND sql IS NOT NULL)
       OR (type IN ('view', 'trigger') AND sql LIKE '%session_participants%')`).all().length>0)throw Error(`Participant migration cannot rebuild unknown indexes, views, or triggers.`);for(let t of e.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table'`).all())if(e.prepare(`PRAGMA foreign_key_list("${String(t.name).replaceAll(`"`,`""`)}")`).all().some(e=>e.table===`session_participants`))throw Error(`Participant migration cannot rebuild a table referenced by an unknown foreign key.`);let n=z(e,`session_participants`,`actor_source`)?`actor_source`:`NULL`,r=z(e,`session_participants`,`contribution_count`)?`coalesce(contribution_count, 1)`:`1`,i=`actor_type = 'agent' AND ${n} = 'agent' AND actor_id <> ''`,a=`(${i}) OR (actor_type = 'human' AND ${n} = 'channel')`;e.exec(`
    ${an().replace(`IF NOT EXISTS session_participants`,$)}
    INSERT INTO ${$}
      (session_key, identity_namespace, actor_id, contribution_count, first_prompted_at, last_prompted_at)
    SELECT session_key,
      CASE
        WHEN actor_type = 'human' AND ${n} = 'profile' AND actor_id <> '' THEN json_object('type', 'profile')
        WHEN ${i} THEN json_object('type', 'agent')
        ELSE json_object('type', 'legacy', 'actorType', actor_type, 'source', ${n})
      END,
      actor_id, ${r},
      CASE WHEN ${a} THEN first_prompted_at ELSE NULL END,
      CASE WHEN ${a} THEN last_prompted_at ELSE NULL END
    FROM session_participants;
    DROP TABLE session_participants;
    ALTER TABLE ${$} RENAME TO session_participants;
  `)}const Yn=[`memory_index_chunks_fts`,`memory_index_paths_fts`],Xn=[`config`,`content`,`data`,`docsize`,`idx`];function publishedMemoryFtsMatches(e,t){let n=Et(e).readCatalog([],[t]);return[`unicode61`,`trigram`].some(e=>{try{return Zt(n,{kind:t===`memory_index_paths_fts`?`path-fts`:`body-fts`,tableName:t,tokenizer:e})}catch(e){if(e instanceof Error&&e.message.includes(`Memory search schema has no generated fingerprint`))return!1;throw e}})}function admitPublishedMemoryFtsTables(e,t,n,r){let i=[];for(let a of Yn)if(n.has(a)){if(!publishedMemoryFtsMatches(e,a))throw new H(`Cannot repair v16 validity triggers for ${t}: drifted memory FTS table ${a}. Preserve the database and SQLite sidecars before repair.`);r.add(a),i.push(a)}if(i.length===0)return;let a=new Set(i.flatMap(e=>Xn.map(t=>`${e}_${t}`)));for(let t of nn(e,{includeInternal:!0}))t.type===`shadow`&&a.has(t.name)&&r.add(t.name)}function repairAndAssertOpenClawAgentV16Validity(e,t,n){let r=E(e)??je(e);if([`session_nodes_entry_valid_after_insert`,`session_nodes_entry_valid_after_entry_update`,`session_nodes_entry_valid_after_identity_update`].every(e=>r.triggers.has(e)))return;let i=Ue(e,O(e).selectFrom(`session_nodes`).select([`current_session_id`,`entry_json`,`updated_at`]));for(let e of i)if(!vn(e))throw new H(`Cannot repair v16 validity triggers for ${t}: invalid session entry identity or JSON. Stop the Gateway and preserve the database and SQLite sidecars; restore a verified backup or contact OpenClaw support to repair the affected rows. No session rows were changed.`);ensureLegacySessionEntryValidityTriggers(e),F(e,t,n,{...W,allowCompatibleAdditiveColumns:!1,allowedMissingColumns:[...W.allowedMissingColumns,...sn],allowedMissingTables:[...W.allowedMissingTables,`session_transcript_cold_archives`]}),r.tables.has(`state_leases`)&&F(e,t,dn);let a=/* @__PURE__ */ new Set([...M(n),`state_leases`]);admitPublishedMemoryFtsTables(e,t,r.tables,a);let o=/* @__PURE__ */ new Set([...N(n),`idx_agent_state_leases_expiry`,`idx_agent_state_leases_owner`,`idx_memory_index_chunks_path`]);for(let[e,n,i]of[[`table`,r.tables,a],[`index`,r.indexes,o]])for(let r of n)if(!r.startsWith(`sqlite_`)&&!i.has(r))throw new H(`Cannot repair v16 validity triggers for ${t}: unexpected ${e} ${r}. Preserve the database and SQLite sidecars and contact OpenClaw support; the unknown schema needs inspection before migration.`)}function migratedSessionColumn(e,t,n){return e.has(t)?t:n}function hasRetiredAgentStateLeaseSchema(e){return!!e.prepare(`SELECT 1 FROM main.sqlite_schema WHERE name = 'state_leases'`).get()}function assertOpenClawAgentSchemaContains(e,t,n,r=`current`,i=!1,a,o=!1){let s={...W,allowedMissingIndexes:o?[]:W.allowedMissingIndexes,allowedMissingTables:[...W.allowedMissingTables,...r===`legacy`?[`session_transcript_cold_archives`]:[]],allowedMissingColumns:[...W.allowedMissingColumns,...r===`legacy`?sn:[]]};if(!i)return F(e,t,n,s,a),!1;let c=new Set(N(n)),l=st(e,n,s,a);return l.some(e=>e.code!==`missing-or-drifted-index`||!c.has(e.objectName))&&Kt(t,Jt(l)),l.length>0}function assertOpenClawAgentCurrentRuntimeSchema(e,t,n){let r=D(t.agentId),i=P(e);if(at(i,r,t.pathname),hasRetiredAgentStateLeaseSchema(e))throw new H(`OpenClaw agent database ${t.pathname} retains retired state_leases storage; run openclaw doctor --fix before using it.`);assertOpenClawAgentSchemaContains(e,t.pathname,f,`current`,!1,n,t.requireCanonicalIndexes)}function hasAnyCanonicalTable(e,t){let n=M(t),r=n.map(()=>`?`).join(`, `);return!!e.prepare(`SELECT 1 FROM main.sqlite_schema
         WHERE type = 'table' AND name IN (${r})
         LIMIT 1`).get(...n)}function repairAndAssertAgentSchemaGroup(e,t,n){wn(e,t,n,{verifyPhysicalIntegrity:!1}),assertOpenClawAgentSchemaContains(e,t,n,`legacy`)}function ensureSessionKeyContractSchemaInTransaction(e){B(e,`session_key_contract`)&&e.prepare(`SELECT 1 FROM session_key_contract WHERE id = 1`).get()||e.exec(T(f,`session_key_contract`,{endMarker:`CREATE TABLE IF NOT EXISTS session_windows (`,includeEndMarker:!1,errorMessage:`OpenClaw agent session-key contract schema markers are missing.`}))}function ensureSessionReactionsSchemaInTransaction(e){E(e)?.tables.has(`session_reactions`)||e.exec(T(f,`session_reactions`,{endMarker:`CREATE TABLE IF NOT EXISTS board_tabs (`,includeEndMarker:!1,errorMessage:`OpenClaw agent session-reactions schema markers are missing.`}))}function repairAndAssertOpenClawAgentV14SchemaForMigration(e,t){let n=we(e);if(n!==14)throw new H(`OpenClaw agent database ${t.pathname} uses schema version ${n}; expected 14 before migrating it.`);let r=D(t.agentId),i=P(e);if(!i)throw new H(`OpenClaw agent database ${t.pathname} has no schema ownership metadata. Run openclaw doctor --fix to inspect and repair its ownership.`);if(ct(i,r,t.pathname),i.schemaVersion!==14)throw new H(`OpenClaw agent database ${t.pathname} metadata schema version ${i.schemaVersion??`invalid`} does not match 14; repair the ownership metadata before migrating it.`);ensureSessionAdditiveColumns(e),ensureSessionEntryValidityProjection(e),ensureLegacySessionEntryValidityTriggers(e),ensureSessionKeyContractSchemaInTransaction(e),repairAndAssertAgentSchemaGroup(e,t.pathname,un),hasAnyCanonicalTable(e,pn)&&repairAndAssertAgentSchemaGroup(e,t.pathname,pn),hasAnyCanonicalTable(e,cn)&&repairAndAssertAgentSchemaGroup(e,t.pathname,cn),hasAnyCanonicalTable(e,G)&&(rt(e,t.pathname,G),kn(e),repairAndAssertAgentSchemaGroup(e,t.pathname,G)),hasAnyCanonicalTable(e,fn)&&(rt(e,t.pathname,fn),hn(e),repairAndAssertAgentSchemaGroup(e,t.pathname,fn))}function migrateRetiredAgentStateLeaseSchema(e,t,n){n<17||!hasRetiredAgentStateLeaseSchema(e)||(F(e,t,dn),e.exec(`DROP TABLE state_leases;`))}function assertAgentSchemaVersion(e,t,n){let r=P(e);if(ct(r,t.agentId,t.pathname),we(e)!==t.version||r?.schemaVersion!==t.version)throw new H(`OpenClaw agent database ${t.pathname} did not converge on schema version ${t.version}.`);assertOpenClawAgentSchemaContains(e,t.pathname,n,t.version<18?`legacy`:`current`)}function finishAgentSchemaMigration(e,t,n,r,i,a,o,s){Te(e,r),persistAgentSchemaMetadata(e,t,r),assertAgentSchemaVersion(e,{agentId:t,pathname:n,version:r},i);for(let t of s?.tables??[])B(e,t)&&Xe(e,n,t);if(a){let t=s?.foreignKeyTables?.map(e=>`PRAGMA foreign_key_check(${ke(e)})`)??[`PRAGMA foreign_key_check`];for(let r of t)if(e.prepare(r).all().length>0)throw Error(`Agent schema migration failed foreign key validation for ${n}.`)}o()}function hasLegacyMemoryChunkProvenanceTrigger(e){return!!e.prepare(`SELECT 1 FROM sqlite_schema WHERE type = 'trigger' AND name = 'memory_index_chunk_provenance_after_insert'`).get()}function hasPendingMemoryChunkMetadataMigration(e){return tn(e)||hasLegacyMemoryChunkProvenanceTrigger(e)}function migrateMemoryChunkMetadataSchema(e){en(e),$t(e)}function hasPendingSessionKeyContractSchemaMigration(e){let t=readSqliteTableColumns(e,`session_nodes`);if(!t)return!1;let n=B(e,`session_key_contract`);return!t.has(`entry_valid`)||!n}function hasPendingCurrentVersionAgentDatabaseMigration(e){return!B(e,`session_reactions`)||hasPendingMemoryChunkMetadataMigration(e)||hasPendingSessionKeyContractSchemaMigration(e)||hasRetiredAgentStateLeaseSchema(e)||m((E(e)??je(e)).tableSql)}const Zn=/* @__PURE__ */ new Map;function captureAgentDatabaseStartupVerification(e,t,n){if(n?.birthtime===void 0)return;let r=Ie(t);for(let t of Zn.values())if(t.identity.canonicalPath===e&&t.statePath===r&&!t.signal.aborted&&(t.status===`pending`||t.status===`running`)){if(t.identity.key!==`file:${n.physicalIdentity}`||t.identity.birthtime!==n.birthtime)throw Error(`SQLite database file identity changed before existing-only open`);return t.assertCurrent(),t.assertCurrent}}function admitAgentDatabaseRuntimeStructure(e,t,n,r){et(e,t);try{let validateSchema=r=>assertOpenClawAgentCurrentRuntimeSchema(e,{agentId:n,pathname:t,requireCanonicalIndexes:!0},r),i=performance.now(),a=wn(e,t,f,{nonUniqueOnly:!0,verifyPhysicalIntegrity:!1,validateAfterRepair:validateSchema,validateUnchanged:validateSchema});return r&&(r.canonicalIndexMs=Math.floor(performance.now()-i),r.repairedIndexCount=a.length,r.integrityGateMode=`deferred`,r.integrityGateOutcome=`pending`),a}catch(e){if(qt(e))return;throw e}}function createSessionWorkerExecutionSource(e,t,n){return{assertCurrent:e,readCustody:n,createAdmission(n){return()=>({nativeLocations:n.nativeLocations,admission:kt((r,i)=>{if(n.authorize(r),e(),!i())throw Error(t)},n.attachment)})}}}export{prepareAgentDeletionPathFence as $,seedCanonicalSessionValidationPending as A,refreshAgentDatabaseIdleTimer as B,migrateSessionCreatorNamespaces as C,persistAgentSchemaMetadata as D,readSqliteTableColumns as E,closeMaintenanceAgentDatabase as F,assertAgentDatabaseMaintenanceAuthorityIfPresent as G,retainFailedAgentDatabaseClose as H,closeOpenClawAgentDatabaseByPathAsync as I,hasAgentDatabaseMaintenanceAuthority as J,assertOpenClawAgentDatabaseLease as K,closeOpenClawAgentDatabases as L,runOpenClawAgentWriteAdmission as M,Z as N,ensureLegacySessionEntryValidityTriggers as O,Q as P,assertAgentDeletionPathFence as Q,createAgentDatabaseScopeOwnedClose as R,migrateConversationDeliveryTargetColumn as S,migrateSessionTranscriptGenerations as T,revokePendingAgentDatabaseOpen as U,registerAgentDatabaseHandle as V,startAgentDatabaseOpenTiming as W,releaseOpenClawAgentDatabaseLease as X,recordOpenClawAgentDatabaseAdmission as Y,renewAgentDatabaseMaintenanceAuthorityIfPresent as Z,migrateSessionParticipantsSchema as _,assertOpenClawAgentCurrentRuntimeSchema as a,getGatewayShutdownCleanupSignal as at,ensureSessionAdditiveColumns as b,ensureSessionReactionsSchemaInTransaction as c,hasPendingMemoryChunkMetadataMigration as d,readAgentDatabaseDeletionSnapshot as et,migrateMemoryChunkMetadataSchema as f,repairAndAssertOpenClawAgentV16Validity as g,repairAndAssertOpenClawAgentV14SchemaForMigration as h,assertAgentSchemaVersion as i,getGatewayRestartDrainSignal as it,runOpenClawAgentWorkerWrite as j,migrateCanonicalSessionWriterValidation as k,finishAgentSchemaMigration as l,migratedSessionColumn as m,admitAgentDatabaseRuntimeStructure as n,readLegacyMigrationReceiptFromDatabase as nt,assertOpenClawAgentSchemaContains as o,isGatewayRestartDrainError as ot,migrateRetiredAgentStateLeaseSchema as p,claimOpenClawAgentDatabaseLease as q,captureAgentDatabaseStartupVerification as r,resolveLegacyMigrationSourceKey as rt,ensureSessionKeyContractSchemaInTransaction as s,createSessionWorkerExecutionSource as t,readRetainedAgentDeletionsFromDatabase as tt,hasPendingCurrentVersionAgentDatabaseMigration as u,assertSupportedAgentMigrationSchemas as v,migrateSessionTranscriptActiveProjection as w,ensureSessionEntryValidityProjection as x,backfillSessionConversations as y,recordOpenClawAgentDatabaseOpenFailure as z};