openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,411 lines • 162 kB
JavaScript
import{i as e,n as t,r as n}from"./openclaw-state-read-semver-CqfGj9gv.mjs";import{C as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,N as f,P as p,T as m,U as h,W as g,Z as ee,p as _,q as v,v as y,z as b}from"./openclaw-state-read-sqlite-readonly-worker-umlSCyCR.mjs";import{H as te}from"./openclaw-state-read-map-size-DJbMcZYM.mjs";import{_ as x,a as S,f as C,v as w}from"./openclaw-state-read-home-dir-BQZX1pD2.mjs";import{Ct as T,D as E,Kt as ne,Q as D,Qt as re,St as ie,T as ae,c as oe,k as se,tn as ce,w as le,yt as ue}from"./openclaw-state-read-sqlite-database-admission-Ck6VG7rE.mjs";import{n as de,o as fe,r as pe}from"./openclaw-state-read-src-BpoB6DKe.mjs";import{a as me}from"./openclaw-state-read-tmp-openclaw-dir-C3Ynn93H.mjs";import{A as he,O as ge,p as _e}from"./openclaw-state-read-openclaw-state-db-cache-BVY8IYkn.mjs";import{s as ve}from"./openclaw-state-read-logger-Ix7jXPG1.mjs";import{v as ye,x as be,y as xe}from"./openclaw-state-read-read-open-flags-CtNL1rJs.mjs";import{t as Se}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{i as Ce}from"./openclaw-state-read-path-existence-Bp_sxI9A.mjs";import{a as we,i as Te,s as Ee}from"./openclaw-state-read-openclaw-state-db.paths-CFemYLpA.mjs";import{d as De,s as O}from"./openclaw-state-read-openclaw-state-db-async-lifecycle-B_Y330HB.mjs";import{a as k,n as Oe,r as A}from"./openclaw-state-read-record-coerce-D1s3ReAs.mjs";import{s as j}from"./openclaw-state-read-openclaw-state-db-contract-DiFTYPe3.mjs";import{S as ke,_ as M,b as Ae,c as je,l as N,n as Me,o as Ne,p as P,r as Pe,t as Fe,y as F}from"./openclaw-state-read-schemas-CLrAtqTl.mjs";import{o as Ie}from"./openclaw-state-read-sqlite-worker-operation-settlement-ogK5IsJy.mjs";import{c as Le,d as Re,s as ze,u as I}from"./openclaw-state-read-sqlite-post-commit-CEHMNIsB.mjs";import{a as Be}from"./openclaw-state-read-kysely-sync-cache-state-PxpuKzoA.mjs";import{a as Ve,i as He}from"./openclaw-state-read-sqlite-busy-timeout-D5Khm-oR.mjs";import{t as Ue}from"./openclaw-state-read-node-crypto-DZZez2wo.mjs";import{n as We,r as Ge}from"./openclaw-state-read-sqlite-files-B6lm_PVC.mjs";import{t as Ke}from"./openclaw-state-read-subsystem-DSi0tJn8.mjs";import{n as qe}from"./openclaw-state-read-json-coercion-DgTIp8OM.mjs";import{c as Je}from"./openclaw-state-read-sqlite-snapshot-capacity-error-Df9fZtJA.mjs";import{a as L,c as Ye,l as Xe,m as Ze,o as Qe,p as R,r as z,s as $e,t as et,u as tt}from"./openclaw-state-read-kysely-sync-DQyYiAw5.mjs";import{c as nt,t as rt}from"./openclaw-state-read-sqlite-schema-sql-BnVx4b5A.mjs";import"./openclaw-state-read-errors-D_saNBXy.mjs";import"./openclaw-state-read-open-pprz0Grj.mjs";import{_ as it,d as at,h as ot,o as st,t as ct,u as lt,y as ut}from"./openclaw-state-read-sqlite-schema-facts-DxLfPKu-.mjs";import{n as dt,r as ft}from"./openclaw-state-read-node-sqlite-UqZdY7HG.mjs";import{o as pt,r as mt}from"./openclaw-state-read-sqlite-worker-operation-admission-DTfv_SKu.mjs";import{a as ht,i as gt,o as _t}from"./openclaw-state-read-sqlite-transaction-V1rK3HH2.mjs";import{n as vt,o as yt,s as bt}from"./openclaw-state-read-openclaw-state-db-schema-helpers-BkqUYEFY.mjs";import{c as xt,d as St,i as Ct,n as wt,s as Tt,u as Et}from"./openclaw-state-read-openclaw-state-db-DnrW7QY9.mjs";import{n as B,t as Dt}from"./openclaw-state-read-agent-id-DmscQLD6.mjs";import{t as Ot}from"./openclaw-state-read-gateway-supervision-queMstQ7.mjs";import{d as kt,l as At,p as jt,u as Mt}from"./openclaw-state-read-openclaw-state-db-schema-migration-required-D_rQ-tLc.mjs";import{c as Nt,o as Pt,s as Ft}from"./openclaw-state-read-openclaw-state-db-readonly-CDG18cNK.mjs";import{r as It}from"./openclaw-state-read-sqlite-handle-lifecycle-DQ13SM2U.mjs";import{l as Lt,u as Rt}from"./openclaw-state-read-openclaw-state-db-handle-D9nuaODy.mjs";import{a as zt,c as V,d as Bt,f as Vt,l as H,m as U,p as Ht,r as Ut,s as Wt}from"./openclaw-state-read-json-values-CH7dRPGy.mjs";import{c as Gt,i as Kt,l as qt,o as Jt,s as Yt}from"./openclaw-state-read-sqlite-integrity-6ijoQyXy.mjs";import{t as Xt}from"./openclaw-state-read-sqlite-schema-contract-CE8IFvCt.mjs";import{A as Zt,B as Qt,C as $t,D as en,E as W,F as tn,G as nn,H as rn,I as an,J as on,K as sn,L as cn,M as G,N as ln,O as un,P as dn,R as fn,S as pn,T as mn,U as hn,V as gn,W as _n,X as K,Y as vn,Z as yn,_ as bn,a as xn,b as q,c as Sn,d as Cn,f as wn,g as Tn,h as En,i as Dn,j as On,k as kn,l as An,m as J,n as jn,o as Mn,p as Nn,q as Pn,s as Fn,t as In,u as Ln,v as Rn,w as zn,x as Bn,y as Vn,z as Hn}from"./openclaw-state-read-openclaw-agent-write-admission-DlU_dfHg.mjs";import{L as Un,Wt as Wn,xt as Gn}from"./openclaw-state-read.worker.js";import{r as Kn}from"./openclaw-state-read-src-DfYHsQWn.mjs";import{i as qn,l as Jn}from"./openclaw-state-read-session-key-DaKMXMbu.mjs";import{i as Yn,n as Xn,r as Zn,t as Qn}from"./openclaw-state-read-store-entry-C1CP-bSg.mjs";import{n as $n,r as er,t as tr}from"./openclaw-state-read-session-accessor.sqlite-scope-helpers-Dc9dXhfU.mjs";import{C as nr,_ as rr,a as ir,b as ar,c as or,f as sr,g as cr,h as lr,i as ur,m as dr,n as fr,v as pr}from"./openclaw-state-read-agent-scope-config-DBTVDK8I.mjs";import{i as mr,o as hr}from"./openclaw-state-read-openclaw-state-worker-context-Cvog3s4V.mjs";import{n as gr,o as _r,t as vr}from"./openclaw-state-read-session-sqlite-target-DOCApy1k.mjs";import{A as yr,C as br,E as xr,F as Sr,I as Cr,L as wr,M as Tr,O as Er,T as Dr,_ as Or,a as kr,c as Ar,d as jr,g as Mr,h as Nr,i as Pr,l as Fr,o as Ir,p as Lr,r as Rr,s as zr,v as Br,y as Vr}from"./openclaw-state-read-session-store-read-candidates-Mon1wMui.mjs";import"./openclaw-state-read-session-row-changes-C0Qzq-vO.mjs";import{a as Hr,o as Ur,t as Wr}from"./openclaw-state-read-openclaw-agent-db-identity-2iBH9vAR.mjs";import{i as Gr,n as Kr,o as qr,r as Jr}from"./openclaw-state-read-openclaw-agent-db-registry-listing-0iIGDbl2.mjs";import{n as Yr}from"./openclaw-state-read-sqlite-strict-C2nIX5Dk.mjs";import"./openclaw-state-read-message-channel-core-VkoqSJSs.mjs";import{i as Xr,r as Zr}from"./openclaw-state-read-agent-run-terminal-reply-4GCOQgEl.mjs";import{n as Qr}from"./openclaw-state-read-agent-deletion-journal-status-hTodcgwC.mjs";import{E as $r,G as ei,H as ti,K as ni,R as ri,T as ii,U as ai,V as oi,W as si,b as ci,c as li,d as ui,h as di,i as fi,n as pi,o as mi,p as hi,q as gi,r as _i,s as vi,u as yi,y as bi,z as xi}from"./openclaw-state-read-session-entry-json-DJKbSB_m.mjs";import{_ as Si,a as Ci,b as wi,c as Ti,d as Ei,f as Di,g as Oi,h as ki,i as Ai,l as ji,m as Mi,n as Ni,o as Pi,p as Fi,r as Ii,s as Li,t as Ri,u as zi,v as Bi,y as Vi}from"./openclaw-state-read-session-entry-read-source-Cn1lhSEg.mjs";import"./openclaw-state-read-backoff-DDprjZZH.mjs";import{r as Hi}from"./openclaw-state-read-agent-deletion-journal.read-DWSUE9n3.mjs";import{r as Ui,t as Wi}from"./openclaw-state-read-agent-deletion-journal-UgiZY2jq.mjs";import"./openclaw-state-read-agent-database-preparation-context-Cw99Iadw.mjs";import"./openclaw-state-read-parse-duration-DaoU71uo.mjs";import{t as Gi}from"./openclaw-state-read-gateway-request-scope-_mUrevdn.mjs";import{t as Ki}from"./openclaw-state-read-secure-random-Bwhk0Eun.mjs";import{t as qi}from"./openclaw-state-read-zstd-codec-Bwg8OR0e.mjs";import"node:v8";import Y,{chmodSync as Ji,existsSync as Yi,mkdirSync as Xi,statSync as Zi}from"node:fs";import X from"node:path";import{isMainThread as Z}from"node:worker_threads";import"node:fs/promises";import{AsyncLocalStorage as Qi}from"node:async_hooks";import"node:util";function string(e){return ke(Fe,e)}function scanJsonObjectFields(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=new Set(t),o=0,s=0,c=/[\t\n\r ]*/y,l=/-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y,u=/["\\\u0000-\u001f]/g;function fail(){throw SyntaxError(`Invalid JSON predicate source`)}let skipWhitespace=()=>{c.lastIndex=o,c.exec(e),o=c.lastIndex},string=()=>{for(e[o++]!==`"`&&fail();o<e.length;){u.lastIndex=o;let t=u.exec(e);if(t||fail(),o=u.lastIndex,t[0]===`"`)return;t[0]!==`\\`&&fail();let n=e[o++];n===`u`?(/^[0-9a-fA-F]{4}$/.test(e.slice(o,o+4))||fail(),o+=4):n!==void 0&&`"\\/bfnrt`.includes(n)||fail()}fail()},value=t=>{skipWhitespace();let c=e[o];if(s=Math.max(s,t+ +(c===`{`||c===`[`)),c===`"`)return string(),`string`;if(c===`{`||c===`[`){let s=c===`{`,l=s?`}`:`]`;if(o++,skipWhitespace(),e[o]===l)return o++,s?`object`:`array`;for(;o<e.length;){let c;if(s){let n=o;string(),t===0&&(c=JSON.parse(e.slice(n,o))),skipWhitespace(),e[o++]!==`:`&&fail()}skipWhitespace();let u=o,d=value(t+1);if(c!==void 0){let t=c.indexOf(`\0`),s=t<0?c:c.slice(0,t),l=a.has(s)&&!n.has(s),f=a.has(c);if(l||f){let t={kind:d,text:e.slice(u,o)};l&&n.set(s,t),f&&(r.has(c)&&i.add(c),r.set(c,t))}}skipWhitespace();let f=e[o++];if(f===l)return s?`object`:`array`;f!==`,`&&fail(),skipWhitespace()}fail()}let u=c===`t`?`true`:c===`f`?`false`:c===`n`?`null`:void 0;return u&&e.startsWith(u,o)?(o+=u.length,u===`null`?`null`:`boolean`):(l.lastIndex=o,l.test(e)||fail(),o=l.lastIndex,`number`)};try{return value(0),skipWhitespace(),o!==e.length&&e[o]!==`\0`&&fail(),{valid:!0,maximumDepth:s,first:n,last:r,duplicateKeys:i}}catch{return{valid:!1,maximumDepth:s,first:/* @__PURE__ */ new Map,last:/* @__PURE__ */ new Map,duplicateKeys:/* @__PURE__ */ new Set}}}function readJsonPredicateScalar(e){if(e&&e.kind!==`object`&&e.kind!==`array`)return JSON.parse(e.text)}w(Symbol.for(`openclaw.preparedSessionSharingReads`),()=>/* @__PURE__ */ new Map),w(Symbol.for(`openclaw.pendingSessionEntryPublications`),()=>/* @__PURE__ */ new Map),x(Symbol.for(`openclaw.unknownSessionSharingAuthorities`),`close-and-restart`),w(Symbol.for(`openclaw.preparedSessionSharingChanges`),()=>({changes:/* @__PURE__ */ new WeakMap,operations:/* @__PURE__ */ new WeakMap,current:new Qi}));function readSessionTranscriptRunId(e){return k(e)?C((A(e.__openclaw)??{}).runId):void 0}x(Symbol.for(`openclaw.sessionTranscriptListeners`),`close-and-restart`),x(Symbol.for(`openclaw.internalSessionTranscriptListeners`),`close-and-restart`),w(Symbol.for(`openclaw.sessionTranscriptUpdateState`),()=>({version:0}));const Q=`openclawSyntheticMissingToolResult`,$i=`[openclaw] missing tool result in session history; inserted synthetic error result for transcript repair.`;function isSyntheticMissingToolResult(e){if(!e.isError)return!1;if(Oe(e.details)?.openclawSyntheticMissingToolResult===!0)return!0;let t=e.content;return Array.isArray(t)&&t.some(e=>{let t=Oe(e);return t?.type===`text`&&t.text===`[openclaw] missing tool result in session history; inserted synthetic error result for transcript repair.`})}const ea=`openclaw.background-result-placement`,ta=/* @__PURE__ */ new Set([`message`,`thinking_level_change`,`model_change`,`compaction`,`reset`,`branch_summary`,`custom`,`custom_message`,`label`,`session_info`]),na=string().pipe(Me([`new`,`reset`,`idle`,`daily`,`cron-stale`])),ra=P({type:Ae().optional().refine(e=>e!==`session`&&e!==`leaf`),id:M().min(1),parentId:F([M(),Pe()])}),ia=P({type:N(`leaf`),id:M().min(1),parentId:F([M(),Pe()]),targetId:F([M(),Pe()]),appendParentId:F([M(),Pe()]).optional(),appendMode:N(`side`).optional(),billsDisplaced:N(!0).optional()}),aa=P({type:N(`session`),id:M()});function findSessionTranscriptHeader(e){for(let t of e)if(aa.safeParse(t).success)return t}function isReadableSessionMessage(e){if(!k(e))return!1;switch(e.role){case`user`:case`assistant`:return isReadableContent(e.content);case`custom`:return typeof e.customType==`string`&&isReadableContent(e.content);case`toolResult`:return typeof e.toolCallId==`string`&&typeof e.toolName==`string`&&typeof e.isError==`boolean`&&Array.isArray(e.content);case`bashExecution`:return typeof e.command==`string`&&typeof e.output==`string`;default:return!1}}function isIndexedSessionEntry(e){if(!k(e)||!isNonemptyString(e.id)||e.parentId!==void 0&&e.parentId!==null&&typeof e.parentId!=`string`||e.timestamp!==void 0&&typeof e.timestamp!=`string`)return!1;switch(e.type){case`message`:return isReadableSessionMessage(e.message);case`thinking_level_change`:return isNonemptyString(e.thinkingLevel);case`model_change`:return isNonemptyString(e.provider)&&isNonemptyString(e.modelId);case`compaction`:return typeof e.summary==`string`&&isNonemptyString(e.firstKeptEntryId)&&typeof e.tokensBefore==`number`;case`reset`:return(e.firstKeptEntryId===void 0||typeof e.firstKeptEntryId==`string`)&&na.safeParse(e.reason).success;case`branch_summary`:return typeof e.fromId==`string`&&typeof e.summary==`string`;case`custom`:return isNonemptyString(e.customType);case`custom_message`:return isNonemptyString(e.customType)&&isReadableContent(e.content)&&typeof e.display==`boolean`;case`label`:return isNonemptyString(e.targetId)&&(e.label===void 0||typeof e.label==`string`);case`session_info`:return e.name===void 0||typeof e.name==`string`;default:return!1}}function isNonemptyString(e){return typeof e==`string`&&e.length>0}function isReadableContent(e){if(typeof e==`string`)return!0;if(!Array.isArray(e))return!1;for(let t of e)if(!k(t)||typeof t.type!=`string`)return!1;return!0}function isReadableLegacySessionEntry(e){let t=k(e)&&e.type===`message`?e.message:void 0;return k(e)&&typeof e.type==`string`&&ta.has(e.type)&&(e.type!==`message`||(k(t)&&t.role===`hookMessage`?isReadableContent(t.content):isReadableSessionMessage(t)))}function normalizePersistedLegacyHookMessage(e){if(!k(e)||e.type!==`message`||!k(e.message))return e;let t=e.message;return t.role!==`custom`||t.customType!==void 0||!isReadableContent(t.content)?e:{...e,message:{...t,customType:`hook`}}}function parseParentLinkedOpaqueEntry(e){let t=ra.safeParse(e);return t.success?{id:t.data.id,parentId:t.data.parentId}:void 0}function parseOpaqueLeafEntry(e){let t=ia.safeParse(e);if(!t.success)return;let n=t.data;return{id:n.id,parentId:n.parentId,targetId:n.targetId,...n.appendParentId===void 0?{}:{appendParentId:n.appendParentId},...n.appendMode===`side`?{appendMode:n.appendMode}:{},...n.billsDisplaced?{billsDisplaced:!0}:{}}}function classifySessionFileEntry(e,t){let n=normalizePersistedLegacyHookMessage(e);return t<3&&isReadableLegacySessionEntry(n)||isIndexedSessionEntry(n)?{entry:n,recognized:!0}:{entry:n,recognized:!1}}w(Symbol.for(`openclaw.sessionEntryPublicationSources`),()=>/* @__PURE__ */ new WeakMap),[...[Zr,Xr].map(e=>`After completing all due tasks, reply ${e}.`),`${Xr}`],w(Symbol.for(`openclaw.replyPayloadMetadata`),()=>/* @__PURE__ */ new WeakMap);const oa={"image/avif":`.avif`,"image/heic":`.heic`,"image/heic-sequence":`.heic`,"image/heif":`.heif`,"image/heif-sequence":`.heif`,"image/bmp":`.bmp`,"image/jpg":`.jpg`,"image/jpeg":`.jpg`,"image/png":`.png`,"image/svg+xml":`.svg`,"image/webp":`.webp`,"image/gif":`.gif`,"audio/aiff":`.aiff`,"audio/x-aiff":`.aiff`,"audio/ogg":`.ogg`,"audio/mpeg":`.mp3`,"audio/mp3":`.mp3`,"audio/wav":`.wav`,"audio/wave":`.wav`,"audio/x-wav":`.wav`,"audio/flac":`.flac`,"audio/aac":`.aac`,"audio/amr":`.amr`,"audio/opus":`.opus`,"audio/webm":`.webm`,"audio/x-m4a":`.m4a`,"audio/m4a":`.m4a`,"audio/mp4":`.m4a`,"audio/x-caf":`.caf`,"video/x-msvideo":`.avi`,"video/x-m4v":`.m4v`,"video/mp4":`.mp4`,"video/x-matroska":`.mkv`,"video/webm":`.webm`,"video/x-flv":`.flv`,"video/x-ms-wmv":`.wmv`,"video/quicktime":`.mov`,"application/pdf":`.pdf`,"application/json":`.json`,"application/yaml":`.yaml`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/x-tar":`.tar`,"application/x-7z-compressed":`.7z`,"application/vnd.rar":`.rar`,"application/msword":`.doc`,"application/vnd.ms-excel":`.xls`,"application/vnd.ms-powerpoint":`.ppt`,"application/vnd.openxmlformats-officedocument.wordprocessingml.document":`.docx`,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":`.xlsx`,"application/vnd.openxmlformats-officedocument.presentationml.presentation":`.pptx`,"text/csv":`.csv`,"text/plain":`.txt`,"text/markdown":`.md`,"text/html":`.html`,"text/xml":`.xml`,"text/css":`.css`,"application/xml":`.xml`},sa={};for(let[e,t]of Object.entries(oa))sa[t]??=e;Object.assign(sa,{".jpg":`image/jpeg`,".m2a":`audio/mpeg`,".m4b":`audio/mp4`,".mp3":`audio/mpeg`,".oga":`audio/ogg`,".wav":`audio/wav`,".webm":`video/webm`,".aif":`audio/aiff`,".aifc":`audio/aiff`,".jpeg":`image/jpeg`,".cfg":`text/plain`,".conf":`text/plain`,".env":`text/plain`,".ini":`text/plain`,".js":`text/javascript`,".log":`text/plain`,".htm":`text/html`,".tsv":`text/tab-separated-values`,".xml":`text/xml`,".yml":`application/yaml`}),(/* @__PURE__ */ e((/* @__PURE__ */ t(((e,t,n)=>{(function(e){let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=/* @__PURE__ */ RegExp(`^0[0-7]+$`,`i`),a=/* @__PURE__ */ RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function expandIPv6(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>=t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(t[e].length>4?NaN:parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function matchCIDR(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function parseIntAuto(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function padPart(e,t){for(;e.length<t;)e=`0${e}`;return e}let l={};l.IPv4=(function(){function IPv4(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,18,0,0]),15],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]],as112:[[new IPv4([192,175,48,0]),24],[new IPv4([192,31,196,0]),24]],amt:[[new IPv4([192,52,193,0]),24]]},IPv4.prototype.kind=function(){return`ipv4`},IPv4.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return matchCIDR(this.octets,e.octets,8,t)},IPv4.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},IPv4.prototype.range=function(){return l.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.toIPv4MappedAddress=function(){return l.IPv6.parse(`::ffff:${this.toString()}`)},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toString=function(){return this.octets.join(`.`)},IPv4})(),l.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv4 CIDR format`,{cause:e})}},l.IPv4.isIPv4=function(e){return this.parser(e)!==null},l.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},l.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},l.IPv4.isValidFourPartDecimal=function(e){return!!(l.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},l.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!l.IPv4.isValidCIDR(e)||!t?!1:l.IPv4.isValidFourPartDecimal(t[1])},l.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv4 CIDR format`,{cause:e})}},l.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},l.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,"toString",{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},l.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(parseIntAuto(n));return r})();if(t=e.match(r.longValue)){if(i=parseIntAuto(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t=0;for(;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}return(t=e.match(r.twoOctet))?(function(){let e=t.slice(1,4),n=[];if(i=parseIntAuto(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(parseIntAuto(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})():(t=e.match(r.threeOctet))?(function(){let e=t.slice(1,5),n=[];if(i=parseIntAuto(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(parseIntAuto(e[0])),n.push(parseIntAuto(e[1])),n.push(i>>8&255),n.push(i&255),n})():null},l.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),Number.isNaN(e)||e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},l.IPv6=(function(){function IPv6(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return IPv6.prototype.SpecialRanges={unspecified:[new IPv6([0,0,0,0,0,0,0,0]),128],linkLocal:[new IPv6([65152,0,0,0,0,0,0,0]),10],multicast:[new IPv6([65280,0,0,0,0,0,0,0]),8],loopback:[new IPv6([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new IPv6([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new IPv6([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new IPv6([65216,0,0,0,0,0,0,0]),10],discard:[new IPv6([256,0,0,0,0,0,0,0]),64],rfc6145:[new IPv6([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new IPv6([100,65435,0,0,0,0,0,0]),96],[new IPv6([100,65435,1,0,0,0,0,0]),48]],"6to4":[new IPv6([8194,0,0,0,0,0,0,0]),16],teredo:[new IPv6([8193,0,0,0,0,0,0,0]),32],benchmarking:[new IPv6([8193,2,0,0,0,0,0,0]),48],amt:[new IPv6([8193,3,0,0,0,0,0,0]),32],as112v6:[[new IPv6([8193,4,274,0,0,0,0,0]),48],[new IPv6([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new IPv6([8193,16,0,0,0,0,0,0]),28],orchid2:[new IPv6([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new IPv6([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new IPv6([24320,0,0,0,0,0,0,0]),16],reserved:[[new IPv6([8193,0,0,0,0,0,0,0]),23],[new IPv6([8193,3512,0,0,0,0,0,0]),32],[new IPv6([16383,0,0,0,0,0,0,0]),20]]},IPv6.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},IPv6.prototype.kind=function(){return`ipv6`},IPv6.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return matchCIDR(this.parts,e.parts,16,t)},IPv6.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},IPv6.prototype.range=function(){return l.subnetMatch(this,this.SpecialRanges)},IPv6.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},IPv6.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(padPart(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},IPv6.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new l.IPv4([t>>8,t&255,n>>8,n&255])},IPv6.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},IPv6.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=``;this.zoneId&&(t=`%${this.zoneId}`);let n=this.toNormalizedString(),r=n.slice(0,n.length-t.length),i=0,a=-1,o=-1,s;for(;s=e.exec(r);){let e=(s[0].match(/0/g)||[]).length;e>o&&(o=e,i=s.index,a=s[0].length)}return a<0?r+t:`${r.substring(0,i)}::${r.substring(i+a)}${t}`},IPv6.prototype.toString=function(){return this.toRFC5952String()},IPv6})(),l.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format`,{cause:e})}},l.IPv6.isIPv6=function(e){return this.parser(e)!==null},l.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},l.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},l.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format`,{cause:e})}},l.IPv6.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},l.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,"toString",{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},l.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return expandIPv6(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=expandIPv6(t+o,6),t&&t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},l.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),Number.isNaN(e)||e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},l.fromByteArray=function(e){let t=e.length;if(t===4)return new l.IPv4(e);if(t===16)return new l.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},l.isValid=function(e){return l.IPv6.isValid(e)||l.IPv4.isValid(e)},l.isValidCIDR=function(e){return l.IPv6.isValidCIDR(e)||l.IPv4.isValidCIDR(e)},l.parse=function(e){if(l.IPv6.isValid(e))return l.IPv6.parse(e);if(l.IPv4.isValid(e))return l.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},l.parseCIDR=function(e){try{return l.IPv6.parseCIDR(e)}catch{try{return l.IPv4.parseCIDR(e)}catch(e){throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`,{cause:e})}}},l.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},l.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=l:e.ipaddr=l})(n)})))(),1)).default.IPv4.parse(`198.18.0.0`),new TextEncoder;const ca=[`agent_harness_task`,`agent_harness_completion`,`image_generate`,`music_generate`,`video_generate`];new Set(ca),[...ca],[.../* @__PURE__ */ new Set([`tool_call`,`tool_result`,`function_call`,`function_calls`,`function_response`,`function`,`tool_calls`,`invoke`,`antml:invoke`,`antml:parameter`,`antml:function_calls`,`mm:tool_call`,`mm:function_calls`,`mm:invoke`,`mm:parameter`])];const la=`[A-Za-z_:][-A-Za-z0-9_:.]*`,ua=String.raw`(?:"[^"]*"|'[^']*'|[^\s"'=<>\x60]+)`,da=String.raw`(?:\s+${la}\s*=\s*${ua})*`;new RegExp(String.raw`^${da}\s*[[{]`),new RegExp(String.raw`^${da}(?:\s+${la}(?:\s*=(?:\s*(?:"[^"]*|'[^']*|[^\s"'=<>\x60]+))?)?)?\s*$`),[...[`data`,`blob`,`path`,`file`,`filePath`,`localPath`].filter(e=>e!==`path`)],w(Symbol.for(`openclaw.transcriptAuthorityStaged`),()=>/* @__PURE__ */ new WeakMap),w(Symbol.for(`openclaw.transcriptAuthorityChanges`),()=>/* @__PURE__ */ new WeakMap);function mapAgentSessionDirs(e,t,n){return t.filter(e=>e.isDirectory()&&(n?.(e.name)??!0)).map(t=>X.join(e,t.name,`sessions`)).sort((e,t)=>e.localeCompare(t))}function resolveAgentSessionDirsFromAgentsDirSync(e,t){let n;try{n=Y.readdirSync(e,{withFileTypes:!0})}catch(e){return te(e)??[]}return mapAgentSessionDirs(e,n,t)}const fa=Ke(`sessions/targets`);function dedupeSessionStoreTargetsBySqliteTarget(e,t){let n,readRegistry=()=>n??=vr(t.registeredDatabases,t.env),reportDiagnostic=e=>{t.onDiagnostic?t.onDiagnostic(e):fa.warn(e.message)},r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=s(),o=a.createIndex(),c=a.createIndex(),resolveGroupKey=(e,t,n)=>e.size===0?X.resolve(n):(e.size===1&&t(e.keys().next().value),t(n));for(let n of e){let e=gr(n.storePath,{agentId:n.agentId,defaultAgentId:t.defaultAgentId,env:t.env,get registeredDatabases(){return readRegistry()},isSameDatabasePath:a,readCandidates:t.readCandidates}),s=resolveGroupKey(r,o,e.path),l=r.get(s)??[];if(l.push({target:n,shared:e.shared===!0,...e.agentId?{databaseOwnerAgentId:e.agentId}:{}}),r.set(s,l),e.shared)continue;let u=resolveGroupKey(i,c,X.resolve(ar(n.storePath).path)),d=i.get(u)??[];d.push({target:n,...e.ownerSource?{ownerSource:e.ownerSource}:{},...e.unsuffixedOwnerAgentId?{unsuffixedOwnerAgentId:e.unsuffixedOwnerAgentId}:{}}),i.set(u,d)}for(let[e,t]of i){let n=[...new Set(t.map(({target:e})=>B(e.agentId)))];if(n.length<=1||t.some(e=>!e.ownerSource))continue;let r=t[0]?.unsuffixedOwnerAgentId,i=t[0]?.ownerSource??`configured-default`,a=r?n.filter(e=>e!==r):n;reportDiagnostic({message:r?`Session store target collision at ${e}: owner "${r}" selected by ${i}; suffixed owner(s): ${a.map(e=>`"${e}"`).join(`, `)}.`:i===`registered-suffixed`?`Session store target collision at ${e}: configured default retains its registered suffixed target; all claimant(s) use suffixed targets: ${a.map(e=>`"${e}"`).join(`, `)}.`:i===`occupied-unsuffixed`?`Session store target collision at ${e}: unsuffixed target is occupied without a durable owner; all claimant(s) use suffixed targets: ${a.map(e=>`"${e}"`).join(`, `)}.`:`Session store target collision at ${e}: registry ownership is ambiguous; all claimant(s) use suffixed targets: ${a.map(e=>`"${e}"`).join(`, `)}.`,sqlitePath:e,...r?{ownerAgentId:r}:{},ignoredAgentIds:a,ownerSource:i})}let l=[];for(let[e,n]of r){let r=new Map(n.map(({target:e})=>[B(e.agentId),e])),i=[...new Set(n.flatMap(e=>e.databaseOwnerAgentId??[]))],o=i.length===1?[]:[...new Set(readRegistry().filter(t=>a(t.path,e)).map(e=>B(e.agentId)))],s=r.size>1;if(i.length!==1&&o.length>1){reportDiagnostic({message:`Session store target collision at ${e}: registry ownership is ambiguous across ${o.map(e=>`"${e}"`).join(`, `)}; no owner selected.`,sqlitePath:e,ignoredAgentIds:[...r.keys()],ownerSource:`ambiguous-registry`});continue}let c=i.length===1?`database-path`:o.length===1?`database-registry`:`configured-default`,u=B(i[0]??o[0]??(s?t.defaultAgentId:n[0].target.agentId)),d=r.get(u)??(n.some(e=>e.shared)?r.get(B(t.defaultAgentId))??n[0]?.target:void 0);if(d&&(l.push(d),t.onResolvedTarget?.(d,{agentId:u,storePath:e}),t.onSharedTarget)){let e=new Set(n.filter(e=>e.shared).map(e=>e.target.storePath));e.size>0&&t.onSharedTarget(d,e)}let f=d?B(d.agentId):u,p=[...r.keys()].filter(e=>e!==f);if(!d||p.length>0){let t=d?p:[...r.keys()];reportDiagnostic({message:`Session store target collision at ${e}: owner "${u}" selected by ${c}; ignored owner(s): ${t.map(e=>`"${e}"`).join(`, `)}.`,sqlitePath:e,ownerAgentId:u,ignoredAgentIds:t,ownerSource:c})}}return l}const pa=/* @__PURE__ */ new Set([`EACCES`,`ELOOP`,`ENOENT`,`ENOTDIR`,`EPERM`,`ESTALE`]);function shouldSkipDiscoveryError(e){let t=xe(e)?e.code:void 0;return typeof t==`string`&&pa.has(t)}function createRealAgentsRootResolver(){let e=/* @__PURE__ */ new Map;return t=>{if(e.has(t))return e.get(t);try{let n=Y.realpathSync.native(t);return e.set(t,n),n}catch(n){if(shouldSkipDiscoveryError(n)){e.set(t,void 0);return}throw n}}}function isWithinRoot(e,t){return e===t||e.startsWith(`${t}${X.sep}`)}function shouldSkipDiscoveredAgentDirName(e,t){return!/[a-z0-9]/i.test(e)||!Dt(t)||t===`main`&&e.toLowerCase()!==`main`}function resolveValidatedManagedFilePathSync(e){try{let t=Y.lstatSync(e.filePath);return t.isSymbolicLink()||!t.isFile()?void 0:isWithinRoot(Y.realpathSync.native(e.filePath),e.realAgentsRoot??Y.realpathSync.native(e.agentsRoot))?e.filePath:void 0}catch(e){if(shouldSkipDiscoveryError(e))return;throw e}}function resolveValidatedDiscoveredStorePathSync(e){let t=X.join(e.sessionsDir,`sessions.json`);if(!e.sqliteOnly){let n=resolveValidatedManagedFilePathSync({agentsRoot:e.agentsRoot,filePath:t,realAgentsRoot:e.realAgentsRoot});if(n)return n}let n=gr(t).path;return resolveValidatedManagedFilePathSync({agentsRoot:e.agentsRoot,filePath:n,realAgentsRoot:e.realAgentsRoot})?t:void 0}function isValidatedRecoveryCandidateSessionsDir(e){let t=X.dirname(e.sessionsDir);try{let n=Y.lstatSync(t);if(n.isSymbolicLink()||!n.isDirectory()||!isWithinRoot(Y.realpathSync.native(t),e.realAgentsRoot))return!1;try{let t=Y.lstatSync(e.sessionsDir);return!t.isSymbolicLink()&&t.isDirectory()&&isWithinRoot(Y.realpathSync.native(e.sessionsDir),e.realAgentsRoot)}catch(e){return ye(e,`ENOENT`)}}catch(t){if(ye(t,`ENOENT`))return e.allowMissingAgentDir===!0;if(shouldSkipDiscoveryError(t))return!1;throw t}}function toDiscoveredSessionStoreTarget(e,t){let n=X.basename(X.dirname(e)),r=B(n);if(!shouldSkipDiscoveredAgentDirName(n,r))return{agentId:r,storePath:t}}function resolveExplicitSessionStoreTarget(e){let t=rr(e.store,{agentId:e.defaultAgentId,env:e.env});return(cr(t)?toDiscoveredSessionStoreTarget(X.dirname(t),t):void 0)??{agentId:e.defaultAgentId,storePath:t}}var ma=/* @__PURE__ */ n({isConfiguredAgentDatabaseTarget:()=>isConfiguredAgentDatabaseTarget,resolveAllAgentSessionStoreTargetsSync:()=>resolveAllAgentSessionStoreTargetsSync,resolveConfiguredAgentDatabaseCandidatePaths:()=>resolveConfiguredAgentDatabaseCandidatePaths,resolveConfiguredAgentDatabaseTargets:()=>resolveConfiguredAgentDatabaseTargets,resolveConfiguredSessionStoreTargets:()=>resolveConfiguredSessionStoreTargets,resolveSessionStoreTargets:()=>resolveSessionStoreTargets});function resolveConfiguredSessionStoreTargets(e,t,n){return St(e).map(r=>({agentId:r,storePath:Rr(e.session?.store,r,t,n)}))}function resolveSessionStoreDiscoveryState(e,t){let n=t.env??process.env,r=t.agentIds,i=r?resolveConfiguredSessionStoreTargets(e,n,t.readPaths):resolveSessionStoreTargets(e,{allAgents:!0},t);if(!lr(e.session?.store))for(let r of t.fixedStoreAgentIds??[])Et(e,r)||i.push({agentId:r,storePath:Rr(e.session?.store,r,n,t.readPaths)});let a=/* @__PURE__ */ new Set;for(let e of i){let t=cr(e.storePath);t&&a.add(t)}return a.add(X.join(me(n),`agents`)),{configuredTargets:r?i.filter(e=>r.has(e.agentId)):i,agentsRoots:[...a]}}function resolveAllAgentSessionStoreTargetsSync(e,t={}){return resolveAllAgentSessionStoreTargets(e,t,!1)}function resolveAllAgentSessionStoreTargets(e,t,n){let r=t.env??process.env,{configuredTargets:i,agentsRoots:a}=resolveSessionStoreDiscoveryState(e,{env:r,registeredDatabases:t.registeredDatabases,readCandidates:t.readCandidates,readPaths:t.readPaths,agentIds:t.agentIds,fixedStoreAgentIds:t.fixedStoreAgentIds,excludeTarget:t.excludeTarget}),o=createRealAgentsRootResolver(),s=i.flatMap(e=>{if(t.excludeTarget?.(e))return[];let r=cr(e.storePath);if(!r||n&&!Y.existsSync(r))return[e];let i=o(r);if(!i)return[];if(n)return isValidatedRecoveryCandidateSessionsDir({allowMissingAgentDir:!0,realAgentsRoot:i,sessionsDir:X.dirname(e.storePath)})?[e]:[];let a=resolveValidatedDiscoveredStorePathSync({sessionsDir:X.dirname(e.storePath),agentsRoot:r,realAgentsRoot:i});return a?[{...e,storePath:a}]:[]}),c=a.flatMap(e=>{try{let r=o(e);return r?resolveAgentSessionDirsFromAgentsDirSync(e).flatMap(i=>{let a=toDiscoveredSessionStoreTarget(i,X.join(i,`sessions.json`));if(a&&t.excludeTarget?.(a))return[];let o=n?isValidatedRecoveryCandidateSessionsDir({realAgentsRoot:r,sessionsDir:i})?X.join(i,`sessions.json`):void 0:resolveValidatedDiscoveredStorePathSync({sessionsDir:i,agentsRoot:e,realAgentsRoot:r}),s=o?toDiscoveredSessionStoreTarget(i,o):void 0;return s?[s]:[]}):[]}catch(e){if(shouldSkipDiscoveryError(e))return[];throw e}}),l=[...s,...c],u=t.agentIds;return dedupeSessionStoreTargetsBySqliteTarget(u?l.filter(e=>u.has(e.agentId)):l,{defaultAgentId:_r(e),env:r,onResolvedTarget:t.onResolvedTarget,registeredDatabases:t.registeredDatabases,readCandidates:t.readCandidates})}function resolveConfiguredAgentDatabaseCandidatePaths(e,t){let n=St(e);return[.../* @__PURE__ */ new Set([...n.flatMap(n=>pr(rr(e.session?.store,{agentId:n,env:t.env}),n)),...[.../* @__PURE__ */ new Set([...n,...nr(e)])].map(n=>X.join(fr(e,n,t.env),`openclaw-agent.sqlite`))])]}function resolveConfiguredAgentDatabaseTargets(e,t){let{env:n}=t,r=t.agentId===void 0?void 0:B(t.agentId),i=/* @__PURE__ */ new Map,add=(e,t)=>{(r===void 0||e===r)&&i.set(`${e}\0${t}`,{agentId:e,path:t})};dedupeSessionStoreTargetsBySqliteTarget(resolveConfiguredSessionStoreTargets(e,n).filter(e=>!t.excludeTarget?.(e)),{...t,defaultAgentId:_r(e),onResolvedTarget:(e,t)=>add(t.agentId,t.storePath)});for(let i of nr(e))r!==void 0&&i!==r||t.nativeAgentIds&&!t.nativeAgentIds.has(i)||add(i,X.join(fr(e,i,n),`openclaw-agent.sqlite`));return[...i.values()]}function isConfiguredAgentDatabaseTarget(e,t,n){return e.some(e=>(t===void 0||e.agentId===void 0||e.agentId===t)&&(e.path===n||Y.statSync(e.path,{throwIfNoEntry:!1})&&Y.statSync(n,{throwIfNoEntry:!1})&&o(e.path,n)))}function resolveSessionStoreTargets(e,t,n={}){let r=n.env??process.env,i=t.agent?.trim();if(t.agent!==void 0&&!i)throw Error(`--agent must not be blank`);if(t.store!==void 0&&!t.store.trim())throw Error(`--store must not be blank`);let a=i!==void 0,o=t.allAgents===!0;if(a&&o)throw Error(`--agent and --all-agents cannot be used together`);if(t.store&&o)throw Error(`--store cannot be combined with --all-agents`);if(t.store){let n=dr({config:e,sessionKey:`main`,storePath:t.store,env:r});if(n.kind===`retired`)throw Error(`Session store owner is retired: ${n.agentId}`);let o=i?B(i):void 0;if(o&&n.kind===`configured`&&n.agentId!==o)throw Error(`Session store belongs to agent "${n.agentId}", not requested agent "${o}".`);let s=o??(n.kind===`configured`?n.agentId:void 0)??or(e)??ir(e);a&&ur(e,s);let c=resolveExplicitSessionStoreTarget({defaultAgentId:s,env:r,store:t.store});if((a||n.kind===`configured`)&&c.agentId!==s)throw Error(`Session store belongs to agent "${c.agentId}", not requested agent "${s}".`);return[c]}if(o){let t=_r(e);return dedupeSessionStoreTargetsBySqliteTarget(resolveConfiguredSessionStoreTargets(e,r,n.readPaths).filter(e=>!n.excludeTarget?.(e)),{defaultAgentId:t,env:r,registeredDatabases:n.registeredDatabases,readCandidates:n.readCandidates,...n.diagnostics?{onDiagnostic:e=>n.diagnostics?.push(e.message)}:{}})}if(a){let t=B(i);return ur(e,t),[{agentId:t,storePath:rr(e.session?.store,{agentId:t,env:r})}]}let s=sr(e);if(s.kind===`retired`)throw Error(`Session store owner is retired: ${s.agentId}`);let c=(s.kind===`configured`?s.agentId:void 0)??or(e)??ir(e);return[{agentId:c,storePath:rr(e.session?.store,{agentId:c,env:r})}]}const ha=/* @__PURE__ */ new WeakMap;function recordRetryAttemptErrors(e,t){ha.set(e,[...t])}function getRetryAttemptErrors(e){return e!==null&&(typeof e==`object`||typeof e==`function`)?ha.get(e):void 0}function createRetryFailure(e){let t=e.flatMap(e=>getRetryAttemptErrors(e)??[e]),n=fe(t.at(-1)??/* @__PURE__ */ Error(`Retry failed`),`Non-Error thrown`);return t.length>1&&recordRetryAttemptErrors(n,t),n}de({shouldRetry:e=>!D(e),random:Ki,createFailure:createRetryFailure}),Ke(`state/agent-admission`);const ga=new Qi;function getAgentDatabaseStartupAdmission(){let e=ga.getStore();return e?.isStopped?void 0:e}function hasSqliteFileFamily(e){return Ge(e).some(e=>Y.lstatSync(e,{throwIfNoEntry:!1})!==void 0)}function hasSqliteArtifacts(e){try{return Y.readdirSync(e).some(e=>/\.(?:sqlite3?|db)(?:-(?:wal|shm|journal))?$/iu.test(e))}catch(t){if(!ye(t,`ENOENT`))throw t;return Y.lstatSync(e,{throwIfNoEntry:!1})!==void 0}}function createAgentDatabaseDeletionClassifier(e){let t=e.artifactDirectories,n=e.retainedDeletions,r=n.status===`present`?n:n.status===`unavailable`?n.known:void 0,i=r?.entries??[],a=n.status===`unavailable`?`unavailable`:void 0,o=s(),c=r?t?r.held.flatMap(n=>{let r=X.dirname(l({agentId:n.agentId,env:e.env})),i=X.dirname(n.path),a=X.basename(n.path)===`openclaw-agent.sqlite`,s=[{agentId:n.agentId,path:r},...t.filter(e=>B(e.agentId)===n.agentId||a&&o(e.path,i))];return(a&&[e.env.OPENCLAW_AGENT_DIR,e.env.PI_CODING_AGENT_DIR].some(t=>t?.trim()&&o(S(t,e.env),i))||a&&X.basename(i)===`agent`&&o(X.dirname(X.dirname(i)),X.dirname(X.dirname(r))))&&s.push({agentId:n.agentId,path:i}),s}):r.held:[],isHeld=(e,n)=>c.some(r=>t&&r.agentId===n||o(r.path,e)),u,configuredTargets=()=>u??=typeof e.configuredAgentDatabaseTargets==`function`?e.configuredAgentDatabaseTargets((e,t)=>isHeld(e,t)||i.some(e=>e.agentId===t)):e.configuredAgentDatabaseTargets;return(n,r)=>{if(isHeld(n,r))return`held`;let s=[];if(c.length&&!t&&r!==void 0){let t=B(r);s=configuredTargets().filter(e=>B(e.agentId)===t),s.length===0&&(s=[...e.registeredAgentDatabases.filter(e=>B(e.agentId)===t),{agentId:t,path:ar(n).path}])}if(s.some(e=>isHeld(e.path,e.agentId)))return`held`;let l=i.find(e=>e.agentId===r||(t?[e.agentDir]:e.databasePaths).some(e=>o(e,n)));return l?r===l.agentId?l:(t??[...configuredTargets(),...e.registeredAgentDatabases]).some(r=>!i.some(e=>e.agentId===B(r.agentId))&&o(r.path,n)&&(t!==void 0||g(r.path,e.env)&&(configuredTargets().includes(r)||be(Y.realpathSync.native(me(e.env)),Y.realpathSync.native(r.path)))))?a:l:a}}function createRetainedAgentDatabaseMatcher(e,t,n=`database`,r=`maintenance`){return createRetainedAgentDatabaseMatcherFromSnapshot(e,t,Hi(e,r),n,r)}function createRetainedAgentDatabaseMatcherFromSnapshot(e,t,n,r=`database`,i=`maintenance`){let a=r!==`database`&&r.kind===`agent-directory`;if(!n&&r!==`database`&&i===`maintenance`){let n=[Ee(e),...r.readDatabasePaths()].some(hasSqliteFileFamily)||a&&t(()=>!1).some(e=>hasSqliteArtifacts(e.path));return(e,t)=>n||a&&hasSqliteArtifacts(e)?`unavailable`:void 0}let o=n?.retainedDeletions;if(!o||o.status!==`present`&&!(o.status===`unavailable`&&o.known))return(e,t)=>i===`maintenance`&&(!o||o.status===`unavailable`)?`unavailable`:void 0;let s=a?t(()=>!1):void 0,c=createAgentDatabaseDeletionClassifier({env:e,retainedDeletions:o,configuredAgentDatabaseTargets:s??t,artifactDirectories:s,registeredAgentDatabases:n?.registeredAgentDatabases??[]});return(e,t)=>{let n=c(e,t);return i!==`maintenance`&&n===`unavailable`?void 0:n}}async function runSqliteIntegrityOperationInWorker(e,t){let n=Je(t.signal)??t.signal,beforeResume=()=>{n.throwIfAborted(),t.beforeResume()};try{beforeResume();let r=e.next();for(;!r.done;){let i,a=!1;try{await Vi(r.value.databaseLabel,t.busyTimeoutMs,n,void 0,r.value.timing,{check:r.value.check,schemaOnly:r.value.schemaOnly,tables:r.value.tables,ftsSchemas:r.value.ftsSchemas},{onToleratedFts:()=>{a=!0}})}catch(e){i={error:e}}if(beforeResume(),!i&&r.value.check!==`quick`&&!a&&se(r.value.database),i&&t.repairIntegrityError){let e=i.error;try{await t.repairIntegrityError(r.value,e)&&(i=void 0)}catch(t){e instanceof Error&&(e.message+=` Startup FTS repair failed: ${String(t)}`)}beforeResume()}r=i?e.throw(i.error):e.next()}return r.value}finally{e.return(void 0)}}async function withWorkerAdmission(e,t,n,r,i,o){let s=l(e);a(e),p(e);let u=c(e),d=B(e.agentId),f=Se(),m=!1,releaseExecution,assertAdmission=()=>{if(m)throw Error(`Agent database admission closed during worker preparation`);t?.(),i?.assertCurrent(),u?.assertCurrent(),n?.throwIfAborted()},h=y({agentId:d,path:s,revoke:()=>{m=!0},close:()=>f.promise},e);try{let t=i?oe(s):void 0,a=t?{...t,canonicalPath:await ce(s)}:await re(s);if(i&&(i.assertCurrent(),i.agentId!==d||i.path!==s))throw Error(`Agent worker admission differs from its captured execution`);assertAdmission();let c=a.canonicalPath===s?void 0:mi({agentId:d,path:s,canonicalPath:a.canonicalPath}),l=await import(`./openclaw-state-read-openclaw-agent-execution-C0akfw7h.mjs`).then(e=>e.t);if(assertAdmission(),!l.supportsOpenClawAgentDatabaseExecution(e))return await r(`native`);let u;if(i)u=i;else{let t=await l.captureOpenClawAgentDatabaseExecutionAsync(e,a.key.startsWith(`file:`)?{expectedIdentity:{kind:`file`,physicalIdentity:a.key.slice(5),nativeLocation:a.canonicalPath,birthtime:a.birthtime}}:{});u=t,releaseExecution=()=>t.release()}let f={assertCurrent:assertAdmission,onRegistryChange:o,createAdmission:e=>()=>({nativeLocations:e.nativeLocations,admission:mt((t,n)=>{if(e.authorize(t),assertAdmission(),c&&t.stage===`prepare`&&k(t.facts)&&t.facts.kind===`agent-validation-start`&&(c=mi({agentId:d,path:s,canonicalPath:a.canonicalPath})),!n())throw Error(`Agent database preparation lost its admission`)},e.attachment)})};return await In(e,()=>u.prepare(f,n)),assertAdmission(),c?.(u.captureGenerationClaim().identity,li({agentId:d,path:a.canonicalPath,canonicalPath:a.canonicalPath})),await r(`worker`)}finally{try{await releaseExecution?.()}finally{h(),f.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,i){if(n.controller.signal.throwIfAborted(),wr(e.agentId,{env:t.env}),G.databases.get(n.path)!==e||!e.db.isOpen)throw Error(`Agent database closed before its admitted operation: ${n.path}`);r(e,t),f(e,t),i?.()}function assertAgentDatabaseWriteAllowed(e){if(X.basename(e)===`incognito-openclaw-agent.sqlite`)throw Error(`Incognito sessions use the memory session actor, not a SQLite database.`);if(ee(`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&&!Z&&pt({stage:`prepare`,facts:{kind:`agent-open-resume`,lease:n.receipt}})},o=n?.startupRepair;return Gt(a,()=>assertAgentDatabaseOpenAuthority(a,assertCurrent),o&&!Z?(e,t)=>o(e,t,assertCurrent):void 0,Z?wi:void 0)},a=O();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(),pt({stage:`prepare`,facts:{kind:`agent-open-resume`,lease:n.receipt}})}),o=n.startupRepair,s=await runSqliteIntegrityOperationInWorker(a,{busyTimeoutMs:j,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:i,singleStatement:a,...o}=n,s=openAgentDatabase(t,void 0,void 0,i),c=m(t)?.withCommit,l=i?e=>{i.assertCurrent?.(),i.expectedIdentity&&Wr(s,i.expectedIdentity),c?c(e):e()}:c,write=()=>(r(s,t),f(s,t),e(s));return a&&!l&&!I(s.db)?He(s.db,o.busyTimeoutMs??5e3,()=>_t(s.db,write)):Le(s.db,()=>gt(s.db,write,{busyTimeoutMs:o.busyTimeoutMs??5e3,databaseLabel:s.path,...o,operationLabel:o.operationLabel??`agent.write`,withCommit:l}))}function withOpenClawAgentDatabaseAsync(e,t,n,r){let run=()=>runAgentDatabaseAsync(e,t,n,r,`native`),i=O();return i?i.run(run):run()}function withOpenClawAgentDatabaseRuntime(e,t,n,r,i){let run=()=>runAgentDatabaseAsync(e,t,n,r,void 0,void 0,i),a=O();return a?a.run(run):run()}function withOpenClawAgentDatabaseRuntimeFromExecution(e,t,n,r,i){let a=B(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=O();return s?s.run(run):run()}async function runAgentDatabaseAsync(e,t,n,r,i,a,o){r?.throwIfAborted(),n?.();let s={...e,env:ge(e.env??process.env)},c=B(s.agentId),u=l({...s,agentId:c});assertAgentDatabaseWriteAllowed(u),s.env.OPENCLAW_STATE_DIR=me(s.env),s.path=u,G.terminal.peek(u)&&await Bi(u,n,r);let d=G.databases.get(u),f=li({agentId:c,path:u})?.schema;if(!i&&Z&&(!d?.db.isOpen||!f||Atomics.load(new Int32Array(f.valid),0)!==1)&&!G.pending.has(u))return withWorkerAdmission(s,n,r,e=>runAgentDatabaseAsync(s,t,n,r,e,a,o),a,o);let p=G.pending.get(u);if(p?.agentId!==void 0&&p.agentId!==c)throw Error(`Agent database ${u} is opening for ${p.agentId}`);if(p?.controller.signal.aborted)return p.promise.then(()=>runAgentDatabaseAsync(s,t,n,r,i,a,o),()=>runAgentDatabaseAsync(s,t,n,r,i,a,o));let m=p??startOpenClawAgentDatabaseAdmission(s,c,u,n,i===`worker`);return m.operations+=1,pe(m.promise,r).then(e=>(r?.throwIfAborted(),assertAgentDatabaseOperationCurrent(e,s,m,n),De(e.db),t(e))).finally(()=>{--m.operations,m.operations||(m.releaseBorrow||m.controller.abort(/* @__PURE__ */ Error(`Agent database admission has no waiting callers`)),m.releaseBorrow?.())})}function withOpenClawAgentDatabaseAdmission(e,t,n){let run=()=>runAgentDatabaseAdmission(e,t,n),r=O();return r?r.run(()=>r.track(run())):run()}async function runAgentDatabaseAdmission(t,n,r){let i={...t,env:ge(t.env??process.env)},a=B(i.agentId),o=l({...i,agentId:a});assertAgentDatabaseWriteAllowed(o),G.terminal.peek(o)&&await Bi(o);let s=G.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:u}=c;u.promise.catch(()=>{}),u.operations+=1;let d=e(i,u),f,p,m=!1;try{for(;;){let e=await n(async(e,t,n)=>{m=!1,assertAgentDatabaseOpenAuthority(d,()=>{e(),assertOpenClawAgentDatabaseAdmissionCurrent(i,u)}),u.validation=t,u.integrityRevoked=n;let a=p?d.throw(p.error):d.next();if(!a.done)return m=!0,{done:!1,check:a.value};u.releaseBorrow=Cr(a.value.db),c.complete(a.value);let assertOperationCurrent=()=>assertAgentDatabaseOperationCurrent(a.value,i,u,e);assertOperationCurrent();let o=Z||I(a.value.db)?void 0:Lt(a.value.db);o?.(assertOperationCurrent);let s=await r(a.value);return o?.(assertOperationCurrent),{done:!0,result:s}});if(e.done)return e.result;f=e.check,p=void 0;try{u.controller.signal.throwIfAborted(),(Z?wi:Yt)(f)}catch(e){p={error:e}}}}catch(e){let t=[e];if(m){let n=Error(`Agent database admission failed: ${o}`,{cause:e});try{d.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{--u.operations,u.operations||u.releaseBorrow?.()}}function createOpenClawAgentDatabaseAdmission(e,t){_({agentId:e,path:t});let n=Se(),r={agentId:e,path:t,controller:new AbortController,promise:n.promise,operations:0};G.pending.set(t,r),G.activePending.add(r);let retire=()=>{G.pending.get(t)===r&&G.pending.delete(t),G.activePending.delete(r)};return{pending:r,complete:e=>{if(retire(),r.controller.signal.aborted||G.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(),wr(t.agentId,{env:e.env}),G.pending.get(n)!==t)throw Error(`Agent database open was replaced: ${n}`);a(e),m(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 Vi(r,j,s.controller.signal,void 0,e.value.timing,{check:e.value.check,schemaOnly:e.value.schemaOnly,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=Cr(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`||(Zi(e).mode&4095)!==t)&&Ji(e,t)}function ensureOpenClawAgentDatabasePermissions(e,t){let n=X.dirname(e),r=l({agentId:t.agentId,env:t.env}),i=X.resolve(e)===X.resolve(r),a=Yi(n);Xi(n,{recursive:!0,mode:448}),(i||!a)&&ensureMode(n,448);for(let t of Ge(e))try{ensureMode(t,384)}catch(e){if(e.code!==`ENOENT`)throw e}}function resolveRegisteredAgentDatabaseStoredPath(e,t){let n=Te(e.path,t.path);if(t.path!==Ce(t.path))return n;let r=L(e.db),{rows:i}=z(e.db,r.selectFrom(`agent_databases`).select(`path`).where(`agent_id`,`=`,t.agentId));return i.some(e=>e.path===n)?n:i.find(n=>o(we(e.path,n.path),t.path))?.path??n}function registerOpenClawAgentDatabase(e,t){if(!g(e.path,e.env)){e.admittedDb&&di({...e,db:e.admittedDb});return}let n=Ui({agentId:e.agentId,path:e.path},{env:e.env}),r=null;try{r=Zi(e.path).size}catch{r=null}let i=Date.now();if(t?.starting?.(),wt(a=>{Wi(a,n);let o=resolveRegisteredAgentDatabaseStoredPath(a,e),s=L(a.db);z(a.db,s.insertInto(`agent_databases`).values({agent_id:e.agentId,path:o,schema_version:e.schemaVersion??42,last_seen_at:i,size_bytes:r}).onConflict(t=>t.columns([`agent_id`,`path`]).doUpdateSet({schema_version:e.schemaVersion??42,last_seen_at:i,size_bytes:r}))),qr(a,`upsert`,[e]);let c=t?.committed;if(c){let t=Object.freeze({agentId:e.agentId,agentPath:e.path,stateDatabasePath:a.path,stateDatabaseIdentity:_e(a).key});if(!ze(a.db,{stage(){},rollback(){},commit:()=>c(t)}))throw Error(`Agent registration requires its canonical transaction publication scope`)}Kr(e.agentId,a.db)},{env:e.env,initializationAgentPaths:[e.path]}),e.admittedDb){let t={...e,db:e.admittedDb};_i(t)||di(t)}else ui(e.path)}function backfillTranscriptMutationWatermarks(e){yt(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(Mt(e)>=42)return;let t=W(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=W(e,`session_entries`),n=W(e,`session_routes`);if(t){let n=J(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=W(e,`sessions`);if(!t)return;let n=W(e,`session_entries`),r=W(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,
${J(t,`session_scope`,`'conversation'`)},
created_at,
updated_at,
${J(t,`transcript_updated_at`,`NULL`)},
${J(t,`transcript_observed_at`,`NULL`)},
${J(t,`session_entry_provenance`,`0`)},
${J(t,`acp_owned`,`0`)},
${J(t,`plugin_owner_id`,`NULL`)},
${J(t,`hook_external_content_source`,`NULL`)},
${J(t,`started_at`,`NULL`)},
${J(t,`ended_at`,`NULL`)},
${J(t,`status`,`NULL`)},
${J(t,`chat_type`,`NULL`)},
${J(t,`channel`,`NULL`)},
${J(t,`account_id`,`NULL`)},
${J(t,`primary_conversation_id`,`NULL`)},
${J(t,`model_provider`,`NULL`)},
${J(t,`model`,`NULL`)},
${J(t,`agent_harness_id`,`NULL`)},
${J(t,`parent_session_key`,`NULL`)},
${J(t,`spawned_by`,`NULL`)},
${J(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){W(e,`session_transcript_generations`)&&!W(e,`transcript_rewrite_watermarks`)&&e.exec(`ALTER TABLE session_transcript_generations RENAME TO transcript_rewrite_watermarks;`)}function rebuildBoardTabs(e){W(e,`board_tabs`)&&(W(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=W(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,
${J(t,`response_reason`,`NULL`)},
${J(t,`priority`,`NULL`)},
${J(t,`next_check`,`NULL`)},
${J(t,`task_names_json`,`NULL`)},
${J(t,`wake_source`,`NULL`)},
${J(t,`wake_reason`,`NULL`)},
h.occurred_at,
${J(t,`context_run_id`,`NULL`)},
${J(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){W(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=W(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,
${J(t,`leaf_event_id`,`NULL`)},
${J(t,`needs_rebuild`,`0`)},
${J(t,`active_event_count`,`0`)},
${J(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||!W(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){vt(e,`session_nodes`,`session_started_at INTEGER`),vt(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;
`),yt(e,`context_engine_turn_outbox`)&&(vt(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 ii.transcript_events)vt(e,`transcript_events`,`${t} ${$r[t]}`)}function migrateOutboxEnqueueSequenceInTransaction(e){if(!yt(e,`context_engine_turn_outbox`)||bt(e,`context_engine_turn_outbox`,`enqueue_sequence`))return null;let t=performance.now(),n=st(e)??it(e),r=[...n.indexDefinitions.values(),...n.triggers.values()].filter(({table:e})=>e===`context_engine_turn_outbox`),i=rt(ue,`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(ai(ue));let t=L(e),n=t.selectFrom(`session_nodes`).select([`session_key`,`current_session_id`,`updated_at`,`entry_json`]).orderBy(`session_key`).limit(64),r=Ye(e,e=>n.where(`session_key`,`>`,e(e=>e))),i=Ye(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=Ye(e,e=>t.updateTable(`session_nodes`).set({entry_json:e(e=>e.entryJson)}).where(`session_key`,`=`,e(e=>e.sessionKey))),o=Ye(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;K();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=pi({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}=Mi(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 _a=qi();function encodeUsageCostRollup(e){let t=JSON.stringify(e.rollup),n=Buffer.from(t,`utf8`),r=n.byteLength>=1024?_a.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:Ue(n)}};return{valueJson:JSON.stringify(o),blob:Uint8Array.from(a)}}const va=`session-cost-usage-rollup-v2`;function decodePreviousRollup(e){let t=qe(e??``);if(t&&t.version===6&&typeof t.pricingFingerprint==`string`&&k(t.checkpoint)&&(t.checkpoint.kind===`jsonl`||t.checkpoint.kind===`sqlite`)&&typeof t.scannedAt==`number`&&typeof t.parsedRecords==`number`&&typeof t.countedRecords==`number`&&k(t.rollup)&&k(t.rollup.buckets)&&k(t.rollup.untimestamped))return t}function migrateSessionCostUsageRollupStorage(e,t){let n=L(e),r;for(;;){t?.();let i=n.selectFrom(`cache_entries`).select([`key`,`value_json`,`updated_at`]).where(`scope`,`=`,va).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:`session-cost-usage-rollup-v3`,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`,`=`,va).where(`key`,`=`,a.key))}}const $=`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`);Xt(e,`deployed transcript FTS ownership`,ti);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($))throw Error(`Transcript FTS migration table already exists`);e.exec(`ALTER TABLE session_transcript_fts_rows RENAME TO ${$}`),e.exec(rt(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 ${$} AS old WHERE old.session_id = state.session_id)
OR EXISTS (
SELECT 1 FROM ${$} 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 ${$} AS old
WHERE old.fts_rowid = current.id AND old.session_id = current.session_id))
);
DROP TABLE ${$};
ALTER TABLE session_transcript_index_state DROP COLUMN fts_row_count;`)}const ya=[`upstreamUserText`],ba=hr(e=>{let t=A(e.details);if(t?.openclawSyntheticMissingToolResult===!0&&Object.keys(t).length===1)return e;let n={...e};return t?.openclawSyntheticMissingToolResult===!0?n.details={[Q]:!0}:delete n.details,n});function stripToolResultDetails(e){let t=!1,n=e.map(e=>{let n=A(e);if(n?.role!==`toolResult`||!(`details`in n))return e;let r=ba(n);return t||=r!==e,r});return t?n:e}function projectModelContextMessages(e,t){let n=[];for(let r of stripToolResultDetails(e)){let e=A(r),i=A(e?.__openclaw);if(!i||!ya.some(e=>e in i)){n.push(r);continue}let a={...i};for(let e of ya)delete a[e];t?.(a),n.push({...e,__openclaw:a})}return n}function projectSessionModelContextEntry(e,{entry:t,omitCheckpoint:n,toolResultOmission:r}){let i={...e,parentId:t.parentId,...t.type===`compaction`||t.type===`reset`?{firstKeptEntryId:t.firstKeptEntryId}:{}};if(i.type!==`message`)return i;let[a]=projectModelContextMessages([i.message]),o={...i,message:a};return n&&o.message.role===`assistant`&&(o.message={...o.message},delete o.message.providerReplay),r!==void 0&&o.message.role===`toolResult`&&(o.message={...o.message,content:[{type:`text`,text:r}]}),o}const xa=[`type`,`id`,`parentId`,`targetId`,`appendParentId`,`appendMode`],Sa=[...xa,`timestamp`,`version`,`cwd`,`firstKeptEntryId`,`reason`,`tokensBefore`,`thinkingLevel`,`provider`,`modelId`,`fromId`,`customType`,`display`,`excludeFromContext`,`label`,`name`],Ca=[`role`,`provider`,`model`,`timestamp`,`excludeFromContext`,`openclawModelPlacement`,`toolCallId`,`toolUseId`,`tool_call_id`,`tool_use_id`,`callId`,`call_id`,`toolName`,`isError`,`stopReason`,`customType`,`display`];function pickNavigation(e,t){return Object.fromEntries(t.filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]]))}function projectSessionModelContextNavigation(e){let t={...pickNavigation({...e},Sa),type:e.type,id:e.id,parentId:e.parentId,timestamp:e.timestamp};if(e.type===`message`){let n=e.message,r={...n},i=`content`in n&&Array.isArray(n.content)?n.content.flatMap(e=>k(e)&&[`toolCall`,`toolUse`,`functionCall`].includes(e.type)?[pickNavigation(e,[`type`,`id`,`name`])]:[]):[],a=k(r.details)?r.details:{},o=r.customType===`openclaw.system-update`&&(a.kind===`prompt-update`||a.kind===`runtime-context`)?a.kind:void 0;t.message={...pickNavigation(r,Ca),content:i,command:``,output:``,providerReplay:{type:k(r.providerReplay)?r.providerReplay.type:null},details:{[Q]:isSyntheticMissingToolResult({isError:r.isError,details:r.details,content:r.content}),...o?{kind:o}:{}}}}else e.type===`compaction`||e.type===`branch_summary`?t.summary=``:e.type===`custom_message`?(t.content=[],e.customType===`openclaw.system-update`&&k(e.details)&&(e.details.kind===`prompt-update`||e.details.kind===`runtime-context`)&&(t.details={kind:e.details.kind})):e.type===`custom`&&e.customType===`openclaw.system-prompt`?t.data={restart:k(e.data)&&e.data.restart===!0}:e.type===`custom`&&e.customType===`openclaw.background-result-placement`&&(t.data=k(e.data)?pickNavigation(e.data,[`afterEntryId`,`resultEntryIds`]):e.data);return t}const wa=/* @__PURE__ */ new WeakSet;function projectModelContextJson(e,t,n=!1,r){let i=JSON.parse(e);return JSON.stringify(t?projectSessionModelContextNavigation(i):projectSessionModelContextEntry(i,{entry:i,omitCheckpoint:n,toolResultOmission:r}))}function projectDeepModelContextSql(e,t,n,r=R.lit(0),i=R.lit(null)){let a=`openclaw_deep_model_context`;return wa.has(e)||(e.function(a,{deterministic:!0,directOnly:!0},(e,t,n,r)=>{if(typeof e!=`string`)throw TypeError(`Deep transcript projection requires canonical JSON text`);return projectModelContextJson(e,t===1,n===1,typeof r==`string`?r:void 0)}),wa.add(e)),L(e).fn(a,[t,R.lit(+!!n),r,i])}function projectModelContextEventSql(e,t,n,r,i=V(e,t,R.lit(`$.message.role`)),a=U(e,t)){if(I(e)){let e=postgresModelEventSql(t,i),a=r?R`CASE WHEN ${r} IS NOT NULL AND ${i} = 'toolResult'
THEN jsonb_set(${e}, '{message,content}', jsonb_build_array(jsonb_build_object('type', 'text', 'text', ${r}::text)))
ELSE ${e} END`:e;return R`(CASE WHEN ${n} = 1
THEN ${a} #- '{message,providerReplay}' ELSE ${a} END)::text`}let o=ya.map(e=>`$.message.__openclaw.${e}`),s=Bt(e,t,o.map(e=>R.val(e))),c=R`CASE WHEN ${i} = 'toolResult'
THEN ${Bt(e,s,[R.lit(`$.message.details`)])} ELSE ${s} END`,l=r?R`CASE WHEN ${r} IS NOT NULL AND ${i} = 'toolResult'
THEN ${Vt(e,c,R.lit(`$.message.content`),Ut(e,[Wt(e,{type:R.lit(`text`),text:r})]),!0)} ELSE ${c} END`:c;return R`CASE WHEN NOT ${a} THEN ${projectDeepModelContextSql(e,t,!1,n,r)}
WHEN ${n} = 1
THEN ${Bt(e,l,[R.lit(`$.message.providerReplay`)])} ELSE ${l} END`}function contentPropertySql(e,t){return R`CASE WHEN typeof(key) = 'integer' AND key < 8
THEN json_extract(${e}, fullkey || ${`.${t}`})
ELSE json_extract(value, ${`$.${t}`}) END`}function jsonMemberValue(e){let t=R.ref(`${e}.type`),n=R.ref(`${e}.value`);return R`CASE ${t}
WHEN 'object' THEN json(${n})
WHEN 'array' THEN json(${n})
WHEN 'true' THEN json('true') WHEN 'false' THEN json('false')
ELSE ${n} END`}function projectTranscriptPayloadNavigationSql(e,t){if(I(e))return R`(
SELECT coalesce(json_object_agg(root_member.key, CASE
WHEN root_member.key = 'message' AND json_typeof(root_member.value) = 'object' THEN (
SELECT coalesce(json_object_agg(message_member.key, CASE
WHEN message_member.key = '__openclaw' AND json_typeof(message_member.value) = 'object' THEN (
SELECT coalesce(json_object_agg(internal.key, internal.value), '{}'::json)
FROM json_each(message_member.value) AS internal
WHERE internal.key IN ('runId', 'steerTargetRunId', 'contextFreeCommand'))
ELSE message_member.value END), '{}'::json)
FROM json_each(root_member.value) AS message_member
WHERE message_member.key IN ('role', 'idempotencyKey', 'provenance', 'excludeFromContext', '__openclaw'))
ELSE root_member.value END), '{}'::json)::text
FROM json_each(${t}::json) AS root_member
WHERE root_member.key IN (${R.join([...Sa,`message`])}))`;let n=R.ref(`message_member.value`),r=H(e,n,[`runId`,`steerTargetRunId`,`contextFreeCommand`]),i=R`(SELECT json_group_object(message_member.key,
CASE WHEN message_member.key = '__openclaw' AND message_member.type = 'object'
THEN json(${r}) ELSE ${jsonMemberValue(`message_member`)} END)
FROM json_each(root_member.value) AS message_member
WHERE message_member.key IN ('role', 'idempotencyKey', 'provenance', 'excludeFromContext', '__openclaw'))`;return R`(SELECT json_group_object(root_member.key,
CASE WHEN root_member.key = 'message' AND root_member.type = 'object'
THEN json(${i}) ELSE ${jsonMemberValue(`root_member`)} END)
FROM json_each(${t}) AS root_member
WHERE root_member.key IN (${R.join([...Sa,`message`])}))`}function projectResetBoundaryNavigationSql(e,t){let n=H(e,t,[...xa,`timestamp`,`firstKeptEntryId`,`customType`,`display`]);return R`CASE WHEN ${zt(e,t)} THEN
CASE WHEN ${Ht(e,t)} = 'object' THEN
${Vt(e,n,R.lit(`$.message`),Wt(e,{role:V(e,t,R.lit(`$.message.role`))}),!0)}
ELSE ${t} END
ELSE ${t} END`}function systemUpdateKindSql(e,t){return R`CASE
WHEN ${V(e,t,R.lit(`$.customType`))} = 'openclaw.system-update'
AND ${V(e,t,R.lit(`$.details.kind`))} IN ('prompt-update', 'runtime-context')
THEN ${V(e,t,R.lit(`$.details.kind`))} ELSE NULL END`}function projectModelContextNavigationSql(e,t,n,r=U(e,t)){if(I(e)){let r=R.ref(`nav_parts.event`),i=R.ref(`nav_parts.message`),a=R.ref(`nav_parts.content`),o=n??R`${r} ->> 'type'`,s=zt(e,t);return R`CASE WHEN ${s} THEN (
WITH nav_input AS MATERIALIZED (SELECT (CASE WHEN ${s} THEN ${t} END)::jsonb AS event),
nav_parts AS MATERIALIZED (SELECT event, event -> 'message' AS message,
event #> '{message,content}' AS content FROM nav_input)
SELECT ${postgresModelNavigationSql(r,i,a,o)}::text FROM nav_parts)
ELSE ${t} END`}let i=n??V(e,t,R.lit(`$.type`)),a=H(e,t,Sa),o=T()?R`jsonb_extract(${t}, '$.message')`:R`json_extract(${t}, '$.message')`,s=H(e,o,Ca),c=systemUpdateKindSql(e,o),l=systemUpdateKindSql(e,t),u=R`json_set(${a}, '$.content', json('[]'))`,d=R`(SELECT json_group_array(json_object(
'type', ${contentPropertySql(t,`type`)}, 'id', ${contentPropertySql(t,`id`)},
'name', ${contentPropertySql(t,`name`)}))
FROM json_each(${t}, '$.message.content') WHERE type = 'object'
AND ${contentPropertySql(t,`type`)} IN ('toolCall', 'toolUse', 'functionCall'))`,f=R`COALESCE(json_extract(${t}, ${`$.message.details.${Q}`}), 0) = 1 OR EXISTS (
SELECT 1 FROM json_each(${t}, '$.message.content') WHERE type = 'object'
AND ${contentPropertySql(t,`type`)} = 'text' AND ${contentPropertySql(t,`text`)} = ${$i})`,p=R`CASE ${i}
WHEN 'message' THEN json_set(${a}, '$.message', json_set(${s},
'$.content', json(${d}), '$.command', '', '$.output', '',
'$.providerReplay', json_object('type', json_extract(${t}, '$.message.providerReplay.type')),
'$.details', json_patch(json_object(${Q}, json(CASE WHEN (${f}) THEN 'true' ELSE 'false' END)),
CASE WHEN ${c} IS NULL THEN json('{}') ELSE json_object('kind', ${c}) END)))
WHEN 'custom_message' THEN CASE WHEN ${l} IS NULL THEN ${u}
ELSE json_set(${u}, '$.details', json_object('kind', ${l})) END
WHEN 'custom' THEN CASE WHEN ${V(e,t,R.lit(`$.customType`))} = 'openclaw.system-prompt'
THEN json_set(${a}, '$.data', json_object('restart', json(CASE
WHEN json_type(${t}, '$.data.restart') = 'true' THEN 'true' ELSE 'false' END)))
WHEN ${V(e,t,R.lit(`$.customType`))} = ${ea}
THEN ${Vt(e,a,R.lit(`$.data`),L(e).fn(`json`,[H(e,V(e,t,R.lit(`$.data`)),[`afterEntryId`,`resultEntryIds`])]),!0)}
ELSE ${a} END
WHEN 'compaction' THEN json_set(${a}, '$.summary', '')
WHEN 'branch_summary' THEN json_set(${a}, '$.summary', '')
ELSE ${a} END`;return R`CASE WHEN ${r} THEN ${p}
ELSE ${projectDeepModelContextSql(e,t,!0)} END`}function postgresModelEventSql(e,t){let n=e;for(let e of ya)n=R`(${n}::jsonb #- ${R.lit(`{message,__openclaw,${e}}`)}::text[])`;return R`CASE WHEN ${t} = 'toolResult'
THEN ${n} #- '{message,details}' ELSE ${n} END`}function postgresNavigationObjectSql(e,t){return R`(
SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)
FROM jsonb_each(CASE WHEN jsonb_typeof(${e}) = 'object' THEN ${e} ELSE '{}'::jsonb END)
WHERE key IN (${R.join(t.map(e=>R.lit(e)))})
)`}function postgresModelNavigationSql(e,t,n,r){let i=postgresNavigationObjectSql(e,Sa),a=postgresNavigationObjectSql(t,Ca),o=R`jsonb_array_elements(
CASE WHEN jsonb_typeof(${n}) = 'array' THEN ${n} ELSE '[]'::jsonb END)`,s=R`(
SELECT coalesce(jsonb_agg(jsonb_build_object('type', value ->> 'type', 'id', value ->> 'id', 'name', value ->> 'name')), '[]'::jsonb)
FROM ${o} WHERE jsonb_typeof(value) = 'object' AND value ->> 'type' IN ('toolCall', 'toolUse', 'functionCall'))`,c=R`coalesce((${t} #> ${R.lit(`{details,${Q}}`)}::text[])::text, 'false') IN ('true', '1') OR EXISTS (
SELECT 1 FROM ${o} WHERE value ->> 'type' = 'text' AND value ->> 'text' = ${$i})`,l=R`CASE WHEN ${t} ->> 'customType' = 'openclaw.system-update'
AND ${t} #>> '{details,kind}' IN ('prompt-update', 'runtime-context') THEN ${t} #>> '{details,kind}' END`,u=R`CASE WHEN ${e} ->> 'customType' = 'openclaw.system-update'
AND ${e} #>> '{details,kind}' IN ('prompt-update', 'runtime-context') THEN ${e} #>> '{details,kind}' END`;return R`CASE ${r}
WHEN 'message' THEN ${i} || jsonb_build_object('message', ${a} || jsonb_build_object(
'content', ${s}, 'command', '', 'output', '',
'providerReplay', jsonb_build_object('type', ${t} #>> '{providerReplay,type}'),
'details', jsonb_build_object(${R.lit(Q)}, (${c})) ||
CASE WHEN ${l} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('kind', ${l}) END))
WHEN 'custom_message' THEN ${i} || jsonb_build_object('content', '[]'::jsonb) ||
CASE WHEN ${u} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('details', jsonb_build_object('kind', ${u})) END
WHEN 'custom' THEN CASE WHEN ${e} ->> 'customType' = 'openclaw.system-prompt'
THEN ${i} || jsonb_build_object('data', jsonb_build_object('restart', coalesce((${e} #> '{data,restart}')::text, 'false') = 'true'))
WHEN ${e} ->> 'customType' = ${ea}
THEN ${i} || jsonb_build_object('data', ${postgresNavigationObjectSql(R`${e} -> 'data'`,[`afterEntryId`,`resultEntryIds`])})
ELSE ${i} END
WHEN 'compaction' THEN ${i} || jsonb_build_object('summary', '')
WHEN 'branch_summary' THEN ${i} || jsonb_build_object('summary', '')
ELSE ${i} END`}const Ta={id:M().min(1),parentId:F([M(),Pe()]).optional(),timestamp:M().optional(),appendMode:Ae().optional()};P({kind:N(`canonical`),hasParentId:Ne(),entry:je(`type`,[P({...Ta,type:N(`message`),assistantResponseId:M().optional(),assistantRunId:M().optional()}),P({...Ta,type:N(`custom_message`),customType:M().min(1)}),P({...Ta,type:N(`label`),targetId:M().min(1),label:M().optional()}),P({...Ta,type:Me([`thinking_level_change`,`model_change`,`compaction`,`reset`,`branch_summary`,`custom`,`session_info`])})])}).refine(({entry:e,hasParentId:t})=>t===(e.parentId!==void 0));function projectSessionTranscriptReportFacts(e){let{entry:t,recognized:n}=classifySessionFileEntry(e,3);if(!n||t.type===`session`){let t=parseOpaqueLeafEntry(e);if(t)return{kind:`leaf`,entry:t};let n=parseParentLinkedOpaqueEntry(e);return n?{kind:`link`,...n}:{kind:`ignored`}}let r={id:t.id,parentId:t.parentId,timestamp:t.timestamp,appendMode:t.appendMode},i=Object.hasOwn(t,`parentId`);return t.type===`label`?{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type,targetId:t.targetId,label:t.label}}:t.type===`custom_message`?{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type,customType:t.customType}}:t.type===`message`?{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type,...t.message.role===`assistant`?{assistantRunId:readSessionTranscriptRunId(t.message),...typeof t.message.responseId==`string`?{assistantResponseId:t.message.responseId}:{}}:{}}}:{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type}}}const Ea={version:1,report:null,navigation:{},reset:{},model:{},modelBytes:0,modelWithoutCheckpointBytes:0,withoutCustomDataBytes:0};function minimumNavigationBytes(e){return Buffer.byteLength(JSON.stringify({...Ea,navigation:e,reset:e,model:e}))-4}const Da=[minimumNavigationBytes({}),minimumNavigationBytes({type:0,id:0}),minimumNavigationBytes({type:0,id:0,parentId:0})];function navigationProjection(e,t,n,r){if(I(e))return R`CASE
WHEN ${U(e,r)} AND ${U(e,n)} THEN CASE
WHEN json_typeof(${r}::json) != 'object'
OR coalesce(json_typeof(${r}::json -> 'message'), 'null') NOT IN ('object', 'null') THEN NULL
ELSE json_build_object('version', 1,
'report', ${n}::json,
'navigation', ${projectTranscriptPayloadNavigationSql(e,t)}::json,
'reset', ${projectResetBoundaryNavigationSql(e,r)}::json,
'model', ${projectModelContextNavigationSql(e,t)}::json,
'modelBytes', octet_length(${projectModelContextEventSql(e,t,R.lit(0))}),
'modelWithoutCheckpointBytes', octet_length(${projectModelContextEventSql(e,t,R.lit(1))}),
'withoutCustomDataBytes', octet_length(${Bt(e,t,[R.lit(`$.data`)])}))::text
END ELSE NULL END`;let i=Wt(e,{...Object.fromEntries(Object.entries(Ea).map(([e,t])=>[e,typeof t==`number`?R.lit(t):R`json(${JSON.stringify(t)})`])),report:R`json(${n})`,navigation:R`json(${projectTranscriptPayloadNavigationSql(e,t)})`,reset:R`json(${projectResetBoundaryNavigationSql(e,r)})`,model:R`json(${projectModelContextNavigationSql(e,t,void 0,R.lit(1))})`,modelBytes:R`octet_length(${projectModelContextEventSql(e,t,R.lit(0),void 0,void 0,R.lit(1))})`,modelWithoutCheckpointBytes:R`octet_length(${projectModelContextEventSql(e,t,R.lit(1),void 0,void 0,R.lit(1))})`,withoutCustomDataBytes:R`octet_length(json_remove(${t}, '$.data'))`});return R`CASE WHEN json_valid(${r}) AND json_valid(${n}) THEN CASE
WHEN json_type(${t}) != 'object'
OR coalesce(json_type(${t}, '$.message'), 'null') NOT IN ('object', 'null') THEN NULL
ELSE ${i} END ELSE NULL END`}const Oa=et(e=>Xe(e,t=>{let n=L(e),r=n.selectFrom(n.selectNoFrom([t(e=>e.eventJson).as(`event_json`),t(e=>e.reportJson).as(`report_json`)]).as(`input`)).select([`input.event_json`,`input.report_json`]).select(t=>!I(e)&&T()?R`CASE WHEN json_valid(${t.ref(`input.event_json`)})
THEN jsonb(${t.ref(`input.event_json`)}) ELSE ${t.ref(`input.event_json`)} END`.as(`event_projection`):t.ref(`input.event_json`).as(`event_projection`));return n.with(e=>e(`source`).notMaterialized(),()=>r).with(e=>e(`metadata`).materialized(),t=>t.selectFrom(`source`).select(t=>navigationProjection(e,t.ref(`source.event_projection`),t.ref(`source.report_json`),t.ref(`source.event_json`)).as(`navigation_json`))).selectFrom(`metadata`).select(t=>R`CASE WHEN ${U(e,t.ref(`metadata.navigation_json`))}
AND octet_length(metadata.navigation_json) <= ${16384}
THEN metadata.navigation_json ELSE NULL END`.as(`navigation_json`))}));function readTranscriptPayloadNavigation(e,t,n){return Oa(e)({eventJson:t,reportJson:n})?.navigation_json??null}new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});const ka=/* @__PURE__ */ new Set([`session`,`message`,`reset`,`compaction`,`custom_message`,`custom`]),Aa=/* @__PURE__ */ new Set([`openclaw.runtime-context`,`openclaw.cache-ttl`]),ja=/* @__PURE__ */ new Set([`user`,`assistant`,`toolResult`,`system`]);function discriminator(e,t){let n=readJsonPredicateScalar(e);return typeof n==`string`&&t.has(n)?n:null}function deriveTranscriptPredicateFields(e){let t=scanJsonObjectFields(e,[`type`,`customType`,`display`,`message`]);if(!t.valid||t.maximumDepth>1e3)return{navigation_type:null,navigation_custom_type:null,navigation_display:0,message_role:null,navigation_last_type:null,navigation_last_custom_type:null,navigation_valid:0};let n=t.first.get(`message`),r=n?.kind===`object`?scanJsonObjectFields(n.text,[`role`]).first.get(`role`):void 0;return{navigation_type:discriminator(t.first.get(`type`),ka),navigation_custom_type:discriminator(t.first.get(`customType`),Aa),navigation_display:+(readJsonPredicateScalar(t.first.get(`display`))===!0),message_role:discriminator(r,ja),navigation_last_type:discriminator(t.last.get(`type`),ka),navigation_last_custom_type:discriminator(t.last.get(`customType`),Aa),navigation_valid:1}}function readTranscriptStorageEncoding(e){if(I(e))return`UTF-8`;let t=st(e);if(!t)throw Error(`Transcript payload preparation requires admitted SQLite schema facts`);return t.textEncoding}const identityPayload=(e,t)=>({...deriveTranscriptPredicateFields(e),event_json:e,event_zstd:null,event_utf8_bytes:t,navigation_json:null});function prepareTranscriptPayload(e,t,n,r=readTranscriptStorageEncoding(e)){let i=Buffer.byteLength(t,`utf8`),a=r===`UTF-8`,o=identityPayload(t,a?i:null);if(I(e)||!a||i>4194304||t.includes(`\\u`)||t.includes(`\0`))return o;let s=qi();if(i<1024||!t.isWellFormed())return o;let c=Buffer.from(t,`utf8`),l=s.compress(c,1,!0),u=i-Math.max(64,Math.ceil(i/10));if(l.byteLength>u)return o;let d;try{let e=n===void 0?JSON.parse(t):n;if(findSessionTranscriptHeader([e]))return o;let r=projectSessionTranscriptReportFacts(e);d=JSON.stringify(r);let i=Da[r.kind===`canonical`?r.entry.parentId===void 0?1:2:0];if(l.byteLength+Buffer.byteLength(d,`utf8`)+i>u)return o}catch{return o}let f=readTranscriptPayloadNavigation(e,t,d);return f===null||l.byteLength+Buffer.byteLength(f,`utf8`)>u?o:{...o,event_json:null,event_zstd:l,navigation_json:f}}const Ma=`transcript_events_payload_migration`,Na=/* @__PURE__ */ new Set([`transcript_event_identities`,`session_transcript_active_events`]);function assertTranscriptRebuildInputs(e){Xt(e,`transcript payload migration`,rt(oi(ue),`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(Ma))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(!Na.has(t.name)&&e.prepare(`PRAGMA foreign_key_list(${nt(t.name)})`).all().some(e=>e.table===`transcript_events`))throw Error(`Transcript payload migration cannot rebuild an unknown foreign-key target`)}}function migrateTranscriptPayloadStorageInTransaction(e,t){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 n=ut(e)===`UTF-8`,r=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),i=qi();e.exec(rt(t,`transcript_events`).replace(`IF NOT EXISTS transcript_events`,Ma));let a=e.prepare(`
INSERT INTO ${Ma}
(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 = ?`),o=e.prepare(`
INSERT INTO ${Ma}
(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 = ?`);a.setReadBigInts(!0),o.setReadBigInts(!0);let s=e.prepare(`SELECT CAST(event_json AS BLOB) AS bytes FROM transcript_events WHERE rowid = ?`),c=e.prepare(`SELECT rowid AS storage_rowid, octet_length(event_json) AS bytes FROM transcript_events ORDER BY rowid`);c.setReadBigInts(!0);let l=performance.now();for(let t of c.iterate()){if(performance.now()-l>=1e3&&(K(),l=performance.now()),typeof t.storage_rowid!=`bigint`||typeof t.bytes!=`bigint`)throw Error(`Invalid transcript storage identity during migration`);let c=null,u=!1;if(n&&t.bytes<=BigInt(4194304)){let n=s.get(t.storage_rowid)?.bytes;if(!(n instanceof Uint8Array))throw Error(`Transcript payload disappeared during migration`);let a;try{a=r.decode(n)}catch{}if(a!==void 0){let r=prepareTranscriptPayload(e,a,void 0,`UTF-8`);if(c=r.navigation_json,r.event_zstd!==null){if(r.event_utf8_bytes===null||!i.decompress(r.event_zstd,r.event_utf8_bytes).equals(n))throw Error(`Transcript compression did not preserve canonical bytes`);let e=o.run(r.event_zstd,r.event_utf8_bytes,c,t.storage_rowid);if(Number(e.changes)!==1)throw Error(`Transcript payload disappeared before migration publication`);u=!0}}}if(!u&&Number(a.run(+!!n,c,t.storage_rowid).changes)!==1)throw Error(`Transcript identity payload disappeared before migration publication`)}K(),e.exec(`DROP TABLE transcript_events;
ALTER TABLE ${Ma} RENAME TO transcript_events;`)}function migrateAgentStorageInTransaction(e,t,n,r){if(K(),gi(e,{renewAuthority:K,onWarning:e=>r.push(e)}),K(),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.`);K(),migrateTranscriptPayloadStorageInTransaction(e,t),K(),migrateSessionCostUsageRollupStorage(e,K),K(),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;
`)}const Pa=Ke(`state/agent-db`);function*agentDatabaseIntegrityBeforeMutationSteps(e,t,n,{runtimeAdmission:r=!1,diagnostics:i,verification:a,reuseRuntimeIntegrity:o=!1,admittedSchema:s=!1,integrityCheck:c,integrityTables:l}={}){let u=r&&o;if(u&&s)return i&&(i.integrityGateOutcome=`cached`),!1;Ve(e,j);let d=st(e)?.userVersion??Mt(e),f=d===0&&Vr(e),p=d===0&&f||d>0&&d<42;p&&Pa.info(`agent database schema migration pending; verifying integrity first`,{fromVersion:d,path:n,toVersion:42});let m=d===42&&Ln(e),h=Ct({kind:`agent`,foundVersion:d,supportedVersion:42},c),g=performance.now();if(d===42&&!m){let o=r&&!a&&!u&&c!==`full`?jn(e,n,t,i):void 0,s=u||a!==void 0&&!p&&!m,validateSchema=r=>xn(e,{agentId:t,pathname:n},r),d=o??(yield*xt(e,n,`-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;
-- session_entry_snapshots owns keyed cold values. Promoted node columns are query
-- indexes; session_windows and their children own transcript generations.
-- Legacy ACP provenance is private import evidence carried with its logical session.
CREATE TABLE IF NOT EXISTS schema_meta (
meta_key TEXT NOT NULL PRIMARY KEY,
role TEXT NOT NULL,
schema_version INTEGER NOT NULL,
agent_id TEXT,
app_version TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
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,
session_started_at INTEGER,
has_optional_references INTEGER NOT NULL DEFAULT 0,
snapshot_revision INTEGER NOT NULL DEFAULT 0,
legacy_acp_migration_json TEXT,
entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),
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,
owner_actor_type TEXT,
owner_actor_id TEXT,
owner_assigned_by_type TEXT,
owner_assigned_by_id TEXT,
owner_assigned_at INTEGER,
project_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;
CREATE TABLE IF NOT EXISTS session_entry_snapshots (
session_key TEXT NOT NULL,
field TEXT NOT NULL CHECK (field IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')),
value_json TEXT NOT NULL,
PRIMARY KEY (session_key, field),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;
CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_insert
AFTER INSERT ON session_entry_snapshots
BEGIN
UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
WHERE session_key = NEW.session_key;
END;
CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_update
AFTER UPDATE OF session_key, field, value_json ON session_entry_snapshots
WHEN NEW.session_key IS NOT OLD.session_key
OR NEW.field IS NOT OLD.field OR NEW.value_json IS NOT OLD.value_json
BEGIN
UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
WHERE session_key IN (OLD.session_key, NEW.session_key);
END;
CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_delete
AFTER DELETE ON session_entry_snapshots
BEGIN
UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
WHERE session_key = OLD.session_key;
END;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at
ON session_nodes(updated_at DESC, session_key);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label
ON session_nodes(label, session_key)
WHERE label IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_parent_session_key
ON session_nodes(parent_session_key, session_key);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_spawned_by
ON session_nodes(spawned_by, session_key);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_status
ON session_nodes(status, session_key)
WHERE status IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_archived_at
ON session_nodes(archived_at, session_key)
WHERE archived_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_active
ON session_nodes(session_key)
WHERE archived_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_current_session_id
ON session_nodes(current_session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_valid_pending
ON session_nodes(session_key)
WHERE entry_valid = 0;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_not_valid
ON session_nodes(session_key)
WHERE entry_valid != 1;
CREATE TABLE IF NOT EXISTS session_participants (
session_key TEXT NOT NULL,
identity_namespace TEXT NOT NULL,
actor_id TEXT NOT NULL,
contribution_count INTEGER NOT NULL,
first_prompted_at INTEGER,
last_prompted_at INTEGER,
PRIMARY KEY (session_key, identity_namespace, actor_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS session_key_contract (
id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
main_key TEXT NOT NULL,
canonical_ready TEXT,
updated_at INTEGER NOT NULL
) STRICT;
INSERT OR IGNORE INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0);
CREATE TABLE IF NOT EXISTS session_windows (
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,
row_transcript_json TEXT,
row_transcript_updated_at INTEGER,
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;
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_updated_at
ON session_windows(updated_at DESC, session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_session_key
ON session_windows(session_key, updated_at DESC, session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_created_at
ON session_windows(created_at DESC, session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_conversation
ON session_windows(primary_conversation_id)
WHERE primary_conversation_id IS NOT NULL;
-- Offline imports and repairs queue explicit work; admission also settles keys
-- removed during repair, so the queue deliberately has no node foreign key.
CREATE TABLE IF NOT EXISTS session_canonical_validation_pending (
session_key TEXT NOT NULL PRIMARY KEY
) STRICT;
CREATE TABLE IF NOT EXISTS conversations (
conversation_id TEXT NOT NULL PRIMARY KEY,
channel TEXT NOT NULL,
account_id TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('direct', 'group', 'channel')),
peer_id TEXT NOT NULL,
delivery_target TEXT NOT NULL,
parent_conversation_id TEXT,
thread_id TEXT,
native_channel_id TEXT,
native_direct_user_id TEXT,
label TEXT,
metadata_json TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_conversations_lookup
ON conversations(channel, account_id, kind, peer_id, thread_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_conversations_identity
ON conversations(
channel,
account_id,
kind,
peer_id,
IFNULL(parent_conversation_id, ''),
IFNULL(thread_id, '')
);
CREATE INDEX IF NOT EXISTS idx_agent_conversations_updated
ON conversations(updated_at DESC, conversation_id);
CREATE TABLE IF NOT EXISTS conversation_deliveries (
operation_id TEXT NOT NULL PRIMARY KEY,
operation_kind TEXT NOT NULL CHECK (operation_kind IN ('send', 'turn')),
conversation_id TEXT NOT NULL,
source_session_key TEXT,
message_hash TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied')),
prepared_message_id TEXT,
platform_message_id TEXT,
queue_id TEXT,
rejection_error TEXT,
reply_message_id TEXT,
reply_to_id TEXT,
reply_thread_id TEXT,
reply_text TEXT,
reply_timestamp INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
CHECK (
(status = 'rejected' AND rejection_error IS NOT NULL) OR
(status != 'rejected' AND rejection_error IS NULL)
),
FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_reply
ON conversation_deliveries(conversation_id, platform_message_id, prepared_message_id)
WHERE status IN ('queued', 'sent', 'replied');
CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_updated
ON conversation_deliveries(updated_at DESC, operation_id);
CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_source_session
ON conversation_deliveries(source_session_key, operation_id);
CREATE TABLE IF NOT EXISTS 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 "session_windows"(session_id) ON DELETE CASCADE,
FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;
-- Older same-version writers preserve the envelope while updating the association.
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;
CREATE INDEX IF NOT EXISTS idx_agent_session_conversations_conversation
ON session_conversations(conversation_id, last_seen_at DESC, session_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_session_conversations_primary
ON session_conversations(session_id)
WHERE role = 'primary';
CREATE TABLE IF NOT EXISTS session_members (
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;
CREATE INDEX IF NOT EXISTS idx_agent_session_members_identity
ON session_members(identity_id, session_key);
CREATE TABLE IF NOT EXISTS session_suggestions (
id TEXT PRIMARY KEY,
session_key TEXT NOT NULL,
author_id TEXT NOT NULL,
author_label TEXT,
text TEXT NOT NULL,
created_at INTEGER NOT NULL,
state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'dismissed')),
dispatch_token TEXT,
dispatch_started_at INTEGER,
dispatch_resolution TEXT CHECK (dispatch_resolution IN ('send', 'queue', 'edit', 'dismiss')),
CHECK (
(dispatch_token IS NULL AND dispatch_started_at IS NULL AND dispatch_resolution IS NULL)
OR (dispatch_token IS NOT NULL AND dispatch_started_at IS NOT NULL AND dispatch_resolution IS NOT NULL)
),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_session_state_created
ON session_suggestions(session_key, state, created_at, id);
CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_author_created
ON session_suggestions(author_id, created_at, id);
CREATE TABLE IF NOT EXISTS session_reactions (
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
message_id TEXT NOT NULL,
emoji TEXT NOT NULL,
identity_id TEXT NOT NULL,
identity_label TEXT,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_key, session_id, message_id, emoji, identity_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS board_tabs (
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;
CREATE TABLE IF NOT EXISTS board_widgets (
session_key TEXT NOT NULL,
name TEXT NOT NULL,
tab_id TEXT NOT NULL,
title TEXT,
content_kind TEXT NOT NULL CHECK (content_kind IN ('html', 'mcp-app', 'plugin')),
html BLOB,
descriptor_json TEXT,
sha256 TEXT NOT NULL,
view_generation TEXT,
revision INTEGER NOT NULL CHECK (revision >= 1),
size_w INTEGER NOT NULL CHECK (size_w BETWEEN 1 AND 12),
size_h INTEGER NOT NULL CHECK (size_h BETWEEN 1 AND 20),
position INTEGER NOT NULL CHECK (position >= 0),
manifest TEXT NOT NULL DEFAULT '{}',
grant_state TEXT NOT NULL DEFAULT 'none' CHECK (grant_state IN ('none', 'pending', 'granted', 'rejected')),
granted_sha TEXT,
created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_key, name),
FOREIGN KEY (session_key, tab_id) REFERENCES board_tabs(session_key, tab_id) ON DELETE CASCADE,
CHECK (
(content_kind = 'html' AND html IS NOT NULL AND descriptor_json IS NULL AND view_generation IS NOT NULL) OR
(content_kind = 'mcp-app' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL) OR
(content_kind = 'plugin' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL)
)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position
ON board_widgets(session_key, tab_id, position);
CREATE TABLE IF NOT EXISTS session_progress_cards (
session_key TEXT NOT NULL PRIMARY KEY,
markdown TEXT,
steps_json TEXT,
revision INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS heartbeat_outcomes (
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;
CREATE TABLE IF NOT EXISTS message_tool_run_outcomes (
id INTEGER PRIMARY KEY,
run_id TEXT NOT NULL,
session_key TEXT NOT NULL,
agent_id TEXT NOT NULL,
provider TEXT NOT NULL,
model TEXT NOT NULL,
outcome TEXT NOT NULL CHECK (outcome IN ('tool_delivered', 'mute')),
run_status TEXT NOT NULL CHECK (run_status IN ('completed', 'errored', 'aborted')),
occurred_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_message_tool_run_outcomes_occurred
ON message_tool_run_outcomes(occurred_at DESC, id DESC);
-- Receipts outlive Goal clear and session reset so a delayed retry cannot recreate a Goal.
-- They intentionally have no session FK; bounded retention belongs to the operation owner.
CREATE TABLE IF NOT EXISTS session_creation_operations (
operation_digest TEXT PRIMARY KEY,
request_fingerprint TEXT NOT NULL,
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
lifecycle_revision TEXT,
role TEXT,
scopes_json TEXT NOT NULL,
expires_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_creation_operations_expiry
ON session_creation_operations(expires_at);
-- END SESSION CREATION OPERATIONS
CREATE TABLE IF NOT EXISTS session_goal_operations (
session_key TEXT NOT NULL,
operation_id TEXT NOT NULL,
session_id TEXT NOT NULL,
request_fingerprint TEXT NOT NULL,
result_json TEXT NOT NULL,
expires_at INTEGER NOT NULL,
PRIMARY KEY (session_key, operation_id)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_goal_operations_expiry
ON session_goal_operations(expires_at);
CREATE TABLE IF NOT EXISTS transcript_events (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_json TEXT,
created_at INTEGER NOT NULL,
event_zstd BLOB,
event_utf8_bytes INTEGER CHECK (event_utf8_bytes IS NULL OR event_utf8_bytes >= 0),
navigation_json TEXT,
navigation_type TEXT,
navigation_custom_type TEXT,
navigation_display INTEGER NOT NULL DEFAULT 0,
message_role TEXT,
navigation_last_type TEXT,
navigation_last_custom_type TEXT,
navigation_valid INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
CHECK (
(event_json IS NOT NULL AND event_zstd IS NULL)
OR (
event_json IS NULL AND event_zstd IS NOT NULL
AND event_utf8_bytes IS NOT NULL
AND event_utf8_bytes BETWEEN 1 AND 4194304
AND length(event_zstd) BETWEEN 1 AND 4194304
AND navigation_json IS NOT NULL
)
OR (
event_json IS NULL AND event_zstd IS NULL
AND event_utf8_bytes IS NOT NULL
AND event_utf8_bytes BETWEEN 1 AND 4194304
AND navigation_json IS NOT NULL
)
),
CHECK (
navigation_json IS NULL OR CASE WHEN json_valid(navigation_json) THEN coalesce(
octet_length(navigation_json) <= 16384
AND json_type(navigation_json, '$.version') = 'integer'
AND json_extract(navigation_json, '$.version') = 1
AND json_type(navigation_json, '$.report') = 'object'
AND json_extract(navigation_json, '$.report.kind') IN ('canonical', 'leaf', 'link', 'ignored')
AND json_type(navigation_json, '$.navigation') = 'object'
AND json_type(navigation_json, '$.reset') = 'object'
AND json_type(navigation_json, '$.model') = 'object'
AND json_type(navigation_json, '$.modelBytes') = 'integer'
AND json_extract(navigation_json, '$.modelBytes') BETWEEN 0 AND 4194304
AND json_type(navigation_json, '$.modelWithoutCheckpointBytes') = 'integer'
AND json_extract(navigation_json, '$.modelWithoutCheckpointBytes') BETWEEN 0 AND 4194304
AND json_type(navigation_json, '$.withoutCustomDataBytes') = 'integer'
AND json_extract(navigation_json, '$.withoutCustomDataBytes') BETWEEN 0 AND 4194304,
0) ELSE 0 END
)
) STRICT;
-- Canonical cold-tier owner for reclaimed transcript generations. The derived
-- .deleted/.reset file may be recreated from this row after a crash.
CREATE TABLE IF NOT EXISTS session_transcript_archives (
session_id TEXT NOT NULL,
generation TEXT NOT NULL,
session_key TEXT NOT NULL,
reason TEXT NOT NULL CHECK (reason IN ('deleted', 'reset')),
encoding TEXT NOT NULL CHECK (encoding IN ('identity', 'zstd')),
archive_blob BLOB NOT NULL,
archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
archive_name TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
published_at INTEGER,
publish_attempts INTEGER NOT NULL DEFAULT 0 CHECK (publish_attempts >= 0),
last_publish_attempt_at INTEGER,
last_publish_error TEXT,
PRIMARY KEY (session_id, generation),
CHECK (archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_pending
ON session_transcript_archives(created_at, session_id, generation)
WHERE published_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_retention
ON session_transcript_archives(created_at, session_id, generation);
CREATE TABLE IF NOT EXISTS session_transcript_cold_archives (
session_id TEXT NOT NULL PRIMARY KEY,
generation TEXT NOT NULL,
archive_name TEXT NOT NULL UNIQUE,
archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
event_count INTEGER NOT NULL CHECK (event_count >= 1),
raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
last_seq INTEGER NOT NULL,
archived_at INTEGER NOT NULL,
storage TEXT NOT NULL CHECK (storage IN ('file', 'sqlite')),
archive_blob BLOB,
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%'),
CHECK ((storage = 'file' AND archive_blob IS NULL) OR (storage = 'sqlite' AND archive_blob IS NOT NULL))
) STRICT;
CREATE TABLE IF NOT EXISTS session_transcript_cold_archive_chunks (
session_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
archive_name TEXT NOT NULL UNIQUE,
archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
first_seq INTEGER NOT NULL,
last_seq INTEGER NOT NULL CHECK (last_seq >= first_seq),
event_count INTEGER NOT NULL CHECK (event_count >= 1),
raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
archive_blob BLOB,
PRIMARY KEY (session_id, chunk_index),
FOREIGN KEY (session_id) REFERENCES session_transcript_cold_archives(session_id) ON DELETE CASCADE,
CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT, WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (
session_id TEXT NOT NULL PRIMARY KEY,
generation TEXT NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS trajectory_runtime_events (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
run_id TEXT,
event_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
event_utf8_bytes INTEGER,
event_payload BLOB,
event_codec TEXT,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_trajectory_runtime_run
ON trajectory_runtime_events(session_id, run_id, created_at, COALESCE(event_utf8_bytes, octet_length(event_json)));
CREATE TABLE IF NOT EXISTS acp_parent_stream_events (
session_id TEXT NOT NULL,
run_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_id, run_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_acp_parent_stream_run
ON acp_parent_stream_events(run_id, seq);
CREATE TABLE IF NOT EXISTS transcript_event_identities (
session_id TEXT NOT NULL,
event_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_type TEXT,
parent_id TEXT,
message_idempotency_key TEXT,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_id, event_id),
FOREIGN KEY (session_id, seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_message_idempotency
ON transcript_event_identities(session_id, message_idempotency_key)
WHERE message_idempotency_key IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_identity_sequence
ON transcript_event_identities(session_id, seq);
CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence
ON transcript_event_identities(session_id, event_type, seq DESC);
CREATE TABLE IF NOT EXISTS context_engine_turn_outbox (
enqueue_sequence INTEGER PRIMARY KEY,
advancement_key TEXT NOT NULL UNIQUE,
engine_id TEXT NOT NULL,
owner_plugin_id TEXT,
session_id TEXT NOT NULL,
payload_json TEXT NOT NULL,
payload_state TEXT,
attempt_count INTEGER NOT NULL DEFAULT 0,
last_attempt_at INTEGER,
last_error TEXT,
created_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_context_engine_turn_outbox_engine
ON context_engine_turn_outbox(engine_id, created_at);
CREATE TABLE IF NOT EXISTS agent_tool_usage (
tool_id TEXT PRIMARY KEY NOT NULL,
score REAL NOT NULL CHECK (score >= 0),
updated_at INTEGER NOT NULL
) STRICT;
-- END AGENT TOOL USAGE
CREATE TABLE IF NOT EXISTS cache_entries (
scope TEXT NOT NULL,
key TEXT NOT NULL,
value_json TEXT,
blob BLOB,
expires_at INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (scope, key)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_cache_expiry
ON cache_entries(scope, expires_at, key)
WHERE expires_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_cache_updated
ON cache_entries(scope, updated_at DESC, key);
CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_scope
ON cache_entries(CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.agentId') END,
CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.sessionKey') END, CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.origin') END)
WHERE scope = 'talk-client-voice-sessions'
AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';
CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_updated
ON cache_entries(scope, updated_at)
WHERE scope = 'talk-client-voice-sessions'
AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';
CREATE TABLE IF NOT EXISTS auth_profile_store (
store_key TEXT NOT NULL PRIMARY KEY,
store_json TEXT NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS auth_profile_state (
state_key TEXT NOT NULL PRIMARY KEY,
state_json TEXT NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_sources (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'memory',
hash TEXT NOT NULL,
mtime REAL NOT NULL,
size INTEGER NOT NULL,
UNIQUE (path, source)
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_chunks (
chunk_rowid INTEGER PRIMARY KEY,
id TEXT NOT NULL UNIQUE,
path TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'memory',
start_line INTEGER NOT NULL,
end_line INTEGER NOT NULL,
hash TEXT NOT NULL,
model TEXT NOT NULL,
text TEXT NOT NULL,
embedding BLOB NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_chunk_recall_metadata (
chunk_id TEXT PRIMARY KEY,
importance INTEGER CHECK (importance IS NULL OR importance BETWEEN 1 AND 10),
triggers TEXT,
project_key TEXT,
FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_chunk_provenance (
chunk_id TEXT PRIMARY KEY,
origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),
observed_at INTEGER NOT NULL,
supersedes_key TEXT,
FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS memory_entry_origins (
entry_key TEXT NOT NULL,
agent_id TEXT NOT NULL,
session_id TEXT NOT NULL,
session_key TEXT,
origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
observed_at INTEGER NOT NULL,
PRIMARY KEY (entry_key, agent_id, session_id)
) STRICT, WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS memory_session_tombstones (
session_id TEXT NOT NULL PRIMARY KEY,
agent_id TEXT NOT NULL,
reason TEXT NOT NULL,
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_embedding_cache (
provider TEXT NOT NULL,
model TEXT NOT NULL,
provider_key TEXT NOT NULL,
hash TEXT NOT NULL,
embedding BLOB NOT NULL,
dims INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (provider, model, provider_key, hash)
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
revision INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS standing_intents (
intent_key INTEGER PRIMARY KEY,
id TEXT NOT NULL UNIQUE,
description TEXT NOT NULL,
trigger_keywords TEXT NOT NULL,
trigger_embedding TEXT,
channel_scope TEXT,
sender_scope TEXT,
creator_sender TEXT CHECK (creator_sender IS NULL OR length(trim(creator_sender)) > 0),
status TEXT NOT NULL CHECK (status IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired')),
expires_at INTEGER NOT NULL,
max_fires INTEGER NOT NULL CHECK (max_fires > 0),
fire_count INTEGER NOT NULL DEFAULT 0 CHECK (fire_count >= 0),
cooldown_seconds INTEGER NOT NULL DEFAULT 86400 CHECK (cooldown_seconds >= 0),
last_fired_at INTEGER,
created_at INTEGER NOT NULL,
source_session_id TEXT
) STRICT;
CREATE INDEX IF NOT EXISTS idx_standing_intents_lifecycle
ON standing_intents(status, expires_at, last_fired_at);
CREATE INDEX IF NOT EXISTS idx_standing_intents_scope
ON standing_intents(status, channel_scope, sender_scope);
CREATE VIRTUAL TABLE IF NOT EXISTS standing_intents_fts USING fts5(
trigger_keywords,
content = 'standing_intents',
content_rowid = 'intent_key',
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_insert
AFTER INSERT ON standing_intents
BEGIN
INSERT INTO standing_intents_fts(rowid, trigger_keywords)
VALUES (new.intent_key, new.trigger_keywords);
END;
CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_delete
AFTER DELETE ON standing_intents
BEGIN
INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
VALUES ('delete', old.intent_key, old.trigger_keywords);
END;
CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_update
AFTER UPDATE OF trigger_keywords ON standing_intents
BEGIN
INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
VALUES ('delete', old.intent_key, old.trigger_keywords);
INSERT INTO standing_intents_fts(rowid, trigger_keywords)
VALUES (new.intent_key, new.trigger_keywords);
END;
CREATE TABLE IF NOT EXISTS session_transcript_index_state (
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;
CREATE TABLE IF NOT EXISTS session_transcript_active_events (
session_id TEXT NOT NULL,
active_position INTEGER NOT NULL CHECK (active_position >= 0),
event_seq INTEGER NOT NULL,
message_position INTEGER CHECK (message_position IS NULL OR message_position >= 0),
context_eligible INTEGER,
PRIMARY KEY (session_id, active_position),
FOREIGN KEY (session_id, event_seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_event_seq
ON session_transcript_active_events(session_id, event_seq);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_messages
ON session_transcript_active_events(session_id, message_position)
WHERE message_position IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_transcript_context_pending
ON session_transcript_active_events(session_id)
WHERE context_eligible IS NULL;
CREATE TABLE IF NOT EXISTS session_transcript_active_event_facts (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
serialized_bytes INTEGER NOT NULL CHECK (serialized_bytes >= 1),
dependency_navigation_json TEXT NOT NULL,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id, seq)
REFERENCES session_transcript_active_events(session_id, event_seq) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;
-- END ACTIVE EVENT FACTS
CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(
text,
session_id UNINDEXED,
message_id UNINDEXED,
role UNINDEXED,
timestamp UNINDEXED,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (
id INTEGER PRIMARY KEY,
session_id TEXT NOT NULL,
message_id TEXT
) STRICT;
CREATE INDEX IF NOT EXISTS idx_session_transcript_fts_rows_session_message
ON session_transcript_fts_rows(session_id, message_id);
CREATE TRIGGER IF NOT EXISTS session_transcript_fts_rows_after_delete
AFTER DELETE ON session_transcript_fts_rows
BEGIN
DELETE FROM session_transcript_fts WHERE rowid = OLD.id;
END;
INSERT OR IGNORE INTO memory_index_state (id, revision) VALUES (1, 0);
CREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at
ON memory_embedding_cache(updated_at);
CREATE INDEX IF NOT EXISTS idx_memory_index_sources_source
ON memory_index_sources(source);
CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path_source
ON memory_index_chunks(path, source);
CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_source
ON memory_index_chunks(source);
-- Accepted input stays outside the active transcript until its exact turn owns execution.
CREATE TABLE IF NOT EXISTS session_pending_inputs (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
input_id TEXT NOT NULL UNIQUE,
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
run_id TEXT NOT NULL,
request_hash TEXT NOT NULL,
message_json TEXT NOT NULL,
lifecycle_generation TEXT NOT NULL,
state TEXT NOT NULL CHECK (state IN ('queued', 'interrupted', 'cancelled')),
accepted_at INTEGER NOT NULL,
consumed_event_id TEXT,
UNIQUE (session_id, idempotency_key),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_pending_inputs_session
ON session_pending_inputs(session_key, session_id, seq DESC);
-- Processing completion is separate from input consumption; neither schedules replay.
CREATE TABLE IF NOT EXISTS session_input_completions (
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
run_id TEXT NOT NULL,
request_hash TEXT NOT NULL,
outcome_json TEXT NOT NULL,
succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
completed_at INTEGER NOT NULL,
PRIMARY KEY (session_id, idempotency_key),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_input_completions_session_key
ON session_input_completions(session_key);
`,{allowMissingColumns:!0,validateAfterRepair:validateSchema,validateUnchanged:validateSchema,diagnostics:i,reuseIntegrity:s,integrity:c?{...h,tables:l??h.tables}:void 0}));d.length>0&&Pa.warn(`Rebuilt canonical agent SQLite indexes for ${t} (${n}): ${d.join(`, `)}`,{agentId:t,path:n,indexes:d,elapsedMs:Math.floor(performance.now()-g)})}else d===0&&!f&&e.prepare(`PRAGMA page_count`).get()?.page_count===0?Kt(e,n,c?h:void 0):yield*qt(e,n,i,h);return m}function ensureAgentSchema(e,t,n,r=42,i=e=>e(),a,o=!1,s){let c=[],l=xi(r);e.exec(`PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = OFF;`);let u=!1;try{gt(e,()=>{lt(e);let i=br(e);Or(i,t,n);let a=Br(e,n),d=Ct({kind:`agent`,foundVersion:a,supportedVersion:r},s),f=a===0&&!Vr(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&&Rn(e,n,a);let assertMigration=()=>{p&&(m&&Dr(),O()?.assertAgentSchemaMigration({agentId:t,path:n,foundVersion:a,supportedVersion:r}))};if(assertMigration(),a<r&&ei(e,a),f&&r===42){e.exec(l),e.exec(`PRAGMA user_version = ${r};`),en(e,t,r),u=!0;return}let crossesVersion=e=>!f&&a<e&&r>=e,h=crossesVersion(25),g=crossesVersion(23),ee=crossesVersion(24),_=crossesVersion(30),v=_?Ar(l):l,y=ee?si(v):v,b=g?oi(y,a):y,finishStorageMigration=()=>{if(g&&migrateAgentStorageInTransaction(e,y,a,c),ee&&migrateSessionEntrySnapshotsInTransaction(e),h&&kn(e),crossesVersion(26)&&migrateAgentJsonPredicatesInTransaction(e),a<27&&r>=27){let r=migrateOutboxEnqueueSequenceInTransaction(e);r!==null&&Pa.info(`agent outbox enqueue sequence rebuilt`,{agentId:t,pathname:n,elapsedMs:r})}crossesVersion(28)&&Ir(e),crossesVersion(29)&&e.exec(Lr),_&&zr(e),crossesVersion(31)&&e.exec(jr),crossesVersion(37)&&e.exec(yr),crossesVersion(39)&&Er(e),crossesVersion(40)&&e.exec(xr),crossesVersion(41)&&e.exec(Tr),crossesVersion(42)&&e.exec(Fr),a<25&&Tt(e,n,l,{verifyPhysicalIntegrity:!1,integrity:d}),An(e,t,n,r,l,m,assertMigration,p?{tables:Un({kind:`agent`,foundVersion:a,supportedVersion:r}),...a>=40&&r<=42&&d.check===`quick`?{foreignKeyTables:a<41?[`session_transcript_active_event_facts`]:[]}:{}}:void 0)};if(a>=25&&a<r)Dn(e,{agentId:t,pathname:n,version:a},xi(a)),o||q(e),finishStorageMigration();else if(a<r&&a>=20&&a<25&&r>=21){a>=21&&(Nn(e,n,r),q(e),Bn(e),un(e),Fn(e),Cn(e)&&wn(e));let i=xi(a);Tt(e,n,i,{verifyPhysicalIntegrity:!1,integrity:d}),Dn(e,{agentId:t,pathname:n,version:a},i),a<21&&(e.exec(ri(b)),h||Zt(e)),finishStorageMigration()}else a===17&&(q(e),un(e),Kt(e,n,d),wn(e),Mn(e,n,xi(a),`legacy`,!0)),Nn(e,n,r),a===r?(q(e),Bn(e),Fn(e),Sn(e),Cn(e)&&(wn(e),e.exec(l)),Tt(e,n,l,{verifyPhysicalIntegrity:!1,integrity:s?d:void 0}),a===16&&Tn(e,n,l),en(e,t,r),Dn(e,{agentId:t,pathname:n,version:r},l),_n()):(a===14&&En(e,{agentId:t,pathname:n}),K(),ni(e),migrateOpenClawAgentSchema(e),pn(e),a<11&&Vn(e),migrateSessionNodesAndWindows(e,a),K(),q(e),r>=18&&a<18&&bn(e,n),r>=19&&$t(e,a),Bn(e),K(),e.exec(b),a!==17&&wn(e),a<r&&On(e),mn(e,a),zn(e,a),a<11&&Yr(e,b,{databaseLabel:n,integrityCheck:s}),a<21&&r>=21&&!h&&Zt(e),finishStorageMigration())},{databaseLabel:n,operationLabel:`agent.schema.ensure`,withCommit:i})}finally{e.isOpen&&e.exec(`PRAGMA foreign_keys = ON;`)}u&&(at(e)||st(e))&&(ct(e),bi(e));for(let e of c){let n=`Agent ${t}: ${e}`;Pa.warn(n),a?.(n)}}function registerOpenClawAgentWalMaintenance(e,t){if(I(e.db))return;let n={agentId:e.agentId,path:e.path,env:t},r=Hr(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(),G.databases.get(e.path)!==e||!e.db.isOpen)throw Error(`Agent WAL maintenance owner changed`)};Rt(e.db,async t=>{if(a.signal.aborted)return;let r=Cr(e.db),c=In(n,async()=>{assertCurrent(),s=y({...n,revoke:cancel,async close(){cancel(),await o?.catch(()=>{})}});let{captureOpenClawAgentDatabaseExecution:e}=await import(`./openclaw-state-read-openclaw-agent-execution-C0akfw7h.mjs`).then(e=>e.t);assertCurrent();let r=e(n,{expectedIdentity:i});try{let e=await r.runExisting(yn(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:Fa,openOpenClawAgentDatabaseInWorker:Ia,runOpenClawAgentWriteTransaction:La,withOpenClawAgentDatabaseAsync:Ra,withOpenClawAgentDatabaseRuntime:za,withOpenClawAgentDatabaseRuntimeFromExecution:Ba,withOpenClawAgentDatabaseAdmission:Va}=createOpenClawAgentDatabaseAdmissionOwner(openOpenClawAgentDatabaseSteps);function*openOpenClawAgentDatabaseSteps(e,t,n,r,o){let s=Pr(),c=s?void 0:o?.integrityCheck??O()?.sqliteIntegrityCheck;s&&It();let u=B(e.agentId);wr(u,{env:e.env});let f={...e,agentId:u},p=l(f),assertCurrent=e=>{o?.assertCurrent?.(),o?.expectedIdentity&&(e?Wr(e,o.expectedIdentity):ne(p,o.expectedIdentity.key,o.expectedIdentity.birthtime))};assertCurrent(),a(f),m(f)?.assertCurrent();let h=Sr(f);if(h){if(assertCurrent(h),n)throw Error(`A prepared Worker lease cannot adopt an existing agent database handle`);return t?.workerPrepared&&_i(h,!0,!0),h}_({agentId:u,path:p}),t||rn(p);let g=G.databases.get(p),ee=!process.permission&&ie();o?.expectedIdentity||We(p),Si(p);let v=he(`agent`,p,{env:f.env});if(v)throw fn(p,v),v;g&&(ln(g),G.databases.delete(p),G.failures.delete(p));let y={...e.env??process.env,OPENCLAW_STATE_DIR:me(e.env??process.env),...Ot(e.env??process.env)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};if(n&&(n.receipt.agentId!==u||n.receipt.path!==p))throw Error(`Prepared agent database lease belongs to another store`);let te=!1,x,S={},C=t?.validation??n?.validation,captureVerification=(e,t)=>{te=e,x=t},w={env:y,initializationAgentPaths:[p]};assertCurrent();let T=n?n.claim(captureVerification):sn({agentId:u,path:p,env:y},void 0,captureVerification);t&&(t.assertHeld=()=>nn(T,{agentId:u,path:p,env:y}));let E=hn(u,p,t?`async`:`sync`,S),D,re,oe,se;try{if(assertCurrent(),n&&!Z)try{pt({stage:`prepare`,facts:{kind:`agent-validation-start`,lease:n.receipt}})}catch(e){throw new Ie(e)}o?.expectedIdentity||(ensureOpenClawAgentDatabasePermissions(p,f),Nt(p)),Oi(p);let a=dt(o?.expectedIdentity?ft(p):p,{allowExtension:ee,timeout:s?void 0:j});D=a;let l=a;Ur(a,Ee(y)),assertCurrent({db:a,path:p}),o?.expectedIdentity&&ensureOpenClawAgentDatabasePermissions(p,f),a.enableLoadExtension(!1),Be(a),n&&a.exec(`PRAGMA temp_store = FILE`),E(`open`);let m={db:a,path:p,agentId:u};C&&!s&&fi(m,C);let h=!!vi(m),g=te||t?.workerPrepared===!0&&t.integrityRevoked!==!0,_=!1,v;try{if(s)t&&(se=b(t,f,async()=>{await tn(p,u)})),l=kr(a,u,p,!1,(e,t)=>{throw l=D=e,t}),D=l,v={checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:Wn,close:()=>!0},di({db:l,path:p,agentId:u}),h=!0,_=!0;else{_=_i(m,g,t?.workerPrepared),_||ct(a,e=>{Br(a,p,e)});let e=br(a);Or(e,u,p),_&&Mr(e,u,p),t&&(se=b(t,f,async()=>{await tn(p,u)})),S.integrityGateReason=n?.integrityRevoked===!0||t?.integrityRevoked===!0||yi(p,C)?`revoked`:te?le(a)??`no-proof`:`lease-class`;let r;S.integrityGateReason===`revoked`?(h=!1,_=!1):te&&(r=ae(a));let i=yield*agentDatabaseIntegrityBeforeMutationSteps(a,u,p,{runtimeAdmission:!n?.startupIntegrityRequired,diagnostics:S,verification:r,reuseRuntimeIntegrity:h&&g||S.integrityGateReason===`lease-class`&&x!==void 0&&Gn(p)===x,admittedSchema:_,integrityCheck:c,integrityTables:o?.integrityTables??[]});assertCurrent(m),S.integrityGateOutcome&&S.integrityGateOutcome!==`cached`||delete S.integrityGateReason,h&&(!e||i)&&(ui(p),h=!1),Nr(a,p),E(`validation`),Ft(a,{busyTimeoutMs:j}),v=Pt(a,{busyTimeoutMs:j,autoCheckpointPages:0,databaseLabel:`openclaw-agent:${u}`,databasePath:p,foreignKeys:!0,synchronous:`NORMAL`}),oe=v,E(`configuration`),assertCurrent(m),(!e||i||!h&&kt(a)!==jt)&&ensureAgentSchema(a,u,p,void 0,void 0,void 0,!1,c),E(`schema`),l=kr(a,u,p)}}catch(e){S.integrityGateOutcome===`failed`&&E(`validation`),oe?.close(),l.isOpen&&l.close(),I(l)&&a.isOpen&&a.close();let t=G.databases.get(p);throw t&&t.db!==a||ui(p),e instanceof Error&&(At(e)||Jt(e))&&fn(p,e),e}assertCurrent({db:l,path:p}),ensureOpenClawAgentDatabasePermissions(p,f),_||(ct(a),ci(a));let w={agentId:u,db:l,path:p,walMaintenance:v};if(re=w,Pn())throw Error(`Agent database maintenance is in progress; retry after openclaw doctor --fix completes.`);return i(w,f)?.registerClose(cn(w,`Agent deletion cleanup`)),d(w,f)?.registerClose(cn(w,`Agent creation claim`)),!h||!Jr(w,{env:e.env})?(assertCurrent(w),registerOpenClawAgentDatabase({agentId:u,path:p,env:e.env,admittedDb:c===`quick`&&S.integrityGateOutcome!==`pending`?void 0:l},r)):_||hi(w),G.terminal.clear(p),G.unregisterExitClose??=ve(an),E(`registration`),Qt(w,T,y),assertCurrent(w),on(T,{agentId:u,path:p,env:y}),Hn(w),Z&®isterOpenClawAgentWalMaintenance(w,y),O()?.own(w.db,`agent-handles`,()=>dn(w)),se?.(),w}catch(e){let r=n!==void 0&&!Z&&e instanceof Ie,i;if(re)try{ln(re)}catch(e){i=e}if(D&&(D.isOpen||Re(D).isOpen)){let n=G.databases.get(p);if(t&&n&&n.db!==D){let t=D;throw gn(u,p,()=>{oe?.close(),t.isOpen&&t.close();let e=Re(t);I(t)&&e.isOpen&&e.close(),vn(T,w)}),e}ui(p);let r=re??{agentId:u,db:D,path:p,walMaintenance:oe??{checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:Wn,close:()=>!1}};G.databases.set(p,r),Hn(r),G.leases.set(p,{leaseId:T,env:y}),G.failures.set(p,i??e),O()?.own(r.db,`agent-handles`,()=>dn(r)),G.unregisterExitClose??=ve(an)}else if(!r){let t=e instanceof Ie?`read-only`:void 0;try{vn(T,w,t)}catch(e){throw gn(u,p,()=>vn(T,w,t)),e}}throw i??e}}function discoveryReadOptions(e){return e?{env:e.env,readCandidates:e.readCandidates,registeredDatabases:(e.snapshot?.registeredAgentDatabases??[]).filter(e=>e.schemaVersion===42)}:{}}function gatewayDiscoveryReadOptions(e,t){let n=createGatewayRetainedStoreMatcher(e,t),r=t?.recoveryExclusions;return{...discoveryReadOptions(t),excludeTarget:e=>{let t=ar(e.storePath).path;return r?.agentIds.includes(e.agentId)===!0||r?.storePaths.includes(e.storePath)===!0||r?.databasePaths.includes(t)===!0||!!n(t,e.agentId)}}}function createGatewayRetainedStoreMatcher(e,t){let n=discoveryReadOptions(t),r=n.env??process.env,readConfiguredTargets=t=>resolveConfiguredAgentDatabaseTargets(e,{env:r,...n,excludeTarget:e=>t(ar(e.storePath).path,e.agentId)}),i=t?void 0:Qr(Ee(r)),a=t?.snapshot??(i&&{retainedDeletions:i,registeredAgentDatabases:Gr({env:r})});if(!t&&!a&&Gi())throw Error(`Session discovery requires worker preparation; await the asynchronous session store loader.`);return t||a?createRetainedAgentDatabaseMatcherFromSnapshot(r,readConfiguredTargets,a,`database`,`runtime-discovery`):createRetainedAgentDatabaseMatcher(r,readConfiguredTargets,`database`,`runtime-discovery`)}function loadSessionEntrySnapshot(e,t=`list`,n,r=!1){let i=n?.writeRevision!==void 0&&n.writeRevision===E(e.db)?n:void 0,a=i?.entries??/* @__PURE__ */ new Map,o=i?.keys??[];if(!i)for(let n of Qe(e.db,Fi(e,t).select([`current_session_id`,`updated_at`]).orderBy(`session_key`))){o.push(n.session_key);let e=Di(n,t);e&&a.set(n.session_key,e)}return{entries:r?a:Ai(e.db,a),keys:o}}w(Symbol.for(`openclaw.conversationPublication`),()=>({installingFacts:0,pending:/* @__PURE__ */ new Map,facts:/* @__PURE__ */ new Set,observers:/* @__PURE__ */ new Set})),w(Symbol.for(`openclaw.conversationStaged`),()=>/* @__PURE__ */ new Map);function engineIndexHint(e,t){return R.raw(I(e)?``:`INDEXED BY ${t}`)}et(e=>{let t=I(e),n=R.raw(t?`strpos`:`instr`),r=L(e),i=r.selectFrom(`session_nodes`).select([`session_key`,`updated_at`,`archived_at`,`last_activity_at`,`last_interaction_at`,`session_started_at`]),a=r.selectFrom(i.modifyEnd(engineIndexHint(e,`idx_agent_session_nodes_updated_at`)).as(`age_rows`)).where(`archived_at`,`is`,null).orderBy(`updated_at`,`asc`).orderBy(`session_key`,`desc`),o=r.withRecursive(`age_namespaces`,e=>e.selectFrom(`session_nodes`).select(e=>e.fn.min(`session_key`).as(`first_key`)).where(`session_key`,`>=`,`agent:`).where(`session_key`,`<`,`agent;`).unionAll(e.selectFrom(`age_namespaces`).select(e=>e.selectFrom(`session_nodes`).select(e=>e.fn.min(`session_key`).as(`first_key`)).where(`session_key`,`>`,R`CASE
WHEN ${n}(substr(${e.ref(`age_namespaces.first_key`)}, 7), ':') > 0
THEN substr(${e.ref(`age_namespaces.first_key`)}, 1, 5 + ${n}(substr(${e.ref(`age_namespaces.first_key`)}, 7), ':')) || ';'
ELSE ${e.ref(`age_namespaces.first_key`)}
END`).where(`session_key`,`<`,`agent;`).as(`first_key`)).where(`first_key`,`is not`,null))).selectFrom(`age_namespaces`).crossJoin(i.as(`age_rows`)).where(`age_rows.session_key`,`>=`,R`substr(first_key, 1, 6 + ${n}(substr(first_key, 7), ':')) || 'dashboard:'`).where(`age_rows.session_key`,`<`,R`substr(first_key, 1, 6 + ${n}(substr(first_key, 7), ':')) || 'dashboard;'`).where(`archived_at`,`is`,null).selectAll(`age_rows`),s=r.selectFrom(`session_canonical_validation_pending as pending`).crossJoin(i.as(`age_rows`)).whereRef(`pending.session_key`,`=`,`age_rows.session_key`).where(`archived_at`,`is`,null).selectAll(`age_rows`),c=$e(e,e=>{let n=a.select([`session_key`,`updated_at`]).where(`updated_at`,`>`,e(({minimum:e})=>e));if(!t)return n;let r=e(({minimum:e,previous:t})=>t?.updated_at??e);return n.where(`updated_at`,`>=`,r).where(t=>t.or([t(`updated_at`,`>`,r),t(`session_key`,`<`,e(({previous:e})=>e?.session_key??null))])).limit(64)});return{after:t?function*(e){let t;for(;;){let n=0;for(let r of c({minimum:e,previous:t}))t=r,n++,yield r;if(n<64)return}}:e=>c({minimum:e}),activity:$e(e,()=>a.selectAll(`age_rows`)),activityBefore:$e(e,e=>a.selectAll(`age_rows`).where(`updated_at`,`<`,e(e=>e))),dashboards:$e(e,()=>o.unionAll(s)),dashboardsBefore:$e(e,e=>{let t=e(e=>e);return o.where(`age_rows.updated_at`,`<`,t).unionAll(s.where(`age_rows.updated_at`,`<`,t))})}}),Ke(`sessions/store`);function readSessionEntryCache(e,t){return ot(e.db,()=>{let n=t.projection,r=t.cache&&!t.deferParticipants&&!t.latest&&n!==`full`&&!e.db.isTransaction&&st(e.db)?Li(e.db):void 0,i=Ti(e,n!==`full`);if(!r)return loadSessionEntrySnapshot(e,n,i,t.deferParticipants);let a=Ci.get(e.db);if(a&&Pi(a.validityToken,r))return a;let o=loadSessionEntrySnapshot(e,t.projection,i);for(let e of o.entries.values())mr(e);let s={...o,validityToken:r};return Ci.set(e.db,s),s})}function readSelectedSessionEntriesInDatabase(e,t,n={}){return zi(e,n.continuation,()=>{Ti(e);let r=new Set(t),i=new Set(n.fullEntryKeys),a=Fi(e,`list`,n.fullEntryKeys).select([`current_session_id`,`updated_at`]).orderBy(`session_key`),o=L(e.db),s=o.selectFrom(`session_canonical_validation_pending`).select(`session_key`),c=o.selectFrom(`session_nodes`).select(`session_key`).where(`session_key`,`in`,tt(t));if(n.label!==void 0&&(c=c.union(o.selectFrom(`session_nodes`).select(`session_key`).where(`label`,`=`,n.label.trim()))),n.sessionIdOrKey!==void 0&&(c=c.union(o.selectFrom(`session_nodes`).select(`session_key`).where(`session_key`,`=`,n.sessionIdOrKey)).union(o.selectFrom(`session_nodes`).select(`session_key`).where(`current_session_id`,`=`,n.sessionIdOrKey))),n.transcriptSessionIds!==void 0){let e=n.transcriptSessionIds,r=e.map(e=>e.trim()).filter(Boolean),i=Ze(),a=i.fn(`trim`,[`current_session_id`,i.val(Ni)]),s=o.selectFrom(`session_nodes`).select(a.as(`session_id`)).where(`session_key`,`in`,tt(t)).where(a,`!=`,``);c=c.union(o.selectFrom(`session_nodes`).select(`session_key`).where(i.or([i(`current_session_id`,`in`,tt(e)),i(a,`in`,tt(r)),i(a,`in`,s)])))}let l=a.select(e=>n.transcriptSessionIds===void 0?e.val(0).as(`transcript_selected`):e(`session_key`,`in`,c).as(`transcript_selected`)),u=Qe(e.db,ji(e)?l.where(`session_key`,`in`,s.union(c)):l),d=[];for(let e of u){if(Zn(e.session_key))continue;let t=Di(e,i.has(e.session_key)?`full`:`list`);t&&(Ii(e.session_key,t),(r.has(e.session_key)||e.transcript_selected||n.label!==void 0&&t.label===n.label||n.sessionIdOrKey!==void 0&&(e.session_key===n.sessionIdOrKey||t.sessionId===n.sessionIdOrKey))&&d.push({sessionKey:e.session_key,entry:t}))}return d})}function resolveSqliteDatabaseScopeIdentity(e){let t=Jn(e.sessionKey)?.agentId,n=e.agentId?B(e.agentId):t,r=Kn(e.sessionKey)?qn(e.sessionKey):void 0,i=u(e.storePath,{agentId:r??n,env:e.env});if(i)return{effectiveAgentId:i.agentId,effectiveStorePath:i.path,effectiveEnv:i.env,explicitIncognito:i};let a=r?v({agentId:r,env:e.env}):e.storePath;return{effectiveAgentId:r??n,effectiveStorePath:a,effectiveEnv:e.env}}function resolveSqliteDatabaseScope(e,t,n){let{effectiveAgentId:r,effectiveStorePath:i,effectiveEnv:a,explicitIncognito:o}=resolveSqliteDatabaseScopeIdentity(e),s=o??n??(i?resolveCachedSqliteStoreTarget({agentId:r,defaultAgentId:e.defaultAgentId,env:a,storePath:i},t):void 0);return{agentId:tr({scopedAgentId:r,sessionKey:e.sessionKey,storeAgentId:s?.agentId,storeShared:s?.shared}),...s?.shared&&s.agentId?{databaseAgentId:s.agentId}:{},...a?{env:a}:{},...i?{ownerStorePath:i}:{},...s?{path:s.path}:{}}}function resolveSqliteScope(e,t,n){let{agentId:r,...i}=resolveSqliteDatabaseScope(e,t,n);if(!r)throw Error(`Cannot resolve SQLite session scope without an agent id`);return{agentId:r,...i,sessionKey:$n(e.sessionKey,r)}}function resolveSqliteReadScope(e,t,n){let r=e.sessionKey?Qn(e.sessionKey):void 0,{agentId:i,...a}=resolveSqliteDatabaseScope({...e,sessionKey:r},t,n);if(!i)throw Error(`Cannot resolve SQLite transcript read scope without an agent id`);return{agentId:i,...a,...r?{sessionKey:r}:{}}}function resolveCachedSqliteStoreTarget(e,t){let n=t&&(t.get(e.env)??/* @__PURE__ */ new Map);n&&t?.set(e.env,n);let r=n?JSON.stringify([e.storePath,e.agentId,e.defaultAgentId]):``,i=n?.get(r);if(i)return i;let a=gr(e.storePath,{agentId:e.agentId,defaultAgentId:e.defaultAgentId,...e.env?{env:e.env}:{}});return n?.set(r,a),a}function captureListingSource(e,t){if(!t.captureSource)return;let n=Hr(e),r={agentId:e.agentId,path:e.path,databaseIdentity:n.identity,databaseBirthtime:n.birthtime};Ri(r,e),t.captureSource(()=>Ri(r,typeof r.databaseIdentity==`symbol`?e:void 0))}function listSessionEntriesReadOnly(e={},t={}){let n=resolveSqliteScope({...e,sessionKey:``}),r=ki(r=>{let read=()=>listSqliteSessionEntriesFromDatabase(r,n,e,t);return t.continuation?zi(r,t.continuation,read):read()},er(n));return r.found?r.value:[]}function listSqliteSessionEntriesFromDatabase(e,t,n,r={}){captureListingSource(e,n);let i=r.deferParticipants||n.includeParticipants===!1?!0:void 0;if(n.sessionKeys&&!n.cronRetention&&!n.expiredCronRuns){let t=n.sessionKeys;return ot(e.db,()=>{let r=readSelectedSessionEntriesInDatabase(e,t,n.projection===`list`?{}:{fullEntryKeys:t});return i?r:[...Ai(e.db,new Map(r.map(({sessionKey:e,entry:t})=>[e,t])))].map(([e,t])=>({sessionKey:e,entry:t}))})}if(n.cronRetention||n.expiredCronRuns){let t=n.expiredCronRuns,a=t?B(t.agentId):void 0,o=Le(Re(e.db),()=>ht(e.db,()=>{let o=[];if(n.cronRetention){let t=n.cronRetention;for(let n of Qe(e.db,L(e.db).selectFrom(`session_nodes`).select(`session_key`).where(`session_key`,`>`,t.afterSessionKey??``).orderBy(`session_key`)))if(Yn(n.session_key)&&(o.push(n.session_key),o.length>=t.limit))break;r.captureCronRunSessionKey?.(o.length===t.limit?o.at(-1):null)}else for(let t of Qe(e.db,L(e.db).selectFrom(`session_nodes`).select(`session_key`).orderBy(`session_key`)))Yn(t.session_key)&&B(Jn(t.session_key).agentId)===a&&o.push(t.session_key);let s=readSelectedSessionEntriesInDatabase(e,o),c=null,l=s.filter(({sessionKey:e,entry:n})=>{if(!Yn(e)||t&&B(Jn(e).agentId)!==a)return!1;let r=n.updatedAt??0;return c=Math.min(c??r,r),!t||r<t.updatedBefore});r.captureCronRunUpdatedAt?.(c),i||(l=[...Ai(e.db,new Map(l.map(({sessionKey:e,entry:t})=>[e,t])))].map(([e,t])=>({sessionKey:e,entry:t})));let u=l.length?z(e.db,Fi(e,`full`).select(`updated_at`).where(`session_key`,`in`,tt(l.map(({sessionKey:e})=>e)))).rows:[];return{entries:l,rows:u}})),s=new Map(o.rows.map(e=>[e.session_key,e]));for(let e of o.entries){let t=s.get(e.sessionKey);t&&(e.entry={...Di(t),...e.entry})}return o.entries}let a=n.projection??`full`,o=readSessionEntryCache(e,{cache:!h(e.path,{agentId:e.agentId,env:t.env}),latest:n.readConsistency===`latest`,projection:a,deferParticipants:i}),s=a===`list`&&n.clone!==!1&&!i;return Array.from(iterateSessionEntriesForListing(o,s))}function*iterateSessionEntriesForListing(e,t=!1){for(let n of e.keys){if(Zn(n))continue;let r=e.entries.get(n);if(!r)continue;let i=Xn(n,r);if(i!==n)throw Ei(`non-canonical persisted row resolves to session key ${i}`);yield{sessionKey:n,entry:t?structuredClone(r):r}}}var Ha=/* @__PURE__ */ n({readSessionGroupMembership:()=>readSessionGroupMembership});function readSessionGroupMembership(e,t){let n=resolveAllAgentSessionStoreTargetsSync(e,gatewayDiscoveryReadOptions(e,{env:t,snapshot:Hi(t,`runtime-discovery`)})).map(e=>{let n=resolveSqliteReadScope({...e,env:t}),r=er(n);return{agentId:e.agentId,storePath:l(r)}}),r=/* @__PURE__ */ new Map;for(let e of n)for(let{sessionKey:n,entry:i}of listSessionEntriesReadOnly({...e,env:t,projection:`list`,clone:!1})){let t=C(i.category);if(t){let i=r.get(t)??[];i.push({sessionKey:n,agentId:e.agentId}),r.set(t,i)}}return{stores:n,groups:[...r]}}export{resolveConfiguredAgentDatabaseCandidatePaths as a,resolveAgentSessionDirsFromAgentsDirSync as c,isConfiguredAgentDatabaseTarget as i,createAgentDatabaseDeletionClassifier as n,resolveConfiguredSessionStoreTargets as o,getAgentDatabaseStartupAdmission as r,ma as s,Ha as t};