UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,304 lines • 1.14 MB
import{c as e,d as t,f as n,g as r,h as i,l as a,o as s,p as c,r as l,t as u,u as d,y as f}from"./service-child-group-anchor-error-coercion-BOmGaARv.mjs";import{t as p}from"./service-child-group-anchor-deferred-B75K7ut7.mjs";import{d as m,m as h,p as ee,v as g,y as te}from"./service-child-group-anchor-service-child-group-ownership-JC4VWUUW.mjs";import{i as ne,r as v,t as re}from"./service-child-group-anchor-linux-oom-score-spawn-CsK-1L0B.mjs";import{i as ie,r as ae,t as oe}from"./service-child-group-anchor-errno-CsW5NI8i.mjs";import"./service-child-group-anchor-linux-exec-cgroup-CkmtYUFW.mjs";import{a as se,o as ce}from"./service-child-group-anchor-runtime-process-manifest-BzzQjyny.mjs";import{i as le,n as ue,r as de,t as fe}from"./service-child-group-anchor-runtime-binary-BjnZCi-b.mjs";import{a as pe,o as me,s as he}from"./service-child-group-anchor-cli-invocation-DMTcSLIl.mjs";import{n as ge,t as _e}from"./service-child-group-anchor-runtime-worker-url-whbmQ4z6.mjs";import{A as ve,B as ye,C as be,D as xe,E as Se,G as Ce,L as we,M as Te,N as Ee,P as De,R as Oe,U as ke,X as Ae,Y as je,Z as Me,_ as Ne,a as Pe,b as Fe,c as Ie,d as Le,f as Re,g as ze,h as Be,i as Ve,j as He,l as Ue,m as We,n as Ge,o as Ke,p as qe,q as Je,t as y,u as Ye,v as Xe,w as Ze,x as Qe,y as $e,z as et}from"./service-child-group-anchor-subsystem-7ZAB4axr.mjs";import{$ as tt,$n as nt,A as rt,An as it,At as at,B as ot,Bn as st,Bt as ct,C as lt,Cn as ut,D as dt,Dn as ft,Dt as pt,E as mt,En as ht,Et as gt,F as _t,Fn as vt,Ft as yt,G as bt,Gn as xt,Gt as St,H as Ct,Hn as wt,Ht as Tt,I as Et,It as Dt,J as Ot,Jn as kt,Jt as At,K as jt,Kn as Mt,Kt as Nt,L as Pt,Ln as Ft,Lt as It,M as Lt,Mn as Rt,Mt as zt,N as Bt,Nn as Vt,Nt as Ht,O as Ut,On as Wt,Ot as Gt,P as Kt,Pn as qt,Pt as Jt,Q as Yt,Qt as Xt,R as Zt,Rn as Qt,Rt as $t,S as en,Sn as tn,St as nn,T as rn,Tn as an,Tt as on,U as sn,Un as cn,Ut as ln,V as un,Vn as dn,Vt as pn,W as mn,Wn as hn,Wt as gn,X as _n,Xn as vn,Xt as yn,Y as bn,Yn as xn,Yt as Sn,Z as Cn,Zn as wn,Zt as Tn,_ as En,_n as Dn,_t as On,a as kn,an as An,at as jn,b as Mn,bn as Nn,bt as Pn,c as Fn,cn as In,ct as Ln,dn as Rn,dt as zn,en as Bn,et as b,fn as Vn,ft as Hn,g as Un,gn as x,h as Wn,hn as Gn,ht as Kn,in as qn,it as Jn,j as Yn,jn as Xn,k as Zn,kn as Qn,kt as $n,l as er,ln as tr,lt as nr,mn as rr,mt as ir,nt as ar,on as or,ot as sr,pn as S,pt as cr,q as lr,qn as C,qt as ur,r as dr,rn as fr,rt as pr,sn as mr,st as hr,tt as gr,un as _r,ut as w,v as vr,vn as yr,vt as br,w as xr,wn as Sr,wt as Cr,xt as wr,yn as Tr,yt as Er,z as Dr,zn as Or,zt as kr}from"./service-child-group-anchor-worker-task-pool-WPWHTfoZ.mjs";import{n as Ar,r as jr}from"./service-child-group-anchor-path-existence-xZh3wSTB.mjs";import{t as Mr}from"./service-child-group-anchor-errors-BYG1dvP7.mjs";import{n as Nr,r as Pr,t as Fr}from"./service-child-group-anchor-error-graph-internal-BjfMmv6a.mjs";import{createRequire as Ir}from"node:module";import"node:events";import T,{chmodSync as Lr,existsSync as Rr,realpathSync as zr,statSync as Br,unlinkSync as Vr,writeFileSync as Hr,default as Ur}from"node:fs";import{Socket as Wr}from"node:net";import{createHash as Gr,hash as Kr,randomUUID as qr}from"node:crypto";import E from"node:path";import{AsyncLocalStorage as D}from"node:async_hooks";import"node:fs/promises";import Jr from"node:os";import{isDeepStrictEqual as Yr,toUSVString as Xr}from"node:util";import{isPathInside as Zr}from"@openclaw/fs-safe/path";import Qr,{spawnSync as $r}from"node:child_process";import"node:timers/promises";import{channel as ei}from"node:diagnostics_channel";import{MessageChannel as ti,isMainThread as ni,receiveMessageOnPort as ri,threadId as ii}from"node:worker_threads";import{fileURLToPath as ai,pathToFileURL as oi}from"node:url";import"node:perf_hooks";import{createDirectorySync as si,readFileDescriptorBoundedSync as ci,readFileWindowFullySync as li,sameFileIdentity as ui}from"@openclaw/fs-safe/advanced";import{GCProfiler as di,deserialize as fi,serialize as pi}from"node:v8";import{FsSafeError as mi}from"@openclaw/fs-safe/errors";import{sha256FileSync as hi,syncDirectorySync as gi}from"@openclaw/fs-safe/durability";import{isUtf8 as _i}from"node:buffer";import"semver";import{acquireFileLockSync as vi}from"@openclaw/fs-safe/file-lock";import"json5";import"@openclaw/fs-safe/permissions";import"@openclaw/fs-safe/copy";import{Value as yi}from"typebox/value";import{Type as bi}from"typebox";var xi=Object.defineProperty,__exportAll=(e,t)=>{let n={};for(var r in e)xi(n,r,{get:e[r],enumerable:!0});return t||xi(n,Symbol.toStringTag,{value:`Module`}),n};function toStringifiedError(e){return e instanceof Error?e:Error(String(e))}const Si=[`byte`,`kilo`,`mega`,`giga`,`tera`],Ci={iec:{base:1024,labels:[`B`,`KiB`,`MiB`,`GiB`,`TiB`]},"legacy-binary":{base:1024,labels:[`B`,`KB`,`MB`,`GB`,`TB`]}};function formatByteSize(e,t){let{base:n,labels:r}=Ci[t.style],i=Si.indexOf(t.maxUnit),a=0,s=e;for(;s>=n&&a<i;)s/=n,a+=1;for(;;){let e=Me(Si[a],`byte-size unit`),c=Me(r[a],`byte-size label`),l=typeof t.fractionDigits==`function`?t.fractionDigits(s,e):t.fractionDigits;if(l===null)return`${s}${t.separator}${c}`;let u=t.floorUnits?.includes(e)?Math.floor(s*10**l)/10**l:s;if(a<i&&Number(u.toFixed(l))>=n)s/=n,a+=1;else return`${u.toFixed(l)}${t.separator}${c}`}}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var o=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(o===void 0&&(o=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var r=o;if(typeof o!=`function`)throw TypeError(`Object is not disposable.`);r&&(o=function(){try{r.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:o,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}const wi=`ai.openclaw.node`,Ti=`OpenClaw Node`;function normalizeGatewayProfile(t){let n=t?.trim();return n&&e(n)!=="default"?n:null}function resolveGatewayProfileSuffix(e){let t=normalizeGatewayProfile(e);return t?`-${t}`:``}function resolveNodeLaunchAgentLabel(e){let t=normalizeGatewayProfile(e);return t?`${wi}.${t}`:wi}function resolveNodeSystemdServiceName(e){return`openclaw-node${resolveGatewayProfileSuffix(e)}`}function resolveNodeWindowsTaskName(e){let t=normalizeGatewayProfile(e);return t?`${Ti} (${t})`:Ti}function resolveNodeServiceIdentityEnvironment(e={}){let t=e.OPENCLAW_PROFILE;return{OPENCLAW_PROFILE:t,OPENCLAW_LAUNCHD_LABEL:resolveNodeLaunchAgentLabel(t),OPENCLAW_SYSTEMD_UNIT:resolveNodeSystemdServiceName(t),OPENCLAW_WINDOWS_TASK_NAME:resolveNodeWindowsTaskName(t),OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER:`1`,OPENCLAW_TASK_SCRIPT_NAME:`node.cmd`,OPENCLAW_LOG_PREFIX:`node${resolveGatewayProfileSuffix(t)}`,OPENCLAW_SERVICE_MARKER:`openclaw`,OPENCLAW_SERVICE_KIND:`node`}}const Ei=/* @__PURE__ */ new Set([`--dev`,`--no-color`]),Di=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`]);function isValueToken(e){return!e||e===`--`?!1:!e.startsWith(`-`)||/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){let n=e[t];return n?Ei.has(n)||n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`)?1:Di.has(n)?isValueToken(e[t+1])?2:1:0:0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,Ei,Di,`command-path`)}function getRootOptionAwareCommandPath(e,t){let n=e.slice(2),r=[],i=!1;for(let e=0;e<n.length;e+=1){let a=n[e];if(!a)break;if(!i&&a===`--`){if(r.length>0)break;i=!0;continue}let s=i?0:consumeRootCommandOptionToken(n,e);if(s>0)e+=s-1;else if((i||!a.startsWith(`-`))&&(r.push(a),r.length>=t))break}return r}function rewriteUpdateFlagArgv(e){let t=e.indexOf(`--update`);if(t===-1)return e;for(let n=2;n<e.length;n++){let r=e[n];if(!r||r===`--`)return e;if(n===t)return[...e.slice(0,t),`update`,...e.slice(t+1)];let i=consumeRootOptionToken(e,n);if(i>0)n+=i-1;else if(!r.startsWith(`-`))return e}return e}function isUpdateCommandArgv(e){return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e),1)[0]===`update`}function consumeKnownOptionToken(e,t,n,r,i){let a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;let s=a.indexOf(`=`),c=s===-1?a:a.slice(0,s);return n.has(c)?+(s===-1):r.has(c)?s===-1?i===`command-path`?e[t+1]===void 0?0:2:isValueToken(e[t+1])?2:0:i===`command-path`||a.slice(s+1).trim()?1:0:0}function getCommandPositionalsWithRootOptions(e,t){return parseCommandArgsWithRootOptions(e,t,!1)}function parseCommandArgsWithRootOptions(e,t,n,r=!1){let i=e.slice(2),a=new Set(t.booleanFlags??[]),s=new Set(t.valueFlags??[]),c=[],l=[],u=[],d=0,f=!1;for(let e=0;e<i.length;e+=1){let p=i[e];if(p===void 0)break;if(!f&&p===`--`){if(t.mode!==`command-path`)break;f=!0;continue}let m=f?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(m>0)(d>0&&a.has(p)?u:l).push(...i.slice(e,e+m)),e+=m-1;else if(!f&&p.startsWith(`-`)){let n=consumeKnownOptionToken(i,e,a,s,t.mode);if(n===0||d===0)return null;u.push(p),e+=n-1}else if(d<t.commandPath.length){if(p!==t.commandPath[d])return null;if(d+=1,n&&d===t.commandPath.length){let t=i.slice(e+1);return f?[`--`,...t]:t}}else if(c.push(p),!r&&c.length===t.maxPositionals)return c}return d<t.commandPath.length?null:r?{rootOptions:l,commandOptions:u}:c}let Oi;function isContainerEnvironment(){return Oi??=detectContainerEnvironment()}function detectContainerEnvironment(){if(process.env.FLY_MACHINE_ID?.trim()&&process.env.FLY_APP_NAME?.trim())return!0;for(let e of[`/.dockerenv`,`/run/.containerenv`,`/var/run/.containerenv`])try{return T.accessSync(e,T.constants.F_OK),!0}catch{}try{let e=T.readFileSync(`/proc/1/cgroup`,`utf8`);if(/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e))return!0}catch{}return!1}function sha256Hex(e){return Kr(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=E.resolve(e);for(;;)try{return T.statSync(t).isDirectory()?t:E.dirname(t)}catch{let e=E.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=T.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}function normalizeProcArg(t){return e(t.replaceAll(`\\`,`/`))}const ki=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`];function referencesRetainedArtifact(e){return e.split(/[\\/=]/u).some(e=>isLegacyPluginSourceCaptureName(e)||/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e))}function readProcessPackageIdentity(e,t=!1){for(let n=e;;){let e;try{e=JSON.parse(T.readFileSync(E.join(n,`package.json`),`utf8`))}catch(e){let r=E.dirname(n);if(t&&l(e)===`ENOENT`){if(r===n)return{kind:`absent`};if(E.basename(n)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};n=r;continue}return{kind:`unknown`,reason:`could not read package identity`}}return!f(e)||typeof e.name!=`string`||!e.name.trim()||e.name!==e.name.trim()?{kind:`unknown`,reason:`package identity has no valid name`}:{kind:`package`,name:e.name,scripts:f(e.scripts)?e.scripts:{}}}}function readProcessWorkingDirectories(e){let t=new Set(e.filter(e=>Number.isSafeInteger(e)&&e>0)),n=/* @__PURE__ */ new Map;if(t.size===0)return n;if(process.platform===`linux`){for(let e of t)try{n.set(e,T.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){let e=$r(`/usr/sbin/lsof`,[`-a`,`-p`,[...t].join(`,`),`-d`,`cwd`,`-F0pn`],{encoding:`utf8`,timeout:5e3,maxBuffer:4194304,env:te()});if(e.error||e.status!==0&&e.status!==1)return n;let r=e.stdout.split(`\0`);r.pop();let i=/* @__PURE__ */ new Set,a;for(let e of r){let r=e.replace(/^\n/,``);if(r.startsWith(`p`)){let e=/^p(\d+)$/.exec(r);a=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else a!==void 0&&r.startsWith(`n`)&&E.isAbsolute(r.slice(1))&&(n.delete(a)?i.add(a):i.has(a)||n.set(a,r.slice(1)))}}}catch{}return n}function classifyEntrypoint(e,t={}){let n=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(n.endsWith(`/openclaw`)||n===`openclaw`))return{kind:`openclaw`,entryIndex:0};let r=/(?:^|\/)openclaw\.mjs$/.test(n)?0:de(e).position;if(typeof r!=`number`)return r.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:r.reason}:{kind:`other`};let i=e[r];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&E.isAbsolute(t.cwd)&&fe(e[0]??``)&&!/[\\/]/u.test(i)&&!E.extname(i)){let e=readProcessPackageIdentity(t.cwd,!0);if(e.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:e.reason};let n=e.kind===`package`?e.scripts[i]:void 0;if(typeof n==`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}let a=classifyOpenClawEntrypointPath(i,t);return a.kind===`openclaw`?{...a,entryIndex:r}:a}function classifyOpenClawEntrypointPath(e,t={}){let n=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let r=[...ki,...t.additionalEntrypoints??[]],i=e;if(!E.isAbsolute(e)){let n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!E.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};i=E.resolve(n,e)}let a,s;try{if(a=T.realpathSync(i),t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(a))return{kind:`openclaw`,artifactPath:a};let n=t.requirePackageIdentity||t.inspectPackage?T.statSync(a):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};s=n?.isDirectory()??!1}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}let c=normalizeProcArg(a);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let l=s?void 0:r.find(e=>c.endsWith(`/${e}`));if(!l&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};let u=l?a.slice(0,-l.length):s?a:E.dirname(a),d=readProcessPackageIdentity(u,t.inspectPackage&&!t.requirePackageIdentity||!l&&!s);return d.kind===`unknown`?{kind:`unclassified`,cause:`package-identity`,reason:d.reason}:d.kind===`package`&&d.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:E.resolve(u),entrypoint:a}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){let{command:n,owner:r,pid:i,port:a}=t;if(!t.requirePackageIdentity&&n===`gateway`&&r?.pid===i&&r?.state===`live`&&(a===void 0||r.port===a))return{kind:`openclaw`};let s=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(s))return!n||s===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};let c=classifyEntrypoint(e,t);if(n)return c.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(c.entryIndex)],1)[0]??``)!==n?{kind:`other`}:c;if(c.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return c.kind===`openclaw`?c:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let u=t.serviceMarker;if(i!==void 0&&process.platform===`linux`&&(ue(s)||fe(s)||s===`tsx`))try{u=T.readFileSync(`/proc/${i}/environ`,`utf8`).split(`\0`).find(e=>e.startsWith(`OPENCLAW_SERVICE_MARKER=`))?.slice(24)}catch(e){return{kind:`unclassified`,cause:`service-marker`,reason:`process identity inspection failed (${l(e)??`unavailable`})`}}return!t.requirePackageIdentity&&u===`openclaw`?{kind:`openclaw`}:c}var AppContainerSpawnUnsupportedError=class extends Error{constructor(e){super(`AppContainer: libuv ${e} cannot create child pipes; 1.53.0+ required. Run OpenClaw outside the AppContainer or use a Node build with libuv >= 1.53.0.`),this.code=`APPCONTAINER_SPAWN_UNSUPPORTED`,this.name=`AppContainerSpawnUnsupportedError`}};let Ai=!1,ji;function assertAppContainerSpawnSupported(e){if(process.platform===`win32`&&!(e===`ignore`||e===`inherit`||Array.isArray(e)&&e.length>=3&&e.every(e=>e!=null&&e!==`pipe`&&e!==`overlapped`&&e!==`ipc`&&!(typeof e==`number`&&e<0)))){if(!Ai){Ai=!0;try{let{readCurrentAppContainerSid:e}=Ir(import.meta.url)(`@openclaw/proc-safe/windows-token`),t=e(),n=process.versions.uv,r=Number(n.split(`.`)[0]),i=Number(n.split(`.`)[1]);t!==null&&(r<1||r===1&&i<53)&&(ji=new AppContainerSpawnUnsupportedError(n))}catch(e){import(`./service-child-group-anchor-windows-appcontainer-spawn-log.runtime-WZ124u11.mjs`).then(({logAppContainerTokenProbeFailure:t})=>t(e)).catch(()=>{})}}if(ji)throw ji}}function preparePostgresQuery(e){let t=``,n=0,r=!0,i,a;for(let s=0;s<e.length;){let c=e.slice(s),l=/^(?:[eE]'(?:\\[\s\S]|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*(?:\n|$))/.exec(c),u=/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(c)?.[0];if(c.startsWith(`/*`)){let n=s+2,r=1;for(;n<e.length&&r>0;)e.startsWith(`/*`,n)?(r++,n+=2):e.startsWith(`*/`,n)?(r--,n+=2):n++;t+=e.slice(s,n),s=n}else if(u){let n=e.indexOf(u,s+u.length),a=n<0?e.length:n+u.length;t+=e.slice(s,a),s=a,i=void 0,r=!1}else if(l)t+=l[0],s+=l[0].length,l[0].startsWith(`--`)||(i=void 0,r=!1);else{if(r&&/^pragma\b/i.test(c))throw Error(`The PostgreSQL engine does not support PRAGMA statements`);let l=/^(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?/.exec(c)?.[0];if(l){t+=l,s+=l.length,i=void 0,r=!1;continue}let u=/^[A-Za-z_][A-Za-z_0-9$]*/.exec(c)?.[0];if(u){let e=u.toUpperCase();i!==`AS`&&i!==`.`&&(e===`INTO`&&i!==`INSERT`&&i!==`MERGE`?a=`unscoped`:a===void 0&&/^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(e)&&(e!==`UPDATE`||i!==`FOR`&&i!==`KEY`)&&(a=`scoped`)),i=e,t+=u,s+=u.length,r=!1;continue}let d=e.charAt(s);/\s/.test(d)||(i=d),d===`?`&&e[s+1]===`?`?(t+=`?`,s+=2):d===`?`?(t+=`$${++n}`,s++):(t+=d,s++),d===`;`?r=!0:/\s/.test(d)||(r=!1)}}return{sql:t,mutation:a}}function validatePostgresBindings(e){for(let t of e)if(t!==null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`bigint`&&!ArrayBuffer.isView(t))throw TypeError(`SQL bindings must be null, numbers, bigints, strings, or ArrayBuffer views`)}function decodePostgresRows(e,t){return e.rows.map(n=>Object.fromEntries(e.fields.map(e=>{let r=n[e.name],i;if(r===null)i=null;else if(e.dataTypeID===20){if(typeof r!=`string`)throw TypeError(`PostgreSQL int8 results must be text`);let e=BigInt(r);if(t)i=e;else{let t=Number(e);if(!Number.isSafeInteger(t))throw RangeError(`PostgreSQL int8 ${e} cannot be represented safely as a number`);i=t}}else if(r instanceof Uint8Array)i=new Uint8Array(r);else if(typeof r==`boolean`)i=Number(r);else if(typeof r==`string`||typeof r==`number`||typeof r==`bigint`)i=r;else throw TypeError(`Unsupported PostgreSQL result type for column ${e.name}`);return[e.name,i]})))}function isPostgresConnectionError(e){return!e||e.startsWith(`08`)||/^57P0[123]$/.test(e)}function decodePostgresError(e){let t=Object.assign(Error(e.message),e);if(e.code===`57014`&&(t.name=`PostgresQueryCanceledError`),e.code===`55P03`||e.code===`40P01`||e.code===`40001`)return Object.assign(Error(e.message,{cause:t}),{code:`ERR_SQLITE_ERROR`,errcode:5});let n={23505:[2067,`UNIQUE`],23503:[787,`FOREIGN KEY`],23502:[1299,`NOT NULL`],23514:[275,`CHECK`]}[e.code??``];return n?Object.assign(Error(`${n[1]} constraint failed: ${e.constraint??e.column??`unknown`}`,{cause:t}),{code:`ERR_SQLITE_ERROR`,errcode:n[0]}):t}function requireDirectorySync(e,t){if(e.status!==`unsupported`||process.platform===`win32`)return;let n=e.code?` (${e.code})`:``;throw Error(`${t} does not support crash-durable directory synchronization${n}.`)}function hashFileDescriptorSync(e,t){let{digest:n,bytes:r}=hi(e,{maxBytes:t});return{sha256:n,sizeBytes:r}}function flushAndHashFileSync(e){let t=T.openSync(e,`r+`);try{return T.fsyncSync(t),hashFileDescriptorSync(t)}finally{T.closeSync(t)}}function sameFileStatFingerprint(e,t){return ui(e,t)&&e.size===t.size}const{kyselyByDatabase:Mi,queryErrorHandlerByDatabase:Ni}=i(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap})),Pi=Symbol.for(`openclaw.kyselySyncStatementCache`),Fi=Symbol.for(`openclaw.kyselySyncStatementInvalidation`),Ii=Symbol.for(`openclaw.kyselySyncStatementCacheEnabled`),Li=Symbol.for(`openclaw.kyselySyncAuthorizerActive`),Ri=Symbol.for(`openclaw.sqliteDisposeCallbacks`),zi=Symbol.for(`openclaw.sqliteDisposeGuards`),Bi=65536;function disposeSqliteStatement(e){e[Symbol.dispose]?.()}function clearStatementCache(e){let t=e[Pi];if(delete e[Pi],t)for(let e of t.statements.values())t.active.has(e)||disposeSqliteStatement(e)}function registerNodeSqliteDisposeCallback(e,t){let n=e;return installStatementInvalidation(n),nt(n[Ri]??=/* @__PURE__ */ new Set,t)}function assertNodeSqliteDisposalAllowed(e){for(let t of e[zi]??[])t()}function disposeNodeSqliteDependents(e,t=`close`){assertNodeSqliteDisposalAllowed(e);for(let n of e[Ri]??[])n(t)}function registerNodeSqliteKyselyQueryErrorHandler(e,t){Ni.set(e,t)}function clearNodeSqliteKyselyCacheForDatabase(e){clearStatementCache(e),Mi.delete(e),Ni.delete(e)}function installStatementInvalidation(e){if(!e[Fi]){if(typeof e.setAuthorizer==`function`){let t=e.setAuthorizer.bind(e);Object.defineProperty(e,"setAuthorizer",{configurable:!0,writable:!0,value(e){t(e),this[Li]=e!==null,clearStatementCache(this)}})}if(typeof e.deserialize==`function`){let t=e.deserialize.bind(e);Object.defineProperty(e,"deserialize",{configurable:!0,writable:!0,value(...e){disposeNodeSqliteDependents(this,`replace`);try{t(...e)}finally{clearStatementCache(this)}}})}for(let t of[`close`,Symbol.dispose])if(typeof e[t]==`function`){let n=e[t].bind(e);Object.defineProperty(e,t,{configurable:!0,writable:!0,value(){return disposeNodeSqliteDependents(this),clearNodeSqliteKyselyCacheForDatabase(this),n()}})}Object.defineProperty(e,Fi,{configurable:!0,value:!0})}}function queryFitsStatementCache(e,t){let n=Buffer.byteLength(e);if(n>Bi)return!1;for(let e of t){if(typeof e==`string`){if(e.length>Bi-n)return!1;n+=Buffer.byteLength(e)}else ArrayBuffer.isView(e)&&(n+=e.byteLength);if(n>Bi)return!1}return!0}function executeWithCachedStatement(e,t,n,r,i){if(C(e))return r(e.prepare(t));let a=e,executeLeased=(e,t)=>{if(i){try{i(t)}catch(e){throw t(),e}return r(e)}try{return r(e)}finally{t()}};if(!a[Ii]||a[Li]||!queryFitsStatementCache(t,n)){let n=e.prepare(t);return executeLeased(n,()=>disposeSqliteStatement(n))}let s=a[Pi];s||(s={statements:/* @__PURE__ */ new Map,candidates:/* @__PURE__ */ new Set,active:/* @__PURE__ */ new WeakSet},Object.defineProperty(a,Pi,{configurable:!0,value:s}));let c=s.statements.get(t),l;if(c&&!s.active.has(c))s.statements.delete(t),s.statements.set(t,c),l=c;else if(l=e.prepare(t),!c&&s.candidates.delete(t)){if(s.statements.set(t,l),s.statements.size>64){let e=s.statements.entries().next().value;s.statements.delete(e[0]),s.active.has(e[1])||disposeSqliteStatement(e[1])}}else if(!c&&(s.candidates.add(t),s.candidates.size>64)){let e=s.candidates.values().next().value;e!==void 0&&s.candidates.delete(e)}return s.active.add(l),executeLeased(l,()=>{s.active.delete(l),(a[Pi]!==s||s.statements.get(t)!==l)&&disposeSqliteStatement(l)})}const Vi=/* @__PURE__ */ new WeakMap,{busyTimeoutByDatabase:Hi,trackedDatabases:Ui}=i(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}));function rememberSqliteBusyTimeout(e,t){Ui.has(e)||(Ui.add(e),registerNodeSqliteDisposeCallback(e,()=>Hi.delete(e))),Hi.set(e,t)}function normalizeSqliteNonNegativeInteger(e,t){if(!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function readSqliteBusyTimeout(e){let t=Hi.get(e);if(t!==void 0)return t;let n=e.prepare(`PRAGMA busy_timeout`).get(),r=n?.busy_timeout??n?.timeout,i=Number(typeof r==`bigint`?r:r??0);return rememberSqliteBusyTimeout(e,i),i}function setSqliteBusyTimeout(e,t){let n=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`);Hi.get(e)!==n&&(e.exec(`PRAGMA busy_timeout = ${n}`),rememberSqliteBusyTimeout(e,n))}function shouldReportSqliteLockFailure(e){return Vi.get(e)!==`suppress`}function runWithSqliteBusyTimeout(e,t,n,r={}){let i=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`),a=readSqliteBusyTimeout(e),s=Vi.get(e);r.lockFailureReporting&&Vi.set(e,r.lockFailureReporting),setSqliteBusyTimeout(e,i);let c=!1,restore=()=>{c||=(e.isOpen&&a!==i&&setSqliteBusyTimeout(e,a),s?Vi.set(e,s):Vi.delete(e),!0)};try{return n(restore)}finally{restore()}}const Wi={name:`database.engine.schema`,schemaDependent:!0};function hasPostgresCatalogColumn(e,t,n){return e.some(e=>e.table===t&&e.kind===`column`&&e.value!==null&&typeof e.value==`object`&&`name`in e.value&&e.value.name===n)}function canonical(e){return JSON.stringify(e,(e,t)=>typeof t==`object`&&t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).toSorted(([e],[t])=>e.localeCompare(t,`en`))):t)}function assertPostgresCatalog(e,t){if(!Yr(e.map(canonical).toSorted(),t.map(canonical).toSorted()))throw Error(`PostgreSQL catalog differs from its generated contract; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`)}function readPostgresCatalog(e){if(!Array.isArray(e)||!e.every(e=>typeof e==`object`&&!!e&&typeof e.table==`string`&&typeof e.kind==`string`&&`value`in e))throw Error(`PostgreSQL did not return catalog facts`);return e}function postgresCatalogQuery(e,t=!1){let n=`'${e.replaceAll(`'`,`''`)}'`,columns=(e,t)=>`(SELECT jsonb_agg(a.attname ORDER BY k.ordinality) FROM unnest(${t}) WITH ORDINALITY k(num, ordinality) JOIN pg_catalog.pg_attribute a ON a.attrelid = ${e} AND a.attnum = k.num)`,action=e=>`CASE ${e} WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END`;return`WITH relations AS (
    SELECT c.oid, c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    WHERE n.nspname = ${n} AND c.relkind IN ('r', 'p')
  ), attributes AS (
    SELECT r.relname, a.attname, a.atttypid, a.atttypmod, a.attnotnull,
      a.attidentity, a.attnum, a.attgenerated, a.attcollation,
      pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS default_expression
    FROM relations r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid
    LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = r.oid AND d.adnum = a.attnum
    WHERE a.attnum > 0 AND NOT a.attisdropped
  ), facts AS (
    SELECT r.relname AS "table", 'table' AS kind, 'null'::jsonb AS value FROM relations r
    UNION ALL SELECT a.relname, 'column', jsonb_build_object(
      'name', a.attname, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod),
      'nullable', NOT a.attnotnull, 'identity', a.attidentity = 'd', 'position', a.attnum,
      'default', regexp_replace(a.default_expression, '::(text|bigint|double precision)$', ''))
      FROM attributes a
    UNION ALL SELECT r.relname, CASE c.contype WHEN 'p' THEN 'primaryKey' ELSE 'unique' END,
      ${columns(`r.oid`,`c.conkey`)} FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid WHERE c.contype IN ('p', 'u')
    UNION ALL SELECT r.relname, 'foreignKey', jsonb_build_object(
      'columns', ${columns(`r.oid`,`c.conkey`)}, 'target', target.relname,
      'targetColumns', ${columns(`c.confrelid`,`c.confkey`)},
      'onUpdate', ${action(`c.confupdtype`)}, 'onDelete', ${action(`c.confdeltype`)},
      'deferrable', c.condeferrable, 'deferred', c.condeferred)
      FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
      JOIN pg_catalog.pg_class target ON target.oid = c.confrelid WHERE c.contype = 'f'
    UNION ALL SELECT r.relname, 'indexes', to_jsonb((SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = r.oid)) FROM relations r
    UNION ALL SELECT r.relname, 'checks', to_jsonb((SELECT count(*) FROM pg_catalog.pg_constraint c WHERE c.conrelid = r.oid AND c.contype = 'c')) FROM relations r
    ${t?`UNION ALL SELECT r.relname, 'constraintDefinition', jsonb_build_object('name', c.conname, 'definition', pg_catalog.pg_get_constraintdef(c.oid)) FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
    UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid
    UNION ALL SELECT a.relname, 'columnDefinition', jsonb_build_object('name', a.attname, 'default', a.default_expression, 'generated', a.attgenerated, 'identity', a.attidentity, 'collation', a.attcollation::regcollation::text) FROM attributes a
    UNION ALL SELECT r.relname, 'triggerDefinition', jsonb_build_object('name', t.tgname, 'definition', pg_catalog.pg_get_triggerdef(t.oid), 'enabled', t.tgenabled, 'function', pg_catalog.pg_get_functiondef(t.tgfoid)) FROM relations r JOIN pg_catalog.pg_trigger t ON t.tgrelid = r.oid WHERE NOT t.tgisinternal
    UNION ALL SELECT c.relname, 'viewDefinition', to_jsonb(pg_catalog.pg_get_viewdef(c.oid)) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${n} AND c.relkind IN ('v', 'm')
    UNION ALL SELECT c.cfgname, 'textSearchDefinition', jsonb_build_object('token', m.maptokentype, 'order', m.mapseqno, 'dictionary', d.dictname, 'namespace', dn.nspname)
      FROM pg_catalog.pg_ts_config c JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace
      JOIN pg_catalog.pg_ts_config_map m ON m.mapcfg = c.oid JOIN pg_catalog.pg_ts_dict d ON d.oid = m.mapdict
      JOIN pg_catalog.pg_namespace dn ON dn.oid = d.dictnamespace WHERE n.nspname = ${n} AND c.cfgname = 'openclaw_simple_unaccent'
    UNION ALL SELECT p.proname, 'functionDefinition', to_jsonb(pg_catalog.pg_get_functiondef(p.oid)) FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${n} AND p.proname = 'openclaw_vector' AND p.prokind = 'f'`:``}
  ) SELECT coalesce(jsonb_agg(facts), '[]'::jsonb) AS catalog FROM facts`}var DatabaseSearchCapabilityUnavailableError=class extends Error{constructor(e,t){super(t??`Database ${e} search capability is unavailable.`),this.capability=e,this.code=`DATABASE_SEARCH_CAPABILITY_UNAVAILABLE`,this.name=`DatabaseSearchCapabilityUnavailableError`}};const pgSearchName=e=>`"${e.replaceAll(`"`,`""`)}"`,Gi=`openclaw_simple_unaccent`;function postgresSearchVectorSql(e,t,n=1){let r=`coalesce(${t}, '')`;return`to_tsvector(${e}::regconfig, ${n===2?`regexp_replace(${r}, '[[:punct:]]+', ' ', 'g')`:r})`}function postgresSearchTextTriggerSql(e){let{table:t,field:n,sync:r}=e;return`CREATE FUNCTION ${r}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.openclaw_search := ${postgresSearchVectorSql(`format('%I.%I', TG_TABLE_SCHEMA, '${Gi}')`,`NEW.${n}`,2)};
  RETURN NEW;
END $$;
CREATE TRIGGER ${r} BEFORE INSERT OR UPDATE OF ${n} ON ${t} FOR EACH ROW EXECUTE FUNCTION ${r}();`}function postgresVectorDimensions(e){if(typeof e!=`number`||!Number.isInteger(e)||e<1||e>16e3)throw Error(`PostgreSQL vector capability unavailable: dimensions must be 1–16000; choose a supported embedding dimension and rebuild the derived index.`);return e}const Ki={name:`database.postgres.search`,schemaDependent:!0};function admitPostgresSearch(e,t,n,r=1){let i=JSON.stringify(t);if(b(e,Ki)?.some(e=>e.signature===i&&e.vectorSearchVersion>=r))return;let a=/* @__PURE__ */ new Set;Object.keys(t.text??{}).length&&a.add(`unaccent`),Object.values(t.text??{}).some(e=>e.postgres?.mode===`trigram`)&&a.add(`pg_trgm`),t.mode!==`keyword-only`&&Object.keys(t.vector??{}).length&&a.add(`vector`);for(let e of t.mode===`keyword-only`?[]:Object.values(t.vector??{}))postgresVectorDimensions(e.postgres?.dimensions);let s=t.extensionSchema??`public`,c=e.prepare(`SELECT a.name, e.extname, e.extversion, n.nspname FROM pg_catalog.pg_available_extensions a
    LEFT JOIN pg_catalog.pg_extension e ON e.extname = a.name
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
    WHERE a.name IN ('unaccent', 'pg_trgm', 'vector')`).all();for(let e of a){let t=c.find(t=>t.name===e);if(!t?.extname||t.nspname!==s){let n=t?t.extname?`Configure the store's extensionSchema as ${String(t.nspname)}, or have a database administrator relocate the extension; installation SQL is`:`Have a database administrator run`:`Install the server extension package for ${e}, then have a database administrator run`;throw new DatabaseSearchCapabilityUnavailableError(e===`vector`?`vector`:`fullText`,`PostgreSQL ${e} capability unavailable. ${n}: CREATE EXTENSION IF NOT EXISTS ${pgSearchName(e)} WITH SCHEMA ${pgSearchName(s)};${e===`vector`?` For keyword-only memory explicitly set memory.search.provider to "none".`:``}`)}if(e===`vector`&&r===2){let e=/^(\d+)\.(\d+)/.exec(String(t.extversion));if(!e||Number(e[1])===0&&Number(e[2])<7)throw new DatabaseSearchCapabilityUnavailableError(`vector`,`PostgreSQL binary vector search requires pgvector 0.7 or newer. Upgrade the server extension package, then have a database administrator run ALTER EXTENSION vector UPDATE before reopening the store.`)}}if(e.prepare(`SELECT coalesce(has_schema_privilege(to_regnamespace(?), 'CREATE'), has_database_privilege(current_database(), 'CREATE'))::int AS allowed`).get(n)?.allowed!==1)throw Error(`PostgreSQL search capability unavailable: insufficient CREATE privilege. Have the database owner grant CREATE on schema ${pgSearchName(n)} (or on the database before initial admission).`);return()=>publishPostgresSearch(e,t,r)}function publishPostgresSearch(e,t,n=1){let r=JSON.stringify(t),i=b(e,Ki)??[],a=i.find(e=>e.signature===r);w(e,Ki,[...i.filter(e=>e.signature!==r),{signature:r,vectorSearchVersion:a?.vectorSearchVersion===2?2:n}])}function postgresVectorDecoderSql(e,t=1,n=!1){let r=pgSearchName(e);return t===1?`CREATE ${n?`OR REPLACE `:``}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE vals real[] := '{}'; bits bigint; exponent integer; fraction double precision; value double precision;
BEGIN
  IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF;
  FOR i IN 0..dimensions-1 LOOP
    bits := 0;
    FOR j IN 0..7 LOOP bits := bits | (get_byte(bytes, i*8+j)::bigint << (j*8)); END LOOP;
    exponent := ((bits >> 52) & 2047)::integer;
    IF exponent = 2047 THEN RAISE EXCEPTION 'embedding must be finite'; END IF;
    fraction := (bits & 4503599627370495)::double precision / 4503599627370496;
    IF exponent < 873 OR (exponent = 873 AND fraction = 0) THEN value := 0;
    ELSE value := (1 + fraction) * power(2::double precision, exponent - 1023); END IF;
    IF bits < 0 THEN value := -value; END IF;
    vals := array_append(vals, value::real);
  END LOOP;
  RETURN vals::${r}.vector;
END $$;`:`CREATE ${n?`OR REPLACE `:``}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE vals double precision[]; first_nonfinite integer;
BEGIN
  IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF;
  -- Flatten TOAST once: repeated get_byte calls otherwise detoast the entire embedding.
  bytes := bytes || '\\x'::bytea;
  WITH bits AS MATERIALIZED (
    SELECT i,
      get_byte(bytes, i*8)::bigint |
      (get_byte(bytes, i*8+1)::bigint << 8) |
      (get_byte(bytes, i*8+2)::bigint << 16) |
      (get_byte(bytes, i*8+3)::bigint << 24) |
      (get_byte(bytes, i*8+4)::bigint << 32) |
      (get_byte(bytes, i*8+5)::bigint << 40) |
      (get_byte(bytes, i*8+6)::bigint << 48) |
      (get_byte(bytes, i*8+7)::bigint << 56) AS b
    FROM generate_series(0, dimensions-1) AS i
  ), parts AS (
    SELECT i, b, ((b >> 52) & 2047)::integer AS exponent,
      (b & 4503599627370495)::double precision / 4503599627370496 AS fraction
    FROM bits
  )
  SELECT coalesce(array_agg(
    CASE WHEN b < 0 THEN -1::double precision ELSE 1::double precision END *
    CASE WHEN exponent = 2047 OR exponent < 873 OR (exponent = 873 AND fraction = 0)
      THEN 0::double precision
      ELSE (1 + fraction) * power(2::double precision, exponent - 1023)
    END ORDER BY i
  ), ARRAY[]::double precision[]), min(i) FILTER (WHERE exponent = 2047)
  INTO vals, first_nonfinite FROM parts;
  IF first_nonfinite IS NOT NULL THEN
    -- Preserve the old left-to-right overflow versus nonfinite error precedence.
    PERFORM vals[1:first_nonfinite]::real[];
    RAISE EXCEPTION 'embedding must be finite';
  END IF;
  RETURN vals::real[]::${r}.vector;
END $$;`}function postgresSearchSql(e,t,n={},r=1,i=1,a=1){let s=pgSearchName(e.extensionSchema??`public`),c=`${pgSearchName(t)}.${pgSearchName(Gi)}`,l=`'${c.replaceAll(`'`,`''`)}'`,u=[];Object.keys(e.text??{}).length&&!n.text&&u.push(`CREATE TEXT SEARCH CONFIGURATION ${c} (COPY = pg_catalog.simple);
ALTER TEXT SEARCH CONFIGURATION ${c} ALTER MAPPING FOR hword, hword_part, word, numword, numhword, hword_numpart WITH ${s}.unaccent, pg_catalog.simple;`);for(let t of Object.values(e.text??{})){if(!t.postgres||t.fields.length!==1)throw Error(`PostgreSQL text index requires one field and a declared source identity`);let e=pgSearchName(t.table),n=pgSearchName(t.fields[0]);u.push(a===2?`ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector;
${postgresSearchTextTriggerSql({table:e,field:n,sync:pgSearchName(`${t.table}_search_sync`)})}
UPDATE ${e} SET openclaw_search = ${postgresSearchVectorSql(l,n,2)};`:`ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector GENERATED ALWAYS AS (${postgresSearchVectorSql(l,n)}) STORED;`),u.push(`CREATE INDEX ${pgSearchName(`${t.table}_search_gin`)} ON ${e} USING gin(openclaw_search);`),t.postgres.mode===`trigram`&&u.push(`CREATE INDEX ${pgSearchName(`${t.table}_trgm_gin`)} ON ${e} USING gin(${n} ${s}.gin_trgm_ops);`)}if(e.mode===`keyword-only`)return u.join(`
`);Object.keys(e.vector??{}).length&&!n.vector&&u.push(postgresVectorDecoderSql(e.extensionSchema??`public`,r));for(let t of Object.values(e.vector??{})){let e=t.postgres;if(!e)throw Error(`PostgreSQL vector index requires a canonical embedding source`);let n=pgSearchName(t.table),r=pgSearchName(e.source),a=pgSearchName(e.key),c=pgSearchName(e.embedding),l=postgresVectorDimensions(e.dimensions),d=`INSERT INTO ${n}(id, embedding) SELECT ${a}, openclaw_vector(${c}, ${l}) FROM ${r} WHERE octet_length(${c}) > 0`,f=i===2?`, embedding_bits bit(${l}) GENERATED ALWAYS AS (CASE WHEN ${s}.vector_norm(embedding) > 0 THEN ${s}.binary_quantize(embedding)::bit(${l}) ELSE NULL END) STORED`:``;u.push(`CREATE TABLE ${n} (id TEXT PRIMARY KEY REFERENCES ${r}(${a}) ON UPDATE CASCADE ON DELETE CASCADE, embedding ${s}.vector(${l}) NOT NULL${f});
CREATE FUNCTION ${pgSearchName(`${t.table}_sync`)}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'UPDATE' AND OLD.${c} IS NOT DISTINCT FROM NEW.${c} THEN RETURN NEW; END IF;
  IF octet_length(NEW.${c}) > 0 THEN
    INSERT INTO ${n}(id, embedding) VALUES (NEW.${a}, openclaw_vector(NEW.${c}, ${l}))
    ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;
  ELSE
    DELETE FROM ${n} WHERE id = NEW.${a};
  END IF;
  RETURN NEW;
END $$;
CREATE TRIGGER ${pgSearchName(`${t.table}_sync`)} AFTER INSERT OR UPDATE OF ${c} ON ${r} FOR EACH ROW EXECUTE FUNCTION ${pgSearchName(`${t.table}_sync`)}();
${d};`)}return u.join(`
`)}function postgresStoreNamespace(e,t,n){return`${e}_${t}_${n.replaceAll(`-`,``).slice(0,16)}`}const qi=`Use a compatible OpenClaw binary or restore the matching PostgreSQL schema and anchor; do not edit schema metadata.`,quote=e=>`"${e.replaceAll(`"`,`""`)}"`,hash$1=e=>Gr(`sha256`).update(e).digest(`hex`),Ji=/* @__PURE__ */ new WeakMap,Yi={name:`database.postgres.schema`,schemaDependent:!0},getAdmittedPostgresSchema=e=>b(e,Yi),retainPostgresSchema=(e,t)=>{let{postgresMigrations:n,...r}=t;w(e,Yi,r)};function admitPostgresCapabilities(e){let t=Ji.get(e);if(t)return t;let n=e.prepare(`SELECT current_setting('server_version_num')::int AS version, current_setting('server_encoding') AS server_encoding, current_setting('client_encoding') AS client_encoding`).get();if(!n||typeof n.version!=`number`||n.version<16e4||n.server_encoding!==`UTF8`||n.client_encoding!==`UTF8`)throw Error(`PostgreSQL requires version 16 or newer and UTF8 server/client encoding; upgrade the server or port to a UTF8 database and set client_encoding=UTF8.`);let r={serverMajor:Math.floor(n.version/1e4),serverEncoding:`UTF8`,clientEncoding:`UTF8`};return Ji.set(e,r),r}function readPostgresSchema(e,t,n){let r=e.query(`WITH captured AS (${postgresCatalogQuery(t,!0)})
    SELECT catalog::text, to_jsonb(meta)::text AS metadata FROM captured
    CROSS JOIN ${quote(t)}.openclaw_schema_meta meta WHERE meta.store = ?`,[n]).rows[0];if(!r||typeof r.catalog!=`string`||typeof r.metadata!=`string`)throw Error(`Missing PostgreSQL catalog or metadata. ${qi}`);let i=JSON.parse(r.metadata);return{catalog:readPostgresCatalog(JSON.parse(r.catalog)),metadata:i}}function withPostgresSearchExtensions(e,t){return{...e,searchExtensions:JSON.parse(t.metadata.search_extensions??`{}`)}}function postgresSchemaFingerprint(e,t){let n=e.filter(e=>e.table!==`openclaw_schema_meta`).map(e=>JSON.stringify(e)).toSorted().join(`
`);if(!t)return hash$1(n);let r=JSON.stringify(t.from).slice(1,-1),i=JSON.stringify(quote(t.from)).slice(1,-1),a=JSON.stringify(t.to).slice(1,-1);return hash$1(n.replaceAll(`${i}.`,`${r}.`).replaceAll(r,a))}function postgresSchemaSql(e,t,n){let r=new Set(n?.filter(e=>e.kind===`table`).map(e=>e.table)),i=e.postgresFragments?.filter(e=>n?e.tables.some(e=>r.has(e)):e.activation===`version-additive`)??[],a=/* @__PURE__ */ new Map,add=t=>{if(!a.has(t.id)){for(let n of t.dependencies){let t=e.postgresFragments?.find(e=>e.id===n);if(!t)throw Error(`Missing PostgreSQL fragment dependency ${n}`);add(t)}a.set(t.id,t.sql)}};i.forEach(add);let s=[e.search,...Object.values(e.searchExtensions??{})].filter(e=>e!==void 0),c={text:!1,vector:!1},l=s.map(n=>{let r=postgresSearchSql(n,t,c,e.postgresVectorDecoderVersion,e.postgresVectorSearchVersion,e.postgresTextSearchVersion);return c.text||=Object.keys(n.text??{}).length>0,c.vector||=n.mode!==`keyword-only`&&Object.keys(n.vector??{}).length>0,`;\n${r}`}),u=e.postgresWithoutOptionalColumn;return[(u&&n&&!hasPostgresCatalogColumn(n,u.table,u.column)?u.sql:e.postgres)??``,...a.values(),...l].join(`
`)}function postgresSchemaHash(e,t){return hash$1(postgresSchemaSql(e,`openclaw_schema`,t))}function recordPostgresSchema(e,t,n,r){if(!e.isTransaction)throw Error(`PostgreSQL schema publication requires the owner's writer transaction`);let i=r??readPostgresSchema(e,t,n.id),a=postgresSchemaHash(n,i.catalog);return e.prepare(`UPDATE openclaw_schema_meta SET fingerprint = ?, ddl_hash = ?, server_major = ? WHERE store = ?`).run(postgresSchemaFingerprint(i.catalog),a,admitPostgresCapabilities(e).serverMajor,n.id),a}function verifyPostgresSchema(e,t,n,r,i=!1,a=!1){let s=postgresSchemaFingerprint(r.catalog),c=postgresSchemaHash(n,r.catalog),{metadata:l}=r,u=admitPostgresCapabilities(e).serverMajor;if(l.server_major===u&&l.fingerprint&&l.fingerprint!==s)throw Error(`PostgreSQL schema drift detected. ${qi}`);if(l.server_major===u&&l.fingerprint&&l.ddl_hash===c)return c;if(a)throw Error(`Read-only PostgreSQL admission requires a matching schema seal. ${qi}`);if(i)e.runTransaction(()=>verifyPostgresSchemaDefinition(e,t,n,r));else return verifyAndRecordPostgresSchema(e,t,n,r),c}function verifyPostgresSchemaDefinition(e,t,n,r){let i=postgresSchemaFingerprint(r.catalog,{from:t,to:t}),a=`openclaw_check_${qr().replaceAll(`-`,``)}`;e.exec(`CREATE SCHEMA ${quote(a)}`);try{e.exec(`SET LOCAL search_path TO ${quote(a)}`),e.exec(postgresSchemaSql(n,a,r.catalog));let s=e.query(`SELECT catalog::text FROM (${postgresCatalogQuery(a,!0)}) captured`).rows[0];if(postgresSchemaFingerprint(readPostgresCatalog(JSON.parse(String(s?.catalog))),{from:a,to:t})!==i)throw Error(`PostgreSQL schema drift detected against generated DDL. ${qi}`)}finally{e.exec(`SET LOCAL search_path TO ${quote(t)}`),e.exec(`DROP SCHEMA ${quote(a)} CASCADE`)}}function verifyAndRecordPostgresSchema(e,t,n,r=readPostgresSchema(e,t,n.id)){return e.runTransaction(()=>{verifyPostgresSchemaDefinition(e,t,n,r),r.metadata.ddl_hash||e.exec(`ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS fingerprint TEXT, ADD COLUMN IF NOT EXISTS ddl_hash TEXT, ADD COLUMN IF NOT EXISTS server_major BIGINT`),recordPostgresSchema(e,t,n,r)}),r}const Xi=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`;function getPostgresPhysicalFacts(e,t){if(C(e)&&e.isTransaction&&!t?.refresh){let t=gt.get(e);if(t?.schema.store===`agent`)return e.isOpen&&e.anchor.isOpen?t.schema:void 0}return b(e,Wi,t)}function admitPostgresPhysicalFacts(e){let t=getPostgresPhysicalFacts(e.db);if(t){if(t.version!==e.version||t.storeId!==e.storeId||t.namespace!==e.namespace||t.store!==e.store)throw Error(`PostgreSQL metadata identity or version mismatch. ${Xi}`);if(e.requireSealedSchema){let n=e.schema,r=getAdmittedPostgresSchema(e.db);if(!n||!t.schemaHash||t.schemaHash!==postgresSchemaHash({...n,searchExtensions:r?.searchExtensions},t.catalog))throw Error(`Read-only PostgreSQL admission requires a matching schema seal. ${Xi}`)}return t}let n=admitPostgresCapabilities(e.db),r;try{r=readPostgresSchema(e.db,e.namespace,e.store)}catch(e){throw Error(`Cannot read PostgreSQL catalog or metadata. ${Xi}`,{cause:e})}let{metadata:i,catalog:a}=r;if(i.version!==e.version||i.store_id!==e.storeId)throw Error(`PostgreSQL metadata identity or version mismatch. ${Xi}`);let s;if(e.schema){let t=withPostgresSearchExtensions(e.schema,r);s=e.recordSchema?recordPostgresSchema(e.db,e.namespace,t,r):verifyPostgresSchema(e.db,e.namespace,t,r,e.preserveSchemaSeal,e.requireSealedSchema),retainPostgresSchema(e.db,t)}let c={engine:`postgres`,admissionId:qr(),store:e.store,namespace:e.namespace,storeId:i.store_id,version:i.version,schemaHash:s,capabilities:n,catalog:a};return w(e.db,Wi,c),c}function requireNativeDatabaseFile(e,t){if(e===`postgres`)throw Error(`PostgreSQL cannot use SQLite ${t}; stop the Gateway and back up/restore the PostgreSQL schema with its matching anchor (P3-6 export support pending).`)}const Zi=i(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap);function getSqlitePinnedReadSnapshot(e){return Zi.get(e)}function runSqliteSchemaReadSnapshotSync(e,t){let n=Zi.get(e);for(let r=0;;r+=1){Zi.set(e,n??{});try{let n=executeWithCachedStatement(e,`PRAGMA schema_version`,[],e=>{let n;try{let i;try{n=e.iterate(),i=n.next()}catch(e){if(!ni&&r<4&&(Tt(e)===261||pn(e)===`SQLITE_BUSY_RECOVERY`))return{retry:!0};throw e}if(i.done)throw Error(`SQLite schema_version query returned no row`);return{retry:!1,value:t(Number(i.value.schema_version))}}finally{n?.return?.()}});if(!n.retry)return n.value}finally{n||Zi.delete(e)}}}const Qi={name:`sqlite-schema`,writer:`connection`,lifetime:`process`,schemaDependent:!0,read:e=>f(e)?e:void 0},$i={name:`sqlite-text-encoding`,writer:`connection`,lifetime:`process`,read:e=>typeof e==`string`?e:void 0};function readSqliteTextEncoding(e){let t=b(e,$i);if(t!==void 0)return t;let n=executeWithCachedStatement(e,`PRAGMA encoding`,[],e=>e.get());if(typeof n?.encoding!=`string`)throw Error(`SQLite did not report its text encoding`);return n.encoding}function readSqliteSchemaObjects(e){return executeWithCachedStatement(e,`SELECT type, name, tbl_name, sql FROM main.sqlite_schema WHERE type IN ('table', 'view', 'index', 'trigger')`,[],e=>e.all())}function captureSqliteSchemaFacts(e,t=0,n){let r=b(e,$i),i=runSqliteSchemaReadSnapshotSync(e,i=>{let a=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get()),s=Number(a?.user_version??0);n?.(s);let c=r??readSqliteTextEncoding(e),l=readSqliteSchemaObjects(e),u={admissionId:qr(),revision:t,userVersion:s,textEncoding:c,schemaVersion:i,tables:/* @__PURE__ */ new Set,views:/* @__PURE__ */ new Set,tableSql:/* @__PURE__ */ new Map,indexes:/* @__PURE__ */ new Set,indexDefinitions:/* @__PURE__ */ new Map,triggers:/* @__PURE__ */ new Map};for(let e of l){if(typeof e.name!=`string`)continue;let t=typeof e.sql==`string`?e.sql:null;switch(e.type){case`table`:u.tables.add(e.name),u.tableSql.set(e.name,t);break;case`view`:u.views.add(e.name);break;case`index`:u.indexes.add(e.name),typeof e.tbl_name==`string`&&u.indexDefinitions.set(e.name,{table:e.tbl_name,sql:t});break;case`trigger`:typeof e.tbl_name==`string`&&u.triggers.set(e.name,{table:e.tbl_name,sql:t})}}return u});return r===void 0&&(i.tables.size>0||i.views.size>0)&&w(e,$i,i.textEncoding),i}function captureTrackedSqliteSchemaFacts(e,t,n){t.capturing=!0;try{return captureSqliteSchemaFacts(e,t.revision,n)}finally{t.capturing=!1}}function invalidateTrackedSqliteSchemaFacts(e){e.revision+=1,e.facts=void 0}function observeSchemaLifetime(e,t,n){t.snapshot&&t.snapshot!==n&&(e.isTransaction&&t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.snapshot=void 0,t.qualifiedSnapshot=void 0);let r=ar(e),i=t.processRevision!==void 0&&t.processRevision!==r;return i&&!t.transactionalSchema&&(e.isTransaction&&t.transactionCatalogBound||t.facts&&n&&t.qualifiedSnapshot===n)?(t.transactionalFacts||=e.isTransaction,t.snapshot=n,!1):(t.processRevision=r,i&&invalidateTrackedSqliteSchemaFacts(t),(t.transactionalSchema||t.transactionalTempSchema||t.transactionalFacts)&&!e.isTransaction&&(t.transactionalSchema&&zn(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema=!1,t.transactionalTempSchema=!1,t.transactionalFacts=!1),i)}function prepareSqliteTempTrackingSchema(e,t){let{createSql:n,objects:r}=prepareTranscriptIndexSchema(t),i=new Map(r.map(e=>[e.name.toLowerCase(),e])),a=r.map(e=>e.name),s=r.filter(e=>e.type===`table`).map(e=>e.name),c=[...a,...s],l=executeWithCachedStatement(e,`SELECT type, name, tbl_name, sql FROM temp.sqlite_schema
     WHERE name COLLATE NOCASE IN (${a.map(()=>`?`).join(`,`)})
       OR (type = 'trigger' AND tbl_name COLLATE NOCASE IN (${s.map(()=>`?`).join(`,`)}))`,c,e=>e.all(...c)),u=l.some(e=>{let t=typeof e.name==`string`?i.get(e.name.toLowerCase()):void 0;return!t||e.type!==t.type||e.tbl_name!==t.table||typeof e.sql!=`string`||S(e.sql)!==S(t.sql)});return{sql:n(new Set(l.flatMap(e=>e.type===`trigger`&&typeof e.name==`string`?[e.name.toLowerCase()]:[]))),unexpected:u}}function prepareTranscriptIndexSchema(e){let t=x(e.statusTable),n=x(e.pendingTable),r=x(e.pendingIndex),i=`${t} (
    id INTEGER PRIMARY KEY CHECK (id = 1), sibling_write_revision INTEGER NOT NULL,
    schema_version INTEGER NOT NULL, complete INTEGER NOT NULL, after_session TEXT,
    completed_traversals INTEGER NOT NULL
  ) STRICT`,a=`${n} (session_id TEXT PRIMARY KEY, state INTEGER NOT NULL) STRICT`,s=`${r} ON ${n}(state, session_id)`,c=e.observedTables.flatMap(e=>[`INSERT`,`UPDATE`,`DELETE`].map(t=>{let r=`openclaw_${e}_projection_${t.toLowerCase()}`,i=t===`UPDATE`?[`OLD`,`NEW`]:[t===`DELETE`?`OLD`:`NEW`];return{name:r,table:e,definition:`TRIGGER ${x(r)} AFTER ${t} ON main.${x(e)}
          WHEN ${i.map(e=>`NOT EXISTS (
                SELECT 1 FROM ${n}
                WHERE session_id = ${e}.session_id AND state = 0
              )`).join(` OR `)} BEGIN
            ${i.map(e=>`
                  UPDATE ${n} SET state = 0 WHERE session_id = ${e}.session_id;
                  INSERT INTO ${n}
                    SELECT ${e}.session_id, 0 WHERE NOT EXISTS (
                      SELECT 1 FROM ${n} WHERE session_id = ${e}.session_id
                    );`).join(`
`)}
          END`}}));return{createSql:e=>`
    CREATE TEMP TABLE IF NOT EXISTS ${i};
    INSERT INTO temp.${t} VALUES (1, -1, -1, 0, NULL, 0)
      ON CONFLICT(id) DO UPDATE SET sibling_write_revision = -1;
    CREATE TEMP TABLE IF NOT EXISTS ${a};
    CREATE INDEX IF NOT EXISTS temp.${s};
    ${c.map(({name:t,definition:n})=>`${e.has(t.toLowerCase())?`DROP TRIGGER IF EXISTS temp.${x(t)};`:``}CREATE TEMP ${n};`).join(`
`)}
  `,objects:[{name:e.statusTable,type:`table`,table:e.statusTable,sql:`CREATE TABLE ${i}`},{name:e.pendingTable,type:`table`,table:e.pendingTable,sql:`CREATE TABLE ${a}`},{name:e.pendingIndex,type:`index`,table:e.pendingTable,sql:`CREATE INDEX ${s}`},...c.map(e=>({name:e.name,type:`trigger`,table:e.table,sql:`CREATE ${e.definition}`}))]}}function beginPostgresReadSnapshotScope(e){let t=getPostgresPhysicalFacts(e),n=Hn(e);return t&&n!==void 0&&gt.set(e,{schema:t,writeRevision:n,mutationRevision:e.mutationRevision,snapshot:{}}),()=>gt.delete(e)}function invalidateSqliteSchemaFacts(e){ar(e),invalidateSchemaFacts(e,!0)}function invalidateSchemaFacts(e,t,n=`main`,r=n!==`temp`){let i=pt.get(e);if(i){let a=n===`main`;if(i.isolatedTempTables.clear(),e.isTransaction&&(i.transactionMutationRevision=void 0),a&&jn(e),a&&e.isTransaction&&!i.transactionalSchema&&(i.transactionBaseFacts=i.facts),r)for(let e of i.mutationListeners??[])e(void 0);invalidateTrackedSqliteSchemaFacts(i),i.transactionalSchema||=a&&e.isTransaction,i.transactionalTempSchema||=n===`temp`&&e.isTransaction,i.pendingSchema||=a&&i.nativeDepth>0,t&&a&&!e.isTransaction&&i.nativeDepth===0&&zn(e)}}function registerSqliteSchemaMutationListener(e,t){let n=pt.get(e);if(!n)throw Error(`SQLite schema observation requires a tracked connection`);let r=n.mutationListeners??=/* @__PURE__ */ new Set;return r.add(t),()=>r.delete(t)}function trackSchemaChanges(e,t,n,r){let settle=(n=!1,r=!1)=>{if(r){let n=getSqlitePinnedReadSnapshot(e),r=n&&(t.transactionalSchema?t.transactionBaseFacts:t.facts);Cn(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema=!1,t.transactionalTempSchema=!1,t.transactionalFacts=!1,n&&t.admitted&&!t.authorizerActive&&(t.facts=r?{...r,revision:t.revision}:captureTrackedSqliteSchemaFacts(e,t),t.snapshot=n,t.qualifiedSnapshot=n),t.transactionBaseFacts=void 0}else(n||!e.isTransaction)&&(t.transactionalSchema||t.transactionalTempSchema||t.transactionalFacts)&&(t.transactionalSchema&&zn(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema&&=e.isTransaction,t.transactionalTempSchema&&=e.isTransaction,t.transactionalFacts=!1)},i=$n(e,n,(n,i)=>{if(t.settling)return{finish:()=>{}};let{control:a,dataChange:s}=n,c=a?.outerRollback!==!0&&n.schemaChange,l=n.mainSchemaChange&&a?.outerRollback!==!0;on(e,t);let u=i===`bind`?void 0:getSqlitePinnedReadSnapshot(e),d=i!==`bind`&&!u&&!t.capturing?{}:void 0;if(u&&u!==t.snapshot&&!t.capturing){if(e.isTransaction&&(t.transactionRead||t.transactionCatalogBound)&&t.processRevision!==ar(e))t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.transactionalFacts=!0;else if(observeSchemaLifetime(e,t,void 0),!t.facts&&!t.transactionalSchema){let n=b(e,Qi);n&&(t.facts={...n,revision:t.revision})}t.snapshot=u,t.qualifiedSnapshot=u}t.nativeDepth===0&&settle();let f=e.isTransaction;if((r||t.processRevision===void 0)&&!f&&(a?.kind===`BEGIN`||a?.kind===`SAVEPOINT`)){let n=ar(e);t.processRevision??=n}let p=!f&&a?.kind===`BEGIN`&&a.single?t.mutationRevision:void 0;!f&&a?.kind===`BEGIN`&&t.admitted&&getAdmittedSqliteSchemaFacts(e);let m=!!a&&!at(a,f),h=a?.kind===`ROLLBACK`,ee=h&&t.transactionalSchema&&!a.outerRollback,g=c&&!n.temporaryTableSchemaChange||h&&t.transactionalSchema,te=l||ee?`main`:h?t.transactionalTempSchema&&!t.transactionalSchema?`temp`:`rollback`:n.temporaryTableSchemaChange?`temp`:`local`;h&&Cn(e),(c||h)&&invalidateSchemaFacts(e,!1,te,g),(s||n.temporaryTableSchemaChange||a?.kind===`ROLLBACK`)&&(t.mutationRevision+=1),i!==`bind`&&f&&!a&&!t.transactionCatalogBound&&(t.transactionRead=!0);let ne=c||s||a!==void 0,v=n.temporaryWriteTables?.every(e=>t.isolatedTempTables.has(e));(s&&!v||l)&&Ot(e,l||t.nativeDepth>0),ne&&(t.mutationDepth+=1),t.nativeDepth+=1;let re=Nn(e),ie=t.schemaMutationRevision;return l&&(t.schemaMutationRevision+=1),t.pendingSchema||=l,d&&t.unmanagedSnapshots.add(d),{stepped:()=>{u&&t.facts&&e.isTransaction&&(t.transactionCatalogBound=!0)},finish:(n,r,i)=>{if(d&&t.unmanagedSnapshots.delete(d)&&t.iteratorFacts&&(invalidateTrackedSqliteSchemaFacts(t),t.iteratorFacts=!1),re(),--t.nativeDepth,ne&&--t.mutationDepth,!e.isOpen)return;(c||h)&&(h&&Cn(e),invalidateSchemaFacts(e,!1,te,g));let s=n&&f&&a?.outerRollback===!0&&!e.isTransaction&&!l&&t.schemaMutationRevision===ie;if(s&&(settle(!1,!0),t.pendingSchema=!1),t.nativeDepth===0){t.settling=!0;try{let i=t.pendingSchema||t.transactionalSchema;!s&&t.pendingSchema&&!e.isTransaction&&!t.transactionalSchema&&zn(e),s||settle(m),i&&!e.isTransaction&&!s&&(invalidateTrackedSqliteSchemaFacts(t),n||Cn(e),t.admitted&&!t.authorizerActive&&!r&&(getAdmittedSqliteSchemaFacts(e),t.transactionBaseFacts=void 0)),t.pendingSchema=!1}finally{t.settling=!1}}Cr(e,t,f,m,n,p),t.mutationDepth===0&&!e.isTransaction&&Yt(e,i),t.transactionRead||=e.isTransaction&&!(!a||a.single)}}});Gt(e,()=>{Yt(e),Kn(e)}),t.installTempTrackingSchema=r=>{let{sql:a,unexpected:s}=prepareSqliteTempTrackingSchema(e,r);try{if(i(()=>n.DatabaseSync.prototype.exec.call(e,a),{schemaChange:s,mainSchemaChange:s,temporaryTableSchemaChange:!1,dataChange:!0,temporaryWriteTables:[],control:void 0}),!s)for(let e of[r.statusTable,r.pendingTable])t.isolatedTempTables.add(e.toLowerCase())}catch(t){throw invalidateSqliteSchemaFacts(e),t}},typeof e.setAuthorizer==`function`&&(e.setAuthorizer=r=>{n.DatabaseSync.prototype.setAuthorizer.call(e,r),t.authorizerActive=r!==null,nn(e,t.authorizerActive),invalidateTrackedSqliteSchemaFacts(t)}),registerNodeSqliteDisposeCallback(e,()=>{invalidateTrackedSqliteSchemaFacts(t),t.readRevision=void 0,t.transactionSnapshot=void 0})}function readSqliteNativeMutationRevision(e){return C(e)?e.mutationRevision:pt.get(e)?.mutationRevision}function runSqliteReadOperationSync(e,t){if(C(e))return t();let n=pt.get(e);if(!n||n.authorizerActive)return t();n.readDepth+=1;try{return n.admitted&&getAdmittedSqliteSchemaFacts(e),t()}finally{--n.readDepth}}function trackSqliteSchema(e,t,n=!0){if(!pt.has(e)){let r={admitted:!1,publicationReady:!1,revision:0,readDepth:0,mutationRevision:0,mutationDepth:0,transactionOpen:e.isOpen&&e.isTransaction,transactionRead:!1,transactionCatalogBound:!1,nativeDepth:0,pendingSchema:!1,schemaMutationRevision:0,settling:!1,capturing:!1,transactionalSchema:!1,transactionalTempSchema:!1,transactionalFacts:!1,authorizerActive:!1,unmanagedSnapshots:/* @__PURE__ */ new Set,isolatedTempTables:/* @__PURE__ */ new Set,iteratorFacts:!1};pt.set(e,r),trackSchemaChanges(e,r,t,n);let i=ar(e,{existingOnly:!0}),a=b(e,Qi,{existingOnly:!0});a&&(r.admitted=!0,r.facts={...a,revision:r.revision},r.processRevision=i)}}function isSqliteSchemaAdmissionCold(e){let t=pt.get(e);return!(!t||t.admitted||t.authorizerActive)}function admitSqliteSchema(e,t){let n=pt.get(e);if(!n)throw Error(`SQLite schema admission requires a connection tracked from native open`);n.admitted=!0;let r=getAdmittedSqliteSchemaFacts(e,t);!n.publicationReady&&r&&n.unmanagedSnapshots.size===0&&!getSqlitePinnedReadSnapshot(e)&&(n.publicationReady=wr(e))}function getAdmittedSqliteSchemaFacts(e,t){if(C(e))return;let n=pt.get(e);if(!n?.admitted||n.authorizerActive)return;let r=getSqlitePinnedReadSnapshot(e),i=e.isTransaction&&(n.transactionRead||n.transactionCatalogBound)&&n.processRevision!==ar(e)||n.unmanagedSnapshots.size>0,a=observeSchemaLifetime(e,n,r);if(n.facts)t?.(n.facts.userVersion);else{n.snapshot=r,n.transactionalFacts||=e.isTransaction&&(n.readDepth===0||a);let s=i||!!r||n.transactionalSchema,c=n.transactionalSchema||s?void 0:b(e,Qi);if(c)return t?.(c.userVersion),n.facts={...c,revision:n.revision},n.facts;let l=ar(e);n.facts=captureTrackedSqliteSchemaFacts(e,n,t),n.iteratorFacts||=n.unmanagedSnapshots.size>0,n.qualifiedSnapshot=r,n.transactionCatalogBound||=e.isTransaction,s||w(e,Qi,n.facts,{schemaRevision:l})}return n.facts}function resolveSqliteFilesystemPath(e){return process.platform===`win32`?E.toNamespacedPath(E.resolve(e)):e}function resolveNodeSqliteLocation(e){return e===``||e===`:memory:`||e.startsWith(`file:`)?e:resolveSqliteFilesystemPath(e)}function resolveSqliteFileUriPath(e,t){if(t===`win32`){let t=E.win32.toNamespacedPath(E.win32.resolve(e));return`file:${encodeURIComponent(t)}`}return oi(E.resolve(e)).href}function resolveReadOnlyShmSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=ro&readonly_shm=1`}function resolveExistingSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=rw`}function resolveImmutableSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=ro&immutable=1`}function openNodeSqliteDatabase(e,t,n){let r=Bn(),i=resolveNodeSqliteLocation(e),a=t?.open===!1?void 0:hr(i,{create:t?.readOnly!==!0});if(t?.open!==!1&&n!==void 0&&a!==n)throw Error(`SQLite staging database changed before native open`);let s=new r.DatabaseSync(i,t??{});if(s.isOpen)try{bn(s,a)}catch(e){throw s.close(),e}return s.open=()=>{let e=hr(i,{create:t?.readOnly!==!0});if(n!==void 0&&e!==n)throw Error(`SQLite staging database changed before native open`);r.DatabaseSync.prototype.open.call(s);try{bn(s,e)}catch(e){throw s.close(),e}},trackSqliteSchema(s,{DatabaseSync:r.DatabaseSync,StatementSync:r.StatementSync},t?.readOnly!==!0),s.isOpen&&t?.timeout!==void 0&&rememberSqliteBusyTimeout(s,Math.max(0,t.timeout)),fr().explicitSqliteCloseReleasesNativeResources||registerNodeSqliteDisposeCallback(s,()=>{}),jt(s),s}const ea=[`owner.sqlite`,`owner.sqlite-journal`,`owner.sqlite-wal`,`owner.sqlite-shm`];var SqliteStagingRetiredError=class extends Error{constructor(){super(`SQLite snapshot parent retired; aborting snapshot allocation`)}};function acquireSqliteStagingToken(e,t,n={}){let r=ur,acquire=()=>acquireStagingToken(e,t,n),i=t===`create`?acquire():r(acquire),a=Object.assign(e=>r(()=>i(e)),{beginRetirement:()=>(r(()=>i.beginRetirement()),a)});return a}function acquireStagingToken(e,t,n){let r=E.join(e,ea[0]),readIdentity=(e,t)=>{let n=T.lstatSync(e,{bigint:!0});if(!(t===`directory`?n.isDirectory():n.isFile())||process.platform===`win32`&&(n.dev===0n||n.ino===0n))throw Error(`SQLite staging ownership is unknown`);return n},i=readIdentity(e,`directory`),a=ea.map(t=>T.lstatSync(E.join(e,t),{throwIfNoEntry:!1})),s=a[0];if(a.some(e=>e&&(!e.isFile()||process.getuid&&e.uid!==process.getuid()))||!s&&t!==`create`&&!n.allowMissing)throw Error(`SQLite snapshot token ownership is unknown`);t===`create`&&!s&&T.writeFileSync(r,``,{flag:`wx`,mode:420});let c=s!==void 0||t===`create`,l=c?readIdentity(r,`file`):void 0;if(n.expectedIdentity){if(!l)throw Error(`SQLite staging ownership is unknown`);Qt(l,n.expectedIdentity)}let u=gn(()=>openNodeSqliteDatabase(c?resolveExistingSqliteFileUri(r):r,{timeout:0},l&&Ft(l))),d,read=e=>executeWithCachedStatement(u,e,[],e=>e.get()),p=t===`reclaim`||t===`create`&&n.exclusiveCreate===!0,m=!1,assertIdentity=()=>{let t=readIdentity(e,`directory`);if(i.dev!==t.dev||i.ino!==t.ino)throw Error(`SQLite staging ownership changed before retirement`);let n=readIdentity(r,`file`);if(d.dev!==n.dev||d.ino!==n.ino)throw Error(`SQLite staging ownership changed before retirement`)},beginRetirement=()=>(assertIdentity(),u.isTransaction&&p||(u.isTransaction&&u.exec(`ROLLBACK`),u.exec(`BEGIN EXCLUSIVE`),p=!0),h),release=(e=!1)=>{u.isOpen&&(e?(beginRetirement(),m||u.exec(`PRAGMA user_version=1`),u.exec(`COMMIT`),m=!0):u.isTransaction&&u.exec(`ROLLBACK`),u.close(),e&&On(r))},h=Object.assign(release,{beginRetirement});try{if(d=l??readIdentity(r,`file`),p?u.exec(`BEGIN EXCLUSIVE`):t===`create`?u.exec(`BEGIN IMMEDIATE`):u.exec(`BEGIN`),t!==`create`||s){let e=read(`PRAGMA journal_mode`);if(!f(e)||e.journal_mode!==`delete`)throw Error(`SQLite snapshot token journal mode is unknown`);let n=read(`PRAGMA user_version`),r=f(n)?n.user_version:void 0;if(r!==0&&(t!==`reclaim`||r!==1))throw new SqliteStagingRetiredError;m=r===1}return assertIdentity(),h}catch(e){throw release(),e}}const ta=`openclaw-sqlite-readonly-v2-`,na=`(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$`,ra=RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${na}`,`u`),ia=RegExp(`^${ta}${na}`,`u`),aa=/^\.fs-safe-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.tmp$/u;function releaseTokens(e){let t=Fr(e,e=>e());if(t.length)throw AggregateError(t,`SQLite snapshot retirement token release failed`)}const isSqliteSnapshotStagingName=e=>ra.test(e)||ia.test(e);function acquireSqliteSnapshotToken(e,t){return acquireSqliteStagingToken(e,t,{allowMissing:ra.test(E.basename(e))})}function beginSqliteSnapshotRetirement(e,t={}){let n=[],r=[],release=()=>releaseTokens(n.filter(e=>e!==t.token));if(!T.existsSync(e))return t.token?.(),{bytes:0,payload:r,release,retire:()=>{}};function inspect(i,a,s=``,c=!0){let l=T.lstatSync(i);if(!l.isDirectory()||process.getuid&&l.uid!==process.getuid())throw Error(`Snapshot directory ownership is unknown`);let u=!s&&ra.test(E.basename(i));if(!s&&t.allowLegacy===!1&&!ia.test(E.basename(i)))throw Error(`Legacy or unrecognized snapshot requires offline operator cleanup`);let d=t.cutoff!==void 0&&u?Math.min(a,Date.now()-864e5):a,f=u?`Legacy snapshot contains activity newer than 24 hours`:`Snapshot contains activity within the reclamation grace period`;if(l.mtimeMs>=d)throw Error(f);u&&c&&t.cutoff!==void 0&&inspect(i,d,s,!1),!s&&c&&n.push(i===e&&t.token?t.token.beginRetirement():acquireSqliteSnapshotToken(i,`reclaim`));let p=0,m=l.mtimeMs;for(let e of T.readdirSync(i,{withFileTypes:!0})){let n=E.join(i,e.name),a=T.lstatSync(n);if(process.getuid&&a.uid!==process.getuid())throw Error(`Snapshot file ownership is unknown`);if(s&&t.cutoff!==void 0||!a.isFile()||!ea.some(t=>t===e.name)){if(m=Math.max(m,a.mtimeMs),a.isDirectory()){let r=isSqliteSnapshotStagingName(e.name),i=r?``:[s,e.name].filter(Boolean).join(`/`);if(t.cutoff!==void 0&&(!r&&![`openclaw`,`openclaw-state`,`openclaw-state/state`].includes(i)&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(i)||r&&s!==``&&s!==`openclaw`&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(s)))throw Error(`Unrecognized snapshot directory`);let a=inspect(n,d,i,c);p+=a.bytes,m=Math.max(m,a.newest)}else if(t.cutoff===void 0||a.isFile()&&(s===`openclaw-state/state`?/^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(e.name):!s&&(/^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(e.name)||e.name===`schema-discovery-ownership.json`||aa.test(e.name)||/^inspection-result-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.json$/u.test(e.name))))p+=a.size,c&&r.push(n);else throw Error(`Unrecognized snapshot artifact`)}}if(m>=d)throw Error(f);return{bytes:p,newest:m}}try{let{bytes:i}=inspect(e,t.cutoff??1/0);return{bytes:i,payload:r,release,retire:()=>{for(let e of n)e(!0)}}}catch(e){throw release(),e}}const oa=i(Symbol.for(`openclaw.sqliteSnapshotCleanup`),()=>({directories:/* @__PURE__ */ new Map,activeWork:/* @__PURE__ */ new Map,exitHandlerInstalled:!1,pendingSignalCleanup:void 0,signalCleanup:cleanupSnapshotOperations})),O=oa.directories,sa=oa.activeWork;function snapshotDirectory(e){let t=O.get(e);return t||(t={readers:/* @__PURE__ */ new Set},O.set(e,t)),t}function completeSnapshotDirectoryRemoval(e){return O.delete(e),!0}function cleanupSnapshotOperations(){return oa.pendingSignalCleanup??=(async()=>{let e=O.entries();for(;;){for(;sa.size>0;){for(let e of sa.values())e();await Promise.allSettled(sa.keys())}let t=e.next();if(t.done)break;let[n]=t.value;await removeTempDirectoryAsync(n,e=>emitSnapshotCleanupFailure({cleanupRoot:n,operation:`rm`,code:l(e)}))}})().finally(()=>{oa.pendingSignalCleanup=void 0}),oa.pendingSignalCleanup}function retainSnapshotWork(e,t=()=>{}){registerSnapshotCleanup(),sa.set(e,t);let release=()=>sa.delete(e);return e.then(release,release),e}function registerSnapshotTempDirectory(e,t){let n=snapshotDirectory(e);n.release=t??n.release,registerSnapshotCleanup()}function registerSnapshotCleanup(){oa.exitHandlerInstalled||(oa.exitHandlerInstalled=!0,Ve(()=>{for(let e of sa.values())e();if(sa.size===0)for(let e of O.keys())removeTempDirectory(e)})),Se(oa.signalCleanup)}function retainSnapshotTempDirectory(e){registerSnapshotTempDirectory(e);let t=snapshotDirectory(e);if(t.retirementStarted)throw new ht(`SQLite snapshot retirement has started`);let n=Symbol(`sqlite.snapshot.reader`);return t.readers.add(n),()=>t.readers.delete(n)}const ca={force:!0,maxRetries:3,recursive:!0,retryDelay:20};function emitSnapshotCleanupFailure(e,t){if(t)try{t(e);return}catch{}try{Ge({subsystem:`infra/sqlite-snapshot`}).warn({path:e.cleanupRoot,operation:e.operation,errorCode:e.code},`SQLite read-only snapshot cleanup failed. Check directory permissions and available storage before retrying.`)}catch{}}function assertSnapshotReadersRetired(e){if(e?.readers.size)throw new ht(`SQLite snapshot still belongs to an active reader`)}function prepareSnapshotRetirement(e,t){if(assertSnapshotReadersRetired(t),t?.releaseRetained)throw new ht(`SQLite snapshot requires asynchronous cleanup`);if(!(t?.retired||!t?.release&&!T.existsSync(E.join(e,ea[0]))))return t&&(t.retirementStarted=!0),beginSqliteSnapshotRetirement(e,{token:t?.release})}function*shrinkSnapshotPayload(e){let t=T.lstatSync(e,{throwIfNoEntry:!1});if(t?.isDirectory())for(let t of T.readdirSync(e))yield*shrinkSnapshotPayload(E.join(e,t));else if(t?.isFile()&&t.nlink>1)T.unlinkSync(e);else if(t?.isFile()&&t.nlink===1&&t.size>64*1024**2){let n=T.openSync(e,T.constants.O_RDWR|T.constants.O_NOFOLLOW);try{for(let e=t.size;e>64*1024**2;)e-=64*1024**2,yield{fd:n,size:e}}finally{T.closeSync(n)}}}async function shrinkSnapshotPayloadAsync(e){for(let{fd:t,size:n}of shrinkSnapshotPayload(e))await retainSnapshotWork(new Promise((e,r)=>{T.ftruncate(t,n,t=>t?r(t):e())}))}function*retireSqliteSnapshotPayload(e){for(let t of e.payload){On(t);for(let{fd:e,size:n}of shrinkSnapshotPayload(t))T.ftruncateSync(e,n),yield;T.rmSync(t,ca)}e.retire()}function removeTempDirectory(e,t){let n=O.get(e);n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{if(t){for(let e of retireSqliteSnapshotPayload(t));n=snapshotDirectory(e),n.release=void 0,n.retired=!0}else if(!n?.retired)for(let{fd:t,size:n}of shrinkSnapshotPayload(e))T.ftruncateSync(t,n);try{T.rmSync(e,ca)}catch(t){throw ft(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){return registerSnapshotTempDirectory(e),snapshotDirectory(e).cleanupFailure=n,t?.(n),!1}}async function removeTempDirectoryAsync(e,t){let n=O.get(e);if(n?.releaseRetained){let r=await startRemoveTempDirectory(e,t,n).result;return r&&O.delete(e),r}n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{for(let e of t?.payload??[])On(e),await shrinkSnapshotPayloadAsync(e),await retainSnapshotWork(T.promises.rm(e,ca));t?(t.retire(),n=snapshotDirectory(e),n.release=void 0,n.retired=!0):n?.retired||await shrinkSnapshotPayloadAsync(e);try{await retainSnapshotWork(T.promises.rm(e,ca))}catch(t){throw ft(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){return registerSnapshotTempDirectory(e),snapshotDirectory(e).cleanupFailure=n,t?.(n),!1}}function startRemoveTempDirectory(e,t,n=O.get(e)){if(n?.retiringRetained)return n.retiringRetained;let r,i=vn(()=>{if(!r||i.operation.read().status!==`pending`)return;r.service();let a=r.read();a.status!==`pending`&&(n&&(n.retiringRetained=void 0),a.status===`rejected`?(snapshotDirectory(e).cleanupFailure=a.error,t?.(a.error),i.resolve(!1)):i.resolve(completeSnapshotDirectoryRemoval(e)))});try{if(n&&(n.cleanupFailure=void 0),sealRetainedSnapshotTempDirectory(e),!n?.releaseRetained)throw new ht(`SQLite snapshot has no retained cleanup owner`);n.retiringRetained=i.operation,r=n.releaseRetained(),r.result.then(()=>i.operation.service(),()=>i.operation.service()),i.operation.service()}catch(r){snapshotDirectory(e).cleanupFailure=r,n&&(n.retiringRetained=void 0),t?.(r),i.resolve(!1)}return i.operation}function sealRetainedSnapshotTempDirectory(e,t){let n=O.get(e);if(!n?.releaseRetained)throw new ht(`SQLite snapshot has no retained cleanup owner`);if(t?.requireRequested&&!n.retirementStarted)throw new ht(`SQLite snapshot is still owned; cleanup has not been requested`);let r=[...O].filter(([t])=>be(e,t));for(let[,e]of r)assertSnapshotReadersRetired(e);for(let[,e]of r)e.retirementStarted=!0;let i=/* @__PURE__ */ new Set([...Rt().map(({location:e})=>e),..._n()]);for(let t of i)be(e,t)&&On(t)}function adoptPreparedLocation(e,t,n=!1,r){let i=t??E.dirname(e);registerSnapshotTempDirectory(i);let a=!0,s,c,u=!1,reportFailure=e=>{!n&&!u&&(u=!0,emitSnapshotCleanupFailure({cleanupRoot:i,operation:`rm`,code:l(e)},r))},complete=e=>{if(e)a=!1,O.delete(i);else if(n)throw new ht(`SQLite read-only worker snapshot cleanup failed: ${i}`,{cause:O.get(i)?.cleanupFailure});return e},startCleanup=()=>{if(c?.read().status===`pending`)return c;if(!a){let e=vn(()=>{});return e.resolve(complete(!0)),c=e.operation}return c=wn(startRemoveTempDirectory(i,reportFailure),complete)};return{location:e,cleanupRoot:i,cleanup:()=>s||c?.read().status===`pending`?n?complete(!1):!1:complete(!a||removeTempDirectory(i,reportFailure)),cleanupAsync:()=>O.get(i)?.releaseRetained||c?startCleanup().result:s||(a?(s=Promise.resolve().then(()=>removeTempDirectoryAsync(i,reportFailure)).then(complete).finally(()=>{s=void 0}),s):Promise.resolve(complete(!0))),startCleanup}}const la=/* @__PURE__ */ new Set([`--no-maglev`,`--maglev`,`--no-concurrent-sparkplug`,`--concurrent-sparkplug`]);function resolveForwardedNodeCompilerArgs(){return process.execArgv.filter(e=>la.has(e.replaceAll(`_`,`-`)))}const ua=i(Symbol.for(`openclaw.artifactPreservingStateReads`),()=>new D),da=i(Symbol.for(`openclaw.liveStateReads`),()=>new D);function isLiveStateRead(){return da.getStore()!==void 0}function isArtifactPreservingStateRead(e=`shared`,t){let n=ua.getStore();return!(!n||e!==`shared`&&!n.agentDatabases||t&&[...n.privateRoots].some(e=>Zr(e,t)))}const fa=i(Symbol.for(`openclaw.maintenanceLiveAuthorityReads`),()=>/* @__PURE__ */ new WeakMap);function allowsMaintenanceLiveAuthorityReads(e,t){return hasAdmittedMaintenanceLiveAuthorityReads(e,jr(t))}function hasAdmittedMaintenanceLiveAuthorityReads(e,t){for(let n=e;n;n=pa.parents.get(n))if(fa.get(n)?.has(t))return!0;return!1}function maintenanceOwnerHasSourceCustody(e,t){return e?.ownsSchemaMaintenance?(e.assertReadAdmission(),!allowsMaintenanceLiveAuthorityReads(e,t)):!1}function readCustodiedDrainedSqliteSource(e){if(!maintenanceOwnerHasSourceCustody(getOpenClawDatabaseMaintenanceScope(),e))return;let t=jr(e);if(!(T.existsSync(`${t}-journal`)||(T.statSync(`${t}-wal`,{throwIfNoEntry:!1})?.size??0)>0))return T.statSync(t,{bigint:!0})}const pa=i(Symbol.for(`openclaw.databaseMaintenanceResources`),()=>({current:new D,claims:/* @__PURE__ */ new WeakMap,parents:/* @__PURE__ */ new WeakMap}));function getOpenClawDatabaseMaintenanceScope(){return pa.current.getStore()?.scope}function isOpenClawDatabaseMaintenanceResourceOwned(e,t){return pa.claims.get(e)?.scope===t}function getOpenClawDatabaseMaintenanceResourceScope(e){return pa.claims.get(e)?.scope}function observeOpenClawDatabaseMaintenanceResource(e){if(!e)return;let t=pa.claims.get(e),n=getOpenClawDatabaseMaintenanceScope();if(!t)return;let r=commonMaintenanceAncestor(t.scope,n);r!==t.scope&&(t.scope.assertAdmission(),t.release(),pa.claims.delete(e),r&&r.own(e,t.phase,t.close))}function commonMaintenanceAncestor(e,t){let n=/* @__PURE__ */ new Set;for(let t=e;t;t=pa.parents.get(t))n.add(t);for(let e=t;e;e=pa.parents.get(e))if(n.has(e))return e}const ma=new we(Symbol(`sqliteReadOnlyWorkerScope`)),ha=ei(`openclaw.memory.critical`);function createStateWorkerMemoryPressureSubscription(e,t){let n=!1,onPressure=e=>t(e===!0);return()=>{let t=e();t!==n&&(n=t,t?ha.subscribe(onPressure):ha.unsubscribe(onPressure))}}const ga={"startupMetadata.readCurrent":`retire-after-result`,"startupMetadata.rollbackRecoveryRequired":`retire-after-result`};function sqliteReadOnlyOperationRequiresProcessRetirement(e){return e in ga}function normalizeExecutableToken(t){let n=E.win32.basename(t),r=E.posix.basename(t),i=n.length<r.length?n:r;return e(i).replace(/\.(?:exe|cmd|bat|com)$/,``)}const _a=/* @__PURE__ */ new Set([`-lc`,`-c`,`--command`,`--commands`,`--cmdline`]);[..._a];function expandPowerShellSwitchPrefixForms(e,t){let n=[];for(let r=t.length;r<=e.length;r+=1){let t=e.slice(0,r);n.push(`-${t}`,`--${t}`,`/${t}`)}return n}function expandPowerShellSwitchForms(t){return t.flatMap(t=>{let n=e(t);return[`-${n}`,`--${n}`,`/${n}`]})}const va=[...expandPowerShellSwitchPrefixForms(`command`,`c`),...expandPowerShellSwitchPrefixForms(`commandwithargs`,`cwa`),...expandPowerShellSwitchForms([`cwa`])],ya=expandPowerShellSwitchPrefixForms(`file`,`f`),ba=new Set(ya);new Set(expandPowerShellSwitchPrefixForms(`noprofile`,`nop`)),[...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchForms([`ea`]),...expandPowerShellSwitchPrefixForms(`interactive`,`i`),...expandPowerShellSwitchPrefixForms(`login`,`l`),...expandPowerShellSwitchPrefixForms(`namedpipeservermode`,`nam`),...expandPowerShellSwitchPrefixForms(`noexit`,`noe`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchForms([`pscf`]),...expandPowerShellSwitchPrefixForms(`servermode`,`s`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`socketservermode`,`so`),...expandPowerShellSwitchPrefixForms(`sshservermode`,`ssh`),...expandPowerShellSwitchPrefixForms(`v2socketservermode`,`v2so`)];const xa=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`encodedcommand`,`e`),...expandPowerShellSwitchPrefixForms(`ec`,`e`)]),Sa=/* @__PURE__ */ new Set([...va,...ya,...xa]),Ca=new Set(va),wa=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchPrefixForms(`executionpolicy`,`ex`),...expandPowerShellSwitchPrefixForms(`inputformat`,`inp`),...expandPowerShellSwitchPrefixForms(`outputformat`,`o`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`token`,`to`),...expandPowerShellSwitchPrefixForms(`utctimestamp`,`utc`),...expandPowerShellSwitchPrefixForms(`version`,`v`),...expandPowerShellSwitchPrefixForms(`windowstyle`,`w`),...expandPowerShellSwitchPrefixForms(`workingdirectory`,`w`),...expandPowerShellSwitchForms([`ea`,`ep`,`if`,`of`,`pscf`,`wd`])]),Ta=/* @__PURE__ */ new Set([`--init-file`,`--rcfile`]);function countSeparateValueOptionChars(e,t){let n=0;for(let r=1;r<e.length;r+=1){let i=e[r];(i===`o`||i===`O`&&t!==`zsh`)&&(n+=1)}return n}function parseCombinedCommandFlag(e,t){if(e.length<2||e[0]!==`-`||e[1]===`-`)return null;let n=e.slice(1),r=n.indexOf(`c`);if(r===-1||n.includes(`-`))return null;let i=n.slice(r+1);return i&&!/^[A-Za-z]+$/.test(i)?{attachedCommand:i,separateValueCount:0}:{attachedCommand:null,separateValueCount:countSeparateValueOptionChars(e,t)}}function combinedSeparateValueOptionCount(e,t){return e.length<2||e[0]!==`-`&&e[0]!==`+`||e[1]===`-`||e.slice(1).includes(`-`)?0:countSeparateValueOptionChars(e,t)}function advancePosixInlineOptionScan(e,t){let n=combinedSeparateValueOptionCount(e,t);return n>0?1+n:Ta.has(e)?2:1}function isPowerShellOptionToken(e){return e.startsWith(`-`)||/^\/[A-Za-z][A-Za-z0-9]*$/.test(e)}function resolveInlineCommandMatch(t,n,r={}){let i=normalizeExecutableToken(t[0]??``);for(let a=1;a<t.length;){let s=t[a]?.trim();if(!s){a+=1;continue}let c=e(s);if(c===`--`)break;let l=r.allowCombinedC?s:c,u=n.has(l),d=!u&&r.allowCombinedC?parseCombinedCommandFlag(s,i):null;if(u||d){if(d&&d.attachedCommand!==null)return{command:d.attachedCommand.trim()||null,valueTokenIndex:a};let e=a+1+(d?.separateValueCount??0),n=!d&&e>=t.length?null:e;return{command:(u&&r.restValueFlags?.has(l)?t.slice(a+1).map(e=>e.trim()).join(` `).trim():t[e]?.trim())||null,valueTokenIndex:n}}if(r.valueOptions?.has(c)){a+=2;continue}let f=r.isOptionToken?.(s)??(s.startsWith(`-`)||s.startsWith(`+`));if(r.stopAtFirstNonOption&&!f||r.allowCombinedC&&!s.startsWith(`-`)&&!s.startsWith(`+`))break;a+=r.allowCombinedC?advancePosixInlineOptionScan(s,i):1}return{command:null,valueTokenIndex:null}}function resolvePowerShellInlineCommandMatch(e){return resolveInlineCommandMatch(e,Sa,{isOptionToken:isPowerShellOptionToken,restValueFlags:Ca,stopAtFirstNonOption:!0,valueOptions:wa})}function isPowerShellInlineFileCommandFlag(t){return ba.has(e(t))}const Ea=i(Symbol.for(`openclaw.childProcessSpawnCounts`),()=>({counts:/* @__PURE__ */ new Map,sampledAt:performance.now()})),Da=/^(node|bun|git|ps|pgrep|lsof|sh|bash|zsh|cmd|powershell|pwsh|npm|pnpm|python|python3|uv|ssh|openclaw)$/,Oa=i(Symbol.for(`openclaw.gitSpawnOperation`),()=>new D),ka=i(Symbol.for(`openclaw.childSpawnOperation`),()=>new D);function unscopedProcessOperation(e,t,n){if(n[0]===`--version`||n[0]===`-v`&&(e===`node`||e===`bun`||t===`gh`))return`unscoped.version`;if(e===`powershell`||e===`pwsh`){let e=[t,...n],{command:r,valueTokenIndex:i}=resolvePowerShellInlineCommandMatch(e);return r!==null&&i!==null&&!isPowerShellInlineFileCommandFlag(e[i-1]??``)?`unscoped.shell-command`:`unscoped.shell`}return/^(sh|bash|zsh)$/.test(e)?resolveInlineCommandMatch([t,...n],_a,{allowCombinedC:!0}).command===null?`unscoped.shell`:`unscoped.shell-command`:e===`cmd`?n.some(e=>/^-[a-z]*c$/.test(e)||/^\/(?:c|k)$/i.test(e))?`unscoped.shell-command`:`unscoped.shell`:e===`node`||e===`bun`?`unscoped.runtime`:e===`other`&&/^(gh|docker|podman|which|uname|sw_vers|sysctl|curl|tar)$/.test(t)?`unscoped.${t}`:`unscoped.command`}function unscopedGitOperation(e){let t=0;for(;t<e.length;){let n=e[t];if([`-C`,`-c`,`--git-dir`,`--work-tree`,`--namespace`,`--config-env`].includes(n))t+=2;else if(/^--(?:git-dir|work-tree|namespace|config-env|attr-source)=/u.test(n))t++;else if([`--no-pager`,`--no-optional-locks`,`--no-lazy-fetch`,`--literal-pathspecs`,`--bare`].includes(n))t++;else break}let n=e[t]??``;return/^(config|rev-parse|status|diff|ls-files|rev-list|merge-base|cat-file|symbolic-ref|for-each-ref|show-ref|remote|log|show|hash-object|update-ref|worktree|branch|fetch|clone|init|checkout|read-tree|write-tree|commit-tree|pack-objects|index-pack|maintenance|multi-pack-index|gc|fast-import|add|commit|push|reset|clean|merge|tag|describe|switch|ls-tree|update-index|check-ref-format|diff-tree|diff-index|diff-files|sparse-checkout|checkout-index|check-attr|mktree|var|apply|fsck|ls-remote|rebase|reflog)$/u.test(n)?`unscoped.${n}`:n===`--version`||n===`version`?`unscoped.version`:`unscoped.other`}function prepareChildProcessSpawnRecorder(e,t=[],n){if(!xe())return;let r=re(e,t),i=r?t.slice(3):t,a=E.win32.basename(r??e).toLowerCase().replace(/\.(exe|cmd)$/,``),s=Da.test(a)?a:`other`,c=s===`git`?Oa.getStore()??ka.getStore()??unscopedGitOperation(i):n??ka.getStore()??unscopedProcessOperation(s,a,i),l=`${s}:${c}`;return()=>{if(xe()){let e=Ea.counts.get(l);Ea.counts.set(l,{family:s,operation:c,count:(e?.count??0)+1})}}}function recordChildProcessSpawn(e,t,n,r=[]){let i=prepareChildProcessSpawnRecorder(e,r,n);i&&t.once(`spawn`,i)}function ok(e){return{ok:!0,value:e}}function err(e){return{ok:!1,error:e}}const Aa=/^[a-z0-9][a-z0-9_-]{0,63}$/i,ja=/[^a-z0-9_-]+/g,Ma=/^-+/,Na=/-+$/;function normalizeAgentId(e){let t=normalizeAgentIdStrict(e);return t.ok?t.value:`main`}function normalizeAgentIdStrict(e){let t=(e??``).trim(),n=t.toLowerCase();if(Aa.test(t))return ok(n);let r=n.replace(ja,`-`).replace(Ma,``).replace(Na,``).slice(0,64);return r?ok(r):err(`unrepresentable`)}const Pa=`incognito-openclaw-agent.sqlite`;(/* @__PURE__ */ new Map()).keys();const Fa=new Ne(64);function resolveDatabasePath(e={}){return e.path===void 0?resolveOpenClawStateSqlitePath(e.env??process.env):wt(E.resolve(e.path))}function resolveOpenClawStateSqliteDir(e=process.env){return E.dirname(resolveOpenClawStateSqlitePath(e))}function resolveOpenClawStateSqlitePath(e=process.env){let t=ze(e),n=Fa.peek(t);if(n!==void 0)return n;let r=wt(E.join(t,`state`,`openclaw.sqlite`));return Fa.set(t,r),r}function resolveOpenClawStateDirForDatabasePath(e){let t=E.dirname(E.resolve(e));return E.basename(t)===`state`?E.dirname(t):t}function resolveQuarantineStorePath(e){return E.join(resolveOpenClawStateSqliteDir(e),`openclaw-quarantine.sqlite`)}const Ia=i(Symbol.for(`openclaw.agentCreationClaim`),()=>new D),La=i(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map);function getActiveAgentCreationClaim(e,t){let n=Ia.getStore();if(n&&n.kind===`host`&&n.isActive()&&n.agentId===normalizeAgentId(e)&&n.statePath===E.resolve(t))return n}function reserveAgentCreationClaimAdmission(e,t,n){let r=getActiveAgentCreationClaim(t.agentId,resolveOpenClawStateSqlitePath(t.env??process.env));if(r)return La.set(e,r),r.registerClose(async()=>{La.get(e)===r&&(await n(),La.delete(e))}),()=>{La.delete(e)}}const Ra=i(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class extends Error{});i(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}}),i(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class extends Error{constructor(){super(`Invalid agent schema admission receipt`)}}),i(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class extends Error{constructor(e){super(Mr(e),{cause:e})}});const za=i(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new D);i(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map),i(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map);function captureAgentDeletionResourceOwner(e){let t=za.getStore();if(t?.ownsDatabase&&(e(t)||t.canonicalPath&&e({agentId:t.agentId,path:t.canonicalPath})))return t.assertCurrentHost(),t}const Ba=`STATE_DATABASE_READ_ADMISSION_INVALIDATED`;var StateDatabaseReadAdmissionInvalidatedError=class extends Error{constructor(...e){super(...e),this.code=Ba}};function isStateDatabaseReadAdmissionInvalidatedError(e){return l(e)===Ba}function createOpenClawStateDatabaseAsyncLifecycle(){let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=Promise.resolve(),proofFor=()=>{let e=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return new BigInt64Array(e)[0]=-1n,e},generationFor=e=>{let t=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return{integrity:{identity:e,lifetime:{revision:new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT),epoch:0n},revision:t,epoch:0n,proof:proofFor()}}},publishCreatedIdentity=(e,n)=>{Atomics.add(new BigInt64Array(e.generation.integrity.revision),0,1n),Atomics.add(new BigInt64Array(e.generation.integrity.lifetime.revision),0,1n),t.delete(e.identity.key),e.identity=n,e.generation.integrity.identity=n,t.set(n.key,e)},known=e=>n.get(e)??n.get(resolveDatabasePath({path:e})),bindPath=(e,t)=>{e.paths.add(t),n.has(t)||n.set(t,e)},overlaps=(e,t)=>{if(e.identity.key===t.identity.key)return!0;for(let n of e.paths)if(t.paths.has(n))return!0;return!1},isSealed=e=>{if(r.size===0)return!1;for(let t of r)if(t.record===void 0||overlaps(t.record,e))return!0;return!1},hasCloseCustody=e=>isSealed(e)||i.has(e),assertOpen=e=>{if(isSealed(e))throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission is closed`)},findPhysicalRecord=e=>{let r=t.get(e.key);if(!r||!e.key.startsWith(`file:`)||hasCloseCustody(r))return r;for(let t of st(r.paths,e))r.admissions.delete(t),r.paths.delete(t),n.get(t)===r&&n.delete(t);if(r.paths.size>0)return r.paths.has(r.identity.canonicalPath)||(r.identity=e,r.generation.integrity.identity=e),r;invalidate(r),forget(r)},resolve=(e,r)=>{let i=n.get(e);if(i&&(!r||i.identity.key===r.key))return!r&&i.identity.key.startsWith(`path:`)?resolve(e,xt(e)):i;let a=r??xt(e),s=findPhysicalRecord(a);return!s&&a.key.startsWith(`file:`)&&(s=[...t.values()].find(e=>{if(!e.identity.key.startsWith(`path:`))return!1;try{return xt(e.identity.canonicalPath).key===a.key}catch{return!1}}),s&&publishCreatedIdentity(s,a)),s||(s={coordinationKey:a.key,identity:a,paths:/* @__PURE__ */ new Set,generation:generationFor(a),admissions:/* @__PURE__ */ new Map},t.set(a.key,s)),bindPath(s,e),bindPath(s,a.canonicalPath),s},resolveForNative=e=>{let t=resolveDatabasePath({path:e}),r=n.get(t);if(r)return r;let i=dn(t);return i?resolve(t,i):void 0},invalidate=e=>{for(let n of e?[e]:t.values())Atomics.store(new BigInt64Array(n.generation.integrity.revision),0,-1n),Atomics.store(new BigInt64Array(n.generation.integrity.lifetime.revision),0,-1n),n.generation=generationFor(n.identity),n.admissions.clear()},seal=e=>{invalidate(e);let t={record:e};return r.add(t),t},release=e=>{e.seal&&=(r.delete(e.seal),void 0)},forget=e=>{if(!hasCloseCustody(e)&&t.get(e.identity.key)===e){t.delete(e.identity.key);for(let r of e.paths)if(n.get(r)===e){n.delete(r);for(let e of t.values())if(e.paths.has(r)){n.set(r,e);break}}}},retireReplacedRecord=e=>{let t=i.get(e);t?(t.superseded=!0,t.seal??=seal(e)):invalidate(e),forget(e)},captureRecord=(e,n)=>{let r=e.admissions.get(n);if(r)return r;let i=e.generation,a=Object.freeze({databasePath:n,coordinationKey:e.coordinationKey,get identity(){return e.identity},captureIntegrity(){a.assertCurrent();let t=i.integrity,n=Atomics.load(new BigInt64Array(t.revision),0),r=Atomics.load(new BigInt64Array(t.lifetime.revision),0);return(n!==t.epoch||r!==t.lifetime.epoch)&&(i.integrity={...t,identity:e.identity,lifetime:{revision:t.lifetime.revision,epoch:r},epoch:n,proof:proofFor()}),i.integrity},assertCurrent(){if(assertOpen(e),t.get(e.identity.key)!==e||e.generation!==i||e.admissions.get(n)!==a)throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission changed`)}});return e.admissions.set(n,a),a};return{identity(e){return known(e)?.identity??dn(e)},knownIdentity(e){return known(e)?.identity},integrity(e){let t=resolveForNative(e);return t&&!isSealed(t)?captureRecord(t,resolveDatabasePath({path:e})).captureIntegrity?.():void 0},publish(e,r){let i=resolveDatabasePath({path:e}),a=r??xt(i),s=n.get(i),c=r&&s?.identity.key===a.key?t.get(a.key):findPhysicalRecord(a);return s&&s.identity.key!==a.key&&(s.identity.key.startsWith(`path:`)&&!c?(publishCreatedIdentity(s,a),c=s):retireReplacedRecord(s)),c||=resolve(i,a),bindPath(c,i),bindPath(c,r?c.identity.canonicalPath:a.canonicalPath),{identity:a,admission:captureRecord(c,i)}},async retireChangedAdmission(e){e.assertCurrent();let n=t.get(e.identity.key),r=await hn(e.databasePath);e.assertCurrent(),n&&n.identity.key!==r.key&&retireReplacedRecord(n)},invalidate(e){if(e===void 0)invalidate();else{let t=known(e);t&&invalidate(t)}},register(t){e.add(t);for(let e of i.values())e.queue?.add(t);return()=>{e.delete(t)}},capture(e,t){let r=n.get(e),i=r?.admissions.get(e);if(r&&i&&r.identity.key.startsWith(`file:`))return i.assertCurrent(),i;let a=resolveDatabasePath({path:e}),s=resolve(a,t);return assertOpen(s),captureRecord(s,a)},holdExclusion(e){let n=resolve(resolveDatabasePath({path:e})),i=seal(n);return()=>{r.delete(i);for(let e of t.values())overlaps(n,e)&&forget(e)}},close(n,r){let s=n===void 0?void 0:resolveForNative(n);if(n!==void 0&&!s)return Promise.resolve(r());let c=i.get(s);if(c?.pending)return c.pending;c||(c={retained:/* @__PURE__ */ new Set},i.set(s,c)),c.seal??=seal(s);let l=c,u=a.then(async()=>{let n=/* @__PURE__ */ new Set([...e,...l.retained]);for(let e of i.values())for(let t of e.retained)n.add(t);l.queue=n;let a=[];for(;l.queue.size;){let e=[...l.queue].filter(e=>e.phase!==`after-resources`);if(!e.length&&a.length){for(let e of l.queue)l.retained.add(e);break}let t=e.length?e:[...l.queue];for(let e of t)l.queue.delete(e);await Promise.all(t.map(async e=>{try{let t=s?.identity;t&&e.admission&&t.key!==e.admission.identity.key||await e.close(t),l.retained.delete(e)}catch(t){l.retained.add(e),a.push(t)}}))}a.length&&!l.superseded&&release(l),it(a,`OpenClaw state resource drainage failed`);let c=await r(s?.identity);if(i.delete(s),release(l),s===void 0){for(let[e,t]of i)t.pending||(i.delete(e),release(t));for(let e of t.values())forget(e)}else forget(s);return c}).finally(()=>{l.queue=void 0});return l.pending=u,a=u.then(()=>void 0,()=>void 0),u.catch(()=>{l.pending=void 0}),u}}}const k=i(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map}));Lt(async(e,t)=>{let n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...k.active,...k.closing.keys()])].filter(n=>!t?.has(E.resolve(n.path))&&e.some(e=>Yn(e,n.path))).map(e=>closeAgentDatabaseResource(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw AggregateError(n,`Agent database resource cleanup failed`)});function matchesAgentDatabaseClose(e,t){return(e.path===void 0||e.path===t.path||t.ownership===`unresolved`&&Yn(t,e.path))&&(e.rootPath===void 0||be(e.rootPath,t.path)||t.ownership===`unresolved`&&Yn(t,e.rootPath))&&(e.agentId===void 0||t.ownership===`unresolved`||e.agentId===t.agentId)}function registerOpenClawAgentDatabaseReadCandidateResource(e){return registerAgentDatabaseResource({...e,ownership:`unresolved`})}function registerAgentDatabaseResource(e,t){let n={...e,path:E.resolve(e.path)};n.cleanupOwner=captureAgentDeletionResourceOwner(e=>matchesAgentDatabaseClose(e,n)),assertAgentDatabaseResourceAdmission(n);let r=t&&n.ownership===`known`?reserveAgentCreationClaimAdmission(n,t,()=>closeAgentDatabaseResource(n)):void 0,unregister=()=>{k.active.delete(n),r?.(),k.onRelease?.(n)};return getOpenClawDatabaseMaintenanceScope()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n)),k.active.add(n),unregister}function assertAgentDatabaseResourceAdmission(e){if([...k.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...k.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&Yn(t,e.path)||e.ownership===`unresolved`&&Yn(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new Ra(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,t){if(e.ownership===`known`&&e.closeSync){k.closing.set(e,void 0);try{return e.revoke(),e.closeSync(),k.active.delete(e),k.closing.delete(e),k.onRelease?.(e),Promise.resolve()}catch(n){t&&t(e.path,n);let r=Promise.reject(s(n,`Agent database cleanup failed`));return r.catch(()=>{}),r}}let n=k.closing.get(e);return n||(n=Promise.resolve().then(()=>e.close()),k.closing.set(e,n),n.then(()=>{k.active.delete(e),k.closing.delete(e),k.onRelease?.(e)},()=>{k.closing.set(e,void 0)}).catch(()=>{})),t&&n.catch(n=>t(e.path,n)).catch(()=>{}),e.revoke(),n}function captureSqliteAuthSchema(e,t){if(gr(e)?.key!==t)return;let n=tt(e,Qi,()=>void 0);if(!n)return;let kind=e=>n.tables.has(e)?`table`:n.views.has(e)||n.indexes.has(e)||n.triggers.has(e)?`other`:`missing`;return{userVersion:n.userVersion,store:kind(`auth_profile_store`),state:kind(`auth_profile_state`)}}function isJsonTransferField(e){return f(e)?e.kind===`object`||e.kind===`array`||e.kind===`end`||(e.kind===`key`||e.kind===`value`)&&(e.append===void 0||e.append===!0&&typeof e.value==`string`)&&(typeof e.value==`string`||e.kind===`value`&&(e.value===null||typeof e.value==`boolean`||typeof e.value==`number`)):!1}function createJsonFieldReceiver(){let e,t=!1,n=[],r,write=r=>{let i=n.at(-1);if(i){if(i.key===void 0)throw Error(`JSON field has no property key`);Object.defineProperty(i.container,i.key,{value:r,writable:!0,enumerable:!0,configurable:!0}),i.key=void 0}else{if(t)throw Error(`JSON transfer has more than one root`);e=r,t=!0}},flush=()=>{if(!r)return;let e=r.chunks.join(``);if(r.kind===`key`){let t=n.at(-1);if(!t||t.key!==void 0)throw Error(`JSON property key has no value or container`);t.key=e}else write(e);r=void 0};return{accept(e){if(!isJsonTransferField(e))throw Error(`Invalid JSON transfer field`);if(e.kind===`key`||e.kind===`value`){if(e.append){if(!r||r.kind!==e.kind||typeof e.value!=`string`)throw Error(`Invalid JSON string continuation`);r.chunks.push(e.value);return}flush(),typeof e.value==`string`?r={kind:e.kind,chunks:[e.value]}:write(e.value)}else if(flush(),e.kind===`end`){let e=n.pop();if(!e||e.key!==void 0)throw Error(`JSON container ended with an incomplete field`)}else{let t=e.kind===`array`?[]:{};write(t),n.push({container:t})}},finish(){if(flush(),n.length)throw Error(`JSON transfer ended with an incomplete container`);return e}}}function createSqliteWorkerTransferOwner(){let e=0,t,cleanup=e=>{let t=[];for(let[n,r]of[[`iteratorClosed`,()=>e.iterator.return?.()],[`cleaned`,()=>e.cleanup?.()]])if(!e[n])try{r(),e[n]=!0}catch(e){t.push(e)}it(t,`SQLite read transfer cleanup failed`)},cancel=()=>{t&&=(cleanup(t),void 0)},requireTransfer=e=>{if(!t||t.id!==e)throw Error(`SQLite read transfer is no longer active`);return t};return{start(n,r){if(t)throw Error(`The preceding SQLite read transfer was not released`);return t={id:++e,iterator:n,cleanup:r.cleanup,iteratorClosed:!1,cleaned:!1,counts:new Map(r.kinds.map(e=>[e,0])),sequence:0,finished:!1},{id:t.id,kinds:[...t.counts.keys()]}},next(e){let t=requireTransfer(e);if(t.finished)throw Error(`SQLite read transfer has already reached its end`);if(t.record&&t.record.offset===t.record.bytes.byteLength&&(t.record=void 0),!t.record){let n=t.iterator.next();if(n.done)return cleanup(t),t.finished=!0,{id:e,sequence:t.sequence++,done:!0,counts:[...t.counts]};let{kind:r}=n.value,i=t.counts.get(r);if(i===void 0)throw Error(`SQLite read transfer returned an unexpected record kind`);t.record={kind:r,bytes:`serialized`in n.value?n.value.serialized:pi(n.value.value),offset:0},t.counts.set(r,i+1)}let n=t.record,r=n.offset,i=Math.min(n.bytes.byteLength,r+8388608);return n.offset=i,{id:e,sequence:t.sequence++,done:!1,kind:n.kind,recordBytes:n.bytes.byteLength,offset:r,recordDone:i===n.bytes.byteLength,bytes:new Uint8Array(n.bytes.subarray(r,i))}},end(e){if(!requireTransfer(e).finished)throw Error(`SQLite read transfer ended before its complete result`);cancel()},cancel,close:cancel}}function createSqliteWorkerTransferReceiver(e,t){let n=new Map(e.kinds.map(e=>[e,0])),r=0,i=!1,a;return{accept(s){try{if(i||s.id!==e.id||s.sequence!==r++)throw Error(`SQLite read transfer frame is out of order`);if(s.done){if(a||s.counts.length!==n.size||s.counts.some(([e,t])=>n.get(e)!==t)||new Set(s.counts.map(([e])=>e)).size!==n.size)throw Error(`SQLite read transfer ended with an incomplete result`);return i=!0,s.counts}let c=n.get(s.kind);if(c===void 0||!Number.isSafeInteger(s.recordBytes)||s.recordBytes<1||!Number.isSafeInteger(s.offset)||s.offset<0||s.bytes.byteLength<1||s.bytes.byteLength>8388608)throw Error(`SQLite read transfer returned an invalid frame`);if(!a){if(s.offset!==0)throw Error(`SQLite read transfer omitted the start of a record`);a={kind:s.kind,bytes:s.recordDone?s.bytes:new Uint8Array(s.recordBytes),offset:0}}let l=s.offset+s.bytes.byteLength;if(a.kind!==s.kind||a.bytes.byteLength!==s.recordBytes||a.offset!==s.offset||l>s.recordBytes||s.recordDone!==(l===s.recordBytes))throw Error(`SQLite read transfer returned a discontinuous record`);if(a.bytes!==s.bytes&&a.bytes.set(s.bytes,s.offset),a.offset=l,s.recordDone){let e=fi(a.bytes),r=a.kind;a=void 0,t({kind:r,value:e}),n.set(r,c+1)}return}catch(e){throw a=void 0,i=!0,e}}}}function decodeFrame(e,t){if(e.done)return e;if(e.bytes.length>11184812)throw Error(`Invalid ${t} transfer bytes`);let n=Buffer.from(e.bytes,`base64`);if(n.toString(`base64`)!==e.bytes)throw Error(`Invalid ${t} transfer encoding`);return{...e,bytes:n}}function createSqliteReadOnlyTransferReceiver(e){let t,n,r=!1,i=!1;return{accept(a){if(i)throw Error(`Invalid ${e.label} transfer response`);if(a.type===`start`&&!t){let r=a.handle;if(!Number.isSafeInteger(r.id)||r.id<1||r.kinds.length!==e.kinds.length||r.kinds.some((t,n)=>t!==e.kinds[n]))throw Error(`Invalid ${e.label} transfer handle`);return n=r.id,t=createSqliteWorkerTransferReceiver({id:n,kinds:e.kinds},({kind:t,value:n})=>e.acceptRecord(t,n)),{request:{type:`next`,transferId:n}}}if(!t||n===void 0)throw Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer has not started`);if(a.type===`frame`&&!r){let i=decodeFrame(a.frame,e.label);if(!i.done&&e.maxRecordBytes&&i.recordBytes>e.maxRecordBytes)throw Error(`${e.label} transfer record exceeds its bound`);let s=t.accept(i);if(s){if(s.length!==e.kinds.length||s.some(([,e])=>e<1))throw Error(`Incomplete ${e.label} transfer result`);r=!0}return{request:{type:r?`end`:`next`,transferId:n}}}if(a.type===`complete`&&r)return i=!0,{value:e.readResult()};throw Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer response is out of order`)}}}function createSqliteAuthTransferReceiver(){let e=createJsonFieldReceiver();return createSqliteReadOnlyTransferReceiver({kinds:[`fields`],label:`auth profile`,maxRecordBytes:65536,acceptRecord(t,n){if(!Array.isArray(n))throw Error(`Invalid auth profile field batch`);for(let t of n)e.accept(t)},readResult(){let t=e.finish();if(!f(t)||!(`store`in t)||!(`state`in t)||typeof t.cacheable!=`boolean`)throw Error(`Invalid auth profile transfer rows`);return{store:t.store,state:t.state,cacheable:t.cacheable}}})}function createSqliteOperationTransferReceiver(e){let t;return createSqliteReadOnlyTransferReceiver({kinds:[`result`],label:`SQLite operation`,acceptRecord(n,r){if(t||!f(r)||r.operation!==e||!(`value`in r))throw Error(`SQLite read-only worker returned a different or duplicate operation`);t={operation:e,value:r.value}},readResult(){if(!t)throw Error(`SQLite read-only worker returned no operation`);return t}})}const Va=/* @__PURE__ */ new WeakSet;function markPrivateDirectoryCreationRefused(e){return typeof e==`object`&&e&&Va.add(e),e}function isPrivateDirectoryCreationRefused(e){return typeof e==`object`&&!!e&&Va.has(e)}var SqliteSnapshotCapacityError=class extends Error{constructor(e,t){super(e,t),this.name=`SqliteSnapshotCapacityError`}};function hasSqliteSnapshotCapacityCode(e){let{code:t,errcode:n}=e;return t===`ENOSPC`||t===`EDQUOT`||n===13}function isSqliteSnapshotStagingMode(e){return e===`staging-create`||e===`staging-create-legacy`||e===`staging-reconcile`||e===`staging-retire`}var SqliteReadOnlyInspectionContentionError=class extends Error{};function sqliteReadOnlyWorkerRequestArgs(e,t){let n=[t.mode,E.resolve(e)];if(t.mode===`task-delivery-recovery`)return[...n,E.resolve(t.recoveryDirectory),E.resolve(t.sourcePath)];let r=t.stagingRoot&&E.resolve(t.stagingRoot);if(t.mode===`private-fork`)return[...n,r??``,JSON.stringify(t.family)];let i=t.mode===`auth-profile-rows`||t.mode===`operation`?void 0:t.expectedSourceIdentity;if(i!==void 0){if(t.mode!==`sync`&&t.mode!==`staged-sync`&&t.mode!==`metadata`)throw Error(`SQLite source identity is supported only for sync or metadata snapshots`);n.push(r??``,JSON.stringify(cn(i)))}else r&&n.push(r);return n}function isSqliteReadOnlyWorkerResult(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:`ok`in e&&e.ok===!1&&`message`in e&&typeof e.message==`string`?Object.keys(e).length===2||Object.keys(e).length===3&&`errcode`in e&&typeof e.errcode==`number`&&Number.isInteger(e.errcode)&&e.errcode>=0&&e.errcode<=2147483647:Object.keys(e).length!==2||!(`ok`in e)?!1:e.ok===!0&&`engine`in e&&f(e.engine)&&(e.engine.engine===`sqlite`||e.engine.engine===`postgres`&&typeof e.engine.storeId==`string`&&typeof e.engine.namespace==`string`)||e.ok===!0&&`reclamation`in e&&f(e.reclamation)&&[e.reclamation.removed,e.reclamation.bytes,e.reclamation.skipped].every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0)||e.ok===!0&&`hasExistingData`in e&&typeof e.hasExistingData==`boolean`||e.ok===!0&&`location`in e&&typeof e.location==`string`||e.ok===!0&&`contentVersion`in e&&typeof e.contentVersion==`string`&&/^(?:[a-f0-9]{64})?$/.test(e.contentVersion)||e.ok===!0&&`generation`in e&&typeof e.generation==`string`||e.ok===!0&&`taskDeliveryRecovery`in e&&f(e.taskDeliveryRecovery)&&Object.keys(e.taskDeliveryRecovery).length===2&&typeof e.taskDeliveryRecovery.count==`number`&&Number.isSafeInteger(e.taskDeliveryRecovery.count)&&e.taskDeliveryRecovery.count>0&&typeof e.taskDeliveryRecovery.payloadSha256==`string`&&/^[a-f0-9]{64}$/u.test(e.taskDeliveryRecovery.payloadSha256)}function createSqliteReadOnlyWorkerError(e,t,n){let r=Xr(ke(t.trim(),-4e3));return Error(`SQLite read-only worker ${e}${r?`\nstderr (tail): ${r}`:``}`,n)}function parseSqliteReadOnlyWorkerResult(e,t){if(!e.trim())throw createSqliteReadOnlyWorkerError(`returned no JSON result`,t);let n;try{n=JSON.parse(e)}catch{throw createSqliteReadOnlyWorkerError(`returned invalid JSON`,t)}if(!isSqliteReadOnlyWorkerResult(n))throw createSqliteReadOnlyWorkerError(`returned an invalid result`,t);return n}function readSqliteReadOnlyWorkerValue(e,t){if(e.kind===`launch-failed`)throw e.error;let n;try{n=parseSqliteReadOnlyWorkerResult(e.stdout,e.stderr)}catch(t){throw e.failure?createSqliteReadOnlyWorkerError(e.failure,e.stderr,{cause:e.cause}):t}if(e.status!==0||e.failure||!n.ok){let r=!n.ok&&(e.status===0||e.status===1)&&n.message.startsWith(`SQLite snapshot capacity unavailable: `),i=n.ok?e.failure??`exited with code ${e.status}`:r?n.message.slice(38):n.message,a=!n.ok&&i.startsWith(`Retryable SQLite inspection contention: `),s=a?i.slice(40):i,c=e.failure===void 0&&!n.ok&&(t===`staging-create`||t===`staging-create-legacy`)&&s.startsWith(`SQLite snapshot directory creation refused: `),l=createSqliteReadOnlyWorkerError(c?s.slice(44):s,e.stderr,{cause:e.cause});if(n.ok||n.errcode===void 0||t!==`backup-engine`&&t!==`backup-engine-preserving`&&t!==`state-sqlite-populated`||e.status!==0&&e.status!==1||Object.assign(l,{errcode:n.errcode}),r)throw new SqliteSnapshotCapacityError(l.message,{cause:e.cause});if(a){let e=new SqliteReadOnlyInspectionContentionError(l.message);throw c?markPrivateDirectoryCreationRefused(e):e}throw l}if((t===`sync`||t===`private-fork`||t===`async`||t===`staged-sync`||t===`staged-async`||t===`metadata`||t===`consolidated`||isSqliteSnapshotStagingMode(t))&&`location`in n)return n.location;if(t===`staging-sweep`&&`reclamation`in n)return n.reclamation;if((t===`backup-engine`||t===`backup-engine-preserving`)&&`engine`in n)return n.engine;if(t===`state-sqlite-populated`&&`hasExistingData`in n)return n.hasExistingData;if(t===`content-version`&&`contentVersion`in n)return n.contentVersion;if((t===`file-generation`||t===`update-generation`)&&`generation`in n)return n.generation;if(t===`task-delivery-recovery`&&`taskDeliveryRecovery`in n)return n.taskDeliveryRecovery;throw createSqliteReadOnlyWorkerError(`returned a result for a different operation`,e.stderr)}function isSameSqliteReadOnlyWorkerLaunch(e,t){let n=Object.keys(t.env);return e.runtimeGeneration===t.runtimeGeneration&&e.transport.kind===t.transport.kind&&(e.transport.kind===`native`||t.transport.kind===`broker`&&e.transport.owner===t.transport.owner)&&t.cwd===e.cwd&&n.length===Object.keys(e.env).length&&n.every(n=>t.env[n]===e.env[n])}function createSqliteReadOnlyWorkerSession(e){Dr();let n={...e.env},r=e.cwd,i=process.execPath,a=e.transport.kind===`broker`?{kind:`broker`,owner:e.transport.owner}:{kind:`native`},s={env:n,cwd:r,transport:a,runtimeGeneration:e.runtimeGeneration},c=[...e.argv],l={env:n,...a.kind===`native`&&r===Qe()?{}:{cwd:r},stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0},u=a.kind===`broker`?a.owner.spawn(i,c,l):Qr.spawn(i,c,l);recordChildProcessSpawn(i,u,e.pooledRead?`sqlite.scoped-read.${a.kind}`:`sqlite.session.${a.kind}`);let setIdle=e=>{if(a.kind!==`native`)return;let t=e?`unref`:`ref`;u[t](),u.channel?.[t]?.();for(let e of[u.stdout,u.stderr])e instanceof Wr&&e[t]()},d=!1,f=0,m,h=``,ee=0,g,{promise:te,resolve:ne}=p(),v=/* @__PURE__ */ new Map,re=te.then(async()=>{a.kind===`broker`&&u instanceof Bt&&!u.notStarted&&u.exitCode===null&&u.signalCode===null&&await a.owner.waitForCleanup();for(let e of v.values())e();v.clear()}),retire=e=>{setIdle(!1),d=!0,g&&e!==void 0&&(g.failure??=e),u.kill(`SIGKILL`)},sendMessage=e=>u.send(e,e=>{e&&retire(e)}),releasePending=t=>{if(g=void 0,m=void 0,t.cleanup(),e.pooledRead){for(let e of v.values())e();v.clear()}return t};e.retainLifetime!==!1&&retainSnapshotWork(re,()=>retire(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)));let ie=!1,ae=!1,oe=!1;u.once(`spawn`,()=>{ae=!0}),u.on(`error`,e=>retire(ae?e:Object.assign(Error([[`EACCES`,`ENOENT`,`EPERM`].includes(e.code??``)?`SQLite read-only worker runtime binary not executable: ${i} (${e.code}, cwd ${r}). Check runtime execute permissions and access to the working directory`:`SQLite read-only worker failed to start (executable ${i}, cwd ${r})`,e.message].join(`: `),{cause:e}),{code:e.code,path:e.path})));let finishClose=async(e,t)=>{oe=!0,d=!0;let n=g?.failure??createSqliteReadOnlyWorkerError(`exited with ${t?`signal ${t}`:`code ${e}`}`,h),r=await un({execPath:i,error:n,stderr:h,signal:t,started:ie}).catch(toStringifiedError);if(g){let e=releasePending(g);e.reject(r??e.failure??n)}ne()};u.once(`close`,(e,t)=>{finishClose(e,t)});let captureOutput=(e,t)=>{ee+=e.length,t&&(h=ke(h+e.toString(`utf8`),-4e3)),ee>1048576&&retire(createSqliteReadOnlyWorkerError(`exceeded its output buffer`,h))},attachOutput=()=>{u.stdout?.on(`data`,e=>captureOutput(e,!1)),u.stderr?.on(`data`,e=>captureOutput(e,!0))},se=u instanceof Bt?u.ready().then(attachOutput).catch(retire):void 0;se||attachOutput(),u.on(`message`,t=>{if(ie=!0,!d){if(!g||!t||typeof t!=`object`||Object.keys(t).length!==2||!(`id`in t)||t.id!==g.id||!(`result`in t))retire(createSqliteReadOnlyWorkerError(`returned an unexpected response`,h));else try{let e;if(g.transfer&&`type`in t.result){let n=g.transfer.accept(t.result);if(`request`in n){sendMessage({id:g.id,transfer:n.request});return}e=n.value}else e=readSqliteReadOnlyWorkerValue({kind:`launched`,stdout:JSON.stringify(t.result),stderr:h,status:0},g.mode);releasePending(g).resolve(e)}catch(n){if(g&&e.retainOnOperationError&&isSqliteSnapshotStagingMode(g.mode)&&isSqliteReadOnlyWorkerResult(t.result)&&!t.result.ok){releasePending(g).reject(n);return}retire(n)}}});let ce={closed:re,isRetired(){return d},get notStarted(){return u instanceof Bt?u.notStarted:oe&&!ae},createNativeReplacement(){return t(()=>createSqliteReadOnlyWorkerSession({...e,env:n,cwd:r,argv:c,transport:{kind:`native`}}))},compatible(e){return!d&&isSameSqliteReadOnlyWorkerLaunch(s,e)},run(t,n){if(d)return Promise.reject(/* @__PURE__ */ Error(`SQLite read-only worker is closed`));if(n.mode===`auth-profile-rows`&&n.source===`canonical`&&!n.artifactPreserving){let e=E.resolve(t);v.has(e)||v.set(e,registerOpenClawAgentDatabaseReadCandidateResource({path:e,revoke:()=>retire(/* @__PURE__ */ Error(`Auth profile reader owner was revoked`)),close:()=>ce.close()}))}return m=new Promise((r,i)=>{h=``,ee=0;let abort=()=>retire(n.signal?.reason),a,s=++f;g={id:s,mode:n.mode,...n.mode===`auth-profile-rows`?{transfer:createSqliteAuthTransferReceiver()}:n.mode===`operation`?{transfer:createSqliteOperationTransferReceiver(n.command.type)}:{},resolve:r,reject:i,cleanup:()=>{clearTimeout(a),n.signal?.removeEventListener(`abort`,abort)}},n.signal?.addEventListener(`abort`,abort,{once:!0}),n.signal?.aborted?abort():(async()=>{try{if(!e.deadlineOwnedByCaller()){let{timeoutMs:n,size:r}=await e.readBudget(t);if(d)return;a=setTimeout(()=>retire(e.timeoutError(t,n,r)),n)}if(se&&(await se,d))return;let r={id:s,args:e.requestArgs(t,n),...n.mode===`auth-profile-rows`||n.mode===`operation`?{[n.mode===`operation`?`operation`:`auth`]:{expectedIdentity:n.expectedIdentity,expectedBirthtime:n.expectedBirthtime,artifactPreserving:n.artifactPreserving,...n.mode===`operation`?{command:pi(n.command).toString(`base64`)}:{immutable:n.immutable,retainReader:!e.pooledRead&&n.source===`canonical`&&!n.artifactPreserving,schema:n.source===`canonical`&&!n.artifactPreserving?captureSqliteAuthSchema(t,n.expectedIdentity):void 0}}}:{}};if(n.mode===`operation`&&Buffer.byteLength(JSON.stringify(r))>1048576)throw Error(`SQLite read-only operation exceeded its request buffer`);sendMessage(r)}catch(e){retire(e)}})()})},setIdle,async close(){if(ce.setIdle(!1),d){await re;return}d=!0;let t=setTimeout(()=>retire(),e.closeTimeoutMs);try{sendMessage(`close`)}catch(e){retire(e)}try{await re}finally{clearTimeout(t)}}};return e.runtimeGeneration?.retain(ce,async()=>(await m?.catch(()=>void 0),()=>ce.close())),ce}const Ha=y(`state/sqlite`);function trackSqliteRead(e){return Zn(`sqlite_read`,rt(e.mode===`operation`?e.command.type:e.mode),e.signal)}function createSqliteReadOnlyWorkerPool(e){let n=[],r=/* @__PURE__ */ new WeakMap,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new WeakSet,s=createStateWorkerMemoryPressureSubscription(()=>n.some(e=>e.idleSince!==void 0&&!e.session?.isRetired()),e=>{for(let t of n)t.session&&!t.leased&&!t.quarantined&&t.queued===0&&Kt(t.idleSince,e)&&retireIdleSlot(t)}),assertBrokerOpen=e=>{if(e.transport.kind===`broker`&&a.has(e.transport.owner))throw Error(`SQLite read-only worker broker is closing`)};async function closeSlot(e){let t=e.session;try{await t?.close(),e.session=void 0}catch(t){e.quarantined={error:t};for(let e of i)e();throw t}}async function selectScopedReadWorker(e,a){assertBrokerOpen(a);let s=e.mode===`operation`&&(e.command.type===`pageCache.begin`||e.command.type===`pageCache.step`),c=ma.getStore();if(s){if(!c?.active)throw Error(`Database page-cache warm requires an active read-only worker scope`);let t=r.get(c);if(t){if(!isSameSqliteReadOnlyWorkerLaunch(t.launch,a))throw Error(`Database page-cache warm worker launch changed during its scope`);return t}if(e.command.type===`pageCache.step`)throw Error(`Database page-cache warm is no longer active`)}for(;;){assertBrokerOpen(a),e.signal?.throwIfAborted();let l=n.filter(e=>!e.leased&&!e.quarantined),u=l.find(e=>isSameSqliteReadOnlyWorkerLaunch(e.launch,a));if(!u&&n.length<4&&(u={launch:a,tail:Promise.resolve(),queued:0},n.push(u)),u??=l.find(e=>e.queued===0&&!e.session),u??=l.reduce((e,t)=>!e||t.queued<e.queued?t:e,void 0),u){if(s&&c){let e=u,t={started:!1};e.leased=t,r.set(c,e),c.releaseReadWorker=async()=>{try{t.started&&(await e.tail,await closeSlot(e))}finally{e.leased=void 0,r.delete(c),c.releaseReadWorker=void 0,!e.quarantined&&e.queued===0&&e.session&&!e.session.isRetired()&&(e.session.setIdle(!0),armScopedReadWorkerIdle(e));for(let e of i)e()}}}return u}if(n.every(e=>e.quarantined))throw AggregateError(n.map(e=>e.quarantined?.error),`SQLite read-only worker capacity is held by unconfirmed cleanup`);let d,f=t(()=>new Promise(e=>{d=e}));i.add(d);try{await se(f,e.signal,e=>e.reason)}finally{i.delete(d)}}}function retireIdleSlot(e){clearTimeout(e.idle),e.idleSince=void 0,s();let n=t(()=>closeSlot(e));return e.tail=n.catch(()=>{Ha.warn(`Idle SQLite read-only worker cleanup failed`)}),n}function armScopedReadWorkerIdle(e){e.launch.transport.kind===`broker`&&a.has(e.launch.transport.owner)?retireIdleSlot(e):(e.idleSince=performance.now(),s(),e.idle=t(()=>setTimeout(()=>{retireIdleSlot(e)},6e4)),e.idle.unref())}return{run:async function(n,r,i,a=trackSqliteRead(r)){let c=r.mode===`operation`&&(r.command.type===`pageCache.begin`||r.command.type===`pageCache.step`),l;try{l=await selectScopedReadWorker(r,i),assertBrokerOpen(i)}catch(e){throw a.completed(),e}clearTimeout(l.idle),l.idleSince=void 0,s(),l.queued++;let u=l.tail,d=t(()=>se(u,r.signal,e=>e.reason)).then(async()=>{if(r.signal?.throwIfAborted(),l.quarantined)throw l.quarantined.error;if(a.started(),l.leased&&r.mode===`operation`&&r.command.type===`pageCache.begin`&&(l.leased.started=!0),(!isSameSqliteReadOnlyWorkerLaunch(l.launch,i)||l.session?.isRetired())&&await closeSlot(l),r.signal?.throwIfAborted(),l.launch=i,!l.session){l.session=e({...i,pooledRead:!0});let{closed:n}=l.session;t(()=>n.then(s,s))}let u=l.session;u.setIdle(!1);try{let e=await u.run(n,r);return r.signal?.throwIfAborted(),!c&&(r.mode===`operation`&&sqliteReadOnlyOperationRequiresProcessRetirement(r.command.type)||!fr().explicitSqliteCloseReleasesNativeResources)&&await closeSlot(l),e}catch(e){try{await closeSlot(l)}catch(t){throw Wt([e,t],`SQLite read and child cleanup failed`,e)}throw e}}).finally(()=>{a.completed(),l.queued--,!l.leased&&!l.quarantined&&l.queued===0&&l.session&&!l.session.isRetired()&&(l.session?.setIdle(!0),armScopedReadWorkerIdle(l))});return l.tail=t(()=>Promise.allSettled([u,d]).then(()=>{})),d},async closeBroker(e){a.add(e);let t=await Promise.allSettled(n.filter(t=>t.launch.transport.kind===`broker`&&t.launch.transport.owner===e&&t.session&&t.queued===0&&!t.leased&&!t.quarantined).map(retireIdleSlot));Pr(t,`SQLite read-only broker worker cleanup failed`)}}}const Ua=3e5,Wa=y(`state/sqlite`);function resolveSqliteInspectionBudget(e,t,n){let r=Ae(Ua+Math.ceil(40*Number(n??0)/33554432)*1e3,Ua),i=n===void 0?`unknown size`:formatByteSize(Number(n),{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:n<1024n?0:1});return r>Ua&&Wa.debug(`SQLite ${e} for ${t}: ${i}, budget ${r/1e3} seconds`),{timeoutMs:r,size:i}}function readSqliteInspectionBudget(e,t,n){let r=n;try{r??=T.statSync(t,{bigint:!0}).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=T.statSync(t+e,{bigint:!0}).size}catch(e){if(!oe(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}async function readSqliteInspectionBudgetAsync(e,t,n){let r=n;try{r??=(await T.promises.stat(t,{bigint:!0})).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=(await T.promises.stat(t+e,{bigint:!0})).size}catch(e){if(!oe(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}function sqliteInspectionTimeoutError(e,t,n,r){return/* @__PURE__ */ Error(`SQLite ${e} timed out after ${n/1e3} seconds (budget for ${r}) for ${t}. Stop the Gateway service and other OpenClaw processes using this database, then retry; if already stopped, check storage performance.`)}function isSqliteInspectionDeadlineOwnedByCaller(){return ma.getStore()?.deadlineOwnedByCaller===!0}function sqliteReadOnlyWorkerArgv(e){let{moduleUrl:t,runtimeGeneration:n}=_t(Pt(e[0]===`content-version`||e[0]===`file-generation`?`sqliteSourceRevision`:`sqliteReadOnly`));return{runtimeGeneration:n,argv:[...resolveForwardedNodeCompilerArgs(),..._e(t),le,...e]}}function createScopedSqliteReadOnlyWorker(e){let n=Pt(`sqliteReadOnly`);return t(()=>createSqliteReadOnlyWorkerSession({...e,argv:[...resolveForwardedNodeCompilerArgs(),..._e(Et(n,e.runtimeGeneration)),le,`session`],requestArgs:sqliteReadOnlyWorkerRequestArgs,readBudget:e=>readSqliteInspectionBudgetAsync(`read-only snapshot`,e),deadlineOwnedByCaller:e.retainLifetime===!1?()=>!1:isSqliteInspectionDeadlineOwnedByCaller,timeoutError:(e,t,n)=>sqliteInspectionTimeoutError(`read-only snapshot`,e,t,n),closeTimeoutMs:Ua}))}createSqliteReadOnlyWorkerPool(createScopedSqliteReadOnlyWorker);function runSqliteReadOnlyWorkerSync(e,t,n=`sync`,r){Dr();let{timeoutMs:i,size:a}=readSqliteInspectionBudget(`read-only snapshot`,e),s=Qr.spawnSync(process.execPath,sqliteReadOnlyWorkerArgv(sqliteReadOnlyWorkerRequestArgs(e,{mode:n,stagingRoot:t,expectedSourceIdentity:r})).argv,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,env:qn(Zt()),maxBuffer:1048576,timeout:i,killSignal:`SIGKILL`}),c=ot({error:s.error,stderr:s.stderr,signal:s.signal,started:!!s.stdout});if(c)throw c;return readSqliteReadOnlyWorkerValue(s.error?{kind:`launch-failed`,error:Error(oe(s.error,`ETIMEDOUT`)?sqliteInspectionTimeoutError(`read-only snapshot`,e,i,a).message:`SQLite read-only worker failed to start for ${e}: ${s.error.message}`,{cause:s.error})}:{kind:`launched`,stdout:s.stdout,stderr:s.stderr,status:s.status,failure:s.status===0?void 0:`exited with ${s.signal?`signal ${s.signal}`:`code ${s.status}`}`},n)}const Ga=i(Symbol.for(`openclaw.quarantineReadCleanupError`),()=>class extends AggregateError{constructor(e,t){super(e,`OpenClaw quarantine reader cleanup failed.`,{cause:e[0]}),this.quarantine=t,this.name=`OpenClawQuarantineReadCleanupError`}}),Ka=i(Symbol.for(`openclaw.stateDatabaseFailurePaths`),()=>/* @__PURE__ */ new WeakMap);function markOpenClawStateDatabaseFailure(e,t){Ka.set(e,t)}function findOpenClawStateDatabaseFailure(e,t){let n=[e],r=/* @__PURE__ */ new Set;for(let e of n)if(e instanceof Error&&!r.has(e)){if(r.add(e),Ka.get(e)===t)return e;n.push(e.cause),e instanceof AggregateError&&n.push(...e.errors)}}var DuplicateAgentError=class extends Error{};const qa=`openclaw doctor --fix`;var AuthProfileStoreUnreadableError=class extends Error{constructor(e){super(`Auth profile store ${Re(e)} is unreadable; run ${qa}.`),this.databasePath=e,this.code=`AUTH_PROFILE_STORE_UNREADABLE`,this.action=qa,this.name=`AuthProfileStoreUnreadableError`}},McpOAuthStoreCorruptionError=class extends Error{constructor(e,t,n){super(`MCP OAuth store ${e} is invalid: ${t}`,n),this.name=`McpOAuthStoreCorruptionError`}},SandboxStateOwnerRequiredError=class extends Error{constructor(e){super(`Sandbox workspace preparation cannot run alongside a foreign live owner of the selected state root, or when that ownership cannot be verified. Run this SDK call inside the owning Gateway plugin/runtime, or stop the Gateway through its service owner and wait for any embedded run to finish, then retry offline. Inspect openclaw gateway status; this call does not acquire ownership or route remotely.`,{cause:e}),this.code=`GATEWAY_STATE_OWNER_REQUIRED`,this.name=`SandboxStateOwnerRequiredError`}},WorkspaceAliasRepointedError=class extends Error{constructor(e){super(`workspace path alias points to a different current target: ${e.aliasPath} now resolves to ${e.currentWorkspacePath}, but its stored workspace state belongs to ${e.storedWorkspacePath}. Run \`openclaw doctor --fix\` and confirm the move, or use \`openclaw doctor --fix --force\`.`),this.code=`WORKSPACE_ALIAS_REPOINTED`,this.name=`WorkspaceAliasRepointedError`,this.aliasPath=e.aliasPath,this.storedWorkspacePath=e.storedWorkspacePath,this.currentWorkspacePath=e.currentWorkspacePath}},WorktreeRemovalContentionError=class extends Error{constructor(e,t,n){super(t),this.kind=e,this.blockedByRun=n,this.name=`WorktreeRemovalContentionError`}},WorktreeRemovalLockError=class extends Error{constructor(e,t){super(t),this.kind=e,this.name=`WorktreeRemovalLockError`}},SessionWorktreeSourceChangedError=class extends Error{},SessionWorktreeLifecycleError=class extends Error{constructor(e,t){super(e),this.reason=t}},SessionGoalOperationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SessionGoalOperationError`}},SessionCanonicalKeyMigrationRequiredError=class extends Error{constructor(e){super(`${e}; stop the Gateway and run openclaw doctor --fix`),this.code=`SESSION_CANONICAL_KEY_MIGRATION_REQUIRED`,this.name=`SessionCanonicalKeyMigrationRequiredError`}},SqliteSessionMutationConflictError=class extends Error{constructor(e){super(`SQLite session state changed while preparing ${e}`),this.operationLabel=e,this.name=`SqliteSessionMutationConflictError`}},SqliteTranscriptMutationConflictError=class extends Error{constructor(e){super(`SQLite transcript changed while preparing rewrite for ${e}`),this.sessionId=e,this.name=`SqliteTranscriptMutationConflictError`}},SessionEntryLifecycleUpsertConflictError=class extends Error{constructor(e){super(`SQLite session entry changed before lifecycle upsert for ${e}`),this.sessionKey=e,this.name=`SessionEntryLifecycleUpsertConflictError`}},SessionPendingInputCustodyError=class extends Error{},SessionTranscriptReadFenceError=class extends Error{constructor(e){super(e),this.name=`SessionTranscriptReadFenceError`}},SessionTranscriptWriterClaimReboundError=class extends Error{constructor(e){super(`session writer claim changed before transcript persistence`,{cause:e}),this.name=`SessionTranscriptWriterClaimReboundError`}},ModelAccountConnectAuthorityError=class extends Error{constructor(){super(`This account action requires a current authorized connection; reconnect and try again.`)}},WorkerSessionAlreadyAttachedError=class extends Error{constructor(e,t){super(`Session ${e} is already attached to worker environment ${t}`),this.sessionId=e,this.environmentId=t}},SqliteJsonlReadBudgetExceededError=class extends Error{};const Ja=/^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/;function parseReleaseVersion(e){let t=e.trim(),n=Ja.exec(t)?.groups;if(!n)return null;let r=Number(n.year),i=Number(n.month),a=Number(n.patch),s=n.prerelease===void 0?void 0:Number(n.prerelease),c=n.correction===void 0?void 0:Number(n.correction);if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||!Number.isSafeInteger(a)||i<1||i>12||a<1||s!==void 0&&!Number.isSafeInteger(s)||c!==void 0&&!Number.isSafeInteger(c))return null;let l=n.channel===`alpha`?`alpha`:n.channel===`beta`?`beta`:`stable`;return{version:t,baseVersion:`${r}.${i}.${a}`,channel:l,year:r,month:i,patch:a,alphaNumber:l===`alpha`?s:void 0,betaNumber:l===`beta`?s:void 0,...c===void 0?{}:{correctionNumber:c}}}function compareReleaseVersions(e,t){let n=parseReleaseVersion(e),r=parseReleaseVersion(t);if(n===null||r===null)return null;if(n.year!==r.year)return Math.sign(n.year-r.year);if(n.month!==r.month)return Math.sign(n.month-r.month);if(n.patch!==r.patch)return Math.sign(n.patch-r.patch);if(n.channel!==r.channel){let e={alpha:0,beta:1,stable:2};return Math.sign(e[n.channel]-e[r.channel])}return n.channel===`alpha`&&r.channel===`alpha`?Math.sign((n.alphaNumber??0)-(r.alphaNumber??0)):n.channel===`beta`&&r.channel===`beta`?Math.sign((n.betaNumber??0)-(r.betaNumber??0)):Math.sign((n.correctionNumber??0)-(r.correctionNumber??0))}const Ya=Symbol.for(`openclaw.stateDatabaseLifecycle`),Xa=[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28],Za=[`agent_deletion_journal`],Qa=/* @__PURE__ */ `durable_background_processes.sandbox_persistent_execs.user_profile_identities.user_background_images.local_workspace_projections.local_workspace_manifest_nodes.local_workspace_tree_packs.local_workspace_source_path_sets.update_runs.session_repository_workspaces.github_repository_publication_requests.github_publication_session_lifecycles.skill_library_entries.skill_library_revisions.skill_library_events.skill_library_uploads.github_personal_publication_requests.cron_job_runtime_authorities.cron_run_trigger_state_retirements.execution_identity_contexts.mcp_oauth_pending_authorizations.node_worker_launch_containers.node_worker_launch_boots.node_worker_launch_cleanup.node_worker_launch_process_scopes.node_worker_launches.node_worker_prepared_workspaces.node_worker_turns.operator_approval_execution_identities.operator_approval_standing_grants.operator_approval_standing_grant_generations.web_push_approval_deliveries.execution_decision_facts.execution_owner_lifecycle_bindings.outbound_message_execution_bindings.outbound_message_progress`.split(`.`),$a=[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`,`idx_user_profile_identities_profile_id`,`idx_user_profile_identities_authorization`,`idx_update_runs_created`,`idx_update_runs_active`,`idx_github_repository_publication_shared_request`,`idx_github_repository_publication_personal_request`,`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`,`idx_node_worker_launches_terminal_completed`,`idx_node_worker_turns_terminal_completed`,`idx_node_worker_turns_active_owner`,`idx_operator_approval_standing_grants_binding`,`idx_web_push_approval_deliveries_subscription`,`execution_identity_contexts_run_created_idx`,`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_run_occurred_idx`,`outbound_message_execution_bindings_execution_event_idx`,`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`],eo=[...Qa,`agent_provenance`,`cron_run_receipts`,`config_revision_keys`,`secret_store_entries`,`projects`,`worktree_templates`,`user_preferences`,`device_pair_setup_completions`,`github_publication_requests`,`device_pairing_join_codes`,`device_pairing_browser_requests`,`skill_workshop_changes`,`worker_environment_ssh_fallback_ports`,`worker_session_placement_moves`],to=[...$a,`cron_run_receipts_cursor_id_idx`,`idx_cron_run_receipts_active_job`,`idx_cron_run_receipts_job_history`,`idx_github_publication_requests_pending`,`secret_store_entries_live_idx`,`skill_workshop_changes_cursor_id_idx`,`idx_skill_workshop_changes_agent_time`],no=5e3,ro=`https://docs.openclaw.ai/reference/database-schemas`;function walkUpFrom(e,t,n){let r=E.resolve(e);for(let e=0;t.maxDepth===void 0||e<t.maxDepth;e+=1){let e=n(r);if(e!=null)return e;let t=E.dirname(r);if(t===r)break;r=t}return null}function readGitMetadataFile(e,t=1048576){let n=T.openSync(e,T.constants.O_RDONLY|(T.constants.O_NONBLOCK??0));try{let e=T.fstatSync(n);if(!e.isFile()||e.size>t)throw Error(`Git metadata is not a bounded regular file`);let r=ci(n,Math.min(e.size,t));if(r.length!==e.size)throw Error(`Git metadata changed during its read`);return r}finally{T.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let n=readGitMetadataFile(e),r=n.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!_i(n)||!r.startsWith(t)||r.length===t.length||r.includes(`\0`))throw Error(`Git directory pointer is incomplete or malformed`);let i=r.slice(t.length);return E.isAbsolute(i)?i:`${E.dirname(e)}${E.sep}${i}`}function readGitDirectoryPointer(e,t=``){return T.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=E.join(e,`.git`);try{let e=T.statSync(t);return e.isDirectory()?t:e.isFile()?readGitDirectoryPointer(t,`gitdir: `):null}catch{return null}}function resolveGitHeadPath(e,t={}){return walkUpFrom(e,t,e=>{let t=resolveGitDirFromMarker(e);return t?E.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){let n=T.openSync(e,T.constants.O_RDONLY|(T.constants.O_NONBLOCK??0));try{if(!T.fstatSync(n).isFile())throw Error(`Git metadata is not a regular file`);let e=Buffer.alloc(t),r=li(n,e,0);return e.subarray(0,r).toString(`utf-8`)}finally{T.closeSync(n)}}function readGitHead(e,t={}){let n=resolveGitHeadPath(e,t);if(!n)return;let r=readGitMetadataFile(n).toString(`utf8`).trim();if(!r.startsWith(`ref:`))return{headPath:n,ref:null,value:r||null};let i=r.replace(/^ref:\s*/i,``).trim(),a=resolveGitRefsBase(n);return{headPath:n,ref:i,value:readGitRefs(a,[i]).get(i)??null,refsBase:a}}function resolveGitRefsBase(e){let t=E.dirname(e),n=E.join(t,`commondir`);try{return readGitDirectoryPointer(n)}catch(e){if(!ie(e)||T.lstatSync(n,{throwIfNoEntry:!1}))throw e}return t}function readGitRefs(e,t){let n=new Map(t.map(e=>[e,null])),r=/* @__PURE__ */ new Set;for(let i of t){let t=resolveRefPath(e,i);if(t)try{n.set(i,readGitMetadataPrefix(t).trim())}catch(e){if(!ie(e))throw e;r.add(i)}}if(r.size===0)return n;try{let t=readGitMetadataFile(E.join(e,`packed-refs`),2**53-1).toString(`utf8`),i=RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(We).join(`|`)})(?=\\s|$)`,`gm`);for(let[,e,a]of t.matchAll(i))r.delete(a)&&n.set(a,e)}catch(e){if(!ie(e))throw e}return n}function resolveRefPath(e,t){if(!t.startsWith(`refs/`)||t.split(/[/]/).includes(`..`))return null;let n=E.resolve(e,t),r=E.relative(e,n);return!r||r.startsWith(`..`)||E.isAbsolute(r)?null:n}async function settlesWithin(e,t){return await ce(e.then(()=>!0),t,()=>!1,{ref:!1})}const io=i(Symbol.for(`openclaw.asyncWorkScope`),()=>new D),ao=i(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new D),oo=i(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}});var so=class AsyncWorkScope{constructor(e){this.failures=e,this.pending=/* @__PURE__ */ new Set,this.controller=new AbortController,this.phase=`open`}get signal(){return this.controller.signal}get hasPendingWork(){return this.pending.size>0}get isClosing(){return this.phase!==`open`}enter(e){let t=io.getStore();if(t===this)return e();let n=ao.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return ye(io,this,()=>(ao.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new oo;if(this.pending.size>0)return this.enter(e);let t=p();this.pending.add(t.promise);try{return this.enter(e)}finally{t.resolve(),this.pending.delete(t.promise)}}track(e){if(this.phase===`closed`)return Promise.reject(new oo);let t=p();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(Nr(e),this.failures.add(e))});try{t.resolve(this.enter(e))}catch(e){t.reject(e)}return t.promise}beginClose(e){this.phase===`open`&&(this.phase=`closing`,this.controller.abort(e),Nr(this.controller.signal.reason))}runWhenIdle(e){return AsyncWorkScope.runWhenAllIdle(()=>[this],()=>this.track(e))}static async runWhenAllIdle(e,t){let n=e();for(;n.some(e=>e.pending.size>0);)await Promise.allSettled(n.flatMap(e=>Array.from(e.pending))),n=e();return t()}async drain(){for(this.beginClose();this.pending.size>0;)await Promise.allSettled(this.pending);this.phase=`closed`}};i(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}});function runOutsideAsyncWorkScope(e){return io.getStore()===void 0?ao.getStore()===void 0?e():ao.exit(e):ye(io,void 0,()=>(ao.enterWith(void 0),e()))}function appendPluginInstanceCleanupFailures(e,t,n){for(let r of n.errors)e.some(e=>e.pluginId===t&&e.error===r)||e.push({pluginId:t,hookId:`instance`,error:r})}function createPluginCacheSdk(){return{hosts:/* @__PURE__ */ new Map,contexts:/* @__PURE__ */ new Map,roots:/* @__PURE__ */ new Set,packageNames:/* @__PURE__ */ new Map,packageSearches:/* @__PURE__ */ new Map,argvDirectories:/* @__PURE__ */ new Map,devSourceRoots:/* @__PURE__ */ new Map,runtimeModules:/* @__PURE__ */ new Map,normalizedJitiAliases:/* @__PURE__ */ new Map,aliasFacts:/* @__PURE__ */ new WeakMap,native:{sdkProviders:/* @__PURE__ */ new Map,nextSdkProviderOrder:0,parents:/* @__PURE__ */ new Map,aliases:/* @__PURE__ */ new Map,registeredHosts:/* @__PURE__ */ new Set,hostRoots:/* @__PURE__ */ new Map,nearestPackageRoots:/* @__PURE__ */ new Map,loaderPackageRoots:/* @__PURE__ */ new Map,allowedParentRoots:/* @__PURE__ */ new Map}}}const co=i(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),lo=i(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),uo=i(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap);function releasePluginCacheInstance(e,t){let n=uo.get(e);if(t)t.instances.delete(e),n?.delete(t);else{for(let t of n??[])t.instances.delete(e);n?.clear()}n?.size===0&&uo.delete(e)}function getPluginCacheRetainers(e){let t=lo.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:p()},lo.set(e,t)),t}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:!1,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},autoEnable:/* @__PURE__ */ new WeakMap,snapshots:/* @__PURE__ */ new Map,derivedIndexes:/* @__PURE__ */ new WeakMap,preparedManifests:/* @__PURE__ */ new WeakMap,snapshotManifestFacts:/* @__PURE__ */ new WeakMap,discovery:/* @__PURE__ */ new Map,sharedDiscovery:/* @__PURE__ */ new Map,projections:/* @__PURE__ */ new WeakMap,projectionSources:/* @__PURE__ */ new WeakMap,completions:/* @__PURE__ */ new WeakMap,indexFacts:/* @__PURE__ */ new WeakMap,providerPolicyOwners:/* @__PURE__ */ new WeakMap,channelAdapters:/* @__PURE__ */ new WeakMap,bundledChannelCatalogs:/* @__PURE__ */ new Map,bundledProviderPolicySurfaces:/* @__PURE__ */ new WeakMap,staticCatalogStates:/* @__PURE__ */ new WeakMap,modelSuppressionResolvers:/* @__PURE__ */ new WeakMap,mcpAuthDeclarations:/* @__PURE__ */ new WeakMap}}function createPluginCache(e={}){return{async[Symbol.asyncDispose](){await retirePluginCache(this)},kind:e.kind??`operation`,roots:/* @__PURE__ */ new Map,rootAliases:/* @__PURE__ */ new Map,sdk:createPluginCacheSdk(),setupModules:/* @__PURE__ */ new Map,instances:/* @__PURE__ */ new Set,metadata:createPluginMetadataCache(),installRecords:/* @__PURE__ */ new Map,persistedInstalledIndex:/* @__PURE__ */ new Map,preparedBundledDiscoveryModes:/* @__PURE__ */ new Map,dependencyStatus:/* @__PURE__ */ new WeakMap,moduleLoaders:/* @__PURE__ */ new Map,sources:/* @__PURE__ */ new Map,sourceAliases:/* @__PURE__ */ new Map,runtimeRecordRoots:/* @__PURE__ */ new WeakMap}}function getProcessPluginCache(){return co.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return Oe()?.cacheScope?.cache}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function retirePluginCache(e,t,n){let r=getPluginCacheRetainers(e);if(r.retirement)return r.retirement;let i=p();return r.retirement=i.promise,r.controller.abort(),Nr(r.controller.signal.reason),runOutsideAsyncWorkScope(async()=>{r.references.size&&await r.settled.promise;let i=new so;try{return await i.track(()=>beginPluginCacheRetirement(e,t,n))}finally{await i.drain()}}).then(i.resolve,i.reject),i.promise}function beginPluginCacheRetirement(e,t,n){if(e.retirement)return e.retirement;let r=p();return e.retirement=r.promise,(async()=>{t?.();let r=e.retireRegistryLoads?.(),i=/* @__PURE__ */ new Set([...e.setupModules.values(),...e.instances]);for(let e of i)e.quiesce();let[a]=await Promise.allSettled([r]),s=await Promise.allSettled([...i].map(async e=>({resource:e,result:await e.dispose(void 0,n)}))),c=e.sourceAdmissions;if(c){let e=s.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof et?[e.settled]:[]):[]);e.length>0?Promise.allSettled(e).then(()=>c.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`)):await c.dispose()}e.setupModules.clear();for(let t of e.instances)releasePluginCacheInstance(t,e);let l=[...a.status===`rejected`?[a.reason]:[],...s.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(l.length)throw AggregateError(l,`Plugin cache resources failed to retire`);let u=a.status===`fulfilled`?a.value:void 0,d=[...u?.failures??[]];for(let e of s){if(e.status!==`fulfilled`)continue;let{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(d,t.pluginId,n)}return{cleanupCount:u?.cleanupCount??0,failures:d}})().then(r.resolve,r.reject),r.promise}function parsePackageName(e){let t=JSON.parse(e);return typeof t.name==`string`?t.name:null}function readPackageNameSync(e){let t=getPluginCache().sdk.packageNames,n=E.join(E.resolve(e),`package.json`);if(t.has(n))return t.get(n)??null;try{let e=parsePackageName(Ur.readFileSync(n,`utf-8`));return t.set(n,e),e}catch{return t.set(n,null),null}}function findPackageRootSync(e){for(let t of iterAncestorDirs(e))if(readPackageNameSync(t)===`openclaw`)return t;return null}function*iterAncestorDirs(e){let t=E.resolve(e);for(let e=0;e<12&&(yield t,E.basename(t)!==`node_modules`);e+=1){let e=E.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,n=E.resolve(e),r=t.get(n);if(r)return[...r];let i=n,a=[];try{let e=Ur.realpathSync(i);e!==i&&a.push(E.dirname(e))}catch{}a.push(E.dirname(i));let s=i.split(E.sep),c=s.lastIndexOf(`.bin`);if(c>0&&s[c-1]===`node_modules`){let e=E.basename(i),t=s.slice(0,c).join(E.sep);a.push(E.join(t,e))}let l=dedupeCandidates(a);return t.set(n,l),[...l]}function preparePackageRootSearch(e,t){let n=buildCandidates(e),r=n.join(`\0`),i=getPluginCache().sdk.packageSearches,a=i.get(r);return{candidates:n,first:a?.all?a.all[0]??null:a?.first,complete(e){return i.set(r,t?{...i.get(r),first:e}:{first:e}),e}}}function resolveOpenClawPackageRootSync(e){let t=preparePackageRootSearch(e,!1);if(t.first!==void 0)return t.first;for(let e of t.candidates){let n=findPackageRootSync(e);if(n)return t.complete(n)}return t.complete(null)}function buildCandidates(e){let t=[];if(e.moduleUrl)try{t.push(E.dirname(ai(e.moduleUrl)))}catch{}return e.argv1&&t.push(...candidateDirsFromArgv1(e.argv1)),e.cwd&&t.push(e.cwd),dedupeCandidates(t)}function dedupeCandidates(e){return[...new Set(e.map(e=>E.resolve(e)))]}const formatCommit=t=>{let n=t?.match(/[0-9a-fA-F]{7,40}/);return n?e(n[0].slice(0,7)):null},fo=new Ne(256),resolveCommitSearchDir=e=>{if(e.cwd)return E.resolve(e.cwd);if(e.moduleUrl)try{return E.dirname(ai(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(fo.set(e,t),t),resolveGitLookupDepth=(e,t)=>{if(!t)return;let n=E.relative(t,e);if(!(n.startsWith(`..`)||E.isAbsolute(n)))return(n?n.split(E.sep).filter(Boolean).length:0)+1},readCommitFromGit=(e,t)=>{let n=readGitHead(e,{maxDepth:resolveGitLookupDepth(e,t)});return n===void 0?void 0:formatCommit(n.value)},readCommitFromPackageJson=()=>{try{let e=Ir(import.meta.url)(`../../package.json`);return formatCommit(e.gitHead??e.githead??null)}catch{return null}},readCommitProbe=(e,t,n)=>{try{for(let i of t){let t=ai(new URL(i,e)),a;try{a=readGitMetadataPrefix(t,1024)}catch(e){if(ie(e))continue;return null}try{let e=r(JSON.parse(a))?.[n];return typeof e==`string`?formatCommit(e):null}catch{return null}}}catch{}},readCommitFromBuildInfo=(e=import.meta.url)=>readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)??null,readLoadedCommit=e=>{let t=readCommitProbe(e,[`../.buildstamp`,`./.buildstamp`],`head`),n=readCommitProbe(e,[`../.runtime-postbuildstamp`,`./.runtime-postbuildstamp`],`head`);return t!==void 0||n!==void 0?t||n?t&&t===n?t:null:readCommitFromBuildInfo(e):readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)},resolveCommitHash=(e={})=>{let t=e.env??process.env,n=t.GIT_COMMIT?.trim()||t.GIT_SHA?.trim(),r=formatCommit(n);if(r)return r;let i=resolveCommitSearchDir(e),a=fo.get(i);if(a!==void 0)return a;let s=resolveOpenClawPackageRootSync({cwd:e.cwd,moduleUrl:e.moduleUrl});try{let e=readCommitFromGit(i,s);if(e!==void 0)return cacheGitCommit(i,e)}catch{}let c=readCommitFromBuildInfo();if(c)return cacheGitCommit(i,c);let l=readCommitFromPackageJson();return l?cacheGitCommit(i,l):cacheGitCommit(i,null)};function resolveLoadedCommitHash(e={}){let t=e.moduleUrl??import.meta.url,n=readLoadedCommit(t);return n===void 0?resolveCommitHash({moduleUrl:t,...e.env?{env:e.env}:{}}):n}const po=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],mo=[`../build-info.json`,`../../build-info.json`,`./build-info.json`];function readStringFromJsonCandidates(e,t,n,r=!1){try{let i=Ir(e);for(let e of t)try{let t=i(e),a=d(t[n]);if(!a||r&&t.name!==`openclaw`)continue;return a}catch{}return null}catch{return null}}function firstNonEmpty(...e){for(let t of e){let e=d(t);if(e&&e.toLowerCase()!==`undefined`&&e.toLowerCase()!==`null`)return e}}function readVersionFromPackageJsonForModuleUrl(e){return readStringFromJsonCandidates(e,po,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,mo,`version`)}function readBuildProvenanceForModuleUrl(e){try{let t=Ir(e);for(let e of mo)try{let n=t(e),r=d(n.buildId);if(r&&r.length<=96){let i={buildId:r};for(let e of[`version`,`commit`,`builtAt`]){let t=d(n[e]);t&&(i[e]=t)}try{i.buildInfoPath=t.resolve(e)}catch{}return i}}catch{}}catch{}return null}function resolveVersionFromModuleUrl(e){return readVersionFromBuildInfoForModuleUrl(e)||readVersionFromPackageJsonForModuleUrl(e)}function resolveBinaryVersion(e){return resolveVersionFromModuleUrl(e.moduleUrl)||firstNonEmpty(e.bundledVersion)||`0.0.0`}readBuildProvenanceForModuleUrl(import.meta.url);const ho=resolveLoadedCommitHash({moduleUrl:import.meta.url});function resolveRuntimeServiceCommit(){return ho}const go=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION}),_o={"state-migrations":`state migration`,"newer-schema":`a newer OpenClaw build`,"agent-media":`offline media migration`,"audit-events-v2":`state database schema migration`,"legacy-workshop-review-index":`state database schema migration`,"legacy-cron-run-logs":`cron run history migration`,"legacy-workspace":`workspace setup state migration`,"legacy-session-store":`session store migration`};var StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n),this.kind=e,this.code=`gateway.maintenance_required`,this.name=`StartupMaintenanceRequiredError`}get reason(){return _o[this.kind]}},SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e),this.name=`SqliteSchemaVersionError`}};function readSqliteUserVersion(e){let t=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get());return Number(t?.user_version??0)}function readSqliteWriterAppVersion(e){try{let t=executeWithCachedStatement(e,`SELECT app_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`,[],e=>e.get());return typeof t?.app_version==`string`&&t.app_version.length>0?t.app_version:void 0}catch{return}}function describeRunningOpenClawBuild(){let e=resolveRuntimeServiceCommit(),t=resolveOpenClawPackageRootSync({moduleUrl:import.meta.url}),n=e?`OpenClaw ${go} (${e})`:`OpenClaw ${go}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,go)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){let s=isNewerSqliteWriterVersion(i),c=s?`; it is newer than this Gateway (${go}).`:a===`runtime`?`; run openclaw doctor --fix to inspect this database.`:`.`;return new SqliteSchemaVersionError(`This OpenClaw build cannot open your existing data.
${e} ${t} uses newer schema version ${n}; this build supports ${r}.\n`+(i&&(a===`runtime`||i!==go)?`It was written by OpenClaw ${i}${c}\n`:``)+`Refused by ${describeRunningOpenClawBuild()}.\n`+(s?`Use the newer install that supports schema ${n} or newer, or run openclaw update to update this Gateway service before restarting. To use an older build, restore your pre-update backup created with openclaw backup create.\n`:`Use a build that supports schema ${n} or newer with this state directory. To use an older build, restore your pre-update backup created with openclaw backup create.\n`)+`See ${ro}.`)}var PluginBlobStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginBlobStoreError`,this.code=t.code,this.operation=t.operation,t.path&&(this.path=t.path)}};function capturePluginStateErrorCause(e,t,n=/* @__PURE__ */ new Set){if(e===void 0)return;let r=t?.(e);if(r)return{canonical:r};if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return{name:`Error`,message:String(e)};if(typeof e!=`object`)return{name:`Error`,message:`Unknown SQLite error cause`};if(n.has(e)||n.size>=8)return{name:`Error`,message:`Additional SQLite error cause omitted`};n.add(e);let i=`name`in e&&typeof e.name==`string`?e.name:`Error`,a=`message`in e&&typeof e.message==`string`?e.message:i,s=`code`in e?e.code:void 0,c=`errcode`in e?e.errcode:void 0,l=`errno`in e?e.errno:void 0;return{name:i,message:a,...typeof s==`string`||typeof s==`number`?{errorCode:s}:{},...typeof c==`number`?{errcode:c}:{},...typeof l==`number`?{errno:l}:{},...`cause`in e?{cause:capturePluginStateErrorCause(e.cause,t,n)}:{},...e instanceof AggregateError?{errors:e.errors.slice(0,8).map(e=>capturePluginStateErrorCause(e,t,n))}:{}}}var PluginStateStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginStateStoreError`,this.code=t.code,this.operation=t.operation,this.owner=t.owner??{pid:process.pid,threadId:ii,version:go},t.path&&(this.path=t.path)}toJSON(){return{name:this.name,message:this.message,code:this.code,operation:this.operation,path:this.path,owner:this.owner,cause:capturePluginStateErrorCause(this.cause)}}},SecretStoreValidationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SecretStoreValidationError`}},ModelSelectionLockedError=class extends Error{constructor(e=`Model selection is locked for this session.`){super(e),this.name=`ModelSelectionLockedError`}},SkillUploadRequestError=class extends Error{constructor(...e){super(...e),this.name=`SkillUploadRequestError`}},SkillLibraryError=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.currentRevision=n,this.name=`SkillLibraryError`}},OpenClawAgentDatabaseMediaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(`agent-media`,`OpenClaw agent database ${e} uses schema version ${t}; run openclaw doctor --fix to migrate persisted media before using it.`),this.pathname=e,this.schemaVersion=t,this.name=`OpenClawAgentDatabaseMediaMigrationRequiredError`}},OpenClawStateDatabaseSchemaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(e,`OpenClaw state database schema migration required (${e}) at ${t}; run openclaw doctor --fix to migrate it.`),this.kind=e,this.pathname=t,this.name=`OpenClawStateDatabaseSchemaMigrationRequiredError`}};function normalizeOpenClawStateSchemaReadError(e,t){if(e instanceof Error&&e.message.startsWith(`malformed database schema (idx_skill_workshop_collection_reviews_workspace_time)`)){let n=new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-workshop-review-index`,t);return n.cause=e,n}return e}var OpenClawStateLeaseError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`OpenClawStateLeaseError`,this.code=t.code,this.loss=t.loss}},SessionMetadataUnavailableError=class extends Error{constructor(e,t,n=[]){super(`Session metadata unavailable (${[e,...n].join(`: `)}); retry after the agent store is ready.`,t),this.reason=e,this.missingTables=n,this.name=`SessionMetadataUnavailableError`}};const vo={"worktree-source-changed":SessionWorktreeSourceChangedError,"model-account-authority":ModelAccountConnectAuthorityError,"duplicate-agent":DuplicateAgentError,"model-selection-locked":ModelSelectionLockedError,"session-canonical-key-migration":SessionCanonicalKeyMigrationRequiredError,"session-pending-input-custody":SessionPendingInputCustodyError,"session-transcript-read-fence":SessionTranscriptReadFenceError,"skill-upload-request":SkillUploadRequestError,"state-database-access":xr,coordinator:an,ownership:ut,"newer-schema":SqliteSchemaVersionError,"jsonl-read-budget":SqliteJsonlReadBudgetExceededError,"range-error":RangeError,"syntax-error":SyntaxError,"type-error":TypeError};function isMessageOnlyErrorIdentity(e){return typeof e.type==`string`&&Object.hasOwn(vo,e.type)}function createError(e){if(isMessageOnlyErrorIdentity(e)){let t=vo[e.type];return new t(e.message)}switch(e.type){case`sandbox-state-owner-required`:return new SandboxStateOwnerRequiredError;case`session-worktree-owner-mismatch`:return new SessionWorktreeLifecycleError(e.message,`owner-mismatch`);case`worktree-removal-contention`:return new WorktreeRemovalContentionError(e.kind,e.message,e.blockedByRun);case`worktree-removal-lock`:return new WorktreeRemovalLockError(e.kind,e.message);case`plugin-state`:return new PluginStateStoreError(e.message,{code:e.stateCode,operation:e.operation,path:e.path,owner:e.owner});case`skill-library`:return new SkillLibraryError(e.libraryCode,e.message,e.currentRevision);case`secret-store-validation`:return new SecretStoreValidationError(e.secretCode,e.message);case`worker-session-already-attached`:return new WorkerSessionAlreadyAttachedError(e.sessionId,e.environmentId);case`workspace-alias-repointed`:return new WorkspaceAliasRepointedError(e);case`session-goal-operation`:return new SessionGoalOperationError(e.goalCode,e.message);case`session-lifecycle-upsert-conflict`:return new SessionEntryLifecycleUpsertConflictError(e.sessionKey);case`session-mutation-conflict`:return new SqliteSessionMutationConflictError(e.operationLabel);case`session-transcript-mutation-conflict`:return new SqliteTranscriptMutationConflictError(e.sessionId);case`session-transcript-writer-claim-rebound`:return new SessionTranscriptWriterClaimReboundError(e.refusal);case`session-metadata`:return new SessionMetadataUnavailableError(e.reason,void 0,e.missingTables);case`error`:return Error(e.message);case`mcp-oauth-corruption`:return new McpOAuthStoreCorruptionError(``,``);case`aggregate`:return AggregateError([],e.message);case`auth-profile-store-unreadable`:return new AuthProfileStoreUnreadableError(e.databasePath);case`state-owner-contention`:return new lt(e.databasePath);case`state-admission-pending`:return new rn(e.databasePath,e.message);case`state-offline-maintenance`:return new dt(e.databasePath,e.message);case`state-maintenance-scope`:return new mt(``);case`ownership-metadata`:return new Sr(e.databasePath,``);case`external-ownership`:return new tn(e.databasePath,e.managerId);case`plugin-blob`:return new PluginBlobStoreError(e.message,{code:e.blobCode,operation:e.operation,...e.path===void 0?{}:{path:e.path}});case`state-lease`:return new OpenClawStateLeaseError(e.message,{code:e.leaseCode,loss:e.leaseLoss});case`maintenance`:return new StartupMaintenanceRequiredError(e.kind,e.message);case`state-migration`:return new OpenClawStateDatabaseSchemaMigrationRequiredError(e.kind,e.pathname)}return new OpenClawAgentDatabaseMediaMigrationRequiredError(e.pathname,e.schemaVersion)}function isNativeErrorCode(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=2147483647}function isWorkerOutcomeCode(e){return e===`outcome-unknown`||e===`unavailable`}function decodeErrorGraph(e,t){try{if(e.version!==1)return;let n=e.nodes;if(t.includeOrdinary!==!0&&!n.some(e=>e.stateDatabasePath!==void 0||e.nativeOpen===!0||e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)||isNativeErrorCode(e.errcode)||It(e)||e.type===`aggregate`&&e.name===`OpenClawQuarantineReadCleanupError`||e.type!==`error`&&e.type!==`aggregate`))return;let r=n.map(e=>{if(e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)){let t=new Sn(e.message,e.code);return e.type===`error`?t:Tn(createError(e),t)}return createError(e)}),decodeValue=e=>`ref`in e?r[e.ref]:`value`in e?e.value:void 0;for(let[e,t]of n.entries()){let n=r[e];n.name=t.name,n.message=t.message,t.nativeOpen&&kr(n),t.stateDatabasePath!==void 0&&markOpenClawStateDatabaseFailure(n,t.stateDatabasePath);for(let[e,r]of Object.entries({...t.code===void 0?{}:{code:t.code},...t.errcode===void 0?{}:{errcode:t.errcode},...t.errno===void 0?{}:{errno:t.errno},...t.cause?{cause:decodeValue(t.cause)}:{}}))Object.defineProperty(n,e,{value:r,configurable:!0,writable:!0});n instanceof AggregateError&&(n.errors=(t.errors??[]).map(decodeValue))}return{errors:r,root:e.root}}catch{return}}const yo=i(Symbol.for(`openclaw.sharedStateWorkerErrorPayloads`),()=>/* @__PURE__ */ new WeakMap);function retainOpenClawStateWorkerErrorPayload(e,t){t&&yo.set(e,t)}function hydrateOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return e;let n=/* @__PURE__ */ new Map,r=[{error:e,finish:!1}],replace=e=>e instanceof Error?n.get(e)??e:e;for(;r.length>0;){let e=r.pop(),{error:i}=e;if(!e.finish){if(n.has(i))continue;n.set(i,i);let e=yo.get(i),a=e===void 0?void 0:decodeErrorGraph(e,t);if(a){n.set(i,a.errors[a.root]);continue}if(r.push({error:i,finish:!0}),i.cause instanceof Error&&r.push({error:i.cause,finish:!1}),i instanceof AggregateError)for(let e of i.errors)e instanceof Error&&r.push({error:e,finish:!1});continue}let a=replace(i.cause),s=i instanceof AggregateError?i.errors:void 0,c=s?.map(replace);if(a===i.cause&&(!c||c.every((e,t)=>e===s?.[t])))continue;let l=i instanceof AggregateError?AggregateError([],i.message):Error(i.message);Object.setPrototypeOf(l,Object.getPrototypeOf(i));let u=Object.getOwnPropertyDescriptors(i);`cause`in i&&(u.cause={configurable:!0,writable:!0,...u.cause,value:a}),c&&(u.errors={configurable:!0,writable:!0,...u.errors,value:c}),Object.defineProperties(l,u),n.set(i,l)}return n.get(e)}function isUndefined(e){return e===void 0||e===void 0}function isString(e){return typeof e==`string`}function isNumber(e){return typeof e==`number`}function isBoolean(e){return typeof e==`boolean`}function isNull(e){return e===null}function isDate(e){return e instanceof Date}function isBigInt(e){return typeof e==`bigint`}function isFunction(e){return typeof e==`function`}function isObject$1(e){return typeof e==`object`&&!!e}function freeze(e){return Object.freeze(e)}function asArray(e){return isReadonlyArray(e)?e:[e]}function isReadonlyArray(e){return Array.isArray(e)}function noop(e){return e}function getMessage(e){return e instanceof Error?e.message:String(e)}const A=freeze({is(e){return e.kind===`AlterTableNode`},create(e){return freeze({kind:`AlterTableNode`,table:e})},cloneWithTableProps(e,t){return freeze({...e,...t})},cloneWithColumnAlteration(e,t){return freeze({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}}),j=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),bo=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:j.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),xo=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:j.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),So=[`preserve rows`,`delete rows`,`drop`],M=freeze({is(e){return e.kind===`CreateTableNode`},create(e){return freeze({kind:`CreateTableNode`,table:e,columns:freeze([])})},cloneWithColumn(e,t){return freeze({...e,columns:freeze([...e.columns,t])})},cloneWithConstraint(e,t){return freeze({...e,constraints:e.constraints?freeze([...e.constraints,t]):freeze([t])})},cloneWithIndex(e,t){return freeze({...e,indexes:e.indexes?freeze([...e.indexes,t]):freeze([t])})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWith(e,t){return freeze({...e,...t})}}),Co=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:j.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:j.create(e),identifier:j.create(t)})}}),wo=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:Co.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),To=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:j.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),Eo=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),Do=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),Oo=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:Co.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:Co.createWithSchema(e,t)})}});function isOperationNodeSource(e){return isObject$1(e)&&isFunction(e.toOperationNode)}function isExpression(e){return isObject$1(e)&&`expressionType`in e&&isOperationNodeSource(e)}function isAliasedExpression(e){return isObject$1(e)&&`expression`in e&&isString(e.alias)&&isOperationNodeSource(e)}const ko=freeze({is(e){return e.kind===`SelectModifierNode`},create(e,t){return freeze({kind:`SelectModifierNode`,modifier:e,of:t})},createWithExpression(e){return freeze({kind:`SelectModifierNode`,rawModifier:e})}}),Ao=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),jo=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),Mo=freeze({is(e){return e.kind===`OnNode`},create(e){return freeze({kind:`OnNode`,on:e})},cloneWithOperation(e,t,n){return freeze({...e,on:t===`And`?Ao.create(e.on,n):jo.create(e.on,n)})}}),No=freeze({is(e){return e.kind===`JoinNode`},create(e,t){return freeze({kind:`JoinNode`,joinType:e,table:t,on:void 0})},createWithOn(e,t,n){return freeze({kind:`JoinNode`,joinType:e,table:t,on:Mo.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?Mo.cloneWithOperation(e.on,`And`,t):Mo.create(t)})}}),Po=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),Fo=freeze({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0});Object.keys(Fo);const Io=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(Io);const Lo=freeze({"->":!0,"->>":!0}),Ro=Object.keys(Lo),zo=freeze({...Fo,...Io,"||":!0}),Bo=Object.keys(zo),Vo=freeze({exists:!0,"not exists":!0});Object.keys(Vo);const Ho=freeze({...Vo,"-":!0,not:!0}),Uo=Object.keys(Ho);[...Bo,...Ro,...Uo];const Wo=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&zo[e]}function isJSONOperator(e){return isString(e)&&Lo[e]}function isUnaryOperator(e){return isString(e)&&Ho[e]}const N=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:j.create(e)})}}),Go=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Ko=freeze({is(e){return e.kind===`ReferenceNode`},create(e,t){return freeze({kind:`ReferenceNode`,table:t,column:e})},createSelectAll(e){return freeze({kind:`ReferenceNode`,table:e,column:Go.create()})}});var DynamicReferenceBuilder=class{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return parseSimpleReferenceExpression(this.#e)}};function isDynamicReferenceBuilder(e){return isObject$1(e)&&isOperationNodeSource(e)&&isString(e.dynamicReference)}const qo=freeze({is(e){return e.kind===`OrderByItemNode`},create(e,t){return freeze({kind:`OrderByItemNode`,orderBy:e,direction:t})},cloneWith(e,t){return freeze({...e,...t})}}),P=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return P.create([e],[])},createWithChild(e){return P.create([``,``],[e])},createWithChildren(e){return P.create(Array(e.length+1).fill(``),e)}}),Jo=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:j.create(e)})}});var Yo=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:qo.cloneWith(this.#e.node,{direction:P.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:qo.cloneWith(this.#e.node,{direction:P.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:qo.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:qo.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:qo.cloneWith(this.#e.node,{collation:Jo.create(e)})})}toOperationNode(){return this.#e.node}};const Xo=/* @__PURE__ */ new Set;function logOnce(e){Xo.has(e)||(Xo.add(e),console.log(e))}function isOrderByDirection(e){return e===`asc`||e===`desc`}function parseOrderBy(e){if(e.length===2)return[parseOrderByItem(e[0],e[1])];if(e.length===1){let[t]=e;return Array.isArray(t)?(logOnce(`orderBy(array) is deprecated, use multiple orderBy calls instead.`),t.map(e=>parseOrderByItem(e))):[parseOrderByItem(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function parseOrderByItem(e,t){let n=parseOrderByExpression(e);if(qo.is(n)){if(t)throw Error(`Cannot specify direction twice!`);return n}return parseOrderByWithModifiers(n,t)}function parseOrderByExpression(e){if(isExpressionOrFactory(e))return parseExpression(e);if(isDynamicReferenceBuilder(e))return e.toOperationNode();let[t,n]=e.split(` `);return n?(logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),parseOrderByWithModifiers(parseStringReference(t),n)):parseStringReference(e)}function parseOrderByWithModifiers(e,t){if(typeof t==`string`){if(!isOrderByDirection(t))throw Error(`Invalid order by direction: ${t}`);return qo.create(e,P.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),qo.create(e,t.toOperationNode());let n=qo.create(e);return t?t(new Yo({node:n})).toOperationNode():n}const Zo=freeze({is(e){return e.kind===`JSONReferenceNode`},create(e,t){return freeze({kind:`JSONReferenceNode`,reference:e,traversal:t})},cloneWithTraversal(e,t){return freeze({...e,traversal:t})}}),Qo=freeze({is(e){return e.kind===`JSONOperatorChainNode`},create(e){return freeze({kind:`JSONOperatorChainNode`,operator:e,values:freeze([])})},cloneWithValue(e,t){return freeze({...e,values:freeze([...e.values,t])})}}),$o=freeze({is(e){return e.kind===`JSONPathNode`},create(e){return freeze({kind:`JSONPathNode`,inOperator:e,pathLegs:freeze([])})},cloneWithLeg(e,t){return freeze({...e,pathLegs:freeze([...e.pathLegs,t])})}});function parseSimpleReferenceExpression(e){return isString(e)?parseStringReference(e):e.toOperationNode()}function parseReferenceExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseReferenceExpression(e)):[parseReferenceExpression(e)]}function parseReferenceExpression(e){return isExpressionOrFactory(e)?parseExpression(e):parseSimpleReferenceExpression(e)}function parseJSONReference(e,t){if(isJSONOperator(t))return Zo.create(parseStringReference(e),Qo.create(Wo.create(t)));if(t===`->$`||t===`->>$`)return Zo.create(parseStringReference(e),$o.create(Wo.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Ko.create(N.create(e));let t=e.split(`.`).map(trim$2);if(t.length===3)return parseStringReferenceWithTableAndSchema(t);if(t.length===2)return parseStringReferenceWithTable(t);throw Error(`invalid column reference ${e}`)}function parseAliasedStringReference(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$2);return Do.create(parseStringReference(n),j.create(r))}return parseStringReference(e)}function parseColumnName(e){return N.create(e)}function parseOrderedColumnName(e){if(e.includes(` `)){let[t,n]=e.split(` `).map(trim$2);if(!isOrderByDirection(n))throw Error(`invalid order direction "${n}" next to "${t}"`);return parseOrderBy([t,n])[0]}return parseColumnName(e)}function parseStringReferenceWithTableAndSchema(e){let[t,n,r]=e;return Ko.create(N.create(r),Oo.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Ko.create(N.create(n),Oo.create(t))}function trim$2(e){return e.trim()}const es=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),ts=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),F=freeze({is(e){return e.kind===`ValueNode`},create(e){return freeze({kind:`ValueNode`,value:e})},createImmediate(e){return freeze({kind:`ValueNode`,value:e,immediate:!0})}});function parseValueExpressionOrList(e){return isReadonlyArray(e)?parseValueExpressionList(e):parseValueExpression(e)}function parseValueExpression(e){return isExpressionOrFactory(e)?parseExpression(e):F.create(e)}function isSafeImmediateValue(e){return isNumber(e)||isBoolean(e)||isNull(e)}function parseSafeImmediateValue(e){if(!isSafeImmediateValue(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return F.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?ts.create(e.map(e=>parseValueExpression(e))):es.create(e)}const ns=freeze({is(e){return e.kind===`ParensNode`},create(e){return freeze({kind:`ParensNode`,node:e})}});function parseValueBinaryOperationOrExpression(e){if(e.length===3)return parseValueBinaryOperation(e[0],e[1],e[2]);if(e.length===1)return parseValueExpression(e[0]);throw Error(`invalid arguments: ${JSON.stringify(e)}`)}function parseValueBinaryOperation(e,t,n){return isIsOperator(t)&&needsIsOperator(n)?Po.create(parseReferenceExpression(e),parseBinaryOperator(t),F.createImmediate(n)):Po.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return Po.create(parseReferenceExpression(e),parseBinaryOperator(t),parseReferenceExpression(n))}function parseFilterObject(e,t){return parseFilterList(Object.entries(e).filter(([,e])=>!isUndefined(e)).map(([e,t])=>parseValueBinaryOperation(e,needsIsOperator(t)?`is`:`=`,t)),t)}function parseFilterList(e,t,n=!0){let r=t===`and`?Ao.create:jo.create;if(e.length===0)return Po.create(F.createImmediate(1),Wo.create(`=`),F.createImmediate(+(t===`and`)));let i=toOperationNode(e[0]);for(let t=1;t<e.length;++t)i=r(i,toOperationNode(e[t]));return e.length>1&&n?ns.create(i):i}function isIsOperator(e){return e===`is`||e===`is not`}function needsIsOperator(e){return isNull(e)||isBoolean(e)}function parseBinaryOperator(e){if(isBinaryOperator(e))return Wo.create(e);if(isOperationNodeSource(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function toOperationNode(e){return isOperationNodeSource(e)?e.toOperationNode():e}const rs=freeze({is(e){return e.kind===`OrderByNode`},create(e){return freeze({kind:`OrderByNode`,items:freeze([...e])})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),is=freeze({is(e){return e.kind===`PartitionByNode`},create(e){return freeze({kind:`PartitionByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),as=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?rs.cloneWithItems(e.orderBy,t):rs.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?is.cloneWithItems(e.partitionBy,t):is.create(t)})}}),os=freeze({is(e){return e.kind===`FromNode`},create(e){return freeze({kind:`FromNode`,froms:freeze(e)})},cloneWithFroms(e,t){return freeze({...e,froms:freeze([...e.froms,...t])})}}),ss=freeze({is(e){return e.kind===`GroupByNode`},create(e){return freeze({kind:`GroupByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),cs=freeze({is(e){return e.kind===`HavingNode`},create(e){return freeze({kind:`HavingNode`,having:e})},cloneWithOperation(e,t,n){return freeze({...e,having:t===`And`?Ao.create(e.having,n):jo.create(e.having,n)})}}),I=freeze({is(e){return e.kind===`InsertQueryNode`},create(e,t,n){return freeze({kind:`InsertQueryNode`,into:e,...t&&{with:t},replace:n})},createWithoutInto(){return freeze({kind:`InsertQueryNode`})},cloneWith(e,t){return freeze({...e,...t})}}),ls=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),us=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:ls.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?os.cloneWithFroms(e.from,t):os.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),ds=freeze({is(e){return e.kind===`UsingNode`},create(e){return freeze({kind:`UsingNode`,tables:freeze(e)})},cloneWithTables(e,t){return freeze({...e,tables:freeze([...e.tables,...t])})}}),fs=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:os.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>R.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>R.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithUsing(e,t){return freeze({...e,using:e.using===void 0?ds.create(t):ds.cloneWithTables(e.using,t)})}}),L=freeze({is(e){return e.kind===`WhereNode`},create(e){return freeze({kind:`WhereNode`,where:e})},cloneWithOperation(e,t,n){return freeze({...e,where:t===`And`?Ao.create(e.where,n):jo.create(e.where,n)})}}),ps=freeze({is(e){return e.kind===`ReturningNode`},create(e){return freeze({kind:`ReturningNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),ms=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),hs=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),gs=freeze({is(e){return e.kind===`MergeQueryNode`},create(e,t){return freeze({kind:`MergeQueryNode`,into:e,...t&&{with:t}})},cloneWithUsing(e,t){return freeze({...e,using:t})},cloneWithWhen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens,t]):freeze([t])})},cloneWithThen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens.slice(0,-1),hs.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),_s=freeze({is(e){return e.kind===`OutputNode`},create(e){return freeze({kind:`OutputNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),R=freeze({is(e){return z.is(e)||I.is(e)||us.is(e)||fs.is(e)||gs.is(e)},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWithWhere(e,t){return freeze({...e,where:e.where?L.cloneWithOperation(e.where,`And`,t):L.create(t)})},cloneWithJoin(e,t){return freeze({...e,joins:e.joins?freeze([...e.joins,t]):freeze([t])})},cloneWithReturning(e,t){return freeze({...e,returning:e.returning?ps.cloneWithSelections(e.returning,t):ps.create(t)})},cloneWithoutReturning(e){return freeze({...e,returning:void 0})},cloneWithoutWhere(e){return freeze({...e,where:void 0})},cloneWithExplain(e,t,n){return freeze({...e,explain:ms.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?_s.cloneWithSelections(e.output,t):_s.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?rs.cloneWithItems(e.orderBy,t):rs.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),z=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:os.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})},cloneWithDistinctOn(e,t){return freeze({...e,distinctOn:e.distinctOn?freeze([...e.distinctOn,...t]):freeze(t)})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithOrderByItems:(e,t)=>R.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?ss.cloneWithItems(e.groupBy,t):ss.create(t)})},cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithOffset(e,t){return freeze({...e,offset:t})},cloneWithFetch(e,t){return freeze({...e,fetch:t})},cloneWithHaving(e,t){return freeze({...e,having:e.having?cs.cloneWithOperation(e.having,`And`,t):cs.create(t)})},cloneWithSetOperations(e,t){return freeze({...e,setOperations:e.setOperations?freeze([...e.setOperations,...t]):freeze([...t])})},cloneWithoutSelections(e){return freeze({...e,selections:[]})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithoutOffset(e){return freeze({...e,offset:void 0})},cloneWithoutOrderBy:e=>R.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var vs=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:No.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:No.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:No.cloneWithOn(this.#e.joinNode,P.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const ys=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(ys.create)}var bs=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:as.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:R.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:as.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const xs=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:Go.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Ko.createSelectAll(e)})}});function parseSelectArg(e){return isFunction(e)?parseSelectArg(e(expressionBuilder())):isReadonlyArray(e)?e.map(e=>parseSelectExpression(e)):[parseSelectExpression(e)]}function parseSelectExpression(e){return isString(e)?xs.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?xs.create(e.toOperationNode()):xs.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[xs.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return xs.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const Ss=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),Cs=freeze({is(e){return e.kind===`DefaultInsertValueNode`},create(){return freeze({kind:`DefaultInsertValueNode`})}});function parseInsertExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return parseInsertColumnsAndValues(isReadonlyArray(t)?t:freeze([t]))}function parseInsertColumnsAndValues(e){let t=parseColumnNamesAndIndexes(e);return[freeze([...t.keys()].map(N.create)),Ss.create(e.map(e=>parseRowValues(e,t)))]}function parseColumnNamesAndIndexes(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Object.keys(n);for(let r of e)!t.has(r)&&n[r]!==void 0&&t.set(r,t.size)}return t}function parseRowValues(e,t){let n=Object.keys(e),r=Array.from({length:t.size}),i=!1,a=n.length;for(let s of n){let n=t.get(s);if(isUndefined(n)){a--;continue}let c=e[s];(isUndefined(c)||isExpressionOrFactory(c))&&(i=!0),r[n]=c}if(a<t.size||i){let e=Cs.create();return ts.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return es.create(r)}const ws=freeze({is(e){return e.kind===`ColumnUpdateNode`},create(e,t){return freeze({kind:`ColumnUpdateNode`,column:e,value:t})}});function parseUpdate(...e){return e.length===2?[ws.create(parseReferenceExpression(e[0]),parseValueExpression(e[1]))]:parseUpdateObjectExpression(e[0])}function parseUpdateObjectExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>ws.create(N.create(e),parseValueExpression(t)))}const Ts=freeze({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return freeze({kind:`OnDuplicateKeyNode`,updates:e})}});var InsertResult=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}},NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}const Es=freeze({is(e){return e.kind===`OnConflictNode`},create(){return freeze({kind:`OnConflictNode`})},cloneWith(e,t){return freeze({...e,...t})},cloneWithIndexWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?L.cloneWithOperation(e.indexWhere,`And`,t):L.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?L.cloneWithOperation(e.indexWhere,`Or`,t):L.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?L.cloneWithOperation(e.updateWhere,`And`,t):L.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?L.cloneWithOperation(e.updateWhere,`Or`,t):L.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var Ds=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=N.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(N.create);return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,...t]):freeze(t)})})}constraint(e){return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWith(this.#e.onConflictNode,{constraint:j.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:Es.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:Es.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new Os({...this.#e,onConflictNode:Es.cloneWith(this.#e.onConflictNode,{updates:parseUpdateObjectExpression(e)})})}$call(e){return e(this)}},OnConflictDoNothingBuilder=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.onConflictNode}},Os=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:Es.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:Es.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:Es.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const ks=freeze({is(e){return e.kind===`TopNode`},create(e,t){return freeze({kind:`TopNode`,expression:e,modifiers:t})}});function parseTop(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid top expression: ${e}`);if(!isUndefined(t)&&!isTopModifiers(t))throw Error(`Invalid top modifiers: ${t}`);return ks.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const As=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var js=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{columns:freeze(e.map(N.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{orAction:As.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{orAction:As.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{orAction:As.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{orAction:As.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{orAction:As.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{orAction:As.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{onConflict:e(new Ds({onConflictNode:Es.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:I.cloneWith(this.#e.queryNode,{onDuplicateKey:Ts.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new InsertQueryBuilder({...this.#e})}$castTo(){return new InsertQueryBuilder(this.#e)}$narrowType(){return new InsertQueryBuilder(this.#e)}$assertType(){return new InsertQueryBuilder(this.#e)}withPlugin(e){return new InsertQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new InsertResult(n.insertId,n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new InsertQueryBuilder({...this.#e,queryNode:R.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const Ms=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var B,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new B({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new B({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new B({...this.#e,queryNode:R.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new B({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new B({...this.#e,queryNode:fs.cloneWithUsing(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new B({...this.#e,queryNode:R.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new B({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new B({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new B({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new B({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new B({...this.#e,queryNode:R.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new B({...this.#e,queryNode:fs.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new B({...this.#e,queryNode:R.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new B({...this.#e,queryNode:R.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new B({...this.#e,queryNode:fs.cloneWithLimit(this.#e.queryNode,Ms.create(parseValueExpression(e)))})}modifyEnd(e){return new B({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new B({...this.#e})}$castTo(){return new B(this.#e)}$narrowType(){return new B(this.#e)}$assertType(){return new B(this.#e)}withPlugin(e){return new B({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new DeleteResult(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new B({...this.#e,queryNode:R.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};B=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},V,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new V({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new V({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new V({...this.#e,queryNode:R.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new V({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new V({...this.#e,queryNode:us.cloneWithFromItems(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new V({...this.#e,queryNode:R.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new V({...this.#e,queryNode:R.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new V({...this.#e,queryNode:R.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new V({...this.#e,queryNode:us.cloneWithLimit(this.#e.queryNode,Ms.create(parseValueExpression(e)))})}set(...e){return new V({...this.#e,queryNode:us.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new V({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new V({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new V({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new V({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new V({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new V({...this.#e,queryNode:R.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new V({...this.#e})}$castTo(){return new V(this.#e)}$narrowType(){return new V(this.#e)}$assertType(){return new V(this.#e)}withPlugin(e){return new V({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new UpdateResult(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new V({...this.#e,queryNode:R.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};V=UpdateQueryBuilder;const Ns=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:Oo.create(e),columns:t?freeze(t.map(N.create)):void 0})}}),Ps=freeze({is(e){return e.kind===`CommonTableExpressionNode`},create(e,t){return freeze({kind:`CommonTableExpressionNode`,name:e,expression:t})},cloneWith(e,t){return freeze({...e,...t})}});var Fs=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:Ps.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:Ps.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}};function parseCommonTableExpression(e,t){let n=isOperationNodeSource(t)?t.toOperationNode():t(createQueryCreator()).toOperationNode();return isFunction(e)?e(cteBuilderFactory(n)).toOperationNode():Ps.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new Fs({node:Ps.create(parseCommonTableExpressionName(t),e)})}function parseCommonTableExpressionName(e){if(e.includes(`(`)){let t=e.split(/[\(\)]/),n=t[0],r=t[1].split(`,`).map(e=>e.trim());return Ns.create(n,r)}return Ns.create(e)}const Is=freeze({is(e){return e.kind===`WithNode`},create(e,t){return freeze({kind:`WithNode`,expressions:freeze([e]),...t})},cloneWithExpression(e,t){return freeze({...e,expressions:freeze([...e.expressions,t])})}}),Ls=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return Ls[~~(Math.random()*Ls.length)]}function createQueryId(){return new LazyQueryId}var LazyQueryId=class{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}},OperationNodeTransformer=class{nodeStack=[];#e=freeze({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(e,t){if(!e)return e;this.nodeStack.push(e);let n=this.transformNodeImpl(e,t);return this.nodeStack.pop(),freeze(n)}transformNodeImpl(e,t){return this.#e[e.kind](e,t)}transformNodeList(e,t){return e&&freeze(e.map(e=>this.transformNode(e,t)))}transformSelectQuery(e,t){return{kind:`SelectQueryNode`,from:this.transformNode(e.from,t),selections:this.transformNodeList(e.selections,t),distinctOn:this.transformNodeList(e.distinctOn,t),joins:this.transformNodeList(e.joins,t),groupBy:this.transformNode(e.groupBy,t),orderBy:this.transformNode(e.orderBy,t),where:this.transformNode(e.where,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),limit:this.transformNode(e.limit,t),offset:this.transformNode(e.offset,t),with:this.transformNode(e.with,t),having:this.transformNode(e.having,t),explain:this.transformNode(e.explain,t),setOperations:this.transformNodeList(e.setOperations,t),fetch:this.transformNode(e.fetch,t),top:this.transformNode(e.top,t)}}transformSelection(e,t){return{kind:`SelectionNode`,selection:this.transformNode(e.selection,t)}}transformColumn(e,t){return{kind:`ColumnNode`,column:this.transformNode(e.column,t)}}transformAlias(e,t){return{kind:`AliasNode`,node:this.transformNode(e.node,t),alias:this.transformNode(e.alias,t)}}transformTable(e,t){return{kind:`TableNode`,table:this.transformNode(e.table,t)}}transformFrom(e,t){return{kind:`FromNode`,froms:this.transformNodeList(e.froms,t)}}transformReference(e,t){return{kind:`ReferenceNode`,column:this.transformNode(e.column,t),table:this.transformNode(e.table,t)}}transformAnd(e,t){return{kind:`AndNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformOr(e,t){return{kind:`OrNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformValueList(e,t){return{kind:`ValueListNode`,values:this.transformNodeList(e.values,t)}}transformParens(e,t){return{kind:`ParensNode`,node:this.transformNode(e.node,t)}}transformJoin(e,t){return{kind:`JoinNode`,joinType:e.joinType,table:this.transformNode(e.table,t),on:this.transformNode(e.on,t)}}transformRaw(e,t){return{kind:`RawNode`,sqlFragments:freeze([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,t)}}transformWhere(e,t){return{kind:`WhereNode`,where:this.transformNode(e.where,t)}}transformInsertQuery(e,t){return{kind:`InsertQueryNode`,into:this.transformNode(e.into,t),columns:this.transformNodeList(e.columns,t),values:this.transformNode(e.values,t),returning:this.transformNode(e.returning,t),onConflict:this.transformNode(e.onConflict,t),onDuplicateKey:this.transformNode(e.onDuplicateKey,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orAction:this.transformNode(e.orAction,t),replace:e.replace,explain:this.transformNode(e.explain,t),defaultValues:e.defaultValues,top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformValues(e,t){return{kind:`ValuesNode`,values:this.transformNodeList(e.values,t)}}transformDeleteQuery(e,t){return{kind:`DeleteQueryNode`,from:this.transformNode(e.from,t),using:this.transformNode(e.using,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orderBy:this.transformNode(e.orderBy,t),limit:this.transformNode(e.limit,t),explain:this.transformNode(e.explain,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformReturning(e,t){return{kind:`ReturningNode`,selections:this.transformNodeList(e.selections,t)}}transformCreateTable(e,t){return{kind:`CreateTableNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),constraints:this.transformNodeList(e.constraints,t),indexes:this.transformNodeList(e.indexes,t),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),selectQuery:this.transformNode(e.selectQuery,t)}}transformColumnDefinition(e,t){return{kind:`ColumnDefinitionNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),references:this.transformNode(e.references,t),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,t),check:this.transformNode(e.check,t),generated:this.transformNode(e.generated,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,t){return{kind:`AddColumnNode`,column:this.transformNode(e.column,t)}}transformDropTable(e,t){return{kind:`DropTableNode`,table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade,temporary:e.temporary}}transformOrderBy(e,t){return{kind:`OrderByNode`,items:this.transformNodeList(e.items,t)}}transformOrderByItem(e,t){return{kind:`OrderByItemNode`,orderBy:this.transformNode(e.orderBy,t),direction:this.transformNode(e.direction,t),collation:this.transformNode(e.collation,t),nulls:e.nulls}}transformGroupBy(e,t){return{kind:`GroupByNode`,items:this.transformNodeList(e.items,t)}}transformGroupByItem(e,t){return{kind:`GroupByItemNode`,groupBy:this.transformNode(e.groupBy,t)}}transformUpdateQuery(e,t){return{kind:`UpdateQueryNode`,table:this.transformNode(e.table,t),from:this.transformNode(e.from,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),updates:this.transformNodeList(e.updates,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),explain:this.transformNode(e.explain,t),limit:this.transformNode(e.limit,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t),orderBy:this.transformNode(e.orderBy,t)}}transformColumnUpdate(e,t){return{kind:`ColumnUpdateNode`,column:this.transformNode(e.column,t),value:this.transformNode(e.value,t)}}transformLimit(e,t){return{kind:`LimitNode`,limit:this.transformNode(e.limit,t)}}transformOffset(e,t){return{kind:`OffsetNode`,offset:this.transformNode(e.offset,t)}}transformOnConflict(e,t){return{kind:`OnConflictNode`,columns:this.transformNodeList(e.columns,t),constraint:this.transformNode(e.constraint,t),indexExpression:this.transformNode(e.indexExpression,t),indexWhere:this.transformNode(e.indexWhere,t),updates:this.transformNodeList(e.updates,t),updateWhere:this.transformNode(e.updateWhere,t),doNothing:e.doNothing}}transformOnDuplicateKey(e,t){return{kind:`OnDuplicateKeyNode`,updates:this.transformNodeList(e.updates,t)}}transformCreateIndex(e,t){return{kind:`CreateIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,t),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,t){return{kind:`ListNode`,items:this.transformNodeList(e.items,t)}}transformDropIndex(e,t){return{kind:`DropIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,t){return{kind:`PrimaryKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,t){return{kind:`UniqueConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,t){return{kind:`ForeignKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),references:this.transformNode(e.references,t),name:this.transformNode(e.name,t),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,t){return{kind:`SetOperationNode`,operator:e.operator,expression:this.transformNode(e.expression,t),all:e.all}}transformReferences(e,t){return{kind:`ReferencesNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,t){return{kind:`CheckConstraintNode`,expression:this.transformNode(e.expression,t),name:this.transformNode(e.name,t)}}transformWith(e,t){return{kind:`WithNode`,expressions:this.transformNodeList(e.expressions,t),recursive:e.recursive}}transformCommonTableExpression(e,t){return{kind:`CommonTableExpressionNode`,name:this.transformNode(e.name,t),materialized:e.materialized,expression:this.transformNode(e.expression,t)}}transformCommonTableExpressionName(e,t){return{kind:`CommonTableExpressionNameNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t)}}transformHaving(e,t){return{kind:`HavingNode`,having:this.transformNode(e.having,t)}}transformCreateSchema(e,t){return{kind:`CreateSchemaNode`,schema:this.transformNode(e.schema,t),ifNotExists:e.ifNotExists}}transformDropSchema(e,t){return{kind:`DropSchemaNode`,schema:this.transformNode(e.schema,t),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,t){return{kind:`AlterTableNode`,table:this.transformNode(e.table,t),renameTo:this.transformNode(e.renameTo,t),setSchema:this.transformNode(e.setSchema,t),columnAlterations:this.transformNodeList(e.columnAlterations,t),addConstraint:this.transformNode(e.addConstraint,t),dropConstraint:this.transformNode(e.dropConstraint,t),renameConstraint:this.transformNode(e.renameConstraint,t),addIndex:this.transformNode(e.addIndex,t),dropIndex:this.transformNode(e.dropIndex,t)}}transformDropColumn(e,t){return{kind:`DropColumnNode`,column:this.transformNode(e.column,t),ifExists:e.ifExists}}transformRenameColumn(e,t){return{kind:`RenameColumnNode`,column:this.transformNode(e.column,t),renameTo:this.transformNode(e.renameTo,t)}}transformAlterColumn(e,t){return{kind:`AlterColumnNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),dataTypeExpression:this.transformNode(e.dataTypeExpression,t),setDefault:this.transformNode(e.setDefault,t),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,t){return{kind:`ModifyColumnNode`,column:this.transformNode(e.column,t)}}transformAddConstraint(e,t){return{kind:`AddConstraintNode`,constraint:this.transformNode(e.constraint,t)}}transformDropConstraint(e,t){return{kind:`DropConstraintNode`,constraintName:this.transformNode(e.constraintName,t),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,t){return{kind:`RenameConstraintNode`,oldName:this.transformNode(e.oldName,t),newName:this.transformNode(e.newName,t)}}transformCreateView(e,t){return{kind:`CreateViewNode`,name:this.transformNode(e.name,t),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,t),as:this.transformNode(e.as,t)}}transformRefreshMaterializedView(e,t){return{kind:`RefreshMaterializedViewNode`,name:this.transformNode(e.name,t),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,t){return{kind:`DropViewNode`,name:this.transformNode(e.name,t),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,t){return{kind:`GeneratedNode`,byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,t)}}transformDefaultValue(e,t){return{kind:`DefaultValueNode`,defaultValue:this.transformNode(e.defaultValue,t)}}transformOn(e,t){return{kind:`OnNode`,on:this.transformNode(e.on,t)}}transformSelectModifier(e,t){return{kind:`SelectModifierNode`,modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,t),of:this.transformNodeList(e.of,t)}}transformCreateType(e,t){return{kind:`CreateTypeNode`,name:this.transformNode(e.name,t),enum:this.transformNode(e.enum,t)}}transformDropType(e,t){return{kind:`DropTypeNode`,name:this.transformNode(e.name,t),additionalNames:this.transformNodeList(e.additionalNames,t),cascade:e.cascade,ifExists:e.ifExists}}transformExplain(e,t){return{kind:`ExplainNode`,format:e.format,options:this.transformNode(e.options,t)}}transformSchemableIdentifier(e,t){return{kind:`SchemableIdentifierNode`,schema:this.transformNode(e.schema,t),identifier:this.transformNode(e.identifier,t)}}transformAggregateFunction(e,t){return{kind:`AggregateFunctionNode`,func:e.func,aggregated:this.transformNodeList(e.aggregated,t),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,t),withinGroup:this.transformNode(e.withinGroup,t),filter:this.transformNode(e.filter,t),over:this.transformNode(e.over,t)}}transformOver(e,t){return{kind:`OverNode`,orderBy:this.transformNode(e.orderBy,t),partitionBy:this.transformNode(e.partitionBy,t)}}transformPartitionBy(e,t){return{kind:`PartitionByNode`,items:this.transformNodeList(e.items,t)}}transformPartitionByItem(e,t){return{kind:`PartitionByItemNode`,partitionBy:this.transformNode(e.partitionBy,t)}}transformBinaryOperation(e,t){return{kind:`BinaryOperationNode`,leftOperand:this.transformNode(e.leftOperand,t),operator:this.transformNode(e.operator,t),rightOperand:this.transformNode(e.rightOperand,t)}}transformUnaryOperation(e,t){return{kind:`UnaryOperationNode`,operator:this.transformNode(e.operator,t),operand:this.transformNode(e.operand,t)}}transformUsing(e,t){return{kind:`UsingNode`,tables:this.transformNodeList(e.tables,t)}}transformFunction(e,t){return{kind:`FunctionNode`,func:e.func,arguments:this.transformNodeList(e.arguments,t)}}transformCase(e,t){return{kind:`CaseNode`,value:this.transformNode(e.value,t),when:this.transformNodeList(e.when,t),else:this.transformNode(e.else,t),isStatement:e.isStatement}}transformWhen(e,t){return{kind:`WhenNode`,condition:this.transformNode(e.condition,t),result:this.transformNode(e.result,t)}}transformJSONReference(e,t){return{kind:`JSONReferenceNode`,reference:this.transformNode(e.reference,t),traversal:this.transformNode(e.traversal,t)}}transformJSONPath(e,t){return{kind:`JSONPathNode`,inOperator:this.transformNode(e.inOperator,t),pathLegs:this.transformNodeList(e.pathLegs,t)}}transformJSONPathLeg(e,t){return{kind:`JSONPathLegNode`,type:e.type,value:e.value}}transformJSONOperatorChain(e,t){return{kind:`JSONOperatorChainNode`,operator:this.transformNode(e.operator,t),values:this.transformNodeList(e.values,t)}}transformTuple(e,t){return{kind:`TupleNode`,values:this.transformNodeList(e.values,t)}}transformMergeQuery(e,t){return{kind:`MergeQueryNode`,into:this.transformNode(e.into,t),using:this.transformNode(e.using,t),whens:this.transformNodeList(e.whens,t),with:this.transformNode(e.with,t),top:this.transformNode(e.top,t),endModifiers:this.transformNodeList(e.endModifiers,t),output:this.transformNode(e.output,t),returning:this.transformNode(e.returning,t)}}transformMatched(e,t){return{kind:`MatchedNode`,not:e.not,bySource:e.bySource}}transformAddIndex(e,t){return{kind:`AddIndexNode`,name:this.transformNode(e.name,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists}}transformCast(e,t){return{kind:`CastNode`,expression:this.transformNode(e.expression,t),dataType:this.transformNode(e.dataType,t)}}transformFetch(e,t){return{kind:`FetchNode`,rowCount:this.transformNode(e.rowCount,t),modifier:e.modifier}}transformTop(e,t){return{kind:`TopNode`,expression:e.expression,modifiers:e.modifiers}}transformOutput(e,t){return{kind:`OutputNode`,selections:this.transformNodeList(e.selections,t)}}transformAlterType(e,t){return{kind:`AlterTypeNode`,name:this.transformNode(e.name,t),addValue:this.transformNode(e.addValue,t),renameTo:this.transformNode(e.renameTo,t),renameValue:this.transformNode(e.renameValue,t),setSchema:this.transformNode(e.setSchema,t)}}transformAddValue(e,t){return{kind:`AddValueNode`,value:this.transformNode(e.value,t),ifNotExists:e.ifNotExists,isBefore:e.isBefore,neighborValue:this.transformNode(e.neighborValue,t)}}transformRenameValue(e,t){return{kind:`RenameValueNode`,oldValue:this.transformNode(e.oldValue,t),newValue:this.transformNode(e.newValue,t)}}transformDataType(e,t){return e}transformSelectAll(e,t){return e}transformIdentifier(e,t){return e}transformValue(e,t){return e}transformPrimitiveValueList(e,t){return e}transformOperator(e,t){return e}transformDefaultInsertValue(e,t){return e}transformOrAction(e,t){return e}transformCollate(e,t){return e}};function isOperationNode(e){return isObject$1(e)&&isString(e.kind)}const Rs={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function isRootOperationNode(e){return isOperationNode(e)&&Rs[e.kind]===!0}const zs=freeze({json_agg:!0,to_json:!0});var WithSchemaTransformer=class extends OperationNodeTransformer{#e;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,t){if(!isRootOperationNode(e))return super.transformNodeImpl(e,t);let n=this.#a(e);for(let e of n)this.#n.add(e);let r=this.#i(e);for(let e of r)this.#t.add(e);let i=super.transformNodeImpl(e,t);for(let e of r)this.#t.delete(e);for(let e of n)this.#n.delete(e);return i}transformSchemableIdentifier(e,t){let n=super.transformSchemableIdentifier(e,t);return n.schema||!this.#t.has(e.identifier.name)?n:{...n,schema:j.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:Oo.createWithSchema(this.#e,n.table.table.identifier.name)}}transformAggregateFunction(e,t){return{...super.transformAggregateFunction({...e,aggregated:[]},t),aggregated:this.#r(e,t,`aggregated`)}}transformFunction(e,t){return{...super.transformFunction({...e,arguments:[]},t),arguments:this.#r(e,t,`arguments`)}}transformSelectModifier(e,t){return{...super.transformSelectModifier({...e,of:void 0},t),of:e.of?.map(e=>Oo.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return zs[e.func]?e[n].map(e=>!Oo.is(e)||e.table.schema?this.transformNode(e,t):{...e,table:this.transformIdentifier(e.table.identifier,t)}):this.transformNodeList(e[n],t)}#i(e){let t=/* @__PURE__ */ new Set;if(`name`in e&&e.name&&Co.is(e.name)&&this.#s(e.name,t),`from`in e&&e.from)for(let n of e.from.froms)this.#o(n,t);if(`into`in e&&e.into&&this.#o(e.into,t),`table`in e&&e.table&&this.#o(e.table,t),`joins`in e&&e.joins)for(let n of e.joins)this.#o(n.table,t);return`using`in e&&e.using&&(No.is(e.using)?this.#o(e.using.table,t):this.#o(e.using,t)),t}#a(e){let t=/* @__PURE__ */ new Set;return`with`in e&&e.with&&this.#c(e.with,t),t}#o(e,t){if(Oo.is(e))return this.#s(e.table,t);if(Do.is(e)&&Oo.is(e.node))return this.#s(e.node.table,t);if(ls.is(e))for(let n of e.items)this.#o(n,t);else if(ds.is(e))for(let n of e.tables)this.#o(n,t)}#s(e,t){let n=e.identifier.name;!this.#t.has(n)&&!this.#n.has(n)&&t.add(n)}#c(e,t){for(let n of e.expressions){let e=n.name.table.table.identifier.name;this.#n.has(e)||t.add(e)}}},WithSchemaPlugin=class{#e;constructor(e){this.#e=new WithSchemaTransformer(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}};const Bs=freeze({is(e){return e.kind===`MatchedNode`},create(e,t=!1){return freeze({kind:`MatchedNode`,not:e,bySource:t})}});function parseMergeWhen(e,t,n){return hs.create(parseFilterList([Bs.create(!e.isMatched,e.bySource),...t&&t.length>0?[t.length===3&&n?parseReferentialBinaryOperation(t[0],t[1],t[2]):parseValueBinaryOperationOrExpression(t)]:[]],`and`,!1))}function parseMergeThen(e){return isString(e)?P.create([e],[]):isOperationNodeSource(e)?e.toOperationNode():e}var Deferred=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function provideControlledConnection(e,t){let n=new Deferred,r=new Deferred;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),freeze({connection:await n.promise,release:r.resolve})}function getInflightQueryAbortHandler(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function throwUnsupportedInflightQueryAbortStrategyError(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function assertNotAborted(e,t,n){e?.aborted&&(n?.(),throwReasonWithTiming(e.reason,t))}function throwReasonWithTiming(e,t){throw decorateWithTiming(e,t),e}const Vs={};async function waitOrAbort(e,t,n,r){if(!t)return e;assertNotAborted(t,`before ${n}`,r);let{promise:i,resolve:a}=new Deferred,abortListener=()=>a(Vs);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==Vs)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(Vs)}}function printBackgroundFail(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${getMessage(t)}`)}function decorateWithTiming(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}const Hs=freeze([]);var QueryExecutorBase=class{#e;constructor(e=Hs){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let n of this.#e){let r=n.transformQuery({node:e,queryId:t});if(r.kind===e.kind)e=r;else throw Error([`KyselyPlugin.transformQuery must return a node`,`of the same kind that was given to it.`,`The plugin was given a ${e.kind}`,`but it returned a ${r.kind}`].join(` `))}return e}async executeQuery(e,t){let{inflightQueryAbortStrategy:n=`ignore query`,signal:r}=t||{};if(!r){let n=await this.provideConnection(async t=>await t.executeQuery(e),t);return await this.#t(n,e.queryId)}assertNotAborted(r,`before query execution`),t=freeze({signal:r});let{connection:i,release:a}=await provideControlledConnection(this,t),s=this.provideConnection.bind(this),{promise:c,resolve:l}=new Deferred,abortListener=()=>l(Vs);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let l=getInflightQueryAbortHandler(n,i,a);if(l&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([c,e]).catch(e=>{throw a(),e})===Vs&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let u=i.executeQuery(e,t),d=await Promise.race([c,u]).catch(e=>{throw a(),e});d===Vs?(Promise.allSettled([u.catch(printBackgroundFail(`query`)),l?.(s).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let f=this.#t(d,e.queryId,t),p=await Promise.race([c,f]);return p===Vs&&(f.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),p}finally{l(Vs),r.removeEventListener(`abort`,abortListener)}}async*stream(e,t,n){let{signal:r}=n||{};if(!r){let{connection:r,release:i}=await provideControlledConnection(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId,n)}finally{i()}return}n=freeze({signal:r}),assertNotAborted(r,`before connection acquisition`);let{connection:i,release:a}=await provideControlledConnection(this,n),{promise:s,resolve:c}=new Deferred,abortListener=()=>c(Vs);r.addEventListener(`abort`,abortListener,{once:!0});let l,u;assertNotAborted(r,`before query streaming`,a);let{queryId:d}=e;try{for(l=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=l.next(),t=await Promise.race([s,e]);if(t===Vs&&(u=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,d,n),a=await Promise.race([s,i]);a===Vs&&(u=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{c(Vs),r.removeEventListener(`abort`,abortListener);let e=(l?.return?.()||Promise.resolve()).finally(()=>u).finally(a);u||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(freeze({queryId:t,result:e,signal:r}));return e}};const Us=new class NoopQueryExecutor extends QueryExecutorBase{get adapter(){throw Error(`this query cannot be compiled to SQL`)}compileQuery(){throw Error(`this query cannot be compiled to SQL`)}provideConnection(){throw Error(`this query cannot be executed`)}withConnectionProvider(){throw Error(`this query cannot have a connection provider`)}withPlugin(e){return new NoopQueryExecutor([...this.plugins,e])}withPlugins(e){return new NoopQueryExecutor([...this.plugins,...e])}withPluginAtFront(e){return new NoopQueryExecutor([e,...this.plugins])}withoutPlugins(){return new NoopQueryExecutor([])}};var MergeResult=class{numChangedRows;constructor(e){this.numChangedRows=e}},Ws=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new Gs({...this.#e,queryNode:gs.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},Gs=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,t,n){return this.#t([e,t,n],!0)}#t(e,t){return new MatchedThenableMergeQueryBuilder({...this.#e,queryNode:gs.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!0},e,t))})}whenNotMatched(){return this.#n([])}whenNotMatchedAnd(...e){return this.#n(e)}whenNotMatchedAndRef(e,t,n){return this.#n([e,t,n],!0)}whenNotMatchedBySource(){return this.#n([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#n(e,!1,!0)}whenNotMatchedBySourceAndRef(e,t,n){return this.#n([e,t,n],!0,!0)}returning(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:gs.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!1,bySource:n},e,t))};return new(n?MatchedThenableMergeQueryBuilder:NotMatchedThenableMergeQueryBuilder)(r)}$call(e){return e(this)}$if(e,t){return e?t(this):new WheneableMergeQueryBuilder({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new MergeResult(n.numAffectedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}},MatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDelete(){return new Gs({...this.#e,queryNode:gs.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new Gs({...this.#e,queryNode:gs.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new Gs({...this.#e,queryNode:gs.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:Us,queryNode:us.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new Gs({...this.#e,queryNode:gs.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new Gs({...this.#e,queryNode:gs.cloneWithThen(this.#e.queryNode,parseMergeThen(I.cloneWith(I.createWithoutInto(),{columns:t,values:n})))})}},Ks=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:z.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:z.cloneWithSelections(z.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new js({queryId:createQueryId(),executor:this.#e.executor,queryNode:I.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new js({queryId:createQueryId(),executor:this.#e.executor,queryNode:I.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:fs.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:us.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new Ws({queryId:createQueryId(),executor:this.#e.executor,queryNode:gs.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?Is.cloneWithExpression(this.#e.withNode,n):Is.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?Is.cloneWithExpression(this.#e.withNode,n):Is.create(n,{recursive:!0})})}withPlugin(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new QueryCreator({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}};function createQueryCreator(){return new Ks({executor:Us})}function createJoinBuilder(e,t){return new vs({joinNode:No.create(e,parseTableExpression(t))})}function createOverBuilder(){return new bs({overNode:as.create()})}function parseJoin(e,t){if(t.length===3)return parseSingleOnJoin(e,t[0],t[1],t[2]);if(t.length===2)return parseCallbackJoin(e,t[0],t[1]);if(t.length===1)return parseOnlessJoin(e,t[0]);throw Error(`not implemented`)}function parseCallbackJoin(e,t,n){return n(createJoinBuilder(e,t)).toOperationNode()}function parseSingleOnJoin(e,t,n,r){return No.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return No.create(e,parseTableExpression(t))}const qs=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),Js=freeze({is(e){return e.kind===`GroupByItemNode`},create(e){return freeze({kind:`GroupByItemNode`,groupBy:e})}});function parseGroupBy(e){return e=isFunction(e)?e(expressionBuilder()):e,parseReferenceExpressionOrList(e).map(Js.create)}const Ys=freeze({is(e){return e.kind===`SetOperationNode`},create(e,t,n){return freeze({kind:`SetOperationNode`,operator:e,expression:t,all:n})}});function parseSetOperations(e,t,n){return isFunction(t)&&(t=t(createExpressionBuilder())),isReadonlyArray(t)||(t=[t]),t.map(t=>Ys.create(e,parseExpression(t),n))}var H=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Xs(jo.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new Zs(Ao.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new ExpressionWrapper(this.#e)}$notNull(){return new ExpressionWrapper(this.#e)}toOperationNode(){return this.#e}},AliasedExpressionWrapper=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Do.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():j.create(this.#t))}},Xs=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(jo.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return ns.create(this.#e)}},Zs=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(Ao.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return ns.create(this.#e)}};const Qs=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:F.create(e),modifier:t}}});function parseFetch(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid fetch row count: ${e}`);if(!isFetchModifier(t))throw Error(`Invalid fetch modifier: ${t}`);return Qs.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var U,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new U({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new U({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new U({...this.#e,queryNode:z.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new U({...this.#e,queryNode:z.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new U({...this.#e,queryNode:z.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new U({...this.#e,queryNode:z.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new U({...this.#e,queryNode:z.cloneWithFrontModifier(this.#e.queryNode,ko.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.createWithExpression(e.toOperationNode()))})}distinct(){return new U({...this.#e,queryNode:z.cloneWithFrontModifier(this.#e.queryNode,ko.create(`Distinct`))})}forUpdate(e){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.create(`SkipLocked`))})}noWait(){return new U({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ko.create(`NoWait`))})}selectAll(e){return new U({...this.#e,queryNode:z.cloneWithSelections(this.#e.queryNode,parseSelectAll(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}crossJoin(...e){return this.#t(`CrossJoin`,e)}innerJoinLateral(...e){return this.#t(`LateralInnerJoin`,e)}leftJoinLateral(...e){return this.#t(`LateralLeftJoin`,e)}crossJoinLateral(...e){return this.#t(`LateralCrossJoin`,e)}crossApply(...e){return this.#t(`CrossApply`,e)}outerApply(...e){return this.#t(`OuterApply`,e)}#t(e,t){return new U({...this.#e,queryNode:R.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new U({...this.#e,queryNode:R.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new U({...this.#e,queryNode:z.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new U({...this.#e,queryNode:z.cloneWithLimit(this.#e.queryNode,Ms.create(parseValueExpression(e)))})}offset(e){return new U({...this.#e,queryNode:z.cloneWithOffset(this.#e.queryNode,qs.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new U({...this.#e,queryNode:z.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new U({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new U({...this.#e,queryNode:z.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new U({...this.#e,queryNode:z.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new U({...this.#e,queryNode:z.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new U({...this.#e,queryNode:z.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new U({...this.#e,queryNode:z.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new U({...this.#e,queryNode:z.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new U({...this.#e,queryNode:z.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new U({...this.#e,queryNode:R.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new U({...this.#e,queryNode:z.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new U({...this.#e,queryNode:z.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new U({...this.#e,queryNode:R.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new U({...this.#e,queryNode:z.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new U({...this.#e})}$castTo(){return new U(this.#e)}$narrowType(){return new U(this.#e)}$assertType(){return new U(this.#e)}$asTuple(){return new H(this.toOperationNode())}$asScalar(){return new H(this.toOperationNode())}withPlugin(e){return new U({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();return(await this.#e.executor.executeQuery(t,e)).rows}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new U({...this.#e,queryNode:R.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};U=SelectQueryBuilderImpl;function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var AliasedSelectQueryBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Do.create(this.#e.toOperationNode(),j.create(this.#t))}};const $s=freeze({is(e){return e.kind===`AggregateFunctionNode`},create(e,t=[]){return freeze({kind:`AggregateFunctionNode`,func:e,aggregated:t})},cloneWithDistinct(e){return freeze({...e,distinct:!0})},cloneWithOrderBy(e,t,n=!1){let r=n?`withinGroup`:`orderBy`;return freeze({...e,[r]:e[r]?rs.cloneWithItems(e[r],t):rs.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?L.cloneWithOperation(e.filter,`And`,t):L.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?L.cloneWithOperation(e.filter,`Or`,t):L.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),ec=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var tc=class AggregateFunctionBuilder{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}as(e){return new AliasedAggregateFunctionBuilder(this,e)}distinct(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:$s.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:R.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:R.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:$s.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:$s.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:$s.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:$s.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(t):t).toOperationNode())})}$call(e){return e(this)}$castTo(){return new AggregateFunctionBuilder(this.#e)}$notNull(){return new AggregateFunctionBuilder(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},AliasedAggregateFunctionBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Do.create(this.#e.toOperationNode(),j.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new H(ec.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new tc({aggregateFunctionNode:$s.create(e,t?parseReferenceExpressionOrList(t):void 0)});return Object.assign(fn,{agg,avg(e){return agg(`avg`,[e])},coalesce(...e){return fn(`coalesce`,e)},count(e){return agg(`count`,[e])},countAll(e){return new tc({aggregateFunctionNode:$s.create(`count`,parseSelectAll(e))})},max(e){return agg(`max`,[e])},min(e){return agg(`min`,[e])},sum(e){return agg(`sum`,[e])},any(e){return fn(`any`,[e])},jsonAgg(e){return new tc({aggregateFunctionNode:$s.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new H(ec.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const nc=freeze({is(e){return e.kind===`UnaryOperationNode`},create(e,t){return freeze({kind:`UnaryOperationNode`,operator:e,operand:t})}});function parseUnaryOperation(e,t){if(isUnaryOperator(e))return nc.create(Wo.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const W=freeze({is(e){return e.kind===`CaseNode`},create(e){return freeze({kind:`CaseNode`,value:e})},cloneWithWhen(e,t){return freeze({...e,when:freeze(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return freeze({...e,when:e.when?freeze([...e.when.slice(0,-1),hs.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:W.cloneWithWhen(this.#e.node,hs.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:W.cloneWithWhen(this.#e.node,hs.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:W.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:W.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:W.cloneWithWhen(this.#e.node,hs.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:W.cloneWithWhen(this.#e.node,hs.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:W.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:W.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new H(W.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new H(W.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new H(W.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new H(W.cloneWith(this.#e.node,{isStatement:!0}))}};const rc=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),ic=/^#-\d+$/;var JSONPathBuilder=class{#e;constructor(e){this.#e=e}at(e){if(typeof e!=`number`&&typeof e!=`string`||typeof e==`number`&&!Number.isInteger(e)||typeof e==`string`&&e!==`last`&&!ic.test(e))throw Error(`Unexpected index value in .at(...): ${e}`);return this.#t(`ArrayLocation`,e)}key(e){return this.#t(`Member`,e)}#t(e,t){return Zo.is(this.#e)?new ac(Zo.cloneWithTraversal(this.#e,$o.is(this.#e.traversal)?$o.cloneWithLeg(this.#e.traversal,rc.create(e,t)):Qo.cloneWithValue(this.#e.traversal,F.createImmediate(t)))):new ac($o.cloneWithLeg(this.#e,rc.create(e,t)))}},ac=class TraversedJSONPathBuilder extends JSONPathBuilder{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new AliasedJSONPathBuilder(this,e)}$castTo(){return new TraversedJSONPathBuilder(this.#e)}$notNull(){return new TraversedJSONPathBuilder(this.#e)}toOperationNode(){return this.#e}},AliasedJSONPathBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Do.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():j.create(this.#t))}};const oc=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),sc=freeze({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),cc=freeze([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),lc=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return sc[e]||cc.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return lc.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const uc=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=Us){function binary(e,t,n){return new H(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new H(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:z.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:W.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new H(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder($o.create())},table(e){return new H(parseTable(e))},val(e){return new H(parseValueExpression(e))},refTuple(...e){return new H(oc.create(e.map(parseReferenceExpression)))},tuple(...e){return new H(oc.create(e.map(parseValueExpression)))},lit(e){return new H(parseSafeImmediateValue(e))},unary,not(e){return unary(`not`,e)},exists(e){return unary(`exists`,e)},neg(e){return unary(`-`,e)},between(e,t,n){return new H(Po.create(parseReferenceExpression(e),Wo.create(`between`),Ao.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new H(Po.create(parseReferenceExpression(e),Wo.create(`between symmetric`),Ao.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new H(parseFilterList(e,`and`)):new H(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new H(parseFilterList(e,`or`)):new H(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return ns.is(t)?new H(t):new H(ns.create(t))},cast(e,t){return new H(uc.create(parseReferenceExpression(e),parseDataTypeExpression(t)))}});return t.fn=createFunctionModule(),t.eb=t,t}function expressionBuilder(e){return createExpressionBuilder()}function parseExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function parseAliasedExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function isExpressionOrFactory(e){return isExpression(e)||isAliasedExpression(e)||isFunction(e)}var DynamicTableBuilder=class{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new AliasedDynamicTableBuilder(this.#e,e)}},AliasedDynamicTableBuilder=class{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,t){this.#e=e,this.#t=t}toOperationNode(){return Do.create(parseTable(this.#e),j.create(this.#t))}};function isAliasedDynamicTableBuilder(e){return isObject$1(e)&&isOperationNodeSource(e)&&isString(e.table)&&isString(e.alias)}function parseTableExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseTableExpression(e)):[parseTableExpression(e)]}function parseTableExpression(e){return isString(e)?parseAliasedTable(e):isAliasedDynamicTableBuilder(e)?e.toOperationNode():parseAliasedExpression(e)}function parseAliasedTable(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$1);return Do.create(parseTable(n),j.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return Oo.createWithSchema(t,n)}return Oo.create(e)}function trim$1(e){return e.trim()}const dc=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),G=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:N.create(e),dataType:t})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):[t]})},cloneWith(e,t){return freeze({...e,...t})}}),fc=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:N.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),pc=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:N.create(e),renameTo:N.create(t)})}}),mc=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?j.create(t):void 0})}}),hc=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(hc);const gc=freeze({is(e){return e.kind===`ReferencesNode`},create(e,t){return freeze({kind:`ReferencesNode`,table:e,columns:freeze([...t])})},cloneWithOnDelete(e,t){return freeze({...e,onDelete:t})},cloneWithOnUpdate(e,t){return freeze({...e,onUpdate:t})}});function isOnModifyForeignAction(e){return isString(e)&&hc[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():F.createImmediate(e)}const _c=freeze({is(e){return e.kind===`GeneratedNode`},create(e){return freeze({kind:`GeneratedNode`,...e})},createWithExpression(e){return freeze({kind:`GeneratedNode`,always:!0,expression:e})},cloneWith(e,t){return freeze({...e,...t})}}),vc=freeze({is(e){return e.kind===`DefaultValueNode`},create(e){return freeze({kind:`DefaultValueNode`,defaultValue:e})}});function parseOnModifyForeignAction(e){if(isOnModifyForeignAction(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}var yc=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||Go.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{references:gc.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error(`on delete constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{references:gc.cloneWithOnDelete(this.#e.references,parseOnModifyForeignAction(e))}))}onUpdate(e){if(!this.#e.references)throw Error(`on update constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{references:gc.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{defaultTo:vc.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{check:mc.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{generated:_c.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{generated:_c.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{generated:_c.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{generated:_c.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(G.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(G.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(G.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const bc=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),xc=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:gc.create(t,n),name:r?j.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var Sc=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(xc.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(xc.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(xc.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(xc.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(xc.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(xc.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Cc=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),wc=freeze({is(e){return e.kind===`UniqueConstraintNode`},create(e,t,n){return isString(e.at(0))&&(logOnce("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(N.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?j.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),Tc=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:j.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Ec=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:N.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(Ec.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(Ec.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(Ec.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(Ec.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(Ec.create(this.#e,`dropNotNull`,!0))}$call(e){return e(this)}},AlteredColumnBuilder=class{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}},AlterTableExecutor=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Dc=class AlterTableAddForeignKeyConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}onDelete(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(A.cloneWithTableProps(this.#e.node,{addConstraint:Cc.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Oc=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:Tc.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:Tc.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:Tc.cloneWith(this.#e.node.dropConstraint,{modifier:`restrict`})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const kc=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(N.create)),name:t?j.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),Ac=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:j.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var jc=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ac.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ac.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ac.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ac.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ac.cloneWith(this.#e.node.addIndex,{using:P.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Mc=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(wc.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(wc.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(wc.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(wc.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(wc.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},Nc=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(kc.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(kc.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(kc.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(kc.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},CheckConstraintBuilder=class{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}};const Pc=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:j.create(e),newName:j.create(t)})}});var Fc=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:fc.cloneWith(this.#e.node,{ifExists:!0})})}toOperationNode(){return this.#e.node}},AlterTableBuilder=class{#e;constructor(e){this.#e=freeze(e)}renameTo(e){return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{setSchema:j.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new Ic({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new Fc({node:fc.create(e)}));return new Ic({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new Ic({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,pc.create(e,t))})}addColumn(e,t,n=noop){let r=n(new yc(G.create(e,parseDataTypeExpression(t))));return new Ic({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,dc.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new yc(G.create(e,parseDataTypeExpression(t))));return new Ic({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,bc.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new Mc(wc.create(t.map(e=>isString(e)?N.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addConstraint:Cc.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(mc.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addConstraint:Cc.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Sc(xc.create(t.map(N.create),parseTable(n),r.map(N.create),e)));return new Dc({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new Nc(kc.create(t,e)));return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addConstraint:Cc.create(r.toOperationNode())})})}dropConstraint(e){return new Oc({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:Tc.create(e)})})}renameConstraint(e,t){return new Oc({...this.#e,node:A.cloneWithTableProps(this.#e.node,{renameConstraint:Pc.create(e,t)})})}addIndex(e){return new jc({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ac.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropIndex:wo.create(e)})})}$call(e){return e(this)}},Ic=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new Fc({node:fc.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,pc.create(e,t))})}addColumn(e,t,n=noop){let r=n(new yc(G.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,dc.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new yc(G.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,bc.create(r.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},ImmediateValueTransformer=class extends OperationNodeTransformer{transformPrimitiveValueList(e){return ts.create(e.values.map(F.createImmediate))}transformValue(e){return F.createImmediate(e.value)}},Lc=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:bo.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:bo.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:bo.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{using:P.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:R.cloneWithWhere(this.#e.node,t.transformNode(parseValueBinaryOperationOrExpression(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Rc=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:xo.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function parseOnCommitAction(e){if(So.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var zc=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(Ac.cloneWith(this.#e,{using:P.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},Bc=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:M.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:M.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:M.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new yc(G.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:M.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new Nc(kc.create(t,e)));return new CreateTableBuilder({...this.#e,node:M.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new Mc(wc.create(t.map(e=>isString(e)?N.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:M.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new zc(Ac.cloneWithColumns(Ac.create(e),t.map(e=>isString(e)?N.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:M.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(mc.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:M.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Sc(xc.create(t.map(N.create),parseTable(n),r.map(N.create),e)));return new CreateTableBuilder({...this.#e,node:M.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:M.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:M.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:M.cloneWith(this.#e.node,{selectQuery:parseExpression(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Vc=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:wo.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:wo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:wo.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Hc=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:To.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:To.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Uc=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Wc=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:Co.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var ImmediateValuePlugin=class{#e=new ImmediateValueTransformer;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}},Gc=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:Wc.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:Wc.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:Wc.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:Wc.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:Wc.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:Wc.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Kc=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:Co.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var qc=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:Kc.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:Kc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:Kc.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Jc=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:ts.create(t.map(F.createImmediate))})}});var Yc=class CreateTypeBuilder{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new CreateTypeBuilder({...this.#e,node:Jc.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Xc=freeze({is(e){return e.kind===`DropTypeNode`},create(e){return Array.isArray(e)||(e=[e]),freeze({kind:`DropTypeNode`,name:e[0],additionalNames:e.slice(1)})},cloneWith(e,t){return freeze({...e,...t})}});var Zc=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:Xc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:Xc.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function parseSchemableIdentifier(e){if(e.includes(`.`)){let t=e.split(`.`).map(trim);if(t.length===2)return Co.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return Co.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Qc=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:Co.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var $c=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Qc.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Qc.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Qc.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const el=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),tl=freeze({is(e){return e.kind===`AddValueNode`},create(e){return freeze({kind:`AddValueNode`,value:e})},cloneWith(e,t){return freeze({...e,...t})}});var QueryFinalizer=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){return await this.#e.executor.executeQuery(this.compile(),e)}},nl,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new nl({...this.#e,node:el.cloneWith(this.#e.node,{addValue:tl.cloneWith(this.#e.node.addValue,{ifNotExists:!0})})})}before(e){return this.#t(e,!0)}after(e){return this.#t(e,!1)}#t(e,t){return new nl({...this.#e,node:el.cloneWith(this.#e.node,{addValue:tl.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:F.createImmediate(e)})})})}};nl=AlterTypeAddValueBuilder;const rl=freeze({is(e){return e.kind===`RenameValueNode`},create(e,t){return freeze({kind:`RenameValueNode`,oldValue:e,newValue:t})}});var AlterTypeBuilder=class{#e;constructor(e){this.#e=freeze(e)}addValue(e){return new AlterTypeAddValueBuilder({...this.#e,node:el.cloneWith(this.#e.node,{addValue:tl.create(F.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:el.cloneWith(this.#e.node,{renameTo:j.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:el.cloneWith(this.#e.node,{renameValue:rl.create(F.createImmediate(e),F.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:el.cloneWith(this.#e.node,{setSchema:j.create(e)})})}},il=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new Bc({queryId:createQueryId(),executor:this.#e,node:M.create(parseTable(e))})}dropTable(e){return new Uc({queryId:createQueryId(),executor:this.#e,node:Eo.create(parseTable(e))})}createIndex(e){return new Lc({queryId:createQueryId(),executor:this.#e,node:bo.create(e)})}dropIndex(e){return new Vc({queryId:createQueryId(),executor:this.#e,node:wo.create(e)})}createSchema(e){return new Rc({queryId:createQueryId(),executor:this.#e,node:xo.create(e)})}dropSchema(e){return new Hc({queryId:createQueryId(),executor:this.#e,node:To.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:A.create(parseTable(e))})}createView(e){return new Gc({queryId:createQueryId(),executor:this.#e,node:Wc.create(e)})}refreshMaterializedView(e){return new $c({queryId:createQueryId(),executor:this.#e,node:Qc.create(e)})}dropView(e){return new qc({queryId:createQueryId(),executor:this.#e,node:Kc.create(e)})}createType(e){return new Yc({queryId:createQueryId(),executor:this.#e,node:Jc.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:el.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new Zc({queryId:createQueryId(),executor:this.#e,node:Xc.create(parseSchemableIdentifierArray(e))})}withPlugin(e){return new SchemaModule(this.#e.withPlugin(e))}withoutPlugins(){return new SchemaModule(this.#e.withoutPlugins())}withSchema(e){return new SchemaModule(this.#e.withPluginAtFront(new WithSchemaPlugin(e)))}},DynamicModule=class{ref(e){return new DynamicReferenceBuilder(e)}table(e){return new DynamicTableBuilder(e)}},DefaultConnectionProvider=class{#e;constructor(e){this.#e=e}async provideConnection(e,t){let n=await this.#e.acquireConnection(t);try{return await e(n)}finally{await this.#e.releaseConnection(n,t)}}},al=class DefaultQueryExecutor extends QueryExecutorBase{#e;#t;#n;constructor(e,t,n,r=[]){super(r),this.#e=e,this.#t=t,this.#n=n}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return this.#n.provideConnection(e,t)}withPlugins(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,...e])}withPlugin(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,e])}withPluginAtFront(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[e,...this.plugins])}withConnectionProvider(e){return new DefaultQueryExecutor(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[])}};function performanceNow(){return typeof performance<`u`&&isFunction(performance.now)?performance.now():Date.now()}var ConnectionMutex=class{#e;#t;async obtainLock(){for(;this.#e;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}releaseLock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},RuntimeDriver=class{#e;#t;#n;#r;#i;#a=/* @__PURE__ */ new WeakSet;#o;constructor(e,t,n){this.#e=e,this.#r=!1,this.#t=n,t.supportsMultipleConnections===!1&&(this.#o=new ConnectionMutex)}async init(e){if(this.#i)throw Error(`driver has already been destroyed`);this.#n??=this.#e.init(e).then(()=>{this.#r=!0}).catch(e=>{throw this.#n=void 0,e}),await waitOrAbort(this.#n,e?.signal,`init`)}async acquireConnection(e){if(this.#i)throw Error(`driver has already been destroyed`);if(this.#r||await this.init(e),this.#o){let t=this.#o.obtainLock();await waitOrAbort(t,e?.signal,`acquireConnection:mutex`,()=>t.then(()=>this.#o?.releaseLock()))}let t=this.#e.acquireConnection(e),n=await waitOrAbort(t,e?.signal,`acquireConnection:acquire`,()=>t?.then(e=>this.releaseConnection(e).catch(printBackgroundFail(`driver.releaseConnection`))).catch(printBackgroundFail(`driver.acquireConnection`)));return this.#a.has(n)||(this.#s()&&this.#c(n),this.#a.add(n)),n}async releaseConnection(e,t){await this.#e.releaseConnection(e,t),this.#o?.releaseLock()}async beginTransaction(e,t){return await this.#e.beginTransaction(e,t)}async commitTransaction(e){return await this.#e.commitTransaction(e)}async rollbackTransaction(e){return await this.#e.rollbackTransaction(e)}async savepoint(e,t,n){if(this.#e.savepoint)return await this.#e.savepoint(e,t,n);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(e,t,n){if(this.#e.rollbackToSavepoint)return await this.#e.rollbackToSavepoint(e,t,n);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(e,t,n){if(this.#e.releaseSavepoint)return await this.#e.releaseSavepoint(e,t,n);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(e){this.#n&&(await waitOrAbort(this.#n,e?.signal,`destroy:initPromise`),this.#i??=this.#e.destroy(e).catch(e=>{throw this.#i=void 0,e}),await waitOrAbort(this.#i,e?.signal,`destroy`))}#s(){return this.#t.isLevelEnabled(`query`)||this.#t.isLevelEnabled(`error`)}#c(e){let t=e.executeQuery,n=e.streamQuery,r=this;e.executeQuery=async(n,i)=>{let a,s=performanceNow();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,s),e}finally{a||await r.#u(n,s)}},e.streamQuery=async function*(t,i,a){let s,c=performanceNow();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw s=e,await r.#l(e,t,c),e}finally{s||await r.#u(t,c,!0)}}}async#l(e,t,n){await this.#t.error(()=>({level:`error`,error:e,query:t,queryDurationMillis:this.#d(n)}))}async#u(e,t,n=!1){await this.#t.query(()=>({level:`query`,isStream:n,query:e,queryDurationMillis:this.#d(t)}))}#d(e){return performanceNow()-e}};const ignoreError=()=>{};var SingleConnectionProvider=class{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch(ignoreError);return this.#t=this.#n(e).finally(()=>{this.#t=void 0}),this.#t}async#n(e){return await e(this.#e)}};const ol=[`read only`,`read write`],sl=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!ol.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!sl.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}freeze([`query`,`error`]);var Log=class{#e;#t;constructor(e){isFunction(e)?(this.#t=e,this.#e=freeze({query:!0,error:!0})):(this.#t=defaultLogger,this.#e=freeze({query:e.includes(`query`),error:e.includes(`error`)}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}};function defaultLogger(e){if(e.level===`query`){let t=`kysely:query:${e.isStream?`stream:`:``}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else e.level===`error`&&(e.error instanceof Error?console.error(`kysely:error: ${e.error.stack??e.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`))}function isCompilable(e){return isObject$1(e)&&isFunction(e.compile)}Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`);var cl=class Kysely extends Ks{#e;constructor(e){let t,n;if(isKyselyProps(e))t={executor:e.executor},n={...e};else{let r=e.dialect,i=r.createDriver(),a=r.createQueryCompiler(),s=r.createAdapter(),c=new RuntimeDriver(i,s,new Log(e.log??[])),l=new al(a,s,new DefaultConnectionProvider(c),e.plugins??[]);t={executor:l},n={config:e,executor:l,dialect:r,driver:c}}super(t),this.#e=freeze(n)}get schema(){return new il(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:W.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new ul({...this.#e})}startTransaction(){return new dl({...this.#e})}connection(){return new ConnectionBuilder({...this.#e})}withPlugin(e){return new Kysely({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Kysely({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Kysely({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}$extendTables(){return new Kysely({...this.#e})}$omitTables(){return new Kysely({...this.#e})}$pickTables(){return new Kysely({...this.#e})}withTables(){return this.$extendTables()}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}async executeQuery(e,t){let n=isCompilable(e)?e.compile():e;return await this.#e.executor.executeQuery(n,t)}async[Symbol.asyncDispose](){await this.destroy()}},ll=class Transaction extends cl{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw Error(`calling the transaction method for a Transaction is not supported`)}startTransaction(){throw Error(`calling the controlled transaction method for a Transaction is not supported`)}connection(){throw Error(`calling the connection method for a Transaction is not supported`)}destroy(){throw Error(`calling the destroy method for a Transaction is not supported`)}withPlugin(e){return new Transaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Transaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Transaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new Transaction({...this.#e})}$extendTables(){return new Transaction({...this.#e})}$omitTables(){return new Transaction({...this.#e})}$pickTables(){return new Transaction({...this.#e})}};function isKyselyProps(e){return isObject$1(e)&&isObject$1(e.config)&&isObject$1(e.driver)&&isObject$1(e.executor)&&isObject$1(e.dialect)}var ConnectionBuilder=class{#e;constructor(e){this.#e=freeze(e)}async execute(e,t){return this.#e.executor.provideConnection(async t=>{let n=this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t));return await e(new cl({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},ul=class TransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new TransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new TransactionBuilder({...this.#e,isolationLevel:e})}async execute(e){let{isolationLevel:t,accessMode:n,...r}=this.#e,i={isolationLevel:t,accessMode:n};return validateTransactionSettings(i),this.#e.executor.provideConnection(async t=>{let n={isCommitted:!1,isRolledBack:!1},a=new pl(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),s=new ll({...r,executor:a}),c=!1;try{await this.#e.driver.beginTransaction(t,i),c=!0;let r=await e(s);return await this.#e.driver.commitTransaction(t),n.isCommitted=!0,r}catch(e){throw c&&(await this.#e.driver.rollbackTransaction(t),n.isRolledBack=!0),e}})}},dl=class ControlledTransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new ControlledTransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new ControlledTransactionBuilder({...this.#e,isolationLevel:e})}async execute(){let{isolationLevel:e,accessMode:t,...n}=this.#e,r={isolationLevel:e,accessMode:t};validateTransactionSettings(r);let i=await provideControlledConnection(this.#e.executor);try{await this.#e.driver.beginTransaction(i.connection,r)}catch(e){throw i.release(),e}return new fl({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},fl=class ControlledTransaction extends ll{#e;#t;constructor(e){e={...e,executor:new pl(e.executor,e.state)};let{connection:t,state:n,...r}=e;super(r),this.#e=freeze(e);let i=createQueryId();this.#t=t=>e.executor.compileQuery(t,i)}get isCommitted(){return this.#e.state.isCommitted}get isRolledBack(){return this.#e.state.isRolledBack}commit(){return new Command$1(async()=>{await this.#e.executor.provideConnection(async e=>{await this.#e.driver.commitTransaction(e),this.#e.state.isCommitted=!0,this.#e.connection.release()})})}rollback(){return new Command$1(async()=>{await this.#e.executor.provideConnection(async e=>{try{await this.#e.driver.rollbackTransaction(e)}finally{this.#e.state.isRolledBack=!0,this.#e.connection.release()}})})}savepoint(e){return new Command$1(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.savepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}rollbackToSavepoint(e){return new Command$1(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.rollbackToSavepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}releaseSavepoint(e){return new Command$1(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.releaseSavepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}withPlugin(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new ControlledTransaction({...this.#e})}$extendTables(){return new ControlledTransaction({...this.#e})}$omitTables(){return new ControlledTransaction({...this.#e})}$pickTables(){return new ControlledTransaction({...this.#e})}},Command$1=class{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}};function assertNotCommittedOrRolledBack(e){if(e.isCommitted)throw Error(`Transaction is already committed`);if(e.isRolledBack)throw Error(`Transaction is already rolled back`)}var pl=class NotCommittedOrRolledBackAssertingExecutor{#e;#t;constructor(e,t){this.#e=e instanceof NotCommittedOrRolledBackAssertingExecutor?e.#e:e,this.#t=t}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return assertNotCommittedOrRolledBack(this.#t),this.#e.provideConnection(async t=>(assertNotCommittedOrRolledBack(this.#t),await e(t)),t)}executeQuery(e,t){return assertNotCommittedOrRolledBack(this.#t),this.#e.withConnectionProvider(this).executeQuery(e,t)}stream(e,t,n){return assertNotCommittedOrRolledBack(this.#t),this.#e.withConnectionProvider(this).stream(e,t,n)}withConnectionProvider(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withoutPlugins(),this.#t)}},ml=class RawBuilderImpl{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new AliasedRawBuilderImpl(this,e)}$castTo(){return new RawBuilderImpl({...this.#e})}$notNull(){return new RawBuilderImpl(this.#e)}withPlugin(e){return new RawBuilderImpl({...this.#e,plugins:this.#e.plugins===void 0?freeze([e]):freeze([...this.#e.plugins,e])})}toOperationNode(){return this.#n(this.#t())}compile(e){return this.#r(this.#t(e))}async execute(e,t){let n=this.#t(e);return n.executeQuery(this.#r(n),t)}#t(e){let t=e===void 0?Us:e.getExecutor();return this.#e.plugins===void 0?t:t.withPlugins(this.#e.plugins)}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}};function createRawBuilder(e){return new ml(e)}var AliasedRawBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return Do.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():j.create(this.#t))}};const hl=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:P.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:P.create(t,e.map(j.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithChild(F.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithSql(e)})},join(e,t=hl`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=parseParameter(e[t]),t!==e.length-1&&(n[2*t+1]=r);return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithChildren(n)})}});function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var OperationNodeVisitor=class{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=freeze({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}};const gl=/'/g,_l=/['"]/g;var DefaultQueryCompiler=class extends OperationNodeVisitor{#e=``;#t=[];get numParameters(){return this.#t.length}compileQuery(e,t){return this.#e=``,this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),freeze({query:e,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){let t=this.parentNode!==void 0&&!ns.is(this.parentNode)&&!I.is(this.parentNode)&&!M.is(this.parentNode)&&!Wc.is(this.parentNode)&&!Ys.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`select`),e.distinctOn&&(this.append(` `),this.compileDistinctOn(e.distinctOn)),e.frontModifiers?.length&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.top&&(this.append(` `),this.visitNode(e.top)),e.selections&&(this.append(` `),this.compileList(e.selections)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.groupBy&&(this.append(` `),this.visitNode(e.groupBy)),e.having&&(this.append(` `),this.visitNode(e.having)),e.setOperations&&(this.append(` `),this.compileList(e.setOperations,` `)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),e.offset&&(this.append(` `),this.visitNode(e.offset)),e.fetch&&(this.append(` `),this.visitNode(e.fetch)),e.endModifiers?.length&&(this.append(` `),this.compileList(this.sortSelectModifiers(e.endModifiers),` `)),t&&this.append(`)`)}visitFrom(e){this.append(`from `),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append(`distinct on (`),this.compileList(e),this.append(`)`)}compileList(e,t=`, `){let n=e.length-1;for(let r=0;r<=n;r++)this.visitNode(e[r]),r<n&&this.append(t)}visitWhere(e){this.append(`where `),this.visitNode(e.where)}visitHaving(e){this.append(`having `),this.visitNode(e.having)}visitInsertQuery(e){let t=this.parentNode!==void 0&&!ns.is(this.parentNode)&&!P.is(this.parentNode)&&!hs.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(e.replace?`replace`:`insert`),e.orAction&&(this.append(` `),this.visitNode(e.orAction)),e.top&&(this.append(` `),this.visitNode(e.top)),e.into&&(this.append(` into `),this.visitNode(e.into)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.output&&(this.append(` `),this.visitNode(e.output)),e.values&&(this.append(` `),this.visitNode(e.values)),e.defaultValues&&(this.append(` `),this.append(`default values`)),e.onConflict&&(this.append(` `),this.visitNode(e.onConflict)),e.onDuplicateKey&&(this.append(` `),this.visitNode(e.onDuplicateKey)),e.returning&&(this.append(` `),this.visitNode(e.returning)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitValues(e){this.append(`values `),this.compileList(e.values)}visitDeleteQuery(e){let t=this.parentNode!==void 0&&!ns.is(this.parentNode)&&!P.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`delete `),e.top&&(this.visitNode(e.top),this.append(` `)),this.visitNode(e.from),e.output&&(this.append(` `),this.visitNode(e.output)),e.using&&(this.append(` `),this.visitNode(e.using)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitReturning(e){this.append(`returning `),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(` as `),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(`.`)),this.visitNode(e.column)}visitSelectAll(e){this.append(`*`)}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!isString(e.name))throw Error(`a non-string identifier was passed to compileUnwrappedIdentifier.`);this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(` and `),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(` or `),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitTuple(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitPrimitiveValueList(e){this.append(`(`);let{values:t}=e;for(let e=0;e<t.length;++e)this.appendValue(t[e]),e!==t.length-1&&this.append(`, `);this.append(`)`)}visitParens(e){this.append(`(`),this.visitNode(e.node),this.append(`)`)}visitJoin(e){this.append(bl[e.joinType]),this.append(` `),this.visitNode(e.table),e.on&&(this.append(` `),this.visitNode(e.on))}visitOn(e){this.append(`on `),this.visitNode(e.on)}visitRaw(e){let{sqlFragments:t,parameters:n}=e;for(let e=0;e<t.length;++e)this.append(t[e]),n.length>e&&this.visitNode(n[e])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){e.schema&&(this.visitNode(e.schema),this.append(`.`)),this.visitNode(e.identifier)}visitCreateTable(e){this.append(`create `),e.frontModifiers?.length&&(this.compileList(e.frontModifiers,` `),this.append(` `)),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.table),e.selectQuery||(this.append(` (`),this.compileList([...e.columns,...e.constraints??[],...e.indexes??[]]),this.append(`)`)),e.onCommit&&(this.append(` on commit `),this.append(e.onCommit)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `)),e.selectQuery&&(this.append(` as `),this.visitNode(e.selectQuery))}visitColumnDefinition(e){e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.column),this.append(` `),this.visitNode(e.dataType),e.unsigned&&this.append(` unsigned`),e.frontModifiers&&e.frontModifiers.length>0&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.generated&&(this.append(` `),this.visitNode(e.generated)),e.identity&&this.append(` identity`),e.defaultTo&&(this.append(` `),this.visitNode(e.defaultTo)),e.notNull&&this.append(` not null`),e.unique&&this.append(` unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.primaryKey&&this.append(` primary key`),e.autoIncrement&&(this.append(` `),this.append(this.getAutoIncrement())),e.references&&(this.append(` `),this.visitNode(e.references)),e.check&&(this.append(` `),this.visitNode(e.check)),e.endModifiers&&e.endModifiers.length>0&&(this.append(` `),this.compileList(e.endModifiers,` `))}getAutoIncrement(){return`auto_increment`}visitReferences(e){this.append(`references `),this.visitNode(e.table),this.append(` (`),this.compileList(e.columns),this.append(`)`),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate))}visitDropTable(e){this.append(`drop `),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifExists&&this.append(`if exists `),this.visitNode(e.table),e.cascade&&this.append(` cascade`)}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append(`order by `),this.compileList(e.items)}visitOrderByItem(e){this.visitNode(e.orderBy),e.collation&&(this.append(` `),this.visitNode(e.collation)),e.direction&&(this.append(` `),this.visitNode(e.direction)),e.nulls&&(this.append(` nulls `),this.append(e.nulls))}visitGroupBy(e){this.append(`group by `),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){let t=this.parentNode!==void 0&&!ns.is(this.parentNode)&&!P.is(this.parentNode)&&!hs.is(this.parentNode);if(this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`update `),e.top&&(this.visitNode(e.top),this.append(` `)),e.table&&(this.visitNode(e.table),this.append(` `)),this.append(`set `),e.updates&&this.compileList(e.updates),e.output&&(this.append(` `),this.visitNode(e.output)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins){if(!e.from)throw Error(`Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins`);this.append(` `),this.compileList(e.joins,` `)}e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitColumnUpdate(e){this.visitNode(e.column),this.append(` = `),this.visitNode(e.value)}visitLimit(e){this.append(`limit `),this.visitNode(e.limit)}visitOffset(e){this.append(`offset `),this.visitNode(e.offset)}visitOnConflict(e){this.append(`on conflict`),e.columns?(this.append(` (`),this.compileList(e.columns),this.append(`)`)):e.constraint?(this.append(` on constraint `),this.visitNode(e.constraint)):e.indexExpression&&(this.append(` (`),this.visitNode(e.indexExpression),this.append(`)`)),e.indexWhere&&(this.append(` `),this.visitNode(e.indexWhere)),e.doNothing===!0?this.append(` do nothing`):e.updates&&(this.append(` do update set `),this.compileList(e.updates),e.updateWhere&&(this.append(` `),this.visitNode(e.updateWhere)))}visitOnDuplicateKey(e){this.append(`on duplicate key update `),this.compileList(e.updates)}visitCreateIndex(e){this.append(`create `),e.unique&&this.append(`unique `),this.append(`index `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.using&&(this.append(` using `),this.visitNode(e.using)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.where&&(this.append(` `),this.visitNode(e.where))}visitDropIndex(e){this.append(`drop index `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.cascade&&this.append(` cascade`)}visitCreateSchema(e){this.append(`create schema `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.schema)}visitDropSchema(e){this.append(`drop schema `),e.ifExists&&this.append(`if exists `),this.visitNode(e.schema),e.cascade&&this.append(` cascade`)}visitPrimaryKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`primary key (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}buildDeferrable(e){e.deferrable!==void 0&&(e.deferrable?this.append(` deferrable`):this.append(` not deferrable`)),e.initiallyDeferred!==void 0&&(e.initiallyDeferred?this.append(` initially deferred`):this.append(` initially immediate`))}visitUniqueConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),this.append(` (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}visitCheckConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`check (`),this.visitNode(e.expression),this.append(`)`)}visitForeignKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`foreign key (`),this.compileList(e.columns),this.append(`) `),this.visitNode(e.references),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate)),this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){this.append(`with `),e.recursive&&this.append(`recursive `),this.compileList(e.expressions)}visitCommonTableExpression(e){this.visitNode(e.name),this.append(` as `),isBoolean(e.materialized)&&(e.materialized||this.append(`not `),this.append(`materialized `)),this.visitNode(e.expression)}visitCommonTableExpressionName(e){this.visitNode(e.table),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`)`))}visitAlterTable(e){this.append(`alter table `),this.visitNode(e.table),this.append(` `),e.renameTo&&(this.append(`rename to `),this.visitNode(e.renameTo)),e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema)),e.addConstraint&&this.visitNode(e.addConstraint),e.dropConstraint&&this.visitNode(e.dropConstraint),e.renameConstraint&&this.visitNode(e.renameConstraint),e.columnAlterations&&this.compileColumnAlterations(e.columnAlterations),e.addIndex&&this.visitNode(e.addIndex),e.dropIndex&&this.visitNode(e.dropIndex)}visitAddColumn(e){this.append(`add column `),this.visitNode(e.column)}visitRenameColumn(e){this.append(`rename column `),this.visitNode(e.column),this.append(` to `),this.visitNode(e.renameTo)}visitDropColumn(e){this.append(`drop column `),e.ifExists&&this.append(`if exists `),this.visitNode(e.column)}visitAlterColumn(e){this.append(`alter column `),this.visitNode(e.column),this.append(` `),e.dataType&&(this.announcesNewColumnDataType()&&this.append(`type `),this.visitNode(e.dataType),e.dataTypeExpression&&(this.append(`using `),this.visitNode(e.dataTypeExpression))),e.setDefault&&(this.append(`set default `),this.visitNode(e.setDefault)),e.dropDefault&&this.append(`drop default`),e.setNotNull&&this.append(`set not null`),e.dropNotNull&&this.append(`drop not null`)}visitModifyColumn(e){this.append(`modify column `),this.visitNode(e.column)}visitAddConstraint(e){this.append(`add `),this.visitNode(e.constraint)}visitDropConstraint(e){this.append(`drop constraint `),e.ifExists&&this.append(`if exists `),this.visitNode(e.constraintName),e.modifier===`cascade`?this.append(` cascade`):e.modifier===`restrict`&&this.append(` restrict`)}visitRenameConstraint(e){this.append(`rename constraint `),this.visitNode(e.oldName),this.append(` to `),this.visitNode(e.newName)}visitSetOperation(e){this.append(e.operator),this.append(` `),e.all&&this.append(`all `),this.visitNode(e.expression)}visitCreateView(e){this.append(`create `),e.orReplace&&this.append(`or replace `),e.materialized&&this.append(`materialized `),e.temporary&&this.append(`temporary `),this.append(`view `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),this.append(` `),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`) `)),e.as&&(this.append(`as `),this.visitNode(e.as))}visitRefreshMaterializedView(e){this.append(`refresh materialized view `),e.concurrently&&this.append(`concurrently `),this.visitNode(e.name),e.withNoData?this.append(` with no data`):this.append(` with data`)}visitDropView(e){this.append(`drop `),e.materialized&&this.append(`materialized `),this.append(`view `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.cascade&&this.append(` cascade`)}visitGenerated(e){this.append(`generated `),e.always&&this.append(`always `),e.byDefault&&this.append(`by default `),this.append(`as `),e.identity&&this.append(`identity`),e.expression&&(this.append(`(`),this.visitNode(e.expression),this.append(`)`)),e.stored&&this.append(` stored`)}visitDefaultValue(e){this.append(`default `),this.visitNode(e.defaultValue)}visitSelectModifier(e){e.rawModifier?this.visitNode(e.rawModifier):this.append(vl[e.modifier]),e.of&&(this.append(` of `),this.compileList(e.of,`, `))}visitCreateType(e){this.append(`create type `),this.visitNode(e.name),e.enum&&(this.append(` as enum `),this.visitNode(e.enum))}visitDropType(e){this.append(`drop type `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.additionalNames?.length&&(this.append(`, `),this.compileList(e.additionalNames)),e.cascade&&this.append(` cascade`)}visitAlterType(e){this.append(`alter type `),this.visitNode(e.name),this.append(` `),e.addValue?this.visitNode(e.addValue):e.renameTo?(this.append(`rename to `),this.visitNode(e.renameTo)):e.renameValue?this.visitNode(e.renameValue):e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema))}visitAddValue(e){this.append(`add value `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.value),e.neighborValue&&(this.append(e.isBefore?` before `:` after `),this.visitNode(e.neighborValue))}visitRenameValue(e){this.append(`rename value `),this.visitNode(e.oldValue),this.append(` to `),this.visitNode(e.newValue)}visitExplain(e){this.append(`explain`),(e.options||e.format)&&(this.append(` `),this.append(this.getLeftExplainOptionsWrapper()),e.options&&(this.visitNode(e.options),e.format&&this.append(this.getExplainOptionsDelimiter())),e.format&&(this.append(`format`),this.append(this.getExplainOptionAssignment()),this.append(e.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(e){this.append(`default`)}visitAggregateFunction(e){this.append(e.func),this.append(`(`),e.distinct&&this.append(`distinct `),this.compileList(e.aggregated),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),this.append(`)`),e.withinGroup&&(this.append(` within group (`),this.visitNode(e.withinGroup),this.append(`)`)),e.filter&&(this.append(` filter(`),this.visitNode(e.filter),this.append(`)`)),e.over&&(this.append(` `),this.visitNode(e.over))}visitOver(e){this.append(`over(`),e.partitionBy&&(this.visitNode(e.partitionBy),e.orderBy&&this.append(` `)),e.orderBy&&this.visitNode(e.orderBy),this.append(`)`)}visitPartitionBy(e){this.append(`partition by `),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(` `),this.visitNode(e.operator),this.append(` `),this.visitNode(e.rightOperand)}visitUnaryOperation(e){this.visitNode(e.operator),this.isMinusOperator(e.operator)||this.append(` `),this.visitNode(e.operand)}isMinusOperator(e){return Wo.is(e)&&e.operator===`-`}visitUsing(e){this.append(`using `),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append(`(`),this.compileList(e.arguments),this.append(`)`)}visitCase(e){this.append(`case`),e.value&&(this.append(` `),this.visitNode(e.value)),e.when&&(this.append(` `),this.compileList(e.when,` `)),e.else&&(this.append(` else `),this.visitNode(e.else)),this.append(` end`),e.isStatement&&this.append(` case`)}visitWhen(e){this.append(`when `),this.visitNode(e.condition),e.result&&(this.append(` then `),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append(`'$`);for(let t of e.pathLegs)this.visitNode(t);this.append(`'`)}visitJSONPathLeg(e){let t=e.type===`ArrayLocation`,n=String(e.value);t?(this.append(`[`),this.append(this.sanitizeStringLiteral(n)),this.append(`]`)):(this.append(`."`),this.append(this.sanitizeJSONPathMemberValue(n)),this.append(`"`))}visitJSONOperatorChain(e){for(let t=0,n=e.values.length;t<n;t++)t===n-1?this.visitNode(e.operator):this.append(`->`),this.visitNode(e.values[t])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`merge `),e.top&&(this.visitNode(e.top),this.append(` `)),this.append(`into `),this.visitNode(e.into),e.using&&(this.append(` `),this.visitNode(e.using)),e.whens&&(this.append(` `),this.compileList(e.whens,` `)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.output&&(this.append(` `),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitMatched(e){e.not&&this.append(`not `),this.append(`matched`),e.bySource&&this.append(` by source`)}visitAddIndex(e){this.parentNode&&M.is(this.parentNode)||this.append(`add `),e.unique&&this.append(`unique `),this.append(`index `),this.visitNode(e.name),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.using&&(this.append(` using `),this.visitNode(e.using))}visitCast(e){this.append(`cast(`),this.visitNode(e.expression),this.append(` as `),this.visitNode(e.dataType),this.append(`)`)}visitFetch(e){this.append(`fetch next `),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append(`output `),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append(`collate `),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getCurrentParameterPlaceholder(){return`$`+this.numParameters}getLeftExplainOptionsWrapper(){return`(`}getExplainOptionAssignment(){return` `}getExplainOptionsDelimiter(){return`, `}getRightExplainOptionsWrapper(){return`)`}sanitizeIdentifier(e){let t=this.getLeftIdentifierWrapper(),n=this.getRightIdentifierWrapper(),r=``;for(let i of e)r+=i,i===t?r+=t:i===n&&(r+=n);return r}sanitizeStringLiteral(e){return e.replace(gl,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(_l,e=>e===`'`?`''`:`\\"`)}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(isString(e))this.appendStringLiteral(e);else if(isNumber(e)||isBoolean(e)||isBigInt(e))this.append(e.toString());else if(isNull(e))this.append(`null`);else if(isDate(e))this.appendImmediateValue(e.toISOString());else throw Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append(`'`),this.append(this.sanitizeStringLiteral(e)),this.append(`'`)}sortSelectModifiers(e){return freeze(e.toSorted((e,t)=>e.modifier&&t.modifier?yl[e.modifier]-yl[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const vl=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),yl=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),bl=freeze({InnerJoin:`inner join`,LeftJoin:`left join`,RightJoin:`right join`,FullJoin:`full join`,CrossJoin:`cross join`,LateralInnerJoin:`inner join lateral`,LateralLeftJoin:`left join lateral`,LateralCrossJoin:`cross join lateral`,OuterApply:`outer apply`,CrossApply:`cross apply`,Using:`using`}),xl=freeze({raw(e,t=[]){return freeze({sql:e,query:P.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}});var DialectAdapterBase=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function parseSavepointCommand(e,t){return P.createWithChildren([P.createWithSql(`${e} `),j.create(t)])}var SqliteDriver=class{#e;#t;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#t=isFunction(this.#e.database)?await this.#e.database(e):this.#e.database,this.#n=new SqliteConnection(this.#t),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#n,e)}async acquireConnection(){return this.#n}async beginTransaction(e){await e.executeQuery(xl.raw(`begin`))}async commitTransaction(e){await e.executeQuery(xl.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(xl.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(){}async destroy(){this.#t?.close()}},SqliteConnection=class{#e;constructor(e){this.#e=e}async executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t);if(r.reader)return{rows:r.all(n)};let{changes:i,lastInsertRowid:a}=r.run(n);return{insertId:a==null?void 0:BigInt(a),numAffectedRows:i==null?void 0:BigInt(i),rows:[]}}async*streamQuery(e,t){let{sql:n,parameters:r,query:i}=e,a=this.#e.prepare(n);if(!z.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let s=a.iterate(r);for(let e of s)yield{rows:[e]}}};const Sl=/"/g,Cl=/[\\'"]/g;var SqliteQueryCompiler=class extends DefaultQueryCompiler{visitOrAction(e){this.append(`or `),this.append(e.action)}getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}sanitizeIdentifier(e){return e.replace(Sl,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(Cl,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const wl=`kysely_migration`,Tl=`kysely_migration_lock`;freeze({__noMigrations__:!0});var SqliteIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#n(e)}#t(e,t){let n=e.selectFrom(`sqlite_master`).where(`type`,`in`,[`table`,`view`]).where(`name`,`not like`,`sqlite_%`).select([`name`,`sql`,`type`]).orderBy(`name`);return t.withInternalKyselyTables||(n=n.where(`name`,`!=`,wl).where(`name`,`!=`,Tl)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,hl`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject$1(e)&&isString(e.stack)}const El=Symbol();var PostgresDriver=class{#e;#t=/* @__PURE__ */ new WeakMap;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#n=isFunction(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#n.connect();if(!this.#n)throw t.release(),Error(`driver has already been destroyed`);let n=this.#t.get(t);return n||(n=new PostgresConnection(t,{controlClient:this.#e.controlClient||this.#n.Client,cursor:this.#e.cursor??null,poolOptions:this.#n.options}),this.#t.set(t,n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){let n=`begin`;(t.isolationLevel||t.accessMode)&&(n=`start transaction`,t.isolationLevel&&(n+=` isolation level ${t.isolationLevel}`),t.accessMode&&(n+=` ${t.accessMode}`)),await e.executeQuery(xl.raw(n))}async commitTransaction(e){await e.executeQuery(xl.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(xl.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(e){e[El]()}async destroy(){if(this.#n){let e=this.#n;this.#n=void 0,await e.end()}}},PostgresConnection=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=t}async cancelQuery(e){return await this.#i(`select pg_cancel_backend(${this.#r})`,e)}async collectSessionInfo(){if(this.#r)return;let{processID:e}=this.#e;if(e)this.#r=e;else{let{rows:[{pid:e}]}=await this.#e.query(`select pg_backend_pid() as pid`,[]);this.#r=Number(e)}}async executeQuery(e){try{this.#n=e.queryId;let{command:t,rowCount:n,rows:r}=await this.#e.query(e.sql,e.parameters);return{numAffectedRows:t===`INSERT`||t===`UPDATE`||t===`DELETE`||t===`MERGE`?BigInt(n):void 0,rows:r??[]}}catch(e){throw extendStackTrace(e,/* @__PURE__ */ Error())}finally{this.#n=void 0}}async killSession(e){return await this.#i(`select pg_terminate_backend(${this.#r})`,e)}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#n=e.queryId;let n=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{for(;;){let e=await n.read(t);if(e.length===0)break;yield{rows:e}}}finally{await n.close(),this.#n=void 0}}[El](){this.#e.release()}async#i(e,t){if(!this.#n)return;let{controlClient:n,poolOptions:r}=this.#t,i=this.#n;if(!n)return await t(async t=>{i.queryId===this.#n?.queryId&&await t.executeQuery(xl.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,hl`col_description(a.attrelid, a.attnum)`.as(`column_description`),hl`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where(hl`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,wl).where(`c.relname`,`!=`,Tl));let n=await t.execute();return this.#t(n)}#t(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=n.get(r.schema);e||(e=/* @__PURE__ */ new Map,n.set(r.schema,e));let i=e.get(r.table);i||(i=freeze({columns:[],isForeign:r.table_type===`f`,isView:r.table_type===`v`,name:r.table,schema:r.schema}),e.set(r.table,i),t.push(i)),i.columns.push(freeze({comment:r.column_description??void 0,dataType:r.type,dataTypeSchema:r.type_schema,hasDefaultValue:r.has_default,isAutoIncrementing:r.auto_incrementing!==null,isNullable:!r.not_null,name:r.column}))}return t}};const Dl=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(Dl,`""`)}};const Ol=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await hl`
    with set_timeout as (
      select set_config('lock_timeout', '${hl.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${hl.lit(Ol)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await hl`select pg_advisory_unlock(${hl.lit(Ol)})`.execute(e)}},PostgresDialect=class{#e;constructor(e){this.#e=e}createDriver(){return new PostgresDriver(this.#e)}createQueryCompiler(){return new PostgresQueryCompiler}createAdapter(){return new PostgresAdapter}createIntrospector(e){return new PostgresIntrospector(e)}};const templateFragments=(e,t)=>e,kl=templateFragments`(SELECT value FROM json_each(${0}))`,Al=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!P.is(e)||e.sqlFragments!==kl||e.parameters.length!==1)return;let t=e.parameters[0];for(;P.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!F.is(t)||t.immediate||typeof t.value!=`string`)return;let n;try{n=JSON.parse(t.value)}catch{return}if(Array.isArray(n)&&n.every(e=>typeof e==`string`))return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(Wo.is(e.operator)&&e.operator.operator===`in`){let t=postgresStringArray(e.rightOperand);if(t!==void 0){this.visitNode(e.leftOperand),this.append(` = ANY(`),this.appendValue(t),this.append(`::text[])`);return}}super.visitBinaryOperation(e)}visitRaw(e){let t=e.sqlFragments===kl;!t&&e.sqlFragments!==Al?super.visitRaw(e):(this.append(t?`(SELECT value FROM json_array_elements_text(`:`(SELECT ordinality - 1 AS key, value FROM json_array_elements_text(`),this.compileList(e.parameters),this.append(t?`::json) AS value)`:`::json) WITH ORDINALITY AS entries(value, ordinality))`))}},OpenClawPostgresDialect=class extends PostgresDialect{createQueryCompiler(){return new OpenClawPostgresQueryCompiler}};const jl=ne(process.versions.node),Ml=!process.versions.bun&&(jl?.major===24&&v(jl,{major:24,minor:20,patch:0})||v(jl,{major:26,minor:6,patch:0})),Nl=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),Pl=/* @__PURE__ */ new WeakMap,Fl=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(C(e)){let t=Pl.get(e);return t||(t=new cl({dialect:Fl}),Pl.set(e,t)),t}let t=Mi.get(e);if(t)return t;let n=new cl({dialect:Nl});return Mi.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{Ni.get(e)?.(t)}catch{}}function releaseSqliteIterator(e,t,n,r){let i;try{e.return?.()}catch(e){i=e}if(t.release(),!n&&i!==void 0)throw s(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(C(e)){let i=e.query(t.sql,r),a=n?i.rows.slice(0,1):i.rows;return i.columns.length>0?{rows:a}:{rows:[],numAffectedRows:BigInt(i.rowCount)}}try{let i=t.sql;return installStatementInvalidation(e),executeWithCachedStatement(e,i,r,i=>{if(n&&z.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(z.is(t.query)||i.columns().length>0){if(Ml)return{rows:i.all(...r)};let t=i.iterate(...r),n=lr(e,`kysely eager query`),a=!1,c,l=[];try{for(let e of t)n.progress(),l.push(e)}catch(e){a=!0,c=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw s(c,`SQLite query failed`);return{rows:l}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:c,lastInsertRowid:l}=a,u={numAffectedRows:BigInt(c),rows:[]};return I.is(t.query)&&c>0?{...u,insertId:BigInt(l)}:u})}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}}function executeSqliteQuerySync(e,t){return executeCompiledSqliteQuerySync(e,t.compile())}function createSqliteQueryCache(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);return r===void 0&&(r=e(n),t.set(n,r)),r}}function compileSqliteQueryBindings(e){let t=/* @__PURE__ */ new Map,n=e(e=>{let n=Symbol(`sqlite-query-parameter`);return t.set(n,e),hl`${n}`}).compile(),r=n.parameters.map(e=>t.get(e)??(()=>e));return{compiled:n,bind:e=>r.map(t=>t(e))}}function prepareSqliteQuerySync(e,t){let{compiled:n,bind:r}=compileSqliteQueryBindings(t);return t=>executeCompiledSqliteQuerySync(e,n,!1,r(t))}function executeSqliteQueryTakeFirstSync(e,t){return executeCompiledSqliteQuerySync(e,t.compile(),!0).rows[0]}const Il=i(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));let Ll=0;function withEngineStoreAdmission(e){Ll+=1;try{let t=e();if(xn(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--Ll}}function assertEngineStoreExecutionAllowed(){if(ii===0&&Ll===0&&Il.role!==`cli-oneshot`)throw Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}function createSqliteTableContractReader(e,t=[],n=[]){let r,i,a=/* @__PURE__ */ new Set,readCatalog=(s=[])=>{if(r)for(let t of s){if(!a.has(t))continue;let n=readSqliteColumnCatalog(e,t);r={...r,tables:r.tables.map(e=>e.name===t?{...e,columns:n}:e)},a.delete(t),i=void 0}else{let i=[...n,...s];r=readSqliteSchemaCatalog(e,{viewNames:t,virtualTableNames:i});for(let e of r.tables)e.sql&&/^CREATE VIRTUAL TABLE /iu.test(e.sql)&&!i.includes(e.name)&&a.add(e.name)}return r};return Object.assign(e=>{let t=readCatalog([e]);return(i??=sqliteSchemaContractFromCatalog(t)).get(e)},{readCatalog:(n,r)=>n.every(e=>t.includes(e))?readCatalog(r):readSqliteSchemaCatalog(e,{viewNames:n,virtualTableNames:r}),readView:n=>(t.includes(n)?readCatalog().views:readSqliteSchemaCatalog(e,{viewNames:[n],virtualTableNames:[]}).views).find(e=>e.name===n)})}function sqliteSchemaContractFromCatalog(e){return new Map(e.tables.map(e=>[e.name,mr(e.name,e,{schema:`main`,name:e.name,strict:e.strict,wr:e.withoutRowid},e.indexes.map(e=>or(e,e.sql,e.terms)).toSorted(compareJson),e.triggers,e.columns,e.foreignKeys)]))}function readSqliteSchemaCatalog(e,t={}){let n=e.prepare(`SELECT type, name, tbl_name, sql FROM main.sqlite_schema ORDER BY name`).all(),r=n.filter(e=>e.type===`table`&&!e.name.startsWith(`sqlite_`)),i=n.filter(e=>e.type===`view`&&(!t.viewNames||t.viewNames.includes(e.name)));if(r.length===0&&i.length===0)return{tables:[],views:[]};let a=e.prepare(`PRAGMA table_list`).all(),s=a.filter(e=>e.schema===`main`&&e.type===`virtual`&&t.virtualTableNames&&!t.virtualTableNames.includes(e.name)).map(e=>e.name),c=a.some(e=>[`pragma_index_list`,`pragma_index_xinfo`,`pragma_table_xinfo`,`pragma_foreign_key_list`].includes(e.name.toLowerCase())),l,u;if(!c){l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map;let t=e.prepare(`
        SELECT t.name AS table_name, i.seq AS index_seq,
          i.name AS index_name, i.origin, i.partial, i."unique",
          x.seqno, x.cid, x.name, x."desc", x.coll, x."key"
        FROM main.sqlite_schema AS t
        CROSS JOIN pragma_index_list(t.name, 'main') AS i
        LEFT JOIN pragma_index_xinfo(i.name, 'main') AS x ON 1 = 1
        WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
        ORDER BY t.name, i.seq, x.seqno
      `).all();for(let e of t){let t=l.get(e.table_name)??[];if(t.at(-1)?.index_seq!==e.index_seq&&(t.push({table_name:e.table_name,index_seq:e.index_seq,name:e.index_name,origin:e.origin,partial:e.partial,unique:e.unique}),l.set(e.table_name,t)),e.seqno!==null){let t=u.get(e.table_name)??[];t.push({table_name:e.table_name,index_seq:e.index_seq,seqno:e.seqno,cid:e.cid,name:e.name,desc:e.desc,coll:e.coll,key:e.key}),u.set(e.table_name,t)}}}let d=t.viewNames?t.viewNames.length>0?`t.type = 'table' OR (t.type = 'view' AND t.name IN (${t.viewNames.map(()=>`?`).join(`, `)}))`:`t.type = 'table'`:`t.type IN ('table', 'view')`,f=s.length?`AND t.name NOT IN (${s.map(()=>`?`).join(`, `)})`:``,p=c?void 0:Ie(e.prepare(`
          SELECT t.name AS table_name, x.cid, x.name, x.type, x."notnull", x.dflt_value, x.pk, x.hidden
          FROM main.sqlite_schema AS t
          CROSS JOIN pragma_table_xinfo(t.name, 'main') AS x
          WHERE (${d}) AND substr(t.name, 1, 7) <> 'sqlite_'
            ${f}
          ORDER BY t.name, x.cid
        `).all(...t.viewNames??[],...s),e=>e.table_name),m=c?void 0:Ie(e.prepare(`
          SELECT t.name AS table_name, f.id, f.seq, f."table", f."from", f."to",
            f.on_update, f.on_delete, f."match"
          FROM main.sqlite_schema AS t
          CROSS JOIN pragma_foreign_key_list(t.name, 'main') AS f
          WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
          ORDER BY t.name, f.id, f.seq
        `).all(),e=>e.table_name),h=Ie(n.filter(e=>e.type===`trigger`),e=>e.tbl_name),ee=new Map(n.filter(e=>e.type===`index`).map(e=>[e.name,e.sql])),normalizedRow=e=>({name:e.name,sql:S(e.sql)}),readColumns=t=>s.includes(t)?[]:p?(p.get(t)??[]).map(({table_name:e,...t})=>t):readSqliteColumnCatalog(e,t),readTriggers=e=>(h.get(e)??[]).map(normalizedRow);return{tables:r.map(t=>{let n=a.find(e=>e.schema===`main`&&e.name===t.name);if(!n)throw Error(`Could not inspect SQLite table options for ${t.name}.`);let r=l?l.get(t.name)??[]:e.prepare(`PRAGMA main.index_list(${x(t.name)})`).all().map(({name:e,origin:t,partial:n,unique:r,seq:i})=>({name:e,origin:t,partial:n,unique:r,index_seq:i})),i=Ie(u?.get(t.name)??[],e=>e.index_seq);return{name:t.name,sql:S(t.sql),strict:n.strict,withoutRowid:n.wr,columns:readColumns(t.name),foreignKeys:m?(m.get(t.name)??[]).map(({table_name:e,...t})=>t):e.prepare(`PRAGMA main.foreign_key_list(${x(t.name)})`).all(),indexes:r.map(t=>({name:t.name,origin:t.origin,partial:t.partial,unique:t.unique,sql:S(ee.get(t.name)??null),terms:u?(i.get(t.index_seq)??[]).map(({table_name:e,index_seq:t,...n})=>n):e.prepare(`PRAGMA main.index_xinfo(${x(t.name)})`).all()})).toSorted((e,t)=>e.name.localeCompare(t.name)),triggers:readTriggers(t.name)}}),views:i.map(e=>({name:e.name,sql:S(e.sql),columns:readColumns(e.name),triggers:readTriggers(e.name)}))}}function readSqliteColumnCatalog(e,t){return e.prepare(`PRAGMA main.table_xinfo(${x(t)})`).all()}function compareJson(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}const Rl=/* @__PURE__ */ new WeakMap;function getMaintenanceSqliteTableChecks(e){let t=getOpenClawDatabaseMaintenanceScope();if(!t?.ownsSchemaMaintenance||t.sqliteIntegrityCheck!==`quick`)return;let n=readSqliteNativeMutationRevision(e),r=e.location();if(n===void 0||!r||Hn(e)===void 0)return;let i=cr(r);if(i===void 0)return;let a=Rl.get(t);if(a||(a={committed:/* @__PURE__ */ new Map,transactions:/* @__PURE__ */ new WeakMap},Rl.set(t,a)),!e.isTransaction){let e=a.committed.get(i);return e||(e=/* @__PURE__ */ new Set,a.committed.set(i,e)),e}let s=`${i}:${n}`,c=a.transactions.get(e);if(c)c.token!==s&&(c.token=s,c.tables.clear());else{let n=/* @__PURE__ */ new Set;c={token:s,tables:n},a.transactions.set(e,c),t.own(c,`shared-resources`,registerSqliteSchemaMutationListener(e,()=>n.clear()))}return c.tables}var SqliteRepairableForeignKeyError=class extends Error{constructor(e,t){super(`SQLite foreign_key_check failed for ${e}: repairable task_delivery_state.task_id references task_runs.task_id cascade-owned orphans (${t} rows). Run openclaw doctor --fix to migrate this legacy state before retrying.`),this.name=`SqliteRepairableForeignKeyError`,this.repair={kind:`task-delivery-orphans`,relation:`task_delivery_state.task_id`,parentTable:`task_runs`,orphanCount:t}}};function assertSqliteIntegrity(e,t,n={}){if(n.check===`quick`&&n.schemaOnly)return runSqliteCheck(e,t,`quick_check`,`schema_meta`),{integrityCheck:`ok`};let r=n.check===`quick`?`quick_check`:`integrity_check`,i=!1;try{runSqliteCheck(e,t,r,void 0,n.allFindings||n.ftsSchemas!==void 0)}catch(a){if(!n.ftsSchemas||!(a instanceof SqliteIntegrityError)||!a.findings||!classifySqliteFtsIntegrityFindings(e,a.findings,n.ftsSchemas))throw a;if(r===`quick_check`)return assertSqliteIntegrity(e,t,{check:`full`,ftsSchemas:n.ftsSchemas});i=!0}if(r===`quick_check`&&n.tables?.length){let r=new Set(readSqliteSchemaObjects(e).filter(e=>e.type===`table`).map(e=>e.name));for(let i of n.tables)r.has(i)&&assertSqliteTableIntegrity(e,t,i)}return runSqliteForeignKeyCheck(e,t),r===`integrity_check`&&!i&&ir(e),i?{integrityCheck:`ok`,staleFts:!0}:{integrityCheck:`ok`}}function classifySqliteFtsIntegrityFindings(e,t,n){let r=/* @__PURE__ */ new Set;for(let e of t){if(e===`ok`)continue;let t=typeof e==`string`?/^malformed inverted index for FTS5 table main\.([A-Za-z_][A-Za-z0-9_]*)$/u.exec(e):null;if(!t?.[1])return;r.add(t[1])}if(r.size===0)return;let i=/* @__PURE__ */ new Map;for(let e of n)for(let t of e.matchAll(/CREATE VIRTUAL TABLE (?:IF NOT EXISTS )?([A-Za-z_][A-Za-z0-9_]*) USING fts5\s*\(/gu)){let n=t[1],r=Rn(e,t.index+t[0].length-1),a=i.get(n)??/* @__PURE__ */ new Set;a.add(S(e.slice(t.index,r+1))),i.set(n,a)}let a=readSqliteSchemaObjects(e).filter(e=>e.type===`table`);for(let e of r){let t=a.find(t=>t.name===e)?.sql;if(typeof t!=`string`||!i.get(e)?.has(S(t)))return}return[...r].toSorted()}function assertSqliteTableIntegrity(e,t,n){let r=getMaintenanceSqliteTableChecks(e);r?.has(n)||(runSqliteCheck(e,`${t} table ${n}`,`integrity_check`,n),r?.add(n))}function readSqliteCheckFindings(e,t,n,r=!1){let i=n?`('${n.replaceAll(`'`,`''`)}')`:r?`(2147483647)`:``;return e.prepare(`PRAGMA ${t}${i};`).all().map(e=>e[t]??Object.values(e)[0])}function runSqliteCheck(e,t,n,r,i=!1){let a;try{a=readSqliteCheckFindings(e,n,r,i)}catch(e){throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${e instanceof Error?e.message:String(e)}`,e)}if(a.length===1&&a[0]===`ok`)return`ok`;throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${a.map(e=>String(e)).join(`; `)||`no result`}`,void 0,a)}function runSqliteForeignKeyCheck(e,t){let n=0,r=!0,i,a=[];try{let t=e.prepare(`PRAGMA foreign_key_check;`);t.setReadBigInts(!0);for(let s of t.iterate())n+=1,retainSortedForeignKeyViolation(a,s),r&&(s.table===`task_delivery_state`&&s.parent===`task_runs`?(i??=readTaskDeliveryCascadeForeignKeyId(e),r=s.fkid===i):r=!1)}catch(e){throw new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${e instanceof Error?e.message:String(e)}`,e)}if(a.length===0)return;if(r)throw new SqliteRepairableForeignKeyError(t,n);let s=a.map(formatSqliteForeignKeyViolation);throw n>5&&s.push(`additional violations omitted`),new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${s.join(`; `)}`)}function readTaskDeliveryCascadeForeignKeyId(e){let t=e.prepare(`PRAGMA foreign_key_list(task_delivery_state);`);t.setReadBigInts(!0);let n=t.all(),r=n.find(e=>e.table===`task_runs`&&e.from===`task_id`&&e.to===`task_id`&&e.on_delete===`CASCADE`);return r&&typeof r.id==`bigint`&&n.filter(e=>e.id===r.id).length===1?r.id:void 0}var SqliteIntegrityError=class extends Error{constructor(e,t,n){super(t===void 0?`${e}. Stop the Gateway, run "openclaw doctor --fix" to inspect and repair this database, and restart. Only if Doctor still cannot repair the offline database, preserve the database and WAL and restore a verified backup.`:e,t===void 0?void 0:{cause:t}),this.findings=n,this.name=`SqliteIntegrityError`}};function retainSortedForeignKeyViolation(e,t){e.push(t),e.sort(compareSqliteForeignKeyViolations),e.length>5&&e.pop()}function compareSqliteForeignKeyViolations(e,t){let n=Buffer.compare(Buffer.from(e.table),Buffer.from(t.table));if(n!==0)return n;if(e.rowid===null||t.rowid===null){if(e.rowid!==t.rowid)return e.rowid===null?-1:1}else if(e.rowid!==t.rowid)return e.rowid<t.rowid?-1:1;let r=Buffer.compare(Buffer.from(e.parent),Buffer.from(t.parent));return r===0?e.fkid===t.fkid?0:e.fkid<t.fkid?-1:1:r}function formatSqliteForeignKeyViolation(e){let t=e.rowid===null?`row without rowid`:`row ${e.rowid.toString()}`;return`${e.table} ${t} references ${e.parent} (foreign key ${e.fkid.toString()})`}const zl=[[`acp_parent_stream_events`,[`idx_agent_acp_parent_stream_run`]],[`agent_tool_usage`,[]],[`auth_profile_state`,[]],[`auth_profile_store`,[]],[`board_tabs`,[]],[`board_widgets`,[`idx_agent_board_widgets_tab_position`]],[`cache_entries`,[`idx_agent_cache_expiry`,`idx_agent_cache_updated`,`idx_agent_voice_session_open_scope`,`idx_agent_voice_session_open_updated`]],[`context_engine_turn_outbox`,[`idx_agent_context_engine_turn_outbox_engine`]],[`conversation_deliveries`,[`idx_agent_conversation_deliveries_reply`,`idx_agent_conversation_deliveries_source_session`,`idx_agent_conversation_deliveries_updated`]],[`conversations`,[`idx_agent_conversations_identity`,`idx_agent_conversations_lookup`,`idx_agent_conversations_updated`]],[`heartbeat_outcomes`,[]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_entry_origins`,[]],[`memory_index_chunk_provenance`,[]],[`memory_index_chunk_recall_metadata`,[]],[`memory_index_chunks`,[`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_meta`,[]],[`memory_index_sources`,[`idx_memory_index_sources_source`]],[`memory_index_state`,[]],[`memory_session_tombstones`,[]],[`message_tool_run_outcomes`,[`idx_agent_message_tool_run_outcomes_occurred`]],[`schema_meta`,[]],[`session_canonical_validation_pending`,[]],[`session_conversations`,[`idx_agent_session_conversations_conversation`,`idx_agent_session_conversations_primary`]],[`session_creation_operations`,[`idx_agent_session_creation_operations_expiry`]],[`session_entry_snapshots`,[]],[`session_goal_operations`,[`idx_agent_session_goal_operations_expiry`]],[`session_input_completions`,[`idx_agent_session_input_completions_session_key`]],[`session_key_contract`,[]],[`session_members`,[`idx_agent_session_members_identity`]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_participants`,[]],[`session_pending_inputs`,[`idx_agent_session_pending_inputs_session`]],[`session_progress_cards`,[]],[`session_reactions`,[]],[`session_suggestions`,[`idx_agent_session_suggestions_author_created`,`idx_agent_session_suggestions_session_state_created`]],[`session_transcript_active_event_facts`,[]],[`session_transcript_active_events`,[`idx_agent_transcript_active_event_seq`,`idx_agent_transcript_active_messages`,`idx_agent_transcript_context_pending`]],[`session_transcript_archives`,[`idx_agent_session_transcript_archives_pending`,`idx_agent_session_transcript_archives_retention`]],[`session_transcript_cold_archive_chunks`,[]],[`session_transcript_cold_archives`,[]],[`session_transcript_fts`,[]],[`session_transcript_fts_config`,[]],[`session_transcript_fts_content`,[]],[`session_transcript_fts_data`,[]],[`session_transcript_fts_docsize`,[]],[`session_transcript_fts_idx`,[]],[`session_transcript_fts_rows`,[`idx_session_transcript_fts_rows_session_message`]],[`session_transcript_index_state`,[]],[`session_windows`,[`idx_agent_session_windows_conversation`,`idx_agent_session_windows_created_at`,`idx_agent_session_windows_session_key`,`idx_agent_session_windows_updated_at`]],[`standing_intents`,[`idx_standing_intents_lifecycle`,`idx_standing_intents_scope`]],[`standing_intents_fts`,[]],[`standing_intents_fts_config`,[]],[`standing_intents_fts_data`,[]],[`standing_intents_fts_docsize`,[]],[`standing_intents_fts_idx`,[]],[`trajectory_runtime_events`,[`idx_agent_trajectory_runtime_run`]],[`transcript_event_identities`,[`idx_agent_transcript_event_identity_sequence`,`idx_agent_transcript_event_sequence`,`idx_agent_transcript_message_idempotency`]],[`transcript_events`,[]],[`transcript_rewrite_watermarks`,[]],[`context_engine_turn_outbox`,[`idx_agent_context_engine_turn_outbox_engine`]],[`conversation_deliveries`,[`idx_agent_conversation_deliveries_reply`,`idx_agent_conversation_deliveries_updated`]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_entry_origins`,[]],[`memory_index_chunks`,[`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_sources`,[`idx_memory_index_sources_source`]],[`session_input_completions`,[]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_participants`,[]],[`session_reactions`,[`idx_agent_session_reactions_message`]],[`session_windows`,[`idx_agent_session_windows_conversation`,`idx_agent_session_windows_created_at`,`idx_agent_session_windows_session_key`,`idx_agent_session_windows_updated_at`]],[`trajectory_runtime_events`,[`idx_agent_trajectory_runtime_run`]],[`transcript_event_identities`,[`idx_agent_transcript_event_identity_sequence`,`idx_agent_transcript_event_parent`,`idx_agent_transcript_event_sequence`,`idx_agent_transcript_message_idempotency`]],[`transcript_events`,[]],[`session_key_contract`,[]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_windows`,[`idx_agent_session_windows_conversation`,`idx_agent_session_windows_created_at`,`idx_agent_session_windows_session_key`,`idx_agent_session_windows_updated_at`]],[`session_transcript_fts_rows`,[`idx_agent_transcript_fts_rows_session`]],[`session_transcript_index_state`,[]],[`memory_index_chunks`,[`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`transcript_events`,[]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`context_engine_turn_outbox`,[`idx_agent_context_engine_turn_outbox_engine`]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`transcript_events`,[]],[`state_leases`,[]]],Bl={afcfcf93ca60eab84c0b9c33cd6d8d342d42ad526e10371f9f43a3d201a5a28e:[`agent`,`8e70873f6fddd58ffc765c3786c293164dfe8ad7754ae73272875acbae360fc7`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"0d8863d033ed867b9e5410fbf5653fff5668cde5bc9933efdc54a948ef28b3a7":[`agent-version-1`,`0ac0c6eca2bd401dba88942343f73a31b0c1fa320b4ef72672a421775667f341`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,23,26,66,28,29,67,68,32,33,69,35,37,38,40,41,42,43,44,45,46,48,70,50,51,52,53,54,55,71,72,73,59],[]],"987c7895f0acfaa27bdd4af5532a6a9d7364cbbefe8fe63fa9775b9520b25f85":[`agent-version-18`,`516c6a0cbc9a63134e84a65c3af806fbc6b526292c614c84109f4a2b2c106afc`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,23,26,66,28,29,67,31,32,33,69,35,37,38,40,41,42,43,44,45,46,48,70,50,51,52,53,54,55,71,72,73,59],[]],"7a92498057481f996a0c0716dd078ea69694645fbdb3a011dadaee411478b7ad":[`agent-version-21`,`fd83bd56e757e27046bc16f16e0dfd056a4bdb4c187672807f9286089fd4c130`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,22,23,26,66,74,29,75,31,32,33,69,35,37,38,40,41,42,43,44,45,46,48,76,50,51,52,53,54,55,71,72,73,59],[]],"789a67b22bc47d0b58acb19a6041b3ba55bd68c7e7271a4043573739edae02d1":[`agent-version-22`,`1571750d60d036d5b09e53c9d062396551d72f79642ee52ae104e9213da8592c`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,22,23,26,66,74,29,75,31,32,33,69,35,37,38,40,41,42,43,44,45,46,77,78,76,50,51,52,53,54,55,71,72,73,59],[]],dd91f9df477a6b80f156003269b951f0d4e55d62e6dec37ad23dc909ed61f71f:[`agent-version-23`,`4cd5cf45ce55fd199d3025021381ad10187c3a5db5340aec56aa108c5a315611`,[0,2,3,4,5,6,60,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,26,66,74,29,75,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,76,50,51,52,53,54,55,71,72,80,59],[]],"9b51fb6f3b7692ed5b1d114c9123184aacb35d5c8450f896b5d289fd46f0ae60":[`agent-version-24`,`7ba969c7ed61eb3596c809150d7c46676bfb3d8310052ca5f07141762b345e9b`,[0,2,3,4,5,6,60,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,74,29,81,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,76,50,51,52,53,54,55,71,72,80,59],[]],"17cbb50319db12e22248e0397cb068ce670687a96328f502ce3577e4798ae299":[`agent-version-25`,`f4118fc6b09e2d36542335eec66c82e9846b7f50e69e56076814dea6e1244aeb`,[0,2,3,4,5,6,60,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,82,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,70,50,51,52,53,54,55,71,72,80,59],[]],ff21eb3fb5a5836d520af3ea0777944cbcfa61aff52a64d0726a4d6b527823c3:[`agent-version-26`,`86dbc086643d83045d9397da12e5e7a5d197b08a10a8aea4942ee7473f03d9ee`,[0,2,3,4,5,6,83,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,84,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,70,50,51,52,53,54,55,71,72,85,59],[]],"227fcd299f5dfd3012abd0f110cd028ba6add9155bc74e2e558aadeae2761349":[`agent-version-27`,`40d0b84e2467b65ff57c4e8171af1a6b0cc54e0e1b5602b6abbe53fc8c10e151`,[0,2,3,4,5,6,7,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,84,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,70,50,51,52,53,54,55,71,72,85,59],[]],b2e17ebad450773253e5dddaeb87e6baef26b1c20a48982ed9df7ffea4210511:[`agent-version-28`,`a48c6c4d7bc63bb0c14eb2010893f31aa216e4a0ee135e40c81598a39c64b61f`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,84,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,71,57,85,59],[]],abf65b8c18ccb84f0e65b8e4faa6fef6abc23b6bab5e93086339f640d2146082:[`agent-version-29`,`ede47c9558c7c22dfd89ed56f0bc28a9d22e512aa69af0ae3acacc989337dc0e`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,71,57,85,59],[]],dbab54723ad6be5e0146085df0789ef92d03b867c53bed915d804fb4c60b3068:[`agent-version-30`,`afa4044fdeabdb3042002c27a39be73d1f2edf8c4135515266cf6613adc7f0ba`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,85,59],[]],"57f4523156caf6b8446afbd95e0fede01f1c917771242cd05c61c1b48b7e157e":[`agent-version-31`,`4ac0d88399760668d6021213299ff6897bcfd672d2373d5c47b6f0afa31e04a1`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,85,59],[]],"9ffa671518cafee606f88dd17bfdfa9792d9deece5f6773e3cae4de2c10fc84b":[`agent-version-37`,`08f828422ad38a4ad92a46abdd793fd45ce6c9e09e72d83177130079588ea41e`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,85,59],[]],a67326c9ddb50583c3b76b9854324d6a42a4d94b87b6aa2285cefb42a9ff1f27:[`agent-version-39`,`4a73468ea8dc4b374449c5a8455df0b5b161d9028d4e8a925763d6805dee8664`,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"4000b93c887a95d954a139e5d78b74e06586e65f8e9dda9d8ffab73b61ee5568":[`agent-version-40`,`d84ecca0d1e44048fac7058389b356bb26e83c05c99631f5f2cbf5d442cf04f4`,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"91916d079ab20e9e5fd2380d0ec99561d144fed2d0eeca7324d370f295a7205a":[`agent-version-41`,`6b80dff64cad8216687329ec4a9685348b511986ca622623406f44a8164b118b`,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"067f95cffb76737d9084b726b640bc79b266b19279e6b1a3d2322d0e298c6ab6":[`agent-v14-core`,`14b30834a4c01ee92da4b3390aebbd49d9a8f4d0fb3a40fb517b8093ffb11c76`,[0,2,3,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,23,26,66,28,67,68,32,37,38,40,41,42,43,44,45,46,48,70,50,51,52,53,54,55,71,72,73,59],[]],aca181a3ea4d5a94d263653e1b75d2327bd449673d631e9d22c6cb9fe25e40ea:[`agent-v14-session-sharing`,`dcd6c30e5c80fa6647cf4b3257fc0c5a6e3440c20333797263b813add4f43fa2`,[29],[]],be5d39d4389597fcfe2942f51a97d5b1f4e0aa1d6b184677e6abcedc162a2cf0:[`agent-v14-additive`,`08e596f53eef1390bb3048a8c3807ea2413fde157899e0feb314aeebeb26e132`,[69,35],[]],"9b07b30dc725415736f5873babff2b98a1e8bf40e0afbf4eb8cf3d3cf700dc0b":[`agent-v14-board`,`535e952ff0024800a42260733be4f1ab5095d5f7578d78555e351c3c336b4f5a`,[4,5],[]],"83673559dc6bba9fdf13d5a9131b030103935b04d7c81620b0a67f43cb49f970":[`agent-progress-card`,`cbda56cf07f5a79268f761f3c0478fd5c3a6ddefde2cb72a933d9eef110a17a1`,[33],[]],fdc21b6dc361c491311c11d91fbda296535a9c34dd20f0ab03b949b8a698ded0:[`agent-retired-state-leases`,`6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc`,[86],[]],c45b82b3c3aa8ecc3b2cc09dcf38bd568edfa8305f54b5bb959c975a55571ece:[`agent-legacy-participants`,`30851780a54c5bd9b7bd3be1f420fc2b3e61839901e1a726e6cb24a10f8d4276`,[68],[]],"6ce6f0ae658b1b77759d335e07e75d9371e27363c998bbf9b0e5fc5a132bc4cb":[`agent-deployed-fts-rows`,`81df0b00eeb5ae756a6acce81b099c432f6127233d47582dd60ca32eed304768`,[77],[]],"0e9e5f47efa71d187ed505aee8d1e423865a5de8df5387a15759194561307e72":[`agent-legacy-transcript-events`,`6e5d060cc60439ef893bf9bcf395552be213733a1021f82d9ea1173e6103ed2e`,[73],[]]};let Vl;function readSqliteAgentFingerprint(e){let t=Bl[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>zl[e][0]),indexNames:i.flatMap(e=>zl[e][1])}}function readSqliteAgentCatalog(e){if(!Bl[e])return;Vl??=Ir(import.meta.url)(ai(new URL(`../../assets/sqlite-schema/sqlite-agent-catalogs.json`,import.meta.url).href));let t=Vl.catalogs[e];return{tables:t.tables.map(e=>Vl.tables[e]),views:t.views}}const Hl=[[`client_credential_migration`,[]],[`device_auth_tokens`,[`idx_device_auth_tokens_updated`]],[`device_identities`,[`idx_device_identities_device`]],[`gateway_origin_device_tokens`,[]],[`native_exec_socket_credentials`,[]]],Ul={"8e4004e9307fcb7ad18d0b12c076f008afd89a8dcacff53e9d40a3b7881acab9":[`client-credentials-v1`,`a00fccb1a356c0d0f77c40341f320602e4f73396bd88865a238b7f4187edd949`,[0,1,2,3,4],[]]};let Wl;function readSqliteClientFingerprint(e){let t=Ul[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Hl[e][0]),indexNames:i.flatMap(e=>Hl[e][1])}}function readSqliteClientCatalog(e){if(!Ul[e])return;Wl??=Ir(import.meta.url)(ai(new URL(`../../assets/sqlite-schema/sqlite-client-catalogs.json`,import.meta.url).href));let t=Wl.catalogs[e];return{tables:t.tables.map(e=>Wl.tables[e]),views:t.views}}const Gl=[[`daemon_runtime_pin_migration`,[]],[`daemon_runtime_pins`,[]]],Kl={"2da8e5914c65eb868e035a1ebbab7a104fceca3c4b4c1e44dccd14c3387c3376":[`daemon-runtime-pins-v1`,`126cb31aa1921bcac9c54618fdbb59cc157d4d86a456508eea2879db32a716e0`,[0,1],[]]};let ql;function readSqliteDaemonFingerprint(e){let t=Kl[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Gl[e][0]),indexNames:i.flatMap(e=>Gl[e][1])}}function readSqliteDaemonCatalog(e){if(!Kl[e])return;ql??=Ir(import.meta.url)(ai(new URL(`../../assets/sqlite-schema/sqlite-daemon-catalogs.json`,import.meta.url).href));let t=ql.catalogs[e];return{tables:t.tables.map(e=>ql.tables[e]),views:t.views}}const Jl=[[`memory_index_chunk_provenance`,[]],[`memory_index_chunk_recall_metadata`,[]],[`memory_index_chunks`,[]],[`memory_index_meta`,[]],[`memory_index_sources`,[]],[`memory_index_state`,[]],[`memory_embedding_cache`,[]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks_fts`,[]],[`memory_index_chunks_fts_config`,[]],[`memory_index_chunks_fts_content`,[]],[`memory_index_chunks_fts_data`,[]],[`memory_index_chunks_fts_docsize`,[]],[`memory_index_chunks_fts_idx`,[]],[`memory_index_paths_fts`,[]],[`memory_index_paths_fts_config`,[]],[`memory_index_paths_fts_content`,[]],[`memory_index_paths_fts_data`,[]],[`memory_index_paths_fts_docsize`,[]],[`memory_index_paths_fts_idx`,[]],[`memory_index_chunks_fts`,[]],[`memory_index_paths_fts`,[]],[`memory_index_chunks_vec`,[]],[`memory_index_chunks_vec_chunks`,[]],[`memory_index_chunks_vec_info`,[]],[`memory_index_chunks_vec_rowids`,[]],[`memory_index_chunks_vec_vector_chunks00`,[]]],Yl={"27ef93ea7e9facb77b3eead587fd5cb7647bade7c4a0dbc8b03c8f34ba64386c":[`memory-index-v1-cache-0`,`59289b93110d1d3eaf27f0e6d5bef8bc45987a70842597a67302ace145717ec9`,[0,1,2,3,4,5],[]],"93a3fb3dfbcf93f896dd17b298be4c18d2b6d6ee8ab14e46872ecbeadd557654":[`memory-index-v1-cache-1`,`a2cc43111506fdc355121bec101f93d7035cdd20d870dfc5fc5c75ce36eddee8`,[6,0,1,2,3,4,5],[]],b53e7fcdaab29e825534bce175eef96cff2c705bc465308f369f67627a5b53bb:[`memory-cache-binary-strict-1`,`43fea47c3ea00e8ff457540564e0915cb72e75b8f14b119ece1bd74746425ff8`,[7],[]],ac226e0f177ccc01aa1d3df066f10277676100bd8cd01588b860c5d89e8e2269:[`memory-chunks-binary-strict-1-recall-0`,`0e8704d882f34e24b97613115d6552258400608839065e8da56df4b336cfca51`,[8],[]],"257f0fa39f94ca852ed0887002bd286e34727ff73b4825ac5b53cafcb174f453":[`memory-chunks-binary-strict-1-recall-1`,`ed5c454b17073742bf3343b99baec45c854a0927ccd95ab1131ec6856ef08d60`,[9],[]],de46110eea2bb88cd753b7c0efa7aa1becddcb90b1a4b5c9502d5acc41d50939:[`memory-chunks-binary-strict-1-recall-2`,`7c8785c42572cc6669a29704d2079f13a47479484250495898dc3b82e2b8f169`,[10],[]],cc79633111488622f8cf8d50157280d4f9ce002ddf8b731ea7bfce3c1acbc7e9:[`memory-chunks-binary-strict-1-recall-3`,`37b37df7f7ec34ba7fb38ea652c85d9db954b648b3b8b0f2cee1136ace8c4d52`,[11],[]],b12e9eee6fc308eb0d125008d0f4a8a6a7921f87cb0ad03c0dcbabc0f4c9e30b:[`memory-chunks-binary-strict-1-recall-4`,`ded3749dc75f0b9853570d3a29f52e3296835f164d7c7e1471a368e2d79523d3`,[12],[]],b74546436177f3480bbfd0ca7d6f7558e50671a41041aa3b02a4a1d70d4e0124:[`memory-chunks-binary-strict-1-recall-5`,`596ee273523cdc7922a0718a926cff468a4e740a8c653a3e0bebe601037eee7f`,[13],[]],"7b8739ff03a7dabf85ff3846c7cb172a402613024754e064cfd775441b037d2e":[`memory-chunks-binary-strict-1-recall-6`,`126e55c1ce40d42ccb97cdf3f4e35497cf712948f36d794dca163e6a8e0559c4`,[14],[]],"6055ec94ab523719e18078aee8fa973f92d8ba968ecb104f0d61bee314739152":[`memory-chunks-binary-strict-1-recall-7`,`05b66c0fd58af7228e74cb7e881a9ddfe4bc77445ae6215ebf1c38463155d430`,[15],[]],f8f4dda5eccd6ef9b6e82a2187a7dfad76ae3783a0fcfe9623eadc18eecf44b0:[`memory-cache-text-strict-0`,`ca38a58fc93a8fb71370dae23cb0ef9b9d7376b6d48b0cef0b28a1bd9433e8fe`,[16],[]],b9b96c68cff42faadc99ad35ff55d2df4e432e87adf8d5d512c4f2d8e01477e6:[`memory-chunks-text-strict-0-recall-0`,`f62e05b1dac229e56f6bd08d3115e2ea93aec01aa558b17d94ea5bc47cc76cc4`,[17],[]],"572644cd115904fabec76e50a6d81b73b5a738b11e879a1c07bc7f83b12fac8f":[`memory-chunks-text-strict-0-recall-1`,`557db378be09c17e06988bb635f5c1eeac94a0780251f379ca0636c6f955befd`,[18],[]],dc69ef337a630e1c40398b494826d3ef6d8ca67e8a42d5f5b40142cd00e51012:[`memory-chunks-text-strict-0-recall-2`,`f6dea371a0755a537b45176e3219b0fb5123d9bda94527e1e967a63ff1678cfa`,[19],[]],d3e0bbf0a82ae4ca0ae435e0a9943fa32a48ac8d37421809d9fd36d4c0680b13:[`memory-chunks-text-strict-0-recall-3`,`60c4185a64288b050f8ddc89727ff13a6103baeda976c67c791e3c7f7b3e6c95`,[20],[]],f1dbb03304f512a8a7a0e1606d23e7ff1c97223599d3a889850ad0ed69299af3:[`memory-chunks-text-strict-0-recall-4`,`f0061cf0170bf18527093f950d0496fd4601058bc99e9c29dafd6b305dd87296`,[21],[]],"454eb2147f9c1adc93e9210a7aabc5c1fc6a4f937f9e712d632f1b7c76b28b7c":[`memory-chunks-text-strict-0-recall-5`,`2f9c2c14d4995f96d632ba23438b90a607c6345080b59c06fa6fe18fbc1ef789`,[22],[]],"2b12ceffe3ff69a67629d2e195143f53fe0d7f947108f4ee7ce068fa7b288dcf":[`memory-chunks-text-strict-0-recall-6`,`9e7d3aa7fbfd911601a9c372bca6099062bef2a24e26a5d08c21db34abb3e937`,[23],[]],"39602ef462e71c3c485358a1572c7c3f82cda5fe147dbbca5ecf601f72009238":[`memory-chunks-text-strict-0-recall-7`,`5764f18a476a4e6a6aa6f40f9538ac70e10fe5344309dd245d0db339913fbc5d`,[24],[]],"16de82c2873083fc417acc8e09140fd32cbdfb1a6633a82e8746cfe9650c18db":[`memory-cache-text-strict-1`,`aacfccd3fbb3a171753d866a2dbcac2e6ab0cf26d94fa2fa8bd17f7b555c8857`,[25],[]],"50709191e29c47d2702efd82ba0b62cdd7f1b027d532848c2cb08c77b69fa679":[`memory-chunks-text-strict-1-recall-0`,`3477ae66bf655ea65812a5e2dcedeae255314ba79214740c03c2a7fab99e1daa`,[26],[]],bbc96ed43fce73bc3051d0c510bdc3fbfec16c6dd4fa557bd349ac7b60d325f7:[`memory-chunks-text-strict-1-recall-1`,`c672e90a018dba96b0d27706a9aeacc809781009464fcb767a9c4304ae6494b0`,[27],[]],"14b7b7910dc0afdcc0bdd78b889d487bd4281ba57342ba21fbc17e2ac4ab7a5c":[`memory-chunks-text-strict-1-recall-2`,`6070f3ccf01a8815f7cb924aff58ce3ec1a215cb01782915a93b6dc2c334991d`,[28],[]],"671a11689fc7970d79b4be242cf747d6831e32ae4adf3d0cde360d0c43427e2c":[`memory-chunks-text-strict-1-recall-3`,`455f88a45ca48ac0a6a4233d483731d0b0960d2d3610db7f298c39da1c568ae4`,[29],[]],"11a2dca1aa8a69e4db87d79208841dff4abd20d943a3910afc8cc80d92912e9a":[`memory-chunks-text-strict-1-recall-4`,`abcc7d9bd0fb27f1b592b729a59c6a81fbd352917b0996f472ea42bac6dfeef2`,[30],[]],cb98ad487e0d9599983c000d5bdf096ee1f323b982e4afc44229111e5aef2cd1:[`memory-chunks-text-strict-1-recall-5`,`cb12b76fbe6f986bd1f4e7f727731515068c6a6b83d8fb0def4d041f404830c5`,[31],[]],"4a5393a69f56db40e0ada5dc8577a88c91c44f65900e234d46d487d0b5294781":[`memory-chunks-text-strict-1-recall-6`,`64fbd15911fb40635818b4f3397e0749b0b62b92b87fc6c0d067079125ce8f8a`,[32],[]],"05e8eaf13a81810f99cc62d7d25a202c115743c80ebd80c625a0beab0960b892":[`memory-chunks-text-strict-1-recall-7`,`8422ba9c6185a2156a9345807b90032db6858b2f5a12541268d9f4c7967d32e9`,[33],[]],"0ab7773eb3198fc86adb541fe032581ce24b93cd39b7aa229fdf50c8b3f9fe6c":[`memory-body-fts-v1-unicode61`,`c16bed5072a5a006ca243b73fefb1fc86bce894f87a6c8713e87dced77493eb2`,[34,35,36,37,38,39],[]],"315cb6d0263f5aff152863d03d253f867104d86d5028ad2c51e348d10fba2f1a":[`memory-path-fts-v1-unicode61`,`b18b06cf6a1ea0655eeff9c0451fae13336f2ac280468680e7d91370016cf23b`,[40,41,42,43,44,45],[]],"32a102b66f747e2fb75d4b23b2a83928c69d086604e997a29a713eac7a62ec46":[`memory-body-fts-v1-trigram`,`15c47771111fc5beb3af779b2f20333755c0069b7bb113ac6aac160f6aabef7f`,[46,35,36,37,38,39],[]],"02ae4f88ed6c87a22d6eaeb0e4e0a4ececc8d7dd37017aa04659494fd8481ccd":[`memory-path-fts-v1-trigram`,`e2b47e11cf4fa6228471d8f6be5654a6d35ec80d5e0c9e7fd5d6654f47ac200e`,[47,41,42,43,44,45],[]],"8a70e5b7bb1c8163cf6d4f38a6a69165a01f3f44204bbd910428f371ebc376c7":[`memory-vector-v1`,`ebe6798602214794cd87d21d200eaa88c4864fcb30bf8fc0b902246a7fce5023`,[48,49,50,51,52],[]]};let Xl;function readSqliteMemoryFingerprint(e){let t=Yl[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Jl[e][0]),indexNames:i.flatMap(e=>Jl[e][1])}}function readSqliteMemoryCatalog(e){if(!Yl[e])return;Xl??=Ir(import.meta.url)(ai(new URL(`../../assets/sqlite-schema/sqlite-memory-catalogs.json`,import.meta.url).href));let t=Xl.catalogs[e];return{tables:t.tables.map(e=>Xl.tables[e]),views:t.views}}const Zl=[[`acp_replay_events`,[]],[`acp_replay_sessions`,[`idx_acp_replay_sessions_key_updated`,`idx_acp_replay_sessions_updated`]],[`acp_sessions`,[`idx_acp_sessions_agent_activity`,`idx_acp_sessions_resume_acpx`,`idx_acp_sessions_resume_agent`,`idx_acp_sessions_state_activity`]],[`agent_database_leases`,[]],[`agent_databases`,[]],[`agent_deletion_journal`,[]],[`agent_provenance`,[]],[`apns_registration_tombstones`,[]],[`apns_registrations`,[`idx_apns_registrations_updated`]],[`audit_events`,[`idx_audit_events_agent_sequence`,`idx_audit_events_channel_sequence`,`idx_audit_events_direction_sequence`,`idx_audit_events_kind_sequence`,`idx_audit_events_run_sequence`,`idx_audit_events_session_sequence`,`idx_audit_events_status_sequence`,`idx_audit_events_time`]],[`audit_identity_keys`,[]],[`backup_runs`,[`idx_backup_runs_created`]],[`capture_blobs`,[]],[`capture_events`,[`capture_events_flow_idx`,`capture_events_session_ts_idx`]],[`capture_sessions`,[]],[`channel_ingress_events`,[`idx_channel_ingress_claims`,`idx_channel_ingress_lane`,`idx_channel_ingress_pending`]],[`channel_pairing_allow_entries`,[`idx_channel_pairing_allow_account`]],[`channel_pairing_requests`,[`idx_channel_pairing_requests_code`,`idx_channel_pairing_requests_created`]],[`clawhub_promotion_claims`,[]],[`config_health_entries`,[]],[`config_machine_state`,[]],[`config_revision_keys`,[]],[`cron_job_runtime_authorities`,[]],[`cron_job_scratch`,[`idx_cron_job_scratch_store_updated`]],[`cron_jobs`,[`idx_cron_jobs_store_order`]],[`cron_run_receipts`,[`cron_run_receipts_cursor_id_idx`,`idx_cron_run_receipts_active_job`,`idx_cron_run_receipts_job_history`]],[`cron_run_trigger_state_retirements`,[]],[`current_conversation_bindings`,[`idx_current_conversation_bindings_conversation`,`idx_current_conversation_bindings_expires`,`idx_current_conversation_bindings_target`]],[`delivery_queue_entries`,[`idx_delivery_queue_bounded_retention`,`idx_delivery_queue_failed`,`idx_delivery_queue_pending`,`idx_delivery_queue_session`,`idx_delivery_queue_target`]],[`device_bootstrap_tokens`,[`idx_device_bootstrap_tokens_ts`]],[`device_pair_setup_completions`,[]],[`device_pairing_browser_requests`,[]],[`device_pairing_join_codes`,[]],[`device_pairing_paired`,[`idx_device_pairing_paired_approved`]],[`device_pairing_pending`,[`idx_device_pairing_pending_device`]],[`diagnostic_events`,[`idx_diagnostic_events_scope_sequence`]],[`durable_background_processes`,[]],[`exec_approvals_config`,[]],[`execution_decision_facts`,[`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_run_occurred_idx`]],[`execution_identity_contexts`,[`execution_identity_contexts_run_created_idx`]],[`execution_owner_lifecycle_bindings`,[]],[`flow_runs`,[`idx_flow_runs_owner_key`,`idx_flow_runs_status`,`idx_flow_runs_updated_at`]],[`gateway_boot_lifecycle`,[`idx_gateway_boot_lifecycle_started`]],[`gateway_restart_handoff`,[`idx_gateway_restart_handoff_expiry`]],[`gateway_restart_intent`,[]],[`gateway_restart_sentinel`,[`idx_gateway_restart_sentinel_ts`]],[`github_personal_publication_requests`,[`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`]],[`github_publication_requests`,[`idx_github_publication_requests_pending`]],[`github_publication_session_lifecycles`,[]],[`github_repository_publication_requests`,[`idx_github_repository_publication_personal_request`,`idx_github_repository_publication_shared_request`]],[`local_workspace_manifest_nodes`,[]],[`local_workspace_projections`,[]],[`local_workspace_source_path_sets`,[]],[`local_workspace_tree_packs`,[]],[`macos_port_guardian_records`,[`idx_macos_port_guardian_records_port`]],[`managed_outgoing_image_records`,[`idx_managed_outgoing_images_agent_message`,`idx_managed_outgoing_images_agent_session`,`idx_managed_outgoing_images_message`,`idx_managed_outgoing_images_session`]],[`mcp_oauth_pending_authorizations`,[]],[`mcp_oauth_stores`,[]],[`meeting_transcript_sessions`,[`idx_meeting_transcript_sessions_account`,`idx_meeting_transcript_sessions_agent`,`idx_meeting_transcript_sessions_chronology`,`idx_meeting_transcript_sessions_export_key`,`idx_meeting_transcript_sessions_id`,`idx_meeting_transcript_sessions_slug`,`idx_meeting_transcript_sessions_source`,`idx_meeting_transcript_sessions_started`]],[`meeting_transcript_summaries`,[]],[`meeting_transcript_utterances`,[`idx_meeting_transcript_utterances_id`]],[`migration_runs`,[`idx_migration_runs_started`]],[`migration_sources`,[`idx_migration_sources_path`,`idx_migration_sources_run`]],[`native_hook_relay_bridges`,[`idx_native_hook_relay_bridges_expires`]],[`node_worker_launch_boots`,[]],[`node_worker_launch_cleanup`,[]],[`node_worker_launch_containers`,[]],[`node_worker_launch_process_scopes`,[]],[`node_worker_launches`,[`idx_node_worker_launches_terminal_completed`]],[`node_worker_prepared_workspaces`,[]],[`node_worker_turns`,[`idx_node_worker_turns_active_owner`,`idx_node_worker_turns_terminal_completed`]],[`official_external_plugin_catalog_snapshots`,[`idx_official_external_plugin_catalog_snapshots_updated`]],[`operator_approval_execution_identities`,[]],[`operator_approval_standing_grant_generations`,[]],[`operator_approval_standing_grants`,[`idx_operator_approval_standing_grants_binding`]],[`operator_approvals`,[`idx_operator_approvals_cursor_id`,`idx_operator_approvals_resolution_ref`,`idx_operator_approvals_resolved`,`idx_operator_approvals_runtime_pending`,`idx_operator_approvals_source_run_resolved`,`idx_operator_approvals_source_session_created`,`idx_operator_approvals_status_expiry`]],[`outbound_media_provenance`,[]],[`outbound_message_execution_bindings`,[`outbound_message_execution_bindings_execution_event_idx`]],[`outbound_message_progress`,[`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`]],[`plugin_binding_approvals`,[`idx_plugin_binding_approvals_plugin`]],[`plugin_blob_entries`,[`idx_plugin_blob_expiry`,`idx_plugin_blob_listing`]],[`plugin_state_entries`,[`idx_plugin_state_expiry`,`idx_plugin_state_listing`]],[`projects`,[]],[`sandbox_persistent_execs`,[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`]],[`sandbox_registry_entries`,[`idx_sandbox_registry_last_used`,`idx_sandbox_registry_session`,`idx_sandbox_registry_updated`]],[`schema_meta`,[]],[`secret_store_entries`,[`secret_store_entries_live_idx`]],[`session_groups`,[]],[`session_repository_workspaces`,[]],[`session_state_events`,[`idx_session_state_events_session_sequence`,`idx_session_state_events_time`]],[`session_state_heads`,[]],[`session_upstream_links`,[`idx_session_upstream_links_catalog_id`]],[`session_watch_cursors`,[`idx_session_watch_cursors_target`]],[`skill_library_entries`,[]],[`skill_library_events`,[]],[`skill_library_revisions`,[]],[`skill_library_uploads`,[]],[`skill_upload_chunks`,[]],[`skill_uploads`,[`idx_skill_uploads_expiry`,`idx_skill_uploads_idempotency`]],[`skill_usage`,[]],[`skill_workshop_changes`,[`idx_skill_workshop_changes_agent_time`,`skill_workshop_changes_cursor_id_idx`]],[`state_leases`,[`idx_state_leases_expiry`,`idx_state_leases_owner`]],[`subagent_runs`,[`idx_subagent_runs_child_session_key`,`idx_subagent_runs_controller_session_key`,`idx_subagent_runs_requester_session_key`]],[`task_delivery_state`,[]],[`task_runs`,[`idx_task_runs_cron_runtime_order`,`idx_task_runs_cron_source_order`,`idx_task_runs_runtime_run`]],[`template_cron_refs`,[]],[`template_installs`,[]],[`template_mcp_server_refs`,[]],[`template_package_refs`,[]],[`template_workspace_files`,[]],[`update_runs`,[`idx_update_runs_active`,`idx_update_runs_created`]],[`user_background_images`,[]],[`user_preferences`,[]],[`user_profile_identities`,[`idx_user_profile_identities_authorization`,`idx_user_profile_identities_profile_id`]],[`web_push_approval_deliveries`,[`idx_web_push_approval_deliveries_subscription`]],[`web_push_subscriptions`,[`idx_web_push_subscriptions_updated`]],[`worker_environment_credentials`,[]],[`worker_environment_ssh_fallback_ports`,[]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`worker_inference_turns`,[`idx_worker_inference_turns_pending_run`]],[`worker_session_placement_moves`,[]],[`worker_session_placements`,[`idx_worker_session_placements_environment`,`idx_worker_session_placements_reconcile`,`idx_worker_session_placements_session_key`]],[`worker_session_tool_operations`,[]],[`worker_transcript_commit_heads`,[]],[`worker_transcript_commits`,[]],[`worker_turn_tool_authorities`,[]],[`worker_workspace_pending_results`,[]],[`worker_workspace_reconciliations`,[]],[`workspace_generated_bootstrap_hashes`,[]],[`workspace_path_aliases`,[`idx_workspace_path_aliases_workspace`]],[`workspace_setup_state`,[`idx_workspace_setup_state_path`]],[`worktree_provisioned_file_chunks`,[]],[`worktree_templates`,[]],[`worktrees`,[`idx_worktrees_removed_at`,`idx_worktrees_repo_fingerprint`]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`workspace_setup_state`,[`idx_workspace_setup_state_path`]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`session_repository_workspaces`,[]],[`worker_workspace_pending_results`,[]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`agent_provenance`,[]],[`claw_cron_refs`,[]],[`claw_installs`,[]],[`claw_mcp_server_refs`,[]],[`claw_package_refs`,[]],[`claw_workspace_files`,[]],[`local_workspace_projections`,[]],[`local_workspace_projections`,[]],[`acp_replay_events`,[`idx_acp_replay_events_session_seq`]],[`skill_usage`,[`idx_skill_usage_key`]],[`state_leases`,[`idx_state_leases_expiry`,`idx_state_leases_owner`]],[`session_state_heads`,[]],[`user_profile_emails`,[`idx_user_profile_emails_profile_id`]],[`user_profiles`,[]],[`user_profile_identities`,[]],[`user_profile_emails`,[]],[`worker_environment_session_attachments`,[`worker_environment_session_attachments_session_key`]],[`sandbox_persistent_execs`,[]],[`update_runs`,[]],[`github_repository_publication_requests`,[]],[`github_personal_publication_requests`,[]],[`execution_identity_contexts`,[]],[`node_worker_launches`,[]],[`node_worker_turns`,[]],[`web_push_approval_deliveries`,[]],[`execution_decision_facts`,[]],[`outbound_message_execution_bindings`,[]],[`outbound_message_progress`,[]],[`cron_run_receipts`,[]],[`secret_store_entries`,[]],[`github_publication_requests`,[]],[`skill_workshop_changes`,[]],[`state_leases`,[]],[`migration_runs`,[]],[`commitments`,[`idx_commitments_agent_due`,`idx_commitments_agent_sent`,`idx_commitments_scope_dedupe`,`idx_commitments_scope_due`,`idx_commitments_status_due`]],[`commitments`,[`idx_commitments_scope_dedupe`,`idx_commitments_scope_due`,`idx_commitments_status_due`]]],Ql={fcbb00212b86de19fc5fa0f04654883e4714871ea6417f63645a97c1c9e9457f:[`state`,`685cc87a6a367954ee95acecd4646d346e35f2b1048e55de7b66d4dc700f1e5b`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"1afe9a93ab5ff5ecdd8a5ef89f60ed9cf1246b4ffb6dd3b31bd782ca5e44ab9d":[`state-before-v40`,`716519c2f5c5484e7061362cd55dc40f25c44fc55598446763c74152b11e4fc6`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"20652e186439d870636fc9def6e16d67f0bc25efbc56bcbd190ab3711c594f0b":[`state-before-v39`,`5e03dab2bf0ab007cdf397cb1e498ff89deb3dbb1bb0429acbe9a45b6e22e509`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,136,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"6d3d5985c28174dffe934265721644dda70fb01ad73d03514d35e2ee70a97adc":[`state-before-v38`,`a06d8d965a4799d247b9237439e304fb41eb841ca4ab48c5f347e242e979daa4`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,136,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],fe1706f4d38001b97405908240370830f5acfba944ab99d2aaf3b9f4d919424e:[`state-before-v37`,`02c02530dcbfa94282fc7513c2035c144e1da111c571bd677c3fad2feac6aaf5`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],d0cd137b7efd6db59ab303c883f1f8dac6cb8b1f1acd8d8627ada7e06e394071:[`state-before-v36`,`220f897975cabddbbcb199e7cb86bc899e9edb48336439031012ce40d5766b9f`,[0,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],"7ed795835c94f05c1ef977fc923efe5546e8ffdba490daf0830f187f1dfb1d80":[`state-before-v35`,`be6695458a7627c186add059bcf2639b5e9e9ddcd8dc53746b440f1ba77a5780`,[0,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,146,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],a6d49bc647cab1d6e70a56501e06debe8568094726782bd2d2b9ab3efecadff6:[`state-before-v31`,`89d5364b8c63458f600bdc0b7b30e85eefbcdc71ba09a388dc475bb5ffd404be`,[0,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,147,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],d1d0b50ac838dfa09897431b3e3f0f74bd5de636b7a17c7569422cc4e32d419c:[`state-before-v27`,`4d4752c9096151b2d9ac9f843259470d34109ec410b962b9203c5d5192f0abbe`,[148,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,147,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,149,100,150,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],e31a36c4865b72d72a5f7ff8068639e5284f12abe8e58623cbe4bb6907c09c1d:[`state-before-v26`,`153fc4e2e4248b6fb0b9f0d1a936730da53b1ac5f80bfda2d5d4978382cf87ad`,[148,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,147,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,151,91,92,93,94,95,96,97,98,149,100,150,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],f32dcffad8239a4de64de63074202b82a2a8b8671148ade2a5bf66a296a24c94:[`state-before-provision-source`,`65ab29899ed0d4d821be154749cbf12b3deb5fda9006742dcc8513fc24e8726e`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"5bde97da769150d9e0cc19830a835a11599f82cf51c544e629e9d7f5f205b3d5":[`state-before-bootstrap-deferred`,`70b4fd11db71810de8ee5166356977770b88edce037b477b3795972a1af93209`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"54911300fd4efbb44a652d781badc61c60be05619fba7bd6a64b1d1bc2121a81":[`fragment-local_workspace_projections`,`39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497`,[50,51,52,53],[]],f0e11a6fff0a4b79b69a28a0f2ec4694fa1ee88672cac3b7338bc0a3bb9f8d19:[`state-feature-local_workspace_projections`,`39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497`,[50,51,52,53],[]],e119e5203e18e9fba13d43368408775eca1d809807579a697482ab2b7011e840:[`state-feature-local_workspace_manifest_nodes`,`8db5abfb2c2f4c380c80647305b1e4bb5e6af7ac2fec71205a52a97d86835291`,[50],[]],"3142caa54d9bd7d285b37ed3338ed9f4307ad3b32469bd88deecb8725301861e":[`state-feature-local_workspace_tree_packs`,`a63984593fd118417812466c9ee0c189fd7d819401af1943a6f9c11730c47d87`,[53],[]],e95059f2306c8231ee92ef3d76dfcb434a80885f08cbf39380f88a287f98bade:[`state-feature-local_workspace_source_path_sets`,`ead9623df4d41d649f8e4af2351694db5bc8c4e70edb7d2322ba76c11d0dfddb`,[52],[]],bc86e378ea153c42527b6106b01ba4cb8285cca40378ffa0142656577309723e:[`fragment-user_profiles`,`268e6f3b53eb2048a3edf527da424f8df229a01166befc8137ea94dbb560227e`,[152,113,153],[]],f5b54f0fedd88d94c24add8a1fd987ac8592b05d4615424bab9dbc0d19c9cd4a:[`state-feature-user_profiles`,`2c2611b7d0c64f467494ae3922f763dee7fc023a5ee6b92d5821639b18e825aa`,[152,154,153],[]],"9eaae0feb245733106045a2c6766d2a2a729a9bdb22b98ec4434c09d76663264":[`state-feature-user_profile_emails`,`202fadb0df4fc5da385edddbda27e96126d0d7a2db6a63375fa506221163a4fb`,[155],[]],"45451969c6ea5bebf37bbfba310467e482af74731a7cb0f2affb316059e21528":[`state-feature-user_profile_identities`,`3a24e89bd446dffbef50b7bd4b87288abc6eb470c290eaabcb1761fbe5244c06`,[154],[]],"561e14603e294368a12a2b5f6ecb0cc509d0b8847a93817286bd5a14d076ad0f":[`fragment-skill_library_entries`,`c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d`,[93,94,95,96],[]],"6b07280274e87ca0fa5bbc1887818497375298fa700b24852dc981f3da1da555":[`state-feature-skill_library_entries`,`c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d`,[93,94,95,96],[]],"43645abd05379894c2982bcd88b8dff0cd6c9802e5bf2ab6cc54af87a7e6a37d":[`state-feature-skill_library_revisions`,`533218405c3e483d687da824cf15f9ebcb76ba69675946e95c134702dc199890`,[95],[]],ea1b1fb7d6d8256ec58bc7c28541312c1a543e88bf9ed7e4366791ea243d8ec0:[`state-feature-skill_library_events`,`e5269a0f2846007c0b3eef62963979fa7a2cdd01ced20906ec4ac407ace66c03`,[94],[]],"31318a62bdb75dccad514a02adde07df11d26b756f51d1d50d0e6b19d399b26e":[`state-feature-skill_library_uploads`,`ba066e91b42e768b5f705703783cce87eb90fac71a37cad9dfdf308a19ccceb6`,[96],[]],ed3d9e7b13809b3a9b91d48d63816b26354681d727b96e39496d02c775343e1f:[`fragment-operator_approval_standing_grants`,`9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa`,[73,74],[]],be37db3a4634164c401b2d8e5ac3c2d712cd9eb973e3f2b39daa578adedff0ae:[`state-feature-operator_approval_standing_grants`,`9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa`,[73,74],[]],e23a5880a289da464471db5cfff10b9a6962b4d52c99260a3e366746c023de76:[`state-feature-operator_approval_standing_grant_generations`,`0d525f0400a30f0582698e91e78f63063c08a8c06b3bcfe624dbd2f2fbe7834c`,[73],[]],"7b8bf2fd3ae786c589bf138b32270450c1a2582bcb9a825c1eaf7fb3a7bcea06":[`fragment-worker_environment_session_attachments`,`b95d7054311f0f2d1e0885104c66ff243dfe4f68b84ed2d814ae68e748574417`,[156],[]],"32cc45ee15a4c4dd21d3ebeb9c259fe465085ed35ee781e611f293af5bbda189":[`fragment-durable_background_processes`,`a12b3e39e6d9ed28b9aea95a15a7a60f4c9615ad48d323de7a52560475c62ea4`,[36],[]],"6496f80e29da252472af802873996fc3cd761f245f4dcf6fefb1c7aee38e720b":[`fragment-sandbox_persistent_execs`,`f885f117e199277aa5c23a9095f55e742797249d13e2f4e4df8fbef1daba399d`,[83],[]],"156673e9396f27223073abdbbd2e13269bd7f45f577ed6aff00e017ab232d940":[`state-feature-sandbox_persistent_execs`,`026ac7355b83187c8f7eef5cbd48ab36ba7de1b4fe40413ee1168ebff6c2d67a`,[157],[]],"61e308c5a715e5ee5ff29b65a31d2e7ccd039498494d9afe120129f62f86b764":[`fragment-user_background_images`,`1da03995969350f59b3f8a64d9144b781d467e6ea75f70d5abcd6e18734678e1`,[111],[]],b36f4fc0be0d53e48e207f50a3cba34df76c4028a2d85201f7b262b1c7a4c2ab:[`fragment-update_runs`,`7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55`,[110],[]],c3db4ffcf4092146e5d923b60516a00a8db41825f8bffb138b848195576b987b:[`state-feature-update_runs`,`4caad814f837565106a1a17b982bf4ff004bbdba00a6ff05a3b9c5ef2e5a5945`,[158],[]],a0323917d8786f2e6cbc3470d86c2a4e123103b84a5dc95d59bbf20759b8ab4c:[`fragment-session_repository_workspaces`,`51ee403217b5a9bff65b4d3b93a571f8fbeb60a7b2935860db7e21e7959e7833`,[88],[]],d62b52a34e2626a7983ae5c48268f04567e93170457e63502b7096486a6ce9f7:[`fragment-github_repository_publication_requests`,`1ae034bde6e00a9b919bcbb987df8aebc5856ab6f4c979743355ecb682418a99`,[49],[]],"6d205ed705fcf89e34e2679f192b2dd50e4cbcb9b06b473c3e81dd48c8811102":[`state-feature-github_repository_publication_requests`,`bc5c46f3cc22c0572b25d10344108465509d7189e1d51b0f6fa335b1d86497cf`,[159],[]],"079ee34fc1ed4ca27e807b01c7456deceacc57fead388917ff1b275b5047ab06":[`fragment-github_publication_session_lifecycles`,`755e9a26722c11b5edd9d4f6bf270bfdc706428593de4216c311f85fad0a8e69`,[48],[]],fc4d434c6c76c4e5c5b1fb9c54ebe7e98a395fea6370ada7ac4767ad755051ac:[`fragment-github_personal_publication_requests`,`eda486fc6d1c12adfe86012cfa6d0f6afb64906b1d4c75e3785bda082281a4e1`,[46],[]],"8a4a42e9e8549a0f2e73b33b4031673e2e939624d95586693bc2ac43742bf30f":[`state-feature-github_personal_publication_requests`,`aeb05b8ff41f64e5bab165feac6f1abcdb6dfefc2a5bfbbe88e34861cc40922e`,[160],[]],"0f3d662483be17f95f492157a8ba28b163afab9c52429ab6ff277ebe8b0a27fd":[`fragment-cron_job_runtime_authorities`,`ebce08da69716c0011c0db38decb38e5eaa0069c6f8360e85afdec8c624a360e`,[22],[]],e16c741ca5371718cf7d95114ee1043ad33db04c470f268ccbe3130f699998d9:[`fragment-cron_run_trigger_state_retirements`,`0e85a9fecddeef5129569f503fb32cc0d94e9c98877286be10e15eb657e682bb`,[26],[]],"632466e72325a428d8b4c4dfa1b7a14be9f57236bee791e9412ea07b24fca254":[`fragment-execution_identity_contexts`,`15be6a7de30d2ecb9b15fed1eb13dd65da858f1eb378e95f737f14241c11b3d9`,[39],[]],"7683ab1fd0bccb8e29499c3b6df0070d9cc7cd6249c8c103d654b015ce309417":[`state-feature-execution_identity_contexts`,`2dc283d04b315fd0199a9e13653edb03c8614d12be2ca6f005c7e110aab62d2a`,[161],[]],b796607c50ccb0e85abdec5d76b88b8076596077afe71e238b7831edd061f9e8:[`fragment-mcp_oauth_pending_authorizations`,`39eae7dacb98a3cc36bd7598c4e416fc3f180c95aa78b7fd5a1f11afecf2d5b9`,[56],[]],"15f660904a6ff5b2e08b57e7e1979ae85d7476426da0e6aa8fc35a013d557501":[`fragment-node_worker_launch_containers`,`bae513184057ef120b3b7ff1f08fc0affa1293461353ac060f1c0148346225f5`,[66],[]],"2703e870e99174d91597e44b5619574373f3da7030c4cd9907a8ac341f00802f":[`fragment-node_worker_launch_boots`,`ce110d8dd52daad838b24137dc43979dafe784dd08348e09482093f47dd5d98b`,[64],[]],"7c1c6d4fbba2f48e6ad4003bbc7d22b3b543034a8c2456fc542d2dac90c46aad":[`fragment-node_worker_launch_cleanup`,`d45196104873c5924d0fddabdce7a4f08b8fab2c68880492de968c978ef031c8`,[65],[]],"16bb8bbf8eb97d4a3895c031f758ca37106c072cd78e18b99e4f68463679c153":[`fragment-node_worker_launch_process_scopes`,`d9ce1d80156505cb99854d410b48f37b0cf82d0259417bd3c64e1ff91d5b05b2`,[67],[]],b6d0283d081e77179a54f4e54847168156095e3ec4a487d17feea8dfe26a1626:[`fragment-node_worker_launches`,`cac88014114f03cee09470505617bc58f893efc072306d0b4c6fb48e259fb17c`,[68],[]],"5dc1cf9bb59834e9497e191514c7bfb850e062f7744047c7a4289516b4b0e214":[`state-feature-node_worker_launches`,`f07514c3996f79e89f46d771b58859826342f72a12f024b29726a82f6481d6f9`,[162],[]],"5e238c5c57f8e1bfc2d5fc91ad2a4ad3ae421ca1f36a84f973a8299f99ee7015":[`fragment-node_worker_prepared_workspaces`,`1ab2c378547ad29580b84dcebbc4ed9c99008c8a242446cdad0553a24bf06eec`,[69],[]],"865397a51b0e47eda5349293c3fc590226718cdad61afe420c578ab3ec786732":[`fragment-node_worker_turns`,`cb3eaac1dc2492905a55c037ba7c09748bbdbc9c6a13cbb92e3cbec80c94f5d6`,[70],[]],"64cf0d044c7dede24d58a370a2f52cf19616efc9523343a698f7127c4d187f1d":[`state-feature-node_worker_turns`,`d1d9be01c96d9dd47e4e23d0099074f561aedb976de062622daffd173443c17d`,[163],[]],eee176fa30fb315a218b50f12be8d9e4e5561441d59250cf7029aac4edd9eb38:[`fragment-operator_approval_execution_identities`,`0f2bc5e4d656eda1ad36b778905e7e55f8685c0b41a68883f6e9fb1b838a874c`,[72],[]],"57562a3e6f834f876e5c03711f50dc514c8bdd432a87f1f54cbac2901642d5d4":[`fragment-web_push_approval_deliveries`,`f11526f4044590884acc313f8a8fb921ce93fb2372e2e64a635989af93d3012e`,[114],[]],"74b05c720f6b4a8ff88824c9843816992d5233b93ccd85bea66c2fbd2a3480c5":[`state-feature-web_push_approval_deliveries`,`92bd2e9265be63167980a22960aa201502864ec59e283821ad3eab6e765744ce`,[164],[]],"0b710f9ea230c2d23182de151edebc06dfb2800ad6207647d27ccb2c900b5d6a":[`fragment-execution_decision_facts`,`251fe6aa9c0c1ef726ab36810df59e644d472757b269b7e6ac36a5b7b1864ccc`,[38],[]],"9cd9f63b1002094a7e0538c52b75f2c8d26664937ff5559f64a004feabe47816":[`state-feature-execution_decision_facts`,`8235ed3d9eb951894768fa49670db7390f7950e96618daded2851a55c2e827ed`,[165],[]],"49e2b7094b1bf25586bc63b3ce3e971873c26584de40bd96654a31b945b3881f":[`fragment-execution_owner_lifecycle_bindings`,`83228457b7900a349a7a60693f5be9fe5ce2b86f8ea3be6bd1b3bcbae9381c73`,[40],[]],c222191b2157eb84fae227b67417210870ff546ce38b799805cd32e63e198bcd:[`fragment-outbound_message_execution_bindings`,`90715ffad8419a713baa7a63aa0d15038b16391bba0c3739bdae7c3196cc5fe5`,[77],[]],f782e56e1dca81426ff88a94a9702580d0c6bdd1a420e8c1741fef3aa7c18b81:[`state-feature-outbound_message_execution_bindings`,`c29af535c3d6cf16bb31a085c7b68d150c132921b51f560495e75dd1f5451f2d`,[166],[]],"733bbcfcce8373ce968a993fc1f4d3f911d0011c8a60833f613f9cdb7de22d9e":[`fragment-outbound_message_progress`,`07938ecb7fa35203a80bf93cb28900b5eb0c35dcf47bfa476b436fd39d881135`,[78],[]],"6e2c6c197a77c179716d6ddead9a7226c49db5e8b69c1775ea8808e5e24cf271":[`state-feature-outbound_message_progress`,`b1fdd16f1d29ceeed6d32e873b0ef54831ad693b4e910c1fe55bc59aa60c4709`,[167],[]],ab3748daca8019e0908cc9906304f50a26cffd9d5e9ea3ba1ea3a759315737cb:[`fragment-agent_provenance`,`da5d017b6840d65ebd1bc234ae3fdf4540bd00256bfc50c599a4195d15066c17`,[6],[]],be11d3e5a672ca34875c1f06cfc6d5d5a1293a7077302a759c12c2c17b2cdcb6:[`fragment-cron_run_receipts`,`593a0b293257e23cf22f14e308c7f75a7032d5f0bdbba0fa3d307f3382e3bd4c`,[25],[]],"41824738e9d17ef8abfa9bda96824ab259ca9e81d3ad647b16b407a6bc4dc28f":[`state-feature-cron_run_receipts`,`1c1c9f4b60d18e51e0db6940a6813c5a7a1a14dffbe38921318e61c295597112`,[168],[]],"8b28fd18dffd5b09fb5a09d8e0d04b2dbf1372081b356131f1df2f4c41895745":[`fragment-config_revision_keys`,`8b416bf248c7702519e58249d29725d42d52a95d8a22084964637f3ed57cae9d`,[21],[]],"443ee39ca023c21d0234f2897e3790e8e9757daf427989b731f97074c5bf28fe":[`fragment-secret_store_entries`,`45f2e66f10baf9470316cb216a91ef6ffa865a2c2f25b181e37f20171348576b`,[86],[]],"10e3ba9552ac35206e3f3d467a44f71602f4b1d3404204836f72106155b5fe6d":[`state-feature-secret_store_entries`,`1eefc2ba0eecf91c8fd96442e750b4e555fb97485569f3bd2bf7205c02466cee`,[169],[]],ecb98cd64bfc2fc0828eaaac59c122a4a9381d752dfdc4166d1fe287e9f1cecb:[`fragment-projects`,`9ac5c2cc1d8a72b975287fe40d1f9cf5929671ee033dd68538315e9770df9f36`,[82],[]],"7b5e9bd4ec7f91f71f2fcea1deaa9058d06f907e460e2d1a2a8fa333bf6942c0":[`fragment-worktree_templates`,`a9481ceaf044b2db824f5df1823d0619c7b9e53310b83a32c4399421cc6a7e18`,[132],[]],"85b0f3fbf9815fa0125a5a823eacebc68306ac4864d89047bb2699611b0044c5":[`fragment-user_preferences`,`24c5cd67b1014eb8ca50a492d93a9b9ec5e5a3b936722c35c7b0768a8b1823e2`,[112],[]],"1f164add8aeb9d28f7c779f88fe40dc7a344e14479fe9a017181151330bca6fd":[`fragment-device_pair_setup_completions`,`3400a6259bccdb3546a778b36215284bd14c9613a1ece543e9deaf3539e3b288`,[30],[]],"54a593978142e9fdd957d9aff2368fd3b9d26702968b4ede856df3a933023139":[`fragment-github_publication_requests`,`81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e`,[47],[]],"4c1eb061476b0ecbfc022fb1bd4c927c7c4b3868f40702507c9911ccd3504b2f":[`state-feature-github_publication_requests`,`0375d1a5a88363e5cd216f3addbf170f8be1098ea8626e0e0f95ebb91768588d`,[170],[]],"1f844843f7e4c042331e07eb663873d85bfb1291db181f98c0834a0d01bbf2e2":[`fragment-device_pairing_join_codes`,`4ada0f17fe210baff80cc7da940a58ef4bd27911312469dd15a3473ef1119ad0`,[32],[]],"5ac69298f3597ee21ed377f802610edbd4e638bc0d0cd5be7b2066f5c9104b1e":[`fragment-device_pairing_browser_requests`,`c65ddfeaf2ea8a7653a6e2d374d86422deb3fccbb4424f456bd8d0901c69b4c7`,[31],[]],ddfc4231357afb56d903eca77fbfebf817ffafa47d491193e6948b5032ccfefe:[`fragment-skill_workshop_changes`,`993cb9d62f11305ca322f0c76e895a37604132572f2f651c635d0d72eb416b85`,[100],[]],d3bf805006eb83550c1d4a662610e8897cd41ce52de6e370424d3f3ed26e3d80:[`state-feature-skill_workshop_changes`,`01b83680a33b4f2e7d46a70f3e122ebe40044b44ff733891a29a340bdcbba3fb`,[171],[]],"59c7fa24ee5aa93144f936173f6efde68e9d2af33d074d5e208f971d500ac5d3":[`fragment-worker_environment_ssh_fallback_ports`,`18ead5da9eec5f58b75326fdaf9ed55a3d0433facc14dad465add6bd80dff080`,[117],[]],"62bf1862f7ce3c0abcaaf4cc070834c5f402e1696b78d22e7ca7bd23b0fec36d":[`fragment-worker_session_placement_moves`,`8188e7a581a51d08faad38cdf6b07041e2b2e760d17bcfa109df49ec0c83c430`,[120],[]],f01d4e41642436ccdf0ba63450989879b094bd74a7a97cd98b2ec0c4accd4ad4:[`state-runtime-0-0`,`cf307d842aa556e9f0bbaae9cf448744d4991310b34333f0fbf8c7e894c1a86a`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,118,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],"1e2662ff71a59cc056f70d661bddb4c6c0e86b36c4151490343ffd787b15891a":[`state-runtime-before-provision-source-0-0`,`16da1fa5ae0e4e4c25f75803a1b39c8971b93c0a0a311edf4fbdefd50f33d0a2`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],"0c3068a4622b9151d2321f80af94861f162d8288b6391c38d89822e20f856639":[`state-runtime-before-bootstrap-deferred-0-0`,`0d8a0829977f7e6ec02a3fa9febb23562a521779369ad959613d26c4a96d72fe`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],"40222aeec53b8897045719a8d38a4b0658ffd1d21d4fd0fef11458c48ed5625b":[`state-runtime-before-v40-0-0`,`0d8a0829977f7e6ec02a3fa9febb23562a521779369ad959613d26c4a96d72fe`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],a45a311ca45ef1a2814feada0479c1f948470534ccb4bd6b10cf41f2a4ab6d57:[`state-runtime-0-1`,`c913a89e38b081c27405542ec53903e985f81b91564d3f87c237818c1bca9e34`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,118,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],a65a121da4de231f2d96dcf4503136c5f7cc2f80e54aa9d630fb2e5a9de9a97a:[`state-runtime-before-provision-source-0-1`,`350780aa0d95ca738450fff1e3479414d25bc3dca09cbe9741d6e52fb03879f4`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],"3075984cf7583cf173b40648a7b27d0cf683b2c9d38d218e6584da4efd0ef951":[`state-runtime-before-bootstrap-deferred-0-1`,`b866dbf70f630e748a46d2ad5a2c48c5d95bd4070784a9f7fcec3dc349d28af1`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],"5ed7c4627eed8b68ddfcf5b4ffbd98c2085cc17c1ab55a1d69f07aee108f202d":[`state-runtime-before-v40-0-1`,`b866dbf70f630e748a46d2ad5a2c48c5d95bd4070784a9f7fcec3dc349d28af1`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],"381aa534d8d5eb4bec164b7e73e83221d4d78bd8058c425a554dcb91c0e34c58":[`state-runtime-1-0`,`0c8dde495615c5c2a57ec8598ca9ece53f0ea5e72e963b92f1716a5e961106da`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],a99f466c73b07f39b54a6711d7e5df7767e45c7c9b2a45943ed96726ba8f4608:[`state-runtime-before-provision-source-1-0`,`77e32f62ae9edd8ad44e5c9995e71e6c19d5ce8c55f468b0b202379b7e27dc54`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"90569dbff4f9ac27a68a4c13ddd2baaeb92962f32e1a58a6790eb5baeeb453fc":[`state-runtime-before-bootstrap-deferred-1-0`,`0fc6212e574b5022f924a9ed41c6ffadb979ca10c37deb9fc7f3ecd8af9c03f8`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"41b7ccaf89f2ce0b2e8898c714693b62ccdeba93e7eea48612a2783d77a97f28":[`state-runtime-before-v40-1-0`,`c070d1efc0b3e1f67ac4d5d5cc01bb5d57a7ddbf6f72b67da1888dd8a1cb4144`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],cc59fb921d6be3730c729838875b379b1aec8edb9acd5e2ed09ea41f9b9ace33:[`state-runtime-1-1`,`26adf2401aaa91b57cac91157367732c55e904f417428fed0a8f7d01510e55fc`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"269874b20b213faf7f8c8ecb6cc4c759853ffd1d63b5f6a395180667ffb2a9b3":[`state-runtime-before-provision-source-1-1`,`8060a02d609b6c8fe37e25568727275eaa76fb8908a93581083675afbdf3bd80`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],d99906589af97e0bc4e77af6f5e155e6eb689abfde8ef42d8534862f0c0f4d7d:[`state-runtime-before-bootstrap-deferred-1-1`,`288cbad6e819ed548b3fc769bc808be2a06f2b837db943abf969ff334872d540`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"126f5f0137d7c19fb0907ad7f763a83d4b675d38190526623081dff1dad6ab99":[`state-runtime-before-v40-1-1`,`8a47e464e648029da13f34055cf04b4337e35a37bfc83f8ff130959ecfeb29cc`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],d285aca718d789bb5f8799fd148a30792ae63c7ce10fa0f0c757391806d83cac:[`state-table-agent_database_leases`,`fed699717b3ff6f0f406750e7ef2e57c0e047f4a8aa9669855cd001f4eecb4b9`,[3],[]],cac005273b1563f1269aa41ff5cc8a4d7b94a4cb7d9f82be2917853a736168de:[`state-table-agent_deletion_journal`,`6c66fbe42d4b3d671ea3212b0024f65af05cbf9ea67dc8ce1763542f2ce245f2`,[5],[]],dc1f04127c4146d414429aba7f0f055680178ac035c1566f8202cb8ba6ba2575:[`state-table-config_machine_state`,`21025ec6d7ee6da8951d3f519c48e44744b0392597ce821984dd3a9e5abb1787`,[20],[]],"246e73f17e8b92383ee8d6dfe4b657ee3dc3040e8c6398ff36c17ee14222eb37":[`state-table-gateway_restart_intent`,`91a30a8d1423b5d855a975ceb40e2ef07bdfa21f284c59bee6d189679ca8dba9`,[44],[]],df93d6687254de2f31ff263b2dafdd67656caa6ac10180f95801bde2dce8f7f0:[`state-table-schema_meta`,`df4efc2e7d50f8bde377f55f5a020ae5ba98cfda938879054cf02d9b4905b793`,[85],[]],cb1f3279e7e3b90290d5ab10856edf532f9c69f278116dd1a8002a4b050f2c1c:[`state-table-state_leases`,`6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc`,[172],[]],a503e610cfb224030ab2473b374631cefa4972377d9d04e07b5d5efb07cee14c:[`state-table-worker_session_tool_operations`,`a146f78ad23ec99bfcb50819c65478b5e94c4a8e4159086ef5073fc76e26cc2d`,[122],[]],"4f45746754bef21a88b4fdfc0932df58b22bf31590a961e4a53957cce7ccd873":[`state-table-worker_turn_tool_authorities`,`fef54ec7cc72bf3869c78b67f31ce96ed842a1ba872f7090e52feff5f547560c`,[125],[]],"8cbef48665eec155650765377478b38fde1c87ef57fadb423438f85f8c91ad66":[`state-indexed-github_publication_requests`,`81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e`,[47],[]],c7c1408a52e8649cf030b636ee3d984e969c5fdb96f6834634e7cb4807e624f2:[`state-indexed-update_runs`,`7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55`,[110],[]],d40fd26bedb861443248d33289dc8d89a1750f3631730dfde2ae285f2c7988ca:[`state-existing-state_leases`,`4289076cebb114b14ac96672941b2be0679f1033e23fe059eedce8dc2b1eea57`,[85,172],[]],"13150d745ef24ab5e6aafe0b365af15d6c5d471a659e5eb2a1c38e359984a47f":[`state-existing-agent_database_leases`,`9fe50268db674b01265b7e77701aedcfffe36567086fc763de8b89f87f4cb67d`,[3,85,172],[]],cc6464642f0f115776287e4d0966e2fc564b8e62db519c2bfad7a25c9e67de51:[`state-existing-migration_runs`,`c8d7a60b14124212b817fab783e7e9e97253d27ae97c14dd6107ba9f1ad727f1`,[173,85],[]],"789bdcc904f4b35b57f9cb829909f2c9cda541c86179beb6904977146665c0c9":[`state-node-worker-lineage`,`f235501e3f5767c362c7aebce3e678d33cdb45e3b776391980019cdf7cc0f37d`,[65,162],[]],"7c5c2640b3ec45cbac611c07c67f478f0ddc85a4bbfceb9c3576f0d7aa3bd14a":[`state-node-worker-descendants`,`0991532bbc3ca042fc5c1c2026b8aa8d50b24a5bccf26e53675340a4853a665e`,[65,67,162],[]],"72c354791974ce88794c96c16135a89f07b48b9b03542f968beadf05b76aae1e":[`state-retired-commitments`,`19bef9367d336bb367e75740610741cb67deeef86a7f54065758609d67ae8a38`,[174],[]],"2309aff06f4bac77072697764926a0042e6b6069c9504d5bb8c6a0601e9d1314":[`state-retired-commitments-shipped`,`f4d088664f133eea8b1e83fd342d1effaa86d836f8593e02778531468372a303`,[175],[]]};let $l;function readSqliteStateFingerprint(e){let t=Ql[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Zl[e][0]),indexNames:i.flatMap(e=>Zl[e][1])}}function readSqliteStateCatalog(e){if(!Ql[e])return;$l??=Ir(import.meta.url)(ai(new URL(`../../assets/sqlite-schema/sqlite-state-catalogs.json`,import.meta.url).href));let t=$l.catalogs[e];return{tables:t.tables.map(e=>$l.tables[e]),views:t.views}}function readGeneratedSqliteFingerprint(e){let t=Gr(`sha256`).update(e).digest(`hex`);return readSqliteStateFingerprint(t)??readSqliteAgentFingerprint(t)??readSqliteDaemonFingerprint(t)??readSqliteClientFingerprint(t)??readSqliteMemoryFingerprint(t)}function readGeneratedSqliteCatalog(e){let t=Gr(`sha256`).update(e).digest(`hex`);return readSqliteStateCatalog(t)??readSqliteAgentCatalog(t)??readSqliteDaemonCatalog(t)??readSqliteClientCatalog(t)??readSqliteMemoryCatalog(t)}function fingerprintSqliteSchemaCatalog(e,t){let n=t&&new Set(t.tableNames),r=t&&new Set(t.viewNames),i=t&&new Set(t.indexNames),triggers=e=>e.map(({name:e,sql:t})=>({name:e,sql:S(t)})).toSorted(byName),columns=e=>e.map(({cid:e,name:t,type:n,notnull:r,dflt_value:i,pk:a,hidden:s})=>({cid:e,name:t,type:n,notnull:r,dflt_value:i,pk:a,hidden:s})).toSorted((e,t)=>e.cid-t.cid),a={tables:e.tables.filter(e=>!n||n.has(e.name)).map(e=>({name:e.name,sql:S(e.sql),strict:e.strict,withoutRowid:e.withoutRowid,columns:columns(e.columns),foreignKeys:e.foreignKeys.map(({id:e,seq:t,table:n,from:r,to:i,on_update:a,on_delete:s,match:c})=>({id:e,seq:t,table:n,from:r,to:i,on_update:a,on_delete:s,match:c})).toSorted((e,t)=>e.id-t.id||e.seq-t.seq),indexes:e.indexes.filter(e=>!i||e.unique===1||i.has(e.name)).map(e=>({name:e.name,origin:e.origin,partial:e.partial,unique:e.unique,sql:S(e.sql),terms:e.terms.map(({seqno:e,cid:t,name:n,desc:r,coll:i,key:a})=>({seqno:e,cid:t,name:n,desc:r,coll:i,key:a})).toSorted((e,t)=>e.seqno-t.seqno)})).toSorted(byName),triggers:triggers(e.triggers)})).toSorted(byName),views:e.views.filter(e=>!r||r.has(e.name)).map(e=>({name:e.name,sql:S(e.sql),columns:columns(e.columns),triggers:triggers(e.triggers)})).toSorted(byName)};return sha256Hex(JSON.stringify(a))}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};const eu={"missing-table":`missing table`,"missing-column":`column definitions differ for`,"unexpected-column":`column definitions differ for`,"column-definition-drift":`column definitions differ for`,"table-constraint-drift":`table constraints differ for`,"table-definition-drift":`table definition differs for`,"missing-or-drifted-index":`missing or drifted index`,"unexpected-unique-index":`unexpected unique index`,"missing-or-drifted-trigger":`missing or drifted trigger`,"missing-or-drifted-view":`missing or drifted view`,"unexpected-trigger":`unexpected trigger`,"virtual-table-definition-drift":`virtual table definition differs for`,"table-options-drift":`table options differ for`};function isColumnIssue(e){return e===`column-definition-drift`||e===`missing-column`||e===`unexpected-column`}function defaultIssueMessage(e,t){let n=isColumnIssue(e)?t.split(`.`,1)[0]:t;return`${eu[e]} ${n}`}function createSqliteSchemaIssue(e,t,n){return{code:e,objectName:t,message:n??defaultIssueMessage(e,t)}}function legacySqliteSchemaIssueMessages(e){let t=new Set(e.filter(e=>isColumnIssue(e.code)).map(e=>e.objectName.split(`.`,1)[0]));return[...new Set(e.filter(e=>e.code!==`table-constraint-drift`||!t.has(e.objectName)).map(e=>e.message))]}function throwSqliteSchemaMismatches(e,t){let n=t.slice(0,8);throw t.length>n.length&&n.push(`${t.length-n.length} additional mismatch(es)`),new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join(`; `)}; run openclaw doctor --fix to repair it.`)}function assertSqliteSchemaContains(e,t,n,r={},i){let a=collectSqliteSchemaIssues(e,n,r,i);a.length>0&&throwSqliteSchemaMismatches(t,legacySqliteSchemaIssueMessages(a))}function collectSqliteSchemaIssues(e,t,n={},r){if(!getSqlitePinnedReadSnapshot(e))return runSqliteSchemaReadSnapshotSync(e,()=>collectSqliteSchemaIssues(e,t,n,r));let i=typeof t==`string`?readGeneratedSqliteFingerprint(t):void 0,a=i?.viewNames??getSqliteSchemaContract(t).catalog.views.map(e=>e.name),s=r??createSqliteTableContractReader(e,a,i?.tableNames??getSqliteSchemaContract(t).catalog.tables.map(e=>e.name));if(hasCanonicalSqliteSchemaFingerprint(t,s,n))return[];let c=getSqliteSchemaContract(t),l=new Set(n.excludedTables??[]),u=new Set(n.excludedIndexes??[]),d=new Set(n.allowedMissingTables??[]),f=new Set(n.allowedMissingIndexes??[]),p=[],add=(e,t,n)=>{p.push(createSqliteSchemaIssue(e,t,n))};for(let[t,r]of c.tables){if(l.has(t))continue;let i=s(t);if(!i){if(d.has(t))continue;add(`missing-table`,t);continue}p.push(...compareTableDefinitions(t,i.definition,r.definition,n,!d.has(t)));for(let e of compareTablePragmaFacts(t,i,r,n))p.some(t=>t.code===e.code&&t.objectName===e.objectName)||p.push(e);let a=new Set(i.indexes.map(e=>JSON.stringify(e))),c=/* @__PURE__ */ new Set;for(let n of r.indexes){if(n.name!==null&&u.has(n.name))continue;let r=JSON.stringify(n);if(c.add(r),!a.has(r)){let r=n.name??t;if(n.name&&f.has(n.name)&&!e.prepare(`SELECT 1 FROM main.sqlite_schema WHERE type = 'index' AND name = ? COLLATE NOCASE LIMIT 1`).get(n.name))continue;add(`missing-or-drifted-index`,r,`missing or drifted index ${n.name??`on ${t}`}`)}}for(let e of i.indexes)e.unique===1&&!c.has(JSON.stringify(e))&&add(`unexpected-unique-index`,e.name??t,`unexpected unique index ${e.name??`on ${t}`}`);let m=collectOptionalCanonicalTriggerGroups(e,n,t),h=m.flatMap(e=>e.triggers),ee=m.filter(e=>e.optional).flatMap(e=>e.triggers);for(let e of r.triggers)ee.some(t=>t.name===e.name)||containsTrigger(i.triggers,e)||add(`missing-or-drifted-trigger`,e.name);for(let e of m){let t=i.triggers.some(t=>e.triggers.some(e=>t.name===e.name));if(!e.optional||t)for(let t of e.triggers)containsTrigger(i.triggers,t)||add(`missing-or-drifted-trigger`,t.name)}for(let e of i.triggers)!containsTrigger(r.triggers,e)&&!containsTrigger(h,e)&&add(`unexpected-trigger`,e.name);i.virtualTableSql!==r.virtualTableSql&&add(`virtual-table-definition-drift`,t),(i.strict!==r.strict||i.withoutRowid!==r.withoutRowid)&&add(`table-options-drift`,t)}let m=s.readView??createSqliteTableContractReader(e,a).readView;for(let e of c.catalog.views){let t=m(e.name);if(!t||t.sql!==e.sql||JSON.stringify(normalizeColumns(t.columns))!==JSON.stringify(normalizeColumns(e.columns)))add(`missing-or-drifted-view`,e.name);else{for(let n of e.triggers)containsTrigger(t.triggers,n)||add(`missing-or-drifted-trigger`,n.name);for(let n of t.triggers)containsTrigger(e.triggers,n)||add(`unexpected-trigger`,n.name)}}return p}function assertSqliteSchemaTablesPresent(e,t,n,r={}){let i=new Set(r.allowedMissingTables??[]),a=getCanonicalSqliteTableNames(n).filter(e=>!i.has(e)),s=[];for(let t=0;t<a.length;t+=500){let n=a.slice(t,t+500),r=n.map((e,t)=>`(${t}, ?)`).join(`, `),i=e.prepare(`WITH expected(ordinal, name) AS (VALUES ${r})
         SELECT ordinal FROM expected
         WHERE EXISTS (
           SELECT 1 FROM main.sqlite_schema
           WHERE type = 'table' AND name = expected.name LIMIT 1
         )`).all(...n),c=new Set(i.map(e=>e.ordinal));for(let[e,t]of n.entries())c.has(e)||s.push(`missing table ${t}`)}s.length>0&&throwSqliteSchemaMismatches(t,s)}function getCanonicalSqliteNamedIndexContracts(e){let t=getSqliteSchemaContract(e),n=[];for(let[e,r]of t.tables)for(let t of r.indexes)t.name!==null&&t.sql!==null&&t.origin===`c`&&n.push({definition:readCanonicalIndexDefinition(t),fingerprint:t,name:t.name,tableName:e,unique:t.unique===1});return n}function getCanonicalSqliteTableNames(e){if(typeof e==`string`){let t=readGeneratedSqliteFingerprint(e);if(t)return[...t.tableNames]}return[...getSqliteSchemaContract(e).tables.keys()]}function getCanonicalSqliteNamedIndexNames(e){if(typeof e==`string`){let t=readGeneratedSqliteFingerprint(e);if(t)return[...t.indexNames]}return getCanonicalSqliteNamedIndexContracts(e).map(e=>e.name)}function hasCanonicalSqliteSchemaFingerprint(e,t,n={}){let r=typeof e==`string`?readGeneratedSqliteFingerprint(e):void 0;if(!r||!t.readCatalog)return!1;let i=t.readCatalog(r.viewNames,r.tableNames);if(fingerprintSqliteSchemaCatalog(i,r)!==r.fingerprint)return!1;for(let e of n.optionalCanonicalTriggerGroups??[]){if(!r.tableNames.includes(e.tableName)||n.excludedTables?.includes(e.tableName))continue;let t=i.tables.find(t=>t.name===e.tableName).triggers;if((e.optionalWhenTableMissing&&i.tables.some(t=>t.name===e.optionalWhenTableMissing)||t.some(t=>e.triggers.some(e=>e.name===t.name)))&&!e.triggers.every(e=>containsTrigger(t,{name:e.name,sql:normalizeOptionalCanonicalTriggerSql(e.sql)})))return!1}return!n.excludedIndexes?.length||!i.tables.some(e=>r.tableNames.includes(e.name)&&!n.excludedTables?.includes(e.name)&&e.indexes.some(e=>e.origin===`c`&&e.unique===1&&n.excludedIndexes?.includes(e.name)))}function collectOptionalCanonicalTriggerGroups(e,t,n){return(t.optionalCanonicalTriggerGroups??[]).filter(e=>e.tableName===n).map(t=>({optional:!t.optionalWhenTableMissing||!e.prepare(`SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name = ? LIMIT 1`).get(t.optionalWhenTableMissing),triggers:t.triggers.map(e=>({name:e.name,sql:normalizeOptionalCanonicalTriggerSql(e.sql)}))}))}function normalizeOptionalCanonicalTriggerSql(e){return S(e)?.replace(/^(CREATE TRIGGER) main\./iu,`$1 `)??null}const tu=/* @__PURE__ */ new WeakMap,nu=/* @__PURE__ */ new Map;function getSqliteSchemaContract(e){if(typeof e==`string`){let t=nu.get(e);if(t)return t}let t=typeof e==`string`?readGeneratedSqliteCatalog(e):e;if(!t)throw Error(`SQLite schema has no generated catalog; run pnpm db:postgres:gen for its declared schema input.`);let n=tu.get(t);return n||(n={catalog:t,tables:sqliteSchemaContractFromCatalog(t)},tu.set(t,n)),typeof e==`string`&&nu.set(e,n),n}function readCanonicalIndexDefinition(e){if(e.name===null||e.sql===null)throw Error(`Canonical SQLite named index is missing its schema definition.`);let t=(e.unique===1?/^CREATE\s+UNIQUE\s+INDEX\s+/iu:/^CREATE\s+INDEX\s+/iu).exec(e.sql);if(!t)throw Error(`Canonical SQLite index ${e.name} has an unreadable definition.`);let n=Dn(e.sql,t[0].length);if(!n||rr(n.raw)!==e.name.toLowerCase())throw Error(`Canonical SQLite index ${e.name} has an unexpected schema name.`);let r=e.sql.slice(n.end).trim();if(!/^ON\s+/iu.test(r))throw Error(`Canonical SQLite index ${e.name} has an unreadable target.`);return r}function normalizeColumns(e){return e.map(({cid:e,name:t,type:n,dflt_value:r,...i})=>({...i,name:rr(t),type:n.toUpperCase(),dflt_value:r===null?null:Gn(r)})).toSorted((e,t)=>e.name.localeCompare(t.name))}function normalizeForeignKeys(e,t){let n=/* @__PURE__ */ new Map;for(let{id:t,from:r,table:i,to:a,...s}of e){let e=n.get(t)??[];e.push({...s,from:rr(r),table:rr(i),to:a===null?null:rr(a)}),n.set(t,e)}return[...n.values()].filter(e=>!e.some(e=>t.has(e.from))).map(e=>e.toSorted((e,t)=>e.seq-t.seq)).toSorted((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t)))}function compareTablePragmaFacts(e,t,n,r){let i=[],a=new Map(normalizeColumns(t.columns).map(e=>[e.name,e])),s=normalizeColumns(n.columns),c=/* @__PURE__ */ new Set;for(let n of s){let s=n.name,l=`${e}.${s}`,u=a.get(s);if(!u){(r.allowedMissingColumns??[]).includes(l)?c.add(s):i.push(createSqliteSchemaIssue(`missing-column`,l));continue}let d=t.definition?.columns.get(s),f=r.allowedColumnDefinitions?.[l]??[];d!==void 0&&f.some(e=>Gn(e)===d)?c.add(s):JSON.stringify(u)!==JSON.stringify(n)&&i.push(createSqliteSchemaIssue(`column-definition-drift`,l))}if(n.definition===null){let t=new Set(s.map(e=>e.name));for(let n of a.values())t.has(n.name)||i.push(createSqliteSchemaIssue(`unexpected-column`,`${e}.${n.name}`))}return JSON.stringify(normalizeForeignKeys(t.foreignKeys,c))!==JSON.stringify(normalizeForeignKeys(n.foreignKeys,c))&&i.push(createSqliteSchemaIssue(`table-constraint-drift`,e)),i}function compareTableDefinitions(e,t,n,r,i){let a=[],add=(e,t)=>{a.push(createSqliteSchemaIssue(e,t))};if(!t||!n)return t!==n&&add(`table-definition-drift`,e),a;let s=new Set(r.allowedMissingColumns??[]);for(let[a,s]of t.columns)if(!n.columns.has(a)){let t=`${e}.${a}`;if((r.allowedColumnDefinitions?.[t]??[]).some(e=>Gn(e)===s)||i&&r.allowCompatibleAdditiveColumns&&isCompatibleAdditiveColumnDefinition(s))continue;add(`unexpected-column`,t)}for(let[i,a]of n.columns){let n=`${e}.${i}`,c=t.columns.get(i);c===void 0?s.has(n)||add(`missing-column`,n):c!==a&&((r.allowedColumnDefinitions?.[n]??[]).some(e=>Gn(e)===c)||add(`column-definition-drift`,n))}return JSON.stringify(t.constraints)!==JSON.stringify(n.constraints)&&add(`table-constraint-drift`,e),a}const ru=/* @__PURE__ */ new Set([`ANY`,`BLOB`,`INT`,`INTEGER`,`REAL`,`TEXT`]);function isCompatibleAdditiveColumnDefinition(e){let t=Dn(e,0),n=t?Dn(e,t.end):null;return!!(n?.keyword&&ru.has(n.keyword)&&e.slice(n.end).trim().length===0)}function containsTrigger(e,t){return e.some(e=>e.name===t.name&&e.sql===t.sql)}function readSqliteSchemaCookie(e){return e.prepare(`PRAGMA schema_version`).get()?.schema_version}const iu={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},au=/* @__PURE__ */ new Set;let ou,su,cu;function drain(e){let t=ou?.stop();e&&ou?.start();let n=[];for(let e of t?.statistics??[]){let t=iu[e.gcType];if(!t)continue;let r=e.beforeGC.heapStatistics.usedHeapSize,i={kind:t,reason:`other`,durationMs:e.cost/1e3,heapUsedBeforeBytes:r,reclaimedBytes:Math.max(0,r-e.afterGC.heapStatistics.usedHeapSize)};if(t===`mark_sweep_compact`){i.heapUsedAfterMajorGcBytes=e.afterGC.heapStatistics.usedHeapSize,i.heapUsedAfterMajorGcTimestampSeconds=Date.now()/1e3,cu=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(cu+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of au)e(n)}function observeGcSamples(e){if(!process.versions.bun)return ou?drain(!0):(ou=new di,ou.start(),su=setInterval(()=>drain(!0),1e3).unref()),au.add(e),()=>{if(!au.has(e))return;let t=au.size===1;drain(!t),au.delete(e),t&&(clearInterval(su),su=void 0,ou=void 0,cu=void 0)}}const lu={statement:ei(`openclaw.database.statement`),request:ei(`openclaw.database.request`)},uu=/* @__PURE__ */ new WeakSet;let statementTiming;function attributesSqliteStatements(e){return e.startsWith(`session.transcript.`)||e.startsWith(`sessions.transcript-`)||e.startsWith(`session.metadata.`)||e.startsWith(`trajectory.`)||e.startsWith(`audit.writer.`)||e.startsWith(`knowledge.`)||e===`session.lifecycle.delete`||e===`session context snapshot read`}function startSqliteStatementTiming(e=!1){let t=statementTiming,n,r;if(e)try{r=observeGcSamples(e=>{for(let t of e)n=(n??0)+t.durationMs}),n=r?0:void 0}catch{}let i=/* @__PURE__ */ new Map,a=0,s=0,c=0,l;return statementTiming=(e,t,n)=>{a++,s+=t,(l===void 0||t>c)&&(l=e);let r=i.has(e)||i.size<32?e:``,u=i.get(r)??{count:0,totalMs:0,maxMs:0};i.set(r,u),c=Math.max(c,t),n!==void 0&&(u.rows=(u.rows??0)+n),u.count++,u.totalMs+=t,u.maxMs=Math.max(u.maxMs,t)},()=>{statementTiming=t;try{r?.()}catch{n=void 0}return{totalMs:s,callbackGcMs:n,summarize(){let identity=e=>{let t=normalizeSql(`sqlite`,e);return{id:e?Gr(`sha256`).update(t).digest(`hex`).slice(0,16):`other`,operation:/^(SELECT|INSERT|UPDATE|DELETE|WITH|SAVEPOINT|RELEASE|ROLLBACK)\b/i.exec(t)?.[1]?.toUpperCase()??`OTHER`}};return{count:a,maxMs:c,slowest:l===void 0?void 0:{...identity(l),maxMs:c},statements:[...i].toSorted((e,t)=>t[1].totalMs-e[1].totalMs).slice(0,5).map(([e,t])=>Object.assign(identity(e),t,{totalMs:Math.round(t.totalMs*100)/100,maxMs:Math.round(t.maxMs*100)/100})),omittedGroups:Math.max(0,i.size-5)}}}}}function normalizeSql(e,t){let n=``;for(let r=0;r<t.length;){let i=t.slice(r);if(i.startsWith(`/*`)){let e=1;for(r+=2;r<t.length&&e;)t.startsWith(`/*`,r)?(e++,r+=2):t.startsWith(`*/`,r)?(e--,r+=2):r++;n+=` `;continue}let a=/^--[^\r\n]*/.exec(i)?.[0],s=(e===`postgres`?/^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0]:void 0)??/^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0],c=/^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0],l=/^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0],u=/[\w$]/.test(t[r-1]??``)?void 0:/^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0];if(c){let e=t.indexOf(c,r+c.length);r=e<0?t.length:e+c.length,n+=`?`}else if(a||s||l||u){let e=a??s??l??u??``;r+=e.length,n+=a?` `:l?e:`?`}else n+=t[r++]}return n.replace(/\s+/g,` `).trim()}function observeDatabaseOperation(e,t,n,r,i){let a=lu[t],s=e===`sqlite`&&t===`statement`?statementTiming:void 0;if(!a.hasSubscribers&&!s)return r();let c=performance.now(),l=`error`,u;try{let e=r();return l=`ok`,u=i===`all`&&Array.isArray(e)?e.length:i===`get`?Number(e!==void 0):void 0,e}finally{let t=performance.now()-c;n!==void 0&&s?.(n,t,u),a.hasSubscribers&&a.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId:ii,outcome:l,durationMs:t})}}function observeConnection(e){if(uu.has(e))return e;uu.add(e);let t=e.exec.bind(e),n=e.prepare.bind(e);return e.exec=e=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>t(e)),e.prepare=e=>{let t=n(e);for(let n of[`get`,`all`,`run`]){let r=t[n].bind(t);Object.defineProperty(t,n,{configurable:!0,writable:!0,value:(...t)=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>r(...t),n===`run`?void 0:n)})}let r=t.iterate.bind(t);return t.iterate=(...t)=>{let n=r(...t),i=statementTiming;if(!lu.statement.hasSubscribers&&!i)return n;let a=0,s=0,c=!1,l=!1,finish=t=>{l||(l=!0,c&&(i?.(e,a,s),lu.statement.hasSubscribers&&lu.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:ii,outcome:t,durationMs:a})))},step=e=>{if(l)return e();let t=performance.now();try{let n=e();return a+=performance.now()-t,n.done?finish(`ok`):s++,n}catch(e){throw a+=performance.now()-t,finish(`error`),e}},u={next:(...e)=>(c=!0,step(()=>n.next(...e))),return:e=>step(()=>n.return?.(e)??{done:!0,value:e}),[Symbol.iterator](){return this}};return Object.setPrototypeOf(u,Object.getPrototypeOf(n)),u},t},e}const du=1e3,fu=1e3,pu=Symbol.for(`openclaw.sqliteAbortedTransaction`);function assertTransactionUsable(e){if(C(e))return;let t=e[pu];if(t)throw t.error}const mu=y(`sqlite/transaction`),hu=i(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map),gu=/* @__PURE__ */ new WeakMap;function writeAdmissionLocation(e){let t=gu.get(e);if(t!==void 0)return t;let n=e.location(),r=n===null?null:wt(n);return gu.set(e,r),r}function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(wt))].map(e=>{let n=hu.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),hu.set(e,n),{location:e,services:n,retained}});return()=>{for(let{location:e,services:t,retained:r}of n)t.delete(r),t.size===0&&hu.get(e)===t&&hu.delete(e)}}function execNativeBegin(e,t){let n=Date.now();t.nativeAttempts+=1;try{e.exec(`BEGIN IMMEDIATE`)}finally{t.nativeMs+=Date.now()-n}}function beginImmediateTransaction(e,t){let n=hu.size>0?writeAdmissionLocation(e):null,r=n===null?void 0:hu.get(n);if(!r){execNativeBegin(e,t);return}let i=performance.now()+readSqliteBusyTimeout(e);for(;;)try{runWithSqliteBusyTimeout(e,Math.min(25,Math.max(0,Math.ceil(i-performance.now()))),()=>execNativeBegin(e,t));return}catch(e){if(!It(e)||performance.now()>=i)throw e;for(let e of r){let n=Date.now();t.serviceCalls+=1;try{e()}finally{t.serviceMs+=Date.now()-n}}if(performance.now()>=i)throw e}}function slowBusyWaitThresholdMs(e){return e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0?du:Math.min(du,e.busyTimeoutMs)}function transactionDiagnosticLabels(e,t){let n=t?.databaseLabel;if(!n)try{n=e?e.location()??`:memory:`:`unavailable`}catch{n=`unavailable`}return{database:n,operation:t?.operationLabel||sn()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;let n=t?Tt(t.error):void 0,r=t?ln(t.error):void 0;(e.options?.logger??mu).warn(t?`SQLite transaction lock wait failed`:`slow SQLite transaction step`,{async:!1,...e.options?.busyTimeoutMs===void 0?{}:{busyTimeoutMs:e.options.busyTimeoutMs},...transactionDiagnosticLabels(e.db,e.options),...t?{code:pn(t.error)}:{},elapsedMs:e.elapsedMs,...e.holderAtWaitStart?{holderAtWaitStart:e.holderAtWaitStart}:{},...t?{failureKind:`lock-contention`}:{},isMainThread:ni,pid:process.pid,...n===void 0?{}:{sqliteErrcode:n},...r===void 0?{}:{sqlitePrimaryCode:r},step:e.step,threadId:ii,...e.beginAdmission?{beginAdmission:{...e.beginAdmission}}:{}})}catch{}}function execTimedTransactionStep(e){let t=Date.now(),n=e.sql===`BEGIN IMMEDIATE`?{nativeAttempts:0,nativeMs:0,serviceCalls:0,serviceMs:0}:void 0,r=n?Vt(e.db,t):void 0;try{n?beginImmediateTransaction(e.db,n):e.db.exec(e.sql);let i=Date.now()-t;return logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,holderAtWaitStart:r,options:e.options,step:e.step}),i}catch(i){let a=Date.now()-t;throw It(i)&&shouldReportSqliteLockFailure(e.db)&&(e.step!==`begin`||e.options?.beginLockFailureReporting!==`suppress`)&&logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:a,holderAtWaitStart:r,options:e.options,step:e.step},{error:i}),i}}function discardUnsafeConnection(e,t){let n={error:t};e[pu]??=n;try{zt(e,t)}catch(t){throw e[pu]===n&&(n.error=t),t}finally{clearNodeSqliteKyselyCacheForDatabase(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(!e[pu]){if(!n&&e.isOpen&&!e.isTransaction)zt(e,t,`rolled-back`);else try{e.exec(`ROLLBACK`)}catch{discardUnsafeConnection(e,t)}}}function runSqliteTransactionSync(e,t,n,r){if(e.isTransaction){e.exec(`SAVEPOINT openclaw_tx_nested`);try{let n=runSqliteReadOperationSync(e,t);return Mt(n),assertTransactionUsable(e),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`),n}catch(t){let n=e[pu];if(n)throw n.error;try{e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)}catch{discardUnsafeConnection(e,t)}throw t}}let i=mn(),a=i?Date.now()-i.preparedAtMs:void 0,s=execTimedTransactionStep({db:e,options:r,sql:n===`immediate`?`BEGIN IMMEDIATE`:`BEGIN`,step:`begin`});return i&&(i.transactions.count+=1),settleSqliteTransactionSync(e,t,n,s,a,r)}function settleSqliteTransactionSync(e,t,n,r,i,a,s=!1){let c=mn(),l=Date.now(),u=n===`immediate`?vt(e):void 0;u&&qt(u,a?.operationLabel||sn()?.operation||`unlabeled`,l);let d=c?.hostAdmissionWaitMs??0,f=c?.databaseAdmissionWaitMs??0,p=0,commit=()=>{let t=Date.now(),n=c?.databaseAdmissionWaitMs??0;try{Ht(e),execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{p+=Date.now()-t-((c?.databaseAdmissionWaitMs??0)-n)}},m=!1,h=a?.operationLabel||sn()?.operation,ee=h?.startsWith(`sessions.transcript-hydration.`)===!0,g;try{let n=h&&attributesSqliteStatements(h)?startSqliteStatementTiming(ee):void 0,r;try{r=s?t():runSqliteReadOperationSync(e,t)}finally{g=n?.()}return Mt(r),assertTransactionUsable(e),m=!0,a?.withCommit?Mt(a.withCommit(commit)):commit(),r}catch(t){throw abortImmediateTransaction(e,t,m),assertTransactionUsable(e),t}finally{u&&Atomics.compareExchange(u,1,ii+1,0);try{c?.diskRead&&(c.diskRead.context=a?.diagnosticContext);let t=Date.now()-l,s=(c?.hostAdmissionWaitMs??0)-d,u=(c?.databaseAdmissionWaitMs??0)-f,m=Math.max(0,t-s-u-p);t<(a?.slowTransactionHoldMs??fu)||(a?.logger??mu).warn(`slow SQLite transaction hold`,{async:!1,callbackKind:`application-transaction`,isMainThread:ni,mode:n,pid:process.pid,threadId:ii,...transactionDiagnosticLabels(e,a),...c?.holdContext||ee&&c?.hydrationActiveEvents!==void 0?{context:bt(a?.diagnosticContext,ee)}:{},elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:m,...g?{statementExecutionMs:Math.round(g.totalMs*100)/100,callbackOtherMs:Math.round(Math.max(0,m-g.totalMs)*100)/100,callbackGcMs:g.callbackGcMs===void 0?void 0:Math.round(g.callbackGcMs*100)/100}:{},hostAdmissionWaitMs:s,databaseAdmissionWaitMs:u,commitMs:p},...g?{statementTiming:g.summarize()}:{},thresholdMs:a?.slowTransactionHoldMs??fu})}catch{}finally{c&&(c.preparedAtMs=Date.now(),c.hydrationActiveEvents!==void 0&&(c.hydrationActiveEvents=void 0))}}}function runSqliteDeferredTransactionSync(e,t,n){return C(e)?e.runTransaction(t,n):(assertTransactionUsable(e),yt(e,()=>runSqliteTransactionSync(e,t,`deferred`,n)))}function runSqliteReadSnapshotSync(e,t,n){if(C(e)){if(e.isTransaction){let e=t();return Mt(e),e}return e.runTransaction(t,n,!0)}if(assertTransactionUsable(e),!e.isTransaction)return runSqliteDeferredTransactionSync(e,t,n);let r=runSqliteReadOperationSync(e,t);return Mt(r),assertTransactionUsable(e),r}function runSqliteImmediateTransactionSync(e,t,n){return C(e)?e.runTransaction(t,n):(assertTransactionUsable(e),yt(e,()=>runSqliteTransactionSync(e,t,`immediate`,n)))}function runSqliteSingleStatementSync(e,t){return C(e)?e.runTransaction(t):(assertTransactionUsable(e),yt(e,()=>{let n=hu.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&hu.has(n))return runSqliteTransactionSync(e,t,`immediate`);let r=runSqliteReadOperationSync(e,t);return Mt(r),r}))}function createSqliteSchemaEnsurer(e,t){let present=e=>{let n=getAdmittedSqliteSchemaFacts(e);return n!==void 0&&t.tables.every(e=>n.tables.has(e))&&(t.indexes?.every(e=>n.indexes.has(e))??!0)};return(t,n)=>{C(t)&&requireNativeDatabaseFile(`postgres`,`repair`),runSqliteReadOperationSync(t,()=>{if(present(t))return;let install=t=>t.exec(e());n?n(install):t.isTransaction?install(t):runSqliteImmediateTransactionSync(t,()=>install(t))})}}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function joinValues(e,t=`|`){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}var Cached=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function cached(e){return new Cached(e)}function nullish(e){return e==null}function cleanRegex(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function rawShape(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function sourceShape(e){return rawShape(e._zod.def)??e._zod.def.shape}function deferProp(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return assignProp(this,t,e),e},enumerable:!0,configurable:!0})}function putProp(e,t,n){t in e?assignProp(e,t,n):e[t]=n}function mirrorShape(e,t,n,r){let i=sourceShape(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?deferProp(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):putProp(e,a,r?r(n.value,a):n.value))}}function mirrorProps(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?deferProp(e,n,()=>t[n]):putProp(e,n,r.value))}}function mergeDefs(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const _u=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const vu=/* @__PURE__*/ cached(()=>{if(ku.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject(e){if(isObject(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return isObject(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const yu=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function stringifyPrimitive(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const bu={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},xu={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function pick(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return mirrorShape(i,e,maskedKeys(e,t)),clone(e,mergeDefs(n,{shape:i,checks:[]}))}function maskedKeys(e,t){let n=sourceShape(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function omit(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(maskedKeys(e,t)),a={};return mirrorShape(a,e,Reflect.ownKeys(sourceShape(e)).filter(e=>!i.has(e))),clone(e,mergeDefs(n,{shape:a,checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=sourceShape(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function extended(e,t){let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorProps(n,t),n}function safeExtend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function merge(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorShape(n,t,Reflect.ownKeys(sourceShape(t))),clone(e,mergeDefs(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function partial(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(maskedKeys(t,n)):void 0,s={};return mirrorShape(s,t,Reflect.ownKeys(sourceShape(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),clone(t,mergeDefs(t._zod.def,{shape:s,checks:[]}))}function required(e,t,n){let r=n?new Set(maskedKeys(t,n)):void 0,i={};return mirrorShape(i,t,Reflect.ownKeys(sourceShape(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),clone(t,mergeDefs(t._zod.def,{shape:i}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function explicitlyAborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function sizeCaps(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function attachSchema(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function finalizeIssue(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,s=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(a?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`,c={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(c[t]=e[t]);return c.path??=[],c.message=s,t?.reportInput&&(c.input=e.input),c}const Su=/[\uD800-\uDBFF]/;function codePointLength(e){let t=e.length;if(!Su.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function parsedType(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function issue(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function members(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):defineBound(e,n,r.value)}}function own(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function hide(e,t,n){return own(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
function derived(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return own(this,n,r(this))},set(e){own(this,n,e)}})}return t}function defineBound(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:own(this,t,n.bind(this))},set(e){own(this,t,e)}})}function claim(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Cu,wu=!1;const Tu={configurable:!0,get(){wu=!0}};function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Cu!==e._zod?Cu=void 0:(Cu=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Tu);let e=wu;wu=!1;try{let r=n(this);return wu?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),wu||=e,r}catch(n){throw delete this[t],wu||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function installLazyProp(e,t,n,r){let i=claim(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function constantCatch(e){let fn=()=>e;return fn[`~constantCatch`]=!0,fn}var Eu;const Du={value:void 0,enumerable:!1};let Ou=`captureStackTrace`in Error?Error:null;function newError(e){let t=Ou;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Ou=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
function $constructor(e,t,n,r){let i={};function Internals(e){this.def=e,this.constr=_,this.traits=/* @__PURE__ */ new Set}Internals.prototype=i;let a=n,s=a&&/* @__PURE__ */ new WeakSet;function init(n,r){if(!n._zod){Du.value=new Internals(r);try{Object.defineProperty(n,"_zod",Du)}finally{Du.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),members(i,a))}let i=_.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let c=r?.Parent??Object;class Definition extends c{}Object.defineProperty(Definition,"name",{value:e});function _(e){let t=r?.Parent?newError(Definition):this;init(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(_,"name",{value:e}),_}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Eu=globalThis).__zod_globalConfig??(Eu.__zod_globalConfig={});const ku=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(ku,e),ku}function _getMessage(){let e=this._zod;return e.message??=JSON.stringify(e.def,jsonStringifyReplacer,2),e.message}function _setMessage(e){this._zod.message=e}const Au={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},ju={value:void 0,enumerable:!1},Mu=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Nu=/* @__PURE__ */ $constructor(`$ZodError`,(e,t)=>{e.name=`$ZodError`,ju.value=t,Object.defineProperty(e,"issues",ju),ju.value=void 0,Object.defineProperty(e,"message",Au);let n=Object.getPrototypeOf(e);Mu.has(n)||(Mu.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function node(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function flattenError(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?node(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){let n={_errors:[]},processError=(e,r=[])=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>processError({issues:e},[...r,...i.path]));else if(i.code===`invalid_key`)processError({issues:i.issues},[...r,...i.path]);else if(i.code===`invalid_element`)processError({issues:i.issues},[...r,...i.path]);else{let e=[...r,...i.path];if(e.length===0)n._errors.push(t(i));else{let r=n,a=0;for(;a<e.length;){let n=e[a],s=a===e.length-1;if(n===`_errors`){s&&r._errors.push(t(i)),a++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let c=r[n];s&&c._errors.push(t(i)),r=c,a++}}}};return processError(e),n}function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}const _parse=e=>{let fn=(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){let t=new((i?.Err)??e)(s.issues.map(e=>finalizeIssue(e,a,config())));throw _u(t,i?.callee??fn),t}return s.value};return fn},_parseAsync=e=>{let fn=async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let t=new((i?.Err)??e)(s.issues.map(e=>finalizeIssue(e,a,config())));throw _u(t,i?.callee??fn),t}return s.value};return fn},_safeParse=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}};function failure(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>finalizeIssue(e,n,config()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const _safeParseAsync=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}},Pu=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),Fu=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),validate=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Pu)return!0;if(r.definite===!0&&n===void 0)return!1}return validateFallback(e,t,n)});function validateFallback(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[Fu]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new $ZodAsyncError;return a.issues.length===0}const validateAsync$1=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},_encode=e=>{let t=_parse(e),fn=(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return t(e,n,a,finalizeParams(fn,i))};return fn},_decode=e=>{let t=_parse(e),fn=(e,n,r,i)=>t(e,n,r,finalizeParams(fn,i));return fn},_encodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return await t(e,n,a,finalizeParams(fn,i))};return fn},_decodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>await t(e,n,r,finalizeParams(fn,i));return fn},_safeEncode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)},_safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r),_safeEncodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)},_safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r),Iu=/^[cC][0-9a-z]{6,}$/,Lu=/^[0-9a-z]+$/,Ru=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,zu=/^[0-9a-vA-V]{20}$/,Bu=/^[A-Za-z0-9]{27}$/,Vu=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Hu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Uu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Wu=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function emoji(){return/* @__PURE__ */ RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const Gu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ku=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,qu=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ju=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Yu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xu=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Zu=/^https?$/,Qu=/^\+[1-9]\d{6,14}$/,$u=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function anchor(e){return RegExp(`^${e}$`)}const ed=/*@__PURE__*/ anchor($u);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(e){return RegExp(`^${timeSource(e)}$`)}function datetime(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${timeSource({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${timeSource({precision:e.precision})}`:n;return RegExp(`^${$u}T(?:${r})$`)}const td=/^[\s\S]{0,}$/,nd=/^-?\d+$/,rd=/^-?\d+(?:\.\d+)?$/,id=/^(?:true|false)$/i,ad=/^[^A-Z]*$/,od=/^[^a-z]*$/,K=/*@__PURE__*/ $constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_whenHasLength=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0},sd={number:`number`,bigint:`bigint`,object:`date`},cd=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{K.init(e,t);let n=sd[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:sd[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ld=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{K.init(e,t);let n=sd[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:sd[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ud=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{K.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),dd=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{K.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=bu[t.format];e._zod.check=s=>{let c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:c,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}c<i&&s.issues.push({origin:`number`,input:c,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>a&&s.issues.push({origin:`number`,input:c,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),fd=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;K.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?codePointLength(r):i)<=t.maximum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),pd=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;K.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?codePointLength(r):i)>=t.minimum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),md=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;K.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?codePointLength(r):i;if(a===t.length)return;let s=getLengthableOrigin(r),c=a>t.length;n.issues.push({origin:s,...c?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),hd=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;K.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),gd=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{hd.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),_d=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=ad,hd.init(e,t)}),vd=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=od,hd.init(e,t)}),yd=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{K.init(e,t);let n=escapeRegex(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),bd=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{K.init(e,t);let n=RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),xd=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{K.init(e,t);let n=RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Sd=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{K.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Doc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
`)}\n};`)(...Object.values(this.closed))}};const Cd={major:4,minor:6,patch:7},q=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cd;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let runChecks=(t,n,r)=>{if(t.memo)return t;let i=aborted(t),a;for(let s of n){if(s._zod.def.when){if(explicitlyAborted(t)||!s._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,c=s._zod.check(t);if(c instanceof Promise&&r?.async===!1)throw new $ZodAsyncError;if(a||c instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await c,t.issues.length!==n&&(attachSchema(t.issues,n,e),i||=aborted(t,n))});else{if(t.issues.length===n)continue;attachSchema(t.issues,n,e),i||=aborted(t,n)}}return a?a.then(()=>t):t},handleCanaryResult=(t,n,r)=>{if(aborted(t))return t.aborted=!0,t;let a=runChecks(n,i,r);if(a instanceof Promise){if(r.async===!1)throw new $ZodAsyncError;return a.then(t=>e._zod.parse(t,r))}return e._zod.parse(a,r)};e._zod.run=(t,n)=>{if(n.skipChecks)return e._zod.parse(t,n);if(n.direction===`backward`){let r=e._zod.parse({value:t.value,issues:[]},{...n,skipChecks:!0});return r instanceof Promise?r.then(e=>handleCanaryResult(e,t,n)):handleCanaryResult(r,t,n)}let r=e._zod.parse(t,n);if(r instanceof Promise){if(n.async===!1)throw new $ZodAsyncError;return r.then(e=>runChecks(e,i,n))}return runChecks(r,i,n)}}},{get"~standard"(){return hide(this,`~standard`,standardProps(this))},set"~standard"(e){own(this,`~standard`,e)}}),toStandardResult=(e,t)=>e.issues.length?{issues:e.issues.map(e=>finalizeIssue(e,t,config()))}:{value:e.value};async function validateAsync(e,t){let n={async:!0};return toStandardResult(await e._zod.run({value:t,issues:[]},n),n)}function standardProps(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return toStandardResult(r,n)}catch{}return validateAsync(e,t)},vendor:`zod`,version:1}}const wd=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{q.init(e,t),e._zod.pattern=t.pattern??td,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),J=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{hd.init(e,t),wd.init(e,t)}),Td=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??=Uu,J.init(e,t)}),Ed=/*@__PURE__*/ $constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();J.init(e,t)}),Dd=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??=Wu,J.init(e,t)});function canParseURL(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function validateURL(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?canParseURL(e)||2:parseURLObject(e,t)}function parseURLObject(e,t){if(!t.normalize&&t.protocol?.source===Zu.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const Od=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(Od,``)}function urlHostnameOk(e,t){return t.lastIndex=0,t.test(e.hostname)}function urlProtocolOk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const kd=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{J.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=validateURL(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=stripTabAndNewline(r);return}t.hostname&&!urlHostnameOk(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!urlProtocolOk(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:stripTabAndNewline(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Ad=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),J.init(e,t)}),jd=/*@__PURE__*/ $constructor(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Vu:nanoidOfLength(t.length),J.init(e,t)}),Md=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??=Iu,J.init(e,t)}),Nd=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=Lu,J.init(e,t)}),Pd=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??=Ru,J.init(e,t)}),Fd=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??=zu,J.init(e,t)}),Id=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=Bu,J.init(e,t)}),Ld=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),J.init(e,t)}),Rd=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??=ed,J.init(e,t)}),zd=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),J.init(e,t)}),Bd=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=Hu,J.init(e,t)}),Vd=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=Gu,J.init(e,t)}),Hd=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){return Hd.test(e)?canParseURL(`http://[${e}]`):!1}const Ud=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=Ku,J.init(e,t),e._zod.check=n=>{isValidIPv6(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Wd=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=qu,J.init(e,t)});function isValidCIDRv6(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:isValidIPv6(n)}const Gd=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Ju,J.init(e,t),e._zod.check=n=>{isValidCIDRv6(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Kd=/^[0-9a-zA-Z+/]*={0,2}$/,qd=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??=Kd,J.init(e,t),e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Jd=/^[A-Za-z0-9_-]*$/;function isValidBase64URL(e){if(!Jd.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Yd=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=Jd,J.init(e,t),e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Xd=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??=Qu,J.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Zd=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{J.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Qd=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{q.init(e,t),e._zod.pattern=rd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),$d=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{dd.init(e,t),Qd.init(e,t)}),ef=/*@__PURE__*/ $constructor(`$ZodBoolean`,(e,t)=>{q.init(e,t),e._zod.pattern=id,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),tf=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{q.init(e,t),e._zod.parse=e=>e}),nf=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{q.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function capSize(e,t){let n=sizeCaps(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let s=t(n.value);if(s>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of sizeCaps(e._zod.def.checks))if(s>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,attachSchema(n.issues,t,e),n}}return i(n,a)}}const arraySize=e=>Array.isArray(e)?e.length:-1;function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}const rf=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{q.init(e,t);let n=ku.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let s=[],c=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],l=t.element._zod.run({value:n,issues:[]},i);if(l instanceof Promise)s.push(l.then(t=>handleArrayResult(t,r,e)));else if(handleArrayResult(l,r,e),c&&l.issues.length!==0&&aborted(l))break}return s.length?Promise.all(s).then(()=>r):r},capSize(e,arraySize)});function handlePropertyResult(e,t,n,r,i,a){let s=n in r,c=a===`optional`;if(s||!c||i!==`optional`){if(e.issues.length){if(i!==void 0&&c&&!s)return;t.issues.push(...prefixIssues(n,e.issues))}!s&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(s||i===`defaulted`&&!c)&&(t.value[n]=void 0):t.value[n]=e.value}}const af=[];function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:af,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=optionalKeys(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function handleCatchall(e,t,n,r,i,a,s){let c=[],l=i.keySet,u=i.catchall._zod,d=u.def.type,f=u.optin,p=u.optout,m=0;for(let i in t){if(s&&n.issues.length!==m){if(aborted(n,m))break;m=n.issues.length}if(l.has(i))continue;if(i===`__proto__`){d===`never`&&c.push(i);continue}if(d===`never`){c.push(i);continue}let a=u.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,f,p))):handlePropertyResult(a,n,i,t,f,p)}return c.length&&n.issues.push({code:`unrecognized_keys`,keys:c,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const of=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{q.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let get=()=>{let e={...r};return Object.defineProperty(t,"shape",{value:e}),get.raw=e,e};get.raw=r,Object.defineProperty(t,"shape",{get})}let i=cached(()=>normalizeDef(t));defineLazyInternal(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||assignProp(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=isObject,s=t.catchall,c,l=ku.memoizer;l?.attach(e),e._zod.parse=(t,n)=>{c??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=l?l.alloc(e,t,{},n):{};let u=[],d=c.shape,f=n?.abortEarly,p=t.issues.length;for(let e of c.allKeys){if(f&&t.issues.length!==p){if(aborted(t,p))break;p=t.issues.length}if(e===`__proto__`)continue;let i=d[e],a=i._zod.optin,s=i._zod.optout,c=i._zod.run({value:r[e],issues:[]},n);c instanceof Promise?u.push(c.then(n=>handlePropertyResult(n,t,e,r,a,s))):handlePropertyResult(c,t,e,r,a,s)}return s?handleCatchall(u,r,t,n,i.value,e,f===!0):u.length?Promise.all(u).then(()=>t):t}}),sf=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{of.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=ku.memoizer,generateFastpass=t=>{let n=r.value,a=n.symbolKeys,s=new Doc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),parseStr=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,prefixStr=(e,t)=>`
          let ${e}_ab = false;
          for (let i = 0; i < ${e}.issues.length; i++) {
            const iss = ${e}.issues[i];
            iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
            payload.issues.push(iss);
            if (iss.continue !== true) ${e}_ab = true;
          }
          if (${e}_ab && ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }`;s.write(`const input = payload.value;`);let c=Object.create(null),l=0;for(let e of n.allKeys)c[e]=`key_${l++}`;s.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=c[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:esc(e),i=`${r} in input`,l=t[e],u=l?._zod?.optin,d=u!==void 0,f=l?._zod?.optout===`optional`;if(s.write(`const ${n} = ${parseStr(r)};`),d&&f){let e=u===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;s.write(`
        const ${n}_present = ${i};
        if (!${n}.issues.length || ${n}_present) {
          if (${n}.issues.length) {${prefixStr(n,r)}
          }

          if (${e}) {
            newResult[${r}] = ${n}.value;
          }
        }

      `)}else d?(s.write(`
        if (${n}.issues.length) {${prefixStr(n,r)}
        }
      `),u===`defaulted`?s.write(`newResult[${r}] = ${n}.value;`):s.write(`
        if (${n}.value !== undefined || ${i}) {
          newResult[${r}] = ${n}.value;
        }
      `)):s.write(`
        const ${n}_present = ${i};
        if (${n}.issues.length) {${prefixStr(n,r)}
        }
        if (!${n}_present && !${n}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${r}]
          });
          if (ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }
        }

        if (${n}_present) {
          newResult[${r}] = ${n}.value;
        }

      `)}return s.write(`payload.value = newResult;`),s.write(`return payload;`),s.compile()},a,s=isObject,c=!ku.jitless,l=c&&vu.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(a||=generateFastpass(t.shape),i=a(i,f),u?handleCatchall([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function handleUnionResults(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!aborted(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,r,config())))}),t)}const cf=/*@__PURE__*/ $constructor(`$ZodUnion`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),defineLazyInternal(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazyInternal(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazyInternal(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,s=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)s.push(t),a=!0;else{if(t.issues.length===0)return t;s.push(t)}}return a?Promise.all(s).then(t=>handleUnionResults(t,r,e,i)):handleUnionResults(s,r,e,i)}});function discriminatorMap(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}const lf=/*@__PURE__*/ $constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,cf.init(e,t);let n=e._zod.parse;defineLazyInternal(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||assignProp(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=rawShape(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=cached(()=>discriminatorMap(t));e._zod.parse=(i,a)=>{let s=i.value;if(!isObject(s))return i.issues.push({code:`invalid_type`,expected:`object`,input:s,inst:e}),i;let c=s?.[t.discriminator],l=r.value.get(c);return l&&(c!==void 0||a.direction!==`backward`)?l._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:s,path:[t.discriminator],inst:e}),i)}}),uf=/*@__PURE__*/ $constructor(`$ZodIntersection`,(e,t)=>{q.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>handleIntersectionResults(e,t,n)):handleIntersectionResults(e,i,a)}});function mergeValues(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],s=mergeValues(i,a);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,collect=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)collect(n,`l`)||e.issues.push(n);for(let t of n.issues)collect(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=mergeValues(t.value,n.value);if(!c.valid){if(aborted(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const df=/*@__PURE__*/ $constructor(`$ZodRecord`,(e,t)=>{q.init(e,t);let n=ku.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!isPlainObject(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let s=[],c=t.keyType._zod.values;if(c&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let l=/* @__PURE__ */ new Set;for(let n of c)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(l.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let c=t.keyType._zod.run({value:n,issues:[]},i);if(c instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(c.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:c.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}let u=c.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?s.push(d.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...prefixIssues(n,d.issues)),r.value[u]=d.value)}let u;for(let e in a)if(!l.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else u??=[],u.push(e)}u&&u.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:u,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let l;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let u=t.keyType._zod.run({value:n,issues:[]},i);if(u instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&rd.test(n)&&u.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(u=e)}if(u.issues.length){t.mode===`loose`?r.value[n]=a[n]:c?(l??=[],l.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:u.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}let d=u.value;if(d===`__proto__`)continue;let f=t.valueType._zod.run({value:a[n],issues:[]},i);f instanceof Promise?s.push(f.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(n,e.issues)),r.value[d]=e.value})):(f.issues.length&&r.issues.push(...prefixIssues(n,f.issues)),r.value[d]=f.value)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}}),ff=/*@__PURE__*/ $constructor(`$ZodEnum`,(e,t)=>{q.init(e,t);let n=getEnumValues(t.entries),r=new Set(n);e._zod.values=r,defineLazyInternal(e,`pattern`,e=>{let t=getEnumValues(e.def.entries).filter(e=>yu.has(typeof e));return RegExp(t.length?`^(${t.map(e=>escapeRegex(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),pf=/*@__PURE__*/ $constructor(`$ZodLiteral`,(e,t)=>{q.init(e,t);let n=new Set(t.values);e._zod.values=n,defineLazyInternal(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?escapeRegex(e):e?escapeRegex(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),mf=/*@__PURE__*/ $constructor(`$ZodTransform`,(e,t)=>{q.init(e,t),e._zod.optin=`optional`,ku.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new $ZodAsyncError;return n.value=i,n}});function handleOptionalResult(e,t){return e.value=t.issues.length?void 0:t.value,e}const hf=/*@__PURE__*/ $constructor(`$ZodOptional`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>handleOptionalResult(e,t)):handleOptionalResult(e,r)}return t.innerType._zod.run(e,n)}}),gf=/*@__PURE__*/ $constructor(`$ZodExactOptional`,(e,t)=>{hf.init(e,t),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),_f=/*@__PURE__*/ $constructor(`$ZodNullable`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0}),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),vf=/*@__PURE__*/ $constructor(`$ZodDefault`,(e,t)=>{q.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>handleDefaultResult(e,t)):handleDefaultResult(r,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const yf=/*@__PURE__*/ $constructor(`$ZodPrefault`,(e,t)=>{q.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),bf=/*@__PURE__*/ $constructor(`$ZodNonOptional`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function handleCatchResult(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const xf=/*@__PURE__*/ $constructor(`$ZodCatch`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>handleCatchResult(e,r,t,n)):handleCatchResult(e,r,t,n)}}),Sf=/*@__PURE__*/ $constructor(`$ZodPipe`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`values`,e=>e.def.in._zod.values),defineLazyInternal(e,`optin`,e=>e.def.in._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.out._zod.optout),defineLazyInternal(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.in,n)):handlePipeResult(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.out,n)):handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Cf=/*@__PURE__*/ $constructor(`$ZodReadonly`,(e,t)=>{q.init(e,t),defineLazyInternal(e,`propValues`,e=>e.def.innerType._zod.propValues),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`optin`,e=>e.def.innerType?._zod?.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(handleReadonlyResult):handleReadonlyResult(r)}});function handleReadonlyResult(e){return e.memo||(e.value=Object.freeze(e.value)),e}const wf=/*@__PURE__*/ $constructor(`$ZodCustom`,(e,t)=>{K.init(e,t),q.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,n,r,e));handleRefineResult(i,n,r,e)}});function handleRefineResult(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(issue(e))}}var $ZodCyclicError=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Tf=`~memo`,Ef=[];function isRef(e){return typeof e==`object`&&!!e}function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Df=/*@__PURE__*/ new WeakMap;function isRecursive(e,t,n){let r=Df.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,check=e=>{if(i!==2&&e?._zod){let r=isRecursive(e,t,n);r>i&&(i=r)}},shape=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,a);if(r&&!s.enumerable)continue;let c=s.get?1:s.value?._zod?isRecursive(s.value,t,n):0;c>i&&(i=c)}return i},merge=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case`object`:{let e=rawShape(a);merge(e?shape(e,!0):1),check(a.catchall);break}case`array`:check(a.element);break;case`tuple`:for(let e of a.items)check(e);check(a.rest);break;case`record`:case`map`:check(a.keyType),check(a.valueType);break;case`set`:check(a.valueType);break;case`union`:for(let e of a.options)check(e);break;case`intersection`:check(a.left),check(a.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:check(a.innerType);break;case`pipe`:check(a.in),check(a.out);break;case`function`:check(a.input),check(a.output);break;case`lazy`:{let r=a._cachedInner??(n?e._zod.innerType:void 0);merge(r?isRecursive(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in a){let t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)check(n);else if(Array.isArray(n))for(let e of n)check(e)}}}return t.delete(e),settle(e,i)}function settle(e,t){return t!==1&&Df.set(e,t===2),t}function bucketFor(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let Of;const kf=[],Af={alloc(e,t,n){let r=Of;if(!r)return n;Of=void 0;let i={value:n,issues:null};return r.set(t.value,i),kf.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,wrapped=(e,n)=>{if(n.direction!==`backward`&&isBackEdge(n,e.value))throw new $ZodCyclicError;return t(e,n)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,wrapped=(s,c)=>{if(n===void 0){let i=isRecursive(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===wrapped&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!isRef(l))return t(s,c);let u=c[Tf];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[Tf]=u);let d;i===c?d=a:(d=bucketFor(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...cloneIssues(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;Of=d;let p=kf.length,m=t(s,c);Of=void 0;let h=kf.length>p?kf.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?cloneIssues(e.issues):Ef),e)):(h&&(h.issues=m.issues.length?cloneIssues(m.issues):Ef),m)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})}};function memoizer(){return Af}function isBackEdge(e,t){let n=e[Tf]?.backEdges;return n!==void 0&&isRef(t)&&n.has(t)}const error=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function getSizing(t){return e[t]??null}let t={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},n={nan:`NaN`};function getTypeName(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):n[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${getTypeName(e.expected)}, received ${getTypeName(parsedType(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${joinValues(e.values,`|`)}`;case`too_big`:{let t=e.exact?`exactly `:e.inclusive?`<=`:`<`,n=getSizing(e.origin);return n?`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${n.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{let t=e.exact?`exactly `:e.inclusive?`>=`:`>`,n=getSizing(e.origin);return n?`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{let n=e;return n.format===`starts_with`?`Invalid string: must start with "${n.prefix}"`:n.format===`ends_with`?`Invalid string: must end with "${n.suffix}"`:n.format===`includes`?`Invalid string: must include "${n.includes}"`:n.format===`regex`?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${t[n.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${joinValues(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function en_default(){return{localeError:error()}}var jf,$ZodRegistry=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry(){return new $ZodRegistry}(jf=globalThis).__zod_globalRegistry??(jf.__zod_globalRegistry=registry());const Mf=globalThis.__zod_globalRegistry;function snapshotChecks(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
function _string(e,t){return new e(snapshotChecks({type:`string`,...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _number(e,t){return new e(snapshotChecks({type:`number`,checks:[],...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _unknown(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _lt(e,t){return new cd({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _lte(e,t){return new cd({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _gt(e,t){return new ld({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _gte(e,t){return new ld({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _multipleOf(e,t){return new ud({check:`multiple_of`,...normalizeParams(t),value:e})}// @__NO_SIDE_EFFECTS__
function _maxLength(e,t){return new fd({check:`max_length`,...normalizeParams(t),maximum:e})}// @__NO_SIDE_EFFECTS__
function _minLength(e,t){return new pd({check:`min_length`,...normalizeParams(t),minimum:e})}// @__NO_SIDE_EFFECTS__
function _length(e,t){return new md({check:`length_equals`,...normalizeParams(t),length:e})}// @__NO_SIDE_EFFECTS__
function _regex(e,t){return new gd({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}// @__NO_SIDE_EFFECTS__
function _lowercase(e){return new _d({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _uppercase(e){return new vd({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _includes(e,t){return new yd({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}// @__NO_SIDE_EFFECTS__
function _startsWith(e,t){return new bd({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}// @__NO_SIDE_EFFECTS__
function _endsWith(e,t){return new xd({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}// @__NO_SIDE_EFFECTS__
function _overwrite(e){return new Sd({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
function _normalize(e){return/* @__PURE__ */ _overwrite(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
function _trim(){return/* @__PURE__ */ _overwrite(e=>e.trim())}// @__NO_SIDE_EFFECTS__
function _toLowerCase(){return/* @__PURE__ */ _overwrite(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
function _toUpperCase(){return/* @__PURE__ */ _overwrite(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
function _slugify(){return/* @__PURE__ */ _overwrite(e=>slugify(e))}// @__NO_SIDE_EFFECTS__
function _array(e,t,n){return new e({type:`array`,element:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _custom(e,t,n){let r=normalizeParams(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
function _refine(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _superRefine(e,t){let n=/* @__PURE__ */ _check(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(issue(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(issue(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
function _check(e,t){let n=new K({check:`custom`,...normalizeParams(t)});return n._zod.check=e,n}function assignProps(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&assignProp(e,t,n[t]);return e}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Mf,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function handleUnrepresentable(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function processSchema(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{let n=s.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(s.ref||=a,processSchema(a,t,r),t.seen.get(a).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&assignProps(s.schema,l),t.io===`input`&&isTransforming(e)&&(delete s.schema.examples,delete s.schema.default),t.io===`input`&&`_prefault`in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function encodeJSONPointerSegment(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function extractDefs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let makeURI=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${encodeJSONPointerSegment(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+encodeJSONPointerSegment(a)}},extractToDef=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=makeURI(e);t.def={...t.schema},r&&(t.defId=r);let i=t.schema;for(let e in i)delete i[e];i.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])extractToDef(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){extractToDef(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&extractToDef(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function compactTypeUnion(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;compactTypeUnion(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const Nf=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Pf=[`oneOf`,`anyOf`];function undeclaredConstraint(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function foldObjects(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Nf.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??undeclaredConstraint(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}assignProp(n,r,e.length===1?e[0]:foldObjects(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=undeclaredConstraint(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function foldIntersection(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Nf)if(t in e)return;let n=t.filter(e=>Pf.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=Pf.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),s=e[i].map(e=>foldObjects([...a,e]));if(s.some(e=>!e))return;r={[i]:s}}r&&(delete e.allOf,assignProps(e,r))}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let flattenRef=t=>{let n=e.seen.get(t);if(n.ref===null)return;let r=n.def??n.schema,i={...r},a=n.ref;if(n.ref=null,a){flattenRef(a);let n=e.seen.get(a),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(r.allOf=r.allOf??[],r.allOf.push(s)):assignProps(r,s),assignProps(r,i),t._zod.parent===a)for(let e in r)e!==`$ref`&&e!==`allOf`&&(e in i||delete r[e]);if(s.$ref&&n.def)for(let e in r)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}let s=t._zod.parent;if(s&&s!==a){flattenRef(s);let t=e.seen.get(s);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(let e in r)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())flattenRef(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())compactTypeUnion(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])foldIntersection(e)}}let r={};if(e.target===`draft-2020-12`?r.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?r.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?r.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}assignProps(r,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,assignProp(a,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?r.$defs=a:r.definitions=a);try{let n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}const createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return processSchema(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},s=initializeContext({...i??{},target:a,io:t,processors:n});return processSchema(e,s),extractDefs(s,e),finalize(s,e)},narrowMin=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},narrowMax=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},narrowBoth=(e,t)=>{narrowMin(e,`minimum`,t),narrowMax(e,`maximum`,t)},addDivisor=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},addPattern=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},intersectMime=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},setFormat=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},minContributor=(e,t)=>narrowMin(e,`minimum`,t.minimum),maxContributor=(e,t)=>narrowMax(e,`maximum`,t.maximum),formatContributor=e=>(t,n)=>{setFormat(t,n.format);let[r,i]=e[n.format];narrowMin(t,`minimum`,r),narrowMax(t,`maximum`,i)},Ff={greater_than:(e,t)=>narrowMin(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>narrowMax(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>addDivisor(e,t.value),number_format:formatContributor(bu),bigint_format:formatContributor(xu),min_length:minContributor,max_length:maxContributor,length_equals:(e,t)=>narrowBoth(e,t.length),min_size:minContributor,max_size:maxContributor,size_equals:(e,t)=>narrowBoth(e,t.size),string_format:(e,t)=>{setFormat(e,t.format),t.pattern&&addPattern(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>intersectMime(e,t.mime)};function aggregateChecks(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ff[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&narrowMin(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&narrowMin(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&narrowMax(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&narrowMax(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&addDivisor(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&intersectMime(t,i.mime);for(let e of i.patterns??[])addPattern(t,e);return t}const If={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Lf=/* @__PURE__ */ new Map([[Kd,Yu],[Jd,Xu]]),exactPattern=e=>Lf.get(e)??e,stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:s,format:c,patterns:l,contentEncoding:u,laxFormat:d}=aggregateChecks(e);if(typeof a==`number`&&(i.minLength=a),typeof s==`number`&&(i.maxLength=s),c&&(i.format=If[c]??c,i.format===``&&delete i.format,(c===`time`||d)&&delete i.format),u&&(i.contentEncoding=u),l&&l.size>0){let e=[...l].map(exactPattern);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u,isInt:d}=aggregateChecks(e);i.type=d?`integer`:`number`;let f=typeof u==`number`&&u>=(a??-1/0),p=typeof l==`number`&&l<=(s??1/0),m=t.target===`draft-04`||t.target===`openapi-3.0`;if(f?m?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),p?m?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof s==`number`&&(i.maximum=s),c){let n=/* @__PURE__ */ new Set;for(let a of c)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):handleUnrepresentable(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...s]=n;a!==void 0&&(i.multipleOf=a),s.length&&(i.allOf=[...i.allOf??[],...s.map(e=>({multipleOf:e}))])}},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},neverProcessor=(e,t,n,r)=>{n.not={}},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},literalProcessor=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let s of i.values)if(s===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(s))}else a.push(s);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},customProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:s,maximum:c}=aggregateChecks(e);typeof s==`number`&&(i.minItems=s),typeof c==`number`&&(i.maxItems=c),i.type=`array`,i.items=processSchema(a.element,t,{...r,path:[...r.path,`items`]})};function inputOptin(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?inputOptin(t.out):t.type===`catch`?inputOptin(t.innerType):e._zod.optin}const objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,s=a.shape;if(Object.getOwnPropertySymbols(s).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in s)assignProp(i.properties,e,processSchema(s[e],t,{...r,path:[...r.path,`properties`,e]}));let c=[];for(let e of Object.keys(s)){let n=a.shape[e];(t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0)&&c.push(e)}c.length>0&&(i.required=c),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=processSchema(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,s=i.options.map((e,n)=>processSchema(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=s:n.anyOf=s},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.left,t,{...r,path:[...r.path,`allOf`,0]}),s=processSchema(i.right,t,{...r,path:[...r.path,`allOf`,1]}),isSimpleIntersection=e=>`allOf`in e&&Object.keys(e).length===1,c=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(s)?s.allOf:[s]];n.allOf=c,t.intersections.push(c)};function stringifyKeyNames(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=stringifyKeyNames(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>stringifyKeyNames(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:s,maximum:c,exclusiveMinimum:l,exclusiveMaximum:u,multipleOf:d,format:f,id:p,...m}=t;return m.enum?m.enum=m.enum.map(e=>typeof e==`number`?String(e):e):typeof m.const==`number`&&(m.const=String(m.const)),i&&(m.type=`string`,a||(m.pattern=(r.includes(`number`)?rd:nd).source)),m}const Rf=/* @__PURE__ */ new WeakMap;function rewriteKeyNames(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of Rf.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let s=stringifyKeyNames(t,a,/* @__PURE__ */ new Set);s!==a&&n.set(a,s)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let s=a.keyType,c=aggregateChecks(s).patterns;if(a.mode===`loose`&&c&&c.size>0){let e=processSchema(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of c)assignProp(i.patternProperties,exactPattern(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=processSchema(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Rf.get(t);n||(n=[],Rf.set(t,n),t.deferred.push(()=>rewriteKeyNames(t))),n.push(e)}i.additionalProperties=processSchema(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let l=s._zod.values,u=t.io===`input`&&inputOptin(a.valueType)!==void 0;if(l&&!a.partial&&!u){let e=[...l].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.innerType,t,r),s=t.seen.get(e);t.target===`openapi-3.0`?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},zf=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=!1,s=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(handleUnrepresentable(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),zf):JSON.parse(s)}const defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let s=serializeDefaultValue(i.defaultValue,e,t,n,r);s!==zf&&(n.default=s)},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let s=serializeDefaultValue(i.defaultValue,e,t,n,r);s!==zf&&(n._prefault=s)},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=s},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),s=t.io===`input`?a?i.out:i.in:i.out;processSchema(s,t,r);let c=t.seen.get(e);c.ref=s},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Bf=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const Vf=/*@__PURE__*/ $constructor(`ZodError`,(e,t)=>{Nu.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Bf.has(n)||(Bf.add(n),_lazyMethod(n,`format`,e=>t=>formatError(e,t)),_lazyMethod(n,`flatten`,e=>t=>flattenError(e,t)),_lazyMethod(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),_lazyMethod(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Hf=/* @__PURE__ */ _parse(Vf),Uf=/* @__PURE__ */ _parseAsync(Vf),Wf=/* @__PURE__ */ _safeParse(Vf),Gf=/* @__PURE__ */ _safeParseAsync(Vf),Kf=/* @__PURE__ */ _encode(Vf),qf=/* @__PURE__ */ _decode(Vf),Jf=/* @__PURE__ */ _encodeAsync(Vf),Yf=/* @__PURE__ */ _decodeAsync(Vf),Xf=/* @__PURE__ */ _safeEncode(Vf),Zf=/* @__PURE__ */ _safeDecode(Vf),Qf=/* @__PURE__ */ _safeEncodeAsync(Vf),$f=/* @__PURE__ */ _safeDecodeAsync(Vf);function _ensureDefaultLocale(){ku.localeError||config(en_default())}function _ensureDefaultMemoizer(){ku.memoizer||config({memoizer:memoizer()})}const Y=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),q.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(/* @__PURE__ */ _overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return Mf.add(t,{description:e}),t},meta(...e){if(e.length===0)return Mf.get(this);let t=this.clone();return Mf.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return hide(this,`~standard`,{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,`input`),output:createStandardJSONSchemaMethod(this,`output`)}})},set"~standard"(e){own(this,`~standard`,e)},parse:function _parse(e,t){return Hf(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await Uf(this,e,t,{callee:_parseAsync})},safeParse(e,t){return Wf(this,e,t)},async safeParseAsync(e,t){return Gf(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){own(this,`spa`,e)},validate(e,t){return validate(this,e,t)},validateAsync(e,t){return validateAsync$1(this,e,t)},encode:function _encode(e,t){return Kf(this,e,t,{callee:_encode})},decode:function _decode(e,t){return qf(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await Jf(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await Yf(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return Xf(this,e,t)},safeDecode(e,t){return Zf(this,e,t)},async safeEncodeAsync(e,t){return Qf(this,e,t)},async safeDecodeAsync(e,t){return $f(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return Mf.get(this)?.description},get _def(){return this._zod.def}}),ep=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{wd.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r)},/*@__PURE__*/ derived({format:e=>aggregateChecks(e).format??null,minLength:e=>aggregateChecks(e).minimum??null,maxLength:e=>aggregateChecks(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ _regex(...e))},includes(...e){return this.check(/* @__PURE__ */ _includes(...e))},startsWith(...e){return this.check(/* @__PURE__ */ _startsWith(...e))},endsWith(...e){return this.check(/* @__PURE__ */ _endsWith(...e))},min(...e){return this.check(/* @__PURE__ */ _minLength(...e))},max(...e){return this.check(/* @__PURE__ */ _maxLength(...e))},length(...e){return this.check(/* @__PURE__ */ _length(...e))},nonempty(...e){return this.check(/* @__PURE__ */ _minLength(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ _lowercase(e))},uppercase(e){return this.check(/* @__PURE__ */ _uppercase(e))},trim(){return this.check(/* @__PURE__ */ _trim())},normalize(...e){return this.check(/* @__PURE__ */ _normalize(...e))},toLowerCase(){return this.check(/* @__PURE__ */ _toLowerCase())},toUpperCase(){return this.check(/* @__PURE__ */ _toUpperCase())},slugify(){return this.check(/* @__PURE__ */ _slugify())}})),tp=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{wd.init(e,t),ep.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _email(op,e))},url(e){return this.check(/* @__PURE__ */ _url(lp,e))},jwt(e){return this.check(/* @__PURE__ */ _jwt(wp,e))},emoji(e){return this.check(/* @__PURE__ */ _emoji(up,e))},guid(e){return this.check(/* @__PURE__ */ _guid(sp,e))},uuid(e){return this.check(/* @__PURE__ */ _uuid(cp,e))},uuidv4(e){return this.check(/* @__PURE__ */ _uuidv4(cp,e))},uuidv6(e){return this.check(/* @__PURE__ */ _uuidv6(cp,e))},uuidv7(e){return this.check(/* @__PURE__ */ _uuidv7(cp,e))},nanoid(e){return this.check(/* @__PURE__ */ _nanoid(dp,e))},cuid(e){return this.check(/* @__PURE__ */ _cuid(fp,e))},cuid2(e){return this.check(/* @__PURE__ */ _cuid2(pp,e))},ulid(e){return this.check(/* @__PURE__ */ _ulid(mp,e))},base64(e){return this.check(/* @__PURE__ */ _base64(xp,e))},base64url(e){return this.check(/* @__PURE__ */ _base64url(Sp,e))},xid(e){return this.check(/* @__PURE__ */ _xid(hp,e))},ksuid(e){return this.check(/* @__PURE__ */ _ksuid(gp,e))},ipv4(e){return this.check(/* @__PURE__ */ _ipv4(_p,e))},ipv6(e){return this.check(/* @__PURE__ */ _ipv6(vp,e))},cidrv4(e){return this.check(/* @__PURE__ */ _cidrv4(yp,e))},cidrv6(e){return this.check(/* @__PURE__ */ _cidrv6(bp,e))},e164(e){return this.check(/* @__PURE__ */ _e164(Cp,e))},datetime(e){return this.check(/* @__PURE__ */ _isoDateTime(np,e))},date(e){return this.check(/* @__PURE__ */ _isoDate(rp,e))},time(e){return this.check(/* @__PURE__ */ _isoTime(ip,e))},duration(e){return this.check(/* @__PURE__ */ _isoDuration(ap,e))}});function string(e){return/* @__PURE__ */ _string(tp,e)}const X=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{J.init(e,t),ep.init(e,t)}),np=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{Ld.init(e,t),X.init(e,t)}),rp=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{Rd.init(e,t),X.init(e,t)}),ip=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{zd.init(e,t),X.init(e,t)}),ap=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{Bd.init(e,t),X.init(e,t)}),op=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{Dd.init(e,t),X.init(e,t)}),sp=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{Td.init(e,t),X.init(e,t)}),cp=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{Ed.init(e,t),X.init(e,t)}),lp=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{kd.init(e,t),X.init(e,t)}),up=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{Ad.init(e,t),X.init(e,t)}),dp=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{jd.init(e,t),X.init(e,t)}),fp=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{Md.init(e,t),X.init(e,t)}),pp=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{Nd.init(e,t),X.init(e,t)}),mp=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{Pd.init(e,t),X.init(e,t)}),hp=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{Fd.init(e,t),X.init(e,t)}),gp=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{Id.init(e,t),X.init(e,t)}),_p=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{Vd.init(e,t),X.init(e,t)}),vp=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{Ud.init(e,t),X.init(e,t)}),yp=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{Wd.init(e,t),X.init(e,t)}),bp=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{Gd.init(e,t),X.init(e,t)}),xp=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{qd.init(e,t),X.init(e,t)}),Sp=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{Yd.init(e,t),X.init(e,t)}),Cp=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{Xd.init(e,t),X.init(e,t)}),wp=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{Zd.init(e,t),X.init(e,t)}),Tp=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{Qd.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ derived({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=aggregateChecks(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=aggregateChecks(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=aggregateChecks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>aggregateChecks(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ _gt(e,t))},gte(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},min(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},lt(e,t){return this.check(/* @__PURE__ */ _lt(e,t))},lte(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},max(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(/* @__PURE__ */ _gt(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ _gte(0,e))},negative(e){return this.check(/* @__PURE__ */ _lt(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ _lte(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},step(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},finite(){return this}}));function number(e){return/* @__PURE__ */ _number(Tp,e)}const Ep=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{$d.init(e,t),Tp.init(e,t)});function int(e){return/* @__PURE__ */ _int(Ep,e)}const Dp=/*@__PURE__*/ $constructor(`ZodBoolean`,(e,t)=>{ef.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return/* @__PURE__ */ _boolean(Dp,e)}const Op=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{tf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return/* @__PURE__ */ _unknown(Op)}const kp=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{nf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return/* @__PURE__ */ _never(kp,e)}const Ap=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),rf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ _minLength(e,t))},nonempty(e){return this.check(/* @__PURE__ */ _minLength(1,e))},max(e,t){return this.check(/* @__PURE__ */ _maxLength(e,t))},length(e,t){return this.check(/* @__PURE__ */ _length(e,t))},unwrap(){return this.element}});function array(e,t){return/* @__PURE__ */ _array(Ap,e,t)}const jp=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),sf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),installLazyProp(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(zp,this,e[0])},exactPartial(...e){return partial(Bp,this,e[0],`exactPartial`)},required(...e){return required(Wp,this,e[0])}});function object(e,t){let n={type:`object`,shape:e??{},...normalizeParams(t)};return new jp(n)}function strictObject(e,t){return new jp({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new jp({type:`object`,shape:e,catchall:unknown(),...normalizeParams(t)})}const Mp=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{cf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new Mp({type:`union`,options:e,...normalizeParams(t)})}const Np=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{Mp.init(e,t),lf.init(e,t)});function discriminatedUnion(e,t,n){return new Np({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}const Pp=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{uf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new Pp({type:`intersection`,left:e,right:t})}const Fp=/*@__PURE__*/ $constructor(`ZodRecord`,(e,t)=>{_ensureDefaultMemoizer(),df.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>recordProcessor(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,n){return!t||!t._zod?new Fp({type:`record`,keyType:string(),valueType:e,...normalizeParams(t)}):new Fp({type:`record`,keyType:e,valueType:t,...normalizeParams(n)})}const Ip=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{ff.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ip({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ip({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ip({type:`enum`,entries:n,...normalizeParams(t)})}const Lp=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{pf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>literalProcessor(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal$1(e,t){return new Lp({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const Rp=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),mf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function transform(e){return new Rp({type:`transform`,transform:e})}const zp=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{hf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new zp({type:`optional`,innerType:e})}const Bp=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{gf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new Bp({type:`optional`,innerType:e})}const Vp=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{_f.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new Vp({type:`nullable`,innerType:e})}const Hp=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{vf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new Hp({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const Up=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{yf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new Up({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const Wp=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{bf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new Wp({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const Gp=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{xf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new Gp({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}const Kp=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{Sf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new Kp({type:`pipe`,in:e,out:t})}const qp=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{Cf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new qp({type:`readonly`,innerType:e})}const Jp=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{wf.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function custom(e,t){return/* @__PURE__ */ _custom(Jp,e??(()=>!0),t)}function refine(e,t={}){return/* @__PURE__ */ _refine(Jp,e,t)}function superRefine(e,t){return/* @__PURE__ */ _superRefine(e,t)}function safeParseWithSchema(e,t){let n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??h)(t.pid))return{reason:`owner-process-exited`,pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:null};let n=t.starttime===void 0?null:(e.getProcessStartTime??m)(t.pid),r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n},i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;return n!==null&&n!==i?{reason:`owner-starttime-changed`,...r}:null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}const Yp=string().min(1).max(4096),Xp={pid:number().int().positive(),startIdentity:Yp.max(128)},Zp=strictObject({...Xp,startIdentitySource:literal$1(`argv-sha256`).nullable().optional()}).refine(({startIdentity:e,startIdentitySource:t})=>t===`argv-sha256`?/^win32-argv-sha256:[a-f0-9]{64}$/.test(e):!e.startsWith(`win32-argv-sha256:`)),Qp=union([strictObject({platform:_enum([`linux`,`darwin`]),identity:string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),strictObject({platform:literal$1(`win32`),identity:string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),strictObject({platform:literal$1(`freebsd`),identity:string().regex(/^[a-f0-9]{32}$/)})]),$p=strictObject({kind:literal$1(`native`),unit:Yp,scope:Yp,placement:discriminatedUnion(`kind`,[strictObject({kind:literal$1(`pending`)}),strictObject({kind:literal$1(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])}),em=literal$1(`original-cancellation-v1`),tm=strictObject({kind:literal$1(`update`),mutationProtocol:em}).extend({mutationProtocol:em.optional(),custody:_enum([`reserved`,`bound`]).optional()}),nm=discriminatedUnion(`kind`,[tm,strictObject({kind:literal$1(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal$1(`foreground`),boot:Qp}),$p])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),rm=Yp.refine(E.isAbsolute,`Native source path must be absolute`),im=string().regex(/^[a-f0-9]{64}$/),am=strictObject({runId:Yp,transactionId:Yp,claimId:Yp,revision:number().int().nonnegative(),recordSha256:im,serviceKey:rm,configPaths:array(rm).min(1).max(512),lifetimeId:Yp}),om=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:am}),sm={executor:Zp,helper:Zp,action:nm},cm=strictObject({version:literal$1(2),executor:Zp,helper:Zp,action:tm}),lm=strictObject({key:Yp,owner:Yp,payload:string().min(1),updatedAt:number().int().nonnegative()});discriminatedUnion(`version`,[strictObject({version:literal$1(4),executor:Zp,helper:Zp,action:tm,cancellation:lm}).refine(e=>{let t=safeParseJsonWithSchema(cm,e.cancellation.payload);return t!==null&&JSON.stringify(t.helper)===JSON.stringify(e.helper)&&JSON.stringify(t.executor)===JSON.stringify(e.executor)&&JSON.stringify(t.action)===JSON.stringify(e.action)&&(JSON.stringify(e.helper)===JSON.stringify(e.executor)||t.action.mutationProtocol===`original-cancellation-v1`)}),strictObject({version:literal$1(2),...sm,mutationOriginal:lm.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(cm,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`}),strictObject({version:literal$1(3),...sm,action:strictObject({kind:literal$1(`update`)}),nativeBorrower:om})]),strictObject({version:literal$1(1),...Xp});const um=[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`];function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=T.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){let n=process.platform===`freebsd`,r=process.platform===`win32`,i=$r(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?um:n?[`-b`,`kern.boot_id`]:[`-n`,`kern.bootsessionuuid`],{env:e,...n?{maxBuffer:16}:{encoding:`utf8`,windowsHide:!0},timeout:r?5e3:1e3,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]});!i.error&&i.status===0&&(t=n?Buffer.isBuffer(i.stdout)&&i.stdout.length===16?i.stdout.toString(`hex`):void 0:i.stdout.toString().trim())}let r={platform:n,identity:n===`win32`?t:t?.toLowerCase()},i=Qp.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[dm,fm,pm]=Qp.options,mm=string().min(1),hm=string().regex(/^[a-f0-9]{64}$/u),gm=discriminatedUnion(`platform`,[dm.extend({host:mm,platform:literal$1(`linux`),pidNsInode:string().min(1)}),dm.extend({host:mm,platform:literal$1(`darwin`)}),fm.extend({host:mm,identity:fm.shape.identity.optional()}),pm.extend({host:mm})]);let _m;function readGatewayLockProcessNamespace(){if(_m?.platform===process.platform&&(_m.value!==null||process.platform!==`linux`&&process.platform!==`android`))return _m.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=gm.parse({host:Jr.hostname(),...e,...e.platform===`linux`?{pidNsInode:T.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return _m={platform:process.platform,value:t},t}catch{return _m={platform:process.platform,value:null},null}}function isLegacyGatewayLeaseLock(e){return process.platform===`linux`&&e.processNamespace===void 0&&e.role===`gateway`&&typeof e.ownerId==`string`&&e.ownerId.length>0&&typeof e.createdAt==`string`}function readLockHeartbeat(e){try{return T.statSync(e).mtimeMs}catch{return}}function isForeignLinuxNamespace(e,t){return e?.platform===`linux`&&t?.platform===`linux`&&(e.host!==t.host||e.pidNsInode!==t.pidNsInode)}function describeGatewayLockHolder(e,t,n){let r=gm.safeParse(e.processNamespace).data,i=(t?readLockHeartbeat(t):void 0)??e.heartbeatAt,a=i===void 0?void 0:Date.now()-i,s=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`,c=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?`Stop the holder before retrying`:`Run this command inside the Gateway container or with a shared PID namespace`;return`holder ${e.pid??`unknown`} at ${s}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${c}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){let n=process.platform===`linux`&&e.processNamespace===void 0;super(`cannot verify Gateway ownership from this process${t?` at ${t}`:``}. ${n?`Legacy holder ${e.pid??`unknown`} has no PID namespace evidence. It may already have stopped. Independently verify that no Gateway using this state is running on this host or in any sharing container. With a current OpenClaw CLI using the same state and profile, run \`openclaw gateway recover-lock --json\`, then \`openclaw gateway recover-lock --confirm <confirmation> --json\` with the returned confirmation. Retry Doctor afterward.`:describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`,this.legacyLock=n,this.legacyLease=isLegacyGatewayLeaseLock(e)||n&&typeof e.expiresAt==`number`;let r=gm.safeParse(e.processNamespace).data;if(isForeignLinuxNamespace(r,readGatewayLockProcessNamespace())){let n=t?readLockHeartbeat(t):e.heartbeatAt;n!==void 0&&(this.heartbeatAgeMs=Math.max(0,Date.now()-n))}}};function classifyGatewayOwnerProcessNamespace(e,t={}){let n=gm.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;let r=readGatewayLockProcessNamespace();if(!r||n.platform!==r.platform)return`unknown`;if(t.readGatewayHeartbeat&&isForeignLinuxNamespace(n,r)){if(n.host===r.host&&/^[a-f0-9]{12}$/u.test(r.host)&&isContainerEnvironment())return`dead`;let e=t.readGatewayHeartbeat();if(e!==void 0&&Date.now()-e>9e4)return`dead`}if(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=hm.safeParse(t.machineIdentity).data,i=An();if(e&&i){if(e!==i)return`unknown`;if(n.identity!==r.identity)return`dead`}}let i=n.platform===`darwin`&&r.platform===`darwin`&&n.identity===r.identity;return n.host!==r.host&&!i?`unknown`:n.platform===`win32`?`same`:n.identity===r.identity?n.platform!==`linux`||r.platform===`linux`&&n.pidNsInode===r.pidNsInode?`same`:`unknown`:`dead`}const vm=object({pid:number(),ownerId:string().min(1).optional(),stateOwnerKind:literal$1(`schema`).optional(),cronOwnerProjection:literal$1(`dynamic-default-v1`).optional(),createdAt:string(),startupPhase:literal$1(`starting`).optional(),configPath:string(),port:number().int().min(1).max(65535).optional(),role:_enum([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:string().optional(),startTime:number().optional(),parentPid:number().int().positive().optional(),parentStartTime:number().optional(),processNamespace:gm.nullable().optional(),machineIdentity:hm.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(vm,e)}const ym=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(Br(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=Br(e).isDirectory()?e:E.dirname(e);t=E.join(n,`.openclaw-chmod-probe-${qr()}`),Hr(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return Lr(t,384),!1}catch(e){return ae(e)&&e.code===`EPERM`}finally{try{Vr(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&ym.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((Br(e).mode&4095)===t)return{applied:!0};try{return Lr(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,ae(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}const bm=`Run OpenClaw as the user that owns its state directory, and keep that directory on a local filesystem that supports file ownership and permissions`;function ensureOwnerDirectory(e,t){let n=T.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=E.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=T.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),E.toNamespacedPath(t)===r)break;let a=E.dirname(t);if(a===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(let e of i){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let r=T.lstatSync(e),i=process.getuid?.();if(!r.isDirectory())throw Error(`State ownership directory must be a user-owned real directory`);if(i!==void 0&&r.uid!==i)throw Error(`State ownership directory ${e} is owned by uid ${r.uid}, not this user (uid ${i}). ${bm}`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),T.lstatSync(e).mode&63))throw Error(`State ownership directory ${e} permissions could not be set to 0700. ${bm}`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=T.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&T.rmdirSync(t.path)}catch(e){let t=l(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=jr(e);return stateOwnerIdentity(t,jr(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await Ar(e);return stateOwnerIdentity(t,await Ar(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:E.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?Ze(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?E.join(Jr.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):Le(resolveOpenClawStateDirForDatabasePath(e))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}const xm=Date.now.bind(Date);function captureLock(e){let t=T.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,n){let r={};for(let t of e)r[t.lockPath]=captureLock(t);let i=Object.keys(r)[0];if(!i)throw Error(`Gateway state ownership requires a held lock`);let a=T.statSync(i,{bigint:!0}),{moduleUrl:c,runtimeGeneration:l}=_t(Pt(`gatewayStateOwnerHeartbeat`));return t(()=>{let t=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(t,0,BigInt(xm()));let{port1:d,port2:f}=new ti,m=Mn(c,{workerData:{clock:`epoch`,locks:r,intervalMs:15e3,failureMs:6e4,lastBeat:t.buffer,events:f},transferList:[f],execArgv:ge(c)}),h=p();m.on(`message`,e=>{e===`closed`&&h.resolve()}),m.unref();let ee=0,g=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of g.values())t.reject(e);g.clear(),d.unref()};d.on(`message`,e=>{if(en(`lifecycle`,`from_worker`),e===`parent-lost`)me();else if(e&&typeof e==`object`&&e.type===`lost`)n(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=g.get(e.id);g.delete(e.id),g.size===0&&d.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),d.unref(),m.on(`error`,e=>{let t=/* @__PURE__ */ Error(`${u(e)}; restart Gateway.`);rejectPending(t),n(t)}),m.once(`exit`,()=>{h.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let te,remainingUntilInspection=()=>{let e=Atomics.load(t,0),n=xm()-Number(e);return n<0?0:6e4-n},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${i}; retry after storage recovers.`);return e},renewAsync=async()=>{let n=xm(),s=new Date(n);for(let t of e)try{let n=r[t.lockPath];if(n===void 0)throw Error(`owner acquisition bytes were not registered`);let c=await T.promises.open(t.lockPath,`r+`);try{let r=await c.stat({bigint:!0}),l=await T.promises.lstat(t.lockPath,{bigint:!0}),u=Buffer.alloc(Buffer.byteLength(n)+1),{bytesRead:d}=await c.read(u,0,u.length,0),f=await T.promises.lstat(t.lockPath,{bigint:!0});if(te||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(r,l,n,u.subarray(0,d).toString(`utf8`))||!f.isFile()||f.dev!==r.dev||f.ino!==r.ino||t.lockPath===i&&(r.dev!==a.dev||r.ino!==a.ino)){if(t.lockPath!==i)continue;throw Error(`owner lock was removed or replaced`)}await c.utimes(s,s)}finally{await c.close()}}catch(e){if(t.lockPath!==i&&oe(e,`ENOENT`))continue;throw e}!te&&e.size>0&&Atomics.store(t,0,BigInt(n))},ne,v,watch=()=>{let e=remainingUntilInspection();e>0?(ne=setTimeout(watch,e),ne.unref()):v??=renewAsync().then(()=>{v=void 0,te||watch()},e=>{v=void 0,te||n(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${i}: ${u(e)}; restart the Gateway.`))})};watch();let stop=()=>(te||=(clearTimeout(ne),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),d.close(),m.ref(),m.postMessage(`stop`,[]),(async()=>(await settlesWithin(h.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${he}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),m.terminate()))()),Promise.all([te,v]).then(()=>void 0));l?.retain(m,async()=>async()=>{await stop()});let assertActive=()=>{if(te||m.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},re=new Set(Object.keys(r));return{worker:m,paths:re,register(e){let t=captureLock(e);r[e.lockPath]=t,m.postMessage([e.lockPath,t],[]),re.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++ee;return new Promise((n,r)=>{g.set(t,{resolve:n,reject:r}),d.ref();try{m.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){g.delete(t),g.size===0&&d.unref(),r(s(e,`Gateway state ownership verification failed`))}})},stop}})}function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return!1;throw t}}function verifyOwnerLock(e,t){if(e.lost.signal.throwIfAborted(),e.heartbeat?.inspect(),!t)return!1;let n=e.getProjection?.();n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath)&&e.heartbeat.register(n);let r=e.payload.role??`gateway`;return e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat?(e.heartbeat.assertActive(),!0):t.verifyStillHeld()?!0:(loseOwner(e,/* @__PURE__ */ Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`)),!1)}const Sm=y(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,Cm.clear(),e.heartbeat?.stop(),Sm.error(t.message),e.lost.abort(t))}function observeOwnerLoss(e,t,n){let r=[...e.locks,e.getProjection?.()];(!n||r.some(e=>e?.lockPath===n))&&loseOwner(e,t)}const Cm=i(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),wm=i(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),Tm=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),Em=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=getCommandPositionalsWithRootOptions(e,{commandPath:[`gateway`],booleanFlags:[...Em,`--task-supervisor`],valueFlags:[...Tm,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}function classifyGatewayLockProcessNamespace(e,t,n){if(e&&n&&isLegacyGatewayLeaseLock(e)){let t=Date.now(),r=Date.parse(e.createdAt);if(!Number.isFinite(r)||t-r<=3e5)return`unknown`;try{let r=openNodeSqliteDatabase(resolveReadOnlyShmSqliteFileUri(n),{readOnly:!0});try{let n=getNodeSqliteKysely(r),{rows:i}=executeSqliteQuerySync(r,{compile:()=>hl`SELECT expires_at AS expiresAt
              FROM ${hl`state_leases NOT INDEXED`}
              WHERE scope = ${`gateway-owner`} AND owner = ${e.ownerId}`.compile(n)});return i.every(e=>typeof e.expiresAt==`number`&&e.expiresAt<=t)?`dead`:`unknown`}finally{r.close()}}catch{return`unknown`}}if((process.platform===`win32`||process.platform===`darwin`)&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-T.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity,readGatewayHeartbeat:t?()=>readLockHeartbeat(t):void 0})}const Dm=new D;function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?inspectStaleLockOwner({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(e,t,n){let r=f(e)?e:null;if(!r)return!1;let i=classifyGatewayLockProcessNamespace(r,t,n);if(i===`unknown`)throw new GatewayLockNamespaceError(r,t);return comparableStateOwnerStaleReason(r,i)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:t,ownerPath:n,assertMaintenance:r}=e,i=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`,a;try{a=T.readFileSync(n,`utf8`)}catch(e){if(l(e)===`ENOENT`)return;throw new xr(i,{cause:e})}let s=Dm.getStore();if(s?.deadOwner?.path===n&&s.deadOwner.raw===a)return;let c=parseGatewayLockPayload(a);if(!c)throw new rn(t,i);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new xr(i);let u=classifyGatewayLockProcessNamespace(c,n,t),d=comparableStateOwnerStaleReason(c,u);if(d){s&&d===`owner-process-exited`&&(s.deadOwner={path:n,raw:a});return}if(u===`same`&&c.pid===process.pid&&!ni)return;if(u===`same`&&!ee(c.pid))throw new rn(t,i);let f=c.role??`gateway`;if(f===`gateway`||f===`agent-embedded`)return;if(u===`same`&&c.pid===process.pid){r();return}let p=`OpenClaw state at ${t} is undergoing offline maintenance by ${f} process ${c.pid}, started ${c.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(c,n,u===`same`?`live`:`unknown`)}`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new rn(t,p):new dt(t,p)}function defaultPayload(e){let t=resolveOpenClawStateDirForDatabasePath(e),n=m(process.pid),r=pe(),i=r===void 0?null:m(r);return{pid:process.pid,ownerId:qr(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:E.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?An():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,t,n){if(n.role===`gateway`)return;let r;try{r=T.readFileSync(t,`utf8`)}catch(e){if(l(e)===`ENOENT`)return;throw e}let i=parseGatewayLockPayload(r);if(!(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&classifyOpenClawArgv(process.argv,{command:`gateway`}).kind===`openclaw`))throw new rn(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,r=0,i){let a=performance.now()+r,s=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,s,n),ensureOwnerDirectory(E.dirname(t),i);let c={holder:null},stale=({payload:n})=>(c.holder=vm.safeParse(n).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,t,e));if(r>0)try{let n=c.holder=parseGatewayLockPayload(T.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&ee(n.pid)))throw new lt(e)}catch(e){if(l(e)!==`ENOENT`)throw e}for(let u=!1;;)try{return vi(t,{lockPath:t,retry:r>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(a-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>(assertGatewayRestorationPriority(e,s,n),n),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){let r=l(n);if(r===`ENOENT`&&!u){u=!0,ensureOwnerDirectory(E.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){let{holder:r}=c,i=describeGatewayLockHolder(r??{},t,r&&ee(r.pid)?`live`:`unknown`);throw new lt(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}const Om=i(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new D);function getStateDatabaseSchemaLease(e){let t=Om.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),Cm.clear();let t=new Map(Om.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,Cm.clear()};try{let n=Om.run(t,e);return xn(n)?Promise.resolve(n).finally(leave):(leave(),n)}catch(e){throw leave(),e}}let a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||wm.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){Cm.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&wm.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,wm.delete(n.key),n.onReleased?.())),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){Cm.clear();let n=resolveStateOwnerIdentity(e),r=wm.get(n.key),i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new lt(e,r.lost.signal.reason);r&&assertStateDatabaseAccessAllowed(e);let a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},s,c=[];try{s=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,c)}catch(t){if(t instanceof lt)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof rn)throw e}throw t}let l=r?.projectionPath??E.join(Ye(resolveOpenClawStateDirForDatabasePath(jr(e))),`gateway.state.lock`),u;try{u=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,l,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,c)}catch(e){return Qn({release(){s.release(),removeCreatedProjectionDirectories(c)}},`state schema projection admission`,()=>{throw e})}r?(r.locks.add(s),r.locks.add(u),r.projectionDirectories.push(...c)):(r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:l,locks:/* @__PURE__ */ new Set([s,u]),projectionDirectories:c,lost:new AbortController,accepting:!0},wm.set(r.key,r));let d=leaseForFile(i,s,r,u);try{let e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));return d.assertCurrent(),e.register(u),d}catch(e){return Qn(d,`state schema ownership verification`,()=>{throw e})}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(wm.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=E.resolve(e);if(Cm.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=wm.get(i.key),s=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||s!==`gateway`&&s!==`agent-embedded`)assertStateDatabaseAccessAtOwnerPath(e,i,t);else{if(!hasPhysicalOwnership(a))throw a.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);Cm.set(r,a)}}function assertStateDatabaseAccessAllowed(e,t){assertStateDatabaseAccessAtOwnerPath(e,resolveStateOwnerIdentity(e),t)}async function captureStateDatabaseAccess(e){return createStateDatabaseAccess(await resolveStateOwnerIdentityAsync(e))}function createStateDatabaseAccess(e,t){let{canonicalPath:n}=e,r=wm.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){if(r.lost.signal.throwIfAborted(),!r.accepting||wm.get(e.key)!==r)throw Ut()}}:void 0,prepareAccess:async r=>{let i=t??wm.get(e.key),a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`)return assertStateDatabaseAccessAtOwnerPath(n,e,r),(t=r)=>{if(i&&wm.get(e.key)!==i)throw Ut();assertStateDatabaseReadAtOwnerPath(n,t,e)};let s=i.heartbeat,c=i.locks.values().next().value,l=i.getProjection?.();if(!s||!c)throw Ut();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),s.assertActive(),wm.get(e.key)!==i||i.heartbeat!==s)throw Ut();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(c)||i.getProjection?.()!==l)throw Ut()};assertCurrent();let u=[c.lockPath];l&&u.push(l.lockPath);let d=await s.verify(u).catch(e=>{throw i.lost.signal.throwIfAborted(),e});if(assertCurrent(),!d){let e=/* @__PURE__ */ Error(`${c.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);throw loseOwner(i,e),e}return Cm.set(E.resolve(n),i),assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){let assertMaintenance=()=>{let t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}let r=n?n.maintenanceScope:getOpenClawDatabaseMaintenanceScope();if(!r)throw new mt(e);r.assertDatabaseAccess(e)},r=wm.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}const km=i(Symbol.for(`openclaw.stateSchemaMutationConflictError`),()=>class extends Error{constructor(e,t){super(`OpenClaw refused shared state schema mutation at ${e} because another Gateway owns that state directory. Stop that Gateway or perform the update through its managed restart path, then retry.`,{cause:t}),this.name=`StateSchemaMutationConflictError`}});function acquireSchemaMaintenanceLease({databasePath:e,busyTimeoutMs:t}){if(kn(e))return;let n=jr(e),r=getStateDatabaseSchemaLease(n);if(r)r.assertCurrent();else try{return acquireStateDatabaseSchemaLease(n,{busyTimeoutMs:t})}catch(e){throw e instanceof lt?new km(n,e):e}}function withStateDatabaseSchemaMaintenance(e,t){let n=acquireSchemaMaintenanceLease(e);return n?Qn(n,`state schema mutation`,()=>n.run(t)):t()}const Am=new D;function hasUpdateDoctorMigrationCapture(){return Am.getStore()?.capture!==void 0}function capturedAttribution(){if(hasUpdateDoctorMigrationCapture())throw Error(`Update migration capture is active without its attribution owner.`)}function runUpdateSqliteMigration(...e){let t=capturedAttribution();return t?t.runSqlite(...e):e[2]()}function beginUpdatePostgresMigration(e,t){return capturedAttribution()?.beginPostgres(e,t)}function getStateSchemaFacts(e){return C(e)?getPostgresPhysicalFacts(e):getAdmittedSqliteSchemaFacts(e)}const jm={name:`state.schema-version`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`userVersion`in e&&typeof e.userVersion==`number`&&`contentVersion`in e&&typeof e.contentVersion==`number`)return{userVersion:e.userVersion,contentVersion:e.contentVersion}}};function createStateSchemaAdmission(e,t,n){let r={name:e,lifetime:n,schemaDependent:!0,read(e){if(typeof e!=`object`||!e||!(`value`in e)||!(`admissionId`in e)||typeof e.admissionId!=`string`)return;let n=t(e.value);return n===void 0?void 0:{value:n,admissionId:e.admissionId}}};return{get(e){if(pr(e))return;let t=b(e,r);if(!t)return;let n=getStateSchemaFacts(e);return t.admissionId===n?.admissionId?t.value:void 0},publish(e,t){!C(e)&&isSqliteSchemaAdmissionCold(e)&&admitSqliteSchema(e);let n=getStateSchemaFacts(e);if(!n||!C(e)&&b(e,Qi)?.admissionId!==n.admissionId)return;getStateSchemaVersionAdmission(e);let i={value:t,admissionId:n.admissionId};w(e,r,i)}}}const Mm=createStateSchemaAdmission(`state.runtime-schema`,e=>typeof e==`object`&&e&&`startupReady`in e&&typeof e.startupReady==`boolean`?{startupReady:e.startupReady}:void 0,`process`),Nm=/* @__PURE__ */ new WeakMap;function rememberConnectionVersion(e,t){let n=Nm.get(e),install=t=>{t?Nm.set(e,t):Nm.delete(e)};Jt(e,{stage:()=>install(t),commit:()=>{},rollback:()=>install(n)})||install(t)}function schemaVersionKey(e){return{name:`state.schema-version:${e}`,read:jm.read}}function getStateSchemaVersionAdmission(e){let t=getStateSchemaFacts(e);if(!t)return;let n=Nm.get(e);if(n?.schema===t)return n.facts;let r=b(e,schemaVersionKey(t.admissionId)),i=r?void 0:b(e,Qi);if(!r&&!C(e)&&i?.admissionId!==t.admissionId)return;let a=r??b(e,jm);return a&&(rememberConnectionVersion(e,{schema:t,facts:a}),r||w(e,schemaVersionKey(t.admissionId),a)),a}function rememberStateSchemaVersionAdmission(e,t){let n=getStateSchemaFacts(e);if(!n)return;rememberConnectionVersion(e,{schema:n,facts:t});let r=b(e,Qi);(C(e)||r?.admissionId===n.admissionId)&&(w(e,schemaVersionKey(n.admissionId),t),w(e,jm,t))}function publishStateSchemaVersionAdmission(e,t){w(e,jm,t);let n=getStateSchemaFacts(e);n?(rememberConnectionVersion(e,{schema:n,facts:t}),w(e,schemaVersionKey(n.admissionId),t)):rememberConnectionVersion(e)}function adoptPeerPublishedStateSchemaVersion(e,t){return t?.schema_version!==40||readSqliteUserVersion(e)!==40?!1:(publishStateSchemaVersionAdmission(e,{userVersion:40,contentVersion:40}),!0)}function getStateRuntimeSchemaAdmission(e){return Mm.get(e)}function publishStateRuntimeSchemaAdmission(e,t){Mm.publish(e,{startupReady:t})}function createSqliteTerminalOpenLatch(e){let t=/* @__PURE__ */ new Map;return{peek:e=>t.get(E.resolve(e)),get:e=>t.get(E.resolve(e)),record:(n,r)=>{let i=E.resolve(n);Nr(r),t.set(i,r),e.closeByPath(i,r)},clear:e=>{t.delete(E.resolve(e))},clearAll:e=>{for(let n of t.keys())(e===void 0||be(e,n))&&t.delete(n)}}}function sameFileFingerprint(e,t){return e.dev===t.dev&&e.ino===t.ino&&sameFileStatFingerprint(e,t)&&e.sha256===t.sha256}function sameOptionalFileFingerprint(e,t){return e===void 0?t===void 0:t!==void 0&&sameFileFingerprint(e,t)}function sameSqliteFileGeneration(e,t){return sameFileFingerprint(e.database,t.database)&&sameOptionalFileFingerprint(e.journal,t.journal)&&sameOptionalFileFingerprint(e.wal?.size===0n?void 0:e.wal,t.wal?.size===0n?void 0:t.wal)}function parseFileFingerprint(e){if(!f(e))throw Error(`SQLite file fingerprint must be an object`);for(let t of[`birthtimeNs`,`ctimeNs`,`dev`,`ino`,`mtimeNs`,`size`])if(typeof e[t]!=`string`||!/^-?\d+$/u.test(e[t]))throw Error(`SQLite file fingerprint ${t} is invalid`);if(typeof e.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.sha256))throw Error(`SQLite file fingerprint sha256 is invalid`);return{birthtimeNs:BigInt(e.birthtimeNs),ctimeNs:BigInt(e.ctimeNs),dev:BigInt(e.dev),ino:BigInt(e.ino),mtimeNs:BigInt(e.mtimeNs),sha256:e.sha256,size:BigInt(e.size)}}function parseSqliteFileGeneration(e){let t=JSON.parse(e);if(!f(t))throw Error(`SQLite file generation must be an object`);return{database:parseFileFingerprint(t.database),...t.journal===void 0?{}:{journal:parseFileFingerprint(t.journal)},...t.wal===void 0?{}:{wal:parseFileFingerprint(t.wal)}}}function readSqliteFileGenerationSync(e){return parseSqliteFileGeneration(runSqliteReadOnlyWorkerSync(e,void 0,`file-generation`))}function createPrivateWindowsDirectory(e){let t=!1;try{si(E.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof mi&&e.code===`already-exists`?markPrivateDirectoryCreationRefused(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&hasSqliteSnapshotCapacityCode(e)?new SqliteSnapshotCapacityError(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&E.isAbsolute(t))return Pe({preferredDir:E.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,r=process.platform===`win32`?`AppData/Local`:`.cache`,i=process.platform===`darwin`?`Library/Caches`:r,a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&E.isAbsolute(e))??E.join(Fe(e),i),s=ze(e),c=Gr(`sha256`).update(s).digest(`hex`).slice(0,24);T.mkdirSync(a,{recursive:!0,mode:448});let l=Pe({preferredDir:E.join(a,`openclaw`),tmpdir:()=>a}),[u=``,...d]=E.relative(l,s).split(E.sep),f=d.length>0&&/^sqlite-[a-f0-9]{24}$/u.test(u)?u:`sqlite-${c}`,p=E.join(l,f);T.mkdirSync(p,{recursive:!0,mode:448});let m=T.lstatSync(p);if(!m.isDirectory()||process.getuid&&m.uid!==process.getuid()||process.platform!==`win32`&&m.mode&63)throw Error(`SQLite snapshot namespace must be a private user-owned directory`);return p}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return T.mkdtempSync(E.join(e,t))}catch(e){throw markPrivateDirectoryCreationRefused(e)}let n=E.join(e,`${t}${qr()}`);return createPrivateWindowsDirectory(n),n}function sqliteSnapshotSourceFileSize(e){try{let t=T.statSync(e);return t.isFile()?t.size:0}catch(e){if(oe(e,`ENOENT`))return 0;throw e}}function sqliteSnapshotStagingError(e,t,n=!1,r){$t(t,`snapshot`);let i=n,a=!1,s=!1,c;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){s||=r instanceof AggregateError||r instanceof ht;let{errcode:t,path:n}=r;a||=hasSqliteSnapshotCapacityCode(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${E.sep}`.startsWith(`${e}${E.sep}`))&&(i=!0,typeof t==`number`&&(c=t)),r=r.cause}if(!i)return t;let l=a?`free disk space/quota`:`check filesystem health and write permissions`,u=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=tryReadDiskSpace(e)?.availableBytes,i=T.existsSync(`${r}-wal`)&&T.existsSync(`${r}-shm`);u=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let d=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,f=`${t instanceof Error?t.message:String(t)}${c===void 0?``:` (SQLite errcode=${c})`}; snapshot staging root ${n?e:E.dirname(e)}${u}: ${l} or set ${d} to a writable filesystem`,p=a&&!s&&ct(t)!==`source`?new SqliteSnapshotCapacityError(f,{cause:t}):Error(f,{cause:t});return isPrivateDirectoryCreationRefused(t)?markPrivateDirectoryCreationRefused(p):p}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return registerSnapshotTempDirectory(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:ta)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:acquireSqliteSnapshotToken(n,`create`)}}catch(e){throw n&&removeTempDirectory(n),e}}Buffer.from([217,213,5,249,32,161,99,215]),i(Symbol.for(`openclaw.sqliteSnapshotFlights`),()=>({unscoped:/* @__PURE__ */ new Map,scoped:/* @__PURE__ */ new WeakMap}));const Pm=i(Symbol.for(`openclaw.sqliteLiveSnapshotOwners`),()=>/* @__PURE__ */ new Map);function registerLiveSqliteSnapshotOwner(e){let t=xt(e.databasePath),n={assertCurrent:e.assertCurrent,database:e.database};return Pm.set(t.key,n),()=>{Pm.get(t.key)===n&&Pm.delete(t.key)}}function fingerprint(e){return[e.dev,e.ino,e.birthtimeNs,e.ctimeNs,e.mtimeNs,e.size].join(`:`)}function walFingerprint(e){return[e.dev,e.ino,e.mtimeNs,e.size].join(`:`)}function readFile$1(e){let t=T.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});if(t){if(!t.isFile()||t.nlink!==1n)throw Error(`Private SQLite snapshot must be an independent regular file: ${e}`);return t}}function captureSqlitePrivateSnapshotFamily(e,t){if(T.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile$1(e),r=readFile$1(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}const Fm=i(Symbol.for(`openclaw.sqliteReusableSnapshots`),()=>/* @__PURE__ */ new Map),Im=i(Symbol.for(`openclaw.sqliteReusableSnapshotScopes`),()=>({depth:0,retiring:/* @__PURE__ */ new Set}));function completed(e){let t=vn(()=>{});return t.resolve(e),t.operation}function readSource(e){try{let t=T.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!t?.isFile()||T.statSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=T.statSync(`${e}-wal`,{bigint:!0,throwIfNoEntry:!1}),r=n&&n.size>0n?n:void 0;return{fingerprint:[`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,r?`${r.dev}:${r.ino}:${r.size}:${r.mtimeNs}`:`none`].join(`|`),main:t,newestMs:Math.max(Number(t.mtimeMs),Number(r?.mtimeMs??0)),quiescentMs:[t,r].some(e=>e&&e.mtimeNs%1000000000n==0n)?2e3:50}}catch{return}}function canonicalKey(e){try{return T.realpathSync.native(e)}catch{return}}function retire(e,t){Fm.get(e)===t&&Fm.delete(e),t.retired=!0,t.leases===0&&settleRetirement(t.retire)}function settleRetirement(e){let t=new Promise(t=>{t(e())}).catch(reportRetirementFailure).finally(()=>Im.retiring.delete(t));Im.retiring.add(t)}function reportRetirementFailure(e){Ge({subsystem:`infra/sqlite-snapshot`}).warn({error:String(e)},`Retiring a reusable SQLite snapshot failed.`)}function lend(e,t){t.leases+=1;let n=!1,release=()=>(n||(n=!0,--t.leases,t.leases===0&&t.retired&&retire(e,t)),!0);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup:release,cleanupAsync:async()=>release(),startCleanup:()=>completed(release())}}function leaseReusableSqliteSnapshot(e,t,n={}){let r=canonicalKey(e),i=r?Fm.get(r):void 0;if(r&&i){if(readSource(r)?.fingerprint!==i.fingerprint||!T.existsSync(i.location))retire(r,i);else if(!i.logicalOnly||n.logicalReader){if(t)try{Qt(i.main,t)}catch{return}return lend(r,i)}}}function captureReusableSqliteSource(e){let t=Im.depth>0?canonicalKey(e):void 0,n=t?readSource(t):void 0;return n&&Date.now()-n.newestMs>=n.quiescentMs?n:void 0}function captureFamily(e){try{return captureSqlitePrivateSnapshotFamily(e.location,e.cleanupRoot??E.dirname(e.location))}catch{return}}i(Symbol.for(`openclaw.sqliteReusableSnapshotSources`),()=>/* @__PURE__ */ new Map);function publishReusableSqliteSnapshot(e,t,n,r,i={}){let a=canonicalKey(e)??E.resolve(e),s=Fm.get(a);if(s?.location===n.location&&s.fingerprint===t.fingerprint)return settleRetirement(r),lend(a,s);s&&retire(a,s);let c={...t,logicalOnly:i.logicalOnly===!0,location:n.location,cleanupRoot:n.cleanupRoot,privateFamily:n.privateFamily??captureFamily(n),leases:0,retired:!1,retire:r};return Fm.set(a,c),lend(a,c)}const Lm=[``,`-wal`,`-shm`,`-journal`];Lm.slice(1),Buffer.from([0,5,22,7]),y(`state/sqlite`);function resolveSqliteDatabaseFilePaths(e){return Lm.map(t=>`${e}${t}`)}function buildUpdateRehearsalPathEnv(e){return{HOME:e,USERPROFILE:e,TMPDIR:e,TMP:e,TEMP:e,XDG_CONFIG_HOME:E.join(e,`config`),XDG_CACHE_HOME:E.join(e,`cache`),XDG_DATA_HOME:E.join(e,`data`),XDG_STATE_HOME:E.join(e,`state`),OPENCLAW_HOME:e,OPENCLAW_STATE_DIR:e,OPENCLAW_CONFIG_PATH:E.join(e,`openclaw.json`),OPENCLAW_WORKSPACE_DIR:E.join(e,`workspace`),OPENCLAW_SKIP_CHANNELS:`1`,OPENCLAW_SKIP_PROVIDERS:`1`,OPENCLAW_SKIP_CRON:`1`,OPENCLAW_SKIP_GMAIL_WATCHER:`1`,OPENCLAW_SKIP_CANVAS_HOST:`1`,OPENCLAW_SKIP_BROWSER_CONTROL_SERVER:`1`,OPENCLAW_SKIP_STARTUP_MODEL_PREWARM:`1`,OPENCLAW_NO_AUTO_UPDATE:`1`,NODE_DISABLE_COMPILE_CACHE:`1`}}function resolveUpdateRehearsalRoot(e){let t=e.OPENCLAW_STATE_DIR;if(t&&E.isAbsolute(t)&&[`0`,`1`].includes(e.OPENCLAW_UPDATE_IN_PROGRESS??``)&&!Object.entries(buildUpdateRehearsalPathEnv(t)).some(([t,n])=>e[t]!==n)&&e.OPENCLAW_SERVICE_REPAIR_POLICY===`external`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR===`0`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION===`0`&&!e.OPENCLAW_COMPATIBILITY_HOST_VERSION)return E.resolve(t)}function isUpdateRehearsalReadOnlyPath(e,t){let n=resolveUpdateRehearsalRoot(t);if(!n)return!1;let r=E.resolve(e);return!be(n,r)||!be(jr(n),jr(r))}function isUpdateRehearsalPrivateDatabase(e,t){return resolveUpdateRehearsalRoot(t)!==void 0&&resolveSqliteDatabaseFilePaths(e).every(e=>!isUpdateRehearsalReadOnlyPath(e,t))}function findArtifactSnapshot(e,t){let n=e.snapshots.get(t.canonicalPath);if(n&&(n.sourceIdentity.key!==t.key||n.sourceIdentity.birthtime!==t.birthtime))throw Error(`SQLite database file identity changed during inspection`);return n}function retainArtifactSnapshot(e,t,n){let r=retainSnapshotTempDirectory(t.cleanupRoot??E.dirname(t.location));e.privateRoots.add(t.cleanupRoot??E.dirname(t.location));let i={...t,sourceIdentity:n,cleanup:()=>(r(),t.cleanup()),cleanupAsync:()=>(r(),t.cleanupAsync())};return e.snapshots.set(n.canonicalPath,i),i}function assertCustodiedSourceUnchanged(e,t){let n=T.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!n||n.ino!==t.ino||n.size!==t.size||n.mtimeNs!==t.mtimeNs||readCustodiedDrainedSqliteSource(e)===void 0)throw Error(`SQLite source changed during in-place inspection: ${e}`)}function openSqliteReadOnlyDatabase(e,t={}){let n=ua.getStore();if(!n||!isArtifactPreservingStateRead(`agent`,e))return openNodeSqliteDatabase(e,{...t,readOnly:!0});let r=xt(e),i=findArtifactSnapshot(n,r),a=i?void 0:readCustodiedDrainedSqliteSource(r.canonicalPath);i||a||isUpdateRehearsalPrivateDatabase(e,process.env)||(i=retainArtifactSnapshot(n,prepareSqliteReadOnlyLocationSync(e),r));let s=i?retainSnapshotTempDirectory(i.cleanupRoot??E.dirname(i.location)):void 0,c={},close=()=>{c.close?.(),s?.(),n.readers.delete(close)};n.readers.add(close);let l=openNodeSqliteDatabase(i?.location??(a?resolveImmutableSqliteFileUri(r.canonicalPath):e),{...t,readOnly:!0}),u=l.close.bind(l);return c.close=()=>{l.isOpen&&(u(),a&&assertCustodiedSourceUnchanged(r.canonicalPath,a))},l.close=close,l}function prepareSqliteReadOnlyLocationSync(e,t,n={}){let r=n.reuse?leaseReusableSqliteSnapshot(e,t):void 0;if(r)return r;let i=n.reuse?captureReusableSqliteSource(e):void 0,a=createSqliteSnapshotStagingDirectorySync();try{let n=adoptPreparedLocation(runSqliteReadOnlyWorkerSync(e,a,`sync`,t),a);return i?publishReusableSqliteSnapshot(e,i,n,()=>n.cleanup()):n}catch(e){throw removeTempDirectory(a)?e:new ht(`${u(e)}; SQLite snapshot cleanup failed: ${a}`,{cause:e})}}const Rm={name:`openclaw.quarantine.schema`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`version`in e&&typeof e.version==`number`)return{version:e.version}}};function quarantineDecisionAdmission(e){return{name:`openclaw.quarantine.decision:${E.resolve(e)}`,lifetime:`process`,read:e=>e===null||isQuarantineDecision(e)?e:void 0}}function isQuarantineDecision(e){return f(e)&&(e.kind===`agent`||e.kind===`state`)&&typeof e.reason==`string`&&typeof e.quarantinedAt==`number`&&(e.verifiedGenerationJson===null||typeof e.verifiedGenerationJson==`string`)}function readQuarantineSchemaVersion(e,t,n=!1){let r=n?void 0:b(e,Rm);if(r)return r.version;let i=e.prepare(`PRAGMA user_version`).get()?.user_version;if(typeof i!=`number`||!Number.isInteger(i))throw Error(`OpenClaw quarantine store ${t} has an invalid schema version.`);if(i>2)throw Error(`OpenClaw quarantine store ${t} uses newer schema version ${i}.`);return i!==0&&w(e,Rm,{version:i}),i}function readOpenClawDatabaseQuarantine(e,t={}){let n=resolveQuarantineStorePath(t.env??process.env);t.refreshIdentity&&hr(n);let load=()=>readPersistedQuarantineDecision(e,n,t.fresh)??null,r=t.fresh?load():tt(n,quarantineDecisionAdmission(e),load);return r?resolveQuarantineDecision(r,e,n):void 0}function readPersistedQuarantineDecision(e,t,n=!1){if(!Rr(t))return;let r=openSqliteReadOnlyDatabase(t,{timeout:5e3}),i;try{i={value:readQuarantineDecision(r,e,t,n)}}catch(e){i={error:e}}try{r.close()}catch(n){let r,a=`error`in i?i.error:void 0;if(`value`in i&&i.value)try{r=resolveQuarantineDecision(i.value,e,t)}catch(e){a=e}throw new Ga(a===void 0?[n]:[a,n],r)}if(`error`in i)throw i.error;return i.value}function readQuarantineDecision(e,t,n,r=!1){let i=readQuarantineSchemaVersion(e,n,r);if(i===0)return;let a=i>=2?`, verified_generation`:``,s=e.prepare(`SELECT kind, reason, quarantined_at${a} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(E.resolve(t));if(!s)return;let c=i>=2?s.verified_generation:void 0;if(s.kind!==`agent`&&s.kind!==`state`||typeof s.reason!=`string`||typeof s.quarantined_at!=`number`||!Number.isInteger(s.quarantined_at)||c!=null&&typeof c!=`string`)throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`);return{kind:s.kind,quarantinedAt:s.quarantined_at,reason:s.reason,verifiedGenerationJson:typeof c==`string`?c:null}}function resolveQuarantineDecision(e,t,n){if(e.verifiedGenerationJson!==null){let r;try{r=parseSqliteFileGeneration(e.verifiedGenerationJson)}catch{throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`)}try{let e=readSqliteFileGenerationSync(E.resolve(t));if(!sameSqliteFileGeneration(r,e))return}catch{return}}return{kind:e.kind,quarantinedAt:e.quarantinedAt,reason:e.reason}}function readOpenClawDatabaseQuarantineFailure(e,t,n={}){let r,i;try{r=readOpenClawDatabaseQuarantine(t,n)}catch(e){if(!(e instanceof Ga))return;if(!e.quarantine)throw e;r=e.quarantine,i=e}if(!r)return;let a=/* @__PURE__ */ Error(`OpenClaw ${e} database ${t} is quarantined after integrity verification failed: ${r.reason??`unknown integrity error`}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See ${ro}.`);return a.name=`SqliteIntegrityError`,i&&(a.cause=i),a}const zm=new D;function getProcessCleanupBudget(){return zm.getStore()}function createStateDatabaseRetainer(e,t){let admit=(e,n,r)=>{let i=getOpenClawDatabaseMaintenanceScope();return n===`cached-read`?i?.assertReadAdmission():i?.assertAdmission(),t.assertOpen(e,n,r),i},retain=(n,r,i=!1)=>{if(t.capture(n.path).assertCurrent(),e.cachedDatabases.get(n.path)!==n||!n.db.isOpen)throw Error(`OpenClaw state database borrow requires its current canonical handle`);let a=e.borrowers.get(n.db)??{references:/* @__PURE__ */ new Set,retiring:!1,cleanupComplete:!1};if(a.retiring)throw Error(`OpenClaw state database native owner is retiring`);i||observeOpenClawDatabaseMaintenanceResource(n.db),e.borrowers.set(n.db,a);let isCurrent=()=>!r||isOpenClawDatabaseMaintenanceResourceOwned(n.db,r),s=i?void 0:{ordinary:r===void 0,isCurrent,retire:()=>{isCurrent()?t.retire(n,r===void 0):a.retiring=!1}};function createAsyncStateDatabaseRetirement(){let e={},r,i,finish=r=>{a.references.delete(e),a.releaseJoin?a.releaseJoin.resolve():r?.isCurrent()?r.retire():a.retiring=!1,a.retirement=void 0,a.asyncRetirement=void 0,i?.(),i=void 0,a.releaseJoin||t.touch(n)},run=()=>r||(a.cleanupComplete||a.references.size>+!!a.references.has(e)?Promise.resolve():a.retirement?.isCurrent()?(a.retiring=!0,a.references.add(e),i??=t.ownRetirement(n,close),r=Promise.resolve().then(async()=>{await n.walMaintenance.stop(),finish(a.retirement)}).catch(r=>{throw a.references.add(e),t.retainFailed(n),a.releaseJoin?.reject(r),a.releaseJoin=void 0,r}),r.catch(()=>{}),r):(finish(),Promise.resolve()));function close(){let e=run();return e.catch(t=>{throw r===e&&(r=void 0),t})}return{start:()=>void run(),close}}let c={};a.references.add(c);let l=!1,release=()=>{if(l||a.cleanupComplete)l=!0;else if(l=!0,a.references.delete(c),a.releaseJoin)a.references.size===0&&a.releaseJoin.resolve();else if(a.retirement&&!a.retirement.isCurrent()&&(a.retirement=void 0,a.asyncRetirement=void 0,a.retiring=!1),s?.isCurrent()&&!a.retirement?.ordinary&&(a.retirement=s),!(a.references.size>0)){if(!a.retirement)t.touch(n);else if(a.retiring=!0,a.asyncRetirement)a.asyncRetirement.start();else{try{a.retirement.retire()}catch(e){throw l=!1,t.retainFailed(n),e}a.retirement=void 0,t.touch(n)}}},u={release,async releaseAsync(){a.cleanupComplete||(a.releaseJoin?release():((s?.isCurrent()&&!a.retirement?.ordinary?s:a.retirement)?.isCurrent()&&(a.asyncRetirement??=createAsyncStateDatabaseRetirement()),release(),await a.asyncRetirement?.close()))}};return r?.own(u,`shared-references`,()=>u.releaseAsync()),u},findReadDatabase=(t,n,r)=>{let i=resolveDatabasePath({path:t}),a=e.cachedDatabases.get(i);return a?.db.isOpen?{database:a,scope:admit(i,n,r)}:{database:void 0,scope:void 0}},retainReadReference=(t,n)=>{let r=retain(t,n,!0),assertCurrent=()=>{if(e.cachedDatabases.get(t.path)!==t||!t.db.isOpen)throw Error(`Shared-state read lost its original native owner`)};return{assertCurrent,observe(){assertCurrent(),observeOpenClawDatabaseMaintenanceResource(t.db)},release:()=>r.release()}};return{retain:e=>retain(e,admit(e.path)),retainForIndependentRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);return r?retainReadReference(r,i):void 0},borrowForRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);if(r){if(r.db.isTransaction)throw Error(`Asynchronous shared-state reads cannot run inside a native transaction`);return{database:r,...retainReadReference(r,i)}}}}}async function joinStateDatabaseBorrowersReleased(e,t){e&&!e.cleanupComplete&&(e.retiring=!0,e.references.size!==0&&(e.releaseJoin||(e.releaseJoin=p(),getProcessCleanupBudget()?.warn(`Waiting for ${e.references.size} active native borrower(s) before retiring OpenClaw state database: ${t}`)),await e.releaseJoin.promise))}function assertStateDatabaseBorrowersReleased(e,t){if(e?.references.size)throw Error(`OpenClaw state database still has active native borrowers (${e.references.size}): ${t}`)}function createStateDatabaseCacheAdmission(e){return{closeTerminalFailure(t,n){markOpenClawStateDatabaseFailure(n,t),Pn(t),e.invalidate(t);let r=e.cachedDatabases.get(t),i=[];try{r&&e.evict(r)}catch(e){i.push(e)}try{e.notifyTerminalFailure(t,n)}catch(e){i.push(e)}it(i,`Terminal shared-state failure cleanup failed`)},read(t,n){if(!t.db.isOpen)return n(t);let r=!1;try{return runSqliteReadOperationSync(t.db,()=>(r=!0,n(t)))}catch(n){if(r)throw n;let i=n instanceof Error?n:Error(String(n));if(Dt(i)){e.evict(t);return}throw i}}}}const Bm=18e5,Vm=y(`state/db`);function createStateDatabaseIdleRetirement({cachedDatabases:e,retainedDatabaseHandles:n,idleTimers:r,idleReferences:i,borrowers:a},s){let touch=c=>{if(!(e.get(c.path)===c&&c.db.isOpen)&&n.get(c.db)!==c)return;let l=r.get(c.db);if(l){l.refresh();return}let u=t(()=>setTimeout(()=>{r.delete(c.db);try{c.db.isOpen&&c.db.isTransaction?touch(c):!a.get(c.db)?.references.size&&!i.get(c.db)?.size&&s(c,!1,{busyTimeoutMs:0,checkpointMode:`PASSIVE`})}catch(e){Vm.warn(`Idle shared-state database cleanup failed`,{path:c.path,error:e}),touch(c)}},Bm));u.unref(),r.set(c.db,u)};return{touch,retain(t){if(e.get(t.path)!==t||!t.db.isOpen||a.get(t.db)?.retiring)throw Error(`OpenClaw state database idle retention requires its current canonical handle`);let n=i.get(t.db)??/* @__PURE__ */ new Set,r={};return n.add(r),i.set(t.db,n),()=>{n.delete(r)&&e.get(t.path)===t&&t.db.isOpen&&touch(t)}}}}const Hm=i(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=Hm.get(e)?.stopCheckpointTick;Hm.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return Hm.get(e)?.execute!==void 0}var Um={blockedEverywhereKeys:/* @__PURE__ */ `NODE_OPTIONS.NODE_PATH.NODE_REDIRECT_WARNINGS.NODE_REPL_EXTERNAL_MODULE.NODE_REPL_HISTORY.NODE_V8_COVERAGE.PYTHONHOME.PYTHONPATH.PERL5LIB.PERL5OPT.PERL5SHELL.PERLLIB.RUBYLIB.RUBYOPT.BASHOPTS.BASH_ENV.ENV.KSH_ENV.BROWSER.GIT_ALLOW_PROTOCOL.GIT_EDITOR.GIT_EXTERNAL_DIFF.GIT_DIR.GIT_WORK_TREE.GIT_COMMON_DIR.GIT_EXEC_PATH.GIT_INDEX_FILE.GIT_OBJECT_DIRECTORY.GIT_ALTERNATE_OBJECT_DIRECTORIES.GIT_NAMESPACE.GIT_PROTOCOL_FROM_USER.GIT_SEQUENCE_EDITOR.GIT_TEMPLATE_DIR.GIT_SSL_NO_VERIFY.GIT_SSL_CAINFO.GIT_SSL_CAPATH.CC.CPP.CXX.CXXCPP.CARGO_BUILD_RUSTC.CARGO_BUILD_RUSTC_WRAPPER.CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER.CARGO_BUILD_RUSTDOC.RUSTC.RUSTC_WRAPPER.RUSTC_WORKSPACE_WRAPPER.RUSTDOC.CMAKE_C_COMPILER.CMAKE_CXX_COMPILER.SHELL.SHELLOPTS.PS4.GCONV_PATH.IFS.SSLKEYLOGFILE.JAVA_OPTS.JAVA_TOOL_OPTIONS._JAVA_OPTIONS.JDK_JAVA_OPTIONS.PYTHONBREAKPOINT.DOTNET_STARTUP_HOOKS.DOTNET_ADDITIONAL_DEPS.FPATH.GLIBC_TUNABLES.MAVEN_OPTS.MAKE.MAKEFLAGS.MFLAGS.SBT_OPTS.GRADLE_OPTS.ANT_OPTS.HGRCPATH.HGEDITOR.HGMERGE.EXINIT.VIMINIT.MYVIMRC.GVIMINIT.LUA_INIT.LUA_INIT_5_1.LUA_INIT_5_2.LUA_INIT_5_3.LUA_INIT_5_4.EMACSLOADPATH.RUBYSHELL.GIT_HOOK_PATH.SVN_EDITOR.SVN_SSH.BZR_EDITOR.BZR_SSH.BZR_PLUGIN_PATH.SUDO_ASKPASS.JULIA_EDITOR.CONFIG_SITE.CONFIG_SHELL.CMAKE_TOOLCHAIN_FILE.CATALINA_OPTS.CORECLR_PROFILER.HELM_PLUGINS.PACKER_PLUGIN_PATH.VAGRANT_VAGRANTFILE.ERL_AFLAGS.ERL_FLAGS.ERL_ZFLAGS.ELIXIR_ERL_OPTIONS.R_ENVIRON.R_PROFILE.R_ENVIRON_USER.R_PROFILE_USER.TCLLIBPATH.HOSTALIASES`.split(`.`),blockedOverrideOnlyKeys:/* @__PURE__ */ `HOME.GRADLE_USER_HOME.ZDOTDIR.GIT_DIR.GIT_WORK_TREE.GIT_COMMON_DIR.GIT_INDEX_FILE.GIT_OBJECT_DIRECTORY.GIT_ALTERNATE_OBJECT_DIRECTORIES.GIT_NAMESPACE.GIT_SSH_COMMAND.GIT_SSH.GIT_PROXY_COMMAND.GIT_ASKPASS.GIT_SSL_NO_VERIFY.GIT_SSL_CAINFO.GIT_SSL_CAPATH.SSH_ASKPASS.LESSOPEN.LESSCLOSE.PAGER.MANPAGER.GIT_PAGER.EDITOR.VISUAL.FCEDIT.SUDO_EDITOR.PROMPT_COMMAND.HISTFILE.PERL5DB.PERL5DBCMD.OPENSSL_CONF.OPENSSL_ENGINES.PYTHONSTARTUP.WGETRC.CURL_HOME.CLASSPATH.CFLAGS.CGO_CFLAGS.CGO_LDFLAGS.GOFLAGS.MAKEFLAGS.MFLAGS.CORECLR_PROFILER_PATH.PHPRC.PHP_INI_SCAN_DIR.DENO_DIR.BUN_CONFIG_REGISTRY.YARN_RC_FILENAME.HTTP_PROXY.HTTPS_PROXY.ALL_PROXY.NO_PROXY.NODE_TLS_REJECT_UNAUTHORIZED.NODE_EXTRA_CA_CERTS.SSL_CERT_FILE.SSL_CERT_DIR.REQUESTS_CA_BUNDLE.CURL_CA_BUNDLE.DOCKER_HOST.DOCKER_TLS_VERIFY.DOCKER_CERT_PATH.PIP_INDEX_URL.PIP_PYPI_URL.PIP_EXTRA_INDEX_URL.PIP_CONFIG_FILE.PIP_FIND_LINKS.PIP_TRUSTED_HOST.UV_INDEX.UV_INDEX_URL.UV_PYTHON.UV_EXTRA_INDEX_URL.UV_DEFAULT_INDEX.DOCKER_CONTEXT.LIBRARY_PATH.LDFLAGS.CPATH.C_INCLUDE_PATH.CPLUS_INCLUDE_PATH.OBJC_INCLUDE_PATH.GOPROXY.GONOSUMCHECK.GONOSUMDB.GONOPROXY.GOPRIVATE.GOENV.GOPATH.HGRCPATH.PYTHONUSERBASE.RUSTC_WRAPPER.RUSTFLAGS.RUSTUP_DIST_ROOT.RUSTUP_DIST_SERVER.RUSTUP_HOME.RUSTUP_TOOLCHAIN.RUSTUP_UPDATE_ROOT.CARGO_HOME.VIRTUAL_ENV.LUA_PATH.LUA_CPATH.GEM_HOME.GEM_PATH.BUNDLE_GEMFILE.COMPOSER_HOME.CONDA_DEFAULT_ENV.CONDA_PREFIX.CARGO_BUILD_RUSTC_WRAPPER.XDG_CACHE_HOME.XDG_CONFIG_DIRS.XDG_CONFIG_HOME.XDG_DATA_DIRS.XDG_DATA_HOME.XDG_RUNTIME_DIR.XDG_STATE_HOME.AWS_CONFIG_FILE.KUBECONFIG.GOOGLE_APPLICATION_CREDENTIALS.AWS_SHARED_CREDENTIALS_FILE.AWS_WEB_IDENTITY_TOKEN_FILE.AZURE_AUTH_LOCATION.HELM_HOME.ANSIBLE_CONFIG.ANSIBLE_LIBRARY.ANSIBLE_CALLBACK_PLUGINS.ANSIBLE_COLLECTIONS_PATH.ANSIBLE_CONNECTION_PLUGINS.ANSIBLE_FILTER_PLUGINS.ANSIBLE_INVENTORY_PLUGINS.ANSIBLE_LOOKUP_PLUGINS.ANSIBLE_MODULE_UTILS.ANSIBLE_REMOTE_TEMP.ANSIBLE_ROLES_PATH.ANSIBLE_STRATEGY_PLUGINS.R_LIBS_USER.TF_CLI_CONFIG_FILE.TF_PLUGIN_CACHE_DIR.AMQP_URL.AWS_ACCESS_KEY_ID.AWS_CONTAINER_CREDENTIALS_FULL_URI.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.AWS_SECRET_ACCESS_KEY.AWS_SECURITY_TOKEN.AWS_SESSION_TOKEN.AZURE_CLIENT_ID.AZURE_CLIENT_SECRET.DATABASE_URL.GH_TOKEN.GITHUB_TOKEN.GITLAB_TOKEN.MONGODB_URI.NODE_AUTH_TOKEN.NPM_TOKEN.REDIS_URL.SSH_AUTH_SOCK.SYSTEMROOT.WINDIR`.split(`.`),allowedInheritedOverrideOnlyKeys:/* @__PURE__ */ `ALL_PROXY.AWS_CONFIG_FILE.AWS_SHARED_CREDENTIALS_FILE.AWS_WEB_IDENTITY_TOKEN_FILE.AZURE_AUTH_LOCATION.CURL_CA_BUNDLE.DOCKER_CERT_PATH.DOCKER_CONTEXT.DOCKER_HOST.DOCKER_TLS_VERIFY.GIT_PAGER.GOOGLE_APPLICATION_CREDENTIALS.GRADLE_USER_HOME.HISTFILE.HOME.HTTPS_PROXY.HTTP_PROXY.KUBECONFIG.MANPAGER.NODE_EXTRA_CA_CERTS.NODE_TLS_REJECT_UNAUTHORIZED.NO_PROXY.PAGER.REQUESTS_CA_BUNDLE.RUSTUP_DIST_ROOT.RUSTUP_DIST_SERVER.RUSTUP_HOME.RUSTUP_TOOLCHAIN.RUSTUP_UPDATE_ROOT.SSH_AUTH_SOCK.SSL_CERT_DIR.SSL_CERT_FILE.SYSTEMROOT.WINDIR.XDG_CACHE_HOME.XDG_CONFIG_DIRS.XDG_CONFIG_HOME.XDG_DATA_DIRS.XDG_DATA_HOME.XDG_RUNTIME_DIR.XDG_STATE_HOME.ZDOTDIR`.split(`.`),blockedOverridePrefixes:[`GIT_CONFIG_`,`NPM_CONFIG_`,`CARGO_REGISTRIES_`,`TF_VAR_`],blockedPrefixes:[`DYLD_`,`LD_`,`BASH_FUNC_`]};function sortUniqueUppercase(e){return Object.freeze(Array.from(new Set(e.map(e=>e.toUpperCase()))).toSorted((e,t)=>e<t?-1:+(e>t)))}function derivePolicyArrays(e){let t=e.blockedEverywhereKeys??[],n=e.blockedOverrideOnlyKeys??[],r=e.allowedInheritedOverrideOnlyKeys??[],i=new Set(r.map(e=>e.toUpperCase())),a=e.blockedPrefixes??[],s=e.blockedOverridePrefixes??[],c=e.blockedInheritedPrefixes??a;return{blockedInheritedKeys:sortUniqueUppercase([...t,...n.filter(e=>!i.has(e.toUpperCase()))]),blockedInheritedPrefixes:sortUniqueUppercase(c),blockedKeys:sortUniqueUppercase(t),blockedOverrideKeys:sortUniqueUppercase(n),blockedPrefixes:sortUniqueUppercase(a),blockedOverridePrefixes:sortUniqueUppercase(s)}}function loadHostEnvSecurityPolicy(e=Um){let t=derivePolicyArrays(e);return Object.freeze({blockedEverywhereKeys:Object.freeze(e.blockedEverywhereKeys??[]),blockedOverrideOnlyKeys:Object.freeze(e.blockedOverrideOnlyKeys??[]),allowedInheritedOverrideOnlyKeys:Object.freeze(e.allowedInheritedOverrideOnlyKeys??[]),blockedInheritedKeys:t.blockedInheritedKeys,blockedInheritedPrefixes:t.blockedInheritedPrefixes,blockedPrefixes:t.blockedPrefixes,blockedOverridePrefixes:t.blockedOverridePrefixes,blockedKeys:t.blockedKeys,blockedOverrideKeys:t.blockedOverrideKeys})}const Wm=loadHostEnvSecurityPolicy();new Set(Wm.blockedKeys),new Set(Wm.blockedInheritedKeys),new Set(Wm.blockedOverrideKeys),(/* @__PURE__ */ new Set([...Object.keys(resolveNodeServiceIdentityEnvironment()),`OPENCLAW_GATEWAY_SERVICE_PID`])).delete(`OPENCLAW_PROFILE`),new D;function findCaseInsensitiveEnvKey(e,t){if(Object.hasOwn(e,t))return t;let n=t.toUpperCase();return Object.keys(e).find(e=>e.toUpperCase()===n)}const Gm=/* @__PURE__ */ new WeakMap;function resolveAppliedConfigEnvOwnership(e){return{...Gm.get(De(e)),...e===process.env?Km.ownedEnv:{}}}new D;function cloneEnvWithPlatformSemantics(e){let t={...He(e)};return process.platform===`win32`&&(t=new Proxy(t,{deleteProperty(e,t){if(typeof t!=`string`)return Reflect.deleteProperty(e,t);let n=findCaseInsensitiveEnvKey(e,t);return!n||Reflect.deleteProperty(e,n)},get(e,t,n){if(typeof t!=`string`)return Reflect.get(e,t,n);let r=findCaseInsensitiveEnvKey(e,t);return r?e[r]:Reflect.get(e,t,n)},getOwnPropertyDescriptor(e,t){if(typeof t!=`string`)return Reflect.getOwnPropertyDescriptor(e,t);let n=findCaseInsensitiveEnvKey(e,t);if(n)return{configurable:!0,enumerable:!0,value:e[n],writable:!0}},has(e,t){return typeof t==`string`?findCaseInsensitiveEnvKey(e,t)!==void 0:Reflect.has(e,t)},set(e,t,n){return typeof t==`string`?(e[findCaseInsensitiveEnvKey(e,t)??t]=n,!0):Reflect.set(e,t,n)}})),Gm.set(Ee(t),resolveAppliedConfigEnvOwnership(e)),Te(t),t}let Km={ownedEnv:{},sourceConfig:null};const qm=i(Symbol.for(`openclaw.gatewayServiceInstallation`),()=>new D);function getGatewayServiceInstallation(){return qm.getStore()?.installation}function isGatewayExternallySupervised(e=process.env){return e.OPENCLAW_SUPERVISOR_MODE?.trim().toLowerCase()===`external`}const Jm=i(Symbol.for(`openclaw.stateDatabaseSchemaPolicies`),()=>({scopes:new D,existingDatabases:/* @__PURE__ */ new WeakMap,hasAdmittedExistingDatabase:!1}));function canonicalPath(e){let t=resolveDatabasePath({path:e});try{return wt(zr.native(t))}catch(e){if(oe(e,`ENOENT`))return t;throw e}}function assertSchemaScopeActive(e){if(e&&!e.active)throw Error(`Existing shared-state schema admission has ended.`)}function getExistingOpenClawStateSchemaPath(){let e=Jm.scopes.getStore();return assertSchemaScopeActive(e),e?.path}function captureOpenClawStateSchemaReadAdmission(e){let t=Jm.scopes.getStore();if(t)return isExistingOpenClawStateSchema(e),{path:t.path,assertCurrent:()=>assertSchemaScopeActive(t)}}function isExistingOpenClawStateSchema(e,t){let n=getExistingOpenClawStateSchemaPath(),r=Jm.scopes.getStore(),i=t&&Jm.existingDatabases.get(t);if(!r&&!i)return!1;let a=resolveDatabasePath({path:e}),s=n!==void 0&&(n===a||r?.canonicalPath===a||r?.canonicalPath===canonicalPath(a));if(n&&!s)throw Error(`Existing shared-state schema admission is bound to ${n}, not ${e}.`);if(i&&(!s||i!==r?.canonicalPath))throw Error(`Shared-state database ${e} was admitted without schema repair; close its existing handle before ordinary admission.`);return s}function assertExistingOpenClawStateSchemaCacheAdmission(e,t){let n=getExistingOpenClawStateSchemaPath();if(!Jm.hasAdmittedExistingDatabase)return;let r=Jm.scopes.getStore(),i=r?resolveDatabasePath({path:e}):void 0,a=r&&(n===i||r.canonicalPath===i)?r.canonicalPath:void 0;for(let n of[t.cachedDatabases,t.retainedDatabaseHandles])for(let{db:t}of n.values()){let n=Jm.existingDatabases.get(t);n&&t.isOpen&&(a??=canonicalPath(e),n===a&&isExistingOpenClawStateSchema(e,t))}}function assertOpenClawStateSchemaRepairAllowed(e){if(isExistingOpenClawStateSchema(e))throw Error(`Shared-state schema repair is owned by the existing installation at ${e}; run openclaw doctor --fix with that installation. The managed node retries automatically.`)}function captureSqliteWorkerStateContext(e){return{databaseEngineSelection:e.databaseEngineSelection??vr(),environment:{...e.environment},initializationCronDefaultStoreKey:e.initializationCronDefaultStoreKey,...e.initializationEnvironment?{initializationEnvironment:{...e.initializationEnvironment}}:{},...e.initializationAgentPaths?{initializationAgentPaths:[...e.initializationAgentPaths]}:{},existingSchemaPath:e.existingSchemaPath,gatewayServiceInstallation:e.gatewayServiceInstallation,...e.stateIntegrity?{stateIntegrity:e.stateIntegrity}:{},artifactPreservingReads:e.artifactPreservingReads,liveStateReads:e.liveStateReads,...e.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.scheduledMaintenanceSuspension}:{}}}function sqliteWorkerRequestBytes(e,t,n){let r=t?.initializationAgentPaths?.reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0)??0;return[t?.environment,t?.initializationEnvironment].reduce((e,t)=>Object.entries(t??{}).reduce((e,[t,n])=>e+Buffer.byteLength(t,`utf8`)+Buffer.byteLength(n??``,`utf8`),e),e.byteLength+Buffer.byteLength(JSON.stringify(t?.databaseEngineSelection)??``,`utf8`)+Buffer.byteLength(JSON.stringify(t?.gatewayServiceInstallation)??``,`utf8`)+(n?.byteLength??0)+r+Buffer.byteLength(t?.initializationCronDefaultStoreKey??``,`utf8`)+(t?.scheduledMaintenanceSuspension?.byteLength??0))}i(Symbol.for(`openclaw.sqliteWorkerStateContext`),()=>new D);const Ym=/* @__PURE__ */ new WeakMap;function readCanonicalTableDefinition(e,t){if(!/^CREATE TABLE\b/iu.test(e)||Vn(e,/\bAS\b/giu))return;let n=In(e,t);return[...n.columns.values()].every(e=>{let t=Dn(e,0);return t?.keyword!==`CONSTRAINT`&&/^[a-z_][a-z0-9_]*$/u.test(t?.raw??``)})?n:void 0}function tableHasColumn(e,t,n){return readTableColumns(e,t).has(n)}function readTableColumns(e,t){if(C(e)){let n=getPostgresPhysicalFacts(e);if(!n){let n=e.prepare(`SELECT a.attname AS name FROM pg_catalog.pg_attribute a
        JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
        WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?
          AND a.attnum > 0 AND NOT a.attisdropped
        ORDER BY a.attnum`).all(t);return new Set(n.map(e=>String(e.name)))}return new Set(n.catalog.flatMap(e=>e.table===t&&e.kind===`column`&&e.value&&typeof e.value==`object`&&`name`in e.value&&typeof e.value.name==`string`?[e.value.name]:[]))}let n=getAdmittedSqliteSchemaFacts(e),r=n?.tableSql.get(t);if(n&&!r&&![...n.tables,...n.views].some(e=>e.toLowerCase()===t.toLowerCase()))return/* @__PURE__ */ new Set;if(n&&r){let e=Ym.get(n),i=e?.get(t);if(i)return i;let a=readCanonicalTableDefinition(r,t);if(a){let r=new Set(a.columns.keys());return e||(e=/* @__PURE__ */ new Map,Ym.set(n,e)),e.set(t,r),r}}let i=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(i.flatMap(e=>typeof e.name==`string`?[e.name]:[]))}function classifySqliteTableReadError(e,t,n,r){if(C(e)||ln(r)!==1)return r;try{let i=readTableColumns(e,t);if(i.size>0&&n.some(e=>!i.has(e)))return new SqliteSchemaMismatchError(`SQLite table ${t} is missing required columns; run openclaw doctor --fix to repair it.`,{cause:r})}catch{}return r}function tablePrimaryKeyColumns(e,t){if(C(e)){let n=getPostgresPhysicalFacts(e);if(!n)return e.prepare(`SELECT a.attname AS name FROM pg_catalog.pg_index i
        JOIN pg_catalog.pg_class c ON c.oid = i.indrelid
        CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, position)
        JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.attnum
        WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ? AND i.indisprimary
        ORDER BY k.position`).all(t).map(e=>String(e.name));let r=n.catalog.find(e=>e.table===t&&e.kind===`primaryKey`)?.value;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}let n=getAdmittedSqliteSchemaFacts(e)?.tableSql.get(t),r=n&&readCanonicalTableDefinition(n,t);if(r){let e=r.constraints.find(e=>{let t=Dn(e,0);return t&&yr(e,t)===`PRIMARY`});if(!e)return[...r.columns].flatMap(([e,t])=>Vn(t,/\bPRIMARY\s+KEY\b/giu)?[e]:[]);let t=_r(e,`(`),n=Tr(e.slice(t+1,Rn(e,t))).map(e=>rr(Dn(e,0)?.raw??``));if(n.every(e=>r.columns.has(e)))return[...new Set(n)]}return e.prepare(`PRAGMA table_info(${t})`).all().filter(e=>Number(e.pk??0)>0&&typeof e.name==`string`).toSorted((e,t)=>Number(e.pk??0)-Number(t.pk??0)).map(e=>e.name)}function tableExists(e,t){if(C(e)){let n=getPostgresPhysicalFacts(e);return n?n.catalog.some(e=>e.table===t&&e.kind===`table`):e.prepare(`SELECT 1 AS present FROM pg_catalog.pg_class
      WHERE relnamespace = current_schema()::regnamespace AND relname = ? AND relkind IN ('r', 'p')`).get(t)?.present===1}let n=getAdmittedSqliteSchemaFacts(e);return n?n.tables.has(t):executeWithCachedStatement(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}function ensureColumn(e,t,n){let r=n.trim().split(/\s+/,1)[0];return!r||!tableExists(e,t)||tableHasColumn(e,t,r)?!1:(e.exec(`ALTER TABLE ${t} ADD COLUMN ${n};`),!0)}function resolveLegacyCronDefaultStoreKey(e){return E.resolve(Be(e),`cron`,`jobs.json`)}function captureOpenClawStateReadContextWithAdmission(e,t,n,r){let i=captureOpenClawStateSchemaReadAdmission(e),a=t(e,r),s=getGatewayServiceInstallation(),c=a.captureIntegrity?.(),l=a.assertCurrent,u=a,runInCapturedSchemaScope;if(i){let e=D.snapshot();u={databasePath:a.databasePath,coordinationKey:a.coordinationKey,get identity(){return a.identity},captureIntegrity:a.captureIntegrity,assertCurrent(){a.assertCurrent(),i.assertCurrent()}},runInCapturedSchemaScope=t=>e(()=>(u.assertCurrent(),t()))}return{databaseEngineSelection:vr(),maintenanceScope:getOpenClawDatabaseMaintenanceScope(),admission:u,assertPublicationCurrent:l,existingSchemaPath:i?.path,gatewayServiceInstallation:s&&n(s.databasePath)?.key===a.identity.key?s:void 0,stateIntegrity:c,runInCapturedSchemaScope,artifactPreservingReads:isArtifactPreservingStateRead(`agent`,e)||void 0,liveStateReads:isLiveStateRead()||void 0}}function captureOpenClawStateReadWorkerContextWithAdmission(e,t,n){let r=e.env??process.env,i=process.platform===`win32`?cloneEnvWithPlatformSemantics(r):r,a={OPENCLAW_STATE_DIR:ze(i),...isGatewayExternallySupervised(i)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};return{...captureOpenClawStateReadContextWithAdmission(e.path??resolveOpenClawStateSqlitePath(a),t,n),environment:a}}function captureOpenClawStateWorkerContextWithAdmission(e,t,n){let r=captureOpenClawStateReadWorkerContextWithAdmission(e,t,n);return{...r,initializationCronDefaultStoreKey:resolveLegacyCronDefaultStoreKey(e.env??process.env),initializationEnvironment:g([e.env??process.env,{OPENCLAW_STATE_DIR:void 0,OPENCLAW_SUPERVISOR_MODE:void 0},r.environment]),...e.initializationAgentPaths?{initializationAgentPaths:e.initializationAgentPaths.map(e=>E.resolve(e))}:{}}}function createStateDatabaseWalOwner({cachedDatabases:e,retainedDatabaseHandles:t,databaseIdentities:n,asyncResources:r},i,a){return{ownRetirement(e,t){let n={admission:{identity:a(e)},close:t},i=r.register(n);return getOpenClawDatabaseMaintenanceResourceScope(e.db)?.own(n,`shared-references`,()=>n.close()),i},async stop(r,i){let a=/* @__PURE__ */ new Set([...t.values(),...e.values()]);await Promise.all([...a].filter(e=>r===void 0||e.path===r||i!==void 0&&n.get(e.db)?.key===i.key).flatMap(({walMaintenance:e})=>e?[e.stop()]:[]))},register(t,n,a,s){if(!ni||C(t.db))return;let c=captureOpenClawStateWorkerContextWithAdmission({path:t.path,env:s},()=>a,r.knownIdentity),l=new AbortController,u,cancel=()=>{if(l.abort(),!u)f();else return u.then(()=>void 0,()=>void 0)},d={admission:{identity:n},async close(){cancel(),await t.walMaintenance.stop(),f()}},f=r.register(d),run=async r=>{let a=getOpenClawDatabaseMaintenanceResourceScope(t.db),s={...c,maintenanceScope:a},assertCurrent=()=>{if(l.signal.throwIfAborted(),s.admission.assertCurrent(),a?.assertAdmission(),getOpenClawDatabaseMaintenanceResourceScope(t.db)!==a||e.get(t.path)!==t||!t.db.isOpen)throw new StateDatabaseReadAdmissionInvalidatedError(`Shared-state WAL maintenance owner changed`)},u,d=!1;try{assertCurrent(),u=i(t);let{runOpenClawStateWorkerOperation:e}=await import(`./service-child-group-anchor-openclaw-state-worker-store-CV-w5uH1.mjs`);return assertCurrent(),await e(s,e=>e.execute({type:`database.walMaintenance`,input:r},{signal:l.signal}),{existingOnly:!0,assertCurrent,createAdmission:()=>({nativeLocations:[t.path,n.canonicalPath],databaseIdentity:{databasePath:t.path,key:n.key,birthtime:n.birthtime},admission:dr((e,t)=>{if(assertCurrent(),!t())throw new StateDatabaseReadAdmissionInvalidatedError(`Shared-state WAL maintenance authority expired`);d=!0})})})}catch(e){if(!d&&(isStateDatabaseReadAdmissionInvalidatedError(e)||l.signal.aborted&&qe(e)))return;throw e}finally{u?.()}};registerSqliteWalWorkerMaintenance(t.db,e=>{if(l.signal.aborted)return Promise.resolve(void 0);let t=run(e);return u=t,t.finally(()=>{u===t&&(u=void 0),l.signal.aborted&&f()})},cancel)},readHealth(){let t=e.get(E.resolve(resolveOpenClawStateSqlitePath()));return t?.db.isOpen?t.walMaintenance.health:void 0}}}const Xm=i(Symbol.for(`openclaw.stateNativeIdentities`),()=>/* @__PURE__ */ new WeakMap);function readTrackedStateDatabaseIdentity(e){return Xm.get(kt(e))}function openTrackedStateDatabase(e,t){let n=openTrackedStateDatabaseResult(e,t);if(n.status===`unavailable`)throw n.error;return n.database}function openTrackedStateDatabaseResult(e,t){assertStateDatabaseAccessAllowed(e);try{t?.expectedIdentity!==void 0&&Or(e,t.expectedIdentity);let n=t?.existingOnly||t?.expectedIdentity!==void 0?resolveExistingSqliteFileUri(e):e,r=t?.readOnly?{readOnly:!0,timeout:t.timeout}:{enableForeignKeyConstraints:t?.enableForeignKeyConstraints},i=xt(e),a=gn(()=>openNodeSqliteDatabase(n,r));try{assertStateDatabaseAccessAllowed(e),i.key.startsWith(`file:`)&&Or(e,i.key,i.birthtime);let t=i.key.startsWith(`file:`)?i:xt(e);if(t.key.startsWith(`file:`)){Xm.set(a,t);let e=registerNodeSqliteDisposeCallback(a,()=>{Xm.delete(a),e()})}}catch(e){throw a.close(),e}return{status:`available`,database:a}}catch(e){return{status:`unavailable`,error:e}}}function closeTrackedStateDatabase(e){e.isOpen&&e.close()}function closeStateDatabaseHandle(e,t){try{var n=_usingCtx();let r=[];if(C(e.db)){for(let t of[e.db,e.db.anchor]){if(t===e.db.anchor&&e.db.isOpen)break;try{t.isOpen&&t.close()}catch(e){r.push(e)}}let t=e.db.isOpen||e.db.anchor.isOpen;if(!t)try{e.afterClose?.()}catch(e){r.push(e),t=!0}return{errors:r,cleanupPending:t}}let i=n.u(nr(e.db)),a=isSqliteWalWorkerMaintained(e.db),s=e.walMaintenance?.health?.state===`error`,c=!1;try{e.db.isOpen&&!a&&setSqliteBusyTimeout(e.db,0),c=e.walMaintenance?.close(t)===!0&&t?.checkpointMode!==`PASSIVE`}catch(e){r.push(e)}try{clearNodeSqliteKyselyCacheForDatabase(e.db)}catch(e){r.push(e)}try{closeTrackedStateDatabase(e.db)}catch(e){r.push(e)}let l=!1;if(!e.db.isOpen)try{e.afterClose?.()}catch(e){r.push(e),l=!0}return r.length===0&&!l&&t?.checkpointMode!==`PASSIVE`&&(c||a&&!s)&&i.publish(),{errors:r,cleanupPending:l}}catch(e){n.e=e}finally{n.d()}}const Zm=i(Symbol.for(`openclaw.stateIntegrityBindings`),()=>/* @__PURE__ */ new WeakMap),Qm={name:`state.integrity`,lifetime:`process`,read:e=>e===!0||void 0};function hasStateDatabaseIntegrityAdmission(e){return!!(getStateRuntimeSchemaAdmission(e)||b(e,Qm))}function assertStateDatabaseIntegrityOnce(e,t){hasStateDatabaseIntegrityAdmission(e)||(assertSqliteIntegrity(e,t),w(e,Qm,!0))}function invalidate(e){let t=Atomics.load(e,0);for(;t>=0n;){let n=Atomics.compareExchange(e,0,t,t+1n);if(n===t)return;t=n}}function invalidateOpenClawStateRuntimeIntegrity(e){Er(e);let t=Zm.get(e);t&&(invalidate(new BigInt64Array(t.revision)),invalidate(new BigInt64Array(t.lifetimeRevision)))}function bind(e,t){if(Zm.get(e)?.revision===t.revision)return;Zm.get(e)?.release();let n=new BigInt64Array(t.revision),r=registerSqliteSchemaMutationListener(e,()=>invalidate(n)),release=()=>{r(),i()},i=registerNodeSqliteDisposeCallback(e,e=>{e===`replace`&&(invalidate(n),invalidate(new BigInt64Array(t.lifetime.revision))),release()});Zm.set(e,{revision:t.revision,lifetimeRevision:t.lifetime.revision,release})}function assertOpenClawStateRuntimeIntegrity(e,t,n,r,i=`verify`){let a=r&&readTrackedStateDatabaseIdentity(e);if(!r||!a||!a.key.startsWith(`file:`)||a.key!==r.identity.key||a.birthtime!==r.identity.birthtime){if(i===`require-proof`)throw Error(`Shared-state reader requires current worker integrity proof`);assertStateDatabaseIntegrityOnce(e,t);return}bind(e,r);let s=new BigInt64Array(r.revision),c=new BigInt64Array(r.proof),l=BigInt.asIntN(64,BigInt(n.userVersion>>>0)<<32n|BigInt(n.schemaVersion>>>0)),u=Atomics.load(c,0);if(Atomics.load(s,0)===r.epoch&&u!==-1n){if(u===l&&Atomics.load(s,0)===r.epoch&&hasStateDatabaseIntegrityAdmission(e))return;invalidate(s)}if(i===`require-proof`)throw Error(`Shared-state reader requires current worker integrity proof`);assertStateDatabaseIntegrityOnce(e,t);let publish=()=>{Atomics.load(s,0)===r.epoch&&Atomics.store(c,0,l)};return()=>{e.isTransaction?Jt(e,{commit:publish}):publish()}}function retainSqliteDatabaseRemovalExclusion(e,t){if(!Rr(e))return;let n=openNodeSqliteDatabase(resolveExistingSqliteFileUri(e)),close=()=>{if(!n.isOpen)return;let e=[];try{n.isTransaction&&n.exec(`ROLLBACK`)}catch(t){e.push(t)}try{n.close()}catch(t){e.push(t)}it(e,`SQLite state removal exclusion cleanup failed.`)};try{t.own(n,`shared-handles`,close),n.exec(`PRAGMA busy_timeout = 0; PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE;`)}catch(e){try{close()}catch(t){throw Wt([e,t],`SQLite state removal admission and cleanup both failed.`,e)}if(It(e))throw Error(`Cannot remove OpenClaw state directory while another SQLite connection is active`,{cause:e});let t=ln(e);if(t!==11&&t!==26)throw e;return}process.platform===`win32`&&close()}function createOpenClawStateSnapshotOwnerRegistry(){let e=/* @__PURE__ */ new WeakMap;return{register(t,n){C(t.db)||e.set(t.db,registerLiveSqliteSnapshotOwner({database:t.db,databasePath:t.path,assertCurrent:()=>{if(n()!==t||!t.db.isOpen)throw Error(`OpenClaw state snapshot owner is no longer current`)}}))},release(t){C(t)||(e.get(t)?.(),e.delete(t))}}}const $m=i(Symbol.for(`openclaw.stateSnapshotOwners`),createOpenClawStateSnapshotOwnerRegistry),eh=i(Ya,()=>({cachedDatabases:/* @__PURE__ */ new Map,retainedDatabaseHandles:/* @__PURE__ */ new Map,idleTimers:/* @__PURE__ */ new WeakMap,idleReferences:/* @__PURE__ */ new WeakMap,unregisterRetainedExitClose:void 0,databaseIdentities:/* @__PURE__ */ new WeakMap,borrowers:/* @__PURE__ */ new WeakMap,databaseLifecycleListeners:/* @__PURE__ */ new Set,terminalOpenLatch:createSqliteTerminalOpenLatch({closeByPath:(e,t)=>mh.closeTerminalFailure(e,t)}),asyncResources:createOpenClawStateDatabaseAsyncLifecycle()}),()=>closeOpenClawStateDatabaseAsync(),`shared-state`),{cachedDatabases:Z,retainedDatabaseHandles:th,idleTimers:nh,idleReferences:rh,databaseIdentities:ih,borrowers:ah,databaseLifecycleListeners:oh,terminalOpenLatch:sh,asyncResources:Q}=eh,{touch:ch,retain:lh}=createStateDatabaseIdleRetirement(eh,retireOpenClawStateDatabaseHandle),{register:uh,readHealth:dh,ownRetirement:fh,stop:ph}=createStateDatabaseWalOwner(eh,lh,requireOpenClawStateDatabaseIdentity);function notifyOpenClawStateDatabaseLifecycle(e){let t=e.kind===`open-error`?{...e,identity:e.identity??Q.knownIdentity(e.path)}:e;for(let e of oh)e(t)}function notifyOpenClawStateDatabaseClosed(e){notifyOpenClawStateDatabaseLifecycle({kind:`closed`,path:e.path,identity:requireOpenClawStateDatabaseIdentity(e)})}function requireOpenClawStateDatabaseIdentity(e){let t=ih.get(e.db);if(!t)throw Error(`Published shared-state owner has no recorded database identity`);return t}const mh=createStateDatabaseCacheAdmission({cachedDatabases:Z,evict:evictCachedOpenClawStateDatabase,invalidate:e=>Q.invalidate(e),notifyTerminalFailure:(e,t)=>notifyOpenClawStateDatabaseLifecycle({kind:`terminal-failure`,path:e,error:t,identity:Q.knownIdentity(e)})});function registerOpenClawStateDatabaseLifecycleListener(e){oh.add(e);for(let t of Z.values())t.db.isOpen&&e({kind:`opened`,database:t,identity:requireOpenClawStateDatabaseIdentity(t)});return()=>oh.delete(e)}function registerOpenClawStatePathCacheInvalidation(e){return registerOpenClawStateDatabaseLifecycleListener(t=>{if(t.kind!==`opened`)for(let[n,r]of e)r.path===(t.identity?.canonicalPath??t.path)&&e.delete(n)})}function retainStateDatabaseClose(e){th.set(e.db,e),eh.unregisterRetainedExitClose??=Ve(closeOpenClawStateDatabase)}function ownMaintenanceStateDatabaseHandle(e){getOpenClawDatabaseMaintenanceScope()?.own(e.db,`shared-handles`,async()=>{let t=getOpenClawDatabaseMaintenanceScope();t&&isOpenClawDatabaseMaintenanceResourceOwned(e.db,t)&&(Z.get(e.path)===e||th.get(e.db)===e)&&(await e.walMaintenance?.stop(),isOpenClawDatabaseMaintenanceResourceOwned(e.db,t)&&(Z.get(e.path)===e||th.get(e.db)===e)&&retireOpenClawStateDatabaseHandle(e,!1))})}function closeUnpublishedOpenClawStateDatabaseHandle(e){let t=closeOpenClawStateDatabaseHandle(e);return th.get(e.db)===e&&ownMaintenanceStateDatabaseHandle(e),t}const{retain:hh,borrowForRead:gh,retainForIndependentRead:_h}=createStateDatabaseRetainer(eh,{assertOpen(e,t,n){assertOpenClawStateDatabaseOpenAllowed(e,t,n),assertExistingOpenClawStateSchemaCacheAdmission(e,eh)},capture:e=>Q.capture(e),retire:retireOpenClawStateDatabaseHandle,retainFailed:retainStateDatabaseClose,ownRetirement:fh,touch:ch});function closeOpenClawStateDatabaseHandle(e,t){clearTimeout(nh.get(e.db)),nh.delete(e.db);try{assertStateDatabaseBorrowersReleased(ah.get(e.db),e.path)}catch(n){let r=ah.get(e.db);return r&&(r.retiring=!0,r.retirement={ordinary:!0,isCurrent:()=>!0,retire:()=>{it(closeOpenClawStateDatabaseHandle(e,t),`OpenClaw state database cleanup failed for ${e.path}.`),r.cleanupComplete=!0,ah.delete(e.db)}}),retainStateDatabaseClose(e),[n]}rh.delete(e.db),$m.release(e.db);let{errors:n,cleanupPending:r}=closeStateDatabaseHandle(e,t);return e.db.isOpen||r?retainStateDatabaseClose(e):th.delete(e.db),Z.get(e.path)?.db===e.db&&Z.delete(e.path),th.size===0&&(eh.unregisterRetainedExitClose?.(),eh.unregisterRetainedExitClose=void 0),n}function evictCachedOpenClawStateDatabase(e){return C(e.db)||invalidateOpenClawStateRuntimeIntegrity(e.db),Z.get(e.path)===e&&(Q.invalidate(e.path),Z.delete(e.path),notifyOpenClawStateDatabaseClosed(e),closeOpenClawStateDatabaseHandle(e,{checkpointMode:`PASSIVE`}),!0)}function evictOpenClawStateDatabaseAfterCorruption(e,t){return Dt(t)&&evictCachedOpenClawStateDatabase(e)}function publishOpenClawStateDatabase(e,t){let{db:n,path:r}=e,{identity:i,admission:a}=Q.publish(r);return ih.set(n,readTrackedStateDatabaseIdentity(n)??i),Z.set(r,e),uh(e,i,a,t),ch(e),$m.register(e,()=>Z.get(r)),ownMaintenanceStateDatabaseHandle(e),notifyOpenClawStateDatabaseLifecycle({kind:`opened`,database:e,identity:i}),C(n)||registerNodeSqliteKyselyQueryErrorHandler(n,t=>{!n.isTransaction&&Dt(t)&&evictCachedOpenClawStateDatabase(e)}),sh.clear(r),e}function getCachedOpenClawStateDatabase(e,t){let n=resolveDatabasePath({path:e}),r=sh.get(n);if(r)throw r;let i=readCachedOpenClawStateDatabase(n,t?.readOnly===!0);return i&&ch(i),i}function readCachedOpenClawStateDatabase(e,t){let n=getOpenClawDatabaseMaintenanceScope();t?n?.assertReadAdmission():n?.assertAdmission(),assertExistingOpenClawStateSchemaCacheAdmission(e,eh);let r=Z.get(e);if(r&&ah.get(r.db)?.retiring)throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);return r}function prepareOpenClawStateCachedRead(e){let t=resolveDatabasePath({path:e});getCachedOpenClawStateDatabase(t,{readOnly:!0});let n=Q.capture(t);return()=>(n.assertCurrent(),readCachedOpenClawStateDatabase(t,!0))}function withCachedOpenClawStateDatabase(e,t,n){let r=getCachedOpenClawStateDatabase(e,t);return r&&mh.read(r,n)}function getOpenClawStateDatabaseIfOpenAtPath(e){let t=getCachedOpenClawStateDatabase(e);return observeOpenClawDatabaseMaintenanceResource(t?.db.isOpen?t.db:void 0),t?.db.isOpen?t:void 0}function closeStaleCachedOpenClawStateDatabase(e){if(Z.get(e.path)!==e)return;Q.invalidate(e.path);let t=closeOpenClawStateDatabaseHandle(e);notifyOpenClawStateDatabaseClosed(e),it(t,`Stale OpenClaw state database cleanup failed for ${e.path}.`)}function recordOpenClawStateDatabaseOpenFailure(e,t){sh.record(resolveDatabasePath({path:e}),t)}function clearOpenClawStateDatabaseOpenFailure(e){let t=resolveDatabasePath({path:e});sh.clear(t),Q.invalidate(t),notifyOpenClawStateDatabaseLifecycle({kind:`failure-cleared`,path:t,identity:Q.knownIdentity(t)})}async function getOpenClawStateDatabaseTerminalFailureAsync(e,t){return e.admission.assertCurrent(),t?.throwIfAborted(),sh.get(e.admission.databasePath)}function assertOpenClawStateDatabaseOpenAllowed(e,t,n){let r=resolveDatabasePath({path:e});t===`cached-read`&&n?n.assertReadAllowed():(t===`cached-read`?assertStateDatabaseReadAllowed:assertStateDatabaseAccessAllowed)(e);let{identity:i}=Q.capture(r),a=sh.get(r);if(a)throw a;for(let t of th.values())if(ah.get(t.db)?.retiring&&(t.path===r||ih.get(t.db)?.key===i.key))throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`)}function recordOpenClawStateDatabaseLifecycleOpenError(e,t){notifyOpenClawStateDatabaseLifecycle({kind:`open-error`,path:resolveDatabasePath({path:e}),error:t})}function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(e,t,n,r){assertOpenClawStateDatabaseOpenAllowed(e);let i;try{i=readOpenClawDatabaseQuarantineFailure(`state`,e,{env:t,refreshIdentity:r})}catch(e){if(!(e instanceof Ga))throw e;n?.(e)}if(i?.cause instanceof Ga&&n?.(i.cause),i)throw mh.closeTerminalFailure(e,i),i}function retireOpenClawStateDatabaseHandle(e,t=!0,n){assertStateDatabaseBorrowersReleased(ah.get(e.db),e.path);let r=ah.get(e.db);try{let r=Z.get(e.path)?.db===e.db;t&&Q.invalidate(e.path);let i=closeOpenClawStateDatabaseHandle(e,n);if(r&&t)try{notifyOpenClawStateDatabaseClosed(e)}catch(e){i.push(e)}it(i,`OpenClaw state database cleanup failed for ${e.path}.`)}catch(t){throw r&&retainStateDatabaseClose(e),t}r&&(r.cleanupComplete=!0,ah.delete(e.db))}function stateDatabaseHandlesAt(e,t){return[.../* @__PURE__ */ new Set([...th.values(),...Z.values()])].filter(n=>e===void 0||n.path===e||t!==void 0&&ih.get(n.db)?.key===t.key)}function retireOpenClawStateDatabaseHandles(e,t,n){let r=stateDatabaseHandlesAt(e,n),i=[];for(let e of r)try{retireOpenClawStateDatabaseHandle(e,!0,t)}catch(e){i.push(e)}return it(i,`OpenClaw state database cleanup failed.`),r.length>0}function closeOpenClawStateDatabaseByPath(e,t){return retireOpenClawStateDatabaseHandles(resolveDatabasePath({path:e}),t,Q.identity(e))}function sealOpenClawStateDatabaseByPath(e){let t=resolveDatabasePath({path:e}),n=Q.identity(e);return!stateDatabaseHandlesAt(t,n).some(e=>ah.get(e.db)?.references.size)&&retireOpenClawStateDatabaseHandles(t,void 0,n)}function closeOpenClawStateDatabase(e){retireOpenClawStateDatabaseHandles(void 0,e)}const vh=Q.register;function registerOpenClawStatePathAsyncResource(e,t){return vh({close(n){return!n||n.key===e.identity.key||n.canonicalPath===e.identity.canonicalPath?t():Promise.resolve()}})}const yh=Q.capture,bh=Q.integrity;function publishOpenClawStateDatabaseWorkerAdmission(e,t){t&&e.assertCurrent(),Q.publish(e.databasePath,t),e.assertCurrent(),sr(e.databasePath,e.identity)}function closeOpenClawStateDatabaseByPathAsync(e,t){let n=resolveDatabasePath({path:e});return Q.close(n,async e=>(await ph(n,e),retireOpenClawStateDatabaseHandles(n,t,e)))}function closeOpenClawStateDatabaseWorkersByPathAsync(e){return Q.close(resolveDatabasePath({path:e}),()=>!1)}async function closeOpenClawStateDatabaseAsync(e){await Q.close(void 0,async()=>(await ph(),retireOpenClawStateDatabaseHandles(void 0,e)))}async function joinOpenClawStateDatabaseBorrowers(){await Promise.all(stateDatabaseHandlesAt().map(e=>joinStateDatabaseBorrowersReleased(ah.get(e.db),e.path)))}async function releaseOpenClawStateDatabaseCustody(){await closeOpenClawStateDatabaseAsync(),br()}function isOpenClawStateDatabaseOpen(e){return e===void 0?Array.from(Z.values()).some(e=>e.db.isOpen):Z.get(resolveDatabasePath({path:e}))?.db.isOpen===!0}function closeOpenClawStateDatabaseForTest(){closeOpenClawStateDatabase(),sh.clearAll()}function assertPublishedOpenClawStateDatabaseLifecycle(){if(n(Ya)!==eh)throw Error(`OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle`)}const xh={assertOpenClawStateDatabaseFreshOpenAllowedAtPath,assertOpenClawStateDatabaseOpenAllowed,clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase,closeOpenClawStateDatabaseByPath,sealOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseHandle,closeUnpublishedOpenClawStateDatabaseHandle,closeStaleCachedOpenClawStateDatabase,evictCachedOpenClawStateDatabase,evictOpenClawStateDatabaseAfterCorruption,getCachedOpenClawStateDatabase,peekOpenClawStateDatabaseConnection:e=>Z.get(resolveDatabasePath({path:e}))?.db,withCachedOpenClawStateDatabase,getOpenClawStateDatabaseRecordedFailure:sh.peek,getOpenClawStateDatabaseIfOpenAtPath,getKnownOpenClawStateDatabaseIdentity:Q.knownIdentity,isOpenClawStateDatabaseOpen,isOpenClawStateDatabaseSchemaReady:e=>Z.get(e.path)===e&&e.db.isOpen,publishOpenClawStateDatabase,recordOpenClawStateDatabaseOpenFailure,recordOpenClawStateDatabaseLifecycleOpenError,async reconcileFailedWorkerAdmission(e){await Q.retireChangedAdmission(e),e.assertCurrent()},touchStateDatabase:ch};async function prepareOpenClawStateDatabaseRemoval(e,t){let n=resolveDatabasePath({path:e}),r=getOpenClawDatabaseMaintenanceScope();if(!r?.ownsSchemaMaintenance)throw Error(`State removal requires the installation's maintenance owner`);r.assertAdmission();let i=Q.holdExclusion(n);try{await closeOpenClawStateDatabaseByPathAsync(n),r.assertOwnerCurrent(),retainSqliteDatabaseRemovalExclusion(n,r),r.assertOwnerCurrent()}catch(e){throw i(),e}let a=!0;return{assertCurrent(){if(!a)throw Error(`State removal admission has been released`);t()},release(){a&&(a=!1,i())}}}const Sh=36e5,Ch=/* @__PURE__ */ new Map;function closeBridge(e){e.port.close()}function closeIdleBridges(){let e=[...Ch.values()];Ch.clear(),unwatch();for(let{bridge:t,timeout:n}of e)clearTimeout(n),closeBridge(t)}function unwatch(){Ch.size||(process.off(`beforeExit`,closeIdleBridges),process.off(`exit`,closeIdleBridges))}function removeIdleBridge(e){let t=Ch.get(e);return Ch.delete(e),t&&clearTimeout(t.timeout),unwatch(),t}function takeIdlePostgresBridge(e){let t=removeIdleBridge(e);if(t){if(Atomics.load(t.bridge.service,1))closeBridge(t.bridge);else return{bridge:t.bridge,validate:Date.now()-t.releasedAt>=1e3}}}function retainIdlePostgresBridge(e,t){let n=removeIdleBridge(e);if(n&&closeBridge(n.bridge),Ch.size===2){let e=Ch.keys().next().value;closeBridge(removeIdleBridge(e).bridge)}Ch.size||(process.once(`beforeExit`,closeIdleBridges),process.once(`exit`,closeIdleBridges));let r=setTimeout(()=>{let t=removeIdleBridge(e);t&&closeBridge(t.bridge)},18e4);r.unref(),Ch.set(e,{bridge:t,timeout:r,releasedAt:Date.now()})}function postgresBridgeReuseKey(e){return sha256Hex(JSON.stringify([e.url,e.lockTimeoutMs??6e4,e.statementTimeoutMs??9e4,e.readOnly===!0]))}function preparedBridgeKey(e){return JSON.stringify([postgresBridgeReuseKey(e),e.schema,e.storeId])}function createPostgresBridge(e){let{port1:t,port2:n}=new ti,r=new SharedArrayBuffer(8),i=new Int32Array(r),{port:a,signal:s,nextStep:c}=Wn(),l=new Int32Array(s);if(Atomics.load(l,1)){t.close(),n.close();let e=/* @__PURE__ */ Error(`PostgreSQL I/O service is unavailable.${c?` Run ${c}.`:``}`);throw Un(e),e}try{a.postMessage({connection:{port:n,signal:r,url:e.url,schema:e.schema,connectTimeoutMs:6e4,lockTimeoutMs:e.lockTimeoutMs??6e4,statementTimeoutMs:e.statementTimeoutMs??9e4,readOnly:e.readOnly===!0}},[n])}catch(e){throw t.close(),n.close(),e}return t.unref(),{port:t,control:i,service:l,nextStep:c,requestId:0}}const wh=new D;function findPreparedBridge(e){let t=wh.getStore();for(;t;){if(t.key===e&&t.bridge&&!Atomics.load(t.bridge.service,1))return t;t=t.parent}}function takePreparedPostgresBridge(e){let t=findPreparedBridge(preparedBridgeKey(e)),n=t?.bridge;return t&&n&&(t.bridge=void 0,t.detachAbort()),n}function assertPostgresOperationCurrent(){let e=Fn.getStore();if(e&&(!e.active||e.owner.refusal))throw e.owner.refusal??/* @__PURE__ */ Error(`PostgreSQL worker operation is no longer active`)}function runPostgresTransactionSync(e,t,n,r=!1,i=!1){assertPostgresOperationCurrent();let a=kt(e);return yt(a,()=>{let a=e.isTransaction&&!i,s=!1,c;try{r&&!a&&(c=beginPostgresReadSnapshotScope(e)),a?e.exec(`SAVEPOINT openclaw_tx_nested`):e.isTransaction||e.exec(r?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);let i=n?.maintenance&&a?String(e.prepare(`SHOW statement_timeout`).get().statement_timeout):void 0;n?.maintenance&&e.exec(`SET LOCAL statement_timeout = '${Sh}ms'`);let l=t();if(Mt(l),a)i!==void 0&&e.prepare(`SELECT set_config('statement_timeout', ?, true)`).get(i),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||Ht(e),e.exec(r?`ROLLBACK`:`COMMIT`),s=!r};n?.withCommit?Mt(n.withCommit(commit)):commit()}return l}catch(t){let n=yn(t)||s;if(!n)try{a?(e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)):e.isTransaction&&e.exec(`ROLLBACK`)}catch{n=!0}if(n)try{zt(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{c?.()}})}var PostgresSyncConnection=class{constructor(e,t,n,r,i){this.schema=t,this.anchor=n,this.storeId=r,this.isOpen=!0,this.isTransaction=!1,this.mutationRevision=0,this.lastResponseAt=Date.now(),this.outcomeUnknown=!0,this.readOnlyTransaction=!1,this.pendingWrite=!1,this.mainThread=ii===0,this.maintenance=!1,assertEngineStoreExecutionAllowed(),this.admissionReadOnly=i?.readOnly===!0,Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=Gr(`sha256`).update(r).digest().readBigInt64BE(),this.bridgeParameters={url:e,schema:t,storeId:r,...i},this.reuseKey=i?.reuse?postgresBridgeReuseKey(this.bridgeParameters):void 0,this.connect()}connect(){let e=this.reuseKey?takeIdlePostgresBridge(this.reuseKey):void 0,t=e?.bridge??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(this.bridgeParameters);if(this.bridge=t,this.idleCheckout=e?e.validate?`validate`:`reconnect`:void 0,t.port.unref(),e)return t;try{this.request({operation:`connect`,schema:this.schema})}catch(e){throw this.isOpen=!1,this.isTransaction=!1,this.bridge=void 0,t.port.close(),e}return t}runTransaction(e,t,...n){let r=this.maintenance;this.maintenance=r||t?.maintenance===!0;try{return runPostgresTransactionSync(this,e,t,this.admissionReadOnly||n[0],n[1])}finally{this.maintenance=r}}readRecoveryGeneration(e=!1){return this.request({operation:`recovery-generation`,schema:this.schema,storeId:this.storeId,lock:e},!1)}loseConnection(){!this.failure&&this.outcomeUnknown&&(this.pendingWrite=!0,Ot(kt(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new Sn(`PostgreSQL connection lost; outcome unknown`,`outcome-unknown`):/* @__PURE__ */ Error(`PostgreSQL connection lost; transaction rolled back`);let e=this.bridge;return e?.nextStep&&!this.failure.message.includes(e.nextStep)&&(this.failure.message+=` Run ${e.nextStep}.`),e&&Atomics.load(e.service,1)&&Un(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,Yt(kt(this)))}assertOpen(){if(this.failure)throw this.failure;if(!this.isOpen)throw Error(`PostgreSQL connection is closed`)}request(e,t=!0){this.mainThread&&e.operation!==`close`&&e.operation!==`release`&&assertEngineStoreExecutionAllowed(),this.assertOpen();let n=this.bridge??this.connect();this.outcomeUnknown=t;let r=++n.requestId;if(r>2147483647)throw this.loseConnection();let i=(this.maintenance?Sh:this.bridgeParameters.statementTimeoutMs??9e4)+3e4,a=performance.now()+i,s=n.inTransaction===!1,c=(this.idleCheckout!==void 0||s)&&(e.operation===`query`||e.operation===`recovery-generation`),l=c&&(this.idleCheckout===`validate`||s&&Date.now()-this.lastResponseAt>=1e3);n.inTransaction=void 0,this.idleCheckout=void 0,n.port.postMessage({...e,...c?{reconnectIfIdle:c}:{},...l?{validateIfIdle:l}:{},id:r,deadlineMs:i},[]),en(`sqlite_request`,`to_worker`);for(let e=Atomics.load(n.control,0);e!==r;e=Atomics.load(n.control,0)){if(Atomics.load(n.service,1))throw this.loseConnection();let t=a-performance.now();if(t<=0)throw Atomics.store(n.service,1,1),Atomics.notify(n.service,1),this.loseConnection();Atomics.wait(n.control,0,e,Math.min(t,50))}let u=ri(n.port)?.message;if(u&&en(`sqlite_reply`,`from_worker`),!u||u.id!==r)throw this.loseConnection();if(`error`in u)throw e.operation===`connect`?decodePostgresError(u.error):isPostgresConnectionError(u.error.code)?this.loseConnection():(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)&&(this.isTransaction=!1,this.finishWrite()),decodePostgresError(u.error));return this.lastResponseAt=Date.now(),`reusable`in u?(n.inTransaction=!u.reusable,u.reusable):(n.inTransaction=`generation`in u?u.inTransaction:u.result.inTransaction,`generation`in u?u.generation:u.result)}query(e,t=[],n=!1){return observeDatabaseOperation(`postgres`,`statement`,e,()=>this.execute(preparePostgresQuery(e),t,n))}execute({sql:e,mutation:t},n,r){validatePostgresBindings(n);let i=this.isTransaction;/^\s*BEGIN\b/i.test(e)&&(this.isTransaction=!0);let a=this.request({operation:`query`,schema:this.schema,sql:e,parameters:n},!i||/^\s*COMMIT\b/i.test(e)),s=this.readOnlyTransaction;if(this.isTransaction=a.inTransaction,this.readOnlyTransaction=this.isTransaction&&(s||/^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e)),/^\s*COMMIT\s*;?\s*$/i.test(e)&&a.command!==`COMMIT`)throw this.finishWrite(),Error(`PostgreSQL transaction rolled back instead of committing`);let c=a.mutation===`unscoped`||t===`unscoped`?`unscoped`:a.mutation??t,l=c!==void 0;if(l){if(s||this.readOnlyTransaction)throw Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++,this.pendingWrite=!0,Ot(kt(this),c===`unscoped`)}return!this.isTransaction&&(l||i)&&yt(kt(this),()=>{this.finishWrite()}),this.outcomeUnknown=!this.isTransaction,{rows:decodePostgresRows(a,r),rowCount:a.rowCount,columns:a.fields.map(({name:e})=>({name:e}))}}exec(e){this.query(e)}prepare(e){this.assertOpen();let t=preparePostgresQuery(e),n=!1,r=[],execute=i=>{let a=observeDatabaseOperation(`postgres`,`statement`,e,()=>this.execute(t,i,n));return r=a.columns,a};return{get:(...e)=>execute(e).rows[0],all:(...e)=>execute(e).rows,iterate:(...e)=>execute(e).rows[Symbol.iterator](),run:(...e)=>({changes:execute(e).rowCount,lastInsertRowid:0}),columns:()=>r,setReadBigInts:e=>{n=e}}}releaseIdleTransport(){let e=this.bridge;if(!this.isOpen||!e||!this.reuseKey||this.isTransaction)return;let t=!1;try{e.inTransaction===!1||this.request({operation:`release`})?(retainIdlePostgresBridge(this.reuseKey,e),t=!0):(this.isOpen=!1,this.finishWrite())}finally{this.bridge=void 0,t||e.port.close()}}close(){if(this.isOpen)try{this.reuseKey&&!this.isTransaction?this.releaseIdleTransport():this.bridge&&this.request({operation:`close`})}finally{this.finishWrite(),this.isOpen=!1,this.isTransaction=!1,this.bridge?.port.close(),this.bridge=void 0}}};new SqliteQueryCompiler;const Th=`memory_index_chunks_fts`,Eh=`memory_index_paths_fts`;function buildMemoryFtsTriggers(e,t,n,r,i){let trigger=(n,r,i)=>({name:`${e}_after_${n}`,sql:`
      CREATE TRIGGER IF NOT EXISTS main.${e}_after_${n}
      AFTER ${r} ON ${t}
      BEGIN
${i}
      END;
    `});return[trigger(`insert`,`INSERT`,r),trigger(`update`,`UPDATE OF ${n}`,`${i}
${r}`),trigger(`delete`,`DELETE`,i)]}buildMemoryFtsTriggers(Eh,`memory_index_sources`,`id, path, source`,`        INSERT INTO ${Eh} (rowid, path, source)
        VALUES (NEW.id, NEW.path, NEW.source);`,`        DELETE FROM ${Eh}
        WHERE rowid = OLD.id;`),buildMemoryFtsTriggers(Th,`memory_index_chunks`,`chunk_rowid, text, id, path, source, model, start_line, end_line`,`        INSERT INTO ${Th} (rowid, text, id, path, source, model, start_line, end_line)
        VALUES (NEW.chunk_rowid, NEW.text, NEW.id, NEW.path, NEW.source, NEW.model, NEW.start_line, NEW.end_line);`,`        DELETE FROM ${Th} WHERE rowid = OLD.chunk_rowid;`);const Dh={sqlite:{openConnection:({anchor:e})=>observeConnection(e),schema:{bootstrap:e=>e.openSqlite()}},postgres:{openConnection:e=>{if(!e.input||!e.storeId||!e.namespace)throw Error(`PostgreSQL store is not admitted`);try{return new PostgresSyncConnection(e.input.connection,e.namespace,e.anchor,e.storeId,{reuse:e.reusePostgresConnection,readOnly:e.input.readOnly,lockTimeoutMs:6e4,statementTimeoutMs:9e4})}catch(t){let n=t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``,r=Ke(`${n}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${r}; verify database.postgres.connection and server availability.`,{cause:t})}},schema:{bootstrap:(e,t)=>{if(!e.schema.postgres)throw Error(`Store has no PostgreSQL schema`);t.exec(postgresSchemaSql(e.schema,e.namespace)),t.prepare(`INSERT INTO openclaw_schema_meta (store, version, store_id) VALUES (?, ?, ?)`).run(e.schema.id,e.schema.version,e.storeId)},migrate:(e,t,n)=>{if(t>e.schema.version)throw Error(`PostgreSQL ${e.schema.id} schema ${t} is newer than this build (expected ${e.schema.version}); use a compatible binary, or reverse-port with a compatible binary before downgrading.`);for(let r=t+1;r<=e.schema.version;r++){let t=e.schema.postgresMigrations?.find(e=>e.version===r);if(!t)throw Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);let i=readPostgresSchema(n,e.namespace,e.schema.id),a=withPostgresSearchExtensions(e.schema,i);if(verifyPostgresSchema(n,e.namespace,{...a,version:r-1,postgres:t.fromSchema.postgres,postgresFragments:t.fromSchema.postgresFragments,postgresWithoutOptionalColumn:t.fromSchema.postgresWithoutOptionalColumn,postgresVectorDecoderVersion:t.fromSchema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.fromSchema.postgresVectorSearchVersion,postgresTextSearchVersion:t.fromSchema.postgresTextSearchVersion},i),t.schema.postgresVectorSearchVersion===2&&t.fromSchema.postgresVectorSearchVersion!==2)for(let t of[a.search,...Object.values(a.searchExtensions??{})])t&&admitPostgresSearch(n,t,e.namespace,2);e.beforeMigrate?.(n,r-1,new Set(i.catalog.filter(e=>e.kind===`table`).map(e=>e.table))),n.exec(t.sql),n.prepare(`UPDATE openclaw_schema_meta SET version = ? WHERE store = ?`).run(r,e.schema.id),verifyAndRecordPostgresSchema(n,e.namespace,{...a,version:r,postgres:t.schema.postgres,postgresFragments:t.schema.postgresFragments,postgresWithoutOptionalColumn:t.schema.postgresWithoutOptionalColumn,postgresVectorDecoderVersion:t.schema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.schema.postgresVectorSearchVersion,postgresTextSearchVersion:t.schema.postgresTextSearchVersion})}}}}},Oh={name:`database.engine`};function readEngineAnchor(e,t=`identity`,n=!1){try{return t===`schema`?[e.prepare(`SELECT schema FROM openclaw_engine_anchor LIMIT 1`).get()]:e.prepare(`SELECT store_id, engine, schema FROM openclaw_engine_anchor`).all()}catch(e){if(n||!(e instanceof Error)||e.message!==`no such table: openclaw_engine_anchor`)throw e;return}}function familySetting(e){return`database.families.${e.id===`team_reports`?`team-reports`:e.id}.engine`}function refusePostgresAnchor(e,t){let n=readEngineAnchor(e,`schema`);if(n)throw Error(`This store lives in PostgreSQL schema ${String(n[0]?.schema??`unknown`)}; set ${familySetting(t)} to postgres and configure database.postgres.connection.`)}function openEngineStore(e){let{anchor:t}=e,n=e.schema;observeConnection(t);let r=e.input!==void 0&&n.postgres!==void 0,i=b(t,Oh);if(!r){if(i?.engine===`postgres`)throw Error(`This store lives in PostgreSQL schema ${i.namespace}; set ${familySetting(n)} to postgres and configure database.postgres.connection.`);return!i&&e.inspectSqlite().hasEngineAnchor&&refusePostgresAnchor(t,n),e.prepareAnchor(),Dh.sqlite.schema.bootstrap({...e,input:e.input},t),w(t,Oh,{engine:`sqlite`}),Dh.sqlite.openConnection({...e,input:e.input})}if(i?.engine===`sqlite`)throw Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);let a=e.input?.readOnly===!0;a||e.prepareAnchor();let readOrCreateAnchor=()=>{let r=e.inspectSqlite();if(r.hasExistingData)throw Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);if(!r.hasEngineAnchor&&(e.existingOnly||a))throw Error(`Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.`);r.hasEngineAnchor||t.exec(`CREATE TABLE IF NOT EXISTS openclaw_engine_anchor (store_id TEXT NOT NULL, engine TEXT NOT NULL CHECK (engine = 'postgres'), schema TEXT NOT NULL)`);let i=readEngineAnchor(t,`identity`,!0)??[];if(i.length>1||r.hasEngineAnchor&&i.length===0)throw Error(`Invalid engine anchor: expected exactly one identity. Restore a matching backup.`);let s=i[0];if(s){if(typeof s.store_id!=`string`||s.engine!==`postgres`||typeof s.schema!=`string`)throw Error(`Invalid PostgreSQL anchor identity. Restore a matching backup.`);return{storeId:s.store_id,namespace:s.schema}}let c=qr(),l=postgresStoreNamespace(e.input.schemaPrefix,n.id,c);return t.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(c,l),e.onFreshAnchor?.(t),{storeId:c,namespace:l}},s=i?.engine===`postgres`?i:e.existingOnly||a?readOrCreateAnchor():runSqliteImmediateTransactionSync(t,readOrCreateAnchor),c={...e,input:e.input,...s},l=Dh.postgres,u=l.openConnection(c),admit=t=>{admitPostgresPhysicalFacts({db:u,namespace:s.namespace,storeId:s.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion,requireSealedSchema:a}),e.admitPostgres?.(u,t)};try{let r=n.search?admitPostgresSearch(u,n.search,s.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(a)u.runTransaction(()=>admit(!1),void 0,!0);else if(!i||i.engine===`postgres`&&i.version!==n.version){admitPostgresCapabilities(u);let t,r;u.runTransaction(()=>{let i=!u.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(s.namespace);i&&!e.existingOnly&&(u.exec(`CREATE SCHEMA IF NOT EXISTS "${s.namespace.replaceAll(`"`,`""`)}"`),u.exec(`CREATE TABLE openclaw_schema_meta (
  store TEXT PRIMARY KEY, version BIGINT NOT NULL, store_id TEXT NOT NULL,
  fingerprint TEXT, ddl_hash TEXT, server_major BIGINT)`));let a;try{a=u.prepare(`SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?`).get(n.id)}catch(e){throw Error(`Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`,{cause:e})}if(a){if(a.store_id!==s.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${s.storeId}, found ${String(a.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(a.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(a.version)+1)?.fromSchema;if(!e)throw Error(`Missing PostgreSQL source schema for inspection`);n={...n,...e,postgresVectorDecoderVersion:e.postgresVectorDecoderVersion,postgresVectorSearchVersion:e.postgresVectorSearchVersion,postgresTextSearchVersion:e.postgresTextSearchVersion,version:Number(a.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(u,r),jn(u),Jt(u,{stage:()=>{},rollback:()=>{},commit:()=>zn(u),invalidate:()=>zn(u)});let migrate=()=>l.schema.migrate(c,Number(a.version),u);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!i)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);l.schema.bootstrap(c,u)}admit(!a)},{maintenance:!0,withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!i||i.engine===`postgres`&&i.version!==n.version)&&w(t,Oh,{engine:`postgres`,...s,version:n.version}),r?.();for(let e of Object.values(getAdmittedPostgresSchema(u)?.searchExtensions??{}))admitPostgresSearch(u,e,s.namespace,n.postgresVectorSearchVersion)?.();return u}catch(t){if(e.closeOnFailure)return e.closeOnFailure(u,t);throw u.close(),t}}const kh=/CREATE (?:UNIQUE )?INDEX ("(?:[^"]|"")+") ON ("(?:[^"]|"")+") (?:'(?:[^']|'')*'|"(?:[^"]|"")*"|[^;'"])*;/g,Ah=/'(?:[^']|'')*'|"(?:[^"]|"")*"|\) (ASC|DESC)(?=,|\))/g;function withLegacyPostgresIndexOrdering(e,t=`sqlite`,n=e){let r=/* @__PURE__ */ new Map;if(t===`schema-nullability`)for(let[,e,t]of n.matchAll(/CREATE TABLE ("(?:[^"]|"")+") \(\n([\s\S]*?)\n\);/g))r.set(e,new Set([...t.matchAll(/^ {2}("(?:[^"]|"")+") (?:text|bigint|bytea|double precision)([^\n]*)/gm)].filter(e=>!/\bNOT NULL\b/.test(e[2].replace(`GENERATED BY DEFAULT AS IDENTITY`,``).split(/\bDEFAULT\b/)[0])).map(([,e])=>e)));return e.replace(kh,(e,n,i)=>t===`schema-nullability`?e.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"|\(("(?:[^"]|"")+")\) (ASC|DESC)(?=,|\))/g,(e,t,n)=>t&&r.get(i)?.has(t)?`${e} NULLS ${n===`DESC`?`LAST`:`FIRST`}`:e):e.replace(Ah,(e,t)=>t?`${e} NULLS ${t===`DESC`?`LAST`:`FIRST`}`:e))}function postgresIndexOrderingMigration(e,t=`sqlite`){let n=withLegacyPostgresIndexOrdering(e,t),r=new Map([...n.matchAll(kh)].map(([e,t])=>[t,e]));return[...e.matchAll(kh)].filter(([e,t])=>r.get(t)!==e).map(([e,t,n])=>`DO $index_order$
BEGIN
  IF to_regclass('${n.replaceAll(`'`,`''`)}') IS NOT NULL THEN
    DROP INDEX ${t};
    ${e}
  END IF;
END $index_order$;`).join(`
`)}function stateEngineInput(){if(vr())return En(`state`)}[`github_publication_requests`,`github_personal_publication_requests`,`github_repository_publication_requests`].map(e=>`${e}.draft`);function withLegacyPublicationDraft(e){return e.replace(/(CREATE TABLE(?: IF NOT EXISTS)? "?github_(?:personal_|repository_)?publication_requests"? \([\s\S]*?)\n {2}(?:"draft" bigint|draft INTEGER),/gu,`$1`)}const jh=[`local_workspace_tree_packs`,`local_workspace_source_path_sets`],Mh=[`tree_root_digest`,`source_paths_digest`,`canonical_fingerprints`,`projection_fingerprints`];[...jh],Mh.map(e=>`local_workspace_projections.${e}`);function withLegacyLocalWorkspaceCas(e){return e.replace(/\n {2}(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints) BLOB,/gu,``).replace(/\n {2}"(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints)" bytea,/gu,``).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_(?:tree_packs|source_path_sets)"? \([\s\S]*?\n\)(?: STRICT(?:, WITHOUT ROWID)?)?;\n?/gu,``)}function withLegacyLocalWorkspaceManifests(e){return withLegacyLocalWorkspaceCas(e).replace(/\n {2}(?:checkpoint_json TEXT|"checkpoint_json" text COLLATE "C"),/gu,``).replace(/^ {2}CHECK \([^\n]*baseline_json[^\n]*baseline_ref[^\n]*\),$/gmu,e=>e.includes(`"`)?`  CHECK ((("baseline_json" IS NULL) = ("baseline_ref" IS NULL))),`:`  CHECK ((baseline_json IS NULL) = (baseline_ref IS NULL)),`).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_manifest_nodes"? \([\s\S]*?\n\)(?: STRICT)?;\n?/gu,``).replace(/ALTER TABLE "local_workspace_manifest_nodes" ADD FOREIGN KEY[^;]*;\n?/gu,``)}const Nh=[[`workspace_setup_state`,`bootstrap_deferred`,`INTEGER`,!0],[`agent_deletion_journal`,`phase`,`TEXT`,!0],[`agent_database_leases`,`provenance`,`TEXT`,!0],[`user_profile_identities`,`canonical_login`,`TEXT`],[`user_profile_identities`,`authorization_id`,`TEXT`],[`user_profile_identities`,`authorization_basis_json`,`TEXT`],[`user_profile_identities`,`verified_email_json`,`TEXT`,!0],[`template_installs`,`bootstrap_content_digest`,`TEXT`],[`template_installs`,`bootstrap_source_path`,`TEXT`],[`worker_environments`,`desktop_json`,`TEXT`],[`worker_environments`,`bootstrap_install_kind`,`TEXT`],[`worker_environments`,`preparation_purpose`,`TEXT`],[`template_package_refs`,`extension_adapter_identity`,`TEXT`],[`template_package_refs`,`extension_detected_format`,`TEXT`],[`template_package_refs`,`extension_format`,`TEXT`],[`template_package_refs`,`extension_id`,`TEXT`],[`template_package_refs`,`extension_mapped_json`,`TEXT`],[`template_package_refs`,`extension_unavailable_json`,`TEXT`],[`worker_environments`,`shared_host`,`INTEGER`],[`worker_environments`,`node_setup_id`,`TEXT`],[`worker_environments`,`node_device_id`,`TEXT`],[`worker_session_placements`,`terminal_reason`,`TEXT`],[`worker_session_placements`,`terminal_at_ms`,`INTEGER`],[`worker_workspace_pending_results`,`repository_workspace_id`,`TEXT`,!0],[`worker_session_placement_moves`,`abandon_source`,`INTEGER`,!0],[`worker_session_placement_moves`,`target_machine_class`,`TEXT`,!0],[`worker_session_placement_moves`,`target_os`,`TEXT`,!0],[`worktrees`,`run_end_cleanup_json`,`TEXT`],[`worktrees`,`gc_protection_json`,`TEXT`],[`device_bootstrap_tokens`,`setup_id`,`TEXT`,!0],[`session_groups`,`cwd`,`TEXT`,!0],[`session_groups`,`worktree`,`INTEGER`,!0],[`secret_store_entries`,`allowed_hosts`,`TEXT`],[`web_push_subscriptions`,`device_id`,`TEXT`,!0],[`web_push_subscriptions`,`user_profile_id`,`TEXT`,!0],[`web_push_subscriptions`,`preferences_json`,`TEXT`,!0],[`task_runs`,`execution_owner_host`,`TEXT`,!0],[`task_runs`,`execution_owner_pid`,`INTEGER`,!0],[`task_runs`,`execution_owner_start_identity`,`INTEGER`,!0],[`session_watch_cursors`,`watcher_store_path`,`TEXT`,!0],[`subagent_runs`,`requester_store_path`,`TEXT`,!0],[`subagent_runs`,`controller_store_path`,`TEXT`,!0],[`cron_jobs`,`grant_definition_revision`,`TEXT`],[`cron_jobs`,`grant_definition_generation`,`INTEGER`],[`cron_jobs`,`grant_definition_updated_at`,`INTEGER`]];function lazyColumnDefinitions(e){return Nh.filter(t=>e===void 0||!!t[3]===e).map(([e,t,n])=>({columnName:t,dataType:n,tableName:e}))}const Ph=lazyColumnDefinitions(),Fh=lazyColumnDefinitions(!1),Ih=lazyColumnDefinitions(!0),Lh={packageUpdatedAt:[[`template_package_refs`,`updated_at_ms INTEGER NOT NULL DEFAULT 0`]],packageIntegrity:[[`template_package_refs`,`package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'`]],diagnosticSequence:[[`diagnostic_events`,`sequence INTEGER NOT NULL DEFAULT 0`]],cronRunLogs:[[`worktrees`,`provisioned_paths_json TEXT`],[`apns_registrations`,`relay_origin TEXT`],[`device_pairing_pending`,`refreshed_at_ms INTEGER`],[`device_pairing_pending`,`browser_origin TEXT`],[`device_pairing_paired`,`approved_via TEXT`],[`device_pairing_paired`,`browser_origin TEXT`],[`device_pairing_paired`,`operator_label TEXT`],[`device_pairing_paired`,`node_surface_json TEXT`],[`device_pairing_paired`,`pending_node_surface_json TEXT`],[`cron_run_logs`,`status TEXT`],[`cron_run_logs`,`error TEXT`],[`cron_run_logs`,`summary TEXT`],[`cron_run_logs`,`diagnostics_summary TEXT`],[`cron_run_logs`,`delivery_status TEXT`],[`cron_run_logs`,`delivery_error TEXT`],[`cron_run_logs`,`delivered INTEGER`],[`cron_run_logs`,`session_id TEXT`],[`cron_run_logs`,`session_key TEXT`],[`cron_run_logs`,`run_id TEXT`],[`cron_run_logs`,`run_at_ms INTEGER`],[`cron_run_logs`,`duration_ms INTEGER`],[`cron_run_logs`,`next_run_at_ms INTEGER`],[`cron_run_logs`,`model TEXT`],[`cron_run_logs`,`provider TEXT`],[`cron_run_logs`,`total_tokens INTEGER`],[`cron_run_logs`,`entry_json TEXT NOT NULL DEFAULT '{}'`],[`cron_run_logs`,`created_at INTEGER NOT NULL DEFAULT 0`]],acpReplay:[[`acp_replay_events`,`estimated_bytes INTEGER NOT NULL DEFAULT 0`],[`acp_replay_sessions`,`estimated_bytes INTEGER NOT NULL DEFAULT 0`]],cronJobs:[[`cron_jobs`,`description TEXT`],[`cron_jobs`,`declaration_key TEXT`],[`cron_jobs`,`owner_agent_id TEXT`],[`cron_jobs`,`name TEXT NOT NULL DEFAULT ''`],[`cron_jobs`,`enabled INTEGER NOT NULL DEFAULT 1`],[`cron_jobs`,`agent_id TEXT`],[`cron_jobs`,`payload_kind TEXT NOT NULL DEFAULT 'message'`],[`cron_jobs`,`state_json TEXT NOT NULL DEFAULT '{}'`],[`cron_jobs`,`runtime_updated_at_ms INTEGER`],[`cron_jobs`,`schedule_identity TEXT`],[`cron_jobs`,`sort_order INTEGER NOT NULL DEFAULT 0`]],deliveryQueue:[[`sandbox_registry_entries`,`session_key TEXT`],[`sandbox_registry_entries`,`backend_id TEXT`],[`sandbox_registry_entries`,`runtime_label TEXT`],[`sandbox_registry_entries`,`image TEXT`],[`sandbox_registry_entries`,`created_at_ms INTEGER`],[`sandbox_registry_entries`,`last_used_at_ms INTEGER`],[`sandbox_registry_entries`,`config_label_kind TEXT`],[`sandbox_registry_entries`,`config_hash TEXT`],[`sandbox_registry_entries`,`cdp_port INTEGER`],[`sandbox_registry_entries`,`no_vnc_port INTEGER`],[`delivery_queue_entries`,`entry_kind TEXT`],[`delivery_queue_entries`,`session_key TEXT`],[`delivery_queue_entries`,`channel TEXT`],[`delivery_queue_entries`,`target TEXT`],[`delivery_queue_entries`,`account_id TEXT`],[`delivery_queue_entries`,`retry_count INTEGER NOT NULL DEFAULT 0`],[`delivery_queue_entries`,`last_attempt_at INTEGER`],[`delivery_queue_entries`,`last_error TEXT`],[`delivery_queue_entries`,`recovery_state TEXT`],[`delivery_queue_entries`,`platform_send_started_at INTEGER`]],originalMediaRoot:[[`managed_outgoing_image_records`,`original_media_root TEXT NOT NULL DEFAULT ''`]],beforeTaskAttribution:[[`managed_outgoing_image_records`,`agent_id TEXT`],[`managed_outgoing_image_records`,`cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))`],[`current_conversation_bindings`,`conversation_kind TEXT NOT NULL DEFAULT 'channel'`],[`device_bootstrap_tokens`,`pending_profile_json TEXT`],[`gateway_restart_handoff`,`restart_trace_started_at INTEGER`],[`gateway_restart_handoff`,`restart_trace_last_at INTEGER`],[`gateway_restart_intent`,`reason TEXT`],[`gateway_restart_sentinel`,`delivery_channel TEXT`],[`gateway_restart_sentinel`,`delivery_to TEXT`],[`gateway_restart_sentinel`,`delivery_account_id TEXT`],[`gateway_restart_sentinel`,`message TEXT`],[`gateway_restart_sentinel`,`continuation_json TEXT`],[`gateway_restart_sentinel`,`doctor_hint TEXT`],[`gateway_restart_sentinel`,`stats_json TEXT`],[`gateway_boot_lifecycle`,`startup_reason TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_mode TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_key_id TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_signature_count INTEGER`],[`official_external_plugin_catalog_snapshots`,`trust_threshold INTEGER`],[`official_external_plugin_catalog_snapshots`,`trust_verified_at TEXT`]],taskRequester:[[`task_runs`,`requester_agent_id TEXT`]],taskRunDetails:[[`task_runs`,`tool_use_count INTEGER`],[`task_runs`,`last_tool_name TEXT`],[`task_runs`,`detail_json TEXT`]],workerEnvironments:[[`worker_environments`,`bootstrap_bundle_hash TEXT`],[`worker_environments`,`bootstrap_openclaw_version TEXT`],[`worker_environments`,`bootstrap_protocol_features_json TEXT`],[`worker_environments`,`bootstrap_install_kind TEXT`],[`worker_environments`,`owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0)`],[`worker_environments`,`ssh_host_key TEXT`],[`worker_workspace_pending_results`,`staged_result_ref TEXT`],[`worker_environments`,`teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed'))`]]},Rh=[[`claw_installs`,`template_installs`],[`claw_workspace_files`,`template_workspace_files`],[`claw_package_refs`,`template_package_refs`],[`claw_cron_refs`,`template_cron_refs`],[`claw_mcp_server_refs`,`template_mcp_server_refs`]],zh=[[`template_installs`,`claw_name`,`template_name`],[`template_installs`,`claw_version`,`template_version`],[`template_package_refs`,`claw_name`,`template_name`]],Bh=new Set(Rh.map(([,e])=>e)),Vh=Fh.filter(({tableName:e})=>Bh.has(e)),Hh=[...Lh.packageUpdatedAt,...Lh.packageIntegrity],Uh=[[`template_installs`,[1,2,3].map(e=>[`openclaw.clawInstallRecord.v${e}`,`openclaw.templateInstallRecord.v${e}`])],[`template_workspace_files`,[[`openclaw.clawWorkspaceFileRecord.v1`,`openclaw.templateWorkspaceFileRecord.v1`]]],[`template_package_refs`,[[`openclaw.clawPackageRef.v1`,`openclaw.templatePackageRef.v1`]]],[`template_cron_refs`,[[`openclaw.clawCronRef.v1`,`openclaw.templateCronRef.v1`]]],[`template_mcp_server_refs`,[[`openclaw.clawMcpServerRef.v1`,`openclaw.templateMcpServerRef.v1`]]]],literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function legacyTemplateStateIdentifier(e){for(let[t,n]of[...Rh,...zh.map(([,e,t])=>[e,t])])if(e===n)return t;return e}function withLegacyTemplateStateSchema(e){return e.replace(/\btemplate_(?:installs|workspace_files|package_refs|cron_refs|mcp_server_refs|name|version)\b/gu,legacyTemplateStateIdentifier).replaceAll(`'template-introduced'`,`'claw-introduced'`).replaceAll(`'template'`,`'claw'`)}function versionUpdates(e,t){return`UPDATE ${x(e)} SET schema_version = CASE schema_version
    ${t.map(([e,t])=>`WHEN ${literal(e)} THEN ${literal(t)}`).join(`
`)}
    ELSE schema_version END WHERE schema_version IN (${t.map(([e])=>literal(e)).join(`, `)});`}[...Rh.flat()],[...Vh.map(({tableName:e,columnName:t})=>`${e}.${t}`),...Hh.map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)];const Wh=`DO $template_names_v36$
DECLARE item record; column_item record; constraint_name text; next_constraint_name text;
BEGIN
  FOR item IN SELECT * FROM (VALUES
    ${Rh.map(([e,t])=>`(${literal(e)}, ${literal(t)})`).join(`,
`)}
  ) AS names(old_name, new_name) LOOP
    EXECUTE format('ALTER TABLE %I RENAME TO %I', item.old_name, item.new_name);
    FOR column_item IN SELECT * FROM (VALUES
      ${zh.map(([e,t,n])=>`(${literal(e)}, ${literal(t)}, ${literal(n)})`).join(`,
`)}
    ) AS columns(table_name, old_name, new_name) WHERE table_name = item.new_name LOOP
      EXECUTE format('ALTER TABLE %I RENAME COLUMN %I TO %I', item.new_name, column_item.old_name, column_item.new_name);
    END LOOP;
    FOR constraint_name IN SELECT conname FROM pg_constraint
      WHERE conrelid = to_regclass(item.new_name) LOOP
      next_constraint_name := constraint_name;
      IF left(constraint_name, length(item.old_name) + 1) = item.old_name || '_' THEN
        next_constraint_name := item.new_name || substr(constraint_name, length(item.old_name) + 1);
      END IF;
      next_constraint_name := replace(replace(next_constraint_name, '_claw_name_', '_template_name_'), '_claw_version_', '_template_version_');
      IF next_constraint_name <> constraint_name THEN
        EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', item.new_name, constraint_name, next_constraint_name);
      END IF;
    END LOOP;
  END LOOP;
  ${[`template_package_refs`,`template_mcp_server_refs`].map(e=>`
    ALTER TABLE ${x(e)} DROP CONSTRAINT ${x(`${e}_origin_check`)};
    UPDATE ${x(e)} SET origin = 'template-introduced' WHERE origin = 'claw-introduced';
    ALTER TABLE ${x(e)} ADD CONSTRAINT ${x(`${e}_origin_check`)}
      CHECK (origin IN ('template-introduced', 'pre-existing'));`).join(`
`)}
  IF to_regclass('agent_provenance') IS NOT NULL THEN
    ALTER TABLE agent_provenance DROP CONSTRAINT agent_provenance_created_via_check;
    UPDATE agent_provenance SET created_via = 'template' WHERE created_via = 'claw';
    ALTER TABLE agent_provenance ADD CONSTRAINT agent_provenance_created_via_check
      CHECK (created_via IN ('operator', 'agent', 'template'));
  END IF;
  ${Uh.map(([e,t])=>versionUpdates(e,t)).join(`
`)}
END $template_names_v36$;`,Gh={version:37,tables:[`worker_environments`],columns:[`worker_environments.resource_receipt_json`],migrate(e,t){return t>=37?!1:ensureColumn(e,`worker_environments`,`resource_receipt_json TEXT`)},applied:`Retained immutable worker provider resource receipts (v37)`};function withLegacyWorkerResourceReceipts(e){return e.replace(/,\n {2}resource_receipt_json TEXT(?=\n\))|\n {2}"resource_receipt_json" text COLLATE "C",/gu,``)}const Kh=[Gh,{version:38,tables:[`session_repository_workspaces`,`worker_workspace_pending_results`],columns:[`session_repository_workspaces.disk_authority_json`,`worker_workspace_pending_results.repository_disk_authority_json`],migrate(e,t){if(t>=38)return!1;let n=ensureColumn(e,`session_repository_workspaces`,`disk_authority_json TEXT`),r=ensureColumn(e,`worker_workspace_pending_results`,`repository_disk_authority_json TEXT`);return n||r},applied:`Retained repository disk authority and original pending-result authority (v38)`}];function withLegacyRepositoryDiskAuthority(e){return e.replace(/\n {2}(?:(?:disk_authority_json|repository_disk_authority_json) TEXT|"(?:disk_authority_json|repository_disk_authority_json)" text COLLATE "C"),/gu,``)}function withLegacyWorkerRetention(e){return e.replace(/,\n {2}retention_json TEXT(?=\n\))|\n {2}"retention_json" text COLLATE "C",/gu,``)}function withLegacyWorkspaceBootstrapDeferred(e){return e.replace(`  bootstrap_deferred INTEGER,
`,``).replace(`  "bootstrap_deferred" bigint,
`,``)}function withLegacyStateV40Additions(e){return withLegacyWorkspaceBootstrapDeferred(e).replace(/CREATE TABLE IF NOT EXISTS device_pairing_browser_requests \([\s\S]*?\) STRICT;\n\n/u,``)}function withLegacyWorkerProvisionSource(e){return e.replace(/,\n {2}provision_source_json TEXT(?=\n\))|\n {2}"provision_source_json" text COLLATE "C",/gu,``)}const qh=`state.schema.contentVersion`;var PostgresSchemaAdmissionUnavailableError=class extends Error{};function requireStatePostgresPhysicalFacts(e){let t=getPostgresPhysicalFacts(e);if(!t)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL physical schema admission`);return t}const Jh=createSqliteQueryCache(e=>prepareSqliteQuerySync(e,()=>getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,qh)));function readStateSchemaContentVersion(e,t,n=readStateSchemaContentVersionRow,r){if(C(e)){let n=getStateSchemaVersionAdmission(e);if(!n)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state schema admission; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`);return Math.max(t??n.userVersion,n.contentVersion)}let i=getStateSchemaVersionAdmission(e);if(i)return Math.max(t??i.userVersion,i.contentVersion);let a=r??getAdmittedSqliteSchemaFacts(e)?.userVersion??readSqliteUserVersion(e),s=parseStateSchemaContentVersion(tableExists(e,`config_machine_state`)?n(e)?.value_json:void 0);return rememberStateSchemaVersionAdmission(e,{userVersion:a,contentVersion:s}),Math.max(t??a,s)}function readStateSchemaContentVersionRow(e){return Jh(e)().rows[0]}function parseStateSchemaContentVersion(e){if(e===void 0)return 0;let t;try{t=e===null?null:JSON.parse(e)}catch(e){throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${qh}.`,{cause:e})}if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${qh}.`);return t}function admitStateSchemaFacts(e,t,n=`runtime`){if(C(e))requireStatePostgresPhysicalFacts(e);else try{admitSqliteSchema(e,r=>assertSupportedStateSchemaVersion(e,t,{userVersion:r,contentVersion:r},void 0,n))}catch(r){let i;try{i=readSqliteUserVersion(e)}catch{throw normalizeOpenClawStateSchemaReadError(r,t)}throw i>40?createNewerSqliteSchemaVersionError(`OpenClaw state database`,t,i,40,readSqliteWriterAppVersion(e),n):normalizeOpenClawStateSchemaReadError(r,t)}}function assertSupportedStateSchemaVersion(e,t,n,r,i=`runtime`){if(C(e))return readStateSchemaContentVersion(e);try{let a=n?.userVersion??getStateSchemaVersionAdmission(e)?.userVersion??getAdmittedSqliteSchemaFacts(e)?.userVersion??readSqliteUserVersion(e),s=n?.contentVersion??(a>40?a:readStateSchemaContentVersion(e,a,r,a));if(s>40)throw createNewerSqliteSchemaVersionError(`OpenClaw state database`,t,s,40,readSqliteWriterAppVersion(e),i);return a}catch(e){throw normalizeOpenClawStateSchemaReadError(e,t)}}function withPostgresSchemaAdmissionRetry(e,t,n){try{return t()}catch(r){if(!(r instanceof PostgresSchemaAdmissionUnavailableError)||!C(e)||n?.()===!1||!e.isOpen||e.isTransaction)throw r;let i=Math.min(Date.now()+1e3,Nt()??1/0),a=performance.now()+Math.max(0,i-Date.now()),s=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));return At({deadlineAtMs:i},()=>{for(let c=10;;c=Math.min(c*2,100)){St();let l=Math.min(a-performance.now(),i-Date.now());if(l<=0||(Atomics.wait(s,0,0,Math.min(c,l)),St(),performance.now()>=a||Date.now()>=i)||n?.()===!1||!e.isOpen||e.isTransaction)throw r;try{if(!getPostgresPhysicalFacts(e,{refresh:!0}))continue;return t()}catch(t){if(t instanceof er&&(performance.now()>=a||Date.now()>=i))throw r;if(!(t instanceof PostgresSchemaAdmissionUnavailableError)||n?.()===!1||!e.isOpen||e.isTransaction)throw t}}})}}function writeStateSchemaContentVersion(e){executeSqliteQuerySync(e,getNodeSqliteKysely(e).insertInto(`config_machine_state`).values({state_key:qh,value_json:`40`,updated_at_ms:Date.now()}).onConflict(e=>e.column(`state_key`).doUpdateSet({value_json:`40`,updated_at_ms:Date.now()}).where(`config_machine_state.value_json`,`!=`,`40`)))}const $={get eagerSql(){let e=`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "acp_replay_events" (
  "session_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "at" bigint NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C",
  "update_json" text COLLATE "C" NOT NULL,
  "estimated_bytes" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("session_id", "seq")
);

CREATE TABLE "acp_replay_sessions" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "cwd" text COLLATE "C" NOT NULL,
  "complete" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "next_seq" bigint NOT NULL,
  "estimated_bytes" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("session_id")
);

CREATE TABLE "acp_sessions" (
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "backend" text COLLATE "C" NOT NULL,
  "agent" text COLLATE "C" NOT NULL,
  "runtime_session_name" text COLLATE "C" NOT NULL,
  "identity_json" text COLLATE "C",
  "resume_agent_session_id" text COLLATE "C",
  "resume_acpx_session_id" text COLLATE "C",
  "mode" text COLLATE "C" NOT NULL,
  "runtime_options_json" text COLLATE "C",
  "cwd" text COLLATE "C",
  "state" text COLLATE "C" NOT NULL,
  "last_activity_at" bigint NOT NULL,
  "last_error" text COLLATE "C",
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key")
);

CREATE TABLE "agent_database_leases" (
  "lease_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "owner_pid" bigint NOT NULL,
  "owner_start_time" bigint,
  "opened_at" bigint NOT NULL,
  "provenance" text COLLATE "C",
  PRIMARY KEY ("lease_id")
);

CREATE TABLE "agent_databases" (
  "agent_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL,
  "last_seen_at" bigint NOT NULL,
  "size_bytes" bigint,
  PRIMARY KEY ("agent_id", "path")
);

CREATE TABLE "apns_registration_tombstones" (
  "node_id" text COLLATE "C" NOT NULL,
  "deleted_at_ms" bigint NOT NULL,
  PRIMARY KEY ("node_id")
);

CREATE TABLE "apns_registrations" (
  "node_id" text COLLATE "C" NOT NULL,
  "transport" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C",
  "relay_handle" text COLLATE "C",
  "send_grant" text COLLATE "C",
  "installation_id" text COLLATE "C",
  "relay_origin" text COLLATE "C",
  "topic" text COLLATE "C" NOT NULL,
  "environment" text COLLATE "C" NOT NULL,
  "distribution" text COLLATE "C",
  "token_debug_suffix" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("node_id")
);

CREATE TABLE "audit_events" (
  "sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "event_id" text COLLATE "C" NOT NULL,
  "source_id" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL DEFAULT 1,
  "source_sequence" bigint NOT NULL,
  "occurred_at" bigint NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "error_code" text COLLATE "C",
  "actor_type" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C",
  "session_key" text COLLATE "C",
  "session_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "tool_call_id" text COLLATE "C",
  "tool_name" text COLLATE "C",
  "direction" text COLLATE "C",
  "channel" text COLLATE "C",
  "conversation_kind" text COLLATE "C",
  "message_outcome" text COLLATE "C",
  "reason_code" text COLLATE "C",
  "delivery_kind" text COLLATE "C",
  "failure_stage" text COLLATE "C",
  "duration_ms" bigint,
  "result_count" bigint,
  "account_ref" text COLLATE "C",
  "conversation_ref" text COLLATE "C",
  "message_ref" text COLLATE "C",
  "target_ref" text COLLATE "C",
  PRIMARY KEY ("sequence"),
  UNIQUE ("event_id"),
  UNIQUE ("source_id")
);

CREATE TABLE "audit_identity_keys" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "key_id" text COLLATE "C" NOT NULL,
  "key" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("id" = 1))
);

CREATE TABLE "backup_runs" (
  "id" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "archive_path" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "manifest_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE "capture_blobs" (
  "blob_id" text COLLATE "C" NOT NULL,
  "content_type" text COLLATE "C",
  "encoding" text COLLATE "C" NOT NULL,
  "size_bytes" bigint NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  "data" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("blob_id")
);

CREATE TABLE "capture_events" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "ts" bigint NOT NULL,
  "source_scope" text COLLATE "C" NOT NULL,
  "source_process" text COLLATE "C" NOT NULL,
  "protocol" text COLLATE "C" NOT NULL,
  "direction" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "flow_id" text COLLATE "C" NOT NULL,
  "method" text COLLATE "C",
  "host" text COLLATE "C",
  "path" text COLLATE "C",
  "status" bigint,
  "close_code" bigint,
  "content_type" text COLLATE "C",
  "headers_json" text COLLATE "C",
  "data_text" text COLLATE "C",
  "data_blob_id" text COLLATE "C",
  "data_sha256" text COLLATE "C",
  "error_text" text COLLATE "C",
  "meta_json" text COLLATE "C",
  PRIMARY KEY ("id")
);

CREATE TABLE "capture_sessions" (
  "id" text COLLATE "C" NOT NULL,
  "started_at" bigint NOT NULL,
  "ended_at" bigint,
  "mode" text COLLATE "C" NOT NULL,
  "source_scope" text COLLATE "C" NOT NULL,
  "source_process" text COLLATE "C" NOT NULL,
  "proxy_url" text COLLATE "C",
  PRIMARY KEY ("id")
);

CREATE TABLE "channel_ingress_events" (
  "queue_name" text COLLATE "C" NOT NULL,
  "event_id" text COLLATE "C" NOT NULL,
  "channel_id" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "lane_key" text COLLATE "C",
  "payload_json" text COLLATE "C" NOT NULL,
  "metadata_json" text COLLATE "C",
  "received_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "claim_token" text COLLATE "C",
  "claim_owner" text COLLATE "C",
  "claimed_at" bigint,
  "attempts" bigint NOT NULL DEFAULT 0,
  "last_attempt_at" bigint,
  "last_error" text COLLATE "C",
  "failed_reason" text COLLATE "C",
  "failed_at" bigint,
  "completed_at" bigint,
  "completed_metadata_json" text COLLATE "C",
  PRIMARY KEY ("queue_name", "event_id")
);

CREATE TABLE "channel_pairing_allow_entries" (
  "channel_key" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "entry" text COLLATE "C" NOT NULL,
  "sort_order" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("channel_key", "account_id", "entry")
);

CREATE TABLE "channel_pairing_requests" (
  "channel_key" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "request_id" text COLLATE "C" NOT NULL,
  "code" text COLLATE "C" NOT NULL,
  "created_at" text COLLATE "C" NOT NULL,
  "last_seen_at" text COLLATE "C" NOT NULL,
  "meta_json" text COLLATE "C",
  PRIMARY KEY ("channel_key", "account_id", "request_id")
);

CREATE TABLE "clawhub_promotion_claims" (
  "slug" text COLLATE "C" NOT NULL,
  "provider" text COLLATE "C",
  "model_keys_json" text COLLATE "C" NOT NULL,
  "ends_at_ms" bigint NOT NULL,
  "claimed_at_ms" bigint NOT NULL,
  PRIMARY KEY ("slug")
);

CREATE TABLE "config_health_entries" (
  "config_path" text COLLATE "C" NOT NULL,
  "last_known_good_json" text COLLATE "C",
  "last_promoted_good_json" text COLLATE "C",
  "last_observed_suspicious_signature" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("config_path")
);

CREATE TABLE "config_machine_state" (
  "state_key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("state_key")
);

CREATE TABLE "cron_job_scratch" (
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "content" text COLLATE "C",
  "revision" bigint NOT NULL,
  "source_sha256" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("store_key", "job_id"),
  CHECK (("revision" >= 1)),
  CHECK ("content" IS NULL OR (octet_length(convert_to("content", 'UTF8')) <= 262144))
);

CREATE TABLE "cron_jobs" (
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "declaration_key" text COLLATE "C",
  "owner_agent_id" text COLLATE "C",
  "name" text COLLATE "C" NOT NULL,
  "description" text COLLATE "C",
  "enabled" bigint NOT NULL,
  "agent_id" text COLLATE "C",
  "payload_kind" text COLLATE "C" NOT NULL,
  "job_json" text COLLATE "C" NOT NULL,
  "grant_definition_revision" text COLLATE "C",
  "grant_definition_generation" bigint,
  "grant_definition_updated_at" bigint,
  "state_json" text COLLATE "C" NOT NULL DEFAULT '{}',
  "runtime_updated_at_ms" bigint,
  "schedule_identity" text COLLATE "C",
  "sort_order" bigint NOT NULL DEFAULT 0,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("store_key", "job_id")
);

CREATE TABLE "current_conversation_bindings" (
  "binding_key" text COLLATE "C" NOT NULL,
  "binding_id" text COLLATE "C" NOT NULL,
  "target_session_key" text COLLATE "C" NOT NULL,
  "channel" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "conversation_kind" text COLLATE "C" NOT NULL,
  "parent_conversation_id" text COLLATE "C",
  "conversation_id" text COLLATE "C" NOT NULL,
  "target_kind" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "bound_at" bigint NOT NULL,
  "expires_at" bigint,
  "metadata_json" text COLLATE "C",
  "record_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("binding_key")
);

CREATE TABLE "delivery_queue_entries" (
  "queue_name" text COLLATE "C" NOT NULL,
  "id" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "entry_kind" text COLLATE "C",
  "session_key" text COLLATE "C",
  "channel" text COLLATE "C",
  "target" text COLLATE "C",
  "account_id" text COLLATE "C",
  "retry_count" bigint NOT NULL DEFAULT 0,
  "last_attempt_at" bigint,
  "last_error" text COLLATE "C",
  "recovery_state" text COLLATE "C",
  "platform_send_started_at" bigint,
  "entry_json" text COLLATE "C" NOT NULL,
  "retention_id_prefix" text COLLATE "C",
  "retention_max_age_ms" bigint,
  "retention_max_entries" bigint,
  "enqueued_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "failed_at" bigint,
  PRIMARY KEY ("queue_name", "id")
);

CREATE TABLE "device_bootstrap_tokens" (
  "token_key" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "setup_id" text COLLATE "C",
  "ts" bigint NOT NULL,
  "device_id" text COLLATE "C",
  "public_key" text COLLATE "C",
  "profile_json" text COLLATE "C",
  "redeemed_profile_json" text COLLATE "C",
  "pending_profile_json" text COLLATE "C",
  "issued_at_ms" bigint NOT NULL,
  "last_used_at_ms" bigint,
  PRIMARY KEY ("token_key")
);

CREATE TABLE "device_pairing_paired" (
  "device_id" text COLLATE "C" NOT NULL,
  "public_key" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C",
  "operator_label" text COLLATE "C",
  "platform" text COLLATE "C",
  "device_family" text COLLATE "C",
  "client_id" text COLLATE "C",
  "client_mode" text COLLATE "C",
  "browser_origin" text COLLATE "C",
  "role" text COLLATE "C",
  "roles_json" text COLLATE "C",
  "scopes_json" text COLLATE "C",
  "approved_scopes_json" text COLLATE "C",
  "remote_ip" text COLLATE "C",
  "tokens_json" text COLLATE "C",
  "approved_via" text COLLATE "C",
  "node_surface_json" text COLLATE "C",
  "pending_node_surface_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "approved_at_ms" bigint NOT NULL,
  "last_seen_at_ms" bigint,
  "last_seen_reason" text COLLATE "C",
  PRIMARY KEY ("device_id")
);

CREATE TABLE "device_pairing_pending" (
  "request_id" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "public_key" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C",
  "platform" text COLLATE "C",
  "device_family" text COLLATE "C",
  "client_id" text COLLATE "C",
  "client_mode" text COLLATE "C",
  "browser_origin" text COLLATE "C",
  "role" text COLLATE "C",
  "roles_json" text COLLATE "C",
  "scopes_json" text COLLATE "C",
  "remote_ip" text COLLATE "C",
  "silent" bigint,
  "is_repair" bigint,
  "ts" bigint NOT NULL,
  "refreshed_at_ms" bigint,
  PRIMARY KEY ("request_id")
);

CREATE TABLE "diagnostic_events" (
  "scope" text COLLATE "C" NOT NULL,
  "event_key" text COLLATE "C" NOT NULL,
  "payload_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "sequence" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("scope", "event_key")
);

CREATE TABLE "exec_approvals_config" (
  "config_key" text COLLATE "C" NOT NULL,
  "raw_json" text COLLATE "C" NOT NULL,
  "socket_path" text COLLATE "C",
  "has_socket_token" bigint NOT NULL,
  "default_security" text COLLATE "C",
  "default_ask" text COLLATE "C",
  "default_ask_fallback" text COLLATE "C",
  "auto_allow_skills" bigint,
  "agent_count" bigint NOT NULL,
  "allowlist_count" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("config_key")
);

CREATE TABLE "flow_runs" (
  "flow_id" text COLLATE "C" NOT NULL,
  "shape" text COLLATE "C",
  "sync_mode" text COLLATE "C" NOT NULL DEFAULT 'managed',
  "owner_key" text COLLATE "C" NOT NULL,
  "requester_origin_json" text COLLATE "C",
  "controller_id" text COLLATE "C",
  "revision" bigint NOT NULL DEFAULT 0,
  "status" text COLLATE "C" NOT NULL,
  "notify_policy" text COLLATE "C" NOT NULL,
  "goal" text COLLATE "C" NOT NULL,
  "current_step" text COLLATE "C",
  "blocked_task_id" text COLLATE "C",
  "blocked_summary" text COLLATE "C",
  "state_json" text COLLATE "C",
  "wait_json" text COLLATE "C",
  "cancel_requested_at" bigint,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "ended_at" bigint,
  PRIMARY KEY ("flow_id")
);

CREATE TABLE "gateway_boot_lifecycle" (
  "boot_id" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "started_at_ms" bigint NOT NULL,
  "completed_at_ms" bigint,
  "outcome" text COLLATE "C",
  "startup_reason" text COLLATE "C",
  "reason" text COLLATE "C",
  PRIMARY KEY ("boot_id")
);

CREATE TABLE "gateway_restart_handoff" (
  "handoff_key" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "version" bigint NOT NULL,
  "intent_id" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "process_instance_id" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "expires_at" bigint NOT NULL,
  "reason" text COLLATE "C",
  "restart_trace_started_at" bigint,
  "restart_trace_last_at" bigint,
  "source" text COLLATE "C" NOT NULL,
  "restart_kind" text COLLATE "C" NOT NULL,
  "supervisor_mode" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("handoff_key")
);

CREATE TABLE "gateway_restart_intent" (
  "intent_key" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "reason" text COLLATE "C",
  "force" bigint,
  "wait_ms" bigint,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("intent_key")
);

CREATE TABLE "gateway_restart_sentinel" (
  "sentinel_key" text COLLATE "C" NOT NULL,
  "version" bigint NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "ts" bigint NOT NULL,
  "session_key" text COLLATE "C",
  "thread_id" text COLLATE "C",
  "delivery_channel" text COLLATE "C",
  "delivery_to" text COLLATE "C",
  "delivery_account_id" text COLLATE "C",
  "message" text COLLATE "C",
  "continuation_json" text COLLATE "C",
  "doctor_hint" text COLLATE "C",
  "stats_json" text COLLATE "C",
  "payload_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("sentinel_key")
);

CREATE TABLE "macos_port_guardian_records" (
  "pid" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "port" bigint NOT NULL,
  "command" text COLLATE "C" NOT NULL,
  "mode" text COLLATE "C" NOT NULL,
  "timestamp" double precision NOT NULL,
  PRIMARY KEY ("pid")
);

CREATE TABLE "managed_outgoing_image_records" (
  "attachment_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C",
  "message_id" text COLLATE "C",
  "created_at" text COLLATE "C" NOT NULL,
  "updated_at" text COLLATE "C",
  "retention_class" text COLLATE "C",
  "alt" text COLLATE "C" NOT NULL,
  "original_media_root" text COLLATE "C" NOT NULL,
  "original_media_id" text COLLATE "C" NOT NULL,
  "original_media_subdir" text COLLATE "C" NOT NULL,
  "original_content_type" text COLLATE "C" NOT NULL,
  "original_width" bigint,
  "original_height" bigint,
  "original_size_bytes" bigint,
  "original_filename" text COLLATE "C",
  "record_json" text COLLATE "C" NOT NULL,
  "cleanup_pending" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("attachment_id"),
  CHECK (("cleanup_pending" IN (0, 1)))
);

CREATE TABLE "mcp_oauth_stores" (
  "store_key" text COLLATE "C" NOT NULL,
  "format_version" bigint NOT NULL,
  "store_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("store_key"),
  CHECK (("format_version" = 1))
);

CREATE TABLE "meeting_transcript_sessions" (
  "started_at_ms" bigint,
  "session_id" text COLLATE "C" NOT NULL,
  "started_at" text COLLATE "C" NOT NULL,
  "selector" text COLLATE "C" NOT NULL,
  "export_key" text COLLATE "C" NOT NULL,
  "session_slug" text COLLATE "C" NOT NULL,
  "provider_id" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "source_json" text COLLATE "C" NOT NULL,
  "source_account_id" text COLLATE "C",
  "source_guild_id" text COLLATE "C",
  "source_channel_id" text COLLATE "C",
  "source_meeting_url" text COLLATE "C",
  "source_thread_ts" text COLLATE "C",
  "source_file_id" text COLLATE "C",
  "stopped_at" text COLLATE "C",
  "metadata_json" text COLLATE "C",
  "metadata_agent_id" text COLLATE "C",
  "export_manifest_json" text COLLATE "C" NOT NULL DEFAULT '{}',
  "export_pending_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "next_utterance_seq" bigint NOT NULL DEFAULT 0,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "started_at"),
  CHECK (("next_utterance_seq" >= 0)),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  UNIQUE ("selector")
);

CREATE TABLE "meeting_transcript_summaries" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_started_at" text COLLATE "C" NOT NULL,
  "generated_at" text COLLATE "C",
  "summary_json" text COLLATE "C",
  "overview" text COLLATE "C",
  "markdown" text COLLATE "C",
  "utterance_count" bigint NOT NULL,
  PRIMARY KEY ("session_id", "session_started_at"),
  CHECK (("utterance_count" >= 0)),
  CHECK ("summary_json" IS NOT NULL OR "markdown" IS NOT NULL)
);

CREATE TABLE "meeting_transcript_utterances" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_started_at" text COLLATE "C" NOT NULL,
  "sequence" bigint NOT NULL,
  "utterance_id" text COLLATE "C",
  "started_at" text COLLATE "C",
  "ended_at" text COLLATE "C",
  "speaker_id" text COLLATE "C",
  "speaker_label" text COLLATE "C",
  "text" text COLLATE "C" NOT NULL,
  "final" bigint,
  "metadata_json" text COLLATE "C",
  PRIMARY KEY ("session_id", "session_started_at", "sequence"),
  CHECK (("sequence" >= 0)),
  CHECK (("final" IN (0, 1)))
);

CREATE TABLE "migration_runs" (
  "id" text COLLATE "C" NOT NULL,
  "started_at" bigint NOT NULL,
  "finished_at" bigint,
  "status" text COLLATE "C" NOT NULL,
  "report_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE "migration_sources" (
  "source_key" text COLLATE "C" NOT NULL,
  "migration_kind" text COLLATE "C" NOT NULL,
  "source_path" text COLLATE "C" NOT NULL,
  "target_table" text COLLATE "C" NOT NULL,
  "source_sha256" text COLLATE "C",
  "source_size_bytes" bigint,
  "source_record_count" bigint,
  "last_run_id" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "imported_at" bigint NOT NULL,
  "removed_source" bigint NOT NULL DEFAULT 0,
  "report_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("source_key")
);

CREATE TABLE "native_hook_relay_bridges" (
  "relay_id" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "hostname" text COLLATE "C" NOT NULL,
  "port" bigint NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("relay_id")
);

CREATE TABLE "official_external_plugin_catalog_snapshots" (
  "feed_url" text COLLATE "C" NOT NULL,
  "body" text COLLATE "C" NOT NULL,
  "status" bigint NOT NULL,
  "etag" text COLLATE "C",
  "last_modified" text COLLATE "C",
  "checksum" text COLLATE "C" NOT NULL,
  "saved_at" text COLLATE "C" NOT NULL,
  "trust_mode" text COLLATE "C",
  "trust_key_id" text COLLATE "C",
  "trust_signature_count" bigint,
  "trust_threshold" bigint,
  "trust_verified_at" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("feed_url")
);

CREATE TABLE "operator_approvals" (
  "cursor_id" bigint NOT NULL,
  "approval_id" text COLLATE "C" NOT NULL,
  "resolution_ref" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "presentation_json" text COLLATE "C" NOT NULL,
  "requested_by_device_id" text COLLATE "C",
  "requested_by_client_id" text COLLATE "C",
  "requested_by_device_token_auth" bigint NOT NULL DEFAULT 0,
  "reviewer_device_ids_json" text COLLATE "C" NOT NULL,
  "source_agent_id" text COLLATE "C",
  "source_session_key" text COLLATE "C",
  "source_session_id" text COLLATE "C",
  "source_run_id" text COLLATE "C",
  "source_tool_call_id" text COLLATE "C",
  "source_tool_name" text COLLATE "C",
  "audience_session_keys_json" text COLLATE "C" NOT NULL,
  "runtime_epoch" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "decision" text COLLATE "C",
  "terminal_reason" text COLLATE "C",
  "resolved_at_ms" bigint,
  "resolver_kind" text COLLATE "C",
  "resolver_id" text COLLATE "C",
  "consumed_at_ms" bigint,
  "consumed_by" text COLLATE "C",
  PRIMARY KEY ("approval_id"),
  CHECK ((char_length("approval_id") > 0) AND ("approval_id" NOT IN ('.', '..'))),
  CHECK ((char_length("resolution_ref") = 43) AND ("resolution_ref" COLLATE "C" !~ '\\A.*[^A-Za-z0-9_-].*\\Z')),
  CHECK (("kind" IN ('exec', 'plugin', 'system-agent'))),
  CHECK (("status" IN ('pending', 'allowed', 'denied', 'expired', 'cancelled'))),
  CHECK (("decision" IN ('allow-once', 'allow-always', 'deny'))),
  CHECK (("terminal_reason" IN ('user', 'timeout', 'malformed-verdict', 'no-route', 'run-aborted', 'gateway-restart', 'storage-corrupt'))),
  CHECK (("resolver_kind" IN ('device', 'channel', 'runtime', 'system'))),
  CHECK (("expires_at_ms" >= "created_at_ms")),
  CHECK (("updated_at_ms" >= "created_at_ms")),
  CHECK ("resolved_at_ms" IS NULL OR ("resolved_at_ms" >= "created_at_ms")),
  CHECK ("resolved_at_ms" IS NULL OR ("resolved_at_ms" <= "updated_at_ms")),
  CHECK ("consumed_at_ms" IS NULL OR ("consumed_at_ms" >= "resolved_at_ms")),
  CHECK ("consumed_at_ms" IS NULL OR ("consumed_at_ms" <= "updated_at_ms")),
  CHECK (("requested_by_device_token_auth" IN (0, 1))),
  CHECK ((("status" = 'pending') AND "decision" IS NULL AND "terminal_reason" IS NULL AND "resolved_at_ms" IS NULL AND "resolver_kind" IS NULL AND "resolver_id" IS NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'allowed') AND ("decision" IN ('allow-once', 'allow-always')) AND ("terminal_reason" = 'user') AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL) OR (("status" = 'denied') AND ("decision" = 'deny') AND ("terminal_reason" IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')) AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'expired') AND ("decision" = 'deny') AND ("terminal_reason" = 'timeout') AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'cancelled') AND ("decision" = 'deny') AND ("terminal_reason" IN ('run-aborted', 'gateway-restart')) AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL)),
  CHECK (("consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'allowed') AND ("decision" = 'allow-once') AND "consumed_at_ms" IS NOT NULL AND "consumed_by" IS NOT NULL))
);

CREATE TABLE "outbound_media_provenance" (
  "realpath" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "version" bigint NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  "size_bytes" bigint NOT NULL,
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("realpath")
);

CREATE TABLE "plugin_binding_approvals" (
  "plugin_root" text COLLATE "C" NOT NULL,
  "channel" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "plugin_id" text COLLATE "C" NOT NULL,
  "plugin_name" text COLLATE "C",
  "approved_at" bigint NOT NULL,
  PRIMARY KEY ("plugin_root", "channel", "account_id")
);

CREATE TABLE "plugin_blob_entries" (
  "plugin_id" text COLLATE "C" NOT NULL,
  "namespace" text COLLATE "C" NOT NULL,
  "entry_key" text COLLATE "C" NOT NULL,
  "metadata_json" text COLLATE "C" NOT NULL,
  "blob" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  "expires_at" bigint,
  PRIMARY KEY ("plugin_id", "namespace", "entry_key")
);

CREATE TABLE "plugin_state_entries" (
  "plugin_id" text COLLATE "C" NOT NULL,
  "namespace" text COLLATE "C" NOT NULL,
  "entry_key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "expires_at" bigint,
  PRIMARY KEY ("plugin_id", "namespace", "entry_key")
);

CREATE TABLE "sandbox_registry_entries" (
  "registry_kind" text COLLATE "C" NOT NULL,
  "container_name" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C",
  "backend_id" text COLLATE "C",
  "runtime_label" text COLLATE "C",
  "image" text COLLATE "C",
  "created_at_ms" bigint,
  "last_used_at_ms" bigint,
  "config_label_kind" text COLLATE "C",
  "config_hash" text COLLATE "C",
  "cdp_port" bigint,
  "no_vnc_port" bigint,
  "entry_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("registry_kind", "container_name")
);

CREATE TABLE "schema_meta" (
  "meta_key" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL,
  "agent_id" text COLLATE "C",
  "app_version" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("meta_key")
);

CREATE TABLE "session_groups" (
  "name" text COLLATE "C" NOT NULL,
  "position" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "cwd" text COLLATE "C",
  "worktree" bigint,
  PRIMARY KEY ("name")
);

CREATE TABLE "session_state_events" (
  "sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "dedupe_key" text COLLATE "C",
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "agent_id" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "actor_type" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "occurred_at" bigint NOT NULL,
  "summary" text COLLATE "C" NOT NULL,
  "payload_json" text COLLATE "C",
  PRIMARY KEY ("sequence"),
  UNIQUE ("dedupe_key")
);

CREATE TABLE "session_state_heads" (
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "last_sequence" bigint NOT NULL,
  "pruned_max_sequence" bigint NOT NULL DEFAULT 0,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "agent_id")
);

CREATE TABLE "session_upstream_links" (
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "catalog_id" text COLLATE "C" NOT NULL,
  "host_id" text COLLATE "C" NOT NULL,
  "thread_id" text COLLATE "C" NOT NULL,
  "upstream_kind" text COLLATE "C" NOT NULL,
  "upstream_ref_json" text COLLATE "C",
  "last_marker_json" text COLLATE "C",
  "last_scanned_at" bigint,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "agent_id")
);

CREATE TABLE "session_watch_cursors" (
  "watcher_session_key" text COLLATE "C" NOT NULL,
  "watcher_store_path" text COLLATE "C",
  "target_session_key" text COLLATE "C" NOT NULL,
  "last_seen_sequence" bigint NOT NULL DEFAULT 0,
  "notified_sequence" bigint NOT NULL DEFAULT 0,
  "material_sequence" bigint NOT NULL DEFAULT 0,
  "provenance" text COLLATE "C" NOT NULL DEFAULT 'explicit',
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("watcher_session_key", "target_session_key"),
  CHECK (("provenance" IN ('explicit', 'ambient-group')))
);

CREATE TABLE "skill_upload_chunks" (
  "upload_id" text COLLATE "C" NOT NULL,
  "byte_offset" bigint NOT NULL,
  "size_bytes" bigint NOT NULL,
  "chunk_blob" bytea NOT NULL,
  PRIMARY KEY ("upload_id", "byte_offset"),
  CHECK (("byte_offset" >= 0)),
  CHECK (("size_bytes" > 0)),
  CHECK ((octet_length("chunk_blob") = "size_bytes"))
);

CREATE TABLE "skill_uploads" (
  "upload_id" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "slug" text COLLATE "C" NOT NULL,
  "force" bigint NOT NULL,
  "size_bytes" bigint NOT NULL,
  "sha256" text COLLATE "C",
  "actual_sha256" text COLLATE "C",
  "received_bytes" bigint NOT NULL,
  "archive_blob" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  "expires_at" bigint NOT NULL,
  "committed" bigint NOT NULL,
  "committed_at" bigint,
  "idempotency_key_hash" text COLLATE "C",
  PRIMARY KEY ("upload_id"),
  UNIQUE ("idempotency_key_hash")
);

CREATE TABLE "skill_usage" (
  "skill_file" text COLLATE "C" NOT NULL,
  "skill_key" text COLLATE "C" NOT NULL,
  "skill_name" text COLLATE "C" NOT NULL,
  "skill_source" text COLLATE "C" NOT NULL,
  "first_used_at_ms" bigint NOT NULL,
  "last_used_at_ms" bigint NOT NULL,
  "use_count" bigint NOT NULL,
  "last_agent_id" text COLLATE "C",
  PRIMARY KEY ("skill_file")
);

CREATE TABLE "state_leases" (
  "scope" text COLLATE "C" NOT NULL,
  "lease_key" text COLLATE "C" NOT NULL,
  "owner" text COLLATE "C" NOT NULL,
  "expires_at" bigint,
  "heartbeat_at" bigint,
  "payload_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("scope", "lease_key")
);

CREATE TABLE "subagent_runs" (
  "run_id" text COLLATE "C" NOT NULL,
  "child_session_key" text COLLATE "C" NOT NULL,
  "controller_session_key" text COLLATE "C",
  "controller_store_path" text COLLATE "C",
  "requester_session_key" text COLLATE "C" NOT NULL,
  "requester_store_path" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "payload_json" text COLLATE "C" NOT NULL DEFAULT '{}',
  PRIMARY KEY ("run_id")
);

CREATE TABLE "task_delivery_state" (
  "task_id" text COLLATE "C" NOT NULL,
  "requester_origin_json" text COLLATE "C",
  "last_notified_event_at" bigint,
  PRIMARY KEY ("task_id")
);

CREATE TABLE "task_runs" (
  "task_id" text COLLATE "C" NOT NULL,
  "runtime" text COLLATE "C" NOT NULL,
  "task_kind" text COLLATE "C",
  "source_id" text COLLATE "C",
  "requester_session_key" text COLLATE "C",
  "owner_key" text COLLATE "C" NOT NULL,
  "scope_kind" text COLLATE "C" NOT NULL,
  "child_session_key" text COLLATE "C",
  "parent_flow_id" text COLLATE "C",
  "parent_task_id" text COLLATE "C",
  "agent_id" text COLLATE "C",
  "requester_agent_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "execution_owner_host" text COLLATE "C",
  "execution_owner_pid" bigint,
  "execution_owner_start_identity" bigint,
  "label" text COLLATE "C",
  "task" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "delivery_status" text COLLATE "C" NOT NULL,
  "notify_policy" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "started_at" bigint,
  "ended_at" bigint,
  "last_event_at" bigint,
  "cleanup_after" bigint,
  "tool_use_count" bigint,
  "last_tool_name" text COLLATE "C",
  "error" text COLLATE "C",
  "progress_summary" text COLLATE "C",
  "terminal_summary" text COLLATE "C",
  "terminal_outcome" text COLLATE "C",
  "detail_json" text COLLATE "C",
  PRIMARY KEY ("task_id")
);

CREATE TABLE "template_cron_refs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "manifest_id" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "declaration_key" text COLLATE "C" NOT NULL,
  "scheduler_job_id" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "job_json" text COLLATE "C" NOT NULL,
  "error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "manifest_id"),
  UNIQUE ("declaration_key"),
  UNIQUE ("scheduler_job_id")
);

CREATE TABLE "template_installs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "source_kind" text COLLATE "C" NOT NULL,
  "template_name" text COLLATE "C" NOT NULL,
  "template_version" text COLLATE "C" NOT NULL,
  "package_root" text COLLATE "C" NOT NULL,
  "manifest_path" text COLLATE "C" NOT NULL,
  "integrity_kind" text COLLATE "C" NOT NULL,
  "integrity" text COLLATE "C" NOT NULL,
  "source_byte_length" bigint NOT NULL,
  "manifest_schema_version" bigint NOT NULL,
  "plan_integrity" text COLLATE "C" NOT NULL,
  "workspace" text COLLATE "C" NOT NULL,
  "agent_config_digest" text COLLATE "C" NOT NULL,
  "agent_owned_paths_json" text COLLATE "C" NOT NULL,
  "bootstrap_source_path" text COLLATE "C",
  "bootstrap_content_digest" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "added_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id"),
  CHECK (("status" IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial'))),
  UNIQUE ("workspace")
);

CREATE TABLE "template_mcp_server_refs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "name" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "config_digest" text COLLATE "C" NOT NULL,
  "relationship" text COLLATE "C" NOT NULL,
  "origin" text COLLATE "C" NOT NULL,
  "independent_owner" bigint NOT NULL DEFAULT 0,
  "status" text COLLATE "C" NOT NULL,
  "error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "name"),
  CHECK (("relationship" IN ('managed', 'referenced'))),
  CHECK (("origin" IN ('template-introduced', 'pre-existing'))),
  CHECK (("independent_owner" IN (0, 1)))
);

CREATE TABLE "template_package_refs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "package_kind" text COLLATE "C" NOT NULL,
  "package_source" text COLLATE "C" NOT NULL,
  "package_ref" text COLLATE "C" NOT NULL,
  "package_version" text COLLATE "C" NOT NULL,
  "package_integrity" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "template_name" text COLLATE "C" NOT NULL,
  "package_status" text COLLATE "C" NOT NULL,
  "relationship" text COLLATE "C" NOT NULL,
  "origin" text COLLATE "C" NOT NULL,
  "independent_owner" bigint NOT NULL,
  "extension_id" text COLLATE "C",
  "extension_format" text COLLATE "C",
  "extension_detected_format" text COLLATE "C",
  "extension_mapped_json" text COLLATE "C",
  "extension_unavailable_json" text COLLATE "C",
  "extension_adapter_identity" text COLLATE "C",
  "installed_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "package_kind", "package_source", "package_ref", "package_version"),
  CHECK (("relationship" IN ('managed', 'referenced'))),
  CHECK (("origin" IN ('template-introduced', 'pre-existing'))),
  CHECK (("independent_owner" IN (0, 1)))
);

CREATE TABLE "template_workspace_files" (
  "agent_id" text COLLATE "C" NOT NULL,
  "target_path" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "workspace" text COLLATE "C" NOT NULL,
  "source_path" text COLLATE "C" NOT NULL,
  "content_digest" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "target_path")
);

CREATE TABLE "web_push_subscriptions" (
  "endpoint_hash" text COLLATE "C" NOT NULL,
  "subscription_id" text COLLATE "C" NOT NULL,
  "endpoint" text COLLATE "C" NOT NULL,
  "p256dh" text COLLATE "C" NOT NULL,
  "auth" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C",
  "user_profile_id" text COLLATE "C",
  "preferences_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("endpoint_hash"),
  UNIQUE ("subscription_id")
);

CREATE TABLE "worker_environment_credentials" (
  "environment_id" text COLLATE "C" NOT NULL,
  "credential_hash" text COLLATE "C" NOT NULL,
  "bundle_hash" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "rpc_set_version" bigint NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  "delivered_at_ms" bigint,
  PRIMARY KEY ("environment_id"),
  CHECK (("rpc_set_version" >= 1)),
  CHECK (("owner_epoch" >= 0)),
  CHECK (("expires_at_ms" >= 0)),
  CHECK (("delivered_at_ms" >= 0)),
  UNIQUE ("credential_hash")
);

CREATE TABLE "worker_environments" (
  "environment_id" text COLLATE "C" NOT NULL,
  "provider_id" text COLLATE "C" NOT NULL,
  "profile_id" text COLLATE "C" NOT NULL,
  "profile_snapshot_json" text COLLATE "C" NOT NULL,
  "last_activated_at_ms" bigint,
  "preparation_key" text COLLATE "C",
  "preparation_purpose" text COLLATE "C",
  "preparation_demand_at_ms" bigint,
  "preparation_expires_at_ms" bigint,
  "preparation_consumed_at_ms" bigint,
  "provision_operation_id" text COLLATE "C" NOT NULL,
  "lease_id" text COLLATE "C",
  "node_setup_id" text COLLATE "C",
  "node_device_id" text COLLATE "C",
  "ssh_host" text COLLATE "C",
  "ssh_port" bigint,
  "ssh_user" text COLLATE "C",
  "ssh_host_key" text COLLATE "C",
  "ssh_key_ref_json" text COLLATE "C",
  "desktop_json" text COLLATE "C",
  "state" text COLLATE "C" NOT NULL,
  "bootstrap_bundle_hash" text COLLATE "C",
  "bootstrap_openclaw_version" text COLLATE "C",
  "bootstrap_protocol_features_json" text COLLATE "C",
  "bootstrap_install_kind" text COLLATE "C",
  "owner_epoch" bigint NOT NULL DEFAULT 0,
  "teardown_terminal_state" text COLLATE "C",
  "attached_session_ids_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "state_changed_at_ms" bigint NOT NULL,
  "idle_since_at_ms" bigint,
  "destroy_requested_at_ms" bigint,
  "last_error" text COLLATE "C",
  "shared_host" bigint,
  "resource_receipt_json" text COLLATE "C",
  "retention_json" text COLLATE "C",
  "provision_source_json" text COLLATE "C",
  PRIMARY KEY ("environment_id"),
  CHECK (("preparation_key" IS NULL AND "preparation_demand_at_ms" IS NULL AND "preparation_expires_at_ms" IS NULL AND "preparation_consumed_at_ms" IS NULL) OR ("preparation_key" IS NOT NULL AND (char_length("preparation_key") = 64) AND ("preparation_key" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z') AND "preparation_demand_at_ms" IS NOT NULL AND ("preparation_demand_at_ms" BETWEEN 0 AND 9007199254740991) AND "preparation_expires_at_ms" IS NOT NULL AND ("preparation_expires_at_ms" > "preparation_demand_at_ms") AND ("preparation_expires_at_ms" <= 9007199254740991) AND ("preparation_consumed_at_ms" IS NULL OR (("preparation_consumed_at_ms" >= "preparation_demand_at_ms") AND ("preparation_consumed_at_ms" < "preparation_expires_at_ms"))))),
  CHECK ("ssh_port" IS NULL OR (("ssh_port" >= 1) AND ("ssh_port" <= 65535))),
  CHECK (("state" IN ('requested', 'provisioning', 'bootstrapping', 'ready', 'attached', 'idle', 'draining', 'destroying', 'destroyed', 'failed', 'orphaned'))),
  CHECK (("owner_epoch" >= 0)),
  CHECK (("teardown_terminal_state" IN ('destroyed', 'failed'))),
  UNIQUE ("provision_operation_id")
);

CREATE TABLE "worker_inference_turns" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_epoch" bigint NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "turn_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "request_hash" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "terminal_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_epoch", "run_id", "turn_id"),
  CHECK (("run_epoch" >= 0)),
  CHECK (("state" IN ('pending', 'terminal'))),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  CHECK ((("state" = 'pending') AND "terminal_json" IS NULL) OR (("state" = 'terminal') AND "terminal_json" IS NOT NULL))
);

CREATE TABLE "worker_session_placements" (
  "session_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "execution_mode" text COLLATE "C",
  "state" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C",
  "transition_generation" bigint NOT NULL DEFAULT 0,
  "active_owner_epoch" bigint,
  "workspace_base_manifest_ref" text COLLATE "C",
  "remote_workspace_dir" text COLLATE "C",
  "worker_bundle_hash" text COLLATE "C",
  "last_transcript_ack_cursor" bigint,
  "last_live_event_ack_cursor" bigint,
  "recovery_error" text COLLATE "C",
  "turn_claim_owner" text COLLATE "C",
  "turn_claim_id" text COLLATE "C",
  "turn_claim_run_id" text COLLATE "C",
  "turn_claim_generation" bigint,
  "turn_claim_owner_epoch" bigint,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "state_changed_at_ms" bigint NOT NULL,
  "terminal_reason" text COLLATE "C",
  "terminal_at_ms" bigint,
  PRIMARY KEY ("session_id"),
  CHECK (("execution_mode" IN ('worker-turn', 'remote-exec'))),
  CHECK (("state" IN ('local', 'requested', 'provisioning', 'syncing', 'starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed'))),
  CHECK (("transition_generation" >= 0)),
  CHECK ("active_owner_epoch" IS NULL OR ("active_owner_epoch" >= 1)),
  CHECK ("last_transcript_ack_cursor" IS NULL OR ("last_transcript_ack_cursor" >= 0)),
  CHECK ("last_live_event_ack_cursor" IS NULL OR ("last_live_event_ack_cursor" >= 0)),
  CHECK (("turn_claim_owner" IN ('local', 'worker'))),
  CHECK ("turn_claim_generation" IS NULL OR ("turn_claim_generation" >= 0)),
  CHECK ("turn_claim_owner_epoch" IS NULL OR ("turn_claim_owner_epoch" >= 1)),
  CHECK ((("state" IN ('local', 'requested')) AND "environment_id" IS NULL AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NULL AND "remote_workspace_dir" IS NULL AND "worker_bundle_hash" IS NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'provisioning' AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NULL AND "remote_workspace_dir" IS NULL AND "worker_bundle_hash" IS NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'syncing' AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NULL AND "remote_workspace_dir" IS NULL AND "worker_bundle_hash" IS NOT NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'starting' AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NOT NULL AND "remote_workspace_dir" IS NOT NULL AND "worker_bundle_hash" IS NOT NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR (("state" IN ('active', 'draining', 'reconciling')) AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NOT NULL AND "workspace_base_manifest_ref" IS NOT NULL AND "remote_workspace_dir" IS NOT NULL AND "worker_bundle_hash" IS NOT NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'reclaimed' AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NOT NULL AND "workspace_base_manifest_ref" IS NOT NULL AND "remote_workspace_dir" IS NOT NULL AND "worker_bundle_hash" IS NOT NULL AND "recovery_error" IS NULL AND "turn_claim_owner" IS NULL AND "turn_claim_id" IS NULL AND "turn_claim_run_id" IS NULL AND "turn_claim_generation" IS NULL AND "turn_claim_owner_epoch" IS NULL) OR ("state" IS NOT DISTINCT FROM 'failed' AND "recovery_error" IS NOT NULL)),
  CHECK (("turn_claim_owner" IS NULL AND "turn_claim_id" IS NULL AND "turn_claim_run_id" IS NULL AND "turn_claim_generation" IS NULL AND "turn_claim_owner_epoch" IS NULL) OR ("turn_claim_owner" IS NOT DISTINCT FROM 'local' AND "turn_claim_id" IS NOT NULL AND "turn_claim_run_id" IS NOT NULL AND "turn_claim_generation" IS NOT NULL AND "turn_claim_owner_epoch" IS NULL) OR ("turn_claim_owner" IS NOT DISTINCT FROM 'worker' AND "turn_claim_id" IS NOT NULL AND "turn_claim_run_id" IS NOT NULL AND "turn_claim_generation" IS NOT NULL AND "turn_claim_owner_epoch" IS NOT NULL)),
  CHECK ("turn_claim_owner" IS NULL OR ("turn_claim_owner" IS NOT DISTINCT FROM 'local' AND (("state" IN ('local', 'requested', 'failed')) OR (("state" IN ('active', 'draining')) AND "execution_mode" IS NOT DISTINCT FROM 'remote-exec'))) OR ("turn_claim_owner" IS NOT DISTINCT FROM 'worker' AND ("state" IN ('active', 'draining')) AND ("execution_mode" IS NULL OR "execution_mode" IS NOT DISTINCT FROM 'worker-turn') AND "turn_claim_owner_epoch" IS NOT DISTINCT FROM "active_owner_epoch"))
);

CREATE TABLE "worker_session_tool_operations" (
  "source_session_id" text COLLATE "C" NOT NULL,
  "source_claim_id" text COLLATE "C" NOT NULL,
  "tool_call_id" text COLLATE "C" NOT NULL,
  "tool_name" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "operation_seed" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "child_session_key" text COLLATE "C",
  "result_json" text COLLATE "C",
  "gateway_instance_id" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("source_session_id", "source_claim_id", "tool_call_id"),
  CHECK (("tool_name" IN ('sessions_spawn', 'sessions_send'))),
  CHECK (("status" IN ('running', 'succeeded', 'failed', 'unknown')))
);

CREATE TABLE "worker_transcript_commit_heads" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_epoch" bigint NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "next_seq" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_epoch"),
  CHECK (("run_epoch" >= 0)),
  CHECK (("next_seq" >= 1)),
  CHECK (("updated_at_ms" >= 0))
);

CREATE TABLE "worker_transcript_commits" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_epoch" bigint NOT NULL,
  "seq" bigint NOT NULL,
  "request_hash" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "result_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_epoch", "seq"),
  CHECK (("run_epoch" >= 0)),
  CHECK (("seq" >= 1)),
  CHECK (("state" IN ('pending', 'terminal'))),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  CHECK ((("state" = 'pending') AND "result_json" IS NULL) OR (("state" = 'terminal') AND "result_json" IS NOT NULL))
);

CREATE TABLE "worker_turn_tool_authorities" (
  "session_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "claim_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "tool_names_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id"),
  CHECK (("owner_epoch" >= 1)),
  CHECK (("placement_generation" >= 0))
);

CREATE TABLE "worker_workspace_pending_results" (
  "session_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "claim_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C" NOT NULL,
  "recovery_requested_at_ms" bigint,
  "workspace_accepted_at_ms" bigint,
  "staged_result_ref" text COLLATE "C",
  "repository_workspace_id" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "repository_disk_authority_json" text COLLATE "C",
  PRIMARY KEY ("session_id"),
  CHECK (("owner_epoch" >= 1)),
  CHECK (("placement_generation" >= 0))
);

CREATE TABLE "worker_workspace_reconciliations" (
  "session_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "base_manifest_ref" text COLLATE "C" NOT NULL,
  "current_manifest_ref" text COLLATE "C" NOT NULL,
  "plan_json" text COLLATE "C" NOT NULL,
  "base_pack" bytea NOT NULL,
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id"),
  CHECK (("owner_epoch" >= 1)),
  CHECK (("placement_generation" >= 0)),
  CHECK ((octet_length("base_pack") <= 268435456))
);

CREATE TABLE "workspace_generated_bootstrap_hashes" (
  "workspace_key" text COLLATE "C" NOT NULL,
  "filename" text COLLATE "C" NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("workspace_key", "filename")
);

CREATE TABLE "workspace_path_aliases" (
  "alias_key" text COLLATE "C" NOT NULL,
  "alias_path" text COLLATE "C" NOT NULL,
  "workspace_key" text COLLATE "C" NOT NULL,
  "workspace_path" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("alias_key")
);

CREATE TABLE "workspace_setup_state" (
  "workspace_key" text COLLATE "C" NOT NULL,
  "workspace_path" text COLLATE "C",
  "version" bigint,
  "bootstrap_seeded_at" text COLLATE "C",
  "setup_completed_at" text COLLATE "C",
  "updated_at" bigint,
  "attested_at_ms" bigint,
  "attestation_updated_at_ms" bigint,
  "bootstrap_deferred" bigint,
  PRIMARY KEY ("workspace_key"),
  CHECK ("version" IS NULL OR "workspace_path" IS NOT NULL)
);

CREATE TABLE "worktree_provisioned_file_chunks" (
  "worktree_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "chunk_index" bigint NOT NULL,
  "data" bytea NOT NULL,
  PRIMARY KEY ("worktree_id", "path", "chunk_index"),
  CHECK (("chunk_index" >= 0))
);

CREATE TABLE "worktrees" (
  "id" text COLLATE "C" NOT NULL,
  "repo_fingerprint" text COLLATE "C" NOT NULL,
  "repo_root" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "branch" text COLLATE "C" NOT NULL,
  "base_ref" text COLLATE "C" NOT NULL,
  "owner_kind" text COLLATE "C" NOT NULL,
  "owner_id" text COLLATE "C",
  "snapshot_ref" text COLLATE "C",
  "provisioned_paths_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "last_active_at" bigint NOT NULL,
  "removed_at" bigint,
  "run_end_cleanup_json" text COLLATE "C",
  "gc_protection_json" text COLLATE "C",
  PRIMARY KEY ("id"),
  CHECK (("owner_kind" IN ('manual', 'workboard', 'session')))
);

CREATE INDEX "idx_acp_replay_sessions_key_updated" ON "acp_replay_sessions" (("session_key") ASC, ("complete") ASC, ("updated_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_acp_replay_sessions_updated" ON "acp_replay_sessions" (("updated_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_acp_sessions_agent_activity" ON "acp_sessions" (("agent") ASC, ("last_activity_at") DESC, ("session_key") ASC);

CREATE INDEX "idx_acp_sessions_resume_acpx" ON "acp_sessions" (("resume_acpx_session_id") ASC NULLS FIRST);

CREATE INDEX "idx_acp_sessions_resume_agent" ON "acp_sessions" (("resume_agent_session_id") ASC NULLS FIRST);

CREATE INDEX "idx_acp_sessions_state_activity" ON "acp_sessions" (("state") ASC, ("last_activity_at") DESC, ("session_key") ASC);

CREATE INDEX "idx_apns_registrations_updated" ON "apns_registrations" (("updated_at_ms") DESC, ("node_id") ASC);

CREATE INDEX "idx_audit_events_agent_sequence" ON "audit_events" (("agent_id") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_channel_sequence" ON "audit_events" (("channel") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_direction_sequence" ON "audit_events" (("direction") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_kind_sequence" ON "audit_events" (("kind") ASC, ("sequence") DESC);

CREATE INDEX "idx_audit_events_run_sequence" ON "audit_events" (("run_id") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_session_sequence" ON "audit_events" (("session_key") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_status_sequence" ON "audit_events" (("status") ASC, ("sequence") DESC);

CREATE INDEX "idx_audit_events_time" ON "audit_events" (("occurred_at") DESC, ("sequence") DESC);

CREATE INDEX "idx_backup_runs_created" ON "backup_runs" (("created_at") DESC, ("id") ASC);

CREATE INDEX "capture_events_flow_idx" ON "capture_events" (("flow_id") ASC, ("ts") ASC);

CREATE INDEX "capture_events_session_ts_idx" ON "capture_events" (("session_id") ASC, ("ts") ASC);

CREATE INDEX "idx_channel_ingress_claims" ON "channel_ingress_events" (("queue_name") ASC, ("status") ASC, ("claimed_at") ASC NULLS FIRST);

CREATE INDEX "idx_channel_ingress_lane" ON "channel_ingress_events" (("queue_name") ASC, ("status") ASC, ("lane_key") ASC NULLS FIRST);

CREATE INDEX "idx_channel_ingress_pending" ON "channel_ingress_events" (("queue_name") ASC, ("status") ASC, ("received_at") ASC, ("event_id") ASC);

CREATE INDEX "idx_channel_pairing_allow_account" ON "channel_pairing_allow_entries" (("channel_key") ASC, ("account_id") ASC, ("sort_order") ASC, ("entry") ASC);

CREATE INDEX "idx_channel_pairing_requests_code" ON "channel_pairing_requests" (("channel_key") ASC, ("code") ASC);

CREATE INDEX "idx_channel_pairing_requests_created" ON "channel_pairing_requests" (("channel_key") ASC, ("created_at") ASC, ("request_id") ASC);

CREATE INDEX "idx_cron_job_scratch_store_updated" ON "cron_job_scratch" (("store_key") ASC, ("updated_at_ms") DESC, ("job_id") ASC);

CREATE INDEX "idx_cron_jobs_store_order" ON "cron_jobs" (("store_key") ASC, ("sort_order") ASC, ("updated_at") ASC, ("job_id") ASC);

CREATE INDEX "idx_current_conversation_bindings_conversation" ON "current_conversation_bindings" (("channel") ASC, ("account_id") ASC, ("conversation_kind") ASC, ("conversation_id") ASC);

CREATE INDEX "idx_current_conversation_bindings_expires" ON "current_conversation_bindings" (("expires_at") ASC NULLS FIRST, ("binding_key") ASC);

CREATE INDEX "idx_current_conversation_bindings_target" ON "current_conversation_bindings" (("target_session_key") ASC, ("updated_at") DESC, ("binding_key") ASC);

CREATE INDEX "idx_delivery_queue_bounded_retention" ON "delivery_queue_entries" (("queue_name") ASC, ("retention_id_prefix") ASC, ("enqueued_at") DESC, ("id") DESC) WHERE ("status" IN ('completed', 'failed')) AND ("recovery_state" = 'completed_bounded') AND "retention_id_prefix" IS NOT NULL;

CREATE INDEX "idx_delivery_queue_failed" ON "delivery_queue_entries" (("status") ASC, ("queue_name") ASC, ("failed_at") ASC NULLS FIRST, ("id") ASC);

CREATE INDEX "idx_delivery_queue_pending" ON "delivery_queue_entries" (("queue_name") ASC, ("status") ASC, ("enqueued_at") ASC, ("id") ASC);

CREATE INDEX "idx_delivery_queue_session" ON "delivery_queue_entries" (("queue_name") ASC, ("status") ASC, ("session_key") ASC, ("enqueued_at") ASC, ("id") ASC) WHERE "session_key" IS NOT NULL;

CREATE INDEX "idx_delivery_queue_target" ON "delivery_queue_entries" (("queue_name") ASC, ("status") ASC, ("channel") ASC, ("target") ASC, ("enqueued_at") ASC, ("id") ASC) WHERE "channel" IS NOT NULL AND "target" IS NOT NULL;

CREATE INDEX "idx_device_bootstrap_tokens_ts" ON "device_bootstrap_tokens" (("ts") ASC);

CREATE INDEX "idx_device_pairing_paired_approved" ON "device_pairing_paired" (("approved_at_ms") DESC, ("device_id") ASC);

CREATE INDEX "idx_device_pairing_pending_device" ON "device_pairing_pending" (("device_id") ASC, ("ts") DESC);

CREATE INDEX "idx_diagnostic_events_scope_sequence" ON "diagnostic_events" (("scope") ASC, ("sequence") ASC, ("event_key") ASC);

CREATE INDEX "idx_flow_runs_owner_key" ON "flow_runs" (("owner_key") ASC);

CREATE INDEX "idx_flow_runs_status" ON "flow_runs" (("status") ASC);

CREATE INDEX "idx_flow_runs_updated_at" ON "flow_runs" (("updated_at") ASC);

CREATE INDEX "idx_gateway_boot_lifecycle_started" ON "gateway_boot_lifecycle" (("started_at_ms") ASC);

CREATE INDEX "idx_gateway_restart_handoff_expiry" ON "gateway_restart_handoff" (("expires_at") ASC, ("pid") ASC);

CREATE INDEX "idx_gateway_restart_sentinel_ts" ON "gateway_restart_sentinel" (("ts") DESC, ("sentinel_key") ASC);

CREATE INDEX "idx_macos_port_guardian_records_port" ON "macos_port_guardian_records" (("port") ASC, ("timestamp") DESC);

CREATE INDEX "idx_managed_outgoing_images_agent_message" ON "managed_outgoing_image_records" (("session_key") ASC, ("agent_id") ASC NULLS FIRST, ("message_id") ASC, ("attachment_id") ASC) WHERE "message_id" IS NOT NULL;

CREATE INDEX "idx_managed_outgoing_images_agent_session" ON "managed_outgoing_image_records" (("session_key") ASC, ("agent_id") ASC NULLS FIRST, ("created_at") DESC, ("attachment_id") ASC);

CREATE INDEX "idx_managed_outgoing_images_message" ON "managed_outgoing_image_records" (("session_key") ASC, ("message_id") ASC, ("attachment_id") ASC) WHERE "message_id" IS NOT NULL;

CREATE INDEX "idx_managed_outgoing_images_session" ON "managed_outgoing_image_records" (("session_key") ASC, ("created_at") DESC, ("attachment_id") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_account" ON "meeting_transcript_sessions" (("source_account_id") ASC NULLS FIRST);

CREATE INDEX "idx_meeting_transcript_sessions_agent" ON "meeting_transcript_sessions" (("metadata_agent_id") ASC NULLS FIRST);

CREATE INDEX "idx_meeting_transcript_sessions_chronology" ON "meeting_transcript_sessions" (("started_at_ms") DESC NULLS LAST, ("session_id") ASC, ("started_at") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_export_key" ON "meeting_transcript_sessions" (("export_key") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_id" ON "meeting_transcript_sessions" (("session_id") ASC, ("started_at") DESC);

CREATE INDEX "idx_meeting_transcript_sessions_slug" ON "meeting_transcript_sessions" (("session_slug") ASC, ("started_at") DESC);

CREATE INDEX "idx_meeting_transcript_sessions_source" ON "meeting_transcript_sessions" (("provider_id") ASC, ("source_account_id") ASC NULLS FIRST, ("source_guild_id") ASC NULLS FIRST, ("source_channel_id") ASC NULLS FIRST, ("source_meeting_url") ASC NULLS FIRST, ("source_thread_ts") ASC NULLS FIRST, ("source_file_id") ASC NULLS FIRST, ("stopped_at") DESC NULLS LAST, ("started_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_started" ON "meeting_transcript_sessions" (("started_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_meeting_transcript_utterances_id" ON "meeting_transcript_utterances" (("session_id") ASC, ("session_started_at") ASC, ("utterance_id") ASC) WHERE "utterance_id" IS NOT NULL;

CREATE INDEX "idx_migration_runs_started" ON "migration_runs" (("started_at") DESC, ("id") ASC);

CREATE INDEX "idx_migration_sources_path" ON "migration_sources" (("source_path") ASC, ("migration_kind") ASC, ("target_table") ASC);

CREATE INDEX "idx_migration_sources_run" ON "migration_sources" (("last_run_id") ASC, ("source_path") ASC);

CREATE INDEX "idx_native_hook_relay_bridges_expires" ON "native_hook_relay_bridges" (("expires_at_ms") ASC, ("relay_id") ASC);

CREATE INDEX "idx_official_external_plugin_catalog_snapshots_updated" ON "official_external_plugin_catalog_snapshots" (("updated_at_ms") DESC, ("feed_url") ASC);

CREATE UNIQUE INDEX "idx_operator_approvals_cursor_id" ON "operator_approvals" (("cursor_id") ASC);

CREATE UNIQUE INDEX "idx_operator_approvals_resolution_ref" ON "operator_approvals" (("resolution_ref") ASC);

CREATE INDEX "idx_operator_approvals_resolved" ON "operator_approvals" (("resolved_at_ms") ASC, ("approval_id") ASC) WHERE "resolved_at_ms" IS NOT NULL;

CREATE INDEX "idx_operator_approvals_runtime_pending" ON "operator_approvals" (("runtime_epoch") ASC, ("approval_id") ASC) WHERE ("status" = 'pending');

CREATE INDEX "idx_operator_approvals_source_run_resolved" ON "operator_approvals" (("source_run_id") ASC, ("resolved_at_ms") ASC, ("approval_id") ASC) WHERE "source_run_id" IS NOT NULL AND "resolved_at_ms" IS NOT NULL;

CREATE INDEX "idx_operator_approvals_source_session_created" ON "operator_approvals" (("source_session_key") ASC NULLS FIRST, ("created_at_ms") DESC, ("approval_id") ASC);

CREATE INDEX "idx_operator_approvals_status_expiry" ON "operator_approvals" (("status") ASC, ("expires_at_ms") ASC, ("approval_id") ASC);

CREATE INDEX "idx_plugin_binding_approvals_plugin" ON "plugin_binding_approvals" (("plugin_id") ASC, ("approved_at") DESC);

CREATE INDEX "idx_plugin_blob_expiry" ON "plugin_blob_entries" (("expires_at") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_plugin_blob_listing" ON "plugin_blob_entries" (("plugin_id") ASC, ("namespace") ASC, ("created_at") ASC, ("entry_key") ASC);

CREATE INDEX "idx_plugin_state_expiry" ON "plugin_state_entries" (("expires_at") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_plugin_state_listing" ON "plugin_state_entries" (("plugin_id") ASC, ("namespace") ASC, ("created_at") ASC, ("entry_key") ASC, ("expires_at") ASC NULLS FIRST);

CREATE INDEX "idx_sandbox_registry_last_used" ON "sandbox_registry_entries" (("registry_kind") ASC, ("last_used_at_ms") DESC, ("container_name") ASC) WHERE "last_used_at_ms" IS NOT NULL;

CREATE INDEX "idx_sandbox_registry_session" ON "sandbox_registry_entries" (("registry_kind") ASC, ("session_key") ASC, ("last_used_at_ms") DESC NULLS LAST, ("container_name") ASC) WHERE "session_key" IS NOT NULL;

CREATE INDEX "idx_sandbox_registry_updated" ON "sandbox_registry_entries" (("registry_kind") ASC, ("updated_at") DESC, ("container_name") ASC);

CREATE INDEX "idx_session_state_events_session_sequence" ON "session_state_events" (("session_key") ASC, ("sequence") DESC);

CREATE INDEX "idx_session_state_events_time" ON "session_state_events" (("occurred_at") DESC, ("sequence") DESC);

CREATE INDEX "idx_session_upstream_links_catalog_id" ON "session_upstream_links" (("catalog_id") ASC);

CREATE INDEX "idx_session_watch_cursors_target" ON "session_watch_cursors" (("target_session_key") ASC);

CREATE INDEX "idx_skill_uploads_expiry" ON "skill_uploads" (("expires_at") ASC);

CREATE INDEX "idx_skill_uploads_idempotency" ON "skill_uploads" (("idempotency_key_hash") ASC) WHERE "idempotency_key_hash" IS NOT NULL;

CREATE INDEX "idx_state_leases_expiry" ON "state_leases" (("expires_at") ASC, ("scope") ASC, ("lease_key") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_state_leases_owner" ON "state_leases" (("owner") ASC);

CREATE INDEX "idx_subagent_runs_child_session_key" ON "subagent_runs" (("child_session_key") ASC, ("created_at") DESC, ("run_id") ASC);

CREATE INDEX "idx_subagent_runs_controller_session_key" ON "subagent_runs" (("controller_session_key") ASC NULLS FIRST, ("created_at") DESC, ("run_id") ASC);

CREATE INDEX "idx_subagent_runs_requester_session_key" ON "subagent_runs" (("requester_session_key") ASC, ("created_at") DESC, ("run_id") ASC);

CREATE INDEX "idx_task_runs_cron_runtime_order" ON "task_runs" (("runtime") ASC, ("created_at") ASC, ("task_id") ASC) WHERE ("runtime" = 'cron');

CREATE INDEX "idx_task_runs_cron_source_order" ON "task_runs" (("source_id") ASC NULLS FIRST, ("created_at") ASC, ("task_id") ASC) WHERE ("runtime" = 'cron');

CREATE INDEX "idx_task_runs_runtime_run" ON "task_runs" (("runtime") ASC, ("run_id") ASC NULLS FIRST, ("source_id") ASC NULLS FIRST, ("created_at") ASC, ("task_id") ASC);

CREATE INDEX "idx_web_push_subscriptions_updated" ON "web_push_subscriptions" (("updated_at_ms") DESC, ("subscription_id") ASC);

CREATE UNIQUE INDEX "idx_worker_environments_provider_lease" ON "worker_environments" (("provider_id") ASC, ("lease_id") ASC) WHERE "lease_id" IS NOT NULL;

CREATE INDEX "idx_worker_environments_terminal_changed" ON "worker_environments" (("state_changed_at_ms") ASC, ("environment_id") ASC);

CREATE UNIQUE INDEX "idx_worker_inference_turns_pending_run" ON "worker_inference_turns" (("session_id") ASC, ("run_epoch") ASC, ("run_id") ASC) WHERE ("state" = 'pending');

CREATE INDEX "idx_worker_session_placements_environment" ON "worker_session_placements" (("environment_id") ASC) WHERE "environment_id" IS NOT NULL;

CREATE INDEX "idx_worker_session_placements_reconcile" ON "worker_session_placements" (("updated_at_ms") ASC, ("session_id") ASC);

CREATE INDEX "idx_worker_session_placements_session_key" ON "worker_session_placements" (("agent_id") ASC, ("session_key") ASC);

CREATE INDEX "idx_workspace_path_aliases_workspace" ON "workspace_path_aliases" (("workspace_key") ASC);

CREATE INDEX "idx_workspace_setup_state_path" ON "workspace_setup_state" (("workspace_path") ASC NULLS FIRST);

CREATE INDEX "idx_worktrees_removed_at" ON "worktrees" (("removed_at") ASC NULLS FIRST);

CREATE INDEX "idx_worktrees_repo_fingerprint" ON "worktrees" (("repo_fingerprint") ASC);

ALTER TABLE "acp_replay_events" ADD FOREIGN KEY ("session_id") REFERENCES "acp_replay_sessions" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "capture_events" ADD FOREIGN KEY ("data_blob_id") REFERENCES "capture_blobs" ("blob_id") ON UPDATE NO ACTION ON DELETE SET NULL NOT DEFERRABLE;

ALTER TABLE "capture_events" ADD FOREIGN KEY ("session_id") REFERENCES "capture_sessions" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "meeting_transcript_summaries" ADD FOREIGN KEY ("session_id", "session_started_at") REFERENCES "meeting_transcript_sessions" ("session_id", "started_at") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "meeting_transcript_utterances" ADD FOREIGN KEY ("session_id", "session_started_at") REFERENCES "meeting_transcript_sessions" ("session_id", "started_at") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "migration_sources" ADD FOREIGN KEY ("last_run_id") REFERENCES "migration_runs" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "skill_upload_chunks" ADD FOREIGN KEY ("upload_id") REFERENCES "skill_uploads" ("upload_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "task_delivery_state" ADD FOREIGN KEY ("task_id") REFERENCES "task_runs" ("task_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_environment_credentials" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_inference_turns" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_session_tool_operations" ADD FOREIGN KEY ("source_session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_transcript_commits" ADD FOREIGN KEY ("session_id", "run_epoch") REFERENCES "worker_transcript_commit_heads" ("session_id", "run_epoch") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_turn_tool_authorities" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_workspace_pending_results" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_workspace_reconciliations" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "workspace_generated_bootstrap_hashes" ADD FOREIGN KEY ("workspace_key") REFERENCES "workspace_setup_state" ("workspace_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`;return Object.defineProperty(this,"eagerSql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get operatorRecoveryV25Sql(){let e=`-- Generated v24-to-v25 metadata-only transition; the engine owner publishes openclaw_schema_meta.
-- Subagent operator recovery requires the new reader; catalog and retained rows are unchanged.
UPDATE schema_meta SET schema_version = 25 WHERE meta_key = 'primary' AND schema_version = 24;
UPDATE config_machine_state SET value_json = '25' WHERE state_key = 'state.schema.contentVersion' AND value_json = '24';
`;return Object.defineProperty(this,"operatorRecoveryV25Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get preWriteIndexesV27Sql(){let e={acp_replay_events:`CREATE INDEX "idx_acp_replay_events_session_seq" ON "acp_replay_events" (("session_id") ASC NULLS FIRST, ("seq") ASC NULLS FIRST);`,skill_usage:`CREATE INDEX "idx_skill_usage_key" ON "skill_usage" (("skill_key") ASC NULLS FIRST, ("skill_file") ASC NULLS FIRST);`,state_leases:`CREATE INDEX "idx_state_leases_owner" ON "state_leases" (("owner") ASC NULLS FIRST, ("updated_at") DESC NULLS LAST);`};return Object.defineProperty(this,"preWriteIndexesV27Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get writeIndexesV27Sql(){let e=`
  DROP INDEX IF EXISTS idx_acp_replay_events_session_seq;
  DROP INDEX IF EXISTS idx_skill_usage_key;
  DROP INDEX IF EXISTS idx_state_leases_owner;

CREATE INDEX "idx_state_leases_owner" ON "state_leases" (("owner") ASC NULLS FIRST);`;return Object.defineProperty(this,"writeIndexesV27Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get clientCredentialV29Sql(){let e=`-- Generated v28-to-v29 publication after the local credential owner has verified and retired source rows.
UPDATE schema_meta SET schema_version = 29 WHERE meta_key = 'primary' AND schema_version = 28;
`;return Object.defineProperty(this,"clientCredentialV29Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get workspaceCasV35Sql(){let e=`-- Generated DDL-only v34-to-v35 transition; reconciliation converts retained rows online.
DO $workspace_cas$ BEGIN
IF to_regclass('local_workspace_projections') IS NOT NULL THEN
ALTER TABLE "local_workspace_projections" ADD COLUMN "tree_root_digest" bytea;
ALTER TABLE "local_workspace_projections" ADD COLUMN "source_paths_digest" bytea;
ALTER TABLE "local_workspace_projections" ADD COLUMN "canonical_fingerprints" bytea;
ALTER TABLE "local_workspace_projections" ADD COLUMN "projection_fingerprints" bytea;
CREATE TABLE "local_workspace_source_path_sets" (
  "path_digest" bytea NOT NULL,
  "paths_zstd" bytea NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("path_digest"),
  CHECK ((octet_length("path_digest") = 32))
);
CREATE TABLE "local_workspace_tree_packs" (
  "tree_digest" bytea NOT NULL,
  "records_json" text COLLATE "C" NOT NULL,
  "children_json" text COLLATE "C" NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("tree_digest"),
  CHECK ((octet_length("tree_digest") = 32))
);
END IF; END $workspace_cas$;
`;return Object.defineProperty(this,"workspaceCasV35Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get clientCredentialSource(){let e={sql:`CREATE TABLE "device_auth_tokens" (
  "device_id" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "scopes_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("device_id", "role")
);

CREATE TABLE "device_identities" (
  "identity_key" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "public_key_pem" text COLLATE "C" NOT NULL,
  "private_key_pem" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("identity_key")
);

CREATE TABLE "gateway_origin_device_tokens" (
  "gateway_scope" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "scopes_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("gateway_scope", "device_id", "role")
);

CREATE INDEX "idx_device_auth_tokens_updated" ON "device_auth_tokens" (("updated_at_ms") DESC NULLS LAST, ("device_id") ASC NULLS FIRST, ("role") ASC NULLS FIRST);

CREATE INDEX "idx_device_identities_device" ON "device_identities" (("device_id") ASC NULLS FIRST, ("updated_at_ms") DESC NULLS LAST);`,preData:[0,926],postData:[926,1225],tables:[{name:`device_auth_tokens`,identities:[]},{name:`device_identities`,identities:[]},{name:`gateway_origin_device_tokens`,identities:[]}],expectedCatalog:[{table:`device_auth_tokens`,kind:`table`,value:null},{table:`device_auth_tokens`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_auth_tokens`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_auth_tokens`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_auth_tokens`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_auth_tokens`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`device_auth_tokens`,kind:`primaryKey`,value:[`device_id`,`role`]},{table:`device_auth_tokens`,kind:`indexes`,value:2},{table:`device_auth_tokens`,kind:`checks`,value:0},{table:`device_identities`,kind:`table`,value:null},{table:`device_identities`,kind:`column`,value:{name:`identity_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_identities`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_identities`,kind:`column`,value:{name:`public_key_pem`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_identities`,kind:`column`,value:{name:`private_key_pem`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_identities`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`device_identities`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`device_identities`,kind:`primaryKey`,value:[`identity_key`]},{table:`device_identities`,kind:`indexes`,value:2},{table:`device_identities`,kind:`checks`,value:0},{table:`gateway_origin_device_tokens`,kind:`table`,value:null},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`gateway_scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`gateway_origin_device_tokens`,kind:`primaryKey`,value:[`gateway_scope`,`device_id`,`role`]},{table:`gateway_origin_device_tokens`,kind:`indexes`,value:1},{table:`gateway_origin_device_tokens`,kind:`checks`,value:0}]};return Object.defineProperty(this,"clientCredentialSource",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get fragments(){let e=[{id:`local_workspace_projections`,tables:[`local_workspace_projections`,`local_workspace_manifest_nodes`,`local_workspace_tree_packs`,`local_workspace_source_path_sets`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "local_workspace_manifest_nodes" (
  "worktree_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "node_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("worktree_id", "path")
);

CREATE TABLE "local_workspace_projections" (
  "worktree_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "lifecycle_revision" text COLLATE "C",
  "projection_path" text COLLATE "C" NOT NULL,
  "base_commit" text COLLATE "C" NOT NULL,
  "source_paths_json" text COLLATE "C" NOT NULL,
  "baseline_json" text COLLATE "C",
  "baseline_ref" text COLLATE "C",
  "pending_ref" text COLLATE "C",
  "pending_target" text COLLATE "C",
  "paused_runtimes_json" text COLLATE "C",
  "journal_json" text COLLATE "C",
  "journal_pack" bytea,
  "revision" bigint NOT NULL DEFAULT 0,
  "created_at_ms" bigint NOT NULL,
  "checkpoint_json" text COLLATE "C",
  "tree_root_digest" bytea,
  "source_paths_digest" bytea,
  "canonical_fingerprints" bytea,
  "projection_fingerprints" bytea,
  PRIMARY KEY ("worktree_id"),
  CHECK (("pending_target" IN ('canonical', 'projection'))),
  CHECK ("journal_pack" IS NULL OR (octet_length("journal_pack") <= 268435456)),
  CHECK (("revision" >= 0)),
  CHECK ("baseline_json" IS NULL OR "baseline_ref" IS NOT NULL),
  CHECK ((("journal_json" IS NULL) = ("journal_pack" IS NULL))),
  UNIQUE ("projection_path")
);

CREATE TABLE "local_workspace_source_path_sets" (
  "path_digest" bytea NOT NULL,
  "paths_zstd" bytea NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("path_digest"),
  CHECK ((octet_length("path_digest") = 32))
);

CREATE TABLE "local_workspace_tree_packs" (
  "tree_digest" bytea NOT NULL,
  "records_json" text COLLATE "C" NOT NULL,
  "children_json" text COLLATE "C" NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("tree_digest"),
  CHECK ((octet_length("tree_digest") = 32))
);

ALTER TABLE "local_workspace_manifest_nodes" ADD FOREIGN KEY ("worktree_id") REFERENCES "local_workspace_projections" ("worktree_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`user_profiles`,tables:[`user_profiles`,`user_profile_emails`,`user_profile_identities`],indexes:[`idx_user_profile_emails_profile_id`,`idx_user_profile_identities_profile_id`,`idx_user_profile_identities_authorization`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "user_profile_emails" (
  "email" text COLLATE "C" NOT NULL,
  "profile_id" text COLLATE "C" NOT NULL,
  "binding_id" text COLLATE "C",
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("email")
);

CREATE TABLE "user_profile_identities" (
  "provider" text COLLATE "C" NOT NULL,
  "subject" text COLLATE "C" NOT NULL,
  "profile_id" text COLLATE "C" NOT NULL,
  "canonical_login" text COLLATE "C",
  "verified_email_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "authorization_id" text COLLATE "C",
  "authorization_basis_json" text COLLATE "C",
  PRIMARY KEY ("provider", "subject")
);

CREATE TABLE "user_profiles" (
  "id" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C",
  "primary_github_account_id" bigint,
  "avatar" bytea,
  "avatar_mime" text COLLATE "C",
  "avatar_sha256" text COLLATE "C",
  "merged_into" text COLLATE "C",
  "role" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("id")
);

CREATE INDEX "idx_user_profile_emails_profile_id" ON "user_profile_emails" (("profile_id") ASC);

CREATE UNIQUE INDEX "idx_user_profile_identities_authorization" ON "user_profile_identities" (("authorization_id") ASC NULLS FIRST);

CREATE INDEX "idx_user_profile_identities_profile_id" ON "user_profile_identities" (("profile_id") ASC);
`},{id:`skill_library_entries`,tables:[`skill_library_entries`,`skill_library_revisions`,`skill_library_events`,`skill_library_uploads`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "skill_library_entries" (
  "skill_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C",
  "author_profile_id" text COLLATE "C" NOT NULL,
  "slug" text COLLATE "C" NOT NULL,
  "current_revision" text COLLATE "C" NOT NULL,
  "shared" bigint NOT NULL,
  "enabled" bigint NOT NULL,
  "removed" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("skill_id")
);

CREATE TABLE "skill_library_events" (
  "event_id" text COLLATE "C" NOT NULL,
  "skill_id" text COLLATE "C" NOT NULL,
  "revision" text COLLATE "C" NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "actor_profile_id" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("event_id")
);

CREATE TABLE "skill_library_revisions" (
  "skill_id" text COLLATE "C" NOT NULL,
  "revision" text COLLATE "C" NOT NULL,
  "description" text COLLATE "C" NOT NULL,
  "files_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("skill_id", "revision")
);

CREATE TABLE "skill_library_uploads" (
  "upload_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C" NOT NULL,
  "slug" text COLLATE "C" NOT NULL,
  "size_bytes" bigint NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  "archive_blob" bytea NOT NULL,
  "expires_at" bigint NOT NULL,
  "published_skill_id" text COLLATE "C",
  PRIMARY KEY ("upload_id")
);
`},{id:`operator_approval_standing_grants`,tables:[`operator_approval_standing_grants`,`operator_approval_standing_grant_generations`],indexes:[`idx_operator_approval_standing_grants_binding`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "operator_approval_standing_grant_generations" (
  "grant_id" text COLLATE "C" NOT NULL,
  "job_definition_generation" bigint NOT NULL,
  PRIMARY KEY ("grant_id"),
  CHECK (("job_definition_generation" >= 1))
);

CREATE TABLE "operator_approval_standing_grants" (
  "grant_id" text COLLATE "C" NOT NULL,
  "minted_by_approval_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "cron_job_id" text COLLATE "C" NOT NULL,
  "job_config_revision" text COLLATE "C" NOT NULL,
  "operation_binding" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "expires_at_ms" bigint,
  "revoked_at_ms" bigint,
  "revoked_by" text COLLATE "C",
  "last_used_at_ms" bigint,
  "use_count" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("grant_id"),
  CHECK ((char_length("grant_id") > 0)),
  CHECK ((char_length("agent_id") > 0)),
  CHECK ((char_length("cron_job_id") > 0)),
  CHECK ((char_length("job_config_revision") > 0)),
  CHECK ((char_length("operation_binding") > 0)),
  CHECK ("expires_at_ms" IS NULL OR ("expires_at_ms" >= "created_at_ms"))
);

CREATE INDEX "idx_operator_approval_standing_grants_binding" ON "operator_approval_standing_grants" (("agent_id") ASC, ("cron_job_id") ASC, ("operation_binding") ASC, ("created_at_ms") DESC);

ALTER TABLE "operator_approval_standing_grant_generations" ADD FOREIGN KEY ("grant_id") REFERENCES "operator_approval_standing_grants" ("grant_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "operator_approval_standing_grants" ADD FOREIGN KEY ("minted_by_approval_id") REFERENCES "operator_approvals" ("approval_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`worker_environment_session_attachments`,tables:[`worker_environment_session_attachments`],indexes:[`worker_environment_session_attachments_session_key`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worker_environment_session_attachments" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_lifecycle_revision" text COLLATE "C",
  "environment_id" text COLLATE "C" NOT NULL,
  "generation" bigint NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "last_used_at_ms" bigint NOT NULL,
  "closed_at_ms" bigint,
  PRIMARY KEY ("session_id"),
  CHECK (("generation" >= 1)),
  UNIQUE ("environment_id")
);

CREATE INDEX "worker_environment_session_attachments_session_key" ON "worker_environment_session_attachments" (("agent_id") ASC, ("session_key") ASC);

ALTER TABLE "worker_environment_session_attachments" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`durable_background_processes`,tables:[`durable_background_processes`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "durable_background_processes" (
  "id" text COLLATE "C" NOT NULL,
  "record_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("id")
);
`},{id:`sandbox_persistent_execs`,tables:[`sandbox_persistent_execs`],indexes:[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "sandbox_persistent_execs" (
  "owner_key" text COLLATE "C" NOT NULL,
  "source_identity" text COLLATE "C" NOT NULL,
  "attempt_id" text COLLATE "C" NOT NULL,
  "owner_json" text COLLATE "C" NOT NULL,
  "backend_id" text COLLATE "C" NOT NULL,
  "backend_target_json" text COLLATE "C" NOT NULL,
  "workspace_binding_json" text COLLATE "C" NOT NULL,
  "container_id" text COLLATE "C" NOT NULL,
  "container_name" text COLLATE "C" NOT NULL,
  "container_started_at" text COLLATE "C" NOT NULL,
  "revision" bigint NOT NULL,
  "phase" text COLLATE "C" NOT NULL,
  "receipt_json" text COLLATE "C",
  "error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("owner_key"),
  CHECK (("backend_id" = 'docker')),
  CHECK (("revision" > 0)),
  CHECK (("phase" IN ('reserved', 'prepared', 'running', 'stopping', 'uncertain', 'stopped'))),
  CHECK (("phase" NOT IN ('prepared', 'running')) OR "receipt_json" IS NOT NULL),
  UNIQUE ("attempt_id")
);

CREATE INDEX "idx_sandbox_persistent_execs_container" ON "sandbox_persistent_execs" (("container_id") ASC, ("owner_key") ASC);

CREATE INDEX "idx_sandbox_persistent_execs_container_name" ON "sandbox_persistent_execs" (("container_name") ASC, ("owner_key") ASC);

CREATE INDEX "idx_sandbox_persistent_execs_source" ON "sandbox_persistent_execs" (("source_identity") ASC, ("owner_key") ASC);
`},{id:`user_background_images`,tables:[`user_background_images`],indexes:[],dependencies:[`user_profiles`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "user_background_images" (
  "profile_id" text COLLATE "C" NOT NULL,
  "asset_id" text COLLATE "C" NOT NULL,
  "image" bytea NOT NULL,
  "width" bigint NOT NULL,
  "height" bigint NOT NULL,
  PRIMARY KEY ("profile_id"),
  CHECK ((octet_length("image") BETWEEN 1 AND 2097152)),
  CHECK (("width" BETWEEN 1 AND 2560)),
  CHECK (("height" BETWEEN 1 AND 2560)),
  UNIQUE ("asset_id")
);

ALTER TABLE "user_background_images" ADD FOREIGN KEY ("profile_id") REFERENCES "user_profiles" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`update_runs`,tables:[`update_runs`],indexes:[`idx_update_runs_created`,`idx_update_runs_active`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "update_runs" (
  "run_id" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "trigger" text COLLATE "C" NOT NULL,
  "phase" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "reason" text COLLATE "C",
  "origin_json" text COLLATE "C" NOT NULL,
  "target_json" text COLLATE "C" NOT NULL,
  "before_json" text COLLATE "C" NOT NULL,
  "after_json" text COLLATE "C" NOT NULL,
  "steps_json" text COLLATE "C" NOT NULL,
  "verification_json" text COLLATE "C" NOT NULL,
  "repair_json" text COLLATE "C" NOT NULL,
  "confirmed_at_ms" bigint,
  "finished_at_ms" bigint,
  "downtime_ms" bigint,
  PRIMARY KEY ("run_id"),
  CHECK (("trigger" IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api'))),
  CHECK (("phase" IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished'))),
  CHECK (("status" IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped'))),
  CHECK ((octet_length(convert_to("origin_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("target_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("before_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("after_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("steps_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("verification_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("repair_json", 'UTF8')) <= 16384)),
  CHECK ((("status" = 'running') AND ("phase" != 'finished') AND "finished_at_ms" IS NULL) OR (("status" != 'running') AND ("phase" = 'finished') AND "finished_at_ms" IS NOT NULL))
);

CREATE INDEX "idx_update_runs_active" ON "update_runs" (("status") ASC, ("created_at_ms") DESC, ("run_id") ASC);

CREATE INDEX "idx_update_runs_created" ON "update_runs" (("created_at_ms") DESC, ("run_id") ASC);
`},{id:`session_repository_workspaces`,tables:[`session_repository_workspaces`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "session_repository_workspaces" (
  "workspace_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "url" text COLLATE "C" NOT NULL,
  "requested_ref" text COLLATE "C",
  "run_setup_script" bigint NOT NULL DEFAULT 0,
  "base_commit" text COLLATE "C",
  "base_manifest_hash" text COLLATE "C",
  "branch" text COLLATE "C" NOT NULL,
  "checkpoint_ref" text COLLATE "C",
  "manifest_hash" text COLLATE "C",
  "revision" bigint NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "disk_authority_json" text COLLATE "C",
  PRIMARY KEY ("workspace_id"),
  CHECK ((char_length("workspace_id") = 36)),
  CHECK ((char_length("agent_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("session_key") BETWEEN 1 AND 1024)),
  CHECK ((char_length("url") BETWEEN 1 AND 4096)),
  CHECK ("requested_ref" IS NULL OR (char_length("requested_ref") BETWEEN 1 AND 1024)),
  CHECK (("run_setup_script" IN (0, 1))),
  CHECK ("base_commit" IS NULL OR (char_length("base_commit") IN (40, 64))),
  CHECK ((char_length("branch") BETWEEN 1 AND 256)),
  CHECK (("revision" >= 0)),
  CHECK ("base_manifest_hash" IS NULL OR "base_commit" IS NOT NULL),
  CHECK (("checkpoint_ref" IS NULL AND "manifest_hash" IS NULL) OR ("checkpoint_ref" IS NOT NULL AND "manifest_hash" IS NOT NULL AND "base_manifest_hash" IS NOT NULL)),
  UNIQUE ("agent_id", "session_key")
);
`},{id:`github_repository_publication_requests`,tables:[`github_repository_publication_requests`],indexes:[`idx_github_repository_publication_shared_request`,`idx_github_repository_publication_personal_request`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_repository_publication_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C",
  "connection_generation" text COLLATE "C",
  "idempotency_key" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_lifecycle_revision" text COLLATE "C",
  "requester_authority_json" text COLLATE "C",
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "workspace_id" text COLLATE "C" NOT NULL,
  "checkpoint_ref" text COLLATE "C",
  "checkpoint_digest" text COLLATE "C",
  "claim_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "environment_id" text COLLATE "C",
  "owner_epoch" bigint,
  "placement_generation" bigint,
  "identity_source" text COLLATE "C" NOT NULL,
  "identity_profile_id" text COLLATE "C",
  "identity_account_id" bigint NOT NULL,
  "identity_login" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "body" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C",
  "execution_id" text COLLATE "C",
  "last_effect" text COLLATE "C",
  "effect_state" text COLLATE "C",
  "push_repository" text COLLATE "C",
  "repository" text COLLATE "C",
  "branch" text COLLATE "C" NOT NULL,
  "base_branch" text COLLATE "C",
  "source_head_commit" text COLLATE "C",
  "source_index_tree" text COLLATE "C",
  "workspace_tree" text COLLATE "C",
  "previous_head_commit" text COLLATE "C",
  "pushed_head_commit" text COLLATE "C",
  "head_commit" text COLLATE "C",
  "pull_request_url" text COLLATE "C",
  "error_code" text COLLATE "C",
  "next_action" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "reported_at_ms" bigint,
  "draft" bigint,
  PRIMARY KEY ("request_id"),
  CHECK (("identity_source" IN ('system-detected', 'system-configured', 'agent-override', 'personal'))),
  CHECK (("status" IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed'))),
  CHECK (("last_effect" IN ('push', 'pull_request'))),
  CHECK (("effect_state" IN ('dispatched', 'observed'))),
  CHECK ((("identity_source" = 'personal') AND "owner_profile_id" IS NOT NULL AND "connection_generation" IS NOT NULL) OR (("identity_source" <> 'personal') AND "owner_profile_id" IS NULL AND "connection_generation" IS NULL)),
  CHECK (("checkpoint_ref" IS NULL AND "checkpoint_digest" IS NULL) OR ("checkpoint_ref" IS NOT NULL AND "checkpoint_digest" IS NOT NULL)),
  CHECK (("last_effect" IS NULL AND "effect_state" IS NULL) OR ("last_effect" IS NOT NULL AND "effect_state" IS NOT NULL))
);

CREATE UNIQUE INDEX "idx_github_repository_publication_personal_request" ON "github_repository_publication_requests" (("owner_profile_id") ASC, ("session_id") ASC, ("idempotency_key") ASC) WHERE "owner_profile_id" IS NOT NULL;

CREATE UNIQUE INDEX "idx_github_repository_publication_shared_request" ON "github_repository_publication_requests" (("session_id") ASC, ("idempotency_key") ASC) WHERE "owner_profile_id" IS NULL;
`},{id:`github_publication_session_lifecycles`,tables:[`github_publication_session_lifecycles`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_publication_session_lifecycles" (
  "publication_kind" text COLLATE "C" NOT NULL,
  "request_id" text COLLATE "C" NOT NULL,
  "lifecycle_revision" text COLLATE "C",
  "requester_authority_json" text COLLATE "C",
  PRIMARY KEY ("publication_kind", "request_id"),
  CHECK (("publication_kind" IN ('shared', 'personal')))
);
`},{id:`github_personal_publication_requests`,tables:[`github_personal_publication_requests`],indexes:[`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_personal_publication_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C" NOT NULL,
  "connection_generation" text COLLATE "C" NOT NULL,
  "idempotency_key" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "worktree_id" text COLLATE "C" NOT NULL,
  "repository_fingerprint" text COLLATE "C" NOT NULL,
  "identity_source" text COLLATE "C" NOT NULL,
  "identity_profile_id" text COLLATE "C" NOT NULL,
  "identity_account_id" bigint NOT NULL,
  "identity_login" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "body" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C",
  "execution_id" text COLLATE "C",
  "last_effect" text COLLATE "C",
  "effect_state" text COLLATE "C",
  "push_repository" text COLLATE "C" NOT NULL,
  "repository" text COLLATE "C" NOT NULL,
  "branch" text COLLATE "C" NOT NULL,
  "base_branch" text COLLATE "C" NOT NULL,
  "source_head_commit" text COLLATE "C" NOT NULL,
  "source_index_tree" text COLLATE "C" NOT NULL,
  "workspace_tree" text COLLATE "C" NOT NULL,
  "head_commit" text COLLATE "C",
  "pull_request_url" text COLLATE "C",
  "error_code" text COLLATE "C",
  "next_action" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "reported_at_ms" bigint,
  "draft" bigint,
  PRIMARY KEY ("request_id"),
  CHECK ((char_length("request_id") = 36)),
  CHECK ((char_length("owner_profile_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("connection_generation") = 36)),
  CHECK ((char_length("idempotency_key") BETWEEN 1 AND 128)),
  CHECK ((char_length("request_digest") = 64)),
  CHECK ((char_length("session_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("session_key") BETWEEN 1 AND 1024)),
  CHECK ((char_length("agent_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("worktree_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("repository_fingerprint") BETWEEN 1 AND 256)),
  CHECK (("identity_source" = 'personal')),
  CHECK ((char_length("identity_profile_id") = 36)),
  CHECK (("identity_account_id" >= 1)),
  CHECK ((char_length("identity_login") BETWEEN 1 AND 39)),
  CHECK ("title" IS NULL OR (char_length("title") BETWEEN 1 AND 256)),
  CHECK ("body" IS NULL OR (char_length("body") BETWEEN 1 AND 8192)),
  CHECK (("status" IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed'))),
  CHECK ("gateway_instance_id" IS NULL OR (char_length("gateway_instance_id") BETWEEN 1 AND 128)),
  CHECK ("execution_id" IS NULL OR (char_length("execution_id") = 36)),
  CHECK ("last_effect" IS NULL OR ("last_effect" IN ('push', 'pull_request'))),
  CHECK ("effect_state" IS NULL OR ("effect_state" IN ('dispatched', 'observed'))),
  CHECK ((char_length("push_repository") BETWEEN 3 AND 256)),
  CHECK ((char_length("repository") BETWEEN 3 AND 256)),
  CHECK ((char_length("branch") BETWEEN 1 AND 256)),
  CHECK ((char_length("base_branch") BETWEEN 1 AND 256)),
  CHECK ((char_length("source_head_commit") IN (40, 64))),
  CHECK ((char_length("source_index_tree") IN (40, 64))),
  CHECK ((char_length("workspace_tree") IN (40, 64))),
  CHECK ("head_commit" IS NULL OR (char_length("head_commit") IN (40, 64))),
  CHECK ("pull_request_url" IS NULL OR (char_length("pull_request_url") BETWEEN 1 AND 2048)),
  CHECK ("error_code" IS NULL OR (char_length("error_code") BETWEEN 1 AND 64)),
  CHECK ("next_action" IS NULL OR (char_length("next_action") BETWEEN 1 AND 1024)),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= "created_at_ms")),
  CHECK ((("status" = 'publishing') AND "gateway_instance_id" IS NOT NULL AND "execution_id" IS NOT NULL) OR ("status" <> 'publishing')),
  CHECK (("last_effect" IS NULL AND "effect_state" IS NULL) OR ("last_effect" IS NOT NULL AND "effect_state" IS NOT NULL)),
  CHECK ((("status" = 'published') AND "pull_request_url" IS NOT NULL AND "head_commit" IS NOT NULL AND "error_code" IS NULL AND "next_action" IS NULL) OR (("status" = 'failed') AND "error_code" IS NOT NULL AND "next_action" IS NOT NULL) OR (("status" IN ('requested', 'publishing', 'needs_confirmation')) AND "error_code" IS NULL AND "next_action" IS NULL)),
  UNIQUE ("owner_profile_id", "session_id", "idempotency_key")
);

CREATE INDEX "idx_github_personal_publication_owner_session" ON "github_personal_publication_requests" (("owner_profile_id") ASC, ("session_id") ASC, ("created_at_ms") ASC);

CREATE INDEX "idx_github_personal_publication_pending" ON "github_personal_publication_requests" (("status") ASC, ("updated_at_ms") ASC, ("request_id") ASC);
`},{id:`cron_job_runtime_authorities`,tables:[`cron_job_runtime_authorities`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "cron_job_runtime_authorities" (
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "authority_json" text COLLATE "C",
  "authority_input_fingerprint" text COLLATE "C",
  "recovery_required" bigint NOT NULL,
  PRIMARY KEY ("store_key", "job_id"),
  CHECK (("recovery_required" IN (0, 1))),
  CHECK ((("recovery_required" = 0) AND "authority_json" IS NOT NULL AND "authority_input_fingerprint" IS NOT NULL) OR (("recovery_required" = 1) AND "authority_json" IS NULL AND "authority_input_fingerprint" IS NULL))
);

ALTER TABLE "cron_job_runtime_authorities" ADD FOREIGN KEY ("store_key", "job_id") REFERENCES "cron_jobs" ("store_key", "job_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`cron_run_trigger_state_retirements`,tables:[`cron_run_trigger_state_retirements`],indexes:[],dependencies:[`cron_run_receipts`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "cron_run_trigger_state_retirements" (
  "receipt_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("receipt_id")
);

ALTER TABLE "cron_run_trigger_state_retirements" ADD FOREIGN KEY ("receipt_id") REFERENCES "cron_run_receipts" ("receipt_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`execution_identity_contexts`,tables:[`execution_identity_contexts`],indexes:[`execution_identity_contexts_run_created_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "execution_identity_contexts" (
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "coverage_state" text COLLATE "C" NOT NULL,
  "context_bytes" bigint NOT NULL,
  "context_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("context_id"),
  CHECK ((char_length("context_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("execution_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256)),
  CHECK (("created_at" >= 0)),
  CHECK (("coverage_state" IN ('attribution-only', 'unattributed', 'unknown', 'unsupported'))),
  CHECK (("context_bytes" BETWEEN 1 AND 16384)),
  CHECK ((char_length("context_json") > 0)),
  UNIQUE ("execution_id"),
  UNIQUE ("created_at", "context_id")
);

CREATE INDEX "execution_identity_contexts_run_created_idx" ON "execution_identity_contexts" (("run_id") ASC, ("created_at") ASC, ("execution_id") ASC);
`},{id:`mcp_oauth_pending_authorizations`,tables:[`mcp_oauth_pending_authorizations`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "mcp_oauth_pending_authorizations" (
  "state" text COLLATE "C" NOT NULL,
  "store_key" text COLLATE "C" NOT NULL,
  "create_time" bigint NOT NULL,
  PRIMARY KEY ("state")
);
`},{id:`node_worker_launch_containers`,tables:[`node_worker_launch_containers`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_containers" (
  "launch_id" text COLLATE "C" NOT NULL,
  "container_json" text COLLATE "C",
  PRIMARY KEY ("launch_id")
);
`},{id:`node_worker_launch_boots`,tables:[`node_worker_launch_boots`],indexes:[],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_boots" (
  "launch_id" text COLLATE "C" NOT NULL,
  "boot_id" text COLLATE "C",
  PRIMARY KEY ("launch_id"),
  CHECK ("boot_id" IS NULL OR (char_length("boot_id") BETWEEN 1 AND 128))
);

ALTER TABLE "node_worker_launch_boots" ADD FOREIGN KEY ("launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`node_worker_launch_cleanup`,tables:[`node_worker_launch_cleanup`],indexes:[],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_cleanup" (
  "launch_id" text COLLATE "C" NOT NULL,
  "cleanup_mode" text COLLATE "C" NOT NULL,
  "lineage_settled" bigint,
  PRIMARY KEY ("launch_id"),
  CHECK (("cleanup_mode" IN ('process-group', 'owned-anchor'))),
  CHECK ("lineage_settled" IS NULL OR ("lineage_settled" = 1))
);

ALTER TABLE "node_worker_launch_cleanup" ADD FOREIGN KEY ("launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`node_worker_launch_process_scopes`,tables:[`node_worker_launch_process_scopes`],indexes:[],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_process_scopes" (
  "launch_id" text COLLATE "C" NOT NULL,
  "scope_kind" text COLLATE "C" NOT NULL,
  "descendants_reaped" bigint,
  PRIMARY KEY ("launch_id"),
  CHECK (("scope_kind" = 'linux-subreaper')),
  CHECK ("descendants_reaped" IS NULL OR ("descendants_reaped" = 1))
);

ALTER TABLE "node_worker_launch_process_scopes" ADD FOREIGN KEY ("launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`node_worker_launches`,tables:[`node_worker_launches`],indexes:[`idx_node_worker_launches_terminal_completed`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launches" (
  "launch_id" text COLLATE "C" NOT NULL,
  "plan_hash" text COLLATE "C" NOT NULL,
  "gateway_namespace" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "supervisor_pid" bigint NOT NULL,
  "supervisor_start_time" bigint NOT NULL,
  "worker_pid" bigint,
  "worker_start_time" bigint,
  "result_json" text COLLATE "C",
  "error_text" text COLLATE "C",
  "completed_at_ms" bigint,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("launch_id"),
  CHECK ((char_length("launch_id") BETWEEN 1 AND 256) AND ("launch_id" IS NOT NULL OR NULL)),
  CHECK ((char_length("plan_hash") = 64) AND ("plan_hash" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("gateway_namespace") BETWEEN 1 AND 128) AND ("gateway_namespace" COLLATE "C" !~ '\\A.*[^A-Za-z0-9._-].*\\Z') AND ("gateway_namespace" COLLATE "C" ~ '\\A[A-Za-z0-9].*\\Z')),
  CHECK ((char_length("environment_id") BETWEEN 1 AND 256) AND ("environment_id" IS NOT NULL OR NULL)),
  CHECK ((char_length("session_id") BETWEEN 1 AND 256) AND ("session_id" IS NOT NULL OR NULL)),
  CHECK (("owner_epoch" BETWEEN 1 AND 9007199254740991)),
  CHECK (("placement_generation" BETWEEN 0 AND 9007199254740991)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256) AND ("run_id" IS NOT NULL OR NULL)),
  CHECK (("state" IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled'))),
  CHECK (("supervisor_pid" BETWEEN 1 AND 2147483647)),
  CHECK (("supervisor_start_time" BETWEEN 0 AND 9007199254740991)),
  CHECK ("worker_pid" IS NULL OR ("worker_pid" BETWEEN 1 AND 2147483647)),
  CHECK ("worker_start_time" IS NULL OR ("worker_start_time" BETWEEN 0 AND 9007199254740991)),
  CHECK ("result_json" IS NULL OR ((octet_length(convert_to("result_json", 'UTF8')) BETWEEN 1 AND 65536) AND ("result_json" IS NOT NULL OR NULL) AND ("result_json" IS JSON))),
  CHECK ("error_text" IS NULL OR ((octet_length(convert_to("error_text", 'UTF8')) BETWEEN 1 AND 4096) AND ("error_text" IS NOT NULL OR NULL) AND (strpos("error_text", '
') = 0) AND (strpos("error_text", '\r') = 0))),
  CHECK ("completed_at_ms" IS NULL OR ("completed_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("created_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("updated_at_ms" BETWEEN "created_at_ms" AND 9007199254740991)),
  CHECK ((("worker_pid" IS NULL) = ("worker_start_time" IS NULL))),
  CHECK ((("state" = 'pending') AND "worker_pid" IS NULL AND "result_json" IS NULL AND "error_text" IS NULL AND "completed_at_ms" IS NULL) OR (("state" = 'running') AND "worker_pid" IS NOT NULL AND "result_json" IS NULL AND "error_text" IS NULL AND "completed_at_ms" IS NULL) OR (("state" = 'completed') AND "result_json" IS NOT NULL AND "error_text" IS NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")) OR (("state" IN ('failed', 'interrupted', 'cancelled')) AND "result_json" IS NULL AND "error_text" IS NOT NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")))
);

CREATE INDEX "idx_node_worker_launches_terminal_completed" ON "node_worker_launches" (("completed_at_ms") ASC, ("launch_id") ASC) WHERE "completed_at_ms" IS NOT NULL;
`},{id:`node_worker_prepared_workspaces`,tables:[`node_worker_prepared_workspaces`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_prepared_workspaces" (
  "preparation_key" text COLLATE "C" NOT NULL,
  "cache_key" text COLLATE "C" NOT NULL,
  "gateway_namespace" text COLLATE "C" NOT NULL,
  "workspace_dir" text COLLATE "C" NOT NULL,
  "home_dir" text COLLATE "C" NOT NULL,
  "source_manifest_ref" text COLLATE "C" NOT NULL,
  "prepared_manifest_ref" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "session_key" text COLLATE "C",
  "owner_epoch" bigint,
  "created_at_ms" bigint NOT NULL,
  "bound_at_ms" bigint,
  "retired_at_ms" bigint,
  PRIMARY KEY ("preparation_key"),
  CHECK ((char_length("preparation_key") = 64) AND ("preparation_key" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("cache_key") = 64) AND ("cache_key" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("gateway_namespace") > 0)),
  CHECK ((char_length("workspace_dir") > 0)),
  CHECK ((char_length("home_dir") > 0)),
  CHECK ((char_length("source_manifest_ref") = 71) AND (substr("source_manifest_ref", 1, 7) = 'sha256:') AND (substr("source_manifest_ref", 8) COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("prepared_manifest_ref") = 71) AND (substr("prepared_manifest_ref", 1, 7) = 'sha256:') AND (substr("prepared_manifest_ref", 8) COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK (("state" IN ('available', 'bound', 'retiring', 'retired'))),
  CHECK ((char_length("environment_id") > 0)),
  CHECK (("owner_epoch" BETWEEN 1 AND 9007199254740991)),
  CHECK (("created_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("bound_at_ms" BETWEEN "created_at_ms" AND 9007199254740991)),
  CHECK (("retired_at_ms" BETWEEN coalesce("bound_at_ms", "created_at_ms") AND 9007199254740991)),
  CHECK (("session_id" IS NULL AND "session_key" IS NULL AND "owner_epoch" IS NULL AND "bound_at_ms" IS NULL) OR ("session_id" IS NOT NULL AND (char_length("session_id") > 0) AND "session_key" IS NOT NULL AND (char_length("session_key") > 0) AND "owner_epoch" IS NOT NULL AND "bound_at_ms" IS NOT NULL)),
  CHECK ((("state" = 'available') AND "bound_at_ms" IS NULL AND "retired_at_ms" IS NULL) OR (("state" = 'bound') AND "bound_at_ms" IS NOT NULL AND "retired_at_ms" IS NULL) OR (("state" = 'retiring') AND "retired_at_ms" IS NULL) OR (("state" = 'retired') AND "retired_at_ms" IS NOT NULL)),
  UNIQUE ("workspace_dir")
);
`},{id:`node_worker_turns`,tables:[`node_worker_turns`],indexes:[`idx_node_worker_turns_terminal_completed`,`idx_node_worker_turns_active_owner`],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_turns" (
  "turn_id" text COLLATE "C" NOT NULL,
  "owner_launch_id" text COLLATE "C" NOT NULL,
  "plan_hash" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "result_json" text COLLATE "C",
  "error_text" text COLLATE "C",
  "completed_at_ms" bigint,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("turn_id"),
  CHECK ((char_length("turn_id") BETWEEN 1 AND 256) AND ("turn_id" IS NOT NULL OR NULL)),
  CHECK ((char_length("plan_hash") = 64) AND ("plan_hash" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256) AND ("run_id" IS NOT NULL OR NULL)),
  CHECK (("state" IN ('running', 'completed', 'failed', 'interrupted', 'cancelled'))),
  CHECK ("result_json" IS NULL OR ((octet_length(convert_to("result_json", 'UTF8')) BETWEEN 1 AND 65536) AND ("result_json" IS NOT NULL OR NULL) AND ("result_json" IS JSON))),
  CHECK ("error_text" IS NULL OR ((octet_length(convert_to("error_text", 'UTF8')) BETWEEN 1 AND 4096) AND ("error_text" IS NOT NULL OR NULL) AND (strpos("error_text", '
') = 0) AND (strpos("error_text", '\r') = 0))),
  CHECK ("completed_at_ms" IS NULL OR ("completed_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("created_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("updated_at_ms" BETWEEN "created_at_ms" AND 9007199254740991)),
  CHECK ((("state" = 'running') AND "result_json" IS NULL AND "error_text" IS NULL AND "completed_at_ms" IS NULL) OR (("state" = 'completed') AND "result_json" IS NOT NULL AND "error_text" IS NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")) OR (("state" IN ('failed', 'interrupted', 'cancelled')) AND "result_json" IS NULL AND "error_text" IS NOT NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")))
);

CREATE UNIQUE INDEX "idx_node_worker_turns_active_owner" ON "node_worker_turns" (("owner_launch_id") ASC) WHERE ("state" = 'running');

CREATE INDEX "idx_node_worker_turns_terminal_completed" ON "node_worker_turns" (("completed_at_ms") ASC, ("turn_id") ASC) WHERE "completed_at_ms" IS NOT NULL;

ALTER TABLE "node_worker_turns" ADD FOREIGN KEY ("owner_launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`operator_approval_execution_identities`,tables:[`operator_approval_execution_identities`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "operator_approval_execution_identities" (
  "approval_id" text COLLATE "C" NOT NULL,
  "source_context_id" text COLLATE "C" NOT NULL,
  "source_execution_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("approval_id"),
  CHECK ((char_length("source_context_id") BETWEEN 1 AND 256) AND ("source_context_id" = btrim("source_context_id"))),
  CHECK ((char_length("source_execution_id") BETWEEN 1 AND 256) AND ("source_execution_id" = btrim("source_execution_id")))
);

ALTER TABLE "operator_approval_execution_identities" ADD FOREIGN KEY ("approval_id") REFERENCES "operator_approvals" ("approval_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`web_push_approval_deliveries`,tables:[`web_push_approval_deliveries`],indexes:[`idx_web_push_approval_deliveries_subscription`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "web_push_approval_deliveries" (
  "approval_id" text COLLATE "C" NOT NULL,
  "subscription_id" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "user_profile_id" text COLLATE "C",
  "prepared_at_ms" bigint NOT NULL,
  PRIMARY KEY ("approval_id", "subscription_id")
);

CREATE INDEX "idx_web_push_approval_deliveries_subscription" ON "web_push_approval_deliveries" (("subscription_id") ASC, ("approval_id") ASC);

ALTER TABLE "web_push_approval_deliveries" ADD FOREIGN KEY ("subscription_id") REFERENCES "web_push_subscriptions" ("subscription_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "web_push_approval_deliveries" ADD FOREIGN KEY ("approval_id") REFERENCES "operator_approvals" ("approval_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`execution_decision_facts`,tables:[`execution_decision_facts`],indexes:[`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_run_occurred_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "execution_decision_facts" (
  "cursor_id" bigint NOT NULL,
  "receipt_id" text COLLATE "C" NOT NULL,
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "action_id" text COLLATE "C",
  "action_family" text COLLATE "C" NOT NULL,
  "decision_outcome" text COLLATE "C" NOT NULL,
  "coverage_state" text COLLATE "C" NOT NULL,
  "reason_code" text COLLATE "C" NOT NULL,
  "owner" text COLLATE "C" NOT NULL,
  "source_ref" text COLLATE "C" NOT NULL,
  "occurred_at" bigint NOT NULL,
  "receipt_bytes" bigint NOT NULL,
  "receipt_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("receipt_id"),
  CHECK ((char_length("receipt_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("context_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("execution_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256)),
  CHECK ("action_id" IS NULL OR (char_length("action_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("action_family") BETWEEN 1 AND 256)),
  CHECK (("decision_outcome" IN ('allowed', 'denied', 'not-applicable', 'unknown'))),
  CHECK (("coverage_state" IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported'))),
  CHECK ((char_length("reason_code") BETWEEN 1 AND 256)),
  CHECK ((char_length("owner") BETWEEN 1 AND 256)),
  CHECK ((char_length("source_ref") BETWEEN 1 AND 256)),
  CHECK (("occurred_at" >= 0)),
  CHECK (("receipt_bytes" BETWEEN 1 AND 16384)),
  CHECK ((char_length("receipt_json") > 0)),
  UNIQUE ("occurred_at", "receipt_id")
);

CREATE INDEX "execution_decision_facts_context_occurred_idx" ON "execution_decision_facts" (("context_id") ASC, ("occurred_at") ASC, ("receipt_id") ASC);

CREATE UNIQUE INDEX "execution_decision_facts_cursor_id_idx" ON "execution_decision_facts" (("cursor_id") ASC);

CREATE INDEX "execution_decision_facts_run_occurred_idx" ON "execution_decision_facts" (("run_id") ASC, ("occurred_at") ASC, ("receipt_id") ASC);
`},{id:`execution_owner_lifecycle_bindings`,tables:[`execution_owner_lifecycle_bindings`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "execution_owner_lifecycle_bindings" (
  "owner_kind" text COLLATE "C" NOT NULL,
  "owner_id" text COLLATE "C" NOT NULL,
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("owner_kind", "owner_id")
);
`},{id:`outbound_message_execution_bindings`,tables:[`outbound_message_execution_bindings`],indexes:[`outbound_message_execution_bindings_execution_event_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "outbound_message_execution_bindings" (
  "event_id" text COLLATE "C" NOT NULL,
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("event_id"),
  CHECK ((char_length("context_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("execution_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256))
);

CREATE INDEX "outbound_message_execution_bindings_execution_event_idx" ON "outbound_message_execution_bindings" (("context_id") ASC, ("execution_id") ASC, ("run_id") ASC, ("event_id") ASC);

ALTER TABLE "outbound_message_execution_bindings" ADD FOREIGN KEY ("event_id") REFERENCES "audit_events" ("event_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`outbound_message_progress`,tables:[`outbound_message_progress`],indexes:[`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "outbound_message_progress" (
  "sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "progress_id" text COLLATE "C" NOT NULL,
  "source_id" text COLLATE "C" NOT NULL,
  "source_sequence" bigint NOT NULL,
  "schema_version" bigint NOT NULL,
  "occurred_at" bigint NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "outcome" text COLLATE "C" NOT NULL,
  "actor_type" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "context_id" text COLLATE "C",
  "execution_id" text COLLATE "C",
  "channel" text COLLATE "C" NOT NULL,
  "conversation_kind" text COLLATE "C" NOT NULL,
  "duration_ms" bigint,
  "account_ref" text COLLATE "C",
  "conversation_ref" text COLLATE "C",
  "target_ref" text COLLATE "C",
  PRIMARY KEY ("sequence"),
  CHECK ((char_length("progress_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("source_id") BETWEEN 1 AND 512)),
  CHECK (("source_sequence" >= 1)),
  CHECK (("schema_version" = 1)),
  CHECK (("occurred_at" >= 0)),
  CHECK (("action" IN ('message.outbound.queued', 'message.outbound.platform-started'))),
  CHECK (("outcome" IN ('queued', 'platform_started'))),
  CHECK (("actor_type" IN ('agent', 'system'))),
  CHECK ((char_length("actor_id") BETWEEN 1 AND 256)),
  CHECK ("agent_id" IS NULL OR (char_length("agent_id") BETWEEN 1 AND 256)),
  CHECK ("run_id" IS NULL OR (char_length("run_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("channel") BETWEEN 1 AND 256)),
  CHECK (("conversation_kind" IN ('direct', 'group', 'channel', 'unknown'))),
  CHECK ("duration_ms" IS NULL OR ("duration_ms" >= 0)),
  UNIQUE ("progress_id"),
  UNIQUE ("source_id"),
  UNIQUE ("occurred_at", "progress_id")
);

CREATE INDEX "outbound_message_progress_occurred_idx" ON "outbound_message_progress" (("occurred_at") ASC, ("sequence") ASC);

CREATE INDEX "outbound_message_progress_run_occurred_idx" ON "outbound_message_progress" (("run_id") ASC NULLS FIRST, ("occurred_at") ASC, ("sequence") ASC);
`},{id:`agent_provenance`,tables:[`agent_provenance`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "agent_provenance" (
  "agent_id" text COLLATE "C" NOT NULL,
  "created_via" text COLLATE "C" NOT NULL,
  "creator_agent_id" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id"),
  CHECK (("created_via" IN ('operator', 'agent', 'template')))
);
`},{id:`cron_run_receipts`,tables:[`cron_run_receipts`],indexes:[`cron_run_receipts_cursor_id_idx`,`idx_cron_run_receipts_active_job`,`idx_cron_run_receipts_job_history`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "cron_run_receipts" (
  "cursor_id" bigint NOT NULL,
  "receipt_id" text COLLATE "C" NOT NULL,
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "config_revision" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "request_run_id" text COLLATE "C",
  "delivery_attempt_state" text COLLATE "C" NOT NULL DEFAULT 'unknown',
  "status" text COLLATE "C" NOT NULL,
  "owner_pid" bigint NOT NULL,
  "owner_start_time" bigint,
  "started_at_ms" bigint NOT NULL,
  "finished_at_ms" bigint,
  "error_text" text COLLATE "C",
  PRIMARY KEY ("receipt_id"),
  CHECK (("delivery_attempt_state" IN ('unknown', 'not-started', 'started'))),
  CHECK (("status" IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded'))),
  CHECK ((("status" = 'running') AND "finished_at_ms" IS NULL) OR (("status" != 'running') AND "finished_at_ms" IS NOT NULL))
);

CREATE UNIQUE INDEX "cron_run_receipts_cursor_id_idx" ON "cron_run_receipts" (("cursor_id") ASC);

CREATE UNIQUE INDEX "idx_cron_run_receipts_active_job" ON "cron_run_receipts" (("store_key") ASC, ("job_id") ASC) WHERE ("status" = 'running');

CREATE INDEX "idx_cron_run_receipts_job_history" ON "cron_run_receipts" (("store_key") ASC, ("job_id") ASC, ("started_at_ms") DESC, ("receipt_id") DESC);
`},{id:`config_revision_keys`,tables:[`config_revision_keys`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "config_revision_keys" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "hmac_key" bytea NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("id" = 1)),
  CHECK ((octet_length("hmac_key") = 32))
);
`},{id:`secret_store_entries`,tables:[`secret_store_entries`],indexes:[`secret_store_entries_live_idx`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "secret_store_entries" (
  "scope_kind" text COLLATE "C" NOT NULL,
  "scope_id" text COLLATE "C" NOT NULL,
  "name" text COLLATE "C" NOT NULL,
  "value" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "updated_by" text COLLATE "C",
  "deleted_at_ms" bigint,
  "allowed_hosts" text COLLATE "C",
  PRIMARY KEY ("scope_kind", "scope_id", "name"),
  CHECK (("scope_kind" IN ('team', 'identity'))),
  CHECK (("kind" IN ('secret', 'env'))),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  CHECK ((("scope_kind" = 'team') AND ("scope_id" = '')) OR (("scope_kind" = 'identity') AND (char_length("scope_id") > 0)))
);

CREATE INDEX "secret_store_entries_live_idx" ON "secret_store_entries" (("scope_kind") ASC, ("scope_id") ASC, ("name") ASC) WHERE "deleted_at_ms" IS NULL;
`},{id:`projects`,tables:[`projects`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "projects" (
  "id" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C" NOT NULL,
  "repo_root" text COLLATE "C" NOT NULL,
  "origin_url" text COLLATE "C",
  "source" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("source" IN ('registered', 'cloned')))
);
`},{id:`worktree_templates`,tables:[`worktree_templates`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worktree_templates" (
  "cache_key" text COLLATE "C" NOT NULL,
  "id" text COLLATE "C" NOT NULL,
  "repo_root" text COLLATE "C" NOT NULL,
  "common_dir" text COLLATE "C" NOT NULL,
  "worktree_root" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "backend" text COLLATE "C" NOT NULL,
  "source_commit" text COLLATE "C" NOT NULL,
  "content_key" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "last_used_at" bigint NOT NULL,
  PRIMARY KEY ("cache_key"),
  CHECK (("status" IN ('preparing', 'ready'))),
  UNIQUE ("id")
);
`},{id:`user_preferences`,tables:[`user_preferences`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "user_preferences" (
  "profile_id" text COLLATE "C" NOT NULL,
  "pref_key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("profile_id", "pref_key")
);
`},{id:`device_pair_setup_completions`,tables:[`device_pair_setup_completions`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "device_pair_setup_completions" (
  "setup_id" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "device_name" text COLLATE "C",
  "access" text COLLATE "C" NOT NULL,
  "completed_at_ms" bigint NOT NULL,
  "delivery_state" text COLLATE "C" NOT NULL,
  "retain_until_ms" bigint NOT NULL,
  PRIMARY KEY ("setup_id"),
  CHECK (("delivery_state" IN ('uncertain', 'confirmed')))
);
`},{id:`github_publication_requests`,tables:[`github_publication_requests`],indexes:[`idx_github_publication_requests_pending`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_publication_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "idempotency_key" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "worktree_id" text COLLATE "C" NOT NULL,
  "repository_fingerprint" text COLLATE "C" NOT NULL,
  "claim_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "environment_id" text COLLATE "C",
  "owner_epoch" bigint,
  "placement_generation" bigint,
  "identity_source" text COLLATE "C" NOT NULL,
  "identity_profile_id" text COLLATE "C",
  "identity_account_id" bigint NOT NULL,
  "identity_login" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "body" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C",
  "repository" text COLLATE "C",
  "branch" text COLLATE "C" NOT NULL,
  "base_branch" text COLLATE "C",
  "source_head_commit" text COLLATE "C",
  "source_index_tree" text COLLATE "C",
  "workspace_tree" text COLLATE "C",
  "head_commit" text COLLATE "C",
  "pull_request_url" text COLLATE "C",
  "error_code" text COLLATE "C",
  "next_action" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "reported_at_ms" bigint,
  "draft" bigint,
  PRIMARY KEY ("request_id"),
  CHECK ("owner_epoch" IS NULL OR ("owner_epoch" >= 1)),
  CHECK ("placement_generation" IS NULL OR ("placement_generation" >= 0)),
  CHECK (("identity_source" IN ('system-detected', 'system-configured', 'agent-override'))),
  CHECK (("identity_account_id" >= 1)),
  CHECK (("status" IN ('requested', 'publishing', 'published', 'failed'))),
  CHECK (("claim_id" IS NULL AND "run_id" IS NULL AND "environment_id" IS NULL AND "owner_epoch" IS NULL AND "placement_generation" IS NULL) OR ("claim_id" IS NOT NULL AND "run_id" IS NOT NULL AND "placement_generation" IS NOT NULL AND (("environment_id" IS NULL AND "owner_epoch" IS NULL) OR ("environment_id" IS NOT NULL AND "owner_epoch" IS NOT NULL)))),
  CHECK (("identity_source" IS NOT DISTINCT FROM 'system-detected' AND "identity_profile_id" IS NULL) OR (("identity_source" IN ('system-configured', 'agent-override')) AND "identity_profile_id" IS NOT NULL)),
  CHECK (("source_head_commit" IS NULL AND "source_index_tree" IS NULL AND "workspace_tree" IS NULL) OR ("source_head_commit" IS NOT NULL AND "workspace_tree" IS NOT NULL)),
  CHECK (("status" IS NOT DISTINCT FROM 'published' AND "pull_request_url" IS NOT NULL AND "error_code" IS NULL AND "next_action" IS NULL) OR ("status" IS NOT DISTINCT FROM 'failed' AND "pull_request_url" IS NULL AND "error_code" IS NOT NULL AND "next_action" IS NOT NULL) OR (("status" IN ('requested', 'publishing')) AND "pull_request_url" IS NULL AND "error_code" IS NULL AND "next_action" IS NULL)),
  UNIQUE ("session_id", "idempotency_key")
);

CREATE INDEX "idx_github_publication_requests_pending" ON "github_publication_requests" (("status") ASC, ("updated_at_ms") ASC, ("request_id") ASC);
`},{id:`device_pairing_join_codes`,tables:[`device_pairing_join_codes`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "device_pairing_join_codes" (
  "shortcode" text COLLATE "C",
  "payload_json" text COLLATE "C",
  "created_at_ms" bigint,
  "expires_at_ms" bigint
);
`},{id:`device_pairing_browser_requests`,tables:[`device_pairing_browser_requests`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "device_pairing_browser_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "code" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "public_key" text COLLATE "C" NOT NULL,
  "remote_ip" text COLLATE "C",
  "user_agent" text COLLATE "C",
  "origin" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "approved_token_sha256" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  PRIMARY KEY ("request_id"),
  CHECK (("status" IN ('pending', 'approved', 'rejected'))),
  UNIQUE ("code"),
  UNIQUE ("device_id")
);
`},{id:`skill_workshop_changes`,tables:[`skill_workshop_changes`],indexes:[`skill_workshop_changes_cursor_id_idx`,`idx_skill_workshop_changes_agent_time`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "skill_workshop_changes" (
  "cursor_id" bigint NOT NULL,
  "change_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "skill_name" text COLLATE "C" NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "actor" text COLLATE "C" NOT NULL,
  "summary" text COLLATE "C" NOT NULL,
  "version_id" text COLLATE "C",
  "session_key" text COLLATE "C",
  "run_id" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("change_id"),
  CHECK (("action" IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore'))),
  CHECK (("actor" IN ('agent', 'review', 'curator', 'user')))
);

CREATE INDEX "idx_skill_workshop_changes_agent_time" ON "skill_workshop_changes" (("agent_id") ASC, ("created_at_ms") ASC);

CREATE UNIQUE INDEX "skill_workshop_changes_cursor_id_idx" ON "skill_workshop_changes" (("cursor_id") ASC);
`},{id:`worker_environment_ssh_fallback_ports`,tables:[`worker_environment_ssh_fallback_ports`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worker_environment_ssh_fallback_ports" (
  "environment_id" text COLLATE "C" NOT NULL,
  "position" bigint NOT NULL,
  "port" bigint NOT NULL,
  PRIMARY KEY ("environment_id", "position"),
  CHECK (("position" >= 0) AND ("position" <= 9)),
  CHECK (("port" >= 1) AND ("port" <= 65535)),
  UNIQUE ("environment_id", "port")
);

ALTER TABLE "worker_environment_ssh_fallback_ports" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`worker_session_placement_moves`,tables:[`worker_session_placement_moves`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worker_session_placement_moves" (
  "operation_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "source_generation" bigint NOT NULL,
  "source_environment_id" text COLLATE "C" NOT NULL,
  "source_owner_epoch" bigint NOT NULL,
  "target_kind" text COLLATE "C" NOT NULL,
  "target_id" text COLLATE "C",
  "target_machine_class" text COLLATE "C",
  "target_os" text COLLATE "C",
  "abandon_source" bigint,
  "last_error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("operation_id"),
  CHECK (("source_generation" >= 0)),
  CHECK ((char_length("source_environment_id") BETWEEN 1 AND 256) AND ("source_environment_id" = btrim("source_environment_id"))),
  CHECK (("source_owner_epoch" >= 1)),
  CHECK (("target_kind" IN ('gateway', 'profile', 'device'))),
  CHECK (("target_kind" IS NOT DISTINCT FROM 'gateway' AND "target_id" IS NULL) OR (("target_kind" IN ('profile', 'device')) AND "target_id" IS NOT NULL AND (char_length("target_id") BETWEEN 1 AND 256) AND ("target_id" = btrim("target_id")))),
  UNIQUE ("session_id")
);

ALTER TABLE "worker_session_placement_moves" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`agent_deletion_journal`,tables:[`agent_deletion_journal`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "agent_deletion_journal" (
  "agent_id" text COLLATE "C" NOT NULL,
  "operation_id" text COLLATE "C" NOT NULL DEFAULT '',
  "phase" text COLLATE "C",
  "agent_dir" text COLLATE "C" NOT NULL,
  "workspace_dir" text COLLATE "C" NOT NULL,
  "sessions_dir" text COLLATE "C" NOT NULL,
  "database_paths_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "cleanup_paths_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "created_at" bigint NOT NULL,
  "cleanup_completed" bigint NOT NULL DEFAULT 0,
  "delete_files" bigint NOT NULL DEFAULT 1,
  PRIMARY KEY ("agent_id")
);
`}];return Object.defineProperty(this,"fragments",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get expectedCatalog(){let e=[{table:`acp_replay_events`,kind:`table`,value:null},{table:`acp_replay_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_replay_events`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`acp_replay_events`,kind:`column`,value:{name:`at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_replay_events`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_replay_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`acp_replay_events`,kind:`column`,value:{name:`update_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`acp_replay_events`,kind:`column`,value:{name:`estimated_bytes`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`acp_replay_events`,kind:`primaryKey`,value:[`session_id`,`seq`]},{table:`acp_replay_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`acp_replay_sessions`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`acp_replay_events`,kind:`indexes`,value:1},{table:`acp_replay_events`,kind:`checks`,value:0},{table:`acp_replay_sessions`,kind:`table`,value:null},{table:`acp_replay_sessions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`cwd`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`complete`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`next_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`estimated_bytes`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:8}},{table:`acp_replay_sessions`,kind:`primaryKey`,value:[`session_id`]},{table:`acp_replay_sessions`,kind:`indexes`,value:3},{table:`acp_replay_sessions`,kind:`checks`,value:0},{table:`acp_sessions`,kind:`table`,value:null},{table:`acp_sessions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_sessions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`acp_sessions`,kind:`column`,value:{name:`backend`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_sessions`,kind:`column`,value:{name:`agent`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_sessions`,kind:`column`,value:{name:`runtime_session_name`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`acp_sessions`,kind:`column`,value:{name:`identity_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`acp_sessions`,kind:`column`,value:{name:`resume_agent_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`acp_sessions`,kind:`column`,value:{name:`resume_acpx_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`acp_sessions`,kind:`column`,value:{name:`mode`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`acp_sessions`,kind:`column`,value:{name:`runtime_options_json`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`acp_sessions`,kind:`column`,value:{name:`cwd`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`acp_sessions`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`acp_sessions`,kind:`column`,value:{name:`last_activity_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`acp_sessions`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`acp_sessions`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`acp_sessions`,kind:`primaryKey`,value:[`session_key`]},{table:`acp_sessions`,kind:`indexes`,value:5},{table:`acp_sessions`,kind:`checks`,value:0},{table:`agent_database_leases`,kind:`table`,value:null},{table:`agent_database_leases`,kind:`column`,value:{name:`lease_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_database_leases`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_database_leases`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`agent_database_leases`,kind:`column`,value:{name:`owner_pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_database_leases`,kind:`column`,value:{name:`owner_start_time`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`agent_database_leases`,kind:`column`,value:{name:`opened_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`agent_database_leases`,kind:`column`,value:{name:`provenance`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`agent_database_leases`,kind:`primaryKey`,value:[`lease_id`]},{table:`agent_database_leases`,kind:`indexes`,value:1},{table:`agent_database_leases`,kind:`checks`,value:0},{table:`agent_databases`,kind:`table`,value:null},{table:`agent_databases`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_databases`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_databases`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`agent_databases`,kind:`column`,value:{name:`last_seen_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_databases`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`agent_databases`,kind:`primaryKey`,value:[`agent_id`,`path`]},{table:`agent_databases`,kind:`indexes`,value:1},{table:`agent_databases`,kind:`checks`,value:0},{table:`agent_deletion_journal`,kind:`table`,value:null},{table:`agent_deletion_journal`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`operation_id`,type:`text`,nullable:!1,identity:!1,default:`''`,position:2}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`phase`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`agent_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`workspace_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`sessions_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`database_paths_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:7}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`cleanup_paths_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:8}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`cleanup_completed`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:10}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`delete_files`,type:`bigint`,nullable:!1,identity:!1,default:`1`,position:11}},{table:`agent_deletion_journal`,kind:`primaryKey`,value:[`agent_id`]},{table:`agent_deletion_journal`,kind:`indexes`,value:1},{table:`agent_deletion_journal`,kind:`checks`,value:0},{table:`agent_provenance`,kind:`table`,value:null},{table:`agent_provenance`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_provenance`,kind:`column`,value:{name:`created_via`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_provenance`,kind:`column`,value:{name:`creator_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`agent_provenance`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_provenance`,kind:`primaryKey`,value:[`agent_id`]},{table:`agent_provenance`,kind:`indexes`,value:1},{table:`agent_provenance`,kind:`checks`,value:1},{table:`apns_registration_tombstones`,kind:`table`,value:null},{table:`apns_registration_tombstones`,kind:`column`,value:{name:`node_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`apns_registration_tombstones`,kind:`column`,value:{name:`deleted_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`apns_registration_tombstones`,kind:`primaryKey`,value:[`node_id`]},{table:`apns_registration_tombstones`,kind:`indexes`,value:1},{table:`apns_registration_tombstones`,kind:`checks`,value:0},{table:`apns_registrations`,kind:`table`,value:null},{table:`apns_registrations`,kind:`column`,value:{name:`node_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`apns_registrations`,kind:`column`,value:{name:`transport`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`apns_registrations`,kind:`column`,value:{name:`token`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`apns_registrations`,kind:`column`,value:{name:`relay_handle`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`apns_registrations`,kind:`column`,value:{name:`send_grant`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`apns_registrations`,kind:`column`,value:{name:`installation_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`apns_registrations`,kind:`column`,value:{name:`relay_origin`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`apns_registrations`,kind:`column`,value:{name:`topic`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`apns_registrations`,kind:`column`,value:{name:`environment`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`apns_registrations`,kind:`column`,value:{name:`distribution`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`apns_registrations`,kind:`column`,value:{name:`token_debug_suffix`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`apns_registrations`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`apns_registrations`,kind:`primaryKey`,value:[`node_id`]},{table:`apns_registrations`,kind:`indexes`,value:2},{table:`apns_registrations`,kind:`checks`,value:0},{table:`audit_events`,kind:`table`,value:null},{table:`audit_events`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`audit_events`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`audit_events`,kind:`column`,value:{name:`source_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`audit_events`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:`1`,position:4}},{table:`audit_events`,kind:`column`,value:{name:`source_sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`audit_events`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`audit_events`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`audit_events`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`audit_events`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`audit_events`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`audit_events`,kind:`column`,value:{name:`actor_type`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`audit_events`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`audit_events`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`audit_events`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`audit_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`audit_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`audit_events`,kind:`column`,value:{name:`tool_call_id`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`audit_events`,kind:`column`,value:{name:`tool_name`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`audit_events`,kind:`column`,value:{name:`direction`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`audit_events`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`audit_events`,kind:`column`,value:{name:`conversation_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`audit_events`,kind:`column`,value:{name:`message_outcome`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`audit_events`,kind:`column`,value:{name:`reason_code`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`audit_events`,kind:`column`,value:{name:`delivery_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`audit_events`,kind:`column`,value:{name:`failure_stage`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`audit_events`,kind:`column`,value:{name:`duration_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:26}},{table:`audit_events`,kind:`column`,value:{name:`result_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:27}},{table:`audit_events`,kind:`column`,value:{name:`account_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`audit_events`,kind:`column`,value:{name:`conversation_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`audit_events`,kind:`column`,value:{name:`message_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`audit_events`,kind:`column`,value:{name:`target_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`audit_events`,kind:`primaryKey`,value:[`sequence`]},{table:`audit_events`,kind:`unique`,value:[`event_id`]},{table:`audit_events`,kind:`unique`,value:[`source_id`]},{table:`audit_events`,kind:`indexes`,value:11},{table:`audit_events`,kind:`checks`,value:0},{table:`audit_identity_keys`,kind:`table`,value:null},{table:`audit_identity_keys`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`audit_identity_keys`,kind:`column`,value:{name:`key_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`audit_identity_keys`,kind:`column`,value:{name:`key`,type:`bytea`,nullable:!1,identity:!1,default:null,position:3}},{table:`audit_identity_keys`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`audit_identity_keys`,kind:`primaryKey`,value:[`id`]},{table:`audit_identity_keys`,kind:`indexes`,value:1},{table:`audit_identity_keys`,kind:`checks`,value:1},{table:`backup_runs`,kind:`table`,value:null},{table:`backup_runs`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`backup_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`backup_runs`,kind:`column`,value:{name:`archive_path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`backup_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`backup_runs`,kind:`column`,value:{name:`manifest_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`backup_runs`,kind:`primaryKey`,value:[`id`]},{table:`backup_runs`,kind:`indexes`,value:2},{table:`backup_runs`,kind:`checks`,value:0},{table:`capture_blobs`,kind:`table`,value:null},{table:`capture_blobs`,kind:`column`,value:{name:`blob_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`capture_blobs`,kind:`column`,value:{name:`content_type`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`capture_blobs`,kind:`column`,value:{name:`encoding`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`capture_blobs`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`capture_blobs`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`capture_blobs`,kind:`column`,value:{name:`data`,type:`bytea`,nullable:!1,identity:!1,default:null,position:6}},{table:`capture_blobs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`capture_blobs`,kind:`primaryKey`,value:[`blob_id`]},{table:`capture_blobs`,kind:`indexes`,value:1},{table:`capture_blobs`,kind:`checks`,value:0},{table:`capture_events`,kind:`table`,value:null},{table:`capture_events`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`capture_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`capture_events`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`capture_events`,kind:`column`,value:{name:`source_scope`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`capture_events`,kind:`column`,value:{name:`source_process`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`capture_events`,kind:`column`,value:{name:`protocol`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`capture_events`,kind:`column`,value:{name:`direction`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`capture_events`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`capture_events`,kind:`column`,value:{name:`flow_id`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`capture_events`,kind:`column`,value:{name:`method`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`capture_events`,kind:`column`,value:{name:`host`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`capture_events`,kind:`column`,value:{name:`path`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`capture_events`,kind:`column`,value:{name:`status`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`capture_events`,kind:`column`,value:{name:`close_code`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`capture_events`,kind:`column`,value:{name:`content_type`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`capture_events`,kind:`column`,value:{name:`headers_json`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`capture_events`,kind:`column`,value:{name:`data_text`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`capture_events`,kind:`column`,value:{name:`data_blob_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`capture_events`,kind:`column`,value:{name:`data_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`capture_events`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`capture_events`,kind:`column`,value:{name:`meta_json`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`capture_events`,kind:`primaryKey`,value:[`id`]},{table:`capture_events`,kind:`foreignKey`,value:{columns:[`data_blob_id`],target:`capture_blobs`,targetColumns:[`blob_id`],onUpdate:`NO ACTION`,onDelete:`SET NULL`,deferrable:!1,deferred:!1}},{table:`capture_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`capture_sessions`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`capture_events`,kind:`indexes`,value:3},{table:`capture_events`,kind:`checks`,value:0},{table:`capture_sessions`,kind:`table`,value:null},{table:`capture_sessions`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`capture_sessions`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`capture_sessions`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`capture_sessions`,kind:`column`,value:{name:`mode`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`capture_sessions`,kind:`column`,value:{name:`source_scope`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`capture_sessions`,kind:`column`,value:{name:`source_process`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`capture_sessions`,kind:`column`,value:{name:`proxy_url`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`capture_sessions`,kind:`primaryKey`,value:[`id`]},{table:`capture_sessions`,kind:`indexes`,value:1},{table:`capture_sessions`,kind:`checks`,value:0},{table:`channel_ingress_events`,kind:`table`,value:null},{table:`channel_ingress_events`,kind:`column`,value:{name:`queue_name`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`channel_ingress_events`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`channel_ingress_events`,kind:`column`,value:{name:`channel_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`channel_ingress_events`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`channel_ingress_events`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`channel_ingress_events`,kind:`column`,value:{name:`lane_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`channel_ingress_events`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`channel_ingress_events`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`channel_ingress_events`,kind:`column`,value:{name:`received_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`channel_ingress_events`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`channel_ingress_events`,kind:`column`,value:{name:`claim_token`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`channel_ingress_events`,kind:`column`,value:{name:`claim_owner`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`channel_ingress_events`,kind:`column`,value:{name:`claimed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`channel_ingress_events`,kind:`column`,value:{name:`attempts`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:14}},{table:`channel_ingress_events`,kind:`column`,value:{name:`last_attempt_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`channel_ingress_events`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`channel_ingress_events`,kind:`column`,value:{name:`failed_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`channel_ingress_events`,kind:`column`,value:{name:`failed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:18}},{table:`channel_ingress_events`,kind:`column`,value:{name:`completed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`channel_ingress_events`,kind:`column`,value:{name:`completed_metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`channel_ingress_events`,kind:`primaryKey`,value:[`queue_name`,`event_id`]},{table:`channel_ingress_events`,kind:`indexes`,value:4},{table:`channel_ingress_events`,kind:`checks`,value:0},{table:`channel_pairing_allow_entries`,kind:`table`,value:null},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`channel_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`entry`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`sort_order`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`channel_pairing_allow_entries`,kind:`primaryKey`,value:[`channel_key`,`account_id`,`entry`]},{table:`channel_pairing_allow_entries`,kind:`indexes`,value:2},{table:`channel_pairing_allow_entries`,kind:`checks`,value:0},{table:`channel_pairing_requests`,kind:`table`,value:null},{table:`channel_pairing_requests`,kind:`column`,value:{name:`channel_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`code`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`created_at`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`last_seen_at`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`meta_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`channel_pairing_requests`,kind:`primaryKey`,value:[`channel_key`,`account_id`,`request_id`]},{table:`channel_pairing_requests`,kind:`indexes`,value:3},{table:`channel_pairing_requests`,kind:`checks`,value:0},{table:`clawhub_promotion_claims`,kind:`table`,value:null},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`provider`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`model_keys_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`ends_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`claimed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`clawhub_promotion_claims`,kind:`primaryKey`,value:[`slug`]},{table:`clawhub_promotion_claims`,kind:`indexes`,value:1},{table:`clawhub_promotion_claims`,kind:`checks`,value:0},{table:`config_health_entries`,kind:`table`,value:null},{table:`config_health_entries`,kind:`column`,value:{name:`config_path`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`config_health_entries`,kind:`column`,value:{name:`last_known_good_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`config_health_entries`,kind:`column`,value:{name:`last_promoted_good_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`config_health_entries`,kind:`column`,value:{name:`last_observed_suspicious_signature`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`config_health_entries`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`config_health_entries`,kind:`primaryKey`,value:[`config_path`]},{table:`config_health_entries`,kind:`indexes`,value:1},{table:`config_health_entries`,kind:`checks`,value:0},{table:`config_machine_state`,kind:`table`,value:null},{table:`config_machine_state`,kind:`column`,value:{name:`state_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`config_machine_state`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`config_machine_state`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`config_machine_state`,kind:`primaryKey`,value:[`state_key`]},{table:`config_machine_state`,kind:`indexes`,value:1},{table:`config_machine_state`,kind:`checks`,value:0},{table:`config_revision_keys`,kind:`table`,value:null},{table:`config_revision_keys`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`config_revision_keys`,kind:`column`,value:{name:`hmac_key`,type:`bytea`,nullable:!1,identity:!1,default:null,position:2}},{table:`config_revision_keys`,kind:`primaryKey`,value:[`id`]},{table:`config_revision_keys`,kind:`indexes`,value:1},{table:`config_revision_keys`,kind:`checks`,value:2},{table:`cron_job_runtime_authorities`,kind:`table`,value:null},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`authority_input_fingerprint`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`recovery_required`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`cron_job_runtime_authorities`,kind:`primaryKey`,value:[`store_key`,`job_id`]},{table:`cron_job_runtime_authorities`,kind:`foreignKey`,value:{columns:[`store_key`,`job_id`],target:`cron_jobs`,targetColumns:[`store_key`,`job_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`cron_job_runtime_authorities`,kind:`indexes`,value:1},{table:`cron_job_runtime_authorities`,kind:`checks`,value:2},{table:`cron_job_scratch`,kind:`table`,value:null},{table:`cron_job_scratch`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_job_scratch`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_job_scratch`,kind:`column`,value:{name:`content`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cron_job_scratch`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`cron_job_scratch`,kind:`column`,value:{name:`source_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`cron_job_scratch`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`cron_job_scratch`,kind:`primaryKey`,value:[`store_key`,`job_id`]},{table:`cron_job_scratch`,kind:`indexes`,value:2},{table:`cron_job_scratch`,kind:`checks`,value:2},{table:`cron_jobs`,kind:`table`,value:null},{table:`cron_jobs`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_jobs`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_jobs`,kind:`column`,value:{name:`declaration_key`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cron_jobs`,kind:`column`,value:{name:`owner_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`cron_jobs`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`cron_jobs`,kind:`column`,value:{name:`description`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`cron_jobs`,kind:`column`,value:{name:`enabled`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`cron_jobs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`cron_jobs`,kind:`column`,value:{name:`payload_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`cron_jobs`,kind:`column`,value:{name:`job_json`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`cron_jobs`,kind:`column`,value:{name:`grant_definition_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`cron_jobs`,kind:`column`,value:{name:`grant_definition_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`cron_jobs`,kind:`column`,value:{name:`grant_definition_updated_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`cron_jobs`,kind:`column`,value:{name:`state_json`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:14}},{table:`cron_jobs`,kind:`column`,value:{name:`runtime_updated_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`cron_jobs`,kind:`column`,value:{name:`schedule_identity`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`cron_jobs`,kind:`column`,value:{name:`sort_order`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:17}},{table:`cron_jobs`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`cron_jobs`,kind:`primaryKey`,value:[`store_key`,`job_id`]},{table:`cron_jobs`,kind:`indexes`,value:2},{table:`cron_jobs`,kind:`checks`,value:0},{table:`cron_run_receipts`,kind:`table`,value:null},{table:`cron_run_receipts`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_run_receipts`,kind:`column`,value:{name:`receipt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_run_receipts`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`cron_run_receipts`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`cron_run_receipts`,kind:`column`,value:{name:`config_revision`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`cron_run_receipts`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`cron_run_receipts`,kind:`column`,value:{name:`request_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`cron_run_receipts`,kind:`column`,value:{name:`delivery_attempt_state`,type:`text`,nullable:!1,identity:!1,default:`'unknown'`,position:8}},{table:`cron_run_receipts`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`cron_run_receipts`,kind:`column`,value:{name:`owner_pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`cron_run_receipts`,kind:`column`,value:{name:`owner_start_time`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`cron_run_receipts`,kind:`column`,value:{name:`started_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`cron_run_receipts`,kind:`column`,value:{name:`finished_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`cron_run_receipts`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`cron_run_receipts`,kind:`primaryKey`,value:[`receipt_id`]},{table:`cron_run_receipts`,kind:`indexes`,value:4},{table:`cron_run_receipts`,kind:`checks`,value:3},{table:`cron_run_trigger_state_retirements`,kind:`table`,value:null},{table:`cron_run_trigger_state_retirements`,kind:`column`,value:{name:`receipt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_run_trigger_state_retirements`,kind:`primaryKey`,value:[`receipt_id`]},{table:`cron_run_trigger_state_retirements`,kind:`foreignKey`,value:{columns:[`receipt_id`],target:`cron_run_receipts`,targetColumns:[`receipt_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`cron_run_trigger_state_retirements`,kind:`indexes`,value:1},{table:`cron_run_trigger_state_retirements`,kind:`checks`,value:0},{table:`current_conversation_bindings`,kind:`table`,value:null},{table:`current_conversation_bindings`,kind:`column`,value:{name:`binding_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`binding_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`target_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`conversation_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`parent_conversation_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`conversation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`target_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`bound_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`record_json`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`current_conversation_bindings`,kind:`primaryKey`,value:[`binding_key`]},{table:`current_conversation_bindings`,kind:`indexes`,value:4},{table:`current_conversation_bindings`,kind:`checks`,value:0},{table:`delivery_queue_entries`,kind:`table`,value:null},{table:`delivery_queue_entries`,kind:`column`,value:{name:`queue_name`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`entry_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`target`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retry_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:9}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`last_attempt_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`recovery_state`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`platform_send_started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`entry_json`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retention_id_prefix`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retention_max_age_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retention_max_entries`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`enqueued_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`failed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:20}},{table:`delivery_queue_entries`,kind:`primaryKey`,value:[`queue_name`,`id`]},{table:`delivery_queue_entries`,kind:`indexes`,value:6},{table:`delivery_queue_entries`,kind:`checks`,value:0},{table:`device_bootstrap_tokens`,kind:`table`,value:null},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`token_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`setup_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`profile_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`redeemed_profile_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`pending_profile_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`issued_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`device_bootstrap_tokens`,kind:`primaryKey`,value:[`token_key`]},{table:`device_bootstrap_tokens`,kind:`indexes`,value:2},{table:`device_bootstrap_tokens`,kind:`checks`,value:0},{table:`device_pair_setup_completions`,kind:`table`,value:null},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`setup_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`device_name`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`access`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`delivery_state`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`retain_until_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`device_pair_setup_completions`,kind:`primaryKey`,value:[`setup_id`]},{table:`device_pair_setup_completions`,kind:`indexes`,value:1},{table:`device_pair_setup_completions`,kind:`checks`,value:1},{table:`device_pairing_browser_requests`,kind:`table`,value:null},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`code`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`remote_ip`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`user_agent`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`origin`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`approved_token_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`device_pairing_browser_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`device_pairing_browser_requests`,kind:`unique`,value:[`code`]},{table:`device_pairing_browser_requests`,kind:`unique`,value:[`device_id`]},{table:`device_pairing_browser_requests`,kind:`indexes`,value:3},{table:`device_pairing_browser_requests`,kind:`checks`,value:1},{table:`device_pairing_join_codes`,kind:`table`,value:null},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`shortcode`,type:`text`,nullable:!0,identity:!1,default:null,position:1}},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`device_pairing_join_codes`,kind:`indexes`,value:0},{table:`device_pairing_join_codes`,kind:`checks`,value:0},{table:`device_pairing_paired`,kind:`table`,value:null},{table:`device_pairing_paired`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pairing_paired`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pairing_paired`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_pairing_paired`,kind:`column`,value:{name:`operator_label`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`device_pairing_paired`,kind:`column`,value:{name:`platform`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_pairing_paired`,kind:`column`,value:{name:`device_family`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_pairing_paired`,kind:`column`,value:{name:`client_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_pairing_paired`,kind:`column`,value:{name:`client_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`device_pairing_paired`,kind:`column`,value:{name:`browser_origin`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_pairing_paired`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`device_pairing_paired`,kind:`column`,value:{name:`roles_json`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`device_pairing_paired`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`device_pairing_paired`,kind:`column`,value:{name:`approved_scopes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`device_pairing_paired`,kind:`column`,value:{name:`remote_ip`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`device_pairing_paired`,kind:`column`,value:{name:`tokens_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`device_pairing_paired`,kind:`column`,value:{name:`approved_via`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`device_pairing_paired`,kind:`column`,value:{name:`node_surface_json`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`device_pairing_paired`,kind:`column`,value:{name:`pending_node_surface_json`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`device_pairing_paired`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`device_pairing_paired`,kind:`column`,value:{name:`approved_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`device_pairing_paired`,kind:`column`,value:{name:`last_seen_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:21}},{table:`device_pairing_paired`,kind:`column`,value:{name:`last_seen_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`device_pairing_paired`,kind:`primaryKey`,value:[`device_id`]},{table:`device_pairing_paired`,kind:`indexes`,value:2},{table:`device_pairing_paired`,kind:`checks`,value:0},{table:`device_pairing_pending`,kind:`table`,value:null},{table:`device_pairing_pending`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pairing_pending`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pairing_pending`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_pairing_pending`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`device_pairing_pending`,kind:`column`,value:{name:`platform`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_pairing_pending`,kind:`column`,value:{name:`device_family`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_pairing_pending`,kind:`column`,value:{name:`client_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_pairing_pending`,kind:`column`,value:{name:`client_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`device_pairing_pending`,kind:`column`,value:{name:`browser_origin`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_pairing_pending`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`device_pairing_pending`,kind:`column`,value:{name:`roles_json`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`device_pairing_pending`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`device_pairing_pending`,kind:`column`,value:{name:`remote_ip`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`device_pairing_pending`,kind:`column`,value:{name:`silent`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`device_pairing_pending`,kind:`column`,value:{name:`is_repair`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`device_pairing_pending`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`device_pairing_pending`,kind:`column`,value:{name:`refreshed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`device_pairing_pending`,kind:`primaryKey`,value:[`request_id`]},{table:`device_pairing_pending`,kind:`indexes`,value:2},{table:`device_pairing_pending`,kind:`checks`,value:0},{table:`diagnostic_events`,kind:`table`,value:null},{table:`diagnostic_events`,kind:`column`,value:{name:`scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`diagnostic_events`,kind:`column`,value:{name:`event_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`diagnostic_events`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`diagnostic_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`diagnostic_events`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:5}},{table:`diagnostic_events`,kind:`primaryKey`,value:[`scope`,`event_key`]},{table:`diagnostic_events`,kind:`indexes`,value:2},{table:`diagnostic_events`,kind:`checks`,value:0},{table:`durable_background_processes`,kind:`table`,value:null},{table:`durable_background_processes`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`durable_background_processes`,kind:`column`,value:{name:`record_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`durable_background_processes`,kind:`primaryKey`,value:[`id`]},{table:`durable_background_processes`,kind:`indexes`,value:1},{table:`durable_background_processes`,kind:`checks`,value:0},{table:`exec_approvals_config`,kind:`table`,value:null},{table:`exec_approvals_config`,kind:`column`,value:{name:`config_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`exec_approvals_config`,kind:`column`,value:{name:`raw_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`exec_approvals_config`,kind:`column`,value:{name:`socket_path`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`exec_approvals_config`,kind:`column`,value:{name:`has_socket_token`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`exec_approvals_config`,kind:`column`,value:{name:`default_security`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`exec_approvals_config`,kind:`column`,value:{name:`default_ask`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`exec_approvals_config`,kind:`column`,value:{name:`default_ask_fallback`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`exec_approvals_config`,kind:`column`,value:{name:`auto_allow_skills`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`exec_approvals_config`,kind:`column`,value:{name:`agent_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`exec_approvals_config`,kind:`column`,value:{name:`allowlist_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`exec_approvals_config`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`exec_approvals_config`,kind:`primaryKey`,value:[`config_key`]},{table:`exec_approvals_config`,kind:`indexes`,value:1},{table:`exec_approvals_config`,kind:`checks`,value:0},{table:`execution_decision_facts`,kind:`table`,value:null},{table:`execution_decision_facts`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`execution_decision_facts`,kind:`column`,value:{name:`receipt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`execution_decision_facts`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`execution_decision_facts`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`execution_decision_facts`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`execution_decision_facts`,kind:`column`,value:{name:`action_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`execution_decision_facts`,kind:`column`,value:{name:`action_family`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`execution_decision_facts`,kind:`column`,value:{name:`decision_outcome`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`execution_decision_facts`,kind:`column`,value:{name:`coverage_state`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`execution_decision_facts`,kind:`column`,value:{name:`reason_code`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`execution_decision_facts`,kind:`column`,value:{name:`owner`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`execution_decision_facts`,kind:`column`,value:{name:`source_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`execution_decision_facts`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`execution_decision_facts`,kind:`column`,value:{name:`receipt_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`execution_decision_facts`,kind:`column`,value:{name:`receipt_json`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`execution_decision_facts`,kind:`primaryKey`,value:[`receipt_id`]},{table:`execution_decision_facts`,kind:`unique`,value:[`occurred_at`,`receipt_id`]},{table:`execution_decision_facts`,kind:`indexes`,value:5},{table:`execution_decision_facts`,kind:`checks`,value:14},{table:`execution_identity_contexts`,kind:`table`,value:null},{table:`execution_identity_contexts`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`coverage_state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`context_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`context_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`execution_identity_contexts`,kind:`primaryKey`,value:[`context_id`]},{table:`execution_identity_contexts`,kind:`unique`,value:[`execution_id`]},{table:`execution_identity_contexts`,kind:`unique`,value:[`created_at`,`context_id`]},{table:`execution_identity_contexts`,kind:`indexes`,value:4},{table:`execution_identity_contexts`,kind:`checks`,value:7},{table:`execution_owner_lifecycle_bindings`,kind:`table`,value:null},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`owner_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`owner_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`execution_owner_lifecycle_bindings`,kind:`primaryKey`,value:[`owner_kind`,`owner_id`]},{table:`execution_owner_lifecycle_bindings`,kind:`indexes`,value:1},{table:`execution_owner_lifecycle_bindings`,kind:`checks`,value:0},{table:`flow_runs`,kind:`table`,value:null},{table:`flow_runs`,kind:`column`,value:{name:`flow_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`flow_runs`,kind:`column`,value:{name:`shape`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`flow_runs`,kind:`column`,value:{name:`sync_mode`,type:`text`,nullable:!1,identity:!1,default:`'managed'`,position:3}},{table:`flow_runs`,kind:`column`,value:{name:`owner_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`flow_runs`,kind:`column`,value:{name:`requester_origin_json`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`flow_runs`,kind:`column`,value:{name:`controller_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`flow_runs`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`flow_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`flow_runs`,kind:`column`,value:{name:`notify_policy`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`flow_runs`,kind:`column`,value:{name:`goal`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`flow_runs`,kind:`column`,value:{name:`current_step`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`flow_runs`,kind:`column`,value:{name:`blocked_task_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`flow_runs`,kind:`column`,value:{name:`blocked_summary`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`flow_runs`,kind:`column`,value:{name:`state_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`flow_runs`,kind:`column`,value:{name:`wait_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`flow_runs`,kind:`column`,value:{name:`cancel_requested_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`flow_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`flow_runs`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`flow_runs`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`flow_runs`,kind:`primaryKey`,value:[`flow_id`]},{table:`flow_runs`,kind:`indexes`,value:4},{table:`flow_runs`,kind:`checks`,value:0},{table:`gateway_boot_lifecycle`,kind:`table`,value:null},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`boot_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`started_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`outcome`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`startup_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`gateway_boot_lifecycle`,kind:`primaryKey`,value:[`boot_id`]},{table:`gateway_boot_lifecycle`,kind:`indexes`,value:2},{table:`gateway_boot_lifecycle`,kind:`checks`,value:0},{table:`gateway_restart_handoff`,kind:`table`,value:null},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`handoff_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`intent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`process_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`restart_trace_started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`restart_trace_last_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`source`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`restart_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`supervisor_mode`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`gateway_restart_handoff`,kind:`primaryKey`,value:[`handoff_key`]},{table:`gateway_restart_handoff`,kind:`indexes`,value:2},{table:`gateway_restart_handoff`,kind:`checks`,value:0},{table:`gateway_restart_intent`,kind:`table`,value:null},{table:`gateway_restart_intent`,kind:`column`,value:{name:`intent_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`force`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`wait_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`gateway_restart_intent`,kind:`primaryKey`,value:[`intent_key`]},{table:`gateway_restart_intent`,kind:`indexes`,value:1},{table:`gateway_restart_intent`,kind:`checks`,value:0},{table:`gateway_restart_sentinel`,kind:`table`,value:null},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`sentinel_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`thread_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`delivery_channel`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`delivery_to`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`delivery_account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`message`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`continuation_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`doctor_hint`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`stats_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`gateway_restart_sentinel`,kind:`primaryKey`,value:[`sentinel_key`]},{table:`gateway_restart_sentinel`,kind:`indexes`,value:2},{table:`gateway_restart_sentinel`,kind:`checks`,value:0},{table:`github_personal_publication_requests`,kind:`table`,value:null},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`connection_generation`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`repository_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_source`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_account_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_login`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`body`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`last_effect`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`effect_state`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`push_repository`,type:`text`,nullable:!1,identity:!1,default:null,position:22}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`repository`,type:`text`,nullable:!1,identity:!1,default:null,position:23}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:24}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`base_branch`,type:`text`,nullable:!1,identity:!1,default:null,position:25}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`source_head_commit`,type:`text`,nullable:!1,identity:!1,default:null,position:26}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`source_index_tree`,type:`text`,nullable:!1,identity:!1,default:null,position:27}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`workspace_tree`,type:`text`,nullable:!1,identity:!1,default:null,position:28}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`pull_request_url`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`next_action`,type:`text`,nullable:!0,identity:!1,default:null,position:32}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:33}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:34}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`reported_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:35}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`draft`,type:`bigint`,nullable:!0,identity:!1,default:null,position:36}},{table:`github_personal_publication_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`github_personal_publication_requests`,kind:`unique`,value:[`owner_profile_id`,`session_id`,`idempotency_key`]},{table:`github_personal_publication_requests`,kind:`indexes`,value:4},{table:`github_personal_publication_requests`,kind:`checks`,value:37},{table:`github_publication_requests`,kind:`table`,value:null},{table:`github_publication_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_publication_requests`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`github_publication_requests`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`github_publication_requests`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`github_publication_requests`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`github_publication_requests`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`github_publication_requests`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`github_publication_requests`,kind:`column`,value:{name:`repository_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`github_publication_requests`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`github_publication_requests`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`github_publication_requests`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`github_publication_requests`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`github_publication_requests`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_source`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_account_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_login`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`github_publication_requests`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`github_publication_requests`,kind:`column`,value:{name:`body`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`github_publication_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:20}},{table:`github_publication_requests`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`github_publication_requests`,kind:`column`,value:{name:`repository`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`github_publication_requests`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:23}},{table:`github_publication_requests`,kind:`column`,value:{name:`base_branch`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`github_publication_requests`,kind:`column`,value:{name:`source_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`github_publication_requests`,kind:`column`,value:{name:`source_index_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`github_publication_requests`,kind:`column`,value:{name:`workspace_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`github_publication_requests`,kind:`column`,value:{name:`head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`github_publication_requests`,kind:`column`,value:{name:`pull_request_url`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`github_publication_requests`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`github_publication_requests`,kind:`column`,value:{name:`next_action`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`github_publication_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:32}},{table:`github_publication_requests`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:33}},{table:`github_publication_requests`,kind:`column`,value:{name:`reported_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:34}},{table:`github_publication_requests`,kind:`column`,value:{name:`draft`,type:`bigint`,nullable:!0,identity:!1,default:null,position:35}},{table:`github_publication_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`github_publication_requests`,kind:`unique`,value:[`session_id`,`idempotency_key`]},{table:`github_publication_requests`,kind:`indexes`,value:3},{table:`github_publication_requests`,kind:`checks`,value:9},{table:`github_publication_session_lifecycles`,kind:`table`,value:null},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`publication_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`requester_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`github_publication_session_lifecycles`,kind:`primaryKey`,value:[`publication_kind`,`request_id`]},{table:`github_publication_session_lifecycles`,kind:`indexes`,value:1},{table:`github_publication_session_lifecycles`,kind:`checks`,value:1},{table:`github_repository_publication_requests`,kind:`table`,value:null},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`connection_generation`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`session_lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`requester_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`workspace_id`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`checkpoint_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`checkpoint_digest`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:18}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_source`,type:`text`,nullable:!1,identity:!1,default:null,position:19}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_account_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:21}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_login`,type:`text`,nullable:!1,identity:!1,default:null,position:22}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`body`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:25}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`last_effect`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`effect_state`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`push_repository`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`repository`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:32}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`base_branch`,type:`text`,nullable:!0,identity:!1,default:null,position:33}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`source_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:34}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`source_index_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:35}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`workspace_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:36}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`previous_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:37}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`pushed_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:38}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:39}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`pull_request_url`,type:`text`,nullable:!0,identity:!1,default:null,position:40}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:41}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`next_action`,type:`text`,nullable:!0,identity:!1,default:null,position:42}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:43}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:44}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`reported_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:45}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`draft`,type:`bigint`,nullable:!0,identity:!1,default:null,position:46}},{table:`github_repository_publication_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`github_repository_publication_requests`,kind:`indexes`,value:3},{table:`github_repository_publication_requests`,kind:`checks`,value:7},{table:`local_workspace_manifest_nodes`,kind:`table`,value:null},{table:`local_workspace_manifest_nodes`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_manifest_nodes`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_manifest_nodes`,kind:`column`,value:{name:`node_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_manifest_nodes`,kind:`primaryKey`,value:[`worktree_id`,`path`]},{table:`local_workspace_manifest_nodes`,kind:`foreignKey`,value:{columns:[`worktree_id`],target:`local_workspace_projections`,targetColumns:[`worktree_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`local_workspace_manifest_nodes`,kind:`indexes`,value:1},{table:`local_workspace_manifest_nodes`,kind:`checks`,value:0},{table:`local_workspace_projections`,kind:`table`,value:null},{table:`local_workspace_projections`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_projections`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_projections`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_projections`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`local_workspace_projections`,kind:`column`,value:{name:`lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`local_workspace_projections`,kind:`column`,value:{name:`projection_path`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`local_workspace_projections`,kind:`column`,value:{name:`base_commit`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`local_workspace_projections`,kind:`column`,value:{name:`source_paths_json`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`local_workspace_projections`,kind:`column`,value:{name:`baseline_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`local_workspace_projections`,kind:`column`,value:{name:`baseline_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`local_workspace_projections`,kind:`column`,value:{name:`pending_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`local_workspace_projections`,kind:`column`,value:{name:`pending_target`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`local_workspace_projections`,kind:`column`,value:{name:`paused_runtimes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`local_workspace_projections`,kind:`column`,value:{name:`journal_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`local_workspace_projections`,kind:`column`,value:{name:`journal_pack`,type:`bytea`,nullable:!0,identity:!1,default:null,position:15}},{table:`local_workspace_projections`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:16}},{table:`local_workspace_projections`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`local_workspace_projections`,kind:`column`,value:{name:`checkpoint_json`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`local_workspace_projections`,kind:`column`,value:{name:`tree_root_digest`,type:`bytea`,nullable:!0,identity:!1,default:null,position:19}},{table:`local_workspace_projections`,kind:`column`,value:{name:`source_paths_digest`,type:`bytea`,nullable:!0,identity:!1,default:null,position:20}},{table:`local_workspace_projections`,kind:`column`,value:{name:`canonical_fingerprints`,type:`bytea`,nullable:!0,identity:!1,default:null,position:21}},{table:`local_workspace_projections`,kind:`column`,value:{name:`projection_fingerprints`,type:`bytea`,nullable:!0,identity:!1,default:null,position:22}},{table:`local_workspace_projections`,kind:`primaryKey`,value:[`worktree_id`]},{table:`local_workspace_projections`,kind:`unique`,value:[`projection_path`]},{table:`local_workspace_projections`,kind:`indexes`,value:2},{table:`local_workspace_projections`,kind:`checks`,value:5},{table:`local_workspace_source_path_sets`,kind:`table`,value:null},{table:`local_workspace_source_path_sets`,kind:`column`,value:{name:`path_digest`,type:`bytea`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_source_path_sets`,kind:`column`,value:{name:`paths_zstd`,type:`bytea`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_source_path_sets`,kind:`column`,value:{name:`sweep_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_source_path_sets`,kind:`primaryKey`,value:[`path_digest`]},{table:`local_workspace_source_path_sets`,kind:`indexes`,value:1},{table:`local_workspace_source_path_sets`,kind:`checks`,value:1},{table:`local_workspace_tree_packs`,kind:`table`,value:null},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`tree_digest`,type:`bytea`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`records_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`children_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`sweep_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`local_workspace_tree_packs`,kind:`primaryKey`,value:[`tree_digest`]},{table:`local_workspace_tree_packs`,kind:`indexes`,value:1},{table:`local_workspace_tree_packs`,kind:`checks`,value:1},{table:`macos_port_guardian_records`,kind:`table`,value:null},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`port`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`command`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`mode`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`timestamp`,type:`double precision`,nullable:!1,identity:!1,default:null,position:5}},{table:`macos_port_guardian_records`,kind:`primaryKey`,value:[`pid`]},{table:`macos_port_guardian_records`,kind:`indexes`,value:2},{table:`macos_port_guardian_records`,kind:`checks`,value:0},{table:`managed_outgoing_image_records`,kind:`table`,value:null},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`attachment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`message_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`created_at`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`updated_at`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`retention_class`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`alt`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_media_root`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_media_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_media_subdir`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_content_type`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_width`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_height`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_size_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_filename`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`record_json`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`cleanup_pending`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:18}},{table:`managed_outgoing_image_records`,kind:`primaryKey`,value:[`attachment_id`]},{table:`managed_outgoing_image_records`,kind:`indexes`,value:5},{table:`managed_outgoing_image_records`,kind:`checks`,value:1},{table:`mcp_oauth_pending_authorizations`,kind:`table`,value:null},{table:`mcp_oauth_pending_authorizations`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`mcp_oauth_pending_authorizations`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`mcp_oauth_pending_authorizations`,kind:`column`,value:{name:`create_time`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`mcp_oauth_pending_authorizations`,kind:`primaryKey`,value:[`state`]},{table:`mcp_oauth_pending_authorizations`,kind:`indexes`,value:1},{table:`mcp_oauth_pending_authorizations`,kind:`checks`,value:0},{table:`mcp_oauth_stores`,kind:`table`,value:null},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`format_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`store_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`mcp_oauth_stores`,kind:`primaryKey`,value:[`store_key`]},{table:`mcp_oauth_stores`,kind:`indexes`,value:1},{table:`mcp_oauth_stores`,kind:`checks`,value:1},{table:`meeting_transcript_sessions`,kind:`table`,value:null},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`started_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:1}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`selector`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`export_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`session_slug`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`provider_id`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_json`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_guild_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_channel_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_meeting_url`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_thread_ts`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_file_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`stopped_at`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`metadata_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`export_manifest_json`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:19}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`export_pending_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:20}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`next_utterance_seq`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:21}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:22}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:23}},{table:`meeting_transcript_sessions`,kind:`primaryKey`,value:[`session_id`,`started_at`]},{table:`meeting_transcript_sessions`,kind:`unique`,value:[`selector`]},{table:`meeting_transcript_sessions`,kind:`indexes`,value:10},{table:`meeting_transcript_sessions`,kind:`checks`,value:3},{table:`meeting_transcript_summaries`,kind:`table`,value:null},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`session_started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`generated_at`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`summary_json`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`overview`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`markdown`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`utterance_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`meeting_transcript_summaries`,kind:`primaryKey`,value:[`session_id`,`session_started_at`]},{table:`meeting_transcript_summaries`,kind:`foreignKey`,value:{columns:[`session_id`,`session_started_at`],target:`meeting_transcript_sessions`,targetColumns:[`session_id`,`started_at`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`meeting_transcript_summaries`,kind:`indexes`,value:1},{table:`meeting_transcript_summaries`,kind:`checks`,value:2},{table:`meeting_transcript_utterances`,kind:`table`,value:null},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`session_started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`utterance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`started_at`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`ended_at`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`speaker_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`speaker_label`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`text`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`final`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`meeting_transcript_utterances`,kind:`primaryKey`,value:[`session_id`,`session_started_at`,`sequence`]},{table:`meeting_transcript_utterances`,kind:`foreignKey`,value:{columns:[`session_id`,`session_started_at`],target:`meeting_transcript_sessions`,targetColumns:[`session_id`,`started_at`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`meeting_transcript_utterances`,kind:`indexes`,value:2},{table:`meeting_transcript_utterances`,kind:`checks`,value:2},{table:`migration_runs`,kind:`table`,value:null},{table:`migration_runs`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`migration_runs`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`migration_runs`,kind:`column`,value:{name:`finished_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`migration_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`migration_runs`,kind:`column`,value:{name:`report_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`migration_runs`,kind:`primaryKey`,value:[`id`]},{table:`migration_runs`,kind:`indexes`,value:2},{table:`migration_runs`,kind:`checks`,value:0},{table:`migration_sources`,kind:`table`,value:null},{table:`migration_sources`,kind:`column`,value:{name:`source_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`migration_sources`,kind:`column`,value:{name:`migration_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`migration_sources`,kind:`column`,value:{name:`source_path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`migration_sources`,kind:`column`,value:{name:`target_table`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`migration_sources`,kind:`column`,value:{name:`source_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`migration_sources`,kind:`column`,value:{name:`source_size_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`migration_sources`,kind:`column`,value:{name:`source_record_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`migration_sources`,kind:`column`,value:{name:`last_run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`migration_sources`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`migration_sources`,kind:`column`,value:{name:`imported_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`migration_sources`,kind:`column`,value:{name:`removed_source`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:11}},{table:`migration_sources`,kind:`column`,value:{name:`report_json`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`migration_sources`,kind:`primaryKey`,value:[`source_key`]},{table:`migration_sources`,kind:`foreignKey`,value:{columns:[`last_run_id`],target:`migration_runs`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`migration_sources`,kind:`indexes`,value:3},{table:`migration_sources`,kind:`checks`,value:0},{table:`native_hook_relay_bridges`,kind:`table`,value:null},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`relay_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`hostname`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`port`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`native_hook_relay_bridges`,kind:`primaryKey`,value:[`relay_id`]},{table:`native_hook_relay_bridges`,kind:`indexes`,value:2},{table:`native_hook_relay_bridges`,kind:`checks`,value:0},{table:`node_worker_launch_boots`,kind:`table`,value:null},{table:`node_worker_launch_boots`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_boots`,kind:`column`,value:{name:`boot_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`node_worker_launch_boots`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_boots`,kind:`foreignKey`,value:{columns:[`launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_launch_boots`,kind:`indexes`,value:1},{table:`node_worker_launch_boots`,kind:`checks`,value:1},{table:`node_worker_launch_cleanup`,kind:`table`,value:null},{table:`node_worker_launch_cleanup`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_cleanup`,kind:`column`,value:{name:`cleanup_mode`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_launch_cleanup`,kind:`column`,value:{name:`lineage_settled`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`node_worker_launch_cleanup`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_cleanup`,kind:`foreignKey`,value:{columns:[`launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_launch_cleanup`,kind:`indexes`,value:1},{table:`node_worker_launch_cleanup`,kind:`checks`,value:2},{table:`node_worker_launch_containers`,kind:`table`,value:null},{table:`node_worker_launch_containers`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_containers`,kind:`column`,value:{name:`container_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`node_worker_launch_containers`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_containers`,kind:`indexes`,value:1},{table:`node_worker_launch_containers`,kind:`checks`,value:0},{table:`node_worker_launch_process_scopes`,kind:`table`,value:null},{table:`node_worker_launch_process_scopes`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_process_scopes`,kind:`column`,value:{name:`scope_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_launch_process_scopes`,kind:`column`,value:{name:`descendants_reaped`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`node_worker_launch_process_scopes`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_process_scopes`,kind:`foreignKey`,value:{columns:[`launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_launch_process_scopes`,kind:`indexes`,value:1},{table:`node_worker_launch_process_scopes`,kind:`checks`,value:2},{table:`node_worker_launches`,kind:`table`,value:null},{table:`node_worker_launches`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launches`,kind:`column`,value:{name:`plan_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_launches`,kind:`column`,value:{name:`gateway_namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`node_worker_launches`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`node_worker_launches`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`node_worker_launches`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`node_worker_launches`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`node_worker_launches`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`node_worker_launches`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`node_worker_launches`,kind:`column`,value:{name:`supervisor_pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`node_worker_launches`,kind:`column`,value:{name:`supervisor_start_time`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`node_worker_launches`,kind:`column`,value:{name:`worker_pid`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`node_worker_launches`,kind:`column`,value:{name:`worker_start_time`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`node_worker_launches`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`node_worker_launches`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`node_worker_launches`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`node_worker_launches`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`node_worker_launches`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`node_worker_launches`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launches`,kind:`indexes`,value:2},{table:`node_worker_launches`,kind:`checks`,value:20},{table:`node_worker_prepared_workspaces`,kind:`table`,value:null},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`preparation_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`cache_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`gateway_namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`workspace_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`home_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`source_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`prepared_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`bound_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`retired_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`node_worker_prepared_workspaces`,kind:`primaryKey`,value:[`preparation_key`]},{table:`node_worker_prepared_workspaces`,kind:`unique`,value:[`workspace_dir`]},{table:`node_worker_prepared_workspaces`,kind:`indexes`,value:2},{table:`node_worker_prepared_workspaces`,kind:`checks`,value:15},{table:`node_worker_turns`,kind:`table`,value:null},{table:`node_worker_turns`,kind:`column`,value:{name:`turn_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_turns`,kind:`column`,value:{name:`owner_launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_turns`,kind:`column`,value:{name:`plan_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`node_worker_turns`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`node_worker_turns`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`node_worker_turns`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`node_worker_turns`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`node_worker_turns`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`node_worker_turns`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`node_worker_turns`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`node_worker_turns`,kind:`primaryKey`,value:[`turn_id`]},{table:`node_worker_turns`,kind:`foreignKey`,value:{columns:[`owner_launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_turns`,kind:`indexes`,value:3},{table:`node_worker_turns`,kind:`checks`,value:10},{table:`official_external_plugin_catalog_snapshots`,kind:`table`,value:null},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`feed_url`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`body`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`status`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`etag`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`last_modified`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`checksum`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`saved_at`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_key_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_signature_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_threshold`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_verified_at`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`official_external_plugin_catalog_snapshots`,kind:`primaryKey`,value:[`feed_url`]},{table:`official_external_plugin_catalog_snapshots`,kind:`indexes`,value:2},{table:`official_external_plugin_catalog_snapshots`,kind:`checks`,value:0},{table:`operator_approval_execution_identities`,kind:`table`,value:null},{table:`operator_approval_execution_identities`,kind:`column`,value:{name:`approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approval_execution_identities`,kind:`column`,value:{name:`source_context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approval_execution_identities`,kind:`column`,value:{name:`source_execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`operator_approval_execution_identities`,kind:`primaryKey`,value:[`approval_id`]},{table:`operator_approval_execution_identities`,kind:`foreignKey`,value:{columns:[`approval_id`],target:`operator_approvals`,targetColumns:[`approval_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`operator_approval_execution_identities`,kind:`indexes`,value:1},{table:`operator_approval_execution_identities`,kind:`checks`,value:2},{table:`operator_approval_standing_grant_generations`,kind:`table`,value:null},{table:`operator_approval_standing_grant_generations`,kind:`column`,value:{name:`grant_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approval_standing_grant_generations`,kind:`column`,value:{name:`job_definition_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approval_standing_grant_generations`,kind:`primaryKey`,value:[`grant_id`]},{table:`operator_approval_standing_grant_generations`,kind:`foreignKey`,value:{columns:[`grant_id`],target:`operator_approval_standing_grants`,targetColumns:[`grant_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`operator_approval_standing_grant_generations`,kind:`indexes`,value:1},{table:`operator_approval_standing_grant_generations`,kind:`checks`,value:1},{table:`operator_approval_standing_grants`,kind:`table`,value:null},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`grant_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`minted_by_approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`cron_job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`job_config_revision`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`operation_binding`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`revoked_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`revoked_by`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`use_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:12}},{table:`operator_approval_standing_grants`,kind:`primaryKey`,value:[`grant_id`]},{table:`operator_approval_standing_grants`,kind:`foreignKey`,value:{columns:[`minted_by_approval_id`],target:`operator_approvals`,targetColumns:[`approval_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`operator_approval_standing_grants`,kind:`indexes`,value:2},{table:`operator_approval_standing_grants`,kind:`checks`,value:6},{table:`operator_approvals`,kind:`table`,value:null},{table:`operator_approvals`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approvals`,kind:`column`,value:{name:`approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approvals`,kind:`column`,value:{name:`resolution_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`operator_approvals`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`operator_approvals`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`operator_approvals`,kind:`column`,value:{name:`presentation_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`operator_approvals`,kind:`column`,value:{name:`requested_by_device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`operator_approvals`,kind:`column`,value:{name:`requested_by_client_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`operator_approvals`,kind:`column`,value:{name:`requested_by_device_token_auth`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:9}},{table:`operator_approvals`,kind:`column`,value:{name:`reviewer_device_ids_json`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`operator_approvals`,kind:`column`,value:{name:`source_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`operator_approvals`,kind:`column`,value:{name:`source_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`operator_approvals`,kind:`column`,value:{name:`source_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`operator_approvals`,kind:`column`,value:{name:`source_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`operator_approvals`,kind:`column`,value:{name:`source_tool_call_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`operator_approvals`,kind:`column`,value:{name:`source_tool_name`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`operator_approvals`,kind:`column`,value:{name:`audience_session_keys_json`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`operator_approvals`,kind:`column`,value:{name:`runtime_epoch`,type:`text`,nullable:!1,identity:!1,default:null,position:18}},{table:`operator_approvals`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`operator_approvals`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`operator_approvals`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:21}},{table:`operator_approvals`,kind:`column`,value:{name:`decision`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`operator_approvals`,kind:`column`,value:{name:`terminal_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`operator_approvals`,kind:`column`,value:{name:`resolved_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:24}},{table:`operator_approvals`,kind:`column`,value:{name:`resolver_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`operator_approvals`,kind:`column`,value:{name:`resolver_id`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`operator_approvals`,kind:`column`,value:{name:`consumed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:27}},{table:`operator_approvals`,kind:`column`,value:{name:`consumed_by`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`operator_approvals`,kind:`primaryKey`,value:[`approval_id`]},{table:`operator_approvals`,kind:`indexes`,value:8},{table:`operator_approvals`,kind:`checks`,value:16},{table:`outbound_media_provenance`,kind:`table`,value:null},{table:`outbound_media_provenance`,kind:`column`,value:{name:`realpath`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`outbound_media_provenance`,kind:`primaryKey`,value:[`realpath`]},{table:`outbound_media_provenance`,kind:`indexes`,value:1},{table:`outbound_media_provenance`,kind:`checks`,value:0},{table:`outbound_message_execution_bindings`,kind:`table`,value:null},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`outbound_message_execution_bindings`,kind:`primaryKey`,value:[`event_id`]},{table:`outbound_message_execution_bindings`,kind:`foreignKey`,value:{columns:[`event_id`],target:`audit_events`,targetColumns:[`event_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`outbound_message_execution_bindings`,kind:`indexes`,value:2},{table:`outbound_message_execution_bindings`,kind:`checks`,value:3},{table:`outbound_message_progress`,kind:`table`,value:null},{table:`outbound_message_progress`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`outbound_message_progress`,kind:`column`,value:{name:`progress_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`outbound_message_progress`,kind:`column`,value:{name:`source_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`outbound_message_progress`,kind:`column`,value:{name:`source_sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`outbound_message_progress`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`outbound_message_progress`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`outbound_message_progress`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`outbound_message_progress`,kind:`column`,value:{name:`outcome`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`outbound_message_progress`,kind:`column`,value:{name:`actor_type`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`outbound_message_progress`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`outbound_message_progress`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`outbound_message_progress`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`outbound_message_progress`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`outbound_message_progress`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`outbound_message_progress`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`outbound_message_progress`,kind:`column`,value:{name:`conversation_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:16}},{table:`outbound_message_progress`,kind:`column`,value:{name:`duration_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`outbound_message_progress`,kind:`column`,value:{name:`account_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`outbound_message_progress`,kind:`column`,value:{name:`conversation_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`outbound_message_progress`,kind:`column`,value:{name:`target_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`outbound_message_progress`,kind:`primaryKey`,value:[`sequence`]},{table:`outbound_message_progress`,kind:`unique`,value:[`progress_id`]},{table:`outbound_message_progress`,kind:`unique`,value:[`source_id`]},{table:`outbound_message_progress`,kind:`unique`,value:[`occurred_at`,`progress_id`]},{table:`outbound_message_progress`,kind:`indexes`,value:6},{table:`outbound_message_progress`,kind:`checks`,value:14},{table:`plugin_binding_approvals`,kind:`table`,value:null},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`plugin_root`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`plugin_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`plugin_name`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`approved_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`plugin_binding_approvals`,kind:`primaryKey`,value:[`plugin_root`,`channel`,`account_id`]},{table:`plugin_binding_approvals`,kind:`indexes`,value:2},{table:`plugin_binding_approvals`,kind:`checks`,value:0},{table:`plugin_blob_entries`,kind:`table`,value:null},{table:`plugin_blob_entries`,kind:`column`,value:{name:`plugin_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`entry_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:5}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`plugin_blob_entries`,kind:`primaryKey`,value:[`plugin_id`,`namespace`,`entry_key`]},{table:`plugin_blob_entries`,kind:`indexes`,value:3},{table:`plugin_blob_entries`,kind:`checks`,value:0},{table:`plugin_state_entries`,kind:`table`,value:null},{table:`plugin_state_entries`,kind:`column`,value:{name:`plugin_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`plugin_state_entries`,kind:`column`,value:{name:`namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`plugin_state_entries`,kind:`column`,value:{name:`entry_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`plugin_state_entries`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`plugin_state_entries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`plugin_state_entries`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`plugin_state_entries`,kind:`primaryKey`,value:[`plugin_id`,`namespace`,`entry_key`]},{table:`plugin_state_entries`,kind:`indexes`,value:3},{table:`plugin_state_entries`,kind:`checks`,value:0},{table:`projects`,kind:`table`,value:null},{table:`projects`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`projects`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`projects`,kind:`column`,value:{name:`repo_root`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`projects`,kind:`column`,value:{name:`origin_url`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`projects`,kind:`column`,value:{name:`source`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`projects`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`projects`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`projects`,kind:`primaryKey`,value:[`id`]},{table:`projects`,kind:`indexes`,value:1},{table:`projects`,kind:`checks`,value:1},{table:`sandbox_persistent_execs`,kind:`table`,value:null},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`owner_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`source_identity`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`attempt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`owner_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`backend_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`backend_target_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`workspace_binding_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`container_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`container_name`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`container_started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`phase`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`receipt_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`sandbox_persistent_execs`,kind:`primaryKey`,value:[`owner_key`]},{table:`sandbox_persistent_execs`,kind:`unique`,value:[`attempt_id`]},{table:`sandbox_persistent_execs`,kind:`indexes`,value:5},{table:`sandbox_persistent_execs`,kind:`checks`,value:4},{table:`sandbox_registry_entries`,kind:`table`,value:null},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`registry_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`container_name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`backend_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`runtime_label`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`image`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`config_label_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`config_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`cdp_port`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`no_vnc_port`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`entry_json`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`sandbox_registry_entries`,kind:`primaryKey`,value:[`registry_kind`,`container_name`]},{table:`sandbox_registry_entries`,kind:`indexes`,value:4},{table:`sandbox_registry_entries`,kind:`checks`,value:0},{table:`schema_meta`,kind:`table`,value:null},{table:`schema_meta`,kind:`column`,value:{name:`meta_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`schema_meta`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`schema_meta`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`schema_meta`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`schema_meta`,kind:`column`,value:{name:`app_version`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`schema_meta`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`schema_meta`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`schema_meta`,kind:`primaryKey`,value:[`meta_key`]},{table:`schema_meta`,kind:`indexes`,value:1},{table:`schema_meta`,kind:`checks`,value:0},{table:`secret_store_entries`,kind:`table`,value:null},{table:`secret_store_entries`,kind:`column`,value:{name:`scope_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`secret_store_entries`,kind:`column`,value:{name:`scope_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`secret_store_entries`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`secret_store_entries`,kind:`column`,value:{name:`value`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`secret_store_entries`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`secret_store_entries`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`secret_store_entries`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`secret_store_entries`,kind:`column`,value:{name:`updated_by`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`secret_store_entries`,kind:`column`,value:{name:`deleted_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`secret_store_entries`,kind:`column`,value:{name:`allowed_hosts`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`secret_store_entries`,kind:`primaryKey`,value:[`scope_kind`,`scope_id`,`name`]},{table:`secret_store_entries`,kind:`indexes`,value:2},{table:`secret_store_entries`,kind:`checks`,value:5},{table:`session_groups`,kind:`table`,value:null},{table:`session_groups`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_groups`,kind:`column`,value:{name:`position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_groups`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_groups`,kind:`column`,value:{name:`cwd`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_groups`,kind:`column`,value:{name:`worktree`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_groups`,kind:`primaryKey`,value:[`name`]},{table:`session_groups`,kind:`indexes`,value:1},{table:`session_groups`,kind:`checks`,value:0},{table:`session_repository_workspaces`,kind:`table`,value:null},{table:`session_repository_workspaces`,kind:`column`,value:{name:`workspace_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`url`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`requested_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`run_setup_script`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:6}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`base_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`base_manifest_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`checkpoint_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`manifest_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`disk_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`session_repository_workspaces`,kind:`primaryKey`,value:[`workspace_id`]},{table:`session_repository_workspaces`,kind:`unique`,value:[`agent_id`,`session_key`]},{table:`session_repository_workspaces`,kind:`indexes`,value:2},{table:`session_repository_workspaces`,kind:`checks`,value:11},{table:`session_state_events`,kind:`table`,value:null},{table:`session_state_events`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`session_state_events`,kind:`column`,value:{name:`dedupe_key`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`session_state_events`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_state_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_state_events`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_state_events`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_state_events`,kind:`column`,value:{name:`actor_type`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_state_events`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_state_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`session_state_events`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`session_state_events`,kind:`column`,value:{name:`summary`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`session_state_events`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`session_state_events`,kind:`primaryKey`,value:[`sequence`]},{table:`session_state_events`,kind:`unique`,value:[`dedupe_key`]},{table:`session_state_events`,kind:`indexes`,value:4},{table:`session_state_events`,kind:`checks`,value:0},{table:`session_state_heads`,kind:`table`,value:null},{table:`session_state_heads`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_state_heads`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_state_heads`,kind:`column`,value:{name:`last_sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_state_heads`,kind:`column`,value:{name:`pruned_max_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:4}},{table:`session_state_heads`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_state_heads`,kind:`primaryKey`,value:[`session_key`,`agent_id`]},{table:`session_state_heads`,kind:`indexes`,value:1},{table:`session_state_heads`,kind:`checks`,value:0},{table:`session_upstream_links`,kind:`table`,value:null},{table:`session_upstream_links`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_upstream_links`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_upstream_links`,kind:`column`,value:{name:`catalog_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_upstream_links`,kind:`column`,value:{name:`host_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_upstream_links`,kind:`column`,value:{name:`thread_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_upstream_links`,kind:`column`,value:{name:`upstream_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_upstream_links`,kind:`column`,value:{name:`upstream_ref_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`session_upstream_links`,kind:`column`,value:{name:`last_marker_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_upstream_links`,kind:`column`,value:{name:`last_scanned_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`session_upstream_links`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`session_upstream_links`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`session_upstream_links`,kind:`primaryKey`,value:[`session_key`,`agent_id`]},{table:`session_upstream_links`,kind:`indexes`,value:2},{table:`session_upstream_links`,kind:`checks`,value:0},{table:`session_watch_cursors`,kind:`table`,value:null},{table:`session_watch_cursors`,kind:`column`,value:{name:`watcher_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_watch_cursors`,kind:`column`,value:{name:`watcher_store_path`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`session_watch_cursors`,kind:`column`,value:{name:`target_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_watch_cursors`,kind:`column`,value:{name:`last_seen_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:4}},{table:`session_watch_cursors`,kind:`column`,value:{name:`notified_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:5}},{table:`session_watch_cursors`,kind:`column`,value:{name:`material_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:6}},{table:`session_watch_cursors`,kind:`column`,value:{name:`provenance`,type:`text`,nullable:!1,identity:!1,default:`'explicit'`,position:7}},{table:`session_watch_cursors`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_watch_cursors`,kind:`primaryKey`,value:[`watcher_session_key`,`target_session_key`]},{table:`session_watch_cursors`,kind:`indexes`,value:2},{table:`session_watch_cursors`,kind:`checks`,value:1},{table:`skill_library_entries`,kind:`table`,value:null},{table:`skill_library_entries`,kind:`column`,value:{name:`skill_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_entries`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`skill_library_entries`,kind:`column`,value:{name:`author_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_entries`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_entries`,kind:`column`,value:{name:`current_revision`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_entries`,kind:`column`,value:{name:`shared`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_library_entries`,kind:`column`,value:{name:`enabled`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_library_entries`,kind:`column`,value:{name:`removed`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`skill_library_entries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`skill_library_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`skill_library_entries`,kind:`primaryKey`,value:[`skill_id`]},{table:`skill_library_entries`,kind:`indexes`,value:1},{table:`skill_library_entries`,kind:`checks`,value:0},{table:`skill_library_events`,kind:`table`,value:null},{table:`skill_library_events`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_events`,kind:`column`,value:{name:`skill_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_library_events`,kind:`column`,value:{name:`revision`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_events`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_events`,kind:`column`,value:{name:`actor_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_library_events`,kind:`primaryKey`,value:[`event_id`]},{table:`skill_library_events`,kind:`indexes`,value:1},{table:`skill_library_events`,kind:`checks`,value:0},{table:`skill_library_revisions`,kind:`table`,value:null},{table:`skill_library_revisions`,kind:`column`,value:{name:`skill_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_revisions`,kind:`column`,value:{name:`revision`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_library_revisions`,kind:`column`,value:{name:`description`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_revisions`,kind:`column`,value:{name:`files_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_revisions`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_revisions`,kind:`primaryKey`,value:[`skill_id`,`revision`]},{table:`skill_library_revisions`,kind:`indexes`,value:1},{table:`skill_library_revisions`,kind:`checks`,value:0},{table:`skill_library_uploads`,kind:`table`,value:null},{table:`skill_library_uploads`,kind:`column`,value:{name:`upload_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_uploads`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_library_uploads`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_uploads`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_uploads`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_uploads`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_library_uploads`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_library_uploads`,kind:`column`,value:{name:`published_skill_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`skill_library_uploads`,kind:`primaryKey`,value:[`upload_id`]},{table:`skill_library_uploads`,kind:`indexes`,value:1},{table:`skill_library_uploads`,kind:`checks`,value:0},{table:`skill_upload_chunks`,kind:`table`,value:null},{table:`skill_upload_chunks`,kind:`column`,value:{name:`upload_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_upload_chunks`,kind:`column`,value:{name:`byte_offset`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_upload_chunks`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_upload_chunks`,kind:`column`,value:{name:`chunk_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_upload_chunks`,kind:`primaryKey`,value:[`upload_id`,`byte_offset`]},{table:`skill_upload_chunks`,kind:`foreignKey`,value:{columns:[`upload_id`],target:`skill_uploads`,targetColumns:[`upload_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`skill_upload_chunks`,kind:`indexes`,value:1},{table:`skill_upload_chunks`,kind:`checks`,value:3},{table:`skill_uploads`,kind:`table`,value:null},{table:`skill_uploads`,kind:`column`,value:{name:`upload_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_uploads`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_uploads`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_uploads`,kind:`column`,value:{name:`force`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_uploads`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_uploads`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`skill_uploads`,kind:`column`,value:{name:`actual_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`skill_uploads`,kind:`column`,value:{name:`received_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`skill_uploads`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:9}},{table:`skill_uploads`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`skill_uploads`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`skill_uploads`,kind:`column`,value:{name:`committed`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`skill_uploads`,kind:`column`,value:{name:`committed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`skill_uploads`,kind:`column`,value:{name:`idempotency_key_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`skill_uploads`,kind:`primaryKey`,value:[`upload_id`]},{table:`skill_uploads`,kind:`unique`,value:[`idempotency_key_hash`]},{table:`skill_uploads`,kind:`indexes`,value:4},{table:`skill_uploads`,kind:`checks`,value:0},{table:`skill_usage`,kind:`table`,value:null},{table:`skill_usage`,kind:`column`,value:{name:`skill_file`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_usage`,kind:`column`,value:{name:`skill_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_usage`,kind:`column`,value:{name:`skill_name`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_usage`,kind:`column`,value:{name:`skill_source`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_usage`,kind:`column`,value:{name:`first_used_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_usage`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_usage`,kind:`column`,value:{name:`use_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_usage`,kind:`column`,value:{name:`last_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`skill_usage`,kind:`primaryKey`,value:[`skill_file`]},{table:`skill_usage`,kind:`indexes`,value:1},{table:`skill_usage`,kind:`checks`,value:0},{table:`skill_workshop_changes`,kind:`table`,value:null},{table:`skill_workshop_changes`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`change_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`skill_name`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`actor`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`summary`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`version_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`skill_workshop_changes`,kind:`primaryKey`,value:[`change_id`]},{table:`skill_workshop_changes`,kind:`indexes`,value:3},{table:`skill_workshop_changes`,kind:`checks`,value:2},{table:`state_leases`,kind:`table`,value:null},{table:`state_leases`,kind:`column`,value:{name:`scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`state_leases`,kind:`column`,value:{name:`lease_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`state_leases`,kind:`column`,value:{name:`owner`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`state_leases`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`state_leases`,kind:`column`,value:{name:`heartbeat_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`state_leases`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`state_leases`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`state_leases`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`state_leases`,kind:`primaryKey`,value:[`scope`,`lease_key`]},{table:`state_leases`,kind:`indexes`,value:3},{table:`state_leases`,kind:`checks`,value:0},{table:`subagent_runs`,kind:`table`,value:null},{table:`subagent_runs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`subagent_runs`,kind:`column`,value:{name:`child_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`subagent_runs`,kind:`column`,value:{name:`controller_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`subagent_runs`,kind:`column`,value:{name:`controller_store_path`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`subagent_runs`,kind:`column`,value:{name:`requester_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`subagent_runs`,kind:`column`,value:{name:`requester_store_path`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`subagent_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`subagent_runs`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:8}},{table:`subagent_runs`,kind:`primaryKey`,value:[`run_id`]},{table:`subagent_runs`,kind:`indexes`,value:4},{table:`subagent_runs`,kind:`checks`,value:0},{table:`task_delivery_state`,kind:`table`,value:null},{table:`task_delivery_state`,kind:`column`,value:{name:`task_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`task_delivery_state`,kind:`column`,value:{name:`requester_origin_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`task_delivery_state`,kind:`column`,value:{name:`last_notified_event_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`task_delivery_state`,kind:`primaryKey`,value:[`task_id`]},{table:`task_delivery_state`,kind:`foreignKey`,value:{columns:[`task_id`],target:`task_runs`,targetColumns:[`task_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`task_delivery_state`,kind:`indexes`,value:1},{table:`task_delivery_state`,kind:`checks`,value:0},{table:`task_runs`,kind:`table`,value:null},{table:`task_runs`,kind:`column`,value:{name:`task_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`task_runs`,kind:`column`,value:{name:`runtime`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`task_runs`,kind:`column`,value:{name:`task_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`task_runs`,kind:`column`,value:{name:`source_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`task_runs`,kind:`column`,value:{name:`requester_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`task_runs`,kind:`column`,value:{name:`owner_key`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`task_runs`,kind:`column`,value:{name:`scope_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`task_runs`,kind:`column`,value:{name:`child_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`task_runs`,kind:`column`,value:{name:`parent_flow_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`task_runs`,kind:`column`,value:{name:`parent_task_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`task_runs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`task_runs`,kind:`column`,value:{name:`requester_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`task_runs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`task_runs`,kind:`column`,value:{name:`execution_owner_host`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`task_runs`,kind:`column`,value:{name:`execution_owner_pid`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`task_runs`,kind:`column`,value:{name:`execution_owner_start_identity`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`task_runs`,kind:`column`,value:{name:`label`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`task_runs`,kind:`column`,value:{name:`task`,type:`text`,nullable:!1,identity:!1,default:null,position:18}},{table:`task_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:19}},{table:`task_runs`,kind:`column`,value:{name:`delivery_status`,type:`text`,nullable:!1,identity:!1,default:null,position:20}},{table:`task_runs`,kind:`column`,value:{name:`notify_policy`,type:`text`,nullable:!1,identity:!1,default:null,position:21}},{table:`task_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:22}},{table:`task_runs`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:23}},{table:`task_runs`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:24}},{table:`task_runs`,kind:`column`,value:{name:`last_event_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:25}},{table:`task_runs`,kind:`column`,value:{name:`cleanup_after`,type:`bigint`,nullable:!0,identity:!1,default:null,position:26}},{table:`task_runs`,kind:`column`,value:{name:`tool_use_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:27}},{table:`task_runs`,kind:`column`,value:{name:`last_tool_name`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`task_runs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`task_runs`,kind:`column`,value:{name:`progress_summary`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`task_runs`,kind:`column`,value:{name:`terminal_summary`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`task_runs`,kind:`column`,value:{name:`terminal_outcome`,type:`text`,nullable:!0,identity:!1,default:null,position:32}},{table:`task_runs`,kind:`column`,value:{name:`detail_json`,type:`text`,nullable:!0,identity:!1,default:null,position:33}},{table:`task_runs`,kind:`primaryKey`,value:[`task_id`]},{table:`task_runs`,kind:`indexes`,value:4},{table:`task_runs`,kind:`checks`,value:0},{table:`template_cron_refs`,kind:`table`,value:null},{table:`template_cron_refs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_cron_refs`,kind:`column`,value:{name:`manifest_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_cron_refs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_cron_refs`,kind:`column`,value:{name:`declaration_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_cron_refs`,kind:`column`,value:{name:`scheduler_job_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`template_cron_refs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_cron_refs`,kind:`column`,value:{name:`job_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_cron_refs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`template_cron_refs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_cron_refs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_cron_refs`,kind:`primaryKey`,value:[`agent_id`,`manifest_id`]},{table:`template_cron_refs`,kind:`unique`,value:[`declaration_key`]},{table:`template_cron_refs`,kind:`unique`,value:[`scheduler_job_id`]},{table:`template_cron_refs`,kind:`indexes`,value:3},{table:`template_cron_refs`,kind:`checks`,value:0},{table:`template_installs`,kind:`table`,value:null},{table:`template_installs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_installs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_installs`,kind:`column`,value:{name:`source_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_installs`,kind:`column`,value:{name:`template_name`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_installs`,kind:`column`,value:{name:`template_version`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_installs`,kind:`column`,value:{name:`package_root`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_installs`,kind:`column`,value:{name:`manifest_path`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_installs`,kind:`column`,value:{name:`integrity_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_installs`,kind:`column`,value:{name:`integrity`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_installs`,kind:`column`,value:{name:`source_byte_length`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_installs`,kind:`column`,value:{name:`manifest_schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`template_installs`,kind:`column`,value:{name:`plan_integrity`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`template_installs`,kind:`column`,value:{name:`workspace`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`template_installs`,kind:`column`,value:{name:`agent_config_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`template_installs`,kind:`column`,value:{name:`agent_owned_paths_json`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`template_installs`,kind:`column`,value:{name:`bootstrap_source_path`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`template_installs`,kind:`column`,value:{name:`bootstrap_content_digest`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`template_installs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:18}},{table:`template_installs`,kind:`column`,value:{name:`added_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`template_installs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`template_installs`,kind:`primaryKey`,value:[`agent_id`]},{table:`template_installs`,kind:`unique`,value:[`workspace`]},{table:`template_installs`,kind:`indexes`,value:2},{table:`template_installs`,kind:`checks`,value:1},{table:`template_mcp_server_refs`,kind:`table`,value:null},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`config_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`relationship`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`origin`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`independent_owner`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`template_mcp_server_refs`,kind:`primaryKey`,value:[`agent_id`,`name`]},{table:`template_mcp_server_refs`,kind:`indexes`,value:1},{table:`template_mcp_server_refs`,kind:`checks`,value:3},{table:`template_package_refs`,kind:`table`,value:null},{table:`template_package_refs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_package_refs`,kind:`column`,value:{name:`package_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_package_refs`,kind:`column`,value:{name:`package_source`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_package_refs`,kind:`column`,value:{name:`package_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_package_refs`,kind:`column`,value:{name:`package_version`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_package_refs`,kind:`column`,value:{name:`package_integrity`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_package_refs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_package_refs`,kind:`column`,value:{name:`template_name`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_package_refs`,kind:`column`,value:{name:`package_status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_package_refs`,kind:`column`,value:{name:`relationship`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_package_refs`,kind:`column`,value:{name:`origin`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`template_package_refs`,kind:`column`,value:{name:`independent_owner`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_format`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_detected_format`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_mapped_json`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_unavailable_json`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_adapter_identity`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`template_package_refs`,kind:`column`,value:{name:`installed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`template_package_refs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`template_package_refs`,kind:`primaryKey`,value:[`agent_id`,`package_kind`,`package_source`,`package_ref`,`package_version`]},{table:`template_package_refs`,kind:`indexes`,value:1},{table:`template_package_refs`,kind:`checks`,value:3},{table:`template_workspace_files`,kind:`table`,value:null},{table:`template_workspace_files`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_workspace_files`,kind:`column`,value:{name:`target_path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_workspace_files`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_workspace_files`,kind:`column`,value:{name:`workspace`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_workspace_files`,kind:`column`,value:{name:`source_path`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_workspace_files`,kind:`column`,value:{name:`content_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_workspace_files`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_workspace_files`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_workspace_files`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_workspace_files`,kind:`primaryKey`,value:[`agent_id`,`target_path`]},{table:`template_workspace_files`,kind:`indexes`,value:1},{table:`template_workspace_files`,kind:`checks`,value:0},{table:`update_runs`,kind:`table`,value:null},{table:`update_runs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`update_runs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`update_runs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`update_runs`,kind:`column`,value:{name:`trigger`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`update_runs`,kind:`column`,value:{name:`phase`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`update_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`update_runs`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`update_runs`,kind:`column`,value:{name:`origin_json`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`update_runs`,kind:`column`,value:{name:`target_json`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`update_runs`,kind:`column`,value:{name:`before_json`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`update_runs`,kind:`column`,value:{name:`after_json`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`update_runs`,kind:`column`,value:{name:`steps_json`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`update_runs`,kind:`column`,value:{name:`verification_json`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`update_runs`,kind:`column`,value:{name:`repair_json`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`update_runs`,kind:`column`,value:{name:`confirmed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`update_runs`,kind:`column`,value:{name:`finished_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`update_runs`,kind:`column`,value:{name:`downtime_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`update_runs`,kind:`primaryKey`,value:[`run_id`]},{table:`update_runs`,kind:`indexes`,value:3},{table:`update_runs`,kind:`checks`,value:11},{table:`user_background_images`,kind:`table`,value:null},{table:`user_background_images`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_background_images`,kind:`column`,value:{name:`asset_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_background_images`,kind:`column`,value:{name:`image`,type:`bytea`,nullable:!1,identity:!1,default:null,position:3}},{table:`user_background_images`,kind:`column`,value:{name:`width`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`user_background_images`,kind:`column`,value:{name:`height`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`user_background_images`,kind:`primaryKey`,value:[`profile_id`]},{table:`user_background_images`,kind:`unique`,value:[`asset_id`]},{table:`user_background_images`,kind:`foreignKey`,value:{columns:[`profile_id`],target:`user_profiles`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`user_background_images`,kind:`indexes`,value:2},{table:`user_background_images`,kind:`checks`,value:3},{table:`user_preferences`,kind:`table`,value:null},{table:`user_preferences`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_preferences`,kind:`column`,value:{name:`pref_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_preferences`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`user_preferences`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`user_preferences`,kind:`primaryKey`,value:[`profile_id`,`pref_key`]},{table:`user_preferences`,kind:`indexes`,value:1},{table:`user_preferences`,kind:`checks`,value:0},{table:`user_profile_emails`,kind:`table`,value:null},{table:`user_profile_emails`,kind:`column`,value:{name:`email`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_profile_emails`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_profile_emails`,kind:`column`,value:{name:`binding_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`user_profile_emails`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`user_profile_emails`,kind:`primaryKey`,value:[`email`]},{table:`user_profile_emails`,kind:`indexes`,value:2},{table:`user_profile_emails`,kind:`checks`,value:0},{table:`user_profile_identities`,kind:`table`,value:null},{table:`user_profile_identities`,kind:`column`,value:{name:`provider`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_profile_identities`,kind:`column`,value:{name:`subject`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_profile_identities`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`user_profile_identities`,kind:`column`,value:{name:`canonical_login`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`user_profile_identities`,kind:`column`,value:{name:`verified_email_json`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`user_profile_identities`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`user_profile_identities`,kind:`column`,value:{name:`authorization_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`user_profile_identities`,kind:`column`,value:{name:`authorization_basis_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`user_profile_identities`,kind:`primaryKey`,value:[`provider`,`subject`]},{table:`user_profile_identities`,kind:`indexes`,value:3},{table:`user_profile_identities`,kind:`checks`,value:0},{table:`user_profiles`,kind:`table`,value:null},{table:`user_profiles`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_profiles`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`user_profiles`,kind:`column`,value:{name:`primary_github_account_id`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`user_profiles`,kind:`column`,value:{name:`avatar`,type:`bytea`,nullable:!0,identity:!1,default:null,position:4}},{table:`user_profiles`,kind:`column`,value:{name:`avatar_mime`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`user_profiles`,kind:`column`,value:{name:`avatar_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`user_profiles`,kind:`column`,value:{name:`merged_into`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`user_profiles`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`user_profiles`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`user_profiles`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`user_profiles`,kind:`primaryKey`,value:[`id`]},{table:`user_profiles`,kind:`indexes`,value:1},{table:`user_profiles`,kind:`checks`,value:0},{table:`web_push_approval_deliveries`,kind:`table`,value:null},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`subscription_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`user_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`prepared_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`web_push_approval_deliveries`,kind:`primaryKey`,value:[`approval_id`,`subscription_id`]},{table:`web_push_approval_deliveries`,kind:`foreignKey`,value:{columns:[`subscription_id`],target:`web_push_subscriptions`,targetColumns:[`subscription_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`web_push_approval_deliveries`,kind:`foreignKey`,value:{columns:[`approval_id`],target:`operator_approvals`,targetColumns:[`approval_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`web_push_approval_deliveries`,kind:`indexes`,value:2},{table:`web_push_approval_deliveries`,kind:`checks`,value:0},{table:`web_push_subscriptions`,kind:`table`,value:null},{table:`web_push_subscriptions`,kind:`column`,value:{name:`endpoint_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`subscription_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`endpoint`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`p256dh`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`auth`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`user_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`preferences_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`web_push_subscriptions`,kind:`primaryKey`,value:[`endpoint_hash`]},{table:`web_push_subscriptions`,kind:`unique`,value:[`subscription_id`]},{table:`web_push_subscriptions`,kind:`indexes`,value:3},{table:`web_push_subscriptions`,kind:`checks`,value:0},{table:`worker_environment_credentials`,kind:`table`,value:null},{table:`worker_environment_credentials`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`credential_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`bundle_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`rpc_set_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`delivered_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_environment_credentials`,kind:`primaryKey`,value:[`environment_id`]},{table:`worker_environment_credentials`,kind:`unique`,value:[`credential_hash`]},{table:`worker_environment_credentials`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_environment_credentials`,kind:`indexes`,value:2},{table:`worker_environment_credentials`,kind:`checks`,value:4},{table:`worker_environment_session_attachments`,kind:`table`,value:null},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`session_lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`closed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_environment_session_attachments`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_environment_session_attachments`,kind:`unique`,value:[`environment_id`]},{table:`worker_environment_session_attachments`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_environment_session_attachments`,kind:`indexes`,value:3},{table:`worker_environment_session_attachments`,kind:`checks`,value:1},{table:`worker_environment_ssh_fallback_ports`,kind:`table`,value:null},{table:`worker_environment_ssh_fallback_ports`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environment_ssh_fallback_ports`,kind:`column`,value:{name:`position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environment_ssh_fallback_ports`,kind:`column`,value:{name:`port`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environment_ssh_fallback_ports`,kind:`primaryKey`,value:[`environment_id`,`position`]},{table:`worker_environment_ssh_fallback_ports`,kind:`unique`,value:[`environment_id`,`port`]},{table:`worker_environment_ssh_fallback_ports`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_environment_ssh_fallback_ports`,kind:`indexes`,value:2},{table:`worker_environment_ssh_fallback_ports`,kind:`checks`,value:2},{table:`worker_environments`,kind:`table`,value:null},{table:`worker_environments`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environments`,kind:`column`,value:{name:`provider_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environments`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environments`,kind:`column`,value:{name:`profile_snapshot_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_environments`,kind:`column`,value:{name:`last_activated_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_purpose`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_demand_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_expires_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_consumed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_environments`,kind:`column`,value:{name:`provision_operation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`worker_environments`,kind:`column`,value:{name:`lease_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`worker_environments`,kind:`column`,value:{name:`node_setup_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`worker_environments`,kind:`column`,value:{name:`node_device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_host`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_port`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_user`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_host_key`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_key_ref_json`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`worker_environments`,kind:`column`,value:{name:`desktop_json`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`worker_environments`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:21}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_bundle_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_openclaw_version`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_protocol_features_json`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_install_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`worker_environments`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:26}},{table:`worker_environments`,kind:`column`,value:{name:`teardown_terminal_state`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`worker_environments`,kind:`column`,value:{name:`attached_session_ids_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:28}},{table:`worker_environments`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:29}},{table:`worker_environments`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:30}},{table:`worker_environments`,kind:`column`,value:{name:`state_changed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:31}},{table:`worker_environments`,kind:`column`,value:{name:`idle_since_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:32}},{table:`worker_environments`,kind:`column`,value:{name:`destroy_requested_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:33}},{table:`worker_environments`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:34}},{table:`worker_environments`,kind:`column`,value:{name:`shared_host`,type:`bigint`,nullable:!0,identity:!1,default:null,position:35}},{table:`worker_environments`,kind:`column`,value:{name:`resource_receipt_json`,type:`text`,nullable:!0,identity:!1,default:null,position:36}},{table:`worker_environments`,kind:`column`,value:{name:`retention_json`,type:`text`,nullable:!0,identity:!1,default:null,position:37}},{table:`worker_environments`,kind:`column`,value:{name:`provision_source_json`,type:`text`,nullable:!0,identity:!1,default:null,position:38}},{table:`worker_environments`,kind:`primaryKey`,value:[`environment_id`]},{table:`worker_environments`,kind:`unique`,value:[`provision_operation_id`]},{table:`worker_environments`,kind:`indexes`,value:4},{table:`worker_environments`,kind:`checks`,value:5},{table:`worker_inference_turns`,kind:`table`,value:null},{table:`worker_inference_turns`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_inference_turns`,kind:`column`,value:{name:`run_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_inference_turns`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_inference_turns`,kind:`column`,value:{name:`turn_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_inference_turns`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_inference_turns`,kind:`column`,value:{name:`request_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_inference_turns`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_inference_turns`,kind:`column`,value:{name:`terminal_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_inference_turns`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`worker_inference_turns`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`worker_inference_turns`,kind:`primaryKey`,value:[`session_id`,`run_epoch`,`run_id`,`turn_id`]},{table:`worker_inference_turns`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_inference_turns`,kind:`indexes`,value:2},{table:`worker_inference_turns`,kind:`checks`,value:5},{table:`worker_session_placement_moves`,kind:`table`,value:null},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`operation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`source_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`source_environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`source_owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_machine_class`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_os`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`abandon_source`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`worker_session_placement_moves`,kind:`primaryKey`,value:[`operation_id`]},{table:`worker_session_placement_moves`,kind:`unique`,value:[`session_id`]},{table:`worker_session_placement_moves`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_session_placement_moves`,kind:`indexes`,value:2},{table:`worker_session_placement_moves`,kind:`checks`,value:5},{table:`worker_session_placements`,kind:`table`,value:null},{table:`worker_session_placements`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_session_placements`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_session_placements`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_session_placements`,kind:`column`,value:{name:`execution_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`worker_session_placements`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_session_placements`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`worker_session_placements`,kind:`column`,value:{name:`transition_generation`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`worker_session_placements`,kind:`column`,value:{name:`active_owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_session_placements`,kind:`column`,value:{name:`workspace_base_manifest_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_session_placements`,kind:`column`,value:{name:`remote_workspace_dir`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_session_placements`,kind:`column`,value:{name:`worker_bundle_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`worker_session_placements`,kind:`column`,value:{name:`last_transcript_ack_cursor`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`worker_session_placements`,kind:`column`,value:{name:`last_live_event_ack_cursor`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`worker_session_placements`,kind:`column`,value:{name:`recovery_error`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_owner`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:18}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`worker_session_placements`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`worker_session_placements`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:21}},{table:`worker_session_placements`,kind:`column`,value:{name:`state_changed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:22}},{table:`worker_session_placements`,kind:`column`,value:{name:`terminal_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`worker_session_placements`,kind:`column`,value:{name:`terminal_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:24}},{table:`worker_session_placements`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_session_placements`,kind:`indexes`,value:4},{table:`worker_session_placements`,kind:`checks`,value:12},{table:`worker_session_tool_operations`,kind:`table`,value:null},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`source_session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`source_claim_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`tool_call_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`tool_name`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`operation_seed`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`child_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worker_session_tool_operations`,kind:`primaryKey`,value:[`source_session_id`,`source_claim_id`,`tool_call_id`]},{table:`worker_session_tool_operations`,kind:`foreignKey`,value:{columns:[`source_session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_session_tool_operations`,kind:`indexes`,value:1},{table:`worker_session_tool_operations`,kind:`checks`,value:2},{table:`worker_transcript_commit_heads`,kind:`table`,value:null},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`run_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`next_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_transcript_commit_heads`,kind:`primaryKey`,value:[`session_id`,`run_epoch`]},{table:`worker_transcript_commit_heads`,kind:`indexes`,value:1},{table:`worker_transcript_commit_heads`,kind:`checks`,value:3},{table:`worker_transcript_commits`,kind:`table`,value:null},{table:`worker_transcript_commits`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`run_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`request_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_transcript_commits`,kind:`primaryKey`,value:[`session_id`,`run_epoch`,`seq`]},{table:`worker_transcript_commits`,kind:`foreignKey`,value:{columns:[`session_id`,`run_epoch`],target:`worker_transcript_commit_heads`,targetColumns:[`session_id`,`run_epoch`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_transcript_commits`,kind:`indexes`,value:1},{table:`worker_transcript_commits`,kind:`checks`,value:6},{table:`worker_turn_tool_authorities`,kind:`table`,value:null},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`tool_names_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_turn_tool_authorities`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_turn_tool_authorities`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_turn_tool_authorities`,kind:`indexes`,value:1},{table:`worker_turn_tool_authorities`,kind:`checks`,value:2},{table:`worker_workspace_pending_results`,kind:`table`,value:null},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`recovery_requested_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`workspace_accepted_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`staged_result_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`repository_workspace_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`repository_disk_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`worker_workspace_pending_results`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_workspace_pending_results`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_workspace_pending_results`,kind:`indexes`,value:1},{table:`worker_workspace_pending_results`,kind:`checks`,value:2},{table:`worker_workspace_reconciliations`,kind:`table`,value:null},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`base_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`current_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`plan_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`base_pack`,type:`bytea`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`worker_workspace_reconciliations`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_workspace_reconciliations`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_workspace_reconciliations`,kind:`indexes`,value:1},{table:`worker_workspace_reconciliations`,kind:`checks`,value:3},{table:`workspace_generated_bootstrap_hashes`,kind:`table`,value:null},{table:`workspace_generated_bootstrap_hashes`,kind:`column`,value:{name:`workspace_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`workspace_generated_bootstrap_hashes`,kind:`column`,value:{name:`filename`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`workspace_generated_bootstrap_hashes`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`workspace_generated_bootstrap_hashes`,kind:`primaryKey`,value:[`workspace_key`,`filename`]},{table:`workspace_generated_bootstrap_hashes`,kind:`foreignKey`,value:{columns:[`workspace_key`],target:`workspace_setup_state`,targetColumns:[`workspace_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`workspace_generated_bootstrap_hashes`,kind:`indexes`,value:1},{table:`workspace_generated_bootstrap_hashes`,kind:`checks`,value:0},{table:`workspace_path_aliases`,kind:`table`,value:null},{table:`workspace_path_aliases`,kind:`column`,value:{name:`alias_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`alias_path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`workspace_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`workspace_path`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`workspace_path_aliases`,kind:`primaryKey`,value:[`alias_key`]},{table:`workspace_path_aliases`,kind:`indexes`,value:2},{table:`workspace_path_aliases`,kind:`checks`,value:0},{table:`workspace_setup_state`,kind:`table`,value:null},{table:`workspace_setup_state`,kind:`column`,value:{name:`workspace_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`workspace_setup_state`,kind:`column`,value:{name:`workspace_path`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`workspace_setup_state`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`workspace_setup_state`,kind:`column`,value:{name:`bootstrap_seeded_at`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`workspace_setup_state`,kind:`column`,value:{name:`setup_completed_at`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`workspace_setup_state`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`workspace_setup_state`,kind:`column`,value:{name:`attested_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`workspace_setup_state`,kind:`column`,value:{name:`attestation_updated_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`workspace_setup_state`,kind:`column`,value:{name:`bootstrap_deferred`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`workspace_setup_state`,kind:`primaryKey`,value:[`workspace_key`]},{table:`workspace_setup_state`,kind:`indexes`,value:2},{table:`workspace_setup_state`,kind:`checks`,value:1},{table:`worktree_provisioned_file_chunks`,kind:`table`,value:null},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`chunk_index`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`data`,type:`bytea`,nullable:!1,identity:!1,default:null,position:4}},{table:`worktree_provisioned_file_chunks`,kind:`primaryKey`,value:[`worktree_id`,`path`,`chunk_index`]},{table:`worktree_provisioned_file_chunks`,kind:`indexes`,value:1},{table:`worktree_provisioned_file_chunks`,kind:`checks`,value:1},{table:`worktree_templates`,kind:`table`,value:null},{table:`worktree_templates`,kind:`column`,value:{name:`cache_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worktree_templates`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worktree_templates`,kind:`column`,value:{name:`repo_root`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worktree_templates`,kind:`column`,value:{name:`common_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worktree_templates`,kind:`column`,value:{name:`worktree_root`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worktree_templates`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worktree_templates`,kind:`column`,value:{name:`backend`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worktree_templates`,kind:`column`,value:{name:`source_commit`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`worktree_templates`,kind:`column`,value:{name:`content_key`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`worktree_templates`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`worktree_templates`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`worktree_templates`,kind:`column`,value:{name:`last_used_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worktree_templates`,kind:`primaryKey`,value:[`cache_key`]},{table:`worktree_templates`,kind:`unique`,value:[`id`]},{table:`worktree_templates`,kind:`indexes`,value:2},{table:`worktree_templates`,kind:`checks`,value:1},{table:`worktrees`,kind:`table`,value:null},{table:`worktrees`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worktrees`,kind:`column`,value:{name:`repo_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worktrees`,kind:`column`,value:{name:`repo_root`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worktrees`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worktrees`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worktrees`,kind:`column`,value:{name:`base_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worktrees`,kind:`column`,value:{name:`owner_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worktrees`,kind:`column`,value:{name:`owner_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worktrees`,kind:`column`,value:{name:`snapshot_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worktrees`,kind:`column`,value:{name:`provisioned_paths_json`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`worktrees`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`worktrees`,kind:`column`,value:{name:`last_active_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worktrees`,kind:`column`,value:{name:`removed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`worktrees`,kind:`column`,value:{name:`run_end_cleanup_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`worktrees`,kind:`column`,value:{name:`gc_protection_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`worktrees`,kind:`primaryKey`,value:[`id`]},{table:`worktrees`,kind:`indexes`,value:3},{table:`worktrees`,kind:`checks`,value:1}];return Object.defineProperty(this,"expectedCatalog",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}},Yh=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`;function isStatePostgres(){return stateEngineInput()!==void 0}function inspectStateSqlite(e){let t=getAdmittedSqliteSchemaFacts(e)??captureSqliteSchemaFacts(e);return{hasEngineAnchor:t.tables.has(`openclaw_engine_anchor`),hasExistingData:[...t.tables,...t.views,...t.triggers.keys()].some(e=>e!==`openclaw_engine_anchor`&&!e.startsWith(`sqlite_`))}}function admitStatePostgres(e,t){if(!t&&getStateRuntimeSchemaAdmission(e)?.startupReady)return;let n=withPostgresSchemaAdmissionRetry(e,()=>{let t=getPostgresPhysicalFacts(e);if(!t)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${Yh}`);return t}),r=new Set(n.catalog.filter(e=>e.kind===`table`).map(e=>e.table)),i=new Set($.fragments.flatMap(e=>e.tables.some(e=>r.has(e))?[]:e.tables));if(n.version===40&&assertPostgresCatalog(n.catalog.filter(e=>!e.kind.endsWith(`Definition`)&&e.table!==`openclaw_schema_meta`),$.expectedCatalog.filter(e=>!i.has(e.table))),t){let t=Date.now();e.prepare(`INSERT INTO schema_meta
        (meta_key, role, schema_version, agent_id, app_version, created_at, updated_at)
        VALUES ('primary', 'global', ?, NULL, ?, ?, ?)`).run(40,go,t,t),writeStateSchemaContentVersion(e)}let a=e.prepare(`SELECT schema_version, role, agent_id FROM schema_meta WHERE meta_key = 'primary'`).get(),s=e.prepare(`SELECT value_json FROM config_machine_state WHERE state_key = 'state.schema.contentVersion'`).get(),c;try{let e=s?.value_json;if(e!=null&&typeof e!=`string`)throw Error(`Invalid PostgreSQL state content marker`);c=parseStateSchemaContentVersion(e)}catch{throw Error(`PostgreSQL state metadata mismatch. ${Yh}`)}if(a?.schema_version!==n.version||a.role!==`global`||a.agent_id!==null||c>n.version)throw Error(`PostgreSQL state metadata mismatch. ${Yh}`);publishStateSchemaVersionAdmission(e,{userVersion:n.version,contentVersion:n.version}),publishStateRuntimeSchemaAdmission(e,!0)}function statePostgresVersionSql(e){return`UPDATE schema_meta
        SET schema_version = ${e},
          app_version = '${go.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';
        INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
        VALUES ('state.schema.contentVersion', '${e}',
          CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint))
        ON CONFLICT (state_key) DO UPDATE
          SET value_json = EXCLUDED.value_json, updated_at_ms = EXCLUDED.updated_at_ms;`}function createStatePostgresMigrations(){let e={postgres:Xh.postgres,postgresFragments:Xh.postgresFragments},t=withLegacyWorkerProvisionSource(e.postgres),n=withLegacyWorkspaceBootstrapDeferred(t),r={...e,postgres:t,postgresWithoutOptionalColumn:{table:`workspace_setup_state`,column:`bootstrap_deferred`,sql:n}},i={...e,postgres:withLegacyWorkerRetention(n)},a={postgres:withLegacyRepositoryDiskAuthority(i.postgres),postgresFragments:i.postgresFragments.map(e=>({...e,sql:withLegacyRepositoryDiskAuthority(e.sql)}))},s={postgres:withLegacyWorkerResourceReceipts(a.postgres),postgresFragments:a.postgresFragments},c={postgres:withLegacyTemplateStateSchema(s.postgres),postgresFragments:s.postgresFragments.map(e=>({...e,tables:e.tables.map(legacyTemplateStateIdentifier),sql:withLegacyTemplateStateSchema(e.sql)}))},l={postgres:withLegacyLocalWorkspaceCas(c.postgres),postgresFragments:c.postgresFragments.map(e=>({...e,tables:e.tables.filter(e=>!jh.some(t=>t===e)),sql:withLegacyLocalWorkspaceCas(e.sql)}))},u={postgres:withLegacyPostgresIndexOrdering(l.postgres,`schema-nullability`),postgresFragments:l.postgresFragments.map(e=>({...e,sql:withLegacyPostgresIndexOrdering(e.sql,`schema-nullability`)}))},d={postgres:withLegacyPostgresIndexOrdering(u.postgres),postgresFragments:u.postgresFragments.map(e=>({...e,sql:withLegacyPostgresIndexOrdering(e.sql)}))},f={postgres:withLegacyLocalWorkspaceManifests(d.postgres),postgresFragments:d.postgresFragments.map(e=>({...e,tables:e.tables.filter(e=>e!==`local_workspace_manifest_nodes`),sql:withLegacyLocalWorkspaceManifests(e.sql)}))},p={...f,postgres:`${f.postgres}\n${$.clientCredentialSource.sql}`},m={postgres:withLegacyPublicationDraft(p.postgres),postgresFragments:p.postgresFragments.map(e=>({...e,sql:withLegacyPublicationDraft(e.sql)}))},h={...m,postgres:m.postgres.replace(/CREATE INDEX "idx_state_leases_owner"[^;]*;/u,$.preWriteIndexesV27Sql.state_leases)+$.preWriteIndexesV27Sql.skill_usage+$.preWriteIndexesV27Sql.acp_replay_events,postgresFragments:m.postgresFragments};return[{version:25,sql:$.operatorRecoveryV25Sql,fromSchema:h,schema:h},{version:26,fromSchema:h,schema:h,sql:statePostgresVersionSql(26)},{version:27,fromSchema:h,schema:m,sql:`${$.writeIndexesV27Sql}
        ${statePostgresVersionSql(27)}`},{version:28,fromSchema:m,schema:p,sql:`ALTER TABLE IF EXISTS github_publication_requests ADD COLUMN draft bigint;
        ALTER TABLE IF EXISTS github_personal_publication_requests ADD COLUMN draft bigint;
        ALTER TABLE IF EXISTS github_repository_publication_requests ADD COLUMN draft bigint;
        ${statePostgresVersionSql(28)}`},{version:29,fromSchema:p,schema:f,sql:$.clientCredentialV29Sql},{version:30,fromSchema:f,schema:f,sql:statePostgresVersionSql(30)},{version:31,fromSchema:f,schema:d,sql:`DO $workspace$
        DECLARE baseline_constraint text;
        BEGIN
          IF to_regclass('local_workspace_projections') IS NOT NULL THEN
            SELECT conname INTO STRICT baseline_constraint FROM pg_constraint
              WHERE conrelid = 'local_workspace_projections'::regclass AND contype = 'c'
                AND pg_get_constraintdef(oid) LIKE '%baseline_json%baseline_ref%';
            EXECUTE format('ALTER TABLE local_workspace_projections DROP CONSTRAINT %I', baseline_constraint);
            ALTER TABLE local_workspace_projections
              ADD COLUMN checkpoint_json text COLLATE "C",
              ADD CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL);
            CREATE TABLE local_workspace_manifest_nodes (
              worktree_id text COLLATE "C" NOT NULL,
              path text COLLATE "C" NOT NULL,
              node_json text COLLATE "C" NOT NULL,
              PRIMARY KEY (worktree_id, path),
              FOREIGN KEY (worktree_id) REFERENCES local_workspace_projections(worktree_id)
                ON DELETE CASCADE
            );
          END IF;
        END $workspace$;
        ${statePostgresVersionSql(31)}`},{version:32,fromSchema:d,schema:u,sql:`${postgresIndexOrderingMigration([u.postgres,...u.postgresFragments.map(e=>e.sql)].join(`
`))}
        ${statePostgresVersionSql(32)}`},{version:33,fromSchema:u,schema:l,sql:`${postgresIndexOrderingMigration([l.postgres,...l.postgresFragments.map(e=>e.sql)].join(`
`),`schema-nullability`)}
        ${statePostgresVersionSql(33)}`},{version:34,fromSchema:l,schema:l,sql:statePostgresVersionSql(34)},{version:35,fromSchema:l,schema:c,sql:`${$.workspaceCasV35Sql}\n${statePostgresVersionSql(35)}`},{version:36,fromSchema:c,schema:s,sql:`${Wh}\n${statePostgresVersionSql(36)}`},{version:37,fromSchema:s,schema:a,sql:`ALTER TABLE worker_environments ADD COLUMN resource_receipt_json text COLLATE "C";
        ${statePostgresVersionSql(37)}`},{version:38,fromSchema:a,schema:i,sql:`ALTER TABLE IF EXISTS session_repository_workspaces ADD COLUMN disk_authority_json text COLLATE "C";
        ALTER TABLE worker_workspace_pending_results ADD COLUMN repository_disk_authority_json text COLLATE "C";
        ${statePostgresVersionSql(38)}`},{version:39,fromSchema:i,schema:r,sql:`ALTER TABLE worker_environments ADD COLUMN retention_json text COLLATE "C";
        ${statePostgresVersionSql(39)}`},{version:40,fromSchema:r,schema:e,sql:`ALTER TABLE workspace_setup_state ADD COLUMN IF NOT EXISTS bootstrap_deferred bigint;
        ALTER TABLE worker_environments ADD COLUMN provision_source_json text COLLATE "C";
        UPDATE worker_environments
        SET provision_source_json = '{"kind":"unavailable"}'
        WHERE (state IN ('requested', 'provisioning') AND lease_id IS NULL
          OR state = 'bootstrapping' AND owner_epoch = 0)
          AND provision_source_json IS NULL;
        ${statePostgresVersionSql(40)}`}]}const Xh={id:`state`,version:40,sqlite:``,get postgres(){let e=$.eagerSql;return Object.defineProperty(this,"postgres",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get postgresFragments(){let e=$.fragments.map(e=>{let{activation:t}=e;if(t!==`first-use`&&t!==`version-additive`)throw Error(`Unknown PostgreSQL state fragment activation: ${t}`);return{id:e.id,tables:e.tables,sql:e.sql,dependencies:e.dependencies,activation:t}});return Object.defineProperty(this,"postgresFragments",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get postgresMigrations(){let e=createStatePostgresMigrations();return Object.defineProperty(this,"postgresMigrations",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}};function ensureStatePostgresFragment(e,t){let n=getPostgresPhysicalFacts(e);if(!n)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${Yh}`);let r=$.fragments.find(e=>e.tables.includes(t));if(!r){if($.expectedCatalog.some(e=>e.kind===`table`&&e.table===t)&&n.catalog.some(e=>e.kind===`table`&&e.table===t))return;throw Error(`No PostgreSQL state fragment owns ${t}`)}let i=r.tables.filter(e=>n.version>=35||!jh.some(t=>t===e));if(i.every(e=>n.catalog.some(t=>t.kind===`table`&&t.table===e)))return;for(let t of r.dependencies){let n=$.fragments.find(e=>e.id===t);if(!n)throw Error(`Unknown state fragment dependency ${t}`);ensureStatePostgresFragment(e,n.tables[0])}if(!Jt(e,{commit:()=>zn(e),invalidate:()=>zn(e)}))throw Error(`PostgreSQL state fragments require the owner's transaction`);let a=e.prepare(`SELECT 1 AS present FROM pg_catalog.pg_class
    WHERE relnamespace = ?::regnamespace AND relname IN (${i.map(()=>`?`).join(`, `)})
    LIMIT 1`).get(n.namespace,...i),s=getAdmittedPostgresSchema(e);if(!s)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${Yh}`);if(jn(e),a){admitPostgresPhysicalFacts({db:e,namespace:n.namespace,storeId:n.storeId,store:n.store,version:n.version,schema:s,preserveSchemaSeal:!0}),admitStatePostgres(e,!1);return}let c=n.version<38?withLegacyRepositoryDiskAuthority(r.sql):r.sql,l=n.version<36?withLegacyTemplateStateSchema(c):c,u=n.version<35?withLegacyLocalWorkspaceCas(l):l;e.exec(n.version<33?withLegacyPostgresIndexOrdering(u,n.version<32?`sqlite`:`schema-nullability`):u),admitPostgresPhysicalFacts({db:e,namespace:n.namespace,storeId:n.storeId,store:n.store,version:n.version,schema:Xh,recordSchema:!0}),admitStatePostgres(e,!1)}function openExistingStatePostgresConnection(e,t){if(stateEngineInput())return openExistingStatePostgresConnectionFromAnchor(openTrackedStateDatabase(e,{existingOnly:!0,expectedIdentity:t}),e)}function openExistingStatePostgresConnectionFromAnchor(e,t){let n;try{let r=stateEngineInput();if(!r)throw Error(`PostgreSQL state inspection requires the configured state connection.`);admitStateSchemaFacts(e,t);let i=openEngineStore({anchor:e,schema:Xh,input:r,inspectSqlite:()=>inspectStateSqlite(e),prepareAnchor:()=>{},openSqlite:()=>{},existingOnly:!0,reusePostgresConnection:!0,existingVersion:!0,admitPostgres:admitStatePostgres,closeOnFailure:(e,t)=>{throw n=e,t}});if(!C(i))throw Error(`Expected PostgreSQL state connection`);return n=i,{database:{db:n,path:t},close(){return it(xh.closeUnpublishedOpenClawStateDatabaseHandle({db:i,path:t}),`PostgreSQL state connection cleanup failed.`),!i.isOpen&&!e.isOpen}}}catch(r){let i=xh.closeUnpublishedOpenClawStateDatabaseHandle({db:n??e,path:t});throw i.length?Wt([r,...i],`PostgreSQL state connection acquisition and cleanup failed.`,r):r}}const Zh=number().int().min(0).max(2**53-1);discriminatedUnion(`reason`,[object({reason:literal$1(`expired`),expiresAt:Zh,expiredByMs:Zh,heartbeatAgeMs:Zh,renewalTimerLateByMs:Zh.optional()}),object({reason:literal$1(`replaced`),owner:literal$1(`[redacted]`)}),object({reason:literal$1(`missing`)}),object({reason:literal$1(`storage-failed`)}),object({reason:literal$1(`admission-failed`)})]);function hasLegacyCronRunLogs(e){let t=getAdmittedSqliteSchemaFacts(e);return t?t.tables.has(`cron_run_logs`):!!e.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'cron_run_logs' LIMIT 1`).get()}const Qh=string().refine(e=>!e.includes(`\0`),`Must not contain NUL`),$h=union([Qh,array(Qh).min(1).refine(e=>!!e[0]?.length,`Executable must not be empty`)]),eg=union([$h,record(string(),$h)]),tg=string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u),ng=string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),rg=record(ng,object({description:string().optional(),documentationUrl:string().optional()}).passthrough()).refine(e=>Object.keys(e).length<=16,`At most 16 setup secrets may be requested`),ig=record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),Qh),ag=object({source:_enum([`devcontainer`,`script`,`detected`,`none`]),identity:tg.optional(),inputs:record(string(),tg),env:record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),Qh.nullable()),secretNames:array(ng).max(16).optional(),ignoredPropertiesNote:string().optional(),onCreate:eg.optional(),updateContent:eg.optional(),postCreate:eg.optional(),postStart:eg.optional(),detectedInstall:eg.optional()}).strict();object({onCreateCommand:eg.optional(),updateContentCommand:eg.optional(),postCreateCommand:eg.optional(),postStartCommand:eg.optional(),secrets:rg.optional(),containerEnv:ig.optional(),remoteEnv:record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),Qh.nullable()).optional()}).passthrough();const og=string().regex(/^[a-f0-9]{64}$/u),sg=object({nodeBootstrapSha256:og,enabledPluginIds:array(string().min(1).max(256)).max(256),workerBundleHash:og,workerArchiveSha256:og,openclawVersion:string().min(1).max(128),protocolFeatures:array(string().min(1).max(128)).max(64)}).strict(),cg=object({machineClass:string().min(1).max(256),platform:string().min(1).max(64),arch:string().min(1).max(64).optional(),profileKey:og.optional()}).strict();object({key:og,cacheKey:og,contractVersion:union([literal$1(1),literal$1(2)]),setupRecipe:string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u).optional(),runSetupScript:boolean().optional(),recipe:ag.optional(),target:cg,artifacts:sg}).strict().omit({setupRecipe:!0,runSetupScript:!0,recipe:!0}).extend({source:_enum([`empty`,`image`])});const lg=[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`exec_approvals_config`],ug={version:21,tables:[`meeting_transcript_sessions`,`meeting_transcript_summaries`,`delivery_queue_entries`],columns:[...[`source_account_id`,`source_guild_id`,`source_channel_id`,`source_meeting_url`,`source_thread_ts`,`source_file_id`,`metadata_agent_id`].map(e=>`meeting_transcript_sessions.${e}`),`meeting_transcript_summaries.overview`,`delivery_queue_entries.retention_id_prefix`,`delivery_queue_entries.retention_max_age_ms`,`delivery_queue_entries.retention_max_entries`],migrate:migratePredicateColumnsV21,applied:`Derived meeting transcript selectors and bounded delivery retention columns (v21)`};function migratePredicateColumnsV21(e,t){let n=t===21&&ug.columns.some(t=>{let n=t.indexOf(`.`),r=t.slice(0,n);return tableExists(e,r)&&!tableHasColumn(e,r,t.slice(n+1))});if(t>=21&&!n)return!1;let r=!1,text=(e,t)=>`CASE WHEN json_valid(${e}) THEN CASE WHEN json_type(${e}, '${t}') = 'text' THEN json_extract(${e}, '${t}') END END`;if(tableExists(e,`meeting_transcript_sessions`)){let t=[`accountId`,`guildId`,`channelId`,`meetingUrl`,`threadTs`,`fileId`],n=[`source_account_id`,`source_guild_id`,`source_channel_id`,`source_meeting_url`,`source_thread_ts`,`source_file_id`];for(let t of[...n,`metadata_agent_id`])r=ensureColumn(e,`meeting_transcript_sessions`,`${t} TEXT`)||r;e.exec(`UPDATE meeting_transcript_sessions SET
      ${n.map((e,n)=>`${e} = ${text(`source_json`,`$.${t[n]}`)}`).join(`,`)},
      metadata_agent_id = ${text(`metadata_json`,`$.agentId`)}`)}return tableExists(e,`meeting_transcript_summaries`)&&(r=ensureColumn(e,`meeting_transcript_summaries`,`overview TEXT`)||r,e.exec(`UPDATE meeting_transcript_summaries SET overview = ${text(`summary_json`,`$.overview`)}`)),tableExists(e,`delivery_queue_entries`)&&(r=ensureColumn(e,`delivery_queue_entries`,`retention_id_prefix TEXT`)||r,r=ensureColumn(e,`delivery_queue_entries`,`retention_max_age_ms INTEGER`)||r,r=ensureColumn(e,`delivery_queue_entries`,`retention_max_entries INTEGER`)||r,e.exec(`UPDATE delivery_queue_entries SET
      (retention_id_prefix, retention_max_age_ms, retention_max_entries) = (
        SELECT id_prefix, max_age_ms, max_entries FROM (
          SELECT json_extract(entry_json, '$.completionRetention.idPrefix') id_prefix,
            json_extract(entry_json, '$.completionRetention.maxAgeMs') max_age_ms,
            json_extract(entry_json, '$.completionRetention.maxEntries') max_entries
          WHERE json_valid(entry_json)
            AND json_type(entry_json, '$.completionRetention') = 'object'
        ) WHERE typeof(id_prefix) = 'text' AND id_prefix <> ''
          AND substr(id, 1, length(id_prefix)) = id_prefix
          AND typeof(max_age_ms) = 'integer' AND max_age_ms BETWEEN 1 AND 9007199254740991
          AND typeof(max_entries) = 'integer' AND max_entries BETWEEN 1 AND 9007199254740991
      )`)),r}BigInt(2**53-1),i(Symbol.for(`openclaw.outboundDeliveryEnqueued`),()=>({onEnqueued:e=>{}}));function tableSql$1(e){let t=getAdmittedSqliteSchemaFacts(e);if(t)return t.tableSql.get(`operator_approvals`)??void 0;let n=e.prepare(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'operator_approvals'`).get();return typeof n?.sql==`string`?n.sql:void 0}function hasCanonicalOperatorApprovalKinds(e){return!tableExists(e,`operator_approvals`)||/kind\s+text\s+not\s+null\s+check\s*\(\s*kind\s+in\s*\(\s*'exec'\s*,\s*'plugin'\s*,\s*'system-agent'\s*\)\s*\)/.test(tableSql$1(e)?.toLowerCase()??``)}function assertCanonicalOperatorApprovalKinds(e,t){if(!hasCanonicalOperatorApprovalKinds(e))throw new SqliteSchemaMismatchError(`OpenClaw state database ${t} has a legacy operator approval schema; run openclaw doctor --fix to migrate it.`)}const dg=[`operator_approvals`,`cron_run_receipts`,`execution_decision_facts`,`skill_workshop_changes`];function withLegacyStateHeadLayout(e){return e.replace(/(CREATE TABLE IF NOT EXISTS session_state_heads \([\s\S]*?\n\) STRICT), WITHOUT ROWID;/u,`$1;`)}function withLegacyStateWriteIndexes(e){return`${e.replace(/ON state_leases\(owner\);/u,`ON state_leases(owner, updated_at DESC);`)}
CREATE INDEX IF NOT EXISTS idx_skill_usage_key
  ON skill_usage(skill_key, skill_file);
CREATE INDEX IF NOT EXISTS idx_acp_replay_events_session_seq
  ON acp_replay_events(session_id, seq);
`}const fg=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,pg={name:`state.external-ownership`,read(e){if(e===null)return null;if(f(e)&&e.version===1&&e.mode===`external`&&typeof e.managerId==`string`&&typeof e.claimedAt==`number`)return{version:1,mode:`external`,managerId:e.managerId,claimedAt:e.claimedAt}}};function parseExternalOwnership(e,t){let n;try{n=JSON.parse(e)}catch{throw new Sr(t,`reserved value is not valid JSON`)}let r=f(n)?n:void 0,i=r?Object.keys(r).toSorted().join(`,`):``,a=r?.managerId,s=r?.claimedAt;if(i!==`claimedAt,managerId,mode,version`||r?.version!==1||r?.mode!==`external`||typeof a!=`string`||!fg.test(a)||typeof s!=`number`||!Number.isSafeInteger(s)||s<0||s>864e13)throw new Sr(t,`reserved value does not match the version 1 external ownership contract`);return{version:1,mode:`external`,managerId:a,claimedAt:s}}function inspectOpenClawStateOwnershipFromDatabase(e,t,n=!1){try{if(!n&&!tableExists(e,`config_machine_state`))return null;let r=n||C(e)?`SELECT value_json FROM config_machine_state WHERE state_key = ? LIMIT 1`:`SELECT value_json FROM config_machine_state NOT INDEXED WHERE state_key = ? LIMIT 1`,i=e.prepare(r).get(`gateway.supervision`);if(!i)return null;if(typeof i.value_json!=`string`)throw new Sr(t,`reserved value is not text`);return parseExternalOwnership(i.value_json,t)}catch(e){throw normalizeOpenClawStateSchemaReadError(e,t)}}function assertOwnershipAllowsWrite(e,t,n){if(e&&!isGatewayExternallySupervised(n))throw new tn(t,e.managerId)}function assertOpenClawStateWriteAllowed(e){let t=E.resolve(e.databasePath);assertStateDatabaseAccessAllowed(t);let n=e.inspectOwnership?void 0:b(e.database,pg);if(n===void 0){let r=inspectOpenClawStateOwnershipFromDatabase(e.database,t,e.schemaReady);n=e.inspectOwnership?void 0:b(e.database,pg),n===void 0&&(n=r,w(e.database,pg,n))}assertOwnershipAllowsWrite(n,t,e.env??process.env)}function getOpenClawStatePredecessorSchema(e){let t=Xt;for(let[n,r]of[[40,withLegacyWorkerProvisionSource],[40,withLegacyStateV40Additions],[39,withLegacyWorkerRetention],[38,withLegacyRepositoryDiskAuthority],[37,withLegacyWorkerResourceReceipts],[36,withLegacyTemplateStateSchema],[35,withLegacyLocalWorkspaceCas],[31,withLegacyLocalWorkspaceManifests],[27,withLegacyStateWriteIndexes],[26,withLegacyStateHeadLayout]])e<n&&(t=r(t));return t}const mg=[...eo,`worker_session_tool_operations`,`worker_turn_tool_authorities`],hg=[`agent_database_leases`,`agent_deletion_journal`,`claw_cron_refs`,`claw_installs`,`claw_mcp_server_refs`,`claw_package_refs`,`claw_workspace_files`,`config_machine_state`,`cron_job_scratch`,`meeting_transcript_sessions`,`meeting_transcript_summaries`,`meeting_transcript_utterances`,`outbound_media_provenance`,`worker_environment_credentials`,`worker_transcript_commit_heads`,`worker_transcript_commits`,...mg],gg=Ph.map(({columnName:e,tableName:t})=>`${t}.${e}`),_g=Ih.map(({columnName:e,tableName:t})=>`${t}.${e}`);new Set(_g),[...Fh.map(({columnName:e,tableName:t})=>`${t}.${e}`),...Object.values(Lh).flat().map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)];const vg=[`worker_session_tool_operations`,`worker_turn_tool_authorities`];new Set(vg);const yg=[`idx_meeting_transcript_utterances_id`,`idx_operator_approvals_source_run_resolved`,`idx_worker_session_placements_environment`],bg=[`fleet_cells`],xg={excludedTables:bg,allowCompatibleAdditiveColumns:!0,allowedMissingTables:Za,allowedMissingColumns:_g,allowedColumnDefinitions:{"diagnostic_events.sequence":[`sequence INTEGER NOT NULL DEFAULT 0`],"template_package_refs.package_integrity":[`package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'`],"template_package_refs.updated_at_ms":[`updated_at_ms INTEGER NOT NULL DEFAULT 0`],"cron_jobs.enabled":[`enabled INTEGER NOT NULL DEFAULT 1`],"cron_jobs.name":[`name TEXT NOT NULL DEFAULT ''`],"cron_jobs.payload_kind":[`payload_kind TEXT NOT NULL DEFAULT 'message'`],"current_conversation_bindings.conversation_kind":[`conversation_kind TEXT NOT NULL DEFAULT 'channel'`],"operator_approvals.resolution_ref":[`resolution_ref TEXT`],"worker_environments.desktop_json":[`desktop_json TEXT`],"worker_environments.bootstrap_install_kind":[`bootstrap_install_kind TEXT`],"worker_environments.shared_host":[`shared_host INTEGER CHECK (shared_host IN (0, 1))`],"worker_environments.node_setup_id":[`node_setup_id TEXT`],"worker_environments.node_device_id":[`node_device_id TEXT`],"worker_session_placements.terminal_reason":[`terminal_reason TEXT`],"worker_session_placements.terminal_at_ms":[`terminal_at_ms INTEGER`]}},Sg={...xg,excludedTables:[...bg,...eo],excludedIndexes:to};function findMissingLazyStateStartupColumn(e){for(let{tableName:t,columnName:n}of Fh){if(!Sg.excludedTables?.includes(t))continue;let r=e(t);if(r&&!r.columns.some(e=>e.name===n))return{tableName:t,columnName:n}}}const Cg={...xg,allowedMissingTables:[...eo,...vg,...Za],allowedMissingIndexes:yg,allowedMissingColumns:gg},wg={agent:{30:[`trajectory_runtime_events`,`sqlite_stat1`,`sqlite_stat4`],27:[`context_engine_turn_outbox`,`sqlite_stat1`,`sqlite_stat4`],28:[`transcript_event_identities`,`session_windows`,`memory_entry_origins`,`sqlite_stat1`,`sqlite_stat4`],29:[`session_nodes`,`session_reactions`,`sqlite_stat1`,`sqlite_stat4`],31:[`memory_index_sources`,`memory_index_chunks`],32:[],33:[],34:[],35:[],36:[],37:[`session_transcript_cold_archive_chunks`],38:[],39:[`transcript_events`],40:[`session_creation_operations`],41:[`session_transcript_active_event_facts`],42:[`agent_tool_usage`]},state:{29:[...lg,`sqlite_stat1`,`sqlite_stat4`],23:[`meeting_transcript_sessions`,`worker_environments`],26:[`session_state_heads`,`sqlite_stat1`,`sqlite_stat4`],27:[`acp_replay_events`,`skill_usage`,`state_leases`,`sqlite_stat1`,`sqlite_stat4`],28:[`github_publication_requests`,`github_personal_publication_requests`,`github_repository_publication_requests`],30:[],31:[`local_workspace_projections`,`local_workspace_manifest_nodes`,`sqlite_stat1`,`sqlite_stat4`],32:[],33:[],34:[`config_machine_state`],35:[`local_workspace_projections`,`local_workspace_manifest_nodes`,`local_workspace_tree_packs`,`local_workspace_source_path_sets`],36:[`claw_installs`,`template_installs`,`claw_workspace_files`,`template_workspace_files`,`claw_package_refs`,`template_package_refs`,`claw_cron_refs`,`template_cron_refs`,`claw_mcp_server_refs`,`template_mcp_server_refs`,`agent_provenance`,`sqlite_stat1`,`sqlite_stat4`],37:[`worker_environments`],38:[`session_repository_workspaces`,`worker_workspace_pending_results`],39:[`worker_environments`],40:[`worker_environments`]}},Tg=[`sqlite_stat1`,`sqlite_stat4`];[...Tg],[...Fh.map(({tableName:e})=>e),...Object.values(Lh).flatMap(e=>e.map(([e])=>e)),...Tg],{...wg.agent},{...wg.state},[...Tg],[...Tg],[...Tg];function assertOpenClawStateDatabaseOwner(e,t){let n=getStateSchemaVersionAdmission(e);if(n&&getStateRuntimeSchemaAdmission(e))return{schema_version:n.userVersion};let r=tableExists(e,`schema_meta`),i;try{i=r?e.prepare(`SELECT role, schema_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`).get():void 0}catch(t){throw classifySqliteTableReadError(e,`schema_meta`,[`meta_key`,`role`,`schema_version`],t)}if(i?.role!==`global`){let e=typeof i?.role==`string`?i.role:`missing`;throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} has schema role ${e}; expected global. Run openclaw doctor --fix to inspect and repair its ownership.`)}return i}function assertOpenClawStateDatabaseForMaintenance(e,t,n){C(e)&&requireNativeDatabaseFile(`postgres`,`repair`);let r=assertSupportedStateSchemaVersion(e,t.pathname,t.schemaVersions);if((t.schemaVersions?.contentVersion??readStateSchemaContentVersion(e))!==40)throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} uses schema version ${r}; run openclaw doctor --fix before compacting it.`);let i=assertOpenClawStateDatabaseOwner(e,t);if(i?.schema_version!==r&&!adoptPeerPublishedStateSchemaVersion(e,i)){let e=typeof i?.schema_version==`number`?i.schema_version:`invalid`;throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} metadata schema version ${e} does not match ${r}; run openclaw doctor --fix before compacting it.`)}assertSqliteSchemaContains(e,t.pathname,Xt,Cg,n)}function assertOpenClawStateDatabaseVersionForMigration(e,t){let n=readSqliteUserVersion(e);if(readStateSchemaContentVersion(e)!==t.version)throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} uses schema version ${n}; expected ${t.version} before migrating it.`);let r=assertOpenClawStateDatabaseOwner(e,t);if(r?.schema_version!==n){let e=typeof r?.schema_version==`number`?r.schema_version:`invalid`;throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} metadata schema version ${e} does not match ${n}; repair the ownership metadata before migrating it.`)}assertSqliteSchemaTablesPresent(e,t.pathname,getOpenClawStatePredecessorSchema(t.version),{allowedMissingTables:[...t.version===5?hg:t.version<13?mg:eo,...Za]})}new Map(Xa.map(e=>[e,(t,n)=>assertOpenClawStateDatabaseVersionForMigration(t,{...n,version:e})])),[([...dg],[...dg.map(e=>`${e}.cursor_id`)]),...Kh];const Eg=[`audit_events`,`audit_identity_keys`].map(e=>({name:e,sql:S(tr(Xt,e))})),Dg=[`sequence`,`event_id`,`source_id`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`error_code`,`actor_type`,`actor_id`,`agent_id`,`session_key`,`session_id`,`run_id`,`tool_call_id`,`tool_name`],Og=[...Dg.flatMap(e=>e===`source_id`?[e,`schema_version`]:[e]),`direction`,`channel`,`conversation_kind`,`message_outcome`,`reason_code`,`delivery_kind`,`failure_stage`,`duration_ms`,`result_count`,`account_ref`,`conversation_ref`,`message_ref`,`target_ref`];function tableHasCanonicalColumns(e,t,n,r,i){let a=e.prepare(`PRAGMA table_info(${t})`).all(),s=a.filter(e=>Number(e.pk??0)>0);return a.length===n.length&&a.every((e,t)=>e.name===n[t])&&s.length===1&&s[0]?.name===r&&i.every(e=>a.some(t=>t.name===e&&Number(t.notnull??0)===1))}function tableSql(e,t){let n=e.prepare(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`).get(t);return typeof n?.sql==`string`?n.sql:void 0}function tableHasUniqueColumns(e,t,n){let r=e.prepare(`PRAGMA index_list(${t})`).all();return n.every(t=>r.some(n=>{if(Number(n.unique??0)!==1||typeof n.name!=`string`)return!1;let r=n.name.replaceAll(`'`,`''`),i=e.prepare(`PRAGMA index_info('${r}')`).all();return i.length===1&&i[0]?.name===t}))}function hasCanonicalAuditEventTable(e,t,n){let r=tableSql(e,`audit_events`)?.toLowerCase();return tableHasCanonicalColumns(e,`audit_events`,t,`sequence`,n)&&typeof r==`string`&&/\bsequence\s+integer\s+primary\s+key\s+autoincrement\b/.test(r)&&tableHasUniqueColumns(e,`audit_events`,[`event_id`,`source_id`])}function hasCanonicalAuditIdentityKeyTable(e){if(!tableExists(e,`audit_identity_keys`))return!1;let t=tableSql(e,`audit_identity_keys`)?.toLowerCase();return tableHasCanonicalColumns(e,`audit_identity_keys`,[`id`,`key_id`,`key`,`created_at`],`id`,[`id`,`key_id`,`key`,`created_at`])&&typeof t==`string`&&/\bcheck\s*\(\s*id\s*=\s*1\s*\)/.test(t)}function hasCanonicalAuditEventsSchema(e){let t=getAdmittedSqliteSchemaFacts(e);return t&&Eg.every(({name:e,sql:n})=>S(t.tableSql.get(e)??null)===n)?!0:tableExists(e,`audit_events`)?hasCanonicalAuditEventTable(e,Og,[`event_id`,`source_id`,`schema_version`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`actor_type`,`actor_id`])&&hasCanonicalAuditIdentityKeyTable(e):readSqliteUserVersion(e)<2&&!tableExists(e,`audit_identity_keys`)}function canRepairLegacyAuditEventsSchema(e){return!tableExists(e,`audit_events`)||tableExists(e,`audit_events_migration_new`)||tableHasColumn(e,`audit_events`,`schema_version`)?!1:(!tableExists(e,`audit_identity_keys`)||hasCanonicalAuditIdentityKeyTable(e))&&hasCanonicalAuditEventTable(e,Dg,[`event_id`,`source_id`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`actor_type`,`actor_id`,`agent_id`,`run_id`])}const kg=[`skill_curator_state`,`update_check_state`,`clawhub_promotions_feed_state`,`model_catalog_remote`,`voicewake_triggers`,`voicewake_routing_routes`,`voicewake_routing_config`,`onboarding_recommendations`,`cron_store_epochs`,`tui_last_sessions`,`sidebar_sections`,`node_host_config`,`web_push_vapid_keys`],Ag=`
  id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT,
  recipient_id TEXT,
  thread_id TEXT,
  sender_id TEXT,
  kind TEXT NOT NULL,
  sensitivity TEXT NOT NULL,
  source TEXT NOT NULL,
  status TEXT NOT NULL,
  reason TEXT NOT NULL,
  suggested_text TEXT NOT NULL,
  dedupe_key TEXT NOT NULL,
  confidence REAL NOT NULL,
  due_earliest_ms INTEGER NOT NULL,
  due_latest_ms INTEGER NOT NULL,
  due_timezone TEXT NOT NULL,
  source_message_id TEXT,
  source_run_id TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  attempts INTEGER NOT NULL,
  last_attempt_at_ms INTEGER,
  sent_at_ms INTEGER,
  dismissed_at_ms INTEGER,
  snoozed_until_ms INTEGER,
  expired_at_ms INTEGER,
  record_json TEXT NOT NULL
`;`${Ag.slice(1,-1)}`,`${Ag.slice(1,-1)}`,y(`state/db`),[...kg],[...dg],[...Rh.flat()],Xt.split(`
`).flatMap(e=>{let t=/^CREATE TABLE IF NOT EXISTS (\w+) \(/u.exec(e)?.[1];return t?[t]:[]});function assertCanonicalAgentDatabasesPrimaryKey(e,t){if(!tableExists(e,`agent_databases`))return;let n=tablePrimaryKeyColumns(e,`agent_databases`);if(n.length!==2||n[0]!==`agent_id`||n[1]!==`path`)throw new SqliteSchemaMismatchError(`OpenClaw state database ${t} has an unsupported agent database registry schema. Upgrades from pre-July-2026 state are no longer migrated; restore a backup produced by a July 2026 or newer release before retrying.`)}function assertCanonicalStateSchemaShape(e,t){if(assertCanonicalOperatorApprovalKinds(e,t),assertCanonicalAgentDatabasesPrimaryKey(e,t),!hasCanonicalAuditEventsSchema(e))throw canRepairLegacyAuditEventsSchema(e)?new OpenClawStateDatabaseSchemaMigrationRequiredError(`audit-events-v2`,t):new SqliteSchemaMismatchError(`OpenClaw state database ${t} has a noncanonical audit event schema that cannot be repaired automatically; restore the canonical audit_events shape before retrying.`)}function assertCurrentStateRuntimeSchema(e,t,n=createSqliteTableContractReader(e)){let r=findMissingLazyStateStartupColumn(n);r&&throwSqliteSchemaMismatches(t,[`missing column `+r.tableName+`.`+r.columnName]),assertCanonicalStateSchemaShape(e,t),assertOpenClawStateDatabaseForMaintenance(e,{pathname:t},n),assertSqliteSchemaContains(e,t,Xt,Sg,n)}function assertNoLegacyStateRuntimeRepair(e,t){if(hasLegacyCronRunLogs(e))throw new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-cron-run-logs`,t)}function assertExistingOpenClawStateRuntimeMetadata(e,t,n){if(getStateRuntimeSchemaAdmission(e)){let t=getStateSchemaVersionAdmission(e)?.userVersion;if(t!==void 0)return t}let r=assertSupportedStateSchemaVersion(e,t,void 0,void 0,n);if(readStateSchemaContentVersion(e)!==40)throw Error(`Existing shared-state database ${t} requires schema migration by its owning installation; run openclaw doctor --fix there before using it.`);let i;try{i=executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`schema_meta`).select([`role`,`schema_version`]).where(`meta_key`,`=`,`primary`).limit(1))}catch(t){throw classifySqliteTableReadError(e,`schema_meta`,[`meta_key`,`role`,`schema_version`],t)}if(i?.role!==`global`||i.schema_version!==r)throw Error(`Existing shared-state database ${t} has inconsistent ownership or schema metadata.`);return r}function assertExistingOpenClawStateRuntimeSchema(e,t,n,r,i=`runtime`){let a=getStateRuntimeSchemaAdmission(e)?getAdmittedSqliteSchemaFacts(e):void 0;if(a){assertOpenClawStateRuntimeIntegrity(e,t,a,n,r)?.();return}let s;runSqliteReadSnapshotSync(e,()=>{let a=assertExistingOpenClawStateRuntimeMetadata(e,t,i),c=readSqliteSchemaCookie(e);if(typeof c!=`number`)throw Error(`Existing shared-state database ${t} schema version is unavailable.`);s=assertOpenClawStateRuntimeIntegrity(e,t,{schemaVersion:c,userVersion:a},n,r),assertCurrentStateRuntimeSchema(e,t,createSqliteTableContractReader(e)),assertNoLegacyStateRuntimeRepair(e,t)},{operationLabel:`state.admission.existing-schema`}),s?.(),publishStateRuntimeSchemaAdmission(e,!0)}const jg=`NOT EXISTS (SELECT 1 FROM task_runs WHERE task_runs.task_id = task_delivery_state.task_id)`;function orphanRows(e){let t=e.prepare(`SELECT rowid, * FROM task_delivery_state
    WHERE ${jg} ORDER BY rowid`);return t.setReadBigInts(!0),t.iterate()}function encodeOrphanRow(e){if(typeof e.rowid!=`bigint`||typeof e.task_id!=`string`||e.requester_origin_json!==null&&typeof e.requester_origin_json!=`string`||e.last_notified_event_at!==null&&typeof e.last_notified_event_at!=`bigint`)throw Error(`Orphan task delivery values do not match the supported recovery contract.`);return`${JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}\n`}function assertOrphanTaskDeliveryRecoveryShape(e){let t=e.prepare(`PRAGMA table_xinfo(task_delivery_state)`).all(),n=[{cid:0,name:`task_id`,type:`TEXT`,notnull:1,dflt_value:null,pk:1,hidden:0},{cid:1,name:`requester_origin_json`,type:`TEXT`,notnull:0,dflt_value:null,pk:0,hidden:0},{cid:2,name:`last_notified_event_at`,type:`INTEGER`,notnull:0,dflt_value:null,pk:0,hidden:0}],r=e.prepare(`PRAGMA foreign_key_list(task_delivery_state)`).all(),i=[{id:0,seq:0,table:`task_runs`,from:`task_id`,to:`task_id`,on_update:`NO ACTION`,on_delete:`CASCADE`,match:`NONE`}],a=e.prepare(`SELECT 1 FROM sqlite_schema WHERE type = 'trigger' AND tbl_name = 'task_delivery_state'`).get();if(JSON.stringify(t)!==JSON.stringify(n)||JSON.stringify(r)!==JSON.stringify(i)||a)throw Error(`Orphan task delivery recovery refused an unrecognized table, foreign key, or trigger.`)}function assertKnownOrphanTaskDeliveryIntegrity(e){try{return assertSqliteIntegrity(e,`task delivery recovery database`),0}catch(e){if(e instanceof SqliteRepairableForeignKeyError)return e.repair.orphanCount;throw e}}function hasOrphanTaskDeliveryRows(e){return tableExists(e,`task_delivery_state`)&&tableExists(e,`task_runs`)&&!!e.prepare(`SELECT 1 FROM task_delivery_state WHERE ${jg} LIMIT 1`).get()}function hashOrphanRows(e){let t=Gr(`sha256`),n=0;for(let r of orphanRows(e))t.update(encodeOrphanRow(r)),n+=1;return{count:n,payloadSha256:t.digest(`hex`)}}function applyOrphanTaskDeliveryRecovery(e,t,n,r){if(!e.isTransaction)throw Error(`Orphan task delivery recovery requires the Doctor write transaction.`);assertOrphanTaskDeliveryRecoveryShape(e);let i=hashOrphanRows(e);if(i.count!==n.count||i.payloadSha256!==n.payloadSha256)throw Error(`Orphan task delivery snapshot does not preserve the current payload.`);let a=e.prepare(`DELETE FROM task_delivery_state WHERE ${jg}`).run();if(Number(a.changes)!==n.count)throw Error(`Orphan task delivery recovery removed an unexpected number of rows.`);return assertSqliteIntegrity(e,t),[`Preserved and recovered ${n.count} orphan task delivery rows; backup and row export: ${r}`]}function preserveOrphanTaskDeliveryRecoveryInProcess(e,t,n){let r=openNodeSqliteDatabase(e);try{r.exec(`PRAGMA journal_mode = DELETE;`),assertOrphanTaskDeliveryRecoveryShape(r);let i=assertKnownOrphanTaskDeliveryIntegrity(r);if(i===0)throw Error(`Orphan task delivery snapshot no longer contains orphan rows.`);let a=E.join(n,`database.sqlite`),s=flushAndHashFileSync(e);if(T.copyFileSync(e,a,T.constants.COPYFILE_EXCL),T.chmodSync(a,384),JSON.stringify(flushAndHashFileSync(a))!==JSON.stringify(s))throw Error(`Orphan task delivery backup verification failed.`);let c=E.join(n,`orphan-rows.jsonl`),l=T.openSync(c,`wx+`,384),u=Gr(`sha256`),d=0,f;try{for(let e of orphanRows(r)){let t=encodeOrphanRow(e);T.writeFileSync(l,t),u.update(t),d+=1}if(T.fsyncSync(l),f=u.digest(`hex`),hashFileDescriptorSync(l).sha256!==f)throw Error(`Orphan task delivery export verification failed.`)}finally{T.closeSync(l)}if(d!==i)throw Error(`Orphan task delivery export did not account for every foreign-key violation.`);return T.writeFileSync(E.join(n,`manifest.json`),JSON.stringify({format:`openclaw.task-delivery-recovery.v1`,state:`preserved-before-repair`,sourcePath:t,backup:{file:`database.sqlite`,...s,integrity:`structural-ok-known-orphans`},export:{file:`orphan-rows.jsonl`,...flushAndHashFileSync(c),count:i,integerEncoding:`decimal-string`},relation:`task_delivery_state.task_id -> task_runs.task_id`,createdAt:(/* @__PURE__ */ new Date()).toISOString()},null,2),{flag:`wx`,mode:384,flush:!0}),requireDirectorySync(gi(n),`Task delivery recovery directory`),requireDirectorySync(gi(E.dirname(n)),`Task delivery recovery parent`),{count:i,payloadSha256:f}}finally{r.close()}}function recoveryFailure(e,t){return Error(`Task delivery recovery failed without committing row removal${t?`; retained artifacts: ${t}`:``}: ${String(e)}`,{cause:e})}function recoverOrphanTaskDeliveryRows(e,t){if(!hasOrphanTaskDeliveryRows(e))return[];assertOpenClawStateDatabaseOwner(e,{pathname:t}),assertOrphanTaskDeliveryRecoveryShape(e);let n=assertKnownOrphanTaskDeliveryIntegrity(e);if(!e.isTransaction)throw Error(`Orphan task delivery recovery requires the Doctor write transaction.`);let r=prepareSqliteReadOnlyLocationSync(t),i;try{i=createPrivateSqliteTempDirectorySync(E.dirname(t),`openclaw-task-delivery-recovery-`);let a=preserveOrphanTaskDeliveryRecoveryInProcess(r.location,t,i);if(a.count!==n)throw Error(`Orphan task delivery snapshot changed before preservation.`);return assertOpenClawStateDatabaseOwner(e,{pathname:t}),applyOrphanTaskDeliveryRecovery(e,t,a,i)}catch(e){throw recoveryFailure(e,i)}finally{r.cleanup()}}const Mg=i(Symbol.for(`openclaw.managedStateTransactions`),()=>/* @__PURE__ */ new WeakSet);function runManagedStateTransaction(e,t,n){if(e.isTransaction&&!Mg.has(e))throw Error(`Cannot join an unmanaged shared-state transaction; enter through runOpenClawStateWriteTransaction before BEGIN.`);let transaction=()=>yt(e,()=>{let r=!e.isTransaction;r&&Mg.add(e);try{return n.singleStatement?runSqliteSingleStatementSync(e,t):runSqliteImmediateTransactionSync(e,t,n)}finally{r&&Mg.delete(e)}});return n.busyTimeoutMs===void 0||C(e)?transaction():runWithSqliteBusyTimeout(e,n.busyTimeoutMs,transaction)}function assertExistingOpenClawStateSchemaMetadata(e,t,n){let r=assertOpenClawStateDatabaseOwner(e,{pathname:t});if(n>=1&&r?.schema_version===n)return n;if(n>=1&&adoptPeerPublishedStateSchemaVersion(e,r))return 40;throw Error(`Existing-state schema metadata is inconsistent.`)}function assertExistingOpenClawStateSchema(e,t,n,r,i=`full`){let a=assertExistingOpenClawStateSchemaMetadata(e,t,assertSupportedStateSchemaVersion(e,t));return i===`quick`?assertSqliteIntegrity(e,t,{check:`quick`,tables:n===void 0?void 0:getCanonicalSqliteTableNames(n)}):assertStateDatabaseIntegrityOnce(e,t),n!==void 0&&assertSqliteSchemaContains(e,t,n,r),a}function runExistingOpenClawStateWriteTransaction(e,t,n){let r=prepareExistingOpenClawStateWriter(t,n),write=()=>{let i=createExistingOpenClawStateWriter(r,n);try{return i.run(e,t)}finally{i.close()}};return n.recoverTaskDeliveryOrphans?withStateDatabaseSchemaMaintenance({databasePath:r.pathname},write):write()}function prepareExistingOpenClawStateWriter(e,t){if(e.database||e.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let n=e.env??process.env,r=resolveDatabasePath({path:e.path,env:n});isExistingOpenClawStateSchema(r),t.recoverTaskDeliveryOrphans&&assertOpenClawStateSchemaRepairAllowed(r);let i=T.lstatSync(r);if(!i.isFile())throw Error(`Existing-state write requires a regular database file.`);return{env:n,pathname:r,original:i}}function createExistingOpenClawStateWriter({env:e,pathname:t,original:n},r){let assertSameFile=()=>{let e=T.lstatSync(t);if(!e.isFile()||e.dev!==n.dev||e.ino!==n.ino)throw Error(`Existing-state database generation changed.`)};if(assertSameFile(),xh.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t,e),isStatePostgres())return createExistingPostgresStateWriter(t,r,assertSameFile);let i=openTrackedStateDatabase(t,{existingOnly:!0,...r.recoverTaskDeliveryOrphans?{enableForeignKeyConstraints:!1}:{}}),a=createStateSchemaAdmission(`state.subset:${Gr(`sha256`).update(JSON.stringify([r.schemaSql,r.schemaCompatibility,r.integrityCheck])).digest(`hex`)}`,e=>typeof e==`number`?e:void 0,r.integrityCheck===void 0?`process`:void 0),s=r.initializeAdditiveSchema?createSqliteSchemaEnsurer(()=>r.schemaSql,{tables:getCanonicalSqliteTableNames(r.schemaSql),indexes:getCanonicalSqliteNamedIndexNames(r.schemaSql)}):void 0,c=!1,close=()=>{c=!0,clearNodeSqliteKyselyCacheForDatabase(i),closeTrackedStateDatabase(i)};return{run(e,n){if(c||!i.isOpen)throw Error(`Existing-state writer is closed.`);if(n.database||n.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let l=n.env??process.env;if(resolveDatabasePath({path:n.path,env:l})!==t)throw Error(`Existing-state writer cannot change its database path.`);assertSameFile();let u=isExistingOpenClawStateSchema(t),d=n.busyTimeoutMs??r.busyTimeoutMs??5e3;setSqliteBusyTimeout(i,d),admitStateSchemaFacts(i,t),!r.recoverTaskDeliveryOrphans&&r.integrityCheck===void 0&&assertStateDatabaseIntegrityOnce(i,t);let write=()=>runManagedStateTransaction(i,()=>{assertSameFile(),assertOpenClawStateWriteAllowed({database:i,databasePath:t,env:l});let n=a.get(i),c=n===void 0;u&&assertExistingOpenClawStateRuntimeSchema(i,t);let validate=()=>assertExistingOpenClawStateSchema(i,t,c&&r.initializeAdditiveSchema?void 0:r.schemaSql,r.schemaCompatibility,r.integrityCheck),d,f=[];if(r.recoverTaskDeliveryOrphans){try{validate()}catch(e){if(!(e instanceof SqliteRepairableForeignKeyError))throw e}f=recoverOrphanTaskDeliveryRows(i,t),d=validate()}else d=n??validate();c&&r.initializeAdditiveSchema&&(assertSqliteSchemaContains(i,t,r.schemaSql,{...r.schemaCompatibility,allowedMissingTables:getCanonicalSqliteTableNames(r.schemaSql)}),admitSqliteSchema(i),s?.(i),assertSqliteSchemaContains(i,t,r.schemaSql,r.schemaCompatibility)),c&&(admitSqliteSchema(i),a.publish(i,d));let p=e({db:i,path:t,recoveryChanges:f});return assertSameFile(),r.recoverTaskDeliveryOrphans&&assertSqliteIntegrity(i,t),p},{beginLockFailureReporting:r.beginLockFailureReporting,busyTimeoutMs:d,databaseLabel:t,operationLabel:r.operationLabel});return r.attributeUpdateWrite?runUpdateSqliteMigration(i,t,write,{close}):write()},assertSettled(){if(assertSameFile(),assertTransactionUsable(i),i.isOpen&&i.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`);i.isOpen&&Ct(i,`Existing-state writer`)},close}}function createExistingPostgresStateWriter(e,t,n){let r=withEngineStoreAdmission(()=>openExistingStatePostgresConnection(e));if(!r)throw Error(`Existing PostgreSQL state writer requires its selected engine`);let{db:i}=r.database,a=getCanonicalSqliteTableNames(t.schemaSql);return{run(r,s){if(!i.isOpen)throw Error(`Existing-state writer is closed.`);if(s.database||s.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let c=s.env??process.env;if(resolveDatabasePath({path:s.path,env:c})!==e)throw Error(`Existing-state writer cannot change its database path.`);let l=!1;return withEngineStoreAdmission(()=>withPostgresSchemaAdmissionRetry(i,()=>runManagedStateTransaction(i,()=>{n(),assertOpenClawStateWriteAllowed({database:i,databasePath:e,env:c});let s=requireStatePostgresPhysicalFacts(i).catalog;for(let e of a)if(t.initializeAdditiveSchema)ensureStatePostgresFragment(i,e);else if(!s.some(t=>t.kind===`table`&&t.table===e))throw Error(`Existing PostgreSQL state schema is missing ${e}`);l=!0;let u=r({db:i,path:e,recoveryChanges:[]});return n(),u},{databaseLabel:e,operationLabel:t.operationLabel,beginLockFailureReporting:t.beginLockFailureReporting}),()=>!l))},assertSettled(){if(n(),assertTransactionUsable(i),!i.isOpen)throw Error(`Existing-state writer retained a closed PostgreSQL connection`);if(i.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`)},close(){r.close()}}}const Ng={local_workspace_projections:[tr(Xt,`local_workspace_projections`),tr(Xt,`local_workspace_manifest_nodes`),tr(Xt,`local_workspace_tree_packs`),tr(Xt,`local_workspace_source_path_sets`)].join(`
`),user_profiles:`
CREATE TABLE IF NOT EXISTS user_profiles (
  id TEXT NOT NULL PRIMARY KEY,
  display_name TEXT,
  primary_github_account_id INTEGER,
  avatar BLOB,
  avatar_mime TEXT,
  avatar_sha256 TEXT,
  merged_into TEXT,
  role TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS user_profile_emails (
  email TEXT NOT NULL PRIMARY KEY,
  profile_id TEXT NOT NULL,
  binding_id TEXT,
  created_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_user_profile_emails_profile_id
  ON user_profile_emails(profile_id);

${tr(Xt,`user_profile_identities`)}
`,operator_approval_standing_grants:`
CREATE TABLE IF NOT EXISTS operator_approval_standing_grants (
  grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),
  minted_by_approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),
  cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),
  job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),
  operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),
  revoked_at_ms INTEGER,
  revoked_by TEXT,
  last_used_at_ms INTEGER,
  use_count INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding
  ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);

CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
  grant_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;
`,worker_environment_session_attachments:`
CREATE TABLE IF NOT EXISTS worker_environment_session_attachments (
  session_id TEXT PRIMARY KEY,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  session_lifecycle_revision TEXT,
  environment_id TEXT NOT NULL UNIQUE,
  generation INTEGER NOT NULL CHECK (generation >= 1),
  created_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER NOT NULL,
  closed_at_ms INTEGER,
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS worker_environment_session_attachments_session_key
ON worker_environment_session_attachments(agent_id, session_key);
`};function getOpenClawStateFeatureSchemaSql(e,t){return t===void 0&&Ng[e]?Ng[e]:e===`skill_library_entries`&&t===void 0?tr(Xt,e,{endMarker:`-- End profile-owned skill library.`,includeEndMarker:!1,errorMessage:`Canonical skill library schema missing.`}):tr(e===`user_profile_emails`?Ng.user_profiles:Xt,e,t)}Buffer.from(`302a300506032b6570032100`,`hex`),Buffer.from(`302e020100300506032b657004220420`,`hex`),Object.freeze(/* @__PURE__ */ `activity.ai-agents.appearance.approve.apps.ask.automation.automations.channels.chat.templates.communications.config.cron.custodian.dashboard.dashboards.debug.focus.infrastructure.lobsterdex.logs.mcp.meetings.memory-import.model-providers.model-setup.new.nodes.plugin.plugins.portals.profile.sessions.settings.share.skills.systems.terminal.usage.workboard.worktrees`.split(`.`));const Pg=_enum([`allowlist`,`full`,`deny`]),Fg=_enum([`always`,`off`,`on-miss`]),Ig=looseObject({security:Pg.optional(),ask:Fg.optional(),askFallback:Pg.optional(),autoAllowSkills:boolean().optional()});function normalizePersistedAllowlistSource(e){return e===`allow-always`?e:void 0}const Lg=looseObject({pattern:string().refine(e=>e.trim().length>0),id:string().min(1),source:literal$1(`allow-always`).optional(),commandText:never().optional(),argPattern:string().optional(),lastUsedAt:number().finite().optional(),lastUsedCommand:string().optional(),lastResolvedPath:string().optional()}),Rg=union([string().trim().min(1),Lg.extend({id:string().optional(),source:string().transform(normalizePersistedAllowlistSource).optional(),commandText:string().optional()})]).transform(e=>typeof e==`string`?{pattern:e}:e);function createExecApprovalsSchema(e,t){let n=Ig.extend({allowlist:array(e).optional(),mcpTools:array(looseObject({server:string().refine(e=>e.trim().length>0),tool:string().refine(e=>e.trim().length>0),source:literal$1(`allow-always`),addedAt:number().finite().nonnegative(),lastUsedAt:number().finite().nonnegative().optional()})).optional()}),r=unknown().refine(e=>!f(e)||!Object.hasOwn(e,`__proto__`)).pipe(record(string(),n)).refine(e=>t||!Object.hasOwn(e,`default`));return looseObject({version:literal$1(1),socket:looseObject({path:string().optional(),token:string().optional()}).optional(),defaults:Ig.optional(),agents:r.optional()})}createExecApprovalsSchema(Lg,!1),createExecApprovalsSchema(Rg,!0),i(Symbol.for(`openclaw.clientCredentialCustody`),()=>/* @__PURE__ */ new Set),i(Symbol.for(`openclaw.clientCredentialAdmittedFiles`),()=>/* @__PURE__ */ new Map,e=>e.clear()),[.../* @__PURE__ */ new Set([26985,20859,4283649346,4266872130])],y(`infra/sqlite-wal`);const zg=i(Symbol.for(`openclaw.sessionControllerCleanupContext`),()=>({}));function runWithSessionControllerCleanup(e){return zg.exit?zg.exit(e):e()}const Bg=y(`gateway/scheduler`),Vg={now:()=>Date.now(),monotonicNow:()=>performance.now(),arm:(e,t)=>{let n=setTimeout(()=>{ve(`scheduler:wake`,()=>{e()})},t);return n.unref(),()=>clearTimeout(n)}};function nextMaintenanceSlot(e,t,n){return e+(Math.floor(Math.max(0,t-e)/n)+1)*n}var GatewayScheduler=class{constructor(e={}){this.jobs=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.dispatching=!1,this.fenced=!1,this.controller=new AbortController,this.clock=e.clock??Vg}get signal(){return this.controller.signal}now(){return this.clock.now()}get nextWakeAtMs(){let e=this.now(),t=this.clock.monotonicNow(),n=null;for(let r of this.jobs.values()){if(r.running)continue;let i=e+this.remaining(r,e,t);n=n===null?i:Math.min(n,i)}return n}scope(){let e=new AbortController,t={signal:AbortSignal.any([this.signal,e.signal]),jobs:/* @__PURE__ */ new Set},beginClose=()=>{e.abort(),Nr(e.signal.reason),Nr(t.signal.reason);for(let e of t.jobs)this.cancel(e)},close=()=>{beginClose();let e=[...t.jobs].flatMap(e=>e.running??[]);return e.length>0?Promise.all(e).then(()=>void 0):void 0};return{signal:t.signal,now:()=>this.now(),schedule:e=>this.scheduleOwned(e,t),beginClose,close,stop:async()=>{await close()}}}schedule(e){return this.scheduleOwned(e)}scheduleOwned(e,t){let n=`delayMs`in e,r=this.now(),i=n?r+e.delayMs:e.atMs,a=e.phase===`maintenance`?Math.max(r,Math.floor(i/1e4)*1e4):i;if(!Number.isFinite(a)||e.everyMs!==void 0&&(!Number.isFinite(e.everyMs)||e.everyMs<=0))throw Error(`Invalid Gateway schedule: ${e.id}`);let s=this.fenced||t?.signal.aborted===!0,c=s?void 0:this.jobs.get(e.id),l={id:e.id,diagnosticName:`scheduler:${e.id.startsWith(`maintenance:`)?e.id.split(`:`).slice(0,3).join(`:`):e.id.split(/[:/]/u,1)[0]}`,run:e.run,everyMs:e.everyMs,phase:e.phase,atMs:a,elapsedAtMs:e.phase!==`maintenance`&&(n||e.everyMs!==void 0)?this.clock.monotonicNow()+Math.max(0,a-r):void 0,context:runOutsideAsyncWorkScope(()=>runWithSessionControllerCleanup(()=>D.snapshot())),cancelled:s,owner:t};e.mode===`earliest`&&c&&!c.running&&(l.atMs=Math.min(l.atMs,c.atMs),e.phase!==`maintenance`&&c.elapsedAtMs!==void 0&&(l.elapsedAtMs=l.elapsedAtMs===void 0?c.elapsedAtMs:Math.min(l.elapsedAtMs,c.elapsedAtMs)));let cancel=()=>this.cancel(l);return s||(t?.jobs.add(l),this.jobs.set(l.id,l),c&&this.cancel(c),this.arm()),{get atMs(){return l.atMs},cancel,stop:async()=>{cancel(),await l.running}}}cancel(e){e.cancelled=!0,e.running||e.owner?.jobs.delete(e),this.jobs.get(e.id)===e&&(this.jobs.delete(e.id),this.arm())}fence(){this.fenced=!0,this.cancelTimer?.(),this.cancelTimer=void 0;for(let e of this.jobs.values())this.cancel(e);this.jobs.clear()}beginClose(){this.fence(),this.controller.abort(),Nr(this.controller.signal.reason)}async stop(){this.beginClose(),await Promise.all(this.pending)}remaining(e,t,n){let r=e.atMs-t;return e.elapsedAtMs===void 0?r:Math.min(r,e.elapsedAtMs-n)}arm(){if(this.fenced||this.dispatching)return;this.cancelTimer?.(),this.cancelTimer=void 0;let e=this.nextWakeAtMs;if(e!==null){let n=this.now(),r=Math.min(2147483647,Math.max(0,Math.ceil(e-n)));this.cancelTimer=t(()=>this.clock.arm(()=>this.wake(n+r),r))}}wake(e){if(this.cancelTimer=void 0,this.fenced)return;let t=this.now(),n=this.clock.monotonicNow(),r=[...this.jobs.values()].filter(e=>!e.running&&this.remaining(e,t,n)<=0).toSorted((e,r)=>this.remaining(e,t,n)-this.remaining(r,t,n)),i;t-e>6e4&&Bg.debug(`late wake by ${t-e}ms; coalescing ${r.length} due jobs`),this.dispatching=!0;try{for(let e of r){if(this.fenced||e.cancelled||e.owner?.signal.aborted||this.jobs.get(e.id)!==e)continue;e.everyMs===void 0&&this.jobs.delete(e.id);let t=this.run(e);t&&(i??=[]).push(t)}}finally{this.dispatching=!1,this.arm()}return i?Promise.all(i).then(()=>void 0):void 0}run(e){Bg[e.everyMs===void 0?`debug`:`trace`](`running ${e.id}`);let t=p(),n=new so;e.running=t.promise,this.pending.add(t.promise);let finish=()=>{e.running=void 0,this.pending.delete(t.promise),e.everyMs!==void 0&&!e.cancelled&&!this.fenced?e.phase===`maintenance`?(e.atMs=Math.floor(e.atMs/1e4)*1e4,e.atMs=nextMaintenanceSlot(e.atMs,this.now(),e.everyMs)):(e.atMs=this.now()+e.everyMs,e.elapsedAtMs=this.clock.monotonicNow()+e.everyMs):e.owner?.jobs.delete(e),t.resolve(),this.arm()},r;try{r=e.context(()=>ve(e.diagnosticName,()=>n.run(e.run)))}catch(t){Bg.error(`${e.id} failed: ${String(t)}`)}if(!r&&!n.hasPendingWork)finish();else return Promise.resolve(r).catch(t=>Bg.error(`${e.id} failed: ${String(t)}`)).then(()=>so.runWhenAllIdle(()=>[n],()=>n.drain())).finally(finish),t.promise}};i(Symbol.for(`openclaw.sqliteWalCheckpointListeners`),()=>/* @__PURE__ */ new Set),new Int32Array(new SharedArrayBuffer(4)),y(`infra/sqlite-wal`),new GatewayScheduler,new Set([{id:`openclaw`,kind:`system`},{id:`crestodian`,kind:`system`}].map(e=>normalizeAgentId(e.id))),c(Symbol.for(`openclaw.agentDirPreparedPaths`),e=>{for(let t of e.values())t.close();e.clear()},`shared-state`);function resolveDefaultAgentWorkspaceDir(e=process.env,t=Jr.homedir){let n=e.OPENCLAW_WORKSPACE_DIR?.trim();if(n)return E.resolve(n);if(e.OPENCLAW_STATE_DIR?.trim())return E.join(ze(e,t),`workspace`);let r=$e(e,t),i=e.OPENCLAW_PROFILE?.trim();return i&&a(i)!=="default"?E.join(Xe(i,e,t),`workspace`):E.join(r,`.openclaw`,`workspace`)}resolveDefaultAgentWorkspaceDir(),y(`config`);function createDedupeCache(e){let t=je(e.ttlMs,0),n=je(e.maxSize,0),r=/* @__PURE__ */ new Map,i=1/0,a=-1/0,s=!0,prune=e=>{let a=t>0?e-t:void 0;if(a!==void 0&&a>=i){i=1/0;for(let[e,t]of r)if(t.recordedAt<=a)r.delete(e);else if(t.recordedAt<i&&(i=t.recordedAt,s))break}n<=0?(r.clear(),i=1/0):Ue(r,n)},hasUnexpired=(e,n,i)=>{let a=r.get(e);return a?t>0&&n-a.recordedAt>=t?(r.delete(e),!1):(i&&(a.recordedAt=n,r.delete(e),r.set(e,a)),!0):!1};return{check:(e,n,c)=>{if(!e)return!1;let l=n??Date.now();return t>0&&(l<i&&(i=l),s&&(s=l>=a,a=l)),hasUnexpired(e,l,!0)?!0:(r.set(e,{recordedAt:l,...c?{ownerToken:c}:{}}),prune(l),!1)},peek:(e,t=Date.now())=>e?hasUnexpired(e,t,!1):!1,delete:(e,t)=>{e&&(t&&r.get(e)?.ownerToken!==t||r.delete(e))},clear:()=>{r.clear(),i=1/0,a=-1/0,s=!0},size:()=>r.size}}y(`state/db`),createDedupeCache({ttlMs:0,maxSize:4096}),Object.freeze([[`client`,`credentials.sqlite`],[`control`,`services.sqlite`]]);const Hg=i(Symbol.for(`openclaw.pluginSharedStateAdmission`),()=>({}));function getPluginSharedStateResourceHost(){return Hg.resolveHost?.()}function runPluginSharedStateWork(e){let t=getPluginSharedStateResourceHost();return t?t.trackSharedStateWork(e):e()}i(Symbol.for(`openclaw.postgresStateReadSnapshot`),()=>new D);const Ug=i(Symbol.for(`openclaw.sqliteDatabaseAdmissionTurns`),()=>({pending:/* @__PURE__ */ new Map,discovery:Promise.resolve(),discovering:0})),Wg=new we(Symbol.for(`openclaw.sqliteDatabaseAdmissionTurnContext`));function hasPublishedSchema(e){let t=gr(e);return t!==void 0&&Jn(t)}function reserveAdmissionTurn(e){if(e.size===0)return;let t=new Set([...e].flatMap(e=>Ug.pending.get(e)??[])),{promise:n,resolve:r}=p();for(let t of e)Ug.pending.set(t,n);return{ready:Promise.all(t),release:()=>{for(let t of e)Ug.pending.get(t)===n&&Ug.pending.delete(t);r()}}}function prepareAdmissionTurn(e,t,n,r=()=>{}){Ug.discovering++;let i=Ug.discovery.then(async()=>{try{r();let i=typeof n==`function`?await n():n;r();let a=/* @__PURE__ */ new Set;for(let e of t){let t=i?.physicalFamilies?e:await Ar(e);r(),a.add(`family:${t}`)}let s=new Map(i?.readIdentities);for(let t of e){if((typeof n==`function`||!i?.readIdentities?.has(t))&&hasPublishedSchema(t))continue;let e;try{e=await Ln({location:t,identity:i?.readIdentities?.get(t),assertCurrent:r})}catch(e){if(!ie(e))throw e}let c=e?.canonicalPath??await Ar(t);r(),a.add(`path:${c}`),e&&(s.set(t,e),a.add(`${e.key}:${e.birthtime??``}`)),e&&Jn(e)||a.add(`family:${E.dirname(c)}`)}return{turn:reserveAdmissionTurn(a),prepared:{readIdentities:s}}}finally{Ug.discovering--}});return Ug.discovery=i.then(()=>{},()=>{}),i}function runWithSqliteDatabaseAdmissionTurn(e,t,n=[],r,i,a){if(Wg.getStore()?.active||!Xn())return typeof i==`function`?i().then(t):t(i);let run=(e,n)=>{let r={active:!0};return Wg.run(r,async()=>{try{return await t(n)}finally{r.active=!1,e?.release()}})};return!Ug.discovering&&!i&&!n.length&&e.every(hasPublishedSchema)?run(void 0,void 0):prepareAdmissionTurn(e,n,i,()=>{r?.throwIfAborted(),a?.()}).then(({turn:e,prepared:t})=>e?se(e.ready,r,e=>e.reason).then(()=>run(e,t),t=>{throw e.ready.then(e.release),t}):run(void 0,t))}y(`state/db`),i(Symbol.for(`openclaw.disposableStateReads`),()=>new D),i(Symbol.for(`openclaw.stateSnapshotReads`),()=>new D),i(Symbol.for(`openclaw.synchronousStateReadSnapshots`),()=>({current:void 0})),y(`state/db`);const Gg=[`auth`,`auth_permanent`,`format`,`rate_limit`,`overloaded`,`billing`,`server_error`,`route_unavailable`,`timeout`,`tls_certificate`,`context_overflow`,`model_not_found`,`session_expired`,`empty_response`,`no_error_details`,`unclassified`,`unknown`];function closedObject(e){let t=bi.Object(e,{additionalProperties:!1});return Object.defineProperty(t,"~openclawClosedObjectIdentity",{value:Symbol(`closedObject`)}),t}const Kg=bi.Integer({minimum:0,maximum:864e13});function stringLiteralUnion(e){let t=e.map(e=>bi.Literal(e));return bi.Union(t)}const qg=stringLiteralUnion([`progress`,`done`,`blocked`,`needs_attention`]);bi.Union([bi.Literal(`no_change`),qg]);const Jg=bi.String({minLength:1,maxLength:2e3,pattern:`\\S`}),Yg=closedObject({outcome:qg,summary:Jg}),Xg=bi.Union([closedObject({outcome:bi.Literal(`no_change`),summary:bi.Optional(Jg)}),Yg]);closedObject({...Yg.properties,atMs:Kg});function parseAutomationResult(e){if(!f(e))return;let t=typeof e.summary==`string`?{...e,summary:e.summary.trim()}:{...e};return yi.Check(Xg,t)?t:void 0}const Zg=_enum([`ok`,`error`,`skipped`]),Qg=_enum([`succeeded`,`failed`,`unknown`]),$g=_enum([`delivered`,`not-delivered`,`unknown`,`not-requested`]),e_=string().optional().catch(void 0),t_=string().refine(e=>e.trim().length>0).optional().catch(void 0),n_=unknown().optional().transform(e=>normalizeTimestamp(e)),r_=unknown().optional().transform(e=>Je(e,{min:0})),i_=object({input_tokens:r_,output_tokens:r_,total_tokens:r_,cache_read_tokens:r_,cache_write_tokens:r_}).transform(e=>Object.values(e).some(e=>e!==void 0)?e:void 0).optional().catch(void 0),a_=looseObject({status:$g,delivered:boolean().optional().catch(void 0),error:e_}).transform(({status:e,delivered:t,error:n})=>({status:e,...t===void 0?{}:{delivered:t},...n===void 0?{}:{error:n}})).optional().catch(void 0);looseObject({action:literal$1(`finished`),jobId:string().refine(e=>e.trim().length>0),ts:unknown().transform(e=>normalizeTimestamp(e)).pipe(number()),status:Zg.optional().catch(void 0),completionStatus:Qg.optional().catch(void 0),error:e_,errorReason:_enum(Gg).optional().catch(void 0),summary:e_,result:unknown().optional().transform(parseAutomationResult),runId:t_,diagnostics:unknown().optional(),runAtMs:n_,durationMs:r_,nextRunAtMs:n_,triggerFired:boolean().optional().catch(void 0),model:t_,provider:t_,usage:i_,delivered:boolean().optional().catch(void 0),deliveryStatus:$g.optional().catch(void 0),deliveryError:e_,deliverySuppressionReason:_enum([`empty`,`silent`,`heartbeat`,`channel_transform`]).optional().catch(void 0),failureNotificationDelivery:a_,delivery:custom(isJsonObject).optional().catch(void 0),sessionId:t_,sessionKey:t_});function isJsonObject(e){return f(e)}function normalizeTimestamp(e){return Je(e,{min:0,max:Ce})}y(`state/db`);function isNodeWorkerTerminalState(e){return e===`completed`||e===`failed`||e===`interrupted`||e===`cancelled`}function validateNodeWorkerContainerIdentity(e){if(e.engine!==`docker`&&e.engine!==`podman`)throw Error(`node worker container engine must be docker or podman`);if(!/^[a-f0-9]{64}$/u.test(e.containerId))throw Error(`node worker container id must contain exactly 64 lowercase hexadecimal digits`);if(!/^[a-f0-9]{64}$/u.test(e.engineTarget))throw Error(`node worker container engine target must contain exactly 64 lowercase hexadecimal digits`)}function containerIdentity(e){if(e==null)return null;let t;try{t=JSON.parse(e)}catch{throw Error(`invalid node worker container identity`)}if(!f(t)||Object.keys(t).length!==3||t.engine!==`docker`&&t.engine!==`podman`||typeof t.containerId!=`string`||typeof t.engineTarget!=`string`)throw Error(`invalid node worker container identity`);let n={engine:t.engine,containerId:t.containerId,engineTarget:t.engineTarget};return validateNodeWorkerContainerIdentity(n),n}function nodeWorkerLaunchReceiptFromRow(e){if(e.state!==`pending`&&e.state!==`running`&&!isNodeWorkerTerminalState(e.state))throw Error(`invalid node worker launch state ${e.state}`);let t=containerIdentity(e.container_json),n=e.cleanup_mode??null;if(e.scope_kind!=null&&(e.scope_kind!==`linux-subreaper`||n!==`owned-anchor`))throw Error(`invalid node worker process scope`);if(n!==null&&n!==`process-group`&&n!==`owned-anchor`)throw Error(`invalid node worker cleanup mode`);return{launchId:e.launch_id,planHash:e.plan_hash,gatewayNamespace:e.gateway_namespace,environmentId:e.environment_id,sessionId:e.session_id,ownerEpoch:e.owner_epoch,placementGeneration:e.placement_generation,runId:e.run_id,state:e.state,supervisor:{pid:e.supervisor_pid,startTime:e.supervisor_start_time},...e.boot_id?{bootId:e.boot_id}:{},worker:e.worker_pid===null||e.worker_start_time===null?null:{pid:e.worker_pid,startTime:e.worker_start_time},workerCleanupMode:n===`owned-anchor`&&e.boot_id?.startsWith(`win32:`)?`windows-job`:e.scope_kind===`linux-subreaper`?`linux-subreaper`:n,...e.scope_kind===`linux-subreaper`?{workerDescendantsReaped:e.descendants_reaped===1}:{},workerLineageSettled:e.lineage_settled===1,...t?{container:t}:{},resultJson:e.result_json,errorText:e.error_text,completedAtMs:e.completed_at_ms,createdAtMs:e.created_at_ms,updatedAtMs:e.updated_at_ms}}new Map([`node_worker_launches`,`node_worker_launch_boots`,`node_worker_launch_containers`,`node_worker_launch_cleanup`,`node_worker_launch_process_scopes`].map(e=>[e,createSqliteSchemaEnsurer(()=>getOpenClawStateFeatureSchemaSql(e,{endMarker:e===`node_worker_launches`?`
  WHERE completed_at_ms IS NOT NULL;`:void 0}),{tables:[e],indexes:e===`node_worker_launches`?[`idx_node_worker_launches_terminal_completed`]:[]})]));function query(e){return getNodeSqliteKysely(e)}function hasLaunchTable(e,t,n){return t?t.tables.has(n):tableExists(e,n)}function selectLaunchRows(e,t){return query(e).selectFrom(`node_worker_launches`).selectAll(`node_worker_launches`).$if(hasLaunchTable(e,t,`node_worker_launch_boots`),e=>e.leftJoin(`node_worker_launch_boots`,`node_worker_launch_boots.launch_id`,`node_worker_launches.launch_id`).select(`node_worker_launch_boots.boot_id`)).$if(hasLaunchTable(e,t,`node_worker_launch_containers`),e=>e.leftJoin(`node_worker_launch_containers`,`node_worker_launch_containers.launch_id`,`node_worker_launches.launch_id`).select(`node_worker_launch_containers.container_json`)).$if(hasLaunchTable(e,t,`node_worker_launch_cleanup`),e=>e.leftJoin(`node_worker_launch_cleanup`,`node_worker_launch_cleanup.launch_id`,`node_worker_launches.launch_id`).select([`node_worker_launch_cleanup.cleanup_mode`,`node_worker_launch_cleanup.lineage_settled`])).$if(hasLaunchTable(e,t,`node_worker_launch_process_scopes`),e=>e.leftJoin(`node_worker_launch_process_scopes`,`node_worker_launch_process_scopes.launch_id`,`node_worker_launches.launch_id`).select([`node_worker_launch_process_scopes.scope_kind`,`node_worker_launch_process_scopes.descendants_reaped`]))}function readRow(e,t,n){return executeSqliteQueryTakeFirstSync(e,selectLaunchRows(e,n).where(`node_worker_launches.launch_id`,`=`,t))}function readNodeWorkerLaunchReceipt(e,t){let n=getAdmittedSqliteSchemaFacts(e);if(!hasLaunchTable(e,n,`node_worker_launches`))return;let r=readRow(e,t,n);return r?nodeWorkerLaunchReceiptFromRow(r):void 0}function requireNodeWorkerProcessIdentity(e){let t=m(e);if(t===null)throw Error(`cannot establish PID-reuse-safe identity for process ${e}`);return{pid:e,startTime:t}}function inspectNodeWorkerProcessIdentity(e){let t=m(e.pid);return t===null?h(e.pid)?`dead`:`unknown`:t===e.startTime?h(e.pid)?`dead`:`live`:`reused`}var o_=/* @__PURE__ */ __exportAll({recordNodeWorkerDescendantsReaped:()=>recordNodeWorkerDescendantsReaped,recordNodeWorkerLineageSettled:()=>recordNodeWorkerLineageSettled});const s_=[`node_worker_launches`,`node_worker_launch_cleanup`].map(e=>getOpenClawStateFeatureSchemaSql(e)).join(`
`);function recordNodeWorkerLineageSettled(e){return recordCompletion(e,`lineage`)}function recordNodeWorkerDescendantsReaped(e){return recordCompletion(e,`descendants`)}function recordCompletion(e,t){let n=requireNodeWorkerProcessIdentity(process.pid);return runExistingOpenClawStateWriteTransaction(({db:r})=>{let i=readNodeWorkerLaunchReceipt(r,e.launchId);if(!i||i.state!==`running`||i.planHash!==e.planHash||i.workerCleanupMode!==(t===`descendants`?`linux-subreaper`:`owned-anchor`)||i.container||i.supervisor.pid!==e.supervisor.pid||i.supervisor.startTime!==e.supervisor.startTime||i.worker?.pid!==n.pid||i.worker.startTime!==n.startTime||inspectNodeWorkerProcessIdentity(n)!==`live`)return!1;let a=getNodeSqliteKysely(r);return(t===`descendants`?executeSqliteQuerySync(r,a.updateTable(`node_worker_launch_process_scopes`).set({descendants_reaped:1}).where(`launch_id`,`=`,e.launchId).where(`scope_kind`,`=`,`linux-subreaper`)):executeSqliteQuerySync(r,a.updateTable(`node_worker_launch_cleanup`).set({lineage_settled:1}).where(`launch_id`,`=`,e.launchId).where(`cleanup_mode`,`=`,`owned-anchor`))).numAffectedRows===1n},{path:e.databasePath,env:{...process.env,OPENCLAW_SUPERVISOR_MODE:e.externallySupervised?`external`:void 0}},{schemaSql:s_+(t===`descendants`?`
`+getOpenClawStateFeatureSchemaSql(`node_worker_launch_process_scopes`):``),operationLabel:`node-worker-launch.`+t+`-settled`})}export{classifyOpenClawArgv as $,hh as A,retainSqliteWriteAdmissionService as B,recordOpenClawStateDatabaseOpenFailure as C,registerOpenClawStatePathCacheInvalidation as D,registerOpenClawStatePathAsyncResource as E,getExistingOpenClawStateSchemaPath as F,createSqliteWorkerTransferOwner as G,retainOpenClawStateWorkerErrorPayload as H,isExistingOpenClawStateSchema as I,resolveQuarantineStorePath as J,createSqliteWorkerTransferReceiver as K,Bm as L,_h as M,captureSqliteWorkerStateContext as N,releaseOpenClawStateDatabaseCustody as O,sqliteWorkerRequestBytes as P,assertAppContainerSpawnSupported as Q,acquireStateDatabaseSchemaLease as R,dh as S,registerOpenClawStateDatabaseLifecycleListener as T,no as U,hydrateOpenClawStateWorkerError as V,findOpenClawStateDatabaseFailure as W,createStateWorkerMemoryPressureSubscription as X,Pa as Y,getOpenClawDatabaseMaintenanceScope as Z,joinOpenClawStateDatabaseBorrowers as _,gh as a,getRootOptionAwareCommandPath as at,prepareOpenClawStateDatabaseRemoval as b,clearOpenClawStateDatabaseOpenFailure as c,_usingCtx as ct,closeOpenClawStateDatabaseByPath as d,classifyOpenClawEntrypointPath as et,closeOpenClawStateDatabaseByPathAsync as f,isOpenClawStateDatabaseOpen as g,getOpenClawStateDatabaseTerminalFailureAsync as h,assertPublishedOpenClawStateDatabaseLifecycle as i,isContainerEnvironment as it,lh as j,requireOpenClawStateDatabaseIdentity as k,closeOpenClawStateDatabase as l,closeOpenClawStateDatabaseWorkersByPathAsync as m,runWithSqliteDatabaseAdmissionTurn as n,readProcessWorkingDirectories as nt,yh as o,isUpdateCommandArgv as ot,closeOpenClawStateDatabaseForTest as p,StateDatabaseReadAdmissionInvalidatedError as q,runPluginSharedStateWork as r,recordNodeWorkerDescendantsReaped,recordNodeWorkerLineageSettled,referencesRetainedArtifact as rt,bh as s,rewriteUpdateFlagArgv as st,o_ as t,readProcessPackageIdentity as tt,closeOpenClawStateDatabaseAsync as u,xh as v,vh as w,publishOpenClawStateDatabaseWorkerAdmission as x,prepareOpenClawStateCachedRead as y,captureStateDatabaseAccess as z};