UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

470 lines • 80 kB
import{a as e,i as t}from"./transcript-record-coerce-CPLgmAk9.mjs";import"./transcript-plugin-instance-invocation-7y9lfaeO.mjs";import{a as n,g as r,i,n as a,r as o,s,t as c}from"./transcript-agent-creation-claim-Da8lP1e6.mjs";import{g as l}from"./transcript-worker-cpu-DFlTFgab.mjs";import{O as u}from"./transcript-redact-BJEzMNLa.mjs";import{J as d,O as f,S as p,Z as m,ct as h,s as g,st as _,x as ee}from"./transcript-sqlite-database-admission-IPmtadyc.mjs";import{h as v,i as y,m as b}from"./transcript-sqlite-worker-identity-CA1Up8Es.mjs";import{t as x}from"./transcript-subsystem-C0UTtuvS.mjs";import{r as S}from"./transcript-src-gRxwdYZM.mjs";import{a as C,i as te,n as ne}from"./transcript-string-coerce-DTk-8HSr.mjs";import{n as re}from"./transcript-config-env-vars-DvUkP5Hz.mjs";import{a as w,ot as T}from"./transcript-sqlite-readonly-worker-cXU3LbpW.mjs";import{n as E}from"./transcript-json-coercion-Cy9rPWP2.mjs";import{t as D}from"./transcript-state-dir-DEo0wD2Q.mjs";import"./transcript-paths-BSkqmV9_.mjs";import{t as ie}from"./transcript-version-B8n3Ftv8.mjs";import{t as ae}from"./transcript-deferred-B75K7ut7.mjs";import{c as oe,d as se,u as O}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import{a as ce,h as k,o as A,s as le}from"./transcript-sqlite-user-version-CMolZa8i.mjs";import{a as ue}from"./transcript-kysely-sync-cache-state-DHCXK7mb.mjs";import{c as j,t as M}from"./transcript-sqlite-schema-sql-BnVx4b5A.mjs";import{_ as N,h as P,l as de,o as F,t as fe,u as pe}from"./transcript-sqlite-schema-facts-C1_zV4Yg.mjs";import{n as I,r as me}from"./transcript-agent-id-DmscQLD6.mjs";import{c as L}from"./transcript-openclaw-agent-db.paths-DbFl2s5M.mjs";import{n as he}from"./transcript-session-key-normalization-3Mbu27cw.mjs";import"./transcript-session-key-MDDhuEG9.mjs";import{a as R,c as ge,o as _e,r as z}from"./transcript-kysely-sync-CAP5xe3V.mjs";import{a as ve,i as ye}from"./transcript-sqlite-busy-timeout-CphRcSPk.mjs";import{a as be,c as xe}from"./transcript-sqlite-transaction-CBQXI8WC.mjs";import{D as B,d as Se,f as Ce,i as we,j as Te,l as Ee,t as De}from"./transcript-openclaw-agent-db-resources-W6NYYBYU.mjs";import{i as Oe,n as ke,r as Ae}from"./transcript-openclaw-agent-db-borrower-BzSv4n5d.mjs";import{n as je}from"./transcript-node-crypto-0qW6cl8t.mjs";import"./transcript-gateway-process-argv-CixOvMwa.mjs";import{m as Me,n as Ne,p as Pe}from"./transcript-openclaw-quarantine-store-DP1LZEnM.mjs";import{a as Fe,c as Ie,i as Le,o as Re,r as ze,s as Be}from"./transcript-sqlite-integrity-DC7pAsT6.mjs";import{C as Ve,D as He,E as Ue,S as We,T as Ge,k as Ke,x as qe}from"./transcript-sqlite-private-snapshot-fork-CKFbjfTN.mjs";import{n as Je,t as Ye}from"./transcript-node-sqlite-RfCz-ZxM.mjs";import{a as Xe,i as V,l as Ze,n as H,s as U,u as Qe}from"./transcript-openclaw-state-db-schema-helpers-B1k_oHgC.mjs";import{n as $e,r as W}from"./transcript-openclaw-agent-db-metadata-CRoaperl.mjs";import{p as et,u as tt}from"./transcript-sqlite-snapshot-staging-owner-B-Am-HqY.mjs";import{r as nt}from"./transcript-sqlite-handle-lifecycle-fOjKc_YY.mjs";import{t as rt}from"./transcript-gateway-supervision-BIIunoyA.mjs";import{a as it,o as at,t as ot}from"./transcript-openclaw-agent-db-identity-BPgUuROx.mjs";import{i as st,n as ct,o as lt,s as ut,t as G}from"./transcript-sqlite-schema-contract-BGrLZxZe.mjs";import{t as dt}from"./transcript-openclaw-agent-db-contract-DXUC0rkZ.mjs";import{n as ft}from"./transcript-sqlite-strict-OvMalwYT.mjs";import{t as pt}from"./transcript-sqlite-schema-ensure-DehLIZgc.mjs";import{F as mt,M as ht,N as gt,P as _t,b as vt,f as yt,h as bt,i as xt,j as St,k as Ct,l as wt,n as Tt,o as Et,s as Dt,t as Ot,u as kt,w as K,y as At}from"./transcript-openclaw-agent-db-validation-cache-CKkKL5V4.mjs";import{f as jt,i as Mt,l as Nt,n as Pt,o as Ft}from"./transcript-openclaw-agent-trajectory-storage-migration-CUGBXt-A.mjs";import{_ as It,a as Lt,b as Rt,c as zt,d as Bt,g as Vt,h as Ht,i as Ut,l as Wt,n as Gt,o as Kt,p as qt,r as Jt,s as Yt,t as Xt,u as Zt,v as Qt,x as $t,y as en}from"./transcript-openclaw-agent-schema-history-CGfwWZiL.mjs";import{t as tn}from"./transcript-openclaw-agent-progress-card-schema-C9Hgw3JD.mjs";import{n as nn,r as rn,t as an}from"./transcript-openclaw-agent-db-engine-CCFr9cWR.mjs";import{n as on}from"./transcript-openclaw-agent-db-maintenance-authority-CXtNIumq.mjs";import{a as sn,i as cn,n as ln,r as un,t as dn}from"./transcript-openclaw-agent-db-schema-read-Bseq6-pe.mjs";import{c as fn,o as pn,s as mn}from"./transcript-openclaw-agent-db-readonly-open-BK-8SP7K.mjs";import{n as hn}from"./transcript-openclaw-agent-db-readonly-scope-9KdRnbDH.mjs";import{n as gn,t as _n}from"./transcript-conversation-ref-CMqjdGhg.mjs";import{c as vn,r as yn}from"./transcript-session-entry-snapshots-B1SDC3sn.mjs";import{t as bn}from"./transcript-zstd-codec-Bwg8OR0e.mjs";import{t as xn}from"./transcript-transcript-payload-F5t-l1WZ.mjs";import{S as q,_ as Sn,a as Cn,b as wn,c as Tn,d as En,f as Dn,g as On,h as kn,i as J,l as An,m as jn,n as Mn,o as Nn,p as Pn,s as Fn,t as In,u as Ln,v as Rn,x as zn,y as Bn}from"./transcript-session-worker-execution-source-CacG0a-D.mjs";import"./transcript-agent-deletion-journal-w8euRg8V.mjs";import{L as Vn,X as Hn,et as Un}from"./transcript-openclaw-state-db-readonly-DQQE4HMs.mjs";import{i as Wn,o as Gn,s as Kn}from"./transcript-openclaw-state-db-MJzYHUz2.mjs";import{r as qn}from"./transcript-openclaw-agent-db-registry-listing-hSVmRkvc.mjs";import{t as Jn}from"./transcript-openclaw-agent-db-registry-D05sSI_R.mjs";import{t as Yn}from"./transcript-openclaw-agent-board-schema-D4oaUSGI.mjs";import"./transcript-openclaw-agent-db-owner-read-0uCmT78p.mjs";import{isMainThread as Y}from"node:worker_threads";import Xn from"node:path";import{chmodSync as Zn,existsSync as Qn,mkdirSync as $n,statSync as er}from"node:fs";function normalizeAccountId(e){return normalizeOptionalAccountId(e)??`default`}function normalizeOptionalAccountId(e){let t=(e??``).trim();if(!t)return;let n=me(t);return n.ok&&!u(n.value)?n.value:void 0}async function runSqliteIntegrityOperationInWorker(e,t){let n=w(t.signal)??t.signal,beforeResume=()=>{n.throwIfAborted(),t.beforeResume()};try{beforeResume();let r=e.next();for(;!r.done;){let i;try{await fn(r.value.databaseLabel,t.busyTimeoutMs,n,void 0,r.value.timing,{check:r.value.check,tables:r.value.tables,ftsSchemas:r.value.ftsSchemas})}catch(e){i={error:e}}if(beforeResume(),!i&&r.value.check!==`quick`&&f(r.value.database),i&&t.repairIntegrityError){let e=i.error;try{t.repairIntegrityError(r.value,e)&&(i=void 0)}catch(t){e instanceof Error&&(e.message+=` Startup FTS repair failed: ${String(t)}`)}}r=i?e.throw(i.error):e.next()}return r.value}finally{e.return(void 0)}}async function withWorkerAdmission(t,n,r,s,c){let l=L(t);o(t),a(t);let u=i(t),d=c?g(l):void 0,f=d?{...d,canonicalPath:v(l)}:b(l),p=I(t.agentId);if(c&&(c.assertCurrent(),c.agentId!==p||c.path!==l))throw Error(`Agent worker admission differs from its captured execution`);let m=f.canonicalPath===l?void 0:xt({agentId:p,path:l}),h=ae(),_=!1,releaseExecution,assertAdmission=()=>{if(_)throw Error(`Agent database admission closed during worker preparation`);n?.(),c?.assertCurrent(),u?.assertCurrent(),r?.throwIfAborted()},ee=we({agentId:p,path:l,revoke:()=>{_=!0},close:()=>h.promise},t);try{let n=await import(`./transcript-openclaw-agent-execution-BjCoKZsU.mjs`);if(assertAdmission(),!n.supportsOpenClawAgentDatabaseExecution(t))return await s(`native`);let i;if(c)i=c;else{let e=n.captureOpenClawAgentDatabaseExecution(t,f.key.startsWith(`file:`)?{expectedIdentity:{kind:`file`,physicalIdentity:f.key.slice(5),nativeLocation:f.canonicalPath,birthtime:f.birthtime}}:{});i=e,releaseExecution=()=>e.release()}let a={assertCurrent:assertAdmission,createAdmission:t=>()=>({nativeLocations:t.nativeLocations,admission:tt((n,r)=>{if(t.authorize(n),assertAdmission(),m&&n.stage===`prepare`&&e(n.facts)&&n.facts.kind===`agent-validation-start`&&(m=xt({agentId:p,path:l})),!r())throw Error(`Agent database preparation lost its admission`)},t.attachment)})};return await Mn(t,()=>i.prepare(a,r)),assertAdmission(),m?.(i.captureGenerationClaim().identity,Dt({agentId:p,path:f.canonicalPath})),await s(`worker`)}finally{try{await releaseExecution?.()}finally{ee(),h.resolve()}}}function assertAgentDatabaseOpenAuthority(e,t){try{t?.()}catch(t){let n=Error(`Agent database open authority was refused`,{cause:t});try{e.throw(n)}catch(e){if(e!==n)throw AggregateError([t,e],`Agent database authority and cleanup failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}throw t}}function assertAgentDatabaseOperationCurrent(e,t,n,r){if(n.controller.signal.throwIfAborted(),Oe(e.agentId,{env:t.env}),J.databases.get(n.path)!==e||!e.db.isOpen)throw Error(`Agent database closed before its admitted operation: ${n.path}`);Ee(e,t),c(e,t),r?.()}function assertAgentDatabaseWriteAllowed(e){if(Xn.basename(e)===`incognito-openclaw-agent.sqlite`)throw Error(`Incognito sessions use the memory session actor, not a SQLite database.`);if(T(`agent`,e))throw Error(`Programming error: writable agent database open during read-only inspection.`)}function createOpenClawAgentDatabaseAdmissionOwner(e){function openOpenClawAgentDatabase(e,t,n){return openAgentDatabase(e,t,n)}function openAgentDatabase(t,n,r,i){assertAgentDatabaseWriteAllowed(L(t));let run=()=>{let a=e(t,void 0,n,r,i),assertCurrent=()=>{i?.assertCurrent?.(),n&&!Y&&et({stage:`prepare`,facts:{kind:`agent-open-resume`,lease:n.receipt}})},o=n?.startupRepair;return Be(a,()=>assertAgentDatabaseOpenAuthority(a,assertCurrent),o&&!Y?(e,t)=>o(e,t,assertCurrent):void 0)},a=B();return a?a.run(run):run()}async function openOpenClawAgentDatabaseInWorker(t,n,r,i){assertAgentDatabaseWriteAllowed(L(t));let a=e(t,void 0,n,r),assertCurrent=()=>assertAgentDatabaseOpenAuthority(a,()=>{i.throwIfAborted(),et({stage:`prepare`,facts:{kind:`agent-open-resume`,lease:n.receipt}})}),o=n.startupRepair,s=await runSqliteIntegrityOperationInWorker(a,{busyTimeoutMs:k,signal:i,beforeResume:assertCurrent,repairIntegrityError:o?(e,t)=>o(e,t,assertCurrent):void 0});if(!s)throw Error(`Agent database opening ended without its native owner`);return s}function runOpenClawAgentWriteTransaction(e,t,n={}){let{repairAdmission:r,singleStatement:i,...a}=n,o=openAgentDatabase(t,void 0,void 0,r),s=Se(t)?.withCommit,l=r?e=>{r.assertCurrent?.(),r.expectedIdentity&&ot(o,r.expectedIdentity),s?s(e):e()}:s,write=()=>(Ee(o,t),c(o,t),e(o));return i&&!l&&!O(o.db)?ye(o.db,a.busyTimeoutMs??5e3,()=>xe(o.db,write)):oe(o.db,()=>be(o.db,write,{busyTimeoutMs:a.busyTimeoutMs??5e3,databaseLabel:o.path,...a,operationLabel:a.operationLabel??`agent.write`,withCommit:l}))}function withOpenClawAgentDatabaseAsync(e,t,n,r){let run=()=>runAgentDatabaseAsync(e,t,n,r,`native`),i=B();return i?i.run(run):run()}function withOpenClawAgentDatabaseRuntime(e,t,n,r){let run=()=>runAgentDatabaseAsync(e,t,n,r),i=B();return i?i.run(run):run()}function withOpenClawAgentDatabaseRuntimeFromExecution(e,t,n,r,i){let a=I(e.agentId),o=L({...e,agentId:a}),assertExecutionCurrent=()=>{if(t.assertCurrent(),t.agentId!==a||t.path!==o)throw Error(`Agent runtime admission differs from its captured execution`);r?.()},run=()=>runAgentDatabaseAsync(e,n,assertExecutionCurrent,i,void 0,t),s=B();return s?s.run(run):run()}async function runAgentDatabaseAsync(e,t,n,r,i,a){r?.throwIfAborted(),n?.();let o={...e,env:re(e.env??process.env)},s=I(o.agentId),c=L({...o,agentId:s});assertAgentDatabaseWriteAllowed(c),o.env.OPENCLAW_STATE_DIR=D(o.env),o.path=c,J.terminal.peek(c)&&await mn(c,n,r);let l=J.databases.get(c),u=Dt({agentId:s,path:c})?.schema;if(!i&&Y&&(!l?.db.isOpen||!u||Atomics.load(new Int32Array(u.valid),0)!==1)&&!J.pending.has(c))return withWorkerAdmission(o,n,r,e=>runAgentDatabaseAsync(o,t,n,r,e,a),a);let d=J.pending.get(c);if(d?.agentId!==void 0&&d.agentId!==s)throw Error(`Agent database ${c} is opening for ${d.agentId}`);if(d?.controller.signal.aborted)return d.promise.then(()=>runAgentDatabaseAsync(o,t,n,r,i,a),()=>runAgentDatabaseAsync(o,t,n,r,i,a));let f=d??startOpenClawAgentDatabaseAdmission(o,s,c,n,i===`worker`);return f.operations+=1,S(f.promise,r).then(e=>(r?.throwIfAborted(),assertAgentDatabaseOperationCurrent(e,o,f,n),Te(e.db),t(e))).finally(()=>{--f.operations,f.operations||(f.releaseBorrow||f.controller.abort(/* @__PURE__ */ Error(`Agent database admission has no waiting callers`)),f.releaseBorrow?.())})}function withOpenClawAgentDatabaseAdmission(e,t,n){let run=()=>runAgentDatabaseAdmission(e,t,n),r=B();return r?r.run(()=>r.track(run())):run()}async function runAgentDatabaseAdmission(t,n,r){let i={...t,env:re(t.env??process.env)},a=I(i.agentId),o=L({...i,agentId:a});assertAgentDatabaseWriteAllowed(o),J.terminal.peek(o)&&await mn(o);let s=J.pending.get(o);if(s){if(s.agentId!==a)throw Error(`Agent database ${o} is opening for ${s.agentId}`);try{await s.promise}catch(e){if(!s.controller.signal.aborted)throw e}return withOpenClawAgentDatabaseAdmission(i,n,r)}let c=createOpenClawAgentDatabaseAdmission(a,o),{pending:l}=c;l.promise.catch(()=>{}),l.operations+=1;let u=e(i,l),d,f,p=!1;try{for(;;){let e=await n(async(e,t,n)=>{p=!1,assertAgentDatabaseOpenAuthority(u,()=>{e(),assertOpenClawAgentDatabaseAdmissionCurrent(i,l)}),l.validation=t,l.integrityRevoked=n;let a=f?u.throw(f.error):u.next();if(!a.done)return p=!0,{done:!1,check:a.value};l.releaseBorrow=Ae(a.value.db),c.complete(a.value);let assertOperationCurrent=()=>assertAgentDatabaseOperationCurrent(a.value,i,l,e);assertOperationCurrent();let o=Y||O(a.value.db)?void 0:Ge(a.value.db);o?.(assertOperationCurrent);let s=await r(a.value);return o?.(assertOperationCurrent),{done:!0,result:s}});if(e.done)return e.result;d=e.check,f=void 0;try{l.controller.signal.throwIfAborted(),Re(d)}catch(e){f={error:e}}}}catch(e){let t=[e];if(p){let n=Error(`Agent database admission failed: ${o}`,{cause:e});try{u.throw(n)}catch(e){e!==n&&t.push(e)}}let n=t.length===1?e:AggregateError(t,`Agent database admission and cleanup failed`,{cause:e});throw c.fail(n),n}finally{--l.operations,l.operations||l.releaseBorrow?.()}}function createOpenClawAgentDatabaseAdmission(e,t){De({agentId:e,path:t});let n=ae(),r={agentId:e,path:t,controller:new AbortController,promise:n.promise,operations:0};J.pending.set(t,r),J.activePending.add(r);let retire=()=>{J.pending.get(t)===r&&J.pending.delete(t),J.activePending.delete(r)};return{pending:r,complete:e=>{if(retire(),r.controller.signal.aborted||J.databases.get(t)!==e||!e.db.isOpen){let e=r.controller.signal.reason??/* @__PURE__ */ Error(`Agent database closed before admission completed: ${t}`);throw n.reject(e),e}n.resolve(e)},fail:e=>{retire(),n.reject(e)}}}function assertOpenClawAgentDatabaseAdmissionCurrent(e,t){let n=t.path;if(t.controller.signal.throwIfAborted(),Oe(t.agentId,{env:e.env}),J.pending.get(n)!==t)throw Error(`Agent database open was replaced: ${n}`);o(e),Se(e)?.assertCurrent(),t.assertHeld?.()}function startOpenClawAgentDatabaseAdmission(t,n,r,i,a=!1){let o=createOpenClawAgentDatabaseAdmission(n,r),{pending:s}=o;s.workerPrepared=a;let c=e(t,s);return(async()=>{assertAgentDatabaseOpenAuthority(c,i);let e=c.next();for(;!e.done;){let n,a=!1;try{await fn(r,k,s.controller.signal,void 0,e.value.timing,{check:e.value.check,tables:e.value.tables})}catch(e){n=e,a=!0}assertAgentDatabaseOpenAuthority(c,()=>{assertOpenClawAgentDatabaseAdmissionCurrent(t,s),i?.()}),e=a?c.throw(n):c.next()}return s.releaseBorrow=Ae(e.value.db),e.value})().then(o.complete,o.fail).catch(o.fail),s}return{openOpenClawAgentDatabase,openOpenClawAgentDatabaseInWorker,runOpenClawAgentWriteTransaction,withOpenClawAgentDatabaseAsync,withOpenClawAgentDatabaseRuntime,withOpenClawAgentDatabaseRuntimeFromExecution,withOpenClawAgentDatabaseAdmission}}function ensureMode(e,t){(process.platform===`win32`||(er(e).mode&4095)!==t)&&Zn(e,t)}function ensureOpenClawAgentDatabasePermissions(e,t){let n=Xn.dirname(e),r=L({agentId:t.agentId,env:t.env}),i=Xn.resolve(e)===Xn.resolve(r),a=Qn(n);$n(n,{recursive:!0,mode:448}),(i||!a)&&ensureMode(n,448);for(let t of Me(e))try{ensureMode(t,384)}catch(e){if(e.code!==`ENOENT`)throw e}}function ensureLegacySessionEntryValidityTriggers(e){e.exec(Wt)}function migrateCanonicalSessionWriterValidation(e){for(let t of zt)e.exec(`DROP TRIGGER IF EXISTS ${t}`);H(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:ie};z(e,R(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`,`!=`,ie),e(`schema_meta.agent_id`,`!=`,t)])))),$e(e,{role:`agent`,schemaVersion:n,agentId:t})}function normalizeChatType(e){let t=te(e);return t===`dm`?`direct`:t===`direct`||t===`group`||t===`channel`?t:void 0}const tr=/* @__PURE__ */ new Set([`direct`,`dm`,`group`,`channel`]);function isCanonicalPeerKind(e){return tr.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=ne(e);if(!n)return`unknown`;let r=he(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(t){let n=t,r=t.createdActor??(e(n.createdBy)?{...n.createdBy,type:`human`,source:`unknown`}:void 0);if(r?.type!==`human`)return t;let i=r.source===`profile`||r.source===`channel`||r.source===`unknown`?r.source:t.createdVia===`operator`||t.createdVia===`run`?`profile`:t.createdVia===`channel`?`channel`:`unknown`;if(r===t.createdActor&&i===r.source&&!n.createdBy)return t;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=>V(e,t))||V(e,`session_transcript_files`)||readSqliteTableColumns(e,`session_transcript_fts`)?.has(`session_key`))throw new U(`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 U(`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=normalizeChatType(C(e.entry.chatType))??normalizeChatType(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??``)||C(e.entry.groupId)?`group`:`direct`}function migratedConversation(e,n,r){let i=t(e.delivery),a=t(i?.context)??t(e.deliveryContext),o=t(i?.origin)??t(e.origin),s=C(a?.to),c=C(o?.from),l=inferMigratedChatType({entry:e,persistedChatType:n,sessionKey:r,deliveryTarget:s??c}),u=s??(l===`direct`?c:void 0);if(!u)return;let d=!!s,f=(d?C(a?.channel)??C(e.channel)??C(e.lastChannel)??C(o?.provider):C(o?.provider))?.toLowerCase(),p=normalizeAccountId(d?C(a?.accountId)??C(e.lastAccountId)??C(o?.accountId):C(o?.accountId)),m=d?a?.threadId:o?.threadId,h=typeof m==`number`&&Number.isFinite(m)?String(m):C(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:C(o?.nativeChannelId),nativeDirectUserId:C(o?.nativeDirectUserId),label:C(e.displayName)??C(e.label)??C(e.subject)??C(e.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=C(e.session_id),s=typeof e.entry_json==`string`?E(e.entry_json):void 0,c=typeof e.updated_at==`number`?e.updated_at:Date.now(),l=s?migratedConversation(s,C(e.persisted_chat_type),C(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(!V(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 _)H(e,t,`${n} ${r}`);V(e,`session_conversations`)&&!F(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){H(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||!V(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)}}pt(It,{tables:[dt]});const X=`session_participants_identity_migration`;function migrateSessionParticipantsSchema(e,t){if(!V(e,`session_participants`))return;if(G(e,t,Zt,{allowedMissingColumns:Bt}),V(e,X))throw Error(`Participant migration table already exists: ${X}`);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=Xe(e,`session_participants`,`actor_source`)?`actor_source`:`NULL`,r=Xe(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(`
    ${It().replace(`IF NOT EXISTS session_participants`,X)}
    INSERT INTO ${X}
      (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 ${X} RENAME TO session_participants;
  `)}function repairAndAssertOpenClawAgentV16Validity(e,t,n){let r=F(e)??P(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=_e(e,R(e).selectFrom(`session_nodes`).select([`current_session_id`,`entry_json`,`updated_at`]));for(let e of i)if(!vn(e))throw new U(`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),G(e,t,n,{...K,allowCompatibleAdditiveColumns:!1,allowedMissingColumns:[...K.allowedMissingColumns,...Bt],allowedMissingTables:[...K.allowedMissingTables,`session_transcript_cold_archives`]}),r.tables.has(`state_leases`)&&G(e,t,qt);let a=/* @__PURE__ */ new Set([...ut(n),`state_leases`]),o=/* @__PURE__ */ new Set([...lt(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 U(`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){let o={...K,allowedMissingTables:[...K.allowedMissingTables,...r===`legacy`?[`session_transcript_cold_archives`]:[]],allowedMissingColumns:[...K.allowedMissingColumns,...r===`legacy`?Bt:[]]};if(!i)return G(e,t,n,o,a),!1;let s=new Set(lt(n)),c=st(e,n,o,a);return c.some(e=>e.code!==`missing-or-drifted-index`||!s.has(e.objectName))&&Qe(t,Ze(c)),c.length>0}function assertOpenClawAgentCurrentRuntimeSchema(e,t,n){let r=I(t.agentId),i=W(e);if(ln(i,r,t.pathname),hasRetiredAgentStateLeaseSchema(e))throw new U(`OpenClaw agent database ${t.pathname} retains retired state_leases storage; run openclaw doctor --fix before using it.`);assertOpenClawAgentSchemaContains(e,t.pathname,d,`current`,!1,n)}function hasAnyCanonicalTable(e,t){let n=ut(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){Gn(e,t,n,{verifyPhysicalIntegrity:!1}),assertOpenClawAgentSchemaContains(e,t,n,`legacy`)}function ensureSessionKeyContractSchemaInTransaction(e){V(e,`session_key_contract`)&&e.prepare(`SELECT 1 FROM session_key_contract WHERE id = 1`).get()||e.exec(M(d,`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){F(e)?.tables.has(`session_reactions`)||e.exec(M(d,`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=A(e);if(n!==14)throw new U(`OpenClaw agent database ${t.pathname} uses schema version ${n}; expected 14 before migrating it.`);let r=I(t.agentId),i=W(e);if(!i)throw new U(`OpenClaw agent database ${t.pathname} has no schema ownership metadata. Run openclaw doctor --fix to inspect and repair its ownership.`);if(un(i,r,t.pathname),i.schemaVersion!==14)throw new U(`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,Kt),hasAnyCanonicalTable(e,Yt)&&repairAndAssertAgentSchemaGroup(e,t.pathname,Yt),hasAnyCanonicalTable(e,Ut)&&repairAndAssertAgentSchemaGroup(e,t.pathname,Ut),hasAnyCanonicalTable(e,Lt)&&(ct(e,t.pathname,Lt),Yn(e),repairAndAssertAgentSchemaGroup(e,t.pathname,Lt)),hasAnyCanonicalTable(e,Jt)&&(ct(e,t.pathname,Jt),tn(e),repairAndAssertAgentSchemaGroup(e,t.pathname,Jt))}function migrateRetiredAgentStateLeaseSchema(e,t,n){n<17||!hasRetiredAgentStateLeaseSchema(e)||(G(e,t,qt),e.exec(`DROP TABLE state_leases;`))}function assertAgentSchemaVersion(e,t,n){let r=W(e);if(un(r,t.agentId,t.pathname),A(e)!==t.version||r?.schemaVersion!==t.version)throw new U(`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){e.exec(`PRAGMA user_version = ${r};`),persistAgentSchemaMetadata(e,t,r),assertAgentSchemaVersion(e,{agentId:t,pathname:n,version:r},i);for(let t of s??[])V(e,t)&&Le(e,n,t);if(a&&e.prepare(`PRAGMA foreign_key_check`).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 _t(e)||hasLegacyMemoryChunkProvenanceTrigger(e)}function hasPendingSessionKeyContractSchemaMigration(e){let t=readSqliteTableColumns(e,`session_nodes`);if(!t)return!1;let n=V(e,`session_key_contract`);return!t.has(`entry_valid`)||!n}function hasPendingCurrentVersionAgentDatabaseMigration(e){return!V(e,`session_reactions`)||hasPendingMemoryChunkMetadataMigration(e)||hasPendingSessionKeyContractSchemaMigration(e)||hasRetiredAgentStateLeaseSchema(e)||h((F(e)??P(e)).tableSql)}const nr=`session-cost-usage-rollup-v3`,rr=`unpriced`,ir=bn();function encodeUsageCostRollup(e){let t=JSON.stringify(e.rollup),n=Buffer.from(t,`utf8`),r=n.byteLength>=1024?ir.compress(n,1):void 0,i=r!==void 0&&r.byteLength<n.byteLength,a=i?r:n,o={version:e.version,pricingFingerprint:e.pricingFingerprint,checkpoint:e.checkpoint,scannedAt:e.scannedAt,parsedRecords:e.parsedRecords,countedRecords:e.countedRecords,format:1,body:{encoding:i?`zstd`:`identity`,bytes:n.byteLength,storedBytes:a.byteLength,utf16Length:t.length,sha256:je(n)}};return{valueJson:JSON.stringify(o),blob:Uint8Array.from(a)}}function readUsageCostDeferredMetadata(e){let t=e.checkpoint,n=t.kind===`jsonl`?{kind:t.kind,observedSize:t.observedSize,observedMtimeMs:t.observedMtimeMs,device:t.device,inode:t.inode}:{kind:t.kind,maxSeq:t.maxSeq,eventCount:t.eventCount,size:t.size,mtimeMs:t.mtimeMs};if(Object.entries(n).every(([e,t])=>e===`kind`||typeof t==`number`&&Number.isFinite(t))&&Number.isFinite(e.scannedAt))return{checkpoint:n,scannedAt:e.scannedAt}}function decodeUsageCostRollupEnvelope(t,n){try{let r=JSON.parse(t);return!e(r)||r.version!==11||r.format!==1||typeof r.pricingFingerprint!=`string`||n!==void 0&&r.pricingFingerprint!==n&&r.pricingFingerprint!==`unpriced`||!e(r.checkpoint)||r.checkpoint.kind!==`jsonl`&&r.checkpoint.kind!==`sqlite`||typeof r.scannedAt!=`number`||typeof r.parsedRecords!=`number`||typeof r.countedRecords!=`number`||!e(r.body)||r.body.encoding!==`identity`&&r.body.encoding!==`zstd`||typeof r.body.bytes!=`number`||!Number.isSafeInteger(r.body.bytes)||r.body.bytes<=0||typeof r.body.storedBytes!=`number`||!Number.isSafeInteger(r.body.storedBytes)||r.body.storedBytes<=0||typeof r.body.utf16Length!=`number`||!Number.isSafeInteger(r.body.utf16Length)||r.body.utf16Length<=0||r.body.bytes<r.body.utf16Length||r.body.bytes>3*r.body.utf16Length||(r.body.encoding===`identity`?r.body.bytes!==r.body.storedBytes:r.body.bytes<=r.body.storedBytes)||typeof r.body.sha256!=`string`||!/^[0-9a-f]{64}$/.test(r.body.sha256)||r.projection!==void 0&&(!e(r.projection)||r.projection.version!==3||!Array.isArray(r.projection.dates)||!r.projection.dates.every(e=>typeof e==`string`&&/^\d{4}-\d{2}-\d{2}$/.test(e))||typeof r.projection.canonicalNumbers!=`boolean`)?void 0:r}catch{return}}function decodeUsageCostRollup(t,n,r,i){let a=decodeUsageCostRollupEnvelope(t,n);if(a&&r&&r.byteLength===a.body.storedBytes){if(i){if(a.body.bytes>i.remainingBytes)return null;i.remainingBytes-=a.body.bytes}try{let t=a.body.encoding===`zstd`?ir.decompress(r,a.body.bytes):Buffer.from(r.buffer,r.byteOffset,r.byteLength);if(t.byteLength!==a.body.bytes||je(t)!==a.body.sha256)return;let n=t.toString(`utf8`);if(n.length!==a.body.utf16Length)return;let i=JSON.parse(n);if(!e(i)||!e(i.buckets)||!e(i.untimestamped))return;let{format:o,body:s,...c}=a;return{...c,rollup:i}}catch{return}}}function isUsageCostRollupFresh(e){let{checkpoint:t}=e;return!t||t.kind!==e.file.kind?!1:t.kind===`jsonl`?t.observedSize===e.file.size&&t.observedMtimeMs===e.file.mtimeMs&&t.device===e.file.device&&t.inode===e.file.inode:t.size===e.file.size&&t.mtimeMs===e.file.mtimeMs&&t.eventCount===e.file.eventCount&&t.maxSeq===e.file.maxSeq}function canUseUsageCostRollupForPartial(e){let t=e.checkpoint;return!t||t.kind!==e.file.kind?!1:t.kind===`jsonl`?t.parsedOffset<=e.file.size&&t.device===e.file.device&&t.inode===e.file.inode:t.maxSeq<=(e.file.maxSeq??0)}const ar=`session-cost-usage-rollup-v2`;function decodePreviousRollup(t){let n=E(t??``);if(n&&n.version===6&&typeof n.pricingFingerprint==`string`&&e(n.checkpoint)&&(n.checkpoint.kind===`jsonl`||n.checkpoint.kind===`sqlite`)&&typeof n.scannedAt==`number`&&typeof n.parsedRecords==`number`&&typeof n.countedRecords==`number`&&e(n.rollup)&&e(n.rollup.buckets)&&e(n.rollup.untimestamped))return n}function migrateSessionCostUsageRollupStorage(e,t){let n=R(e),r;for(;;){t?.();let i=n.selectFrom(`cache_entries`).select([`key`,`value_json`,`updated_at`]).where(`scope`,`=`,ar).orderBy(`key`,`asc`).limit(1);r!==void 0&&(i=i.where(`key`,`>`,r));let a=z(e,i).rows[0];if(!a)break;r=a.key;let o=decodePreviousRollup(a.value_json);if(o){let t=encodeUsageCostRollup(o);z(e,n.insertInto(`cache_entries`).values({scope:nr,key:a.key,value_json:t.valueJson,blob:t.blob,updated_at:a.updated_at,expires_at:null}).onConflict(e=>e.columns([`scope`,`key`]).doNothing()))}z(e,n.deleteFrom(`cache_entries`).where(`scope`,`=`,ar).where(`key`,`=`,a.key))}}function backfillTranscriptMutationWatermarks(e){V(e,`transcript_events`)&&e.exec(`
    UPDATE sessions
    SET
      transcript_updated_at = COALESCE(
        transcript_updated_at,
        (SELECT MAX(transcript_events.created_at)
         FROM transcript_events
         WHERE transcript_events.session_id = sessions.session_id)
      ),
      transcript_observed_at = COALESCE(transcript_observed_at, updated_at)
    WHERE EXISTS (
      SELECT 1 FROM transcript_events
      WHERE transcript_events.session_id = sessions.session_id
    );
  `)}function migrateOpenClawAgentSchema(e){if(A(e)>=38)return;let t=readSqliteTableColumns(e,`sessions`);if(t){for(let[n,r]of Object.entries({transcript_updated_at:`INTEGER DEFAULT NULL`,transcript_observed_at:`INTEGER DEFAULT NULL`,session_entry_provenance:`INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1))`,acp_owned:`INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1))`,plugin_owner_id:`TEXT`,hook_external_content_source:`TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook'))`}))t.has(n)||e.exec(`ALTER TABLE sessions ADD COLUMN ${n} ${r};`);backfillTranscriptMutationWatermarks(e)}}function jsonText(e){return`CASE
    WHEN json_valid(entry_json) AND json_type(entry_json, '${e}') = 'text'
    THEN NULLIF(trim(CAST(json_extract(entry_json, '${e}') AS TEXT)), '')
    ELSE NULL
  END`}function jsonNumber(e){return`CASE
    WHEN json_valid(entry_json) AND json_type(entry_json, '${e}') IN ('integer', 'real')
    THEN CAST(json_extract(entry_json, '${e}') AS INTEGER)
    ELSE NULL
  END`}function createSessionNodes(e){e.exec(`
    CREATE TABLE IF NOT EXISTS session_nodes (
      session_key TEXT NOT NULL PRIMARY KEY,
      current_session_id TEXT NOT NULL,
      entry_json TEXT NOT NULL,
      updated_at INTEGER NOT NULL,
      status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
      created_at INTEGER,
      created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),
      created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),
      created_actor_id TEXT,
      parent_session_key TEXT,
      spawned_by TEXT,
      fork_source_session_key TEXT,
      fork_source_session_id TEXT,
      fork_source_entry_id TEXT,
      label TEXT,
      display_name TEXT,
      category TEXT,
      icon TEXT,
      pinned_at INTEGER,
      archived_at INTEGER,
      last_read_at INTEGER,
      last_interaction_at INTEGER,
      last_activity_at INTEGER
    ) STRICT;
  `)}function backfillSessionNodes(e){let t=readSqliteTableColumns(e,`session_entries`),n=readSqliteTableColumns(e,`session_routes`);if(t){let n=migratedSessionColumn(t,`status`,`NULL`);e.exec(`INSERT OR REPLACE INTO session_nodes (
        session_key, current_session_id, entry_json, updated_at, status,
        created_at, created_via, created_actor_type, created_actor_id,
        parent_session_key, spawned_by, fork_source_session_key,
        fork_source_session_id, fork_source_entry_id, label, display_name,
        category, icon, pinned_at, archived_at, last_read_at,
        last_interaction_at, last_activity_at
      ) SELECT
        session_key,
        session_id,
        entry_json,
        updated_at,
        ${n},
        ${jsonNumber(`$.createdAt`)},
        CASE
          WHEN json_valid(entry_json)
            AND json_extract(entry_json, '$.createdVia') IN
              ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')
          THEN json_extract(entry_json, '$.createdVia')
          ELSE NULL
        END,
        CASE
          WHEN json_valid(entry_json)
            AND json_extract(entry_json, '$.createdActor.type') IN ('human', 'agent', 'system')
          THEN json_extract(entry_json, '$.createdActor.type')
          WHEN ${jsonText(`$.createdBy.id`)} IS NOT NULL THEN 'human'
          ELSE NULL
        END,
        COALESCE(${jsonText(`$.createdActor.id`)}, ${jsonText(`$.createdBy.id`)}),
        COALESCE(${jsonText(`$.parentSessionKey`)}, ${jsonText(`$.spawnedBy`)}),
        ${jsonText(`$.spawnedBy`)},
        ${jsonText(`$.forkSource.sessionKey`)},
        ${jsonText(`$.forkSource.sessionId`)},
        ${jsonText(`$.forkSource.entryId`)},
        ${jsonText(`$.label`)},
        ${jsonText(`$.displayName`)},
        ${jsonText(`$.category`)},
        NULL,
        ${jsonNumber(`$.pinnedAt`)},
        ${jsonNumber(`$.archivedAt`)},
        ${jsonNumber(`$.lastReadAt`)},
        ${jsonNumber(`$.lastInteractionAt`)},
        ${jsonNumber(`$.lastActivityAt`)}
      FROM session_entries;`)}n&&e.exec(`INSERT OR IGNORE INTO session_nodes
      (session_key, current_session_id, entry_json, updated_at)
      SELECT session_key, session_id, '{}', updated_at FROM session_routes;`),e.exec(`INSERT OR IGNORE INTO session_nodes
    (session_key, current_session_id, entry_json, updated_at)
    SELECT session_key, session_id, '{}', updated_at FROM sessions;`)}function createLegacySessionWindowSelect(e){let t=readSqliteTableColumns(e,`sessions`);if(!t)return;let n=readSqliteTableColumns(e,`session_entries`),r=readSqliteTableColumns(e,`session_routes`),ownerValue=(e,t)=>`(SELECT candidate.${t}
        FROM ${e} AS candidate
        INNER JOIN session_windows AS owner_window ON owner_window.session_id = candidate.session_id
        WHERE candidate.session_id = session_windows.session_id
        ORDER BY CASE WHEN candidate.session_key = owner_window.session_key THEN 0 ELSE 1 END,
                 candidate.updated_at DESC,
                 candidate.session_key ASC
        LIMIT 1)`,i=n?ownerValue(`session_entries`,`session_key`):`NULL`,a=r?ownerValue(`session_routes`,`session_key`):`NULL`,o=n?ownerValue(`session_entries`,`entry_json`):`NULL`;return{columns:`session_id, session_key, previous_session_id, reason, session_scope,
      created_at, updated_at, transcript_updated_at, transcript_observed_at,
      session_entry_provenance, acp_owned, plugin_owner_id,
      hook_external_content_source, started_at, ended_at, status, chat_type,
      channel, account_id, primary_conversation_id, model_provider, model,
      agent_harness_id, parent_session_key, spawned_by, display_name`,sql:`SELECT
      session_id,
      COALESCE(${i}, ${a}, session_key),
      CASE
        WHEN json_valid(${o})
        THEN NULLIF(trim(CAST(json_extract(${o}, '$.previousSessionId') AS TEXT)), '')
        ELSE NULL
      END,
      NULL,
      ${migratedSessionColumn(t,`session_scope`,`'conversation'`)},
      created_at,
      updated_at,
      ${migratedSessionColumn(t,`transcript_updated_at`,`NULL`)},
      ${migratedSessionColumn(t,`transcript_observed_at`,`NULL`)},
      ${migratedSessionColumn(t,`session_entry_provenance`,`0`)},
      ${migratedSessionColumn(t,`acp_owned`,`0`)},
      ${migratedSessionColumn(t,`plugin_owner_id`,`NULL`)},
      ${migratedSessionColumn(t,`hook_external_content_source`,`NULL`)},
      ${migratedSessionColumn(t,`started_at`,`NULL`)},
      ${migratedSessionColumn(t,`ended_at`,`NULL`)},
      ${migratedSessionColumn(t,`status`,`NULL`)},
      ${migratedSessionColumn(t,`chat_type`,`NULL`)},
      ${migratedSessionColumn(t,`channel`,`NULL`)},
      ${migratedSessionColumn(t,`account_id`,`NULL`)},
      ${migratedSessionColumn(t,`primary_conversation_id`,`NULL`)},
      ${migratedSessionColumn(t,`model_provider`,`NULL`)},
      ${migratedSessionColumn(t,`model`,`NULL`)},
      ${migratedSessionColumn(t,`agent_harness_id`,`NULL`)},
      ${migratedSessionColumn(t,`parent_session_key`,`NULL`)},
      ${migratedSessionColumn(t,`spawned_by`,`NULL`)},
      ${migratedSessionColumn(t,`display_name`,`NULL`)}
    FROM session_windows`}}function migrateSessionWindows(e){let t=createLegacySessionWindowSelect(e);t&&(e.exec(`ALTER TABLE sessions RENAME TO session_windows;`),e.exec(`
    DROP TABLE IF EXISTS session_windows_new;
    CREATE TABLE session_windows_new (
      session_id TEXT NOT NULL PRIMARY KEY,
      session_key TEXT NOT NULL,
      previous_session_id TEXT,
      reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),
      session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),
      created_at INTEGER NOT NULL,
      updated_at INTEGER NOT NULL,
      transcript_updated_at INTEGER DEFAULT NULL,
      transcript_observed_at INTEGER DEFAULT NULL,
      session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),
      acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),
      plugin_owner_id TEXT,
      hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),
      started_at INTEGER,
      ended_at INTEGER,
      status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
      chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),
      channel TEXT,
      account_id TEXT,
      primary_conversation_id TEXT,
      model_provider TEXT,
      model TEXT,
      agent_harness_id TEXT,
      parent_session_key TEXT,
      spawned_by TEXT,
      display_name TEXT,
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
      FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL
    ) STRICT;
    INSERT INTO session_windows_new (${t.columns})
    ${t.sql};
    DROP TABLE session_windows;
    ALTER TABLE session_windows_new RENAME TO session_windows;
  `))}function renameTranscriptRewriteWatermarks(e){readSqliteTableColumns(e,`session_transcript_generations`)&&!readSqliteTableColumns(e,`transcript_rewrite_watermarks`)&&e.exec(`ALTER TABLE session_transcript_generations RENAME TO transcript_rewrite_watermarks;`)}function rebuildBoardTabs(e){readSqliteTableColumns(e,`board_tabs`)&&(readSqliteTableColumns(e,`board_widgets`)&&e.exec(`
      DELETE FROM board_widgets
      WHERE NOT EXISTS (
        SELECT 1 FROM session_nodes WHERE session_nodes.session_key = board_widgets.session_key
      );
    `),e.exec(`
    DROP TABLE IF EXISTS board_tabs_new;
    CREATE TABLE board_tabs_new (
      session_key TEXT NOT NULL,
      tab_id TEXT NOT NULL,
      title TEXT NOT NULL,
      position INTEGER NOT NULL CHECK (position >= 0),
      chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),
      created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
      revision INTEGER NOT NULL CHECK (revision >= 0),
      PRIMARY KEY (session_key, tab_id),
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO board_tabs_new (
      session_key, tab_id, title, position, chat_dock, created_by, revision
    )
    SELECT b.session_key, b.tab_id, b.title, b.position, b.chat_dock, b.created_by, b.revision
    FROM board_tabs AS b
    INNER JOIN session_nodes AS n ON n.session_key = b.session_key;
    DROP TABLE board_tabs;
    ALTER TABLE board_tabs_new RENAME TO board_tabs;
  `))}function rebuildHeartbeatOutcomes(e){let t=readSqliteTableColumns(e,`heartbeat_outcomes`);t&&e.exec(`
    DROP TABLE IF EXISTS heartbeat_outcomes_new;
    CREATE TABLE heartbeat_outcomes_new (
      session_key TEXT NOT NULL PRIMARY KEY,
      run_session_key TEXT NOT NULL,
      outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),
      summary TEXT NOT NULL,
      response_reason TEXT,
      priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),
      next_check TEXT,
      task_names_json TEXT,
      wake_source TEXT,
      wake_reason TEXT,
      occurred_at INTEGER NOT NULL,
      context_run_id TEXT,
      context_claimed_at INTEGER,
      updated_at INTEGER NOT NULL,
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO heartbeat_outcomes_new (
      session_key, run_session_key, outcome, summary, response_reason, priority,
      next_check, task_names_json, wake_source, wake_reason, occurred_at,
      context_run_id, context_claimed_at, updated_at
    )
    SELECT
      h.session_key,
      h.run_session_key,
      h.outcome,
      h.summary,
      ${migratedSessionColumn(t,`response_reason`,`NULL`)},
      ${migratedSessionColumn(t,`priority`,`NULL`)},
      ${migratedSessionColumn(t,`next_check`,`NULL`)},
      ${migratedSessionColumn(t,`task_names_json`,`NULL`)},
      ${migratedSessionColumn(t,`wake_source`,`NULL`)},
      ${migratedSessionColumn(t,`wake_reason`,`NULL`)},
      h.occurred_at,
      ${migratedSessionColumn(t,`context_run_id`,`NULL`)},
      ${migratedSessionColumn(t,`context_claimed_at`,`NULL`)},
      h.updated_at
    FROM heartbeat_outcomes AS h
    INNER JOIN session_nodes AS n ON n.session_key = h.session_key;
    DROP TABLE heartbeat_outcomes;
    ALTER TABLE heartbeat_outcomes_new RENAME TO heartbeat_outcomes;
  `)}function rebuildSessionMembers(e){readSqliteTableColumns(e,`session_members`)&&e.exec(`
    DROP TABLE IF EXISTS session_members_new;
    CREATE TABLE session_members_new (
      session_key TEXT NOT NULL,
      identity_id TEXT NOT NULL,
      added_by TEXT NOT NULL,
      added_at INTEGER NOT NULL,
      PRIMARY KEY (session_key, identity_id),
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO session_members_new (session_key, identity_id, added_by, added_at)
    SELECT m.session_key, m.identity_id, m.added_by, m.added_at
    FROM session_members AS m
    INNER JOIN session_nodes AS n ON n.session_key = m.session_key;
    DROP TABLE session_members;
    ALTER TABLE session_members_new RENAME TO session_members;
  `)}function rebuildTranscriptIndexState(e){let t=readSqliteTableColumns(e,`session_transcript_index_state`);t&&e.exec(`
    DROP TABLE IF EXISTS session_transcript_index_state_new;
    CREATE TABLE session_transcript_index_state_new (
      session_id TEXT NOT NULL PRIMARY KEY,
      indexed_seq INTEGER NOT NULL,
      leaf_event_id TEXT,
      needs_rebuild INTEGER NOT NULL DEFAULT 0,
      active_event_count INTEGER NOT NULL DEFAULT 0,
      active_message_count INTEGER NOT NULL DEFAULT 0,
      updated_at INTEGER NOT NULL,
      FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO session_transcript_index_state_new (
      session_id, indexed_seq, leaf_event_id, needs_rebuild,
      active_event_count, active_message_count, updated_at
    )
    SELECT
      i.session_id,
      i.indexed_seq,
      ${migratedSessionColumn(t,`leaf_event_id`,`NULL`)},
      ${migratedSessionColumn(t,`needs_rebuild`,`0`)},
      ${migratedSessionColumn(t,`active_event_count`,`0`)},
      ${migratedSessionColumn(t,`active_message_count`,`0`)},
      i.updated_at
    FROM session_transcript_index_state AS i
    INNER JOIN session_windows AS w ON w.session_id = i.session_id;
    DROP TABLE session_transcript_index_state;
    ALTER TABLE session_transcript_index_state_new RENAME TO session_transcript_index_state;
  `)}function migrateSessionNodesAndWindows(e,t){t>=14||!readSqliteTableColumns(e,`sessions`)||(createSessionNodes(e),backfillSessionNodes(e),migrateSessionWindows(e),renameTranscriptRewriteWatermarks(e),rebuildBoardTabs(e),rebuildHeartbeatOutcomes(e),rebuildSessionMembers(e),rebuildTranscriptIndexState(e),e.exec(`
    DROP TABLE IF EXISTS session_routes;
    DROP TABLE IF EXISTS session_entries;
  `))}function migrateAgentJsonPredicatesInTransaction(e){H(e,`session_nodes`,`session_started_at INTEGER`),H(e,`session_nodes`,`has_optional_references INTEGER NOT NULL DEFAULT 0`),e.exec(`
    UPDATE session_nodes SET
      session_started_at = CASE WHEN json_valid(entry_json)
        THEN CAST(json_extract(entry_json, '$.sessionStartedAt') AS INTEGER) END,
      has_optional_references = CASE WHEN NOT json_valid(entry_json) OR instr(entry_json, char(0)) > 0 THEN 1
        WHEN json_type(entry_json, '$.previousSessionId') IS NOT NULL
          OR json_type(entry_json, '$.usageFamilySessionIds') IS NOT NULL
          OR json_type(entry_json, '$.compactionCheckpoints') IS NOT NULL THEN 1
        ELSE 0 END;
  `),V(e,`context_engine_turn_outbox`)&&(H(e,`context_engine_turn_outbox`,`payload_state TEXT`),e.exec(`
      UPDATE context_engine_turn_outbox SET payload_state = CASE
        WHEN json_valid(payload_json) THEN CASE
          WHEN json_type(payload_json, '$.state') = 'text'
          THEN json_extract(payload_json, '$.state') END END;
    `));for(let t of Xt.transcript_events)H(e,`transcript_events`,`${t} ${Gt[t]}`)}function migrateOutboxEnqueueSequenceInTransaction(e){if(!V(e,`context_engine_turn_outbox`)||Xe(e,`context_engine_turn_outbox`,`enqueue_sequence`))return null;let t=performance.now(),n=F(e)??P(e),r=[...n.indexDefinitions.values(),...n.triggers.values()].filter(({table:e})=>e===`context_engine_turn_outbox`),i=M(d,`context_engine_turn_outbox`);e.exec(`
    ${i.replace(`IF NOT EXISTS context_engine_turn_outbox`,`context_engine_turn_outbox_sequence_migration`)}
    INSERT INTO context_engine_turn_outbox_sequence_migration
      (enqueue_sequence, advancement_key, engine_id, owner_plugin_id, session_id,
       payload_json, payload_state, attempt_count, last_attempt_at, last_error, created_at)
    SELECT rowid, advancement_key, engine_id, owner_plugin_id, session_id,
       payload_json, payload_state, attempt_count, last_attempt_at, last_error, created_at
    FROM context_engine_turn_outbox;
    DROP TABLE context_engine_turn_outbox;
    ALTER TABLE context_engine_turn_outbox_sequence_migration RENAME TO context_engine_turn_outbox;
  `);for(let t of r)t.sql!==null&&e.exec(t.sql);return performance.now()-t}function migrateSessionEntrySnapshotsInTransaction(e){e.exec(`ALTER TABLE session_nodes ADD COLUMN snapshot_revision INTEGER NOT NULL DEFAULT 0`),e.exec(Rt(d));let t=R(e),n=t.selectFrom(`session_nodes`).select([`session_key`,`current_session_id`,`updated_at`,`entry_json`]).orderBy(`session_key`).limit(64),r=ge(e,e=>n.where(`session_key`,`>`,e(e=>e))),i=ge(e,e=>t.insertInto(`session_entry_snapshots`).values({session_key:e(e=>e.sessionKey),field:e(e=>e.field),value_json:e(e=>e.valueJson)})),a=ge(e,e=>t.updateTable(`session_nodes`).set({entry_json:e(e=>e.entryJson)}).where(`session_key`,`=`,e(e=>e.sessionKey))),o=ge(e,e=>t.updateTable(`session_nodes`).set({entry_valid:1}).where(`session_key`,`=`,e(e=>e))),s;for(;;){let{rows:t}=s===void 0?z(e,n):r(s);if(t.length===0)return;q();for(let e of t){if(typeof e.session_key!=`string`||typeof e.current_session_id!=`string`||typeof e.updated_at!=`number`||typeof e.entry_json!=`string`)throw Error(`Unreadable session row during snapshot migration`);s=e.session_key;let t=vn({current_session_id:e.current_session_id,updated_at:e.updated_at,entry_json:e.entry_json});if(!t)continue;let{entryJson:n,snapshots:r}=yn(t);if(r.length!==0){for(let t of r)i({sessionKey:e.session_key,...t});a({entryJson:n,sessionKey:e.session_key}),o(e.session_key)}}}}const Z=`session_transcript_fts_rows_legacy22`;function migrateDeployedTranscriptFtsRowsInTransaction(e,t){if(!e.isTransaction||e.prepare(`PRAGMA foreign_keys`).get()?.foreign_keys!==0)throw Error(`Transcript FTS migration requires an admitted transaction with foreign keys off`);G(e,`deployed transcript FTS ownership`,en);let n=e.prepare(`PRAGMA table_xinfo(session_transcript_fts_rows)`).all();if(n.length!==2||n.some(e=>e.name!==`session_id`&&e.name!==`fts_rowid`))throw Error(`Transcript FTS migration cannot discard unknown row-map columns`);let r=e.prepare(`SELECT name FROM sqlite_schema
    WHERE (tbl_name = 'session_transcript_fts_rows' AND sql IS NOT NULL
      AND type IN ('index', 'trigger') AND name != 'idx_agent_transcript_fts_rows_session')
      OR (type IN ('view', 'trigger') AND sql LIKE '%session_transcript_fts_rows%')`).all(),i=e.prepare(`SELECT schema.name FROM sqlite_schema AS schema
    JOIN pragma_foreign_key_list(schema.name) AS fk
    WHERE schema.type = 'table' AND fk."table" = 'session_transcript_fts_rows'`).all();if(r.length||i.length)throw Error(`Transcript FTS migration cannot discard unknown row-map dependencies`);if(e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = ?`).get(Z))throw Error(`Transcript FTS migration table already exists`);e.exec(`ALTER TABLE session_transcript_fts_rows RENAME TO ${Z}`),e.exec(M(t,`session_transcript_fts_rows`,{endMarker:`INSERT OR IGNORE INTO memory_index_state`,includeEndMarker:!1})),e.exec(`INSERT INTO session_transcript_fts_rows (id, session_id, message_id)
    SELECT rowid, session_id, message_id FROM session_transcript_fts`),e.exec(`UPDATE session_transcript_index_state AS state SET needs_rebuild = 1
    WHERE needs_rebuild = 0 AND (
      fts_row_count IS NULL
      OR fts_row_count != (SELECT count(*) FROM ${Z} AS old WHERE old.session_id = state.session_id)
      OR EXISTS (
        SELECT 1 FROM ${Z} AS old
        WHERE old.session_id = state.session_id AND NOT EXISTS (
          SELECT 1 FROM session_transcript_fts_rows AS current
          WHERE current.id = old.fts_rowid AND current.session_id = old.session_id))
      OR EXISTS (
        SELECT 1 FROM session_transcript_fts_rows AS current
        WHERE current.session_id = state.session_id AND NOT EXISTS (
          SELECT 1 FROM ${Z} AS old
          WHERE old.fts_rowid = current.id AND old.session_id = current.session_id))
    );
    DROP TABLE ${Z};
    ALTER TABLE session_transcript_index_state DROP COLUMN fts_row_count;`)}const Q=`transcript_events_payload_migration`,or=/* @__PURE__ */ new Set([`transcript_event_identities`,`session_transcript_active_events`]);function assertTranscriptRebuildInputs(e){G(e,`transcript payload migration`,M(Qt(d),`transcript_events`));let t=e.prepare(`PRAGMA table_xinfo(transcript_events)`).all(),n=/* @__PURE__ */ new Set([`session_id`,`seq`,`event_json`,`created_at`]);if(t.length!==n.size||t.some(e=>typeof e.name!=`string`||!n.has(e.name)))throw Error(`Transcript payload migration cannot discard unknown columns`);if(e.prepare(`SELECT name FROM sqlite_schema
      WHERE (type IN ('trigger', 'index') AND tbl_name = 'transcript_events' AND sql IS NOT NULL)
         OR (type IN ('view', 'trigger') AND sql LIKE '%transcript_events%')`).all().length>0)throw Error(`Transcript payload migration cannot rebuild unknown indexes, views, or triggers`);if(e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = ?`).get(Q))throw Error(`Transcript payload migration table already exists`);for(let t of e.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table'`).all()){if(typeof t.name!=`string`)throw Error(`Invalid table name during transcript payload migration`);if(!or.has(t.name)&&e.prepare(`PRAGMA foreign_key_list(${j(t.name)})`).all().some(e=>e.table===`transcript_events`))throw Error(`Transcript payload migration cannot rebuild an unknown foreign-key target`)}}function migrateTranscriptPayloadStorageInTransaction(e){if(!e.isTransaction||e.prepare(`PRAGMA foreign_keys`).get()?.foreign_keys!==0)throw Error(`Transcript payload migration requires an admitted transaction with foreign keys off`);assertTranscriptRebuildInputs(e);let t=N(e)===`UTF-8`,n=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),r=bn();e.exec(M(d,`transcript_events`).replace(`IF NOT EXISTS transcript_events`,Q));let i=e.prepare(`
    INSERT INTO ${Q}
      (rowid, session_id, seq, event_json, created_at, event_zstd, event_utf8_bytes, navigation_json)
    SELECT rowid, session_id, seq, event_json, created_at, NULL,
           CASE WHEN ? THEN octet_length(event_json) ELSE NULL END, ?
    FROM transcript_events WHERE rowid = ?`),a=e.prepare(`
    INSERT INTO ${Q}
      (rowid, session_id, seq, event_json, created_at, event_zstd, event_utf8_bytes, navigation_json)
    SELECT rowid, session_id, seq, NULL, created_at, ?, ?, ?
    FROM transcript_events WHERE rowid = ?`);i.setReadBigInts(!0),a.setReadBigInts(!0);let o=e.prepare(`SELECT CAST(event_json AS BLOB) AS bytes FROM transcript_events WHERE rowid = ?`),s=e.prepare(`SELECT rowid AS storage_rowid, octet_length(event_json) AS bytes FROM transcript_events ORDER BY rowid`);s.setReadBigInts(!0);let c=performance.now();for(let l of s.iterate()){if(performance.now()-c>=1e3&&(q(),c=performance.now()),typeof l.storage_rowid!=`bigint`||typeof l.bytes!=`bigint`)throw Error(`Invalid transcript storage identity during migration`);let s=null,u=!1;if(t&&l.bytes<=BigInt(4194304)){let t=o.get(l.storage_rowid)?.bytes;if(!(t instanceof Uint8Array))throw Error(`Transcript payload disappeared during migration`);let i;try{i=n.decode(t)}catch{}if(i!==void 0){let n=xn(e,i,void 0,`UTF-8`);if(s=n.navigation_json,n.event_zstd!==null){if(n.event_utf8_bytes===null||!r.decompress(n.event_zstd,n.event_utf8_bytes).equals(t))throw Error(`Transcript compression did not preserve canonical bytes`);let e=a.run(n.event_zstd,n.event_utf8_bytes,s,l.storage_rowid);if(Number(e.changes)!==1)throw Error(`Transcript payload disappeared before migration publication`);u=!0}}}if(!u&&Number(i.run(+!!t,s,l.storage_rowid).changes)!==1)throw Error(`Transcript identity payload disappeared before migration publication`)}q(),e.exec(`DROP TABLE transcript_events;
    ALTER TABLE ${Q} RENAME TO transcript_events;`)}const $=x(`state/agent-db`);function migrateMemoryChunkMetadataSchema(e){gt(e),mt(e)}function*agentDatabaseIntegrityBeforeMutationSteps(e,t,n,r,i,a=!1,o=!1,s,c){if(a&&o)return r&&(r.integrityGateOutcome=`cached`),!1;ve(e,k);let l=F(e)?.userVersion??A(e),u=l===0&&sn(e),f=l===0&&u||l>0&&l<38;f&&$.info(`agent database schema migration pending; verifying integrity first`,{fromVersion:l,path:n,toVersion:38});let p=l===38&&hasPendingCurrentVersionAgentDatabaseMigration(e),m=Wn({kind:`agent`,foundVersion:l,supportedVersion:38},s),h=performance.now();if(r?.integrityGateReason===`stale-lease-full`&&r.because&&$.info(`agent database integrityGateReason=stale-lease-full because=${r.because}`,{agentId:t,path:n,...r}),l===38&&!p){let o=a||i!==void 0&&!f&&!p,validateSchema=r=>assertOpenClawAgentCurrentRuntimeSchema(e,{agentId:t,pathname:n},r),l=yield*Kn(e,n,d,{allowMissingColumns:!0,validateAfterRepair:validateSchema,validateUnchanged:validateSchema,diagnostics:r,reuseIntegrity:o,integrity:s?{...m,tables:c??m.tables}:void 0});l.length>0&&$.warn(`Rebuilt canonical agent SQLite indexes for ${t} (${n}): ${l.join(`, `)}`,{agentId:t,path:n,indexes:l,elapsedMs:Math.floor(performance.now()-h)})}else l===0&&!u&&e.prepare(`PRAGMA page_count`).get()?.page_count===0?ze(e,n,s?m:void 0):yield*Ie(e,n,r,m);return p}function migrateAgentStorageInTransaction(e,t,n,r){if(q(),n===22)migrateDeployedTranscriptFtsRowsInTransaction(e,t);else if(e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = ?`).get(`session_transcript_fts_rows`))throw Error(`Transcript FTS row map already exists before the schema-23 storage migration.`);q(),migrateTranscriptPayloadStorageInTransaction(e),q(),ht(e,{renewAuthority:q,onWarning:e=>r.push(e)}),q(),migrateSessionCostUsageRollupStorage(e,q),q(),e.exec(t),n!==22&&e.exec(`
    INSERT INTO session_transcript_fts_rows (id, session_id, message_id)
    SELECT rowid, session_id, message_id FROM session_transcript_fts;
  `)}function ensureAgentSchema(e,t,n,r=38,i=e=>e(),a,o=!1,s){let c=[],l=Vt(r);e.exec(`PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = OFF;`);let u=!1;try{be(e,()=>{de(e);let i=W(e);un(i,t,n);let a=cn(e,n),d=Wn({kind:`agent`,foundVersion:a,supportedVersion:r},s),f=a===0&&!sn(e),p=a<r&&(a>0||i!==null),m=r>=18&&p;if(m&&i?.schemaVersion!==a)throw Error(`Agent schema markers disagree for ${n}; repair ownership metadata before migration.`);if(a>r)throw Error(`OpenClaw agent database ${n} uses schema version ${a}; expected at most ${r} for this migration.`);!f&&a<r&&assertSupportedAgentMigrationSchemas(e,n,a);let assertMigration=()=>{p&&(m&&on(),B()?.assertAgentSchemaMigration({agentId:t,path:n,foundVersion:a,supportedVersion:r}))};if(assertMigration(),a<r&&Ct(e,a),f&&r===38){e.exec(l),e.exec(`PRAGMA user_version = ${r};`),persistAgentSchemaMetadata(e,t,r),u=!0;return}let crossesVersion=e=>!f&&a<e&&r>=e,h=crossesVersion(25),g=crossesVersion(23),_=crossesVersion(24),ee=crossesVersion(30),v=ee?Mt(l):l,y=_?$t(v):v,b=g?Qt(y,a):y,finishStorageMigration=()=>{if(g&&migrateAgentStorageInTransaction(e,y,a,c),_&&migrateSessionEntrySnapshotsInTransaction(e),h&&migrateCanonicalSessionWriterValidation(e),crossesVersion(26)&&migrateAgentJsonPredicatesInTransaction(e),a<27&&r>=27){let r=migrateOutboxEnqueueSequenceInTransaction(e);r!==null&&$.info(`agent outbox enqueue sequence rebuilt`,{agentId:t,pathname:n,elapsedMs:r})}crossesVersion(28)&&rn(e),crossesVersion(29)&&e.exec(Nt),ee&&Pt(e),crossesVersion(31)&&e.exec(Ft),crossesVersion(37)&&e.exec(jt),a<25&&Gn(e,n,l,{verifyPhysicalIntegrity:!1,integrity:d}),finishAgentSchemaMigration(e,t,n,r,l,m,assertMigration,p?Vn({kind:`agent`,foundVersion:a,supportedVersion:r}):void 0)};if(a>=25&&a<r)assertAgentSchemaVersion(e,{agentId:t,pathname:n,version:a},Vt(a)),o||ensureSessionAdditiveColumns(e),finishStorageMigration();else if(a<r&&a>=20&&a<25&&r>=21){a>=21&&(migrateRetiredAgentStateLeaseSchema(e,n,r),ensureSessionAdditiveColumns(e),ensureSessionEntryValidityProjection(e),ensureLegacySessionEntryValidityTriggers(e),ensureSessionKeyContractSchemaInTransaction(e),hasPendingMemoryChunkMetadataMigration(e)&&migrateMemoryChunkMetadataSchema(e));let i=Vt(a);Gn(e,n,i,{verifyPhysicalIntegrity:!1,integrity:d}),assertAgentSchemaVersion(e,{agentId:t,pathname:n,version:a},i),a<21&&(e.exec(Ht(b)),h||seedCanonicalSessionValidationPending(e)),finishStorageMigration()}else a===17&&(ensureSessionAdditiveColumns(e),ensureLegacySessionEntryValidityTriggers(e),ze(e,n,d),migrateMemoryChunkMetadataSchema(e),assertOpenClawAgentSchemaContains(e,n,Vt(a),`legacy`,!0)),migrateRetiredAgentStateLeaseSchema(e,n,r),a===r?(ensureSessionAdditiveColumns(e),ensureSessionEntryValidityProjection(e),ensureSessionKeyContractSchemaInTransaction(e),ensureSessionReactionsSchemaInTransaction(e),hasPendingMemoryChunkMetadataMigration(e)&&(migrateMemoryChunkMetadataSchema(e),e.exec(l)),Gn(e,n,l,{verifyPhysicalIntegrity:!1,integrity:s?d:void 0}),a===16&&repairAndAssertOpenClawAgentV16Validity(e,n,l),persistAgentSchemaMetadata(e,t,r),assertAgentSchemaVersion(e,{agentId:t,pathname:n,version:r},l),On()):(a===14&&repairAndAssertOpenClawAgentV14SchemaForMigration(e,{agentId:t,pathname:n}),q(),St(e),migrateOpenClawAgentSchema(e),migrateConversationDeliveryTargetColumn(e),a<11&&backfillSessionConversations(e),migrateSessionNodesAndWindows(e,a),q(),ensureSessionAdditiveColumns(e),r>=18&&a<18&&migrateSessionParticipantsSchema(e,n),r>=19&&migrateSessionCreatorNamespaces(e,a),ensureSessionEntryValidityProjection(e),q(),e.exec(b),a!==17&&migrateMemoryChunkMetadataSchema(e),a<r&&Yn(e),migrateSessionTranscriptGenerations(e,a),migrateSessionTranscriptActiveProjection(e,a),a<11&&ft(e,b,{databaseLabel:n,integrityCheck:s}),a<21&&r>=21&&!h&&seedCanonicalSessionValidationPending(e),finishStorageMigration())},{databaseLabel:n,operationLabel:`agent.schema.ensure`,withCommit:i})}finally{e.isOpen&&e.exec(`PRAGMA foreign_keys = ON;`)}u&&(pe(e)||F(e))&&(fe(e),At(e));for(let e of c){let n=`Agent ${t}: ${e}`;$.warn(n),a?.(n)}}function registerOpenClawAgentWalMaintenance(e,t){if(O(e.db))return;let n={agentId:e.agentId,path:e.path,env:t},r=it(e),i={kind:`file`,physicalIdentity:r.identity,birthtime:r.birthtime,nativeLocation:r.filename},a=new AbortController,o,s,cancel=()=>{a.abort()},assertCurrent=()=>{if(a.signal.throwIfAborted(),J.databases.get(e.path)!==e||!e.db.isOpen)throw Error(`Agent WAL maintenance owner changed`)};Ue(e.db,async t=>{if(a.signal.aborted)return;let r=Ae(e.db),c=Mn(n,async()=>{assertCurrent(),s=we({...n,revoke:cancel,async close(){cancel(),await o?.catch(()=>{})}});let{captureOpenClawAgentDatabaseExecution:e}=await import(`./transcript-openclaw-agent-execution-BjCoKZsU.mjs`);assertCurrent();let r=e(n,{expectedIdentity:i});try{let e=await r.runExisting(In(assertCurrent,`Agent WAL maintenance authority expired`),e=>e.execute({type:`database.walMaintenance`,input:t}));return assertCurrent(),r.assertCurrent(),e}finally{await r.release()}},void 0,a.signal);o=c;try{return await c}finally{r(),o=void 0,s?.(),s=void 0}},cancel)}const{openOpenClawAgentDatabase:sr,openOpenClawAgentDatabaseInWorker:cr,runOpenClawAgentWriteTransaction:lr,withOpenClawAgentDatabaseAsync:ur,withOpenClawAgentDatabaseRuntime:dr,withOpenClawAgentDatabaseRuntimeFromExecution:fr,withOpenClawAgentDatabaseAdmission:pr}=createOpenClawAgentDatabaseAdmissionOwner(openOpenClawAgentDatabaseSteps);function*openOpenClawAgentDatabaseSteps(e,t,i,a,c){let u=an(),d=u?void 0:c?.integrityCheck??B()?.sqliteIntegrityCheck;u&&nt();let f=I(e.agentId);Oe(f,{env:e.env});let h={...e,agentId:f},g=L(h),assertCurrent=e=>{c?.assertCurrent?.(),c?.expectedIdentity&&(e?ot(e,c.expectedIdentity):y(g,c.expectedIdentity.key,c.expectedIdentity.birthtime))};assertCurrent(),o(h),Se(h)?.assertCurrent();let _=ke(h);if(_){if(assertCurrent(_),i)throw Error(`A prepared Worker lease cannot adopt an existing agent database handle`);return t?.workerPrepared&&Ot(_,!0,!0),_}De({agentId:f,path:g}),t||jn(g);let v=J.databases.get(g),b=!process.permission&&m();c?.expectedIdentity||Pe(g),pn(g);let x=Ne(`agent`,g,{env:h.env});if(x)throw Ln(g,x),x;v&&(Cn(v),J.databases.delete(g),J.failures.delete(g));let S={...e.env??process.env,OPENCLAW_STATE_DIR:D(e.env??process.env),...rt(e.env??process.env)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};if(i&&(i.receipt.agentId!==f||i.receipt.path!==g))throw Error(`Prepared agent database lease belongs to another store`);let C=!1,te,ne=!1,re=!1,w={},T=t?.validation??i?.validation,E=i?.integrityRevoked===!0||t?.integrityRevoked===!0||wt(g,T),ae=i?i.provenance:Un(g),captureVerification=(e,n,r,a)=>{C=e,te=a,re=n&&e&&!E&&r===void 0,ne=n||i?.integrityRevoked===!0||t?.integrityRevoked===!0,w.because=n?r:void 0,n&&T&&Atomics.store(new Int32Array(T.valid),0,0)},oe={env:S,initializationAgentPaths:[g]};assertCurrent();let A=i?i.claim(captureVerification):Rn({agentId:f,path:g,env:S},void 0,captureVerification);t&&(t.assertHeld=()=>Sn(A,{agentId:f,path:g,env:S}));let j=kn(f,g,t?`async`:`sync`,w),M,N,P,de;try{if(assertCurrent(),i&&!Y)try{et({stage:`prepare`,facts:{kind:`agent-validation-start`,lease:i.receipt}})}catch(e){throw new l(e)}c?.expectedIdentity||(ensureOpenClawAgentDatabasePermissions(g,h),Ke(g)),hn(g);let o=Ye(c?.expectedIdentity?Je(g):g,{allowExtension:b,timeout:u?void 0:k});M=o;let m=o;at(o,r(S)),assertCurrent({db:o,path:g}),c?.expectedIdentity&&ensureOpenClawAgentDatabasePermissions(g,h),o.enableLoadExtension(!1),ue(o),i&&o.exec(`PRAGMA temp_store = FILE`),j(`open`);let _={db:o,path:g,agentId:f};T&&!u&&Tt(_,T);let v=!!Et(_),y=v||C||t?.workerPrepared===!0&&!ne,x=!1,E;try{if(u)t&&(de=s(t,h,async()=>{await Fn(g,f)})),m=nn(o,f,g,!1,(e,t)=>{throw m=M=e,t}),M=m,E={checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:He,close:()=>!0},bt({db:m,path:g,agentId:f}),v=!0,x=!0;else{x=Ot(_,y,t?.workerPrepared),x||fe(o,e=>{cn(o,g,e)});let e=W(o);un(e,f,g),x&&ln(e,f,g),t&&(de=s(t,h,async()=>{await Fn(g,f)})),w.integrityGateReason=ne?re&&ae!==null&&Un(g)===ae?`process-death`:`stale-lease-full`:wt(g,T)?`revoked`:C?ee(o)??`no-proof`:`lease-class`,w.because??=w.integrityGateReason===`stale-lease-full`?Hn(i?.provenance,g):void 0;let n;w.integrityGateReason===`revoked`||w.integrityGateReason===`process-death`||w.integrityGateReason===`stale-lease-full`?(v=!1,x=!1):C&&(n=p(o)),d!==`quick`&&(d===`full`||![`process-death`,`lease-class`,`no-proof`].includes(w.integrityGateReason))&&wn(A,{agentId:f,path:g,env:S},`full-required`);let r=yield*agentDatabaseIntegrityBeforeMutationSteps(o,f,g,w,n,v&&y||w.integrityGateReason===`lease-class`&&te!==void 0&&Un(g)===te,x,d,c?.integrityTables??[]);assertCurrent(_),(!w.integrityGateOutcome||w.integrityGateOutcome===`cached`)&&delete w.integrityGateReason,v&&(!e||r)&&(kt(g),v=!1),dn(o,g),j(`validation`),We(o,{busyTimeoutMs:k}),E=qe(o,{busyTimeoutMs:k,autoCheckpointPages:0,databaseLabel:`openclaw-agent:${f}`,databasePath:g,foreignKeys:!0,synchronous:`NORMAL`}),P=E,j(`configuration`),assertCurrent(_),(!e||r||!v&&le(o)!==ie)&&ensureAgentSchema(o,f,g,void 0,void 0,void 0,!1,d),j(`schema`),m=nn(o,f,g)}}catch(e){w.integrityGateOutcome===`failed`&&j(`validation`),P?.close(),m.isOpen&&m.close(),O(m)&&o.isOpen&&o.close();let t=J.databases.get(g);throw(!t||t.db===o)&&kt(g),e instanceof Error&&(ce(e)||Fe(e))&&Ln(g,e),e}assertCurrent({db:m,path:g}),ensureOpenClawAgentDatabasePermissions(g,h),x||(fe(o),vt(o));let D={agentId:f,db:m,path:g,walMaintenance:E};if(N=D,Bn())throw Error(`Agent database maintenance is in progress; retry after openclaw doctor --fix completes.`);return Ce(D,h)?.registerClose(An(D,`Agent deletion cleanup`)),n(D,h)?.registerClose(An(D,`Agent creation claim`)),!v||!qn(D,{env:e.env})?(assertCurrent(D),Jn({agentId:f,path:g,env:e.env,admittedDb:d===`quick`?void 0:m},a)):x||yt(D),J.terminal.clear(g),J.unregisterExitClose??=Ve(Tn),j(`registration`),Dn(D,A,S),assertCurrent(D),wn(A,{agentId:f,path:g,env:S}),En(D),Y&&registerOpenClawAgentWalMaintenance(D,S),B()?.own(D.db,`agent-handles`,()=>Nn(D)),de?.(),D}catch(e){let n=i!==void 0&&!Y&&e instanceof l,r;if(N)try{Cn(N)}catch(e){r=e}if(M&&(M.isOpen||se(M).isOpen)){let n=J.databases.get(g);if(t&&n&&n.db!==M){let t=M;throw Pn(f,g,()=>{P?.close(),t.isOpen&&t.close();let e=se(t);O(t)&&e.isOpen&&e.close(),zn(A,oe)}),e}kt(g);let i=N??{agentId:f,db:M,path:g,walMaintenance:P??{checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:He,close:()=>!1}};J.databases.set(g,i),En(i),J.leases.set(g,{leaseId:A,env:S}),J.failures.set(g,r??e),B()?.own(i.db,`agent-handles`,()=>Nn(i)),J.unregisterExitClose??=Ve(Tn)}else if(!n){let t=e instanceof l?`read-only`:void 0;try{zn(A,oe,t)}catch(e){throw Pn(f,g,()=>zn(A,oe,t)),e}}throw r??e}}function borrowOpenClawAgentDatabase(e){let{db:t}=sr(e);return{db:t,release:Ae(t)}}export{nr as a,decodeUsageCostRollup as c,isUsageCostRollupFresh as d,readUsageCostDeferredMetadata as f,dr as i,decodeUsageCostRollupEnvelope as l,normalizeOptionalAccountId as m,sr as n,rr as o,normalizeChatType as p,lr as r,canUseUsageCostRollupForPartial as s,borrowOpenClawAgentDatabase as t,encodeUsageCostRollup as u};