UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6,967 lines • 1.78 MB
import{createRequire as e}from"node:module";import{EventEmitter as t,once as n}from"node:events";import r,{accessSync as i,chmodSync as a,closeSync as s,constants as c,existsSync as l,fstatSync as u,mkdirSync as d,readFileSync as f,readdirSync as p,realpathSync as m,statSync as h,unlinkSync as g,writeFileSync as v,default as y}from"node:fs";import{Socket as b}from"node:net";import{pipeline as x}from"node:stream";import ee,{execFileSync as te,spawn as ne,spawnSync as re}from"node:child_process";import{isatty as ie}from"node:tty";import{ProcSafeError as ae}from"@openclaw/proc-safe/errors";import{readProcessAncestry as oe,readProcessIdentity as se}from"@openclaw/proc-safe/identity";import S,{basename as ce,dirname as le,join as ue,posix as de}from"node:path";import{listProcesses as fe,readProcessCommand as pe}from"@openclaw/proc-safe/inspect";import me,{isDeepStrictEqual as he,toUSVString as ge,types as _e}from"node:util";import{Chalk as ve}from"chalk";import{createHash as ye,createHmac as be,hash as xe,randomUUID as Se}from"node:crypto";import{AsyncLocalStorage as C,AsyncResource as Ce}from"node:async_hooks";import{performance as we}from"node:perf_hooks";import{appendRegularFile as Te,appendRegularFileSync as Ee,canUseRootFileOpen as De,copyRootFileSync as Oe,createDirectorySync as ke,openRootFileSync as Ae,readFileDescriptorBoundedSync as je,readFileWindowFullySync as Me,resolvePathViaExistingAncestorSync as Ne,sameFileContentsSync as Pe,sameFileIdentity as Fe}from"@openclaw/fs-safe/advanced";import{fileURLToPath as Ie,pathToFileURL as Le}from"node:url";import{FsSafeError as Re}from"@openclaw/fs-safe/errors";import{hasNodeErrorCode as w,isNodeError as ze,isPathInside as Be,isPathInside as Ve,isPathInside as He,normalizeWindowsPathForComparison as Ue,normalizeWindowsPathForComparison as We}from"@openclaw/fs-safe/path";import T,{mkdtemp as Ge,realpath as Ke,rm as qe,stat as Je,default as Ye}from"node:fs/promises";import Xe,{availableParallelism as Ze,tmpdir as Qe}from"node:os";import{channel as $e}from"node:diagnostics_channel";import{BroadcastChannel as et,MessageChannel as tt,MessagePort as nt,Worker as rt,getEnvironmentData as it,isMainThread as at,isMarkedAsUntransferable as ot,receiveMessageOnPort as st,setEnvironmentData as ct,threadId as E,workerData as lt}from"node:worker_threads";import{Logger as ut}from"tslog";import{setImmediate as dt,setTimeout as ft}from"node:timers/promises";import{readRootJsonObjectSync as pt}from"@openclaw/fs-safe/json";import{parse as mt}from"semver";import{isNativeError as ht,isPromise as gt,isProxy as _t}from"node:util/types";import{sha256FileSync as vt,syncDirectorySync as yt}from"@openclaw/fs-safe/durability";import{isUtf8 as bt}from"node:buffer";import*as xt from"node:v8";import{deserialize as St,serialize as Ct,setFlagsFromString as wt}from"node:v8";import{replaceFileAtomic as Tt}from"@openclaw/fs-safe/atomic";import{acquireFileLockSync as Et}from"@openclaw/fs-safe/file-lock";import{becomeChildSubreaper as Dt,inspectChildWaitState as Ot,isChildSubreaper as kt,reapChild as At}from"@openclaw/proc-safe/reaper";import"@openclaw/fs-safe/output";import"@openclaw/fs-safe/root";import"@openclaw/fs-safe/secure-file";import"@openclaw/fs-safe/walk";import"@openclaw/fs-safe/copy";import{PinnedProcess as jt}from"@openclaw/proc-safe/windows-job";import"json5";import"@openclaw/fs-safe/permissions";import{Value as Mt}from"typebox/value";import{Type as Nt}from"typebox";var Pt=Object.defineProperty,__esmMin=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},__exportAll=(e,t)=>{let n={};for(var r in e)Pt(n,r,{get:e[r],enumerable:!0});return t||Pt(n,Symbol.toStringTag,{value:`Module`}),n};function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isStringArray(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function asOptionalRecord(e){return isRecord(e)?e:void 0}function asNullableRecord(e){return isRecord(e)?e:null}function asOptionalObjectRecord(e){return e&&typeof e==`object`?e:void 0}var D=__esmMin((()=>{}));function createDeferredCore(){return Ft.withResolvers()}var Ft,It=__esmMin((()=>{Ft=Promise}));D();function monotonicNow(){return performance.now()}function remainingMonotonicMs(e){return e-monotonicNow()}function normalizeNullableString(e){return typeof e==`string`&&e.trim()||null}function normalizeOptionalString(e){return normalizeNullableString(e)??void 0}function normalizeOptionalLowercaseString(e){return normalizeOptionalString(e)?.toLowerCase()}function normalizeLowercaseStringOrEmpty(e){return normalizeOptionalLowercaseString(e)??``}var Lt=__esmMin((()=>{}));function asBoolean(e){return typeof e==`boolean`?e:void 0}function parseBooleanValue(e,t={}){let n=asBoolean(e);if(n!==void 0)return n;let r=normalizeOptionalLowercaseString(e);if(r){if((t.truthy??Rt).includes(r))return!0;if((t.falsy??zt).includes(r))return!1}}var Rt,zt,Bt=__esmMin((()=>{Lt(),Rt=[`true`,`1`,`yes`,`on`],zt=[`false`,`0`,`no`,`off`]}));function raiseChildOomScore(e){if(e!==void 0)try{r.writeFileSync(`/proc/${e}/oom_score_adj`,`1000`)}catch{}}function spawnOomScoreAdjusted(e,t,n){let r=ne(e,t,n);return!n.shell&&shouldAdjustChildOomScore(n)&&raiseChildOomScore(r.pid),r}function shouldAdjustChildOomScore(e){return(e?.platform??process.platform)===`linux`&&parseBooleanValue(e?.env?.[Vt]??process.env[Vt])!==!1}function isWrapped(e,t){return e===`/bin/sh`&&t[0]===`-c`&&t[1]===`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`}function resolveOomScoreWrappedCommand(e,t){return e===`/bin/sh`&&t[0]===`-c`&&(t[1]===`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`||t[1]===Ht)&&t[2]?t[2]:void 0}function spawnWithInheritedOomScore(e,t,n){if(process.platform!==`linux`||!isWrapped(e,t)||!t[2]||n.shell||n.argv0!==void 0)return spawnOomScoreAdjusted(e,t,n);let i,a;try{i=r.openSync(`/proc/self/oom_score_adj`,`r+`),a=r.readFileSync(i,`utf8`).trim(),r.writeSync(i,`1000`,0,`utf8`)}catch{return i!==void 0&&r.closeSync(i),ne(e,t,n)}try{return ne(t[2],t.slice(3),n)}finally{try{r.writeSync(i,a,0,`utf8`)}catch{process.emitWarning(`Could not restore spawn owner's Linux OOM score`)}finally{r.closeSync(i)}}}var Vt,Ht,Ut=__esmMin((()=>{Bt(),Vt=`OPENCLAW_CHILD_OOM_SCORE_ADJ`,Ht=['echo 1000 > /proc/self/oom_score_adj 2>/dev/null; if [ "${OC_INTERNAL_OOM_EXEC_BASH_ENV+x}" = x ]; then BASH_ENV="$OC_INTERNAL_OOM_EXEC_BASH_ENV"; export BASH_ENV; fi; unset OC_INTERNAL_OOM_EXEC_BASH_ENV','if [ "${OC_INTERNAL_OOM_EXEC_ENV+x}" = x ]; then ENV="$OC_INTERNAL_OOM_EXEC_ENV"; export ENV; fi; unset OC_INTERNAL_OOM_EXEC_ENV','if [ "${OC_INTERNAL_OOM_EXEC_CDPATH+x}" = x ]; then CDPATH="$OC_INTERNAL_OOM_EXEC_CDPATH"; export CDPATH; fi; unset OC_INTERNAL_OOM_EXEC_CDPATH','if [ "${OC_INTERNAL_OOM_EXEC_PS4+x}" = x ]; then PS4="$OC_INTERNAL_OOM_EXEC_PS4"; export PS4; fi; unset OC_INTERNAL_OOM_EXEC_PS4; exec "$0" "$@"'].join(`; `)}));Ut();function releaseProcessStdin(){let e=!1;try{let t=u(0);e=t.isFile()||t.isCharacterDevice()&&!ie(0)}catch{}e||process.stdin.destroy()}function serializeBrokerError(e){return{message:e.message,code:e.code,errno:e.errno,syscall:e.syscall,path:e.path}}var SpawnBrokerError,Wt=__esmMin((()=>{SpawnBrokerError=class extends Error{constructor(e,t){super(e,t),this.code=`ERR_SPAWN_BROKER_UNAVAILABLE`,this.name=`SpawnBrokerError`}}})),Gt,Kt=__esmMin((()=>{Gt=5e3}));function isProviderAuthPersistenceError(e){try{return qt in e&&e[qt]===!0}catch{return!1}}function isErrorObject(e){try{return e instanceof Error||Object.prototype.toString.call(e)===`[object Error]`}catch{return!1}}function isAggregateErrorObject(e){try{if(e instanceof AggregateError)return!0;for(let t=Object.getPrototypeOf(e);t;t=Object.getPrototypeOf(t)){let e=Object.getOwnPropertyDescriptor(t,`constructor`)?.value;if(typeof e==`function`&&e.name===`AggregateError`)return!0}}catch{}return!1}function readProperty(e,t){try{return e[t]}catch{return}}function readErrorText(e,t){let n=readProperty(e,t);return typeof n==`string`?n:void 0}function formatStatusAndCode(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return;try{if(Object.keys(e).some(e=>e!==`status`&&e!==`code`))return}catch{}let t=readProperty(e,`status`),n=readProperty(e,`code`);if(t!==void 0||n!==void 0)return`status=${typeof t==`string`||typeof t==`number`?String(t):`unknown`} code=${typeof n==`string`||typeof n==`number`?String(n):`unknown`}`}function stringifyUnknown(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)return String(e);try{let t=JSON.stringify(e);if(t!==void 0)return t}catch{}try{return Object.prototype.toString.call(e)}catch{return`Unknown error`}}function readErrorCauses(e){if(!isErrorObject(e))return[];let t=readProperty(e,`cause`),n=isAggregateErrorObject(e)?readProperty(e,`errors`):void 0,r=isProviderAuthPersistenceError(e)?[readProperty(e,`persistenceError`),readProperty(e,`cleanupError`)]:[],i=readErrorText(e,`name`)===`SuppressedError`?[readProperty(e,`error`),readProperty(e,`suppressed`)].map(e=>e??String(e)):[];return[...r,t||void 0,...Array.isArray(n)?n:[],...i]}function formatErrorMessage$1(e,t={}){let n;if(isErrorObject(e)){n=readErrorText(e,`message`)||readErrorText(e,`name`)||`Error`;let r=/* @__PURE__ */ new Set([n]),appendCauseMessage=e=>{e&&!r.has(e)&&(n+=` | ${e}`,r.add(e))};if(t.includeCode){let t=readProperty(e,`code`);(typeof t==`string`||typeof t==`number`)&&appendCauseMessage(String(t))}let i=collectErrorGraphCandidates(e,readErrorCauses);for(let e of i.slice(1))if(isErrorObject(e)){let t=readErrorText(e,`message`);t&&n.includes(t)?r.add(t):appendCauseMessage(t);let i=readProperty(e,`code`);(typeof i==`string`||typeof i==`number`)&&appendCauseMessage(String(i))}else appendCauseMessage(typeof e==`string`?e:formatStatusAndCode(e)??stringifyUnknown(e))}else n=formatStatusAndCode(e)??stringifyUnknown(e);return t.redact?t.redact(n):n}function formatErrorStackWithMessage(e){let t=readErrorText(e,`name`)||`Error`,n=readErrorText(e,`message`)??``,r=readProperty(e,`stack`);if(typeof r!=`string`||!r)return n||t;if(!n||r.includes(n))return r;let i=`${t}: ${n}`,a=r.indexOf(`
`),s=a<0?r:r.slice(0,a);return s===t?i+r.slice(s.length):`${i}\n${r}`}function toErrorObject(e,t){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);let n=Error(t,{cause:e});return(typeof e==`object`&&e||typeof e==`function`)&&Object.assign(n,e),n}function coerceErrorMessage(e){return e instanceof Error?e.message:String(e)}function extractErrorCode(e){if(!e||typeof e!=`object`)return;let t=readProperty(e,`code`);return typeof t==`string`||typeof t==`number`?String(t):void 0}function collectErrorGraphCandidates(e,t){if(e==null)return[];let n=[e],r=(/* @__PURE__ */ new Set()).add(e);for(let e of n)if(e&&typeof e==`object`&&t)for(let i of t(e))i!=null&&!r.has(i)&&(r.add(i),n.push(i));return n}function collectNestedErrorCandidates(e){return collectErrorGraphCandidates(e,e=>{let t=[readProperty(e,`cause`),readProperty(e,`reason`),readProperty(e,`original`),readProperty(e,`error`),readProperty(e,`suppressed`),readProperty(e,`data`)],n=readProperty(e,`errors`);return Array.isArray(n)&&t.push(...n),t})}var qt,O=__esmMin((()=>{qt=Symbol.for(`openclaw.provider-auth-persistence-error`)}));function resolveEnvironmentValue(e,t,n=process.platform){if(!e)return;if(n!==`win32`)return e[t]??(t===`PATH`?e.Path:void 0);let r=t.toUpperCase(),i=Object.keys(e).toSorted().find(e=>e.toUpperCase()===r);return i===void 0?void 0:e[i]}function mergeProcessEnv(e,t=process.platform){let n=Object.create(null),r=/* @__PURE__ */ new Map;for(let i of e){if(!i)continue;let e=Object.keys(i),a=/* @__PURE__ */ new Set;for(let s of t===`win32`?e.toSorted():e){let e=t===`win32`?s.toUpperCase():void 0;if(e!==void 0){if(a.has(e))continue;a.add(e);let t=r.get(e);t!==void 0&&delete n[t],r.delete(e)}let c=i[s];c===void 0?delete n[s]:(n[s]=c,e!==void 0&&Object.hasOwn(n,s)&&r.set(e,s))}}return n}function resolveDiagnosticProcessEnv(e=process.env,t=process.platform){return Object.fromEntries(Object.entries(mergeProcessEnv([e],t)).filter(([e])=>Jt.has(t===`win32`?e.toUpperCase():e)))}var Jt,Yt=__esmMin((()=>{Jt=/* @__PURE__ */ new Set(/* @__PURE__ */ `PATH.Path.HOME.USER.LOGNAME.TMPDIR.TMP.TEMP.LANG.LANGUAGE.TZ.LC_ALL.LC_COLLATE.LC_CTYPE.LC_MESSAGES.LC_MONETARY.LC_NUMERIC.LC_TIME.LC_ADDRESS.LC_IDENTIFICATION.LC_MEASUREMENT.LC_NAME.LC_PAPER.LC_TELEPHONE.SYSTEMROOT.WINDIR.COMSPEC.PATHEXT.SYSTEMDRIVE.USERPROFILE.HOMEDRIVE.HOMEPATH.USERNAME.USERDOMAIN.APPDATA.LOCALAPPDATA.PROGRAMDATA.ALLUSERSPROFILE.PROGRAMFILES.PROGRAMFILES(X86).PROGRAMW6432.COMMONPROGRAMFILES.COMMONPROGRAMFILES(X86).COMMONPROGRAMW6432.PSMODULEANALYSISCACHEPATH`.split(`.`))}));function readNativeProcessStartTime(e){if(!(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=se(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){let t=resolveEnvironmentValue(e,`SystemRoot`,`win32`)??resolveEnvironmentValue(e,`WINDIR`,`win32`);if(!t)return Qt;let n=S.win32.normalize(t);return/^[A-Za-z]:\\/.test(n)&&!n.startsWith(`\\\\`)?n:Qt}function windowsPowerShellPath(e){return S.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return S.win32.join(windowsSystemRoot(e),`System32`,`wbem`,`wmic.exe`)}function decodeWindowsProcessOutput(e){return Buffer.isBuffer(e)?e.length>=2&&e[0]===255&&e[1]===254?e.toString(`utf16le`):e.toString(`utf8`):e}function parseWindowsProcessStartTime(e){let t=decodeWindowsProcessOutput(e).split(/\r?\n/).map(e=>e.trim()).filter(Boolean),n=t.find(e=>e.toLowerCase().startsWith(`creationdate=`))?.slice(13).trim()??t.find(e=>e.toLowerCase()!==`creationdate`)??``,r=Date.parse(n);if(Number.isFinite(r))return r;let i=n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);if(!i)return null;let[,a,s,c,l,u,d,f,p,m]=i;return Date.UTC(Number(a),Number(s)-1,Number(c),Number(l),Number(u),Number(d),Math.floor(Number(f)/1e3))-Number(m)*6e4*(p===`+`?1:-1)}function readWindowsProcessStartTimeSync(e,t=Zt,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;let r=Date.now()+t,i=readNativeProcessStartTime(e);if(i!==void 0)return i;let a=r-Date.now();if(a<=0)return null;let s=re(windowsPowerShellPath(n),[`-NoProfile`,`-NonInteractive`,`-Command`,`$process = [System.Diagnostics.Process]::GetProcessById(${e}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`],{encoding:`utf8`,env:resolveDiagnosticProcessEnv(n,`win32`),timeout:Math.min(a,Xt),windowsHide:!0});if(!s.error&&s.status===0){let e=parseWindowsProcessStartTime(s.stdout);if(e!==null)return e}let c=r-Date.now();if(c<=0)return null;let l=re(windowsWmicPath(n),[`process`,`where`,`ProcessId=${e}`,`get`,`CreationDate`,`/value`],{env:resolveDiagnosticProcessEnv(n,`win32`),timeout:c,windowsHide:!0,stdio:[`ignore`,`pipe`,`ignore`]});return!l.error&&l.status===0?parseWindowsProcessStartTime(l.stdout):null}var Xt,Zt,Qt,$t=__esmMin((()=>{Yt(),Xt=5e3,Zt=1e4,Qt=`C:\\Windows`}));function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`FreeBSD process identity is unavailable in this sealed runtime`);return en||=e(import.meta.url)(`@openclaw/proc-safe/identity`),en}var en,tn=__esmMin((()=>{}));function readFreeBsdProcessStartTime(e){if(process.platform!==`freebsd`||!Number.isInteger(e)||e<=0||e>2147483647)return null;try{return loadFreeBsdProcessIdentityNative().readProcessIdentity(e)?.startTimeSinceBootMicros??null}catch{return null}}var nn=__esmMin((()=>{tn()}));function readDarwinNativeIdentity(e){if(!(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=se(e);return t&&!t.exited?{startedAt:Math.floor(t.startTimeMicros/1e6),startTimeMicros:t.startTimeMicros}:null}catch{return}}function readNativeLiveness(e){if(!(![`darwin`,`win32`,`freebsd`].includes(process.platform)||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=se(e);return t!==null&&!t.exited}catch(e){return e instanceof ae&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`)?void 0:!0}}function isValidPid(e){return Number.isInteger(e)&&e>0}function hasLinuxProcfs(){return process.platform===`linux`||process.platform===`android`}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return!1;try{let t=r.readFileSync(`/proc/${e}/status`,`utf8`),n=t.match(/^State:\s+(\S)/m)?.[1],i=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(i!==`0`){let r=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return r!==void 0&&Number(r)!==e||(n===`Z`||n===`X`)&&i===`1`}}catch{}try{process.kill(e,0)}catch(e){return e.code===`ESRCH`}return!1}function isPidAlive(e){if(!isValidPid(e))return!1;try{process.kill(e,0)}catch(t){let n=t.code;if(n!==`EPERM`)return n===`ESRCH`?readNativeLiveness(e)??!1:!1}return readNativeLiveness(e)??!isExitedLinuxProcess(e)}function isPidDefinitelyDead(e){if(!isValidPid(e))return!0;let t=!1;try{process.kill(e,0)}catch(e){let n=e.code;if(n!==`ESRCH`&&(process.platform!==`win32`||n!==`EPERM`))return!1;t=n===`ESRCH`}let n=readNativeLiveness(e);return n===void 0?t&&process.platform!==`freebsd`||isExitedLinuxProcess(e):!n}function getDarwinProcessStartTime(e,t,n){let r=performance.now(),i=readDarwinNativeIdentity(e);if(i!==void 0)return i?.startedAt??null;let a=n===void 0?rn:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{let n=ee.execFileSync(`/bin/ps`,[`-o`,`lstart=`,`-p`,String(e)],{encoding:`utf8`,env:{...resolveDiagnosticProcessEnv(t),LC_ALL:`C`,TZ:`UTC`},stdio:[`ignore`,`pipe`,`ignore`],timeout:a,killSignal:`SIGKILL`}).trim(),r=Date.parse(`${n} UTC`);return Number.isFinite(r)?Math.floor(r/1e3):null}catch{return null}}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{let t=r.readFileSync(`/proc/${e}/stat`,`utf8`),n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;let i=t.slice(n+1).trimStart().split(/\s+/),a=Number(i[19]),s=Number(i[1]);return Number.isSafeInteger(a)&&a>=0&&Number.isSafeInteger(s)&&s>=0?{parentPid:s,startedAt:a}:null}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&an!==null)return an;let i=process.platform===`darwin`?getDarwinProcessStartTime(e,t,n):process.platform===`win32`?readWindowsProcessStartTimeSync(e,n,t):process.platform===`freebsd`?readFreeBsdProcessStartTime(e):getProcessStartTime(e);return r&&i!==null&&(an=i),i}var rn,an,on=__esmMin((()=>{Yt(),$t(),nn(),rn=1e3,an=null}));function failure$1(e){if(e instanceof DarwinProcessInspectionError)return e;let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return new DarwinProcessInspectionError(t===`ETIMEDOUT`||t===`ABORT_ERR`||t===`timeout`?`deadline`:[`EACCES`,`EPERM`,`ERR_ACCESS_DENIED`,`access-denied`].includes(String(t))?`permission`:`unavailable`,{cause:e})}function remaining(e){let t=Math.floor(e-performance.now());if(t<=0)throw new DarwinProcessInspectionError(`deadline`);return t}function hasReadableTopology(e){if(e.parentPid===void 0||e.processGroupId===void 0||e.state===void 0){if(se(e.pid)===null)return!1;throw new DarwinProcessInspectionError(`unavailable`)}return!0}function topology(e){return{pid:e.pid,ppid:e.parentPid,pgid:e.processGroupId,state:sn[e.state],owner:e.owner}}function census(e,t){try{let n=fe({timeoutMs:remaining(e),...t?{pids:t}:{}}).filter(hasReadableTopology);return remaining(e),n}catch(t){throw remaining(e),failure$1(t)}}function*readDarwinProcessCensus(e){let t=performance.now()+e,n=census(t).map(topology);for(let e of n)remaining(t),yield e;remaining(t)}var DarwinProcessInspectionError,sn,cn=__esmMin((()=>{DarwinProcessInspectionError=class extends Error{constructor(e,t){super(`Darwin process inspection ${e}`,t),this.reason=e,this.name=`DarwinProcessInspectionError`,this.code=e===`deadline`?`ETIMEDOUT`:e===`permission`?`EPERM`:`EIO`}},sn={running:`R`,sleeping:`S`,stopped:`T`,zombie:`Z`,idle:`I`,unknown:`?`}}));function readLinuxProcessUid(e){try{let t=f(`/proc/${e}/status`,`utf8`).split(`
`).filter(e=>e.startsWith(`Uid:`)),n=(t.length===1?/^Uid:[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]*$/.exec(t[0]):null)?.slice(1).map(Number),r=process.getuid?.();return n?.every(e=>Number.isSafeInteger(e)&&e<=4294967295)?n.find(e=>e===r)??n[0]:void 0}catch{return}}function killOwnedProcessGroupMembers(){for(let{pid:e,pgid:t}of readProcessGroupMembers(1e3))if(e!==process.pid&&t===process.pid)try{process.kill(e,`SIGKILL`)}catch(e){if(extractErrorCode(e)!==`ESRCH`)throw e}}function*readProcessGroupMembers(e,t){let n=t!==void 0;if(process.platform===`linux`){let t=Date.now()+e;for(let e of p(`/proc`)){if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);if(!/^\d+$/.test(e))continue;let r=Number(e),i,a,s,c=!1;try{if(i=f(`/proc/${e}/stat`,`utf8`),n){s=readLinuxProcessUid(r);try{a=f(`/proc/${e}/cmdline`,`utf8`).split(`\0`).filter(Boolean)}catch(e){let t=process.getuid?.();if(c=s!==void 0&&t!==void 0&&s!==t&&[`EACCES`,`EPERM`].includes(extractErrorCode(e)??``),!c)throw e}}}catch(e){if(r!==process.pid&&[`ENOENT`,`ESRCH`].includes(extractErrorCode(e)??``))continue;throw Error(`Could not classify PID ${r}: process command inspection failed (${extractErrorCode(e)??`unavailable`}).`,{cause:e})}let l=/^(\d+) \([\s\S]*\) (\S) (\d+) (-1|\d+)(?:\s|$)/.exec(i);if(!l||Number(l[1])!==r||Date.now()>=t)throw Error(`Process group census is unavailable`);if(a?.length===0){let e=Number(i.slice(i.lastIndexOf(`)`)+2).split(/\s+/)[6]);if(!(Number.isInteger(e)&&e&2097152)&&!isPidDefinitelyDead(r)){let e=process.getuid?.();if(s!==void 0&&e!==void 0&&s!==e)c=!0,a=void 0;else throw Error(`Could not classify PID ${r}: live userspace process has no readable arguments.`)}}yield{pid:r,pgid:Number(l[4]),state:l[2],...a?{command:{ppid:Number(l[3]),argv:a,...s===void 0?{}:{uid:s}}}:c&&s!==void 0?{command:{ppid:Number(l[3]),argvUnavailable:!0,uid:s}}:{}}}if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);return}if(process.platform===`darwin`){for(let r of readDarwinProcessCensus(e)){let e={pid:r.pid,pgid:r.pgid,state:r.state},i;try{i=n?r.state.startsWith(`Z`)||r.pid===0?{argv:[]}:t?.readDarwinCommand(r.pid,r.owner):void 0}catch(t){if(!(t instanceof ae)||t.code!==`incomplete`&&t.code!==`layout-mismatch`)throw t;yield{...e,ppid:r.ppid};continue}(!n||i)&&(yield{...e,...i?{command:{ppid:r.ppid,owner:r.owner,...i}}:{}})}return}if(n)throw Error(`Exact process command census is unavailable on ${process.platform}.`);let r=Date.now()+e,i=re(`/bin/ps`,[`-A`,`-o`,`pid=,pgid=,stat=`],{encoding:`utf8`,timeout:e,maxBuffer:4194304});if(i.error||i.status!==0)throw Error(`Process group census is unavailable`);for(let e of i.stdout.split(`
`)){if(!e.trim())continue;let t=/^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(e);if(!t)throw Error(`Process group census is unavailable`);let n=Number(t[1]);n!==i.pid&&(yield{pid:n,pgid:Number(t[2]),state:t[3]})}if(n&&Date.now()>=r)throw Error(`Process group census exceeded its deadline`)}function isLiveCensusMember({pid:e,state:t}){return!t.startsWith(`Z`)||process.platform===`linux`&&!isPidDefinitelyDead(e)}function hasLiveOwnedProcessGroupMembers(e=1e3){let t=!1;try{for(let{pid:n,pgid:r,state:i}of readProcessGroupMembers(Math.max(1,Math.min(1e3,e))))if(n===process.pid){if(r!==process.pid)return;t=!0}else if(r===process.pid&&isLiveCensusMember({pid:n,state:i}))return!0}catch{return}return!t&&void 0}var ln=__esmMin((()=>{O(),on(),cn()}));ln();function encodeServiceChildMessage(e){return`${JSON.stringify(e)}\n`}function setStdioEntry(e,t,n){for(;e.length<=t;)e.push(`ignore`);e[t]=n}function reserveStdioEntry(e,t){let n=3;for(;e[n]!==void 0&&e[n]!==`ignore`;)n+=1;return setStdioEntry(e,n,t),n}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)}var k=__esmMin((()=>{})),A,un=__esmMin((()=>{k(),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,M=__esmMin((()=>{k(),j=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}})})),dn,pn=__esmMin((()=>{k(),M(),dn=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]})}})})),mn,hn=__esmMin((()=>{k(),M(),mn=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})}})})),gn,_n,vn=__esmMin((()=>{k(),gn=[`preserve rows`,`delete rows`,`drop`],_n=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})}})})),yn,bn=__esmMin((()=>{k(),M(),yn=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)})}})})),xn,Sn=__esmMin((()=>{k(),bn(),xn=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:yn.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}})})),Cn,wn=__esmMin((()=>{k(),M(),Cn=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})}})})),Tn,En=__esmMin((()=>{k(),Tn=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}})})),Dn,On=__esmMin((()=>{k(),Dn=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}})})),kn,An=__esmMin((()=>{k(),bn(),kn=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:yn.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:yn.createWithSchema(e,t)})}})}));function isOperationNodeSource(e){return isObject$1(e)&&isFunction(e.toOperationNode)}var jn=__esmMin((()=>{k()}));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)}var Mn=__esmMin((()=>{jn(),k()})),Nn,Pn=__esmMin((()=>{k(),Nn=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})}})})),Fn,In=__esmMin((()=>{k(),Fn=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}})})),Ln,Rn=__esmMin((()=>{k(),Ln=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}})})),zn,Bn=__esmMin((()=>{k(),In(),Rn(),zn=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`?Fn.create(e.on,n):Ln.create(e.on,n)})}})})),Vn,Hn=__esmMin((()=>{k(),Bn(),Vn=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:zn.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?zn.cloneWithOperation(e.on,`And`,t):zn.create(t)})}})})),Un,Wn=__esmMin((()=>{k(),Un=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}})}));function isBinaryOperator(e){return isString(e)&&Yn[e]}function isJSONOperator(e){return isString(e)&&qn[e]}function isUnaryOperator(e){return isString(e)&&Qn[e]}var Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr=__esmMin((()=>{k(),Gn=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(Gn),Kn=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),Object.keys(Kn),qn=freeze({"->":!0,"->>":!0}),Jn=Object.keys(qn),Yn=freeze({...Gn,...Kn,"||":!0}),Xn=Object.keys(Yn),Zn=freeze({exists:!0,"not exists":!0}),Object.keys(Zn),Qn=freeze({...Zn,"-":!0,not:!0}),$n=Object.keys(Qn),[...Xn,...Jn,...$n],er=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}})})),N,nr=__esmMin((()=>{k(),M(),N=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:j.create(e)})}})})),rr,ir=__esmMin((()=>{k(),rr=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}})})),ar,or=__esmMin((()=>{ir(),k(),ar=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:rr.create()})}})}));function isDynamicReferenceBuilder(e){return isObject$1(e)&&isOperationNodeSource(e)&&isString(e.dynamicReference)}var DynamicReferenceBuilder,sr=__esmMin((()=>{jn(),wr(),k(),DynamicReferenceBuilder=class{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return parseSimpleReferenceExpression(this.#e)}}})),cr,lr=__esmMin((()=>{k(),cr=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,ur=__esmMin((()=>{k(),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)}})})),dr,fr=__esmMin((()=>{k(),M(),dr=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:j.create(e)})}})})),pr,mr=__esmMin((()=>{fr(),lr(),ur(),k(),pr=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:cr.cloneWith(this.#e.node,{direction:P.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:cr.cloneWith(this.#e.node,{direction:P.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:cr.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:cr.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:cr.cloneWith(this.#e.node,{collation:dr.create(e)})})}toOperationNode(){return this.#e.node}}}));function logOnce(e){hr.has(e)||(hr.add(e),console.log(e))}var hr,gr=__esmMin((()=>{hr=/* @__PURE__ */ new Set}));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(cr.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 cr.create(e,P.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),cr.create(e,t.toOperationNode());let n=cr.create(e);return t?t(new pr({node:n})).toOperationNode():n}var _r=__esmMin((()=>{sr(),Mn(),lr(),ur(),mr(),gr(),Po(),wr()})),vr,yr=__esmMin((()=>{k(),vr=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})}})})),br,xr=__esmMin((()=>{k(),br=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])})}})})),Sr,Cr=__esmMin((()=>{k(),Sr=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 vr.create(parseStringReference(e),br.create(er.create(t)));if(t===`->$`||t===`->>$`)return vr.create(parseStringReference(e),Sr.create(er.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return ar.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 Dn.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 ar.create(N.create(r),kn.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return ar.create(N.create(n),kn.create(t))}function trim$2(e){return e.trim()}var wr=__esmMin((()=>{On(),nr(),or(),An(),k(),Po(),M(),_r(),tr(),yr(),xr(),Cr()})),Tr,Er=__esmMin((()=>{k(),Tr=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}})})),Dr,Or=__esmMin((()=>{k(),Dr=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}})})),kr,Ar=__esmMin((()=>{k(),kr=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):kr.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 kr.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Dr.create(e.map(e=>parseValueExpression(e))):Tr.create(e)}var jr=__esmMin((()=>{Er(),Or(),Ar(),k(),Po()})),Mr,Nr=__esmMin((()=>{k(),Mr=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)?Un.create(parseReferenceExpression(e),parseBinaryOperator(t),kr.createImmediate(n)):Un.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return Un.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`?Fn.create:Ln.create;if(e.length===0)return Un.create(kr.createImmediate(1),er.create(`=`),kr.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?Mr.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 er.create(e);if(isOperationNodeSource(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function toOperationNode(e){return isOperationNodeSource(e)?e.toOperationNode():e}var Pr=__esmMin((()=>{Wn(),k(),jn(),tr(),wr(),jr(),Ar(),In(),Nr(),Rn()})),Fr,Ir=__esmMin((()=>{k(),Fr=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])})}})})),Lr,Rr=__esmMin((()=>{k(),Lr=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])})}})})),zr,Br=__esmMin((()=>{k(),Ir(),Rr(),zr=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Fr.cloneWithItems(e.orderBy,t):Fr.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?Lr.cloneWithItems(e.partitionBy,t):Lr.create(t)})}})})),Vr,Hr=__esmMin((()=>{k(),Vr=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])})}})})),Ur,Wr=__esmMin((()=>{k(),Ur=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])})}})})),Gr,Kr=__esmMin((()=>{k(),In(),Rn(),Gr=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`?Fn.create(e.having,n):Ln.create(e.having,n)})}})})),qr,Jr=__esmMin((()=>{k(),qr=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})}})})),Yr,Xr=__esmMin((()=>{k(),Yr=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}})})),Zr,Qr=__esmMin((()=>{k(),Hr(),Xr(),Zr=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Yr.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?Vr.cloneWithFroms(e.from,t):Vr.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}})})),$r,ei=__esmMin((()=>{k(),$r=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])})}})})),ti,ni=__esmMin((()=>{k(),Hr(),ei(),hi(),ti=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:Vr.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>F.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>F.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?$r.create(t):$r.cloneWithTables(e.using,t)})}})})),ri,ii=__esmMin((()=>{k(),In(),Rn(),ri=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`?Fn.create(e.where,n):Ln.create(e.where,n)})}})})),ai,oi=__esmMin((()=>{k(),ai=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)})}})})),si,ci=__esmMin((()=>{k(),si=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}})})),li,ui=__esmMin((()=>{k(),li=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}})})),di,fi=__esmMin((()=>{k(),ui(),di=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),li.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}})})),pi,mi=__esmMin((()=>{k(),pi=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)})}})})),F,hi=__esmMin((()=>{Jr(),gi(),Qr(),ni(),ii(),k(),oi(),ci(),fi(),mi(),Ir(),F=freeze({is(e){return I.is(e)||qr.is(e)||Zr.is(e)||ti.is(e)||di.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?ri.cloneWithOperation(e.where,`And`,t):ri.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?ai.cloneWithSelections(e.returning,t):ai.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:si.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?pi.cloneWithSelections(e.output,t):pi.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Fr.cloneWithItems(e.orderBy,t):Fr.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}})})),I,gi=__esmMin((()=>{k(),Hr(),Wr(),Kr(),hi(),I=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:Vr.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)=>F.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Ur.cloneWithItems(e.groupBy,t):Ur.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?Gr.cloneWithOperation(e.having,`And`,t):Gr.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=>F.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}})})),_i,vi=__esmMin((()=>{Hn(),ur(),Pr(),k(),_i=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:Vn.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:Vn.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:Vn.cloneWithOn(this.#e.joinNode,P.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}}})),yi,bi=__esmMin((()=>{k(),yi=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}})}));function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(yi.create)}var xi=__esmMin((()=>{bi(),wr()})),Si,Ci=__esmMin((()=>{Br(),hi(),_r(),xi(),k(),Si=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:zr.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:F.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:zr.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}}})),wi,Ti=__esmMin((()=>{k(),or(),ir(),wi=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:rr.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:ar.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)?wi.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?wi.create(e.toOperationNode()):wi.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[wi.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return wi.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Ei=__esmMin((()=>{k(),Ti(),wr(),sr(),Po(),Io(),No()})),Di,Oi=__esmMin((()=>{k(),Di=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}})})),ki,Ai=__esmMin((()=>{k(),ki=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)),Di.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=ki.create();return Dr.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Tr.create(r)}var ji=__esmMin((()=>{nr(),Er(),Or(),k(),jr(),Oi(),Po(),Ai(),No()})),Mi,Ni=__esmMin((()=>{k(),Mi=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?[Mi.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])=>Mi.create(N.create(e),parseValueExpression(t)))}var Pi=__esmMin((()=>{nr(),Ni(),No(),k(),jr(),wr()})),Fi,Ii=__esmMin((()=>{k(),Fi=freeze({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return freeze({kind:`OnDuplicateKeyNode`,updates:e})}})})),InsertResult,Li=__esmMin((()=>{InsertResult=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}}}));function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}var NoResultError,Ri=__esmMin((()=>{NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}}})),zi,Bi=__esmMin((()=>{k(),ii(),zi=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?ri.cloneWithOperation(e.indexWhere,`And`,t):ri.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?ri.cloneWithOperation(e.indexWhere,`Or`,t):ri.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?ri.cloneWithOperation(e.updateWhere,`And`,t):ri.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?ri.cloneWithOperation(e.updateWhere,`Or`,t):ri.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}})})),Vi,OnConflictDoNothingBuilder,Hi,Ui=__esmMin((()=>{nr(),M(),Bi(),Pr(),Pi(),k(),Vi=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=N.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:zi.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:zi.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:zi.cloneWith(this.#e.onConflictNode,{constraint:j.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:zi.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:zi.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:zi.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:zi.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:zi.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new Hi({...this.#e,onConflictNode:zi.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}},Hi=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:zi.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:zi.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:zi.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}}})),Wi,Gi=__esmMin((()=>{k(),Wi=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 Wi.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}var Ki=__esmMin((()=>{Gi(),k()})),qi,Ji=__esmMin((()=>{k(),qi=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}})})),Yi,Xi=__esmMin((()=>{Ei(),ji(),Jr(),hi(),Pi(),k(),Ii(),Li(),Ri(),Po(),nr(),Ui(),Bi(),Ki(),Ji(),Yi=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{columns:freeze(e.map(N.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{orAction:qi.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{orAction:qi.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{orAction:qi.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{orAction:qi.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{orAction:qi.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{orAction:qi.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:F.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{onConflict:e(new Vi({onConflictNode:zi.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:qr.cloneWith(this.#e.queryNode,{onDuplicateKey:Fi.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:F.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:F.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}}})),DeleteResult,Zi=__esmMin((()=>{DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}}})),Qi,$i=__esmMin((()=>{k(),Qi=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}})})),ea,DeleteQueryBuilder,ta=__esmMin((()=>{Ua(),Io(),Ei(),hi(),k(),Ri(),Zi(),ni(),$i(),_r(),Pr(),jr(),Ki(),DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new ea({...this.#e,queryNode:F.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new ea({...this.#e,queryNode:F.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new ea({...this.#e,queryNode:F.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new ea({...this.#e,queryNode:F.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new ea({...this.#e,queryNode:ti.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 ea({...this.#e,queryNode:F.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new ea({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new ea({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new ea({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new ea({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new ea({...this.#e,queryNode:F.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ea({...this.#e,queryNode:ti.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new ea({...this.#e,queryNode:F.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new ea({...this.#e,queryNode:F.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new ea({...this.#e,queryNode:ti.cloneWithLimit(this.#e.queryNode,Qi.create(parseValueExpression(e)))})}modifyEnd(e){return new ea({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new ea({...this.#e})}$castTo(){return new ea(this.#e)}$narrowType(){return new ea(this.#e)}$assertType(){return new ea(this.#e)}withPlugin(e){return new ea({...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 ea({...this.#e,queryNode:F.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},ea=DeleteQueryBuilder})),UpdateResult,na=__esmMin((()=>{UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}}})),ra,UpdateQueryBuilder,ia=__esmMin((()=>{Ua(),Io(),Ei(),hi(),Qr(),Pi(),k(),na(),Ri(),Pr(),jr(),$i(),Ki(),_r(),UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new ra({...this.#e,queryNode:F.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new ra({...this.#e,queryNode:F.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new ra({...this.#e,queryNode:F.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new ra({...this.#e,queryNode:F.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new ra({...this.#e,queryNode:Zr.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 ra({...this.#e,queryNode:F.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new ra({...this.#e,queryNode:F.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new ra({...this.#e,queryNode:F.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new ra({...this.#e,queryNode:Zr.cloneWithLimit(this.#e.queryNode,Qi.create(parseValueExpression(e)))})}set(...e){return new ra({...this.#e,queryNode:Zr.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new ra({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new ra({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new ra({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new ra({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new ra({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new ra({...this.#e,queryNode:F.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new ra({...this.#e})}$castTo(){return new ra(this.#e)}$narrowType(){return new ra(this.#e)}$assertType(){return new ra(this.#e)}withPlugin(e){return new ra({...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 ra({...this.#e,queryNode:F.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},ra=UpdateQueryBuilder})),aa,oa=__esmMin((()=>{k(),nr(),An(),aa=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:kn.create(e),columns:t?freeze(t.map(N.create)):void 0})}})})),sa,ca=__esmMin((()=>{k(),sa=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})}})})),la,ua=__esmMin((()=>{ca(),k(),la=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:sa.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:sa.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():sa.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new la({node:sa.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 aa.create(n,r)}return aa.create(e)}var da=__esmMin((()=>{oa(),Ha(),k(),ua(),ca(),jn()})),fa,pa=__esmMin((()=>{k(),fa=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])})}})}));function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return ma[~~(Math.random()*ma.length)]}var ma,ha=__esmMin((()=>{ma=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``)}));function createQueryId(){return new LazyQueryId}var LazyQueryId,ga=__esmMin((()=>{ha(),LazyQueryId=class{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}}})),OperationNodeTransformer,_a=__esmMin((()=>{k(),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)}var va=__esmMin((()=>{k()}));function isRootOperationNode(e){return isOperationNode(e)&&ya[e.kind]===!0}var ya,ba=__esmMin((()=>{va(),ya={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}})),xa,WithSchemaTransformer,Sa=__esmMin((()=>{On(),M(),Hn(),Xr(),_a(),ba(),bn(),An(),ei(),k(),xa=freeze({json_agg:!0,to_json:!0}),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:kn.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=>kn.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return xa[e.func]?e[n].map(e=>!kn.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&&yn.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&&(Vn.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(kn.is(e))return this.#s(e.table,t);if(Dn.is(e)&&kn.is(e.node))return this.#s(e.node.table,t);if(Yr.is(e))for(let n of e.items)this.#o(n,t);else if($r.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,Ca=__esmMin((()=>{Sa(),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}}})),wa,Ta=__esmMin((()=>{k(),wa=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 li.create(parseFilterList([wa.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 Ea=__esmMin((()=>{Ta(),jn(),ur(),ui(),k(),Pr()})),Deferred,Da=__esmMin((()=>{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})}var Oa=__esmMin((()=>{Da(),k()}));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}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(ka);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==ka)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(ka)}}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})}var ka,Aa=__esmMin((()=>{Da(),k(),ka={}})),ja,QueryExecutorBase,Ma=__esmMin((()=>{k(),Oa(),Aa(),Da(),ja=freeze([]),QueryExecutorBase=class{#e;constructor(e=ja){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(ka);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})===ka&&(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===ka?(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===ka&&(f.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),p}finally{l(ka),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(ka);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===ka&&(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===ka&&(u=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{c(ka),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}}})),Na,Pa,Fa=__esmMin((()=>{Ma(),Na=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([])}},Pa=new Na})),MergeResult,Ia=__esmMin((()=>{MergeResult=class{numChangedRows;constructor(e){this.numChangedRows=e}}})),La,Ra,MatchedThenableMergeQueryBuilder,NotMatchedThenableMergeQueryBuilder,za=__esmMin((()=>{Jr(),fi(),hi(),Qr(),ji(),Ua(),Ea(),Ei(),Ki(),Fa(),k(),Ia(),Ri(),ia(),La=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:F.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new Ra({...this.#e,queryNode:di.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},Ra=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:F.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:di.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:F.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:F.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:F.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:di.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 Ra({...this.#e,queryNode:di.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new Ra({...this.#e,queryNode:di.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new Ra({...this.#e,queryNode:di.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:Pa,queryNode:Zr.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new Ra({...this.#e,queryNode:di.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new Ra({...this.#e,queryNode:di.cloneWithThen(this.#e.queryNode,parseMergeThen(qr.cloneWith(qr.createWithoutInto(),{columns:t,values:n})))})}}})),Ba,Va=__esmMin((()=>{io(),Xi(),ta(),ia(),ni(),Jr(),gi(),Qr(),Io(),da(),pa(),ga(),Ca(),k(),Ei(),za(),fi(),Ba=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:I.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:I.cloneWithSelections(I.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new Yi({queryId:createQueryId(),executor:this.#e.executor,queryNode:qr.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new Yi({queryId:createQueryId(),executor:this.#e.executor,queryNode:qr.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:ti.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Zr.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new La({queryId:createQueryId(),executor:this.#e.executor,queryNode:di.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?fa.cloneWithExpression(this.#e.withNode,n):fa.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?fa.cloneWithExpression(this.#e.withNode,n):fa.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 Ba({executor:Pa})}function createJoinBuilder(e,t){return new _i({joinNode:Vn.create(e,parseTableExpression(t))})}function createOverBuilder(){return new Si({overNode:zr.create()})}var Ha=__esmMin((()=>{Hn(),Br(),vi(),Ci(),Va(),Fa(),Io()}));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 Vn.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return Vn.create(e,parseTableExpression(t))}var Ua=__esmMin((()=>{Hn(),Pr(),Ha(),Io()})),Wa,Ga=__esmMin((()=>{k(),Wa=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}})})),Ka,qa=__esmMin((()=>{k(),Ka=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(Ka.create)}var Ja=__esmMin((()=>{qa(),No(),k(),wr()})),Ya,Xa=__esmMin((()=>{k(),Ya=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=>Ya.create(e,parseExpression(t),n))}var Za=__esmMin((()=>{No(),Xa(),k(),Po()})),L,AliasedExpressionWrapper,Qa,$a,eo=__esmMin((()=>{On(),In(),M(),jn(),Rn(),Nr(),Pr(),L=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Qa(Ln.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new $a(Fn.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 Dn.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():j.create(this.#t))}},Qa=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(Ln.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Mr.create(this.#e)}},$a=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(Fn.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Mr.create(this.#e)}}})),to,no=__esmMin((()=>{k(),Ar(),to=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:kr.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 to.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var ro=__esmMin((()=>{no(),k()}));function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var R,SelectQueryBuilderImpl,AliasedSelectQueryBuilderImpl,io=__esmMin((()=>{On(),Pn(),Ua(),Io(),Ei(),wr(),gi(),hi(),_r(),$i(),Ga(),k(),Ja(),Ri(),M(),Za(),Pr(),eo(),jr(),ro(),Ki(),SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new R({...this.#e,queryNode:F.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new R({...this.#e,queryNode:F.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new R({...this.#e,queryNode:I.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new R({...this.#e,queryNode:I.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new R({...this.#e,queryNode:I.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new R({...this.#e,queryNode:I.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new R({...this.#e,queryNode:I.cloneWithFrontModifier(this.#e.queryNode,Nn.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.createWithExpression(e.toOperationNode()))})}distinct(){return new R({...this.#e,queryNode:I.cloneWithFrontModifier(this.#e.queryNode,Nn.create(`Distinct`))})}forUpdate(e){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.create(`SkipLocked`))})}noWait(){return new R({...this.#e,queryNode:F.cloneWithEndModifier(this.#e.queryNode,Nn.create(`NoWait`))})}selectAll(e){return new R({...this.#e,queryNode:I.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 R({...this.#e,queryNode:F.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new R({...this.#e,queryNode:F.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new R({...this.#e,queryNode:I.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new R({...this.#e,queryNode:I.cloneWithLimit(this.#e.queryNode,Qi.create(parseValueExpression(e)))})}offset(e){return new R({...this.#e,queryNode:I.cloneWithOffset(this.#e.queryNode,Wa.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new R({...this.#e,queryNode:I.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new R({...this.#e,queryNode:F.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new R({...this.#e,queryNode:I.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new R({...this.#e,queryNode:I.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new R({...this.#e,queryNode:I.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new R({...this.#e,queryNode:I.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new R({...this.#e,queryNode:I.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new R({...this.#e,queryNode:I.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new R({...this.#e,queryNode:I.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new R({...this.#e,queryNode:F.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new R({...this.#e,queryNode:I.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new R({...this.#e,queryNode:I.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new R({...this.#e,queryNode:F.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new R({...this.#e,queryNode:I.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new R({...this.#e})}$castTo(){return new R(this.#e)}$narrowType(){return new R(this.#e)}$assertType(){return new R(this.#e)}$asTuple(){return new L(this.toOperationNode())}$asScalar(){return new L(this.toOperationNode())}withPlugin(e){return new R({...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 R({...this.#e,queryNode:F.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},R=SelectQueryBuilderImpl,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 Dn.create(this.#e.toOperationNode(),j.create(this.#t))}}})),ao,oo=__esmMin((()=>{k(),ii(),Ir(),ao=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]?Fr.cloneWithItems(e[r],t):Fr.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?ri.cloneWithOperation(e.filter,`And`,t):ri.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?ri.cloneWithOperation(e.filter,`Or`,t):ri.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}})})),so,co=__esmMin((()=>{k(),so=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}})})),lo,AliasedAggregateFunctionBuilder,uo=__esmMin((()=>{k(),oo(),On(),M(),Ha(),Pr(),_r(),hi(),lo=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:ao.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:F.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:F.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:ao.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:ao.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:ao.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:ao.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 Dn.create(this.#e.toOperationNode(),j.create(this.#t))}}}));function createFunctionModule(){let fn=(e,t)=>new L(so.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new lo({aggregateFunctionNode:ao.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 lo({aggregateFunctionNode:ao.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 lo({aggregateFunctionNode:ao.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new L(so.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}var fo=__esmMin((()=>{eo(),oo(),co(),wr(),Ei(),uo(),k(),Io()})),po,mo=__esmMin((()=>{k(),po=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 po.create(er.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}var ho=__esmMin((()=>{tr(),mo(),wr()})),go,_o=__esmMin((()=>{k(),ui(),go=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),li.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}})})),CaseBuilder,CaseThenBuilder,CaseWhenBuilder,CaseEndBuilder,vo=__esmMin((()=>{eo(),k(),wr(),_o(),ui(),Pr(),jr(),CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:go.cloneWithWhen(this.#e.node,li.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:go.cloneWithWhen(this.#e.node,li.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:go.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:go.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:go.cloneWithWhen(this.#e.node,li.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:go.cloneWithWhen(this.#e.node,li.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:go.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:go.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new L(go.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new L(go.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new L(go.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new L(go.cloneWith(this.#e.node,{isStatement:!0}))}}})),yo,bo=__esmMin((()=>{k(),yo=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}})})),xo,JSONPathBuilder,So,AliasedJSONPathBuilder,Co=__esmMin((()=>{On(),M(),xr(),bo(),Cr(),yr(),jn(),Ar(),xo=/^#-\d+$/,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`&&!xo.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 vr.is(this.#e)?new So(vr.cloneWithTraversal(this.#e,Sr.is(this.#e.traversal)?Sr.cloneWithLeg(this.#e.traversal,yo.create(e,t)):br.cloneWithValue(this.#e.traversal,kr.createImmediate(t)))):new So(Sr.cloneWithLeg(this.#e,yo.create(e,t)))}},So=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 Dn.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():j.create(this.#t))}}})),wo,To=__esmMin((()=>{k(),wo=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}})}));function isColumnDataType(e){return Eo[e]||Do.some(t=>t.test(e))}var Eo,Do,Oo,ko=__esmMin((()=>{k(),Eo=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}),Do=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+\)$/]),Oo=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}})}));function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return Oo.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}var Ao=__esmMin((()=>{ko(),jn()})),jo,Mo=__esmMin((()=>{k(),jo=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}})}));function createExpressionBuilder(e=Pa){function binary(e,t,n){return new L(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new L(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:I.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:go.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new L(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Sr.create())},table(e){return new L(parseTable(e))},val(e){return new L(parseValueExpression(e))},refTuple(...e){return new L(wo.create(e.map(parseReferenceExpression)))},tuple(...e){return new L(wo.create(e.map(parseValueExpression)))},lit(e){return new L(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 L(Un.create(parseReferenceExpression(e),er.create(`between`),Fn.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new L(Un.create(parseReferenceExpression(e),er.create(`between symmetric`),Fn.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new L(parseFilterList(e,`and`)):new L(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new L(parseFilterList(e,`or`)):new L(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Mr.is(t)?new L(t):new L(Mr.create(t))},cast(e,t){return new L(jo.create(parseReferenceExpression(e),parseDataTypeExpression(t)))}});return t.fn=createFunctionModule(),t.eb=t,t}function expressionBuilder(e){return createExpressionBuilder()}var No=__esmMin((()=>{io(),gi(),Io(),ga(),fo(),wr(),Pr(),Nr(),eo(),tr(),ho(),jr(),Fa(),vo(),_o(),k(),Co(),Wn(),In(),To(),Cr(),Ao(),Mo()}));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 Po=__esmMin((()=>{Mn(),jn(),No(),k()}));function isAliasedDynamicTableBuilder(e){return isObject$1(e)&&isOperationNodeSource(e)&&isString(e.table)&&isString(e.alias)}var DynamicTableBuilder,AliasedDynamicTableBuilder,Fo=__esmMin((()=>{On(),M(),jn(),Io(),k(),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 Dn.create(parseTable(this.#e),j.create(this.#t))}}}));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 Dn.create(parseTable(n),j.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return kn.createWithSchema(t,n)}return kn.create(e)}function trim$1(e){return e.trim()}var Io=__esmMin((()=>{k(),On(),An(),Po(),M(),Fo()})),Lo,Ro=__esmMin((()=>{k(),Lo=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}})})),z,zo=__esmMin((()=>{k(),nr(),z=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})}})})),Bo,Vo=__esmMin((()=>{k(),nr(),Bo=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:N.create(e)})},cloneWith(e,t){return freeze({...e,...t})}})})),Ho,Uo=__esmMin((()=>{k(),nr(),Ho=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:N.create(e),renameTo:N.create(t)})}})})),Wo,Go=__esmMin((()=>{k(),M(),Wo=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?j.create(t):void 0})}})}));function isOnModifyForeignAction(e){return isString(e)&&Ko[e]}var Ko,qo,Jo=__esmMin((()=>{k(),Ko=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),Object.keys(Ko),qo=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 parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():kr.createImmediate(e)}var Yo=__esmMin((()=>{jn(),Ar()})),Xo,Zo=__esmMin((()=>{k(),Xo=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})}})})),Qo,$o=__esmMin((()=>{k(),Qo=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 es=__esmMin((()=>{Jo()})),ts,ns=__esmMin((()=>{Go(),Jo(),ir(),wr(),zo(),Yo(),Zo(),$o(),es(),ts=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||rr.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{references:qo.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(z.cloneWith(this.#e,{references:qo.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(z.cloneWith(this.#e,{references:qo.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{defaultTo:Qo.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{check:Wo.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{generated:Xo.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{generated:Xo.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{generated:Xo.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{generated:Xo.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(z.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(z.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(z.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}}})),rs,is=__esmMin((()=>{k(),rs=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}})})),as,os=__esmMin((()=>{k(),M(),Jo(),as=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:qo.create(t,n),name:r?j.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}})})),ss,cs=__esmMin((()=>{os(),es(),ss=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(as.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(as.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(as.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(as.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(as.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(as.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}})),ls,us=__esmMin((()=>{k(),ls=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}})})),ds,fs=__esmMin((()=>{gr(),k(),nr(),M(),ds=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})}})})),ps,ms=__esmMin((()=>{k(),M(),ps=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:j.create(e)})},cloneWith(e,t){return freeze({...e,...t})}})})),hs,gs=__esmMin((()=>{k(),nr(),hs=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:N.create(e),[t]:n})}})})),AlterColumnBuilder,AlteredColumnBuilder,_s=__esmMin((()=>{gs(),Ao(),Yo(),AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(hs.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(hs.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(hs.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(hs.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(hs.create(this.#e,`dropNotNull`,!0))}$call(e){return e(this)}},AlteredColumnBuilder=class{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}})),AlterTableExecutor,vs=__esmMin((()=>{k(),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)}}})),ys,bs=__esmMin((()=>{us(),un(),k(),ys=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:ls.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)}}})),xs,Ss=__esmMin((()=>{un(),ms(),k(),xs=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:ps.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:ps.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:ps.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)}}})),Cs,ws=__esmMin((()=>{k(),nr(),M(),Cs=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})}})})),Ts,Es=__esmMin((()=>{k(),M(),Ts=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]})}})})),Ds,Os=__esmMin((()=>{Es(),un(),ur(),wr(),k(),Ds=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ts.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ts.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:Ts.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:Ts.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ts.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)}}})),ks,As=__esmMin((()=>{fs(),ks=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(ds.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(ds.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(ds.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(ds.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(ds.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}})),js,Ms=__esmMin((()=>{ws(),js=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(Cs.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(Cs.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(Cs.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(Cs.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}})),CheckConstraintBuilder,Ns=__esmMin((()=>{CheckConstraintBuilder=class{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}})),Ps,Fs=__esmMin((()=>{k(),M(),Ps=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:j.create(e),newName:j.create(t)})}})})),Is,Ls=__esmMin((()=>{Vo(),k(),Is=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Bo.cloneWith(this.#e.node,{ifExists:!0})})}toOperationNode(){return this.#e.node}}})),AlterTableBuilder,Rs,zs=__esmMin((()=>{Ro(),un(),zo(),Vo(),M(),Uo(),k(),ns(),is(),Ao(),cs(),us(),fs(),Go(),os(),nr(),Io(),ms(),_s(),vs(),bs(),Ss(),ws(),Sn(),Es(),Os(),As(),Ms(),Ns(),Fs(),Po(),Ls(),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 Rs({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new Is({node:Bo.create(e)}));return new Rs({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new Rs({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,Ho.create(e,t))})}addColumn(e,t,n=noop){let r=n(new ts(z.create(e,parseDataTypeExpression(t))));return new Rs({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,Lo.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new ts(z.create(e,parseDataTypeExpression(t))));return new Rs({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,rs.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new ks(ds.create(t.map(e=>isString(e)?N.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addConstraint:ls.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Wo.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addConstraint:ls.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new ss(as.create(t.map(N.create),parseTable(n),r.map(N.create),e)));return new ys({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new js(Cs.create(t,e)));return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addConstraint:ls.create(r.toOperationNode())})})}dropConstraint(e){return new xs({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropConstraint:ps.create(e)})})}renameConstraint(e,t){return new xs({...this.#e,node:A.cloneWithTableProps(this.#e.node,{renameConstraint:Ps.create(e,t)})})}addIndex(e){return new Ds({...this.#e,node:A.cloneWithTableProps(this.#e.node,{addIndex:Ts.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:A.cloneWithTableProps(this.#e.node,{dropIndex:xn.create(e)})})}$call(e){return e(this)}},Rs=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 Is({node:Bo.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,Ho.create(e,t))})}addColumn(e,t,n=noop){let r=n(new ts(z.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,Lo.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new ts(z.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:A.cloneWithColumnAlteration(this.#e.node,rs.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,Bs=__esmMin((()=>{_a(),Or(),Ar(),ImmediateValueTransformer=class extends OperationNodeTransformer{transformPrimitiveValueList(e){return Dr.create(e.values.map(kr.createImmediate))}transformValue(e){return kr.createImmediate(e.value)}}})),Vs,Hs=__esmMin((()=>{pn(),ur(),wr(),Io(),k(),Pr(),hi(),Bs(),Vs=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:dn.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:dn.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:dn.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:dn.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:dn.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:dn.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:dn.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:dn.cloneWith(this.#e.node,{using:P.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:F.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)}}})),Us,Ws=__esmMin((()=>{hn(),k(),Us=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:mn.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(gn.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var Gs=__esmMin((()=>{vn()})),Ks,qs=__esmMin((()=>{Es(),ur(),Ks=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(Ts.cloneWith(this.#e,{using:P.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}}})),Js,Ys=__esmMin((()=>{zo(),vn(),ns(),k(),os(),nr(),cs(),Ao(),ws(),fs(),Go(),Io(),Gs(),As(),Po(),Ms(),Ns(),Es(),qs(),Js=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:_n.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:_n.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:_n.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new ts(z.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:_n.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new js(Cs.create(t,e)));return new CreateTableBuilder({...this.#e,node:_n.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new ks(ds.create(t.map(e=>isString(e)?N.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:_n.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new Ks(Ts.cloneWithColumns(Ts.create(e),t.map(e=>isString(e)?N.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:_n.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Wo.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:_n.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new ss(as.create(t.map(N.create),parseTable(n),r.map(N.create),e)));return new CreateTableBuilder({...this.#e,node:_n.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:_n.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:_n.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:_n.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)}}})),Xs,Zs=__esmMin((()=>{Sn(),Io(),k(),Xs=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:xn.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:xn.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:xn.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)}}})),Qs,$s=__esmMin((()=>{wn(),k(),Qs=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:Cn.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:Cn.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)}}})),ec,tc=__esmMin((()=>{En(),k(),ec=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:Tn.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:Tn.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:Tn.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)}}})),nc,rc=__esmMin((()=>{k(),bn(),nc=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:yn.create(e)})},cloneWith(e,t){return freeze({...e,...t})}})})),ImmediateValuePlugin,ic=__esmMin((()=>{Bs(),ImmediateValuePlugin=class{#e=new ImmediateValueTransformer;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}})),ac,oc=__esmMin((()=>{k(),rc(),wr(),ic(),ac=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:nc.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)}}})),sc,cc=__esmMin((()=>{k(),bn(),sc=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:yn.create(e)})},cloneWith(e,t){return freeze({...e,...t})}})})),lc,uc=__esmMin((()=>{k(),cc(),lc=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:sc.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:sc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:sc.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)}}})),dc,fc=__esmMin((()=>{k(),Or(),Ar(),dc=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Dr.create(t.map(kr.createImmediate))})}})})),pc,mc=__esmMin((()=>{k(),fc(),pc=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:dc.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)}}})),hc,gc=__esmMin((()=>{k(),hc=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})}})})),_c,vc=__esmMin((()=>{gc(),k(),_c=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:hc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:hc.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 yn.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return yn.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}var yc=__esmMin((()=>{bn()})),bc,xc=__esmMin((()=>{k(),bn(),bc=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:yn.create(e)})},cloneWith(e,t){return freeze({...e,...t})}})})),Sc,Cc=__esmMin((()=>{k(),xc(),Sc=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:bc.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:bc.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:bc.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)}}})),wc,Tc=__esmMin((()=>{k(),wc=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}})})),Ec,Dc=__esmMin((()=>{k(),Ec=freeze({is(e){return e.kind===`AddValueNode`},create(e){return freeze({kind:`AddValueNode`,value:e})},cloneWith(e,t){return freeze({...e,...t})}})})),QueryFinalizer,Oc=__esmMin((()=>{k(),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)}}})),kc,AlterTypeAddValueBuilder,Ac=__esmMin((()=>{Dc(),Ar(),Tc(),Oc(),AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new kc({...this.#e,node:wc.cloneWith(this.#e.node,{addValue:Ec.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 kc({...this.#e,node:wc.cloneWith(this.#e.node,{addValue:Ec.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:kr.createImmediate(e)})})})}},kc=AlterTypeAddValueBuilder})),jc,Mc=__esmMin((()=>{k(),jc=freeze({is(e){return e.kind===`RenameValueNode`},create(e,t){return freeze({kind:`RenameValueNode`,oldValue:e,newValue:t})}})})),AlterTypeBuilder,Nc=__esmMin((()=>{k(),Tc(),M(),Ac(),Dc(),Ar(),Oc(),Mc(),AlterTypeBuilder=class{#e;constructor(e){this.#e=freeze(e)}addValue(e){return new AlterTypeAddValueBuilder({...this.#e,node:wc.cloneWith(this.#e.node,{addValue:Ec.create(kr.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:wc.cloneWith(this.#e.node,{renameTo:j.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:wc.cloneWith(this.#e.node,{renameValue:jc.create(kr.createImmediate(e),kr.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:wc.cloneWith(this.#e.node,{setSchema:j.create(e)})})}}})),Pc,Fc=__esmMin((()=>{un(),pn(),hn(),vn(),Sn(),wn(),En(),Io(),zs(),Hs(),Ws(),Ys(),Zs(),$s(),tc(),ga(),Ca(),oc(),rc(),uc(),cc(),mc(),vc(),fc(),gc(),yc(),Cc(),xc(),Nc(),Tc(),Pc=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new Js({queryId:createQueryId(),executor:this.#e,node:_n.create(parseTable(e))})}dropTable(e){return new ec({queryId:createQueryId(),executor:this.#e,node:Tn.create(parseTable(e))})}createIndex(e){return new Vs({queryId:createQueryId(),executor:this.#e,node:dn.create(e)})}dropIndex(e){return new Xs({queryId:createQueryId(),executor:this.#e,node:xn.create(e)})}createSchema(e){return new Us({queryId:createQueryId(),executor:this.#e,node:mn.create(e)})}dropSchema(e){return new Qs({queryId:createQueryId(),executor:this.#e,node:Cn.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:A.create(parseTable(e))})}createView(e){return new ac({queryId:createQueryId(),executor:this.#e,node:nc.create(e)})}refreshMaterializedView(e){return new Sc({queryId:createQueryId(),executor:this.#e,node:bc.create(e)})}dropView(e){return new lc({queryId:createQueryId(),executor:this.#e,node:sc.create(e)})}createType(e){return new pc({queryId:createQueryId(),executor:this.#e,node:dc.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:wc.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new _c({queryId:createQueryId(),executor:this.#e,node:hc.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,Ic=__esmMin((()=>{sr(),Fo(),DynamicModule=class{ref(e){return new DynamicReferenceBuilder(e)}table(e){return new DynamicTableBuilder(e)}}})),DefaultConnectionProvider,Lc=__esmMin((()=>{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)}}}})),Rc,zc=__esmMin((()=>{Ma(),Rc=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 Bc=__esmMin((()=>{k()})),ConnectionMutex,Vc=__esmMin((()=>{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,Hc=__esmMin((()=>{Aa(),Bc(),Vc(),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}}})),ignoreError,SingleConnectionProvider,Uc=__esmMin((()=>{ignoreError=()=>{},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)}}}));function validateTransactionSettings(e){if(e.accessMode&&!Wc.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Gc.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}var Wc,Gc,Kc=__esmMin((()=>{Wc=[`read only`,`read write`],Gc=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`]}));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})}`))}var qc,Log,Jc=__esmMin((()=>{k(),qc=[`query`,`error`],freeze(qc),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 isCompilable(e){return isObject$1(e)&&isFunction(e.compile)}var Yc=__esmMin((()=>{k()}));function isKyselyProps(e){return isObject$1(e)&&isObject$1(e.config)&&isObject$1(e.driver)&&isObject$1(e.executor)&&isObject$1(e.dialect)}function assertNotCommittedOrRolledBack(e){if(e.isCommitted)throw Error(`Transaction is already committed`);if(e.isRolledBack)throw Error(`Transaction is already rolled back`)}var Xc,Zc,ConnectionBuilder,Qc,$c,el,Command$1,tl,nl=__esmMin((()=>{Fc(),Ic(),Lc(),Va(),zc(),k(),Hc(),Uc(),Kc(),fo(),Jc(),ga(),Yc(),vo(),_o(),Po(),Ca(),Oa(),Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`),Xc=class Kysely extends Ba{#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 Log(e.log??[]),l=new RuntimeDriver(i,s,c),u=new DefaultConnectionProvider(l),d=new Rc(a,s,u,e.plugins??[]);t={executor:d},n={config:e,executor:d,dialect:r,driver:l}}super(t),this.#e=freeze(n)}get schema(){return new Pc(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:go.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Qc({...this.#e})}startTransaction(){return new $c({...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()}},Zc=class Transaction extends Xc{#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})}},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 Xc({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Qc=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 tl(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),s=new Zc({...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}})}},$c=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 el({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},el=class ControlledTransaction extends Zc{#e;#t;constructor(e){e={...e,executor:new tl(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()}},tl=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)}}}));function createRawBuilder(e){return new rl(e)}var rl,AliasedRawBuilderImpl,il=__esmMin((()=>{On(),k(),Fa(),M(),jn(),rl=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?Pa: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)}},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 Dn.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():j.create(this.#t))}}}));function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var al,ol=__esmMin((()=>{M(),jn(),ur(),Ar(),wr(),Io(),jr(),ga(),il(),al=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(kr.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:P.createWithSql(e)})},join(e,t=al`, `){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)})}})})),OperationNodeVisitor,sl=__esmMin((()=>{k(),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()}}})),cl,ll,DefaultQueryCompiler,ul,dl,fl,pl=__esmMin((()=>{vn(),Jr(),sl(),tr(),Nr(),ur(),k(),rc(),Xa(),ui(),cl=/'/g,ll=/['"]/g,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&&!Mr.is(this.parentNode)&&!qr.is(this.parentNode)&&!_n.is(this.parentNode)&&!nc.is(this.parentNode)&&!Ya.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&&!Mr.is(this.parentNode)&&!P.is(this.parentNode)&&!li.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&&!Mr.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(fl[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&&!Mr.is(this.parentNode)&&!P.is(this.parentNode)&&!li.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(ul[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 er.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||!_n.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(cl,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(ll,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?dl[e.modifier]-dl[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}},ul=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),dl=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),fl=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`})})),ml,hl=__esmMin((()=>{ur(),k(),ga(),ml=freeze({raw(e,t=[]){return freeze({sql:e,query:P.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}})})),gl=__esmMin((()=>{})),DialectAdapterBase,_l=__esmMin((()=>{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 vl=__esmMin((()=>{M(),ur()})),SqliteDriver,SqliteConnection,yl=__esmMin((()=>{gi(),vl(),hl(),k(),ga(),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(ml.raw(`begin`))}async commitTransaction(e){await e.executeQuery(ml.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(ml.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(!I.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]}}}})),bl,xl,SqliteQueryCompiler,Sl=__esmMin((()=>{pl(),bl=/"/g,xl=/[\\'"]/g,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(bl,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(xl,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}}})),Cl,wl,Tl=__esmMin((()=>{k(),Cl=`kysely_migration`,wl=`kysely_migration_lock`,freeze({__noMigrations__:!0})})),SqliteIntrospector,El=__esmMin((()=>{Tl(),ol(),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`,`!=`,Cl).where(`name`,`!=`,wl)),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`,al`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,Dl=__esmMin((()=>{_l(),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,Ol=__esmMin((()=>{yl(),Sl(),El(),Dl(),k(),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)}var kl=__esmMin((()=>{k()})),Al=__esmMin((()=>{})),jl=__esmMin((()=>{})),Ml=__esmMin((()=>{})),Nl=__esmMin((()=>{})),Pl=__esmMin((()=>{})),Fl,PostgresDriver,PostgresConnection,Il=__esmMin((()=>{vl(),hl(),k(),ga(),kl(),Fl=Symbol(),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(ml.raw(n))}async commitTransaction(e){await e.executeQuery(ml.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(ml.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[Fl]()}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}}[Fl](){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(ml.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,Ll=__esmMin((()=>{Tl(),k(),ol(),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`,al`col_description(a.attrelid, a.attnum)`.as(`column_description`),al`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(al`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`,`!=`,Cl).where(`c.relname`,`!=`,wl));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}}})),Rl,PostgresQueryCompiler,zl=__esmMin((()=>{pl(),Rl=/"/g,PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(Rl,`""`)}}})),Bl,Vl,PostgresAdapter,Hl=__esmMin((()=>{ol(),_l(),Bl=BigInt(`3853314791062309107`),Vl=36e5,PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await al`
    with set_timeout as (
      select set_config('lock_timeout', '${al.lit(Vl)}', true) as config_val
    )
    select pg_advisory_lock(${al.lit(Bl)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await al`select pg_advisory_unlock(${al.lit(Bl)})`.execute(e)}}})),PostgresDialect,Ul=__esmMin((()=>{Il(),Ll(),zl(),Hl(),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)}}})),Wl=__esmMin((()=>{})),Gl=__esmMin((()=>{})),Kl=__esmMin((()=>{})),ql=__esmMin((()=>{})),Jl=__esmMin((()=>{})),Yl=__esmMin((()=>{})),Xl=__esmMin((()=>{})),Zl=__esmMin((()=>{})),Ql=__esmMin((()=>{})),$l=__esmMin((()=>{})),eu=__esmMin((()=>{})),tu=__esmMin((()=>{})),nu=__esmMin((()=>{})),ru=__esmMin((()=>{})),iu=__esmMin((()=>{})),au=__esmMin((()=>{})),ou=__esmMin((()=>{nl(),Va(),Oc(),Mn(),No(),eo(),io(),Xi(),ia(),ta(),Ri(),vi(),fo(),Li(),Zi(),na(),Ui(),uo(),vo(),Co(),za(),Ia(),mr(),il(),ol(),zc(),Fa(),pl(),hl(),Fc(),Ys(),mc(),tc(),vc(),Hs(),Zs(),Ws(),$s(),ns(),cs(),zs(),oc(),Cc(),uc(),_s(),Ls(),Ic(),sr(),Fo(),Kc(),Lc(),Uc(),gl(),_l(),Ol(),yl(),Sl(),El(),Dl(),Pl(),Al(),jl(),Ml(),Nl(),Il(),Ul(),zl(),Ll(),Hl(),Wl(),Jl(),Gl(),Kl(),ql(),Yl(),Xl(),Zl(),pl(),Ql(),$l(),Ca(),eu(),tu(),nu(),ru(),Ro(),us(),Es(),oo(),On(),gs(),un(),In(),Wn(),_o(),Mo(),Go(),fr(),zo(),nr(),Ni(),oa(),ca(),iu(),pn(),hn(),vn(),fc(),rc(),xc(),ko(),Ai(),$o(),ni(),Vo(),ms(),Sn(),wn(),En(),gc(),cc(),ci(),no(),os(),Hr(),co(),Zo(),qa(),Wr(),Kr(),M(),Jr(),Hn(),xr(),bo(),Cr(),yr(),$i(),Xr(),Ta(),fi(),is(),Ga(),Bi(),Ii(),Bn(),jn(),_a(),sl(),tr(),Ji(),Rn(),lr(),Ir(),mi(),Br(),Nr(),bi(),Rr(),ws(),Er(),hi(),ur(),or(),Jo(),Uo(),Fs(),oi(),bn(),ir(),Pn(),gi(),Ti(),Xa(),au(),An(),Gi(),To(),mo(),fs(),Qr(),ei(),Or(),Ar(),Oi(),ui(),ii(),pa(),Tc(),Dc(),Mc(),Yc(),Jc(),gr(),ga()}));function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=su.exec(e.trim());if(!t)return null;let n={major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])};return Object.values(n).every(Number.isSafeInteger)&&(!t[4]||n.major>lu.major)?n:null}function isNodeVersionAtLeast(e,t){return e?e.major===t.major?e.minor===t.minor?e.patch>=t.patch:e.minor>t.minor:e.major>t.major:!1}function renderProcessNodeVersionCheck(){return`((value) => {
  if (typeof value !== "string") return false;
  const match = new RegExp(${JSON.stringify(su.source)}, "u").exec(value.trim());
  if (!match) return false;
  const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
  if (!Object.values(version).every(Number.isSafeInteger)) return false;
  const floors = ${JSON.stringify(cu)};
  if (match[4] && version.major <= floors[floors.length - 1].major) return false;
  const minimum = floors.find((floor) => floor.major === version.major);
  const atLeast = (floor) =>
    version.major > floor.major ||
    (version.major === floor.major &&
      (version.minor > floor.minor ||
        (version.minor === floor.minor && version.patch >= floor.patch)));
  return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major;
})(process.versions.node)`}var su,cu,lu,uu,du=__esmMin((()=>{su=/^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,cu=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],lu=cu[cu.length-1],uu=cu.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<cu.length-1?` <${e+1}`:``}`).join(` || `),`${uu.replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`,renderProcessNodeVersionCheck()}));function resolveGlobalSingletonResetRegistry(){let e=globalThis,t=e[fu];if(t instanceof Map)return t;let n=/* @__PURE__ */ new Map;return e[fu]=n,n}function readGlobalSingleton(e){let t=globalThis;return Object.hasOwn(t,e)?t[e]:void 0}function resolveGlobalSingleton(e,t,n,r=`close-and-restart`){let i=globalThis,a;return Object.hasOwn(i,e)?a=i[e]:(a=t(),i[e]=a),n&&resolveGlobalSingletonResetRegistry().set(e,{lifecycle:r,reset:()=>n(a)}),a}function resolveGlobalMap(e,t,n){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Map,typeof t==`string`?e=>e.clear():t,typeof t==`string`?t:n)}function resolveGlobalSet(e,t){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Set,e=>e.clear(),t)}var fu,B=__esmMin((()=>{fu=Symbol.for(`openclaw.globalSingletonLifecycleResets`)}));function notifyListeners(e,t,n){for(let r of e)try{r(t)}catch(e){n?.(e)}}function registerListener(e,t){return e.add(t),()=>e.delete(t)}var pu=__esmMin((()=>{}));function isPromiseLike(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)return!1;try{return typeof e.then==`function`}catch{return!1}}var mu=__esmMin((()=>{}));function assertSyncTransactionResult$1(e){if(isPromiseLike(e))throw Error(`SQLite write transactions must be synchronous; Promise returns are not supported.`)}function isPostgresSqlConnection(e){return hu in e&&e[hu]===!0}function sqlPublicationAnchor(e){return isPostgresSqlConnection(e)?e.anchor:e}var hu,gu=__esmMin((()=>{mu(),hu=Symbol.for(`openclaw.postgres-sync-connection`)}));function disposeSqliteStatement(e){e[Symbol.dispose]?.()}function clearStatementCache(e){let t=e[yu];if(delete e[yu],t)for(let e of t.statements.values())t.active.has(e)||disposeSqliteStatement(e)}function registerNodeSqliteDisposeCallback(e,t){let n=e;return installStatementInvalidation(n),registerListener(n[Cu]??=/* @__PURE__ */ new Set,t)}function assertNodeSqliteDisposalAllowed(e){for(let t of e[wu]??[])t()}function disposeNodeSqliteDependents(e,t=`close`){assertNodeSqliteDisposalAllowed(e);for(let n of e[Cu]??[])n(t)}function registerNodeSqliteKyselyQueryErrorHandler(e,t){vu.set(e,t)}function clearNodeSqliteKyselyCacheForDatabase(e){clearStatementCache(e),_u.delete(e),vu.delete(e)}function installStatementInvalidation(e){if(!e[bu]){if(typeof e.setAuthorizer==`function`){let t=e.setAuthorizer.bind(e);Object.defineProperty(e,"setAuthorizer",{configurable:!0,writable:!0,value(e){t(e),this[Su]=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,bu,{configurable:!0,value:!0})}}function queryFitsStatementCache(e,t){let n=Buffer.byteLength(e);if(n>Eu)return!1;for(let e of t){if(typeof e==`string`){if(e.length>Eu-n)return!1;n+=Buffer.byteLength(e)}else ArrayBuffer.isView(e)&&(n+=e.byteLength);if(n>Eu)return!1}return!0}function executeWithCachedStatement(e,t,n,r,i){if(isPostgresSqlConnection(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[xu]||a[Su]||!queryFitsStatementCache(t,n)){let n=e.prepare(t);return executeLeased(n,()=>disposeSqliteStatement(n))}let s=a[yu];s||(s={statements:/* @__PURE__ */ new Map,candidates:/* @__PURE__ */ new Set,active:/* @__PURE__ */ new WeakSet},Object.defineProperty(a,yu,{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>Tu){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>Tu)){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[yu]!==s||s.statements.get(t)!==l)&&disposeSqliteStatement(l)})}var _u,vu,yu,bu,xu,Su,Cu,wu,Tu,Eu,Du=__esmMin((()=>{B(),pu(),gu(),{kyselyByDatabase:_u,queryErrorHandlerByDatabase:vu}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap})),yu=Symbol.for(`openclaw.kyselySyncStatementCache`),bu=Symbol.for(`openclaw.kyselySyncStatementInvalidation`),xu=Symbol.for(`openclaw.kyselySyncStatementCacheEnabled`),Su=Symbol.for(`openclaw.kyselySyncAuthorizerActive`),Cu=Symbol.for(`openclaw.sqliteDisposeCallbacks`),wu=Symbol.for(`openclaw.sqliteDisposeGuards`),Tu=64,Eu=65536}));function postgresStringArray(e){if(!P.is(e)||e.sqlFragments!==Ou||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(!kr.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 templateFragments,Ou,ku,OpenClawPostgresQueryCompiler,OpenClawPostgresDialect,Au=__esmMin((()=>{ou(),templateFragments=(e,t)=>e,Ou=templateFragments`(SELECT value FROM json_each(${0}))`,ku=templateFragments`json_each(${0})`,OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(er.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===Ou;!t&&e.sqlFragments!==ku?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}}})),ju=__esmMin((()=>{})),Mu=__esmMin((()=>{})),Nu,Pu=__esmMin((()=>{Nu=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]],RegExp(`[${Nu.flatMap(e=>e.map(([e,t])=>`\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join(``)}]`,`u`),(()=>{let e=Math.max(...Nu.flatMap(e=>e.map(([,e])=>e))),t=new Uint8Array(e+1);for(let[e,n]of Nu.entries())for(let[r,i]of n)t.fill(e+1,r,i+1);return t})()})),Fu=__esmMin((()=>{}));function expectDefined(e,t){if(e==null)throw Error(`expected `+t+` to be defined`);return e}var Iu=__esmMin((()=>{}));function formatByteSize(e,t){let{base:n,labels:r}=Ru[t.style],i=Lu.indexOf(t.maxUnit),a=0,s=e;for(;s>=n&&a<i;)s/=n,a+=1;let c=expectDefined(Lu[a],`byte-size unit`),l=expectDefined(r[a],`byte-size label`),u=typeof t.fractionDigits==`function`?t.fractionDigits(s,c):t.fractionDigits;return u===null?`${s}${t.separator}${l}`:(t.floorUnits?.includes(c)&&(s=Math.floor(s*10**u)/10**u),`${s.toFixed(u)}${t.separator}${l}`)}var Lu,Ru,zu=__esmMin((()=>{Iu(),Lu=[`byte`,`kilo`,`mega`,`giga`,`tera`],Ru={iec:{base:1024,labels:[`B`,`KiB`,`MiB`,`GiB`,`TiB`]},"legacy-binary":{base:1024,labels:[`B`,`KB`,`MB`,`GB`,`TB`]}}})),Bu=__esmMin((()=>{}));function asFiniteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function asSafeIntegerInRange(e,t){if(typeof e==`number`&&Number.isSafeInteger(e)&&!(t.min!==void 0&&e<t.min)&&!(t.max!==void 0&&e>t.max))return e}function resolveTimerTimeoutMs(e,t,n=1){let r=asFiniteNumber(e)??asFiniteNumber(t),i=Math.max(0,Math.floor(n));return r===void 0?i:Math.min(Math.max(Math.floor(r),i),Vu)}function resolveIntegerOption(e,t,n={}){let r=asFiniteNumber(e)??t,i=Math.floor(r),a=n.min===void 0?i:Math.max(n.min,i);return n.max===void 0?a:Math.min(n.max,a)}function resolveNonNegativeIntegerOption(e,t){return resolveIntegerOption(e,t,{min:0})}var Vu,Hu,Uu=__esmMin((()=>{Vu=2147e6,Math.floor(Vu/1e3),Hu=864e13})),Wu=__esmMin((()=>{})),Gu=__esmMin((()=>{}));function normalizeStringEntries(e){return(e??[]).map(e=>String(e).trim()).filter(Boolean)}function normalizeStringEntriesLower(e){return normalizeStringEntries(e).map(e=>e.toLowerCase())}function uniqueValues(e){return[...new Set(e)]}function uniqueStrings(e){return uniqueValues(e)}function normalizeUniqueStringEntriesLower(e){return uniqueStrings(normalizeStringEntriesLower(e?[...e]:void 0))}var Ku=__esmMin((()=>{})),qu=__esmMin((()=>{}));function isHighSurrogate(e){return e>=55296&&e<=56319}function isLowSurrogate(e){return e>=56320&&e<=57343}function sliceUtf16Safe(e,t,n){let r=e.length,i=t<0?Math.max(r+t,0):Math.min(t,r),a=n===void 0?r:n<0?Math.max(r+n,0):Math.min(n,r);return a<=i?``:(i>0&&i<r&&isLowSurrogate(e.charCodeAt(i))&&isHighSurrogate(e.charCodeAt(i-1))&&(i+=1),a>0&&a<r&&isHighSurrogate(e.charCodeAt(a-1))&&isLowSurrogate(e.charCodeAt(a))&&--a,e.slice(i,a))}function truncateUtf16Safe(e,t){let n=Math.max(0,Math.floor(t));return e.length<=n?e:sliceUtf16Safe(e,0,n)}var Ju=__esmMin((()=>{})),Yu=__esmMin((()=>{ju(),Mu(),Pu(),Fu(),O(),Iu(),zu(),Bu(),Uu(),D(),Wu(),Gu(),Lt(),Ku(),qu(),Ju()}));function clearActiveProgressLine(){Xu?.isTTY&&Xu.write(`\r\x1B[2K`)}var Xu,Zu=__esmMin((()=>{Xu=null}));function isVerbose(){return Qu}var Qu,$u=__esmMin((()=>{Qu=!1}));function isInternalDiagnosticEventInterested(e,t,n){return(!e?.include||e.include.includes(t))&&!e?.exclude?.includes(t)&&(!n||!e?.includeTrusted||e.includeTrusted.includes(t))}function hasInternalDiagnosticEventInterest(e,t=!1){let n=t?ed.trustedInterest:ed.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}var ed,td=__esmMin((()=>{B(),ed=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticEventListenerPresence.v1`),()=>({untrustedInterest:{broadInterestCount:0,eventInterestDeltas:/* @__PURE__ */ new Map},trustedInterest:{broadInterestCount:0,eventInterestDeltas:/* @__PURE__ */ new Map},interestListeners:/* @__PURE__ */ new Map,internalCount:0,trustedCount:0,promptStatsCount:0}))}));function enterAsyncStore(e,t){return this.enterWith(e),t()}function runWithAsyncStore(e,t,n){return e.getStore()===t?n():new Ce(`OpenClawAsyncStore`).runInAsyncScope(enterAsyncStore,e,t,n)}var nd=__esmMin((()=>{}));function createPluginExecutionFrame(e,t){return t?t.withScopes(e):new rd(e)}var rd,id,ad,od=__esmMin((()=>{nd(),B(),rd=class InvocationFrame{constructor(e,t=e.invocation){this.retentionOwner=e.retentionOwner,this.invocation=t,this.metadataScope=e.metadataScope,this.cacheScope=e.cacheScope,this.sourceCaptureStorage=e.sourceCaptureStorage}get runtimePluginId(){}withScopes(e){return new InvocationFrame(e)}},id=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new C;return{invocation:{getStore(){return e.getStore()?.invocation},run(t,n){let r=e.getStore();return r?.invocation===t?n():runWithAsyncStore(e,createPluginExecutionFrame({...r,invocation:t},r),n)},exit(t){let n=e.getStore();return n?.invocation?runWithAsyncStore(e,n.withScopes({...n,invocation:void 0}),t):t()}},getFrame(){return e.getStore()},runFrame(t,n){return runWithAsyncStore(e,t,n)}}}),id.invocation,ad=id.getFrame,id.runFrame})),V,sd,cd,ld,ud=__esmMin((()=>{V={priority:!1,publicExcluded:!1},sd=[{...V,name:`worker.request`},{...V,name:`diagnostic.gc`,publicExcluded:!0},{...V,name:`gateway.event_loop.sample`,publicExcluded:!0},{...V,name:`gateway.main_thread.stall`,publicExcluded:!0},{...V,name:`gateway.http.cancelled`,publicExcluded:!0},{...V,name:`gateway.rpc`,publicExcluded:!0},{...V,name:`sessions.list.baseline.retired`},{...V,name:`sessions.list.retention`,publicExcluded:!0},{...V,name:`sessions.event.retention`,publicExcluded:!0},{...V,name:`sessions.event.rows.reset`,publicExcluded:!0},{...V,name:`gateway.ws.event`,publicExcluded:!0},{...V,name:`gateway.ws.connections`,publicExcluded:!0},{...V,name:`tool.execution.started`},{...V,name:`tool.execution.completed`,priority:!0},{...V,name:`tool.execution.error`,priority:!0},{...V,name:`tool.execution.blocked`,priority:!0},{...V,name:`skill.used`},{...V,name:`exec.process.completed`},{...V,name:`exec.approval.followup_suppressed`},{...V,name:`message.delivery.started`},{...V,name:`message.delivery.completed`},{...V,name:`message.delivery.error`},{...V,name:`talk.event`},{...V,name:`model.call.started`},{...V,name:`model.call.completed`,priority:!0},{...V,name:`model.call.error`,priority:!0},{...V,name:`model.response.observed`},{...V,name:`run.progress`},{...V,name:`run.execution_phase`},{...V,name:`agent.commentary`},{...V,name:`harness.run.completed`,priority:!0},{...V,name:`harness.run.error`,priority:!0},{...V,name:`context.assembled`},{...V,name:`log.record`,publicExcluded:!0}],cd=sd.map(e=>e.name),ld=sd.filter(e=>e.priority).map(e=>e.name),sd.filter(e=>e.publicExcluded).map(e=>e.name)})),dd,AsyncContext,fd=__esmMin((()=>{B(),dd=resolveGlobalSingleton(Symbol.for(`openclaw.asyncContext`),()=>new C),AsyncContext=class{constructor(e){this.key=e}getStore(){return dd.getStore()?.[this.key]}run(e,t){let n=dd.getStore(),r=n?.[this.key];if(Object.is(r,e))return t();let i={...n,[this.key]:e};dd.enterWith(i);try{return t()}finally{let e=dd.getStore();dd.enterWith(e===i?n:{...e,[this.key]:r})}}exit(e){return this.run(void 0,e)}enterWith(e){dd.enterWith({...dd.getStore(),[this.key]:e})}}}));function isNonZeroHex(e){return!/^0+$/.test(e)}function isValidDiagnosticTraceId(e){return typeof e==`string`&&pd.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&md.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&hd.test(e)}function getActiveDiagnosticTraceContext(){return _d.getStore()}var pd,md,hd,gd,_d,vd=__esmMin((()=>{Yu(),fd(),pd=/^[0-9a-f]{32}$/,md=/^[0-9a-f]{16}$/,hd=/^[0-9a-f]{2}$/,gd=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`),_d=new AsyncContext(gd)}));function isBlockedObjectKey(e){return yd.has(e)}var yd,bd=__esmMin((()=>{yd=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`])}));function cloneDiagnosticValueForListener(e,t=!1){if(xd.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return xd.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&xd.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return xd.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(xd.has(e)||t?.has(e))return!0;let n=Object.getPrototypeOf(e);if(!Object.isFrozen(e)||n!==Object.prototype&&n!==Array.prototype&&n!==null)return!1;let r=t;return Reflect.ownKeys(e).every(t=>{let n=Object.getOwnPropertyDescriptor(e,t);return typeof t==`symbol`||!(`value`in n)?!1:(n.value&&typeof n.value==`object`&&(r??=/* @__PURE__ */ new WeakSet).add(e),isImmutableDiagnosticValue(n.value,r))})}function freezeDiagnosticValue(e,t){if(!e||typeof e!=`object`||t.has(e))return!0;if(ArrayBuffer.isView(e))return!1;t.add(e);let n=Object.getPrototypeOf(e),r=n===Object.prototype||n===Array.prototype||n===null;for(let n of Object.values(e))freezeDiagnosticValue(n,t)||(r=!1);return Object.freeze(e),r}function enrichDiagnosticEvent(e,t,n=!0){let r={};for(let[e,n]of Object.entries(t))isBlockedObjectKey(e)||(r[e]=n);return n&&(r.trace??=getActiveDiagnosticTraceContext()),e.seq+=1,r.seq=e.seq,r.ts=Date.now(),r}function captureQueuedDiagnosticEvent(e,t){try{let n=!1,r=!1;if(e.privateData||e.trustedListenersOnly){for(let i of t)if(isInternalDiagnosticEventInterested(i,e.event.type,e.metadata.trusted)&&(n=!0,i?.includePrivateData!==!1)){r=!0;break}}if(e.trustedListenersOnly&&!n)return!1;if(e.event=cloneDiagnosticValueForListener(e.event,!0),e.privateData)try{e.privateData=r?cloneDiagnosticValueForListener(e.privateData):void 0}catch(t){e.privateData=void 0,console.error(`[diagnostic-events] private snapshot error type=${e.event.type}: ${String(t)}`)}return!0}catch(t){return console.error(`[diagnostic-events] queue snapshot error type=${e.event.type}: ${String(t)}`),!1}}var xd,Sd=__esmMin((()=>{td(),vd(),bd(),xd=/* @__PURE__ */ new WeakSet})),Cd,wd=__esmMin((()=>{Cd=`coreModelRequestLifecycle`}));function isTrustedOtelDiagnosticListener(e){return Td.has(e)}var Td,Ed=__esmMin((()=>{Td=/* @__PURE__ */ new WeakSet}));function consumeHostPluginUsageDiagnosticEvent(e){let t=Dd.get(e);return Dd.delete(e),t}var Dd,Od=__esmMin((()=>{Dd=/* @__PURE__ */ new WeakMap}));function consumeCoreSemanticRunProgressDiagnosticEvent(e){let t=Ad.get(e);return Ad.delete(e),t}var kd,Ad,jd=__esmMin((()=>{kd=`coreSemanticRunProgress`,Ad=/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){let t=Nd.events.get(e);return Nd.events.delete(e),t}var Md,Nd,Pd=__esmMin((()=>{fd(),B(),Md=`toolExecutionLiveness`,Nd=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new AsyncContext(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}))}));function hasDiagnosticTracePropagationConsumer(){return Id.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=Id.activeBridge;if(!t?.prepareEvent)return!1;if(!t.shouldPrepareEvent)return!0;try{return t.shouldPrepareEvent(e)}catch(e){return console.error(`[diagnostic-trace-propagation] prepare filter error: ${String(e)}`),!1}}function prepareDiagnosticTracePropagation(e,t){let n=Id.activeBridge;if(n?.prepareEvent)try{n.prepareEvent(e,t)}catch(t){console.error(`[diagnostic-trace-propagation] prepare error type=${e.type} seq=${e.seq}: ${String(t)}`)}}var Fd,Id,Ld=__esmMin((()=>{B(),vd(),Fd=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),Id=resolveGlobalSingleton(Fd,()=>({marker:Fd,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}))}));function hasNonzeroUsage(e){return!e||e.usageReport?.state===`unavailable`?!1:[e.input,e.output,e.cacheRead,e.cacheWrite,e.contextUsage?.state===`available`?e.contextUsage.promptTokens:void 0,e.contextUsage?.state===`available`?e.contextUsage.totalTokens:void 0,e.reasoningTokens,e.total].some(e=>typeof e==`number`&&Number.isFinite(e)&&e>0)||e.contextUsage?.state===`unavailable`}function hasRecordedUsageCost(e){let t=asOptionalRecord(e),n=asFiniteNumber(t?.total);return n!==void 0&&n>=0&&(n>0||t?.totalOrigin===`provider-billed`||Rd.some(e=>(asFiniteNumber(t?.[e])??0)!==0))}function hasObservedModelUsage(e){return e?.usageReport!==void 0||hasRecordedUsageCost(e?.cost)||hasNonzeroUsage(e)}var Rd,zd=__esmMin((()=>{Uu(),D(),Rd=[`input`,`output`,`cacheRead`,`cacheWrite`]}));function parseDiagnosticEnvFlags(e){let t=e?.trim()??``,n=t.toLowerCase();return n?[`0`,`false`,`off`,`none`].includes(n)?{flags:[],disablesAll:!0}:[`1`,`true`,`all`,`*`].includes(n)?{flags:[`*`],disablesAll:!1}:{flags:t.split(/[,\s]+/),disablesAll:!1}:{flags:[],disablesAll:!1}}var Bd=__esmMin((()=>{}));function isDiagnosticFlagEnabled(e,t,n=process.env){let r=t?.diagnostics?.flags??[],i=parseDiagnosticEnvFlags(n[Vd]),a=i.disablesAll?[]:normalizeUniqueStringEntriesLower([...r,...i.flags]),s=normalizeLowercaseStringOrEmpty(e);if(!s)return!1;for(let e of a)if(e===`*`||e===`all`||e===s||e.endsWith(`.*`)&&s===e.slice(0,-2)||e.endsWith(`*`)&&s.startsWith(e.slice(0,-1)))return!0;return!1}var Vd,Hd=__esmMin((()=>{Lt(),Ku(),Bd(),Vd=`OPENCLAW_DIAGNOSTICS`}));function nativeModeIsValid(e){let t=e?.trim().toLowerCase()??``;return/^(?:0|false|off|never|1|true|on|auto|required|require)$/u.test(t)}function currentFallback(e){let t=Kd.get(e);return t&&e[t.key]===t.value?t:void 0}function fsSafeEnvInput(e){let t=currentFallback(e);if(!t)return e;let n={...e,[t.key]:t.previous};return t.existed||delete n[t.key],n}function clearFsSafeEnvFallback(e){let t=currentFallback(e);Kd.delete(e),t&&(t.existed?e[t.key]=t.previous:delete e[t.key])}function normalizeFsSafeNativeEnv(e=process.env){clearFsSafeEnvFallback(e);let t=Gd.filter(t=>e[t]!==void 0);if(t.length&&e===process.env&&!qd&&(qd=!0,process.emitWarning(`${t.join(`, `)} is deprecated. OpenClaw maps legacy mode values to native mode only when neither FS_SAFE_NATIVE_MODE nor OPENCLAW_FS_SAFE_NATIVE_MODE selects a mode. Replace Python mode variables with native mode variables; interpreter path settings are ignored.`,{code:`FS_SAFE_PYTHON_DEPRECATED`,type:`DeprecationWarning`})),nativeModeIsValid(e.FS_SAFE_NATIVE_MODE)||nativeModeIsValid(e[Ud]))return;let n=Wd.map(t=>e[t]).find(e=>e!==void 0);if(n===void 0)return;let r=Object.keys(e),i=!r.includes(Ud)&&Object.hasOwn(e,Ud)?r.find(e=>e.toUpperCase()===Ud)??Ud:Ud,a=Object.hasOwn(e,i),s=e[i];e[i]=n,Kd.set(e,{key:i,value:n,previous:s,existed:a})}var Ud,Wd,Gd,Kd,qd,Jd=__esmMin((()=>{Ud=`OPENCLAW_FS_SAFE_NATIVE_MODE`,Wd=[`FS_SAFE_PYTHON_MODE`,`OPENCLAW_FS_SAFE_PYTHON_MODE`],Gd=[...Wd,`FS_SAFE_PYTHON`,`OPENCLAW_FS_SAFE_PYTHON`,`OPENCLAW_PINNED_PYTHON`,`OPENCLAW_PINNED_WRITE_PYTHON`],Kd=/* @__PURE__ */ new WeakMap,qd=!1}));function isTruthyEnvValue(e){return parseBooleanValue(e)===!0}var Yd=__esmMin((()=>{Bt(),Jd()}));function runInDetachedAsyncContext(e){return Zd?Zd.runInAsyncScope(e):e()}var Xd,Zd,Qd=__esmMin((()=>{B(),Xd=typeof process>`u`?void 0:process.getBuiltinModule?.(`node:async_hooks`),Zd=Xd?resolveGlobalSingleton(Symbol.for(`openclaw.detachedAsyncContext`),()=>new Xd.AsyncResource(`openclaw.detached-async-context`)):void 0}));function runWithMainThreadTask(e,t,n){let r=$d.observer;return r?r.run(e,t,n):t()}var $d,ef=__esmMin((()=>{Qd(),B(),$d=resolveGlobalSingleton(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new 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()}}}var tf=__esmMin((()=>{}));function modelUsageTimelineAttributes(e){let t={usageState:e?.usageReport?.state??(hasObservedModelUsage(e)?`available`:`unreported`)};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`,`cacheWrite1h`,`cacheWrite5m`,`reasoningTokens`,`promptTokens`,`total`]){let r=e?.[n];r!==void 0&&(t[n]=r)}return t}function recordDiagnosticModelUsageTimeline(e){if(!isDiagnosticsTimelineEnabled())return;let t=e.trace??getActiveDiagnosticTraceContext();emitDiagnosticsTimelineEvent({type:`mark`,name:`model.usage`,provider:e.provider,attributes:{...modelUsageTimelineAttributes({...e.usage,usageReport:e.usageReport}),...e.model?{model:e.model}:{},...e.sessionId?{sessionId:e.sessionId}:{},...t?{traceId:t.traceId}:{},...e.purpose?{purpose:e.purpose}:{},...e.runtimeKind?{runtimeKind:e.runtimeKind}:{},...e.completionId?{completionId:e.completionId}:{},...e.attemptId?{attemptId:e.attemptId}:{},...e.costUsd===void 0?{}:{costUsd:e.costUsd}}})}function isDiagnosticsTimelineEnabled(e={}){let{config:t,env:n=process.env}=e,r=n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH;return typeof r!=`string`||r.trim().length===0?!1:isDiagnosticFlagEnabled(`timeline`,t,n)||isDiagnosticFlagEnabled(`diagnostics.timeline`,t,n)||isTruthyEnvValue(n.OPENCLAW_DIAGNOSTICS)}function normalizeNumber(e){if(typeof e==`number`&&Number.isFinite(e))return Math.max(0,Math.round(e*1e3)/1e3)}function normalizeAttributes(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))typeof r==`number`?Number.isFinite(r)&&(t[n]=r):(typeof r==`string`||typeof r==`boolean`||r===null)&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function serializeTimelineEvent(e,t){let n=normalizeAttributes(e.attributes),r={schemaVersion:nf,type:e.type,timestamp:e.timestamp??(/* @__PURE__ */ new Date()).toISOString(),name:e.name,...t.OPENCLAW_DIAGNOSTICS_RUN_ID?{runId:t.OPENCLAW_DIAGNOSTICS_RUN_ID}:{},...t.OPENCLAW_DIAGNOSTICS_ENV?{envName:t.OPENCLAW_DIAGNOSTICS_ENV}:{},pid:process.pid,...e.runId?{runId:e.runId}:{},...e.envName?{envName:e.envName}:{},...typeof e.pid==`number`?{pid:e.pid}:{},phase:e.phase||void 0,spanId:e.spanId||void 0,parentSpanId:e.parentSpanId||void 0,durationMs:normalizeNumber(e.durationMs),errorName:e.errorName||void 0,errorMessage:e.errorMessage||void 0,p50Ms:normalizeNumber(e.p50Ms),p95Ms:normalizeNumber(e.p95Ms),p99Ms:normalizeNumber(e.p99Ms),maxMs:normalizeNumber(e.maxMs),activeSpanName:e.activeSpanName||void 0,provider:e.provider||void 0,operation:e.operation||void 0,ok:typeof e.ok==`boolean`?e.ok:void 0,status:normalizeNumber(e.status),command:e.command||void 0,exitCode:e.exitCode,signal:e.signal,attributes:n};return`${JSON.stringify(r)}\n`}function emitDiagnosticsTimelineEvent(e,t={}){let n=t.env??process.env;if(!isDiagnosticsTimelineEnabled(t))return;let r=n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH?.trim();r&&af.write(r,e,n)}var nf,rf,af,of=__esmMin((()=>{zd(),B(),Hd(),vd(),Yd(),ef(),nf=`openclaw.diagnostics.v1`,rf=65536,new C,new C,af=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e,t,n,r=!1,i=!1,a=/* @__PURE__ */ new Set;function append(e,t){try{let n=le(e.path);a.has(n)||(d(n,{recursive:!0}),a.add(n)),Ee({filePath:e.path,content:t})}catch(t){e.failedWrites++,i||(i=!0,console.warn(`[diagnostics] failed to write timeline event: ${String(t)}`))}}function flush(){n&&=(clearImmediate(n),void 0);let e=t;t=void 0,e&&append(e.capture,e.content)}return process.once(`exit`,()=>{r=!0,flush()}),{flush,write(i,a,s){e?.path!==i&&(flush(),e={path:i,id:Se(),sequence:0,failedWrites:0});let c=serializeTimelineEvent({...a,attributes:{...a.attributes,captureId:e.id,sequence:++e.sequence,failedWrites:e.failedWrites}},s),l=Buffer.byteLength(c,`utf8`);t&&t.bytes+l>rf&&flush(),r||l>rf?append(e,c):(t?(t.content+=c,t.bytes+=l):t={capture:e,content:c,bytes:l},n??=setImmediate(flush).unref())}}})}));function createRuntimeProcessEntrypoints(e){function runtimeProcessEntrypoint(t,n=t,r=`.js`,i){return{currentModuleUrl:e,sourceModulePath:`src/${t}${i??`.ts`}`,sourceExtension:i,sourceWorkerName:t.startsWith(`infra/`)?t.slice(6):`../${t}`,distWorkerPath:`${n}${r}`}}let loaderFreeEntrypoint=e=>runtimeProcessEntrypoint(e,void 0,void 0,`.mjs`);return{daemonRuntimeProbe:runtimeProcessEntrypoint(`infra/daemon-runtime-probe.entry`),pluginToolsServe:runtimeProcessEntrypoint(`mcp/plugin-tools-serve`),openclawToolsServe:runtimeProcessEntrypoint(`mcp/openclaw-tools-serve`),repositoryPublicationRestore:loaderFreeEntrypoint(`gateway/repository-publication-restore.generated.worker`),nodeWorkspacePublicationSnapshot:loaderFreeEntrypoint(`node-host/node-worker-publication-snapshot.generated.worker`),nodeWorkspaceManifest:loaderFreeEntrypoint(`node-host/node-worker-workspace-manifest.generated.worker`),nodeWorkspaceGitHistory:loaderFreeEntrypoint(`node-host/node-worker-workspace-git-history.generated.worker`),doctorDatabaseEngineInspection:runtimeProcessEntrypoint(`commands/doctor-database-engine-inspection.worker`),backupDatabaseDiscovery:runtimeProcessEntrypoint(`infra/backup-database-discovery.worker`),sqliteHeaderProbe:runtimeProcessEntrypoint(`infra/sqlite-header-probe.worker`),databaseBackup:runtimeProcessEntrypoint(`snapshot/database-backup.worker`),managedHandoffEngine:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-engine.worker`),updatePostgresState:runtimeProcessEntrypoint(`infra/update-candidate-state.postgres.worker`),databasePortCommand:runtimeProcessEntrypoint(`infra/database-engine/port-command.entry.worker`),systemCaWarmup:runtimeProcessEntrypoint(`gateway/system-ca-warmup.worker`),shutdownHardExit:loaderFreeEntrypoint(`cli/gateway-cli/shutdown-hard-exit.worker`),packageIntegrityHasher:runtimeProcessEntrypoint(`infra/package-update-integrity-hasher.worker`),packageLocalOverrides:runtimeProcessEntrypoint(`infra/package-local-overrides.worker`),directoryWatchHost:runtimeProcessEntrypoint(`infra/directory-watch-host.worker`),directoryWatchParent:runtimeProcessEntrypoint(`infra/directory-watch-parent.worker`),workspaceQuiescenceAcquire:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-acquire.generated.worker`),workspaceQuiescenceRenew:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-renew.generated.worker`),workspaceQuiescenceRelease:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-release.generated.worker`),packageActivationRecovery:runtimeProcessEntrypoint(`infra/package-update-activation-sealed`,`package-update-activation-recovery`,`.mjs`),managedHandoffPostgresBridge:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-postgres.worker`,`managed-handoff-postgres-bridge.worker`,`.mjs`),managedHandoffRuntime:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-sealed`,`managed-handoff-runtime`,`.mjs`),sqliteVector:runtimeProcessEntrypoint(`infra/database-engine/sqlite-vector.child`),postgresBridge:runtimeProcessEntrypoint(`infra/postgres-sync/bridge.worker`),secretEgressProxy:runtimeProcessEntrypoint(`secrets/egress-proxy/proxy.worker`),codeModeNode:runtimeProcessEntrypoint(`agents/code-mode-node.worker`),cronReadOnly:runtimeProcessEntrypoint(`cron/store/read-only.worker`),stateRead:runtimeProcessEntrypoint(`state/openclaw-state-read.worker`),workerNativeLifecycle:runtimeProcessEntrypoint(`infra/worker-native-lifecycle.worker`),spawnBroker:runtimeProcessEntrypoint(`process/spawn-broker/worker`),cronStreamMatcher:runtimeProcessEntrypoint(`gateway/cron-stream-matcher.worker`),controlUiFile:runtimeProcessEntrypoint(`gateway/control-ui-file.worker`),publicSessionCard:runtimeProcessEntrypoint(`gateway/control-ui-public-session-card.worker`),nodeBootstrapArtifact:runtimeProcessEntrypoint(`gateway/worker-environments/node-bootstrap-artifact.worker`),nativeHookRelayClient:runtimeProcessEntrypoint(`agents/harness/native-hook-relay-client.worker`),computerHost:runtimeProcessEntrypoint(`gateway/desktop/computer.worker`),imageProcessor:runtimeProcessEntrypoint(`media/image-processor.worker`),fileToolPlanning:runtimeProcessEntrypoint(`agents/sessions/tools/file-tool-planning.worker`),fileToolRead:runtimeProcessEntrypoint(`agents/sessions/tools/read-file.worker`),attachmentProcessor:runtimeProcessEntrypoint(`media/attachment-processor.worker`),widgetScriptSyntax:runtimeProcessEntrypoint(`canvas/widget-script-syntax.worker`),gitOperations:runtimeProcessEntrypoint(`infra/git-operation.worker`),gitPackCleanup:runtimeProcessEntrypoint(`agents/worktrees/git-pack-cleanup.worker`),fsSafeCopy:runtimeProcessEntrypoint(`infra/fs-safe-copy.worker`),sharedStateStore:runtimeProcessEntrypoint(`state/openclaw-state.worker`),clientCredentials:runtimeProcessEntrypoint(`infra/client-credential.worker`),ttsPreferences:runtimeProcessEntrypoint(`tts/tts-settings-write.worker`),authProfileInlineUsage:runtimeProcessEntrypoint(`agents/auth-profiles/inline-usage.worker`),pluginModelCatalogRead:runtimeProcessEntrypoint(`agents/plugin-model-catalog-read.worker`),pluginModelCatalogCredentials:runtimeProcessEntrypoint(`agents/plugin-model-catalog.worker`),pluginCaptureNativeResource:runtimeProcessEntrypoint(`plugins/plugin-capture-native-resource`),pluginGenerationPreparation:runtimeProcessEntrypoint(`plugins/plugin-generation-preparation.worker`),agentDatabaseExecution:runtimeProcessEntrypoint(`state/openclaw-agent-execution.worker`),workspaceMemory:runtimeProcessEntrypoint(`worker/memory-worker-entry`,`agents/workspace-memory.worker`),localAgentAvatar:runtimeProcessEntrypoint(`agents/identity-avatar-file.worker`),identityFile:runtimeProcessEntrypoint(`agents/identity-file.worker`),workspaceSkills:runtimeProcessEntrypoint(`worker/skills-worker-entry`,`agents/workspace-skills.worker`),skillsDiscovery:runtimeProcessEntrypoint(`skills/runtime/discovery.worker`),boardStore:runtimeProcessEntrypoint(`boards/sqlite-board-store.worker`),progressCardStore:runtimeProcessEntrypoint(`session-cards/progress-card-store.worker`),sessionSharingStore:runtimeProcessEntrypoint(`config/sessions/session-sharing-store.worker`),sessionForkDomain:runtimeProcessEntrypoint(`config/sessions/session-fork-domain.worker`),sessionGoalOperations:runtimeProcessEntrypoint(`config/sessions/goals-operations.worker`),sessionLifecyclePlanningDomain:runtimeProcessEntrypoint(`config/sessions/session-lifecycle-projection.worker`),sessionMessageRewriteDomain:runtimeProcessEntrypoint(`config/sessions/session-message-rewrite.worker`),sessionDiskBudget:runtimeProcessEntrypoint(`config/sessions/disk-budget.worker`),contextEngineTurnOutbox:runtimeProcessEntrypoint(`agents/harness/context-engine-turn-outbox.worker`),sqliteStore:runtimeProcessEntrypoint(`infra/sqlite-store.worker`),sqliteWriterAdmission:runtimeProcessEntrypoint(`infra/sqlite-writer-admission.worker`),agentSchemaInspection:runtimeProcessEntrypoint(`state/openclaw-agent-schema-inspection.worker`),stateMigrationSnapshot:runtimeProcessEntrypoint(`infra/state-migrations.snapshot.worker`),githubExec:runtimeProcessEntrypoint(`agents/github-exec-launcher`),shellSnapshotEnvironment:runtimeProcessEntrypoint(`agents/shell-snapshot-env.worker`),sqliteReadOnly:runtimeProcessEntrypoint(`infra/sqlite-readonly-location.worker`),sqliteSnapshotStaging:runtimeProcessEntrypoint(`infra/sqlite-snapshot-staging.worker`),sqliteReadOnlyNativeResource:runtimeProcessEntrypoint(`infra/sqlite-readonly-native-resource`),sqliteSourceRevision:runtimeProcessEntrypoint(`infra/sqlite-source-revision.worker`),sqliteIntegrity:runtimeProcessEntrypoint(`infra/sqlite-integrity.worker`),sqliteCloseProbe:runtimeProcessEntrypoint(`infra/bun-sqlite-close-probe.worker`),preparedModelCatalog:runtimeProcessEntrypoint(`agents/prepared-model-catalog.worker`),providerPromptState:runtimeProcessEntrypoint(`agents/embedded-agent-runner/provider-prompt-state.worker`),retiredWorktreeCleanup:runtimeProcessEntrypoint(`agents/worktrees/retired-worktree-cleanup.worker`),updateNativeGate:runtimeProcessEntrypoint(`cli/update-cli/update-command-native-gate.worker`),updateStateSizes:runtimeProcessEntrypoint(`infra/update-state-sizes.entry`),updateRepair:runtimeProcessEntrypoint(`infra/update-repair.worker`),immutableBuild:runtimeProcessEntrypoint(`infra/update-immutable-build.worker`),updateMigratedFinalize:runtimeProcessEntrypoint(`infra/update-migrated-finalize.worker`),updateAutomaticCleanup:runtimeProcessEntrypoint(`infra/update-automatic-cleanup.worker`),updateCandidateState:runtimeProcessEntrypoint(`infra/update-candidate-state.worker`),doctorLint:runtimeProcessEntrypoint(`commands/doctor-lint.worker`),doctor:runtimeProcessEntrypoint(`commands/doctor.worker`),databaseVerify:runtimeProcessEntrypoint(`state/openclaw-database-verify.worker`),stateOwnership:runtimeProcessEntrypoint(`state/openclaw-state-ownership.worker`),stateLeaseHeartbeat:runtimeProcessEntrypoint(`state/openclaw-state-lease-heartbeat.worker`),gatewayStateOwnerHeartbeat:runtimeProcessEntrypoint(`infra/gateway-state-owner-heartbeat.worker`),sessionTranscriptArchive:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-archive.worker`),sessionTranscript:runtimeProcessEntrypoint(`config/sessions/session-transcript.worker`),usageOverview:runtimeProcessEntrypoint(`infra/session-cost-usage-overview-report.worker`),workerTranscriptCommit:runtimeProcessEntrypoint(`gateway/worker-environments/transcript-commit.worker`),sessionManagerMetadata:runtimeProcessEntrypoint(`agents/sessions/session-manager-metadata.worker`),sessionTranscriptProjectionPublication:runtimeProcessEntrypoint(`config/sessions/session-transcript-projection-publication.worker`),sessionTranscriptReports:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-transcript-reports.worker`),sessionTranscriptReconcile:runtimeProcessEntrypoint(`config/sessions/session-transcript-reconcile.worker`),tailscaleRouteOwner:runtimeProcessEntrypoint(`infra/tailscale-route-owner.worker`),serviceChildRelay:runtimeProcessEntrypoint(`process/supervisor/service-child-relay`),terminalPty:runtimeProcessEntrypoint(`process/terminal-pty-worker`),serviceChildGroupAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-group-anchor`),serviceChildWindowsJobAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-windows-job-anchor`),bunSqliteLibrary:runtimeProcessEntrypoint(`infra/bun-sqlite-library`)}}function pluginRuntimeProcess(e,t,n){return{plugin:e,ownerSource:`extensions/${e}/${t}.ts`,sourceWorkerName:n,distWorkerPath:`extensions/${e}/${n}.js`,package:{name:`@openclaw/${e}`,distWorkerPath:`${n}.js`}}}var sf,cf,lf=__esmMin((()=>{sf={browserNativeHost:{...pluginRuntimeProcess(`browser`,`native-host-entry`,`native-host-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`native-host-entry.js`}},browserRelayDaemon:{...pluginRuntimeProcess(`browser`,`native-host-entry`,`relay-daemon-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`relay-daemon-entry.js`}},browserSetup:{...pluginRuntimeProcess(`browser`,`setup-entry`,`setup-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`setup-entry.js`}},quickJsCodeMode:{...pluginRuntimeProcess(`code-mode-quickjs`,`src/executor`,`src/code-mode.worker`),sourceWorkerName:`code-mode.worker`},codexStdio:pluginRuntimeProcess(`codex`,`stdio-worker-entrypoint`,`stdio.worker`),codexCatalogPage:pluginRuntimeProcess(`codex`,`catalog-page-worker-entrypoint`,`catalog-page.worker`),codexSessionHistory:pluginRuntimeProcess(`codex`,`session-history-worker-entrypoint`,`session-history.worker`),discordAudio:{...pluginRuntimeProcess(`discord`,`src/voice/audio-worker-thread`,`src/voice/audio-worker.runtime`),sourceWorkerName:`audio-worker.runtime`},documentExtractor:{...pluginRuntimeProcess(`document-extract`,`document-extractor-worker-entrypoint`,`document-extractor.worker`),package:{name:`@openclaw/document-extract-plugin`,distWorkerPath:`document-extractor.worker.js`}},webReadability:{...pluginRuntimeProcess(`web-readability`,`web-content-extractor-worker.runtime`,`web-content-extractor.worker`),package:{name:`@openclaw/web-readability-plugin`,distWorkerPath:`web-content-extractor.worker.js`}},fileTransferDirFetch:{plugin:`file-transfer`,ownerSource:`extensions/file-transfer/src/node-host/dir-fetch-archive.ts`,sourceWorkerName:`dir-fetch-archive.worker`,distWorkerPath:`extensions/file-transfer/src/node-host/dir-fetch-archive.worker.js`,package:{name:`@openclaw/file-transfer`,distWorkerPath:`src/node-host/dir-fetch-archive.worker.js`}},fileTransferDirList:{plugin:`file-transfer`,ownerSource:`extensions/file-transfer/src/node-host/dir-list-worker-command.ts`,sourceWorkerName:`dir-list.worker`,distWorkerPath:`extensions/file-transfer/src/node-host/dir-list.worker.js`,package:{name:`@openclaw/file-transfer`,distWorkerPath:`src/node-host/dir-list.worker.js`}},iMessageChatDb:{...pluginRuntimeProcess(`imessage`,`src/chat-db`,`src/chat-db.worker`),sourceWorkerName:`chat-db.worker`},knowledgeRegistry:{...pluginRuntimeProcess(`knowledge`,`src/registry-client`,`src/registry-worker`),sourceWorkerName:`registry-worker`},knowledgeStorage:{...pluginRuntimeProcess(`knowledge`,`src/storage-client`,`src/storage-worker`),sourceWorkerName:`storage-worker`},mxcLauncher:{plugin:`mxc`,ownerSource:`extensions/mxc/src/plugin-root.ts`,sourceWorkerName:`mxc-spawn-launcher`,sourceExtension:`.mjs`,build:`static-asset`,distWorkerPath:`extensions/mxc/mxc-spawn-launcher.mjs`,package:{name:`@openclaw/mxc-sandbox`,distWorkerPath:`mxc-spawn-launcher.mjs`}},onePasswordSecretResolver:{plugin:`onepassword`,ownerSource:`extensions/onepassword/onepassword-secret-ref-resolver.js`,sourceWorkerName:`onepassword-secret-ref-resolver`,sourceExtension:`.js`,build:`static-asset`,distWorkerPath:`extensions/onepassword/onepassword-secret-ref-resolver.js`,package:{name:`@openclaw/onepassword`,distWorkerPath:`onepassword-secret-ref-resolver.js`}},vaultSecretResolver:{plugin:`vault`,ownerSource:`extensions/vault/vault-secret-ref-resolver.js`,sourceWorkerName:`vault-secret-ref-resolver`,sourceExtension:`.js`,build:`static-asset`,distWorkerPath:`extensions/vault/vault-secret-ref-resolver.js`,package:{name:`@openclaw/vault`,distWorkerPath:`vault-secret-ref-resolver.js`}},memorySearch:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-search.worker`),sourceWorkerName:`manager-search.worker`,distWorkerPath:`extensions/memory-core/memory-search.worker.js`},memoryIndex:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-index.worker`),sourceWorkerName:`manager-index.worker`,distWorkerPath:`extensions/memory-core/memory-index.worker.js`},memoryPublication:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-publication.worker`),sourceWorkerName:`manager-publication.worker`,distWorkerPath:`extensions/memory-core/memory-publication.worker.js`},memoryStandingIntents:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/standing-intents.worker`),sourceWorkerName:`../standing-intents.worker`,distWorkerPath:`extensions/memory-core/standing-intents.worker.js`},memoryEntryOrigins:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory-entry-origins.worker`),sourceWorkerName:`../memory-entry-origins.worker`,distWorkerPath:`extensions/memory-core/memory-entry-origins.worker.js`},memoryStatsRuntime:pluginRuntimeProcess(`memory-lancedb`,`memory-stats-entrypoint`,`memory-stats.worker`),memoryWikiQuery:{...pluginRuntimeProcess(`memory-wiki`,`src/query-reader`,`src/query-reader.worker`),sourceWorkerName:`query-reader.worker`},openAiRealtimeAudio:{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-peer.runtime`,`realtime-quicksilver-audio.worker`),package:{name:`@openclaw/openai-provider`,distWorkerPath:`realtime-quicksilver-audio.worker.js`}},openAiRealtimeSocket:{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-socket`,`realtime-quicksilver-socket.worker`),package:{name:`@openclaw/openai-provider`,distWorkerPath:`realtime-quicksilver-socket.worker.js`}},qaExecutionIdentityInspection:{...pluginRuntimeProcess(`qa-lab`,`src/execution-identity-storage-inspection`,`src/execution-identity-storage-inspection.worker`),sourceWorkerName:`execution-identity-storage-inspection.worker`},telegramIngress:{...pluginRuntimeProcess(`telegram`,`src/telegram-ingress-worker`,`src/telegram-ingress-worker.runtime`),sourceWorkerName:`telegram-ingress-worker.runtime`,distWorkerPath:`telegram-ingress-worker.runtime.js`},telegramWidgetCheck:{...pluginRuntimeProcess(`telegram`,`src/widgets/widget-check`,`src/widgets/widget-check.worker`),sourceWorkerName:`widget-check.worker`},onnxInference:pluginRuntimeProcess(`onnx`,`index`,`src/inference.worker`),teamReportsStore:pluginRuntimeProcess(`team-reports`,`index`,`src/store.worker`),teamReportsRun:pluginRuntimeProcess(`team-reports`,`index`,`src/run.worker`),logbookStore:pluginRuntimeProcess(`logbook`,`index`,`src/store.worker`),workboardSqlite:pluginRuntimeProcess(`workboard`,`index`,`src/sqlite-store.worker`)},cf={bunSqliteLibraryProbe:{buildSource:`src/infra/bun-sqlite-library-probe.entry.ts`,sourceModule:`src/infra/bun-sqlite-library-probe.generated.ts`,sourceBinding:`BUN_SQLITE_LIBRARY_PROBE_SOURCE`,kind:`file`,fileName:`bun-sqlite-library-probe.mjs`,materialize:!0},packageCliNodeProbe:{buildSource:`scripts/lib/package-cli-node-probe.entry.mjs`,sourceModule:`scripts/lib/package-cli-node-probe.generated.mjs`,sourceBinding:`PACKAGE_CLI_NODE_PROBE_SOURCE`,kind:`file`,fileName:`package-cli-node-probe.mjs`,materialize:!0},fsSafeNpmCliPreload:{buildSource:`scripts/lib/fs-safe-npm-cli-preload.entry.mjs`,sourceModule:`scripts/lib/fs-safe-npm-cli-preload.generated.mjs`,sourceBinding:`FS_SAFE_NPM_CLI_PRELOAD_DATA_URL`,kind:`data-url`},repositoryPublicationRestoreRemote:{sourceModule:`src/gateway/github-repository-publication-restore.ts`,sourceBinding:`RESTORE_PUBLICATION_INDEX_JS`,kind:`source`},nodeRuntimeProbe:{buildSource:`src/infra/node-runtime-probe.entry.ts`,sourceModule:`src/infra/node-runtime-probe.generated.mjs`,sourceBinding:`NODE_RUNTIME_PROBE_SOURCE`,kind:`file`,fileName:`node-runtime-probe.mjs`,materialize:!0},daemonRuntimeProbe:{buildSource:`src/infra/daemon-runtime-probe.entry.ts`,sourceModule:`src/infra/daemon-runtime-probe.generated.mjs`,sourceBinding:`DAEMON_RUNTIME_PROBE_SOURCE`,kind:`file`,fileName:`daemon-runtime-probe.mjs`,materialize:!0,runtimeEntrypoint:`daemonRuntimeProbe`},updateStateSizes:{sourceModule:`src/infra/update-state-sizes.generated.mjs`,sourceBinding:`UPDATE_STATE_SIZES_SOURCE`,kind:`file`,fileName:`update-state-sizes.mjs`,materialize:!0,runtimeEntrypoint:`updateStateSizes`},updateNativeGate:{sourceModule:`src/cli/update-cli/update-command-native-gate.generated.ts`,sourceBinding:`UPDATE_NATIVE_GATE_SOURCE`,kind:`file`,fileName:`update-native-gate.mjs`},managedUpdateHandoff:{sourceModule:`src/infra/update-managed-service-handoff.ts`,sourceBinding:`HANDOFF_SCRIPT`,kind:`file`,fileName:`handoff.cjs`},workspaceQuiescence:{sourceModule:`src/gateway/worker-environments/workspace-quiescence-scripts.ts`,export:`workspaceQuiescenceArgv`,kind:`argv`}}})),uf,df=__esmMin((()=>{lf(),uf={managedHandoff:{ownerSource:`src/infra/update-managed-service-handoff-sealed.ts`,entries:[[`postgresBridge`,`managedHandoffPostgresBridge`]]},worker:{ownerSource:`src/worker/worker-deploy-runtime.ts`,entries:[[`clientCredentials`,`client-credential.worker`],[`codeModeNode`,`code-mode-node.worker`],[`stateRead`,`openclaw-state-read.worker`],[`workerNativeLifecycle`,`worker-native-lifecycle.worker`],[`fileToolPlanning`,`file-tool-planning.worker`],[`fileToolRead`,`file-tool-read.worker`],[`gatewayStateOwnerHeartbeat`,`gateway-state-owner-heartbeat.worker`],[`githubExec`,`github-exec-launcher`],[`imageProcessor`,`image-processor.worker`],[`serviceChildRelay`,`service-child-relay`],[`sqliteSourceRevision`,`sqlite-source-revision.worker`],[`sqliteStore`,`sqlite-store.worker`],[`sharedStateStore`,`sqlite-store.worker`]]},serviceChildRelay:{ownerSource:`src/process/supervisor/service-child-relay.ts`,entries:[[`serviceChildGroupAnchor`,`service-child-group-anchor`]]}}}));function normalizeDiagnosticWorkerScript(e){return typeof e==`string`&&mf.has(e)?e:`other`}function workerScriptName(e,t=!1){return t||e instanceof URL&&e.protocol!==`file:`?`other`:pf.get(scriptBasename(e instanceof URL?Ie(e):e))??`other`}var scriptBasename,ff,pf,mf,hf=__esmMin((()=>{lf(),df(),scriptBasename=e=>ce(e).replace(/\.[cm]?[jt]s$/u,`.js`),ff=createRuntimeProcessEntrypoints(import.meta.url),pf=/* @__PURE__ */ new Map;for(let e of Object.values(ff)){let t=scriptBasename(e.distWorkerPath);pf.set(t,t),pf.set(scriptBasename(e.sourceModulePath),t)}for(let e of Object.values(sf)){let t=scriptBasename(e.distWorkerPath);pf.set(t,t),pf.set(scriptBasename(e.package.distWorkerPath),t),pf.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(let e of Object.values(uf))for(let[t,n]of e.entries){let e=scriptBasename(`${n}.mjs`);pf.has(e)||pf.set(e,scriptBasename(ff[t].distWorkerPath))}mf=new Set(pf.values())}));function areDiagnosticsEnabledForProcess(){return Sf.enabled}function dispatchDiagnosticEvent(e,t,n,r,i={}){if(e.dispatchDepth>100)console.error(`[diagnostic-events] recursion guard tripped at depth=${e.dispatchDepth}, dropping type=${t.type}`);else{e.dispatchDepth+=1;try{let a=createDiagnosticValueForListeners(t,!0),s=r&&createDiagnosticValueForListeners(r);if(!i.trustedListenersOnly){for(let[r,i]of e.listeners)if(isInternalDiagnosticEventInterested(i,t.type,n.trusted))try{r(a(),n)}catch(e){let n=e instanceof Error?formatErrorStackWithMessage(e):String(e);console.error(`[diagnostic-events] listener error type=${t.type} seq=${t.seq}: ${n}`)}}for(let[r,c]of e.trustedListeners)if(isInternalDiagnosticEventInterested(c,t.type,n.trusted))try{let e=a(),t=isTrustedOtelDiagnosticListener(r),l=gf;if(c?.includePrivateData!==!1&&(l=s?.()??gf,t&&(i.hostPluginId||Object.hasOwn(l,`hostPluginId`)))){let e={...l,hostPluginId:i.hostPluginId};i.hostPluginId||Reflect.deleteProperty(e,`hostPluginId`),l=Object.freeze(e)}r(e,n,l)}catch(e){let n=e instanceof Error?formatErrorStackWithMessage(e):String(e);console.error(`[diagnostic-events] trusted listener error type=${t.type} seq=${t.seq}: ${n}`)}}finally{--e.dispatchDepth}}}function isPriorityAsyncDiagnosticEvent(e){return e.metadata.trusted&&xf.has(e.event.type)}function noteAsyncDiagnosticDrop(e,t){e.asyncDroppedEvents+=1,t.metadata.trusted?e.asyncDroppedTrustedEvents+=1:e.asyncDroppedUntrustedEvents+=1,isPriorityAsyncDiagnosticEvent(t)&&(e.asyncDroppedPriorityEvents+=1)}function makeRoomForPriorityAsyncDiagnosticEvent(e){let t=e.asyncQueue.findIndex(e=>!isPriorityAsyncDiagnosticEvent(e));return t>=0?e.asyncQueue.splice(t,1)[0]:e.asyncQueue.shift()}function scheduleAsyncDiagnosticDrain(e){e.asyncDrainScheduled||(e.asyncDrainScheduled=!0,setImmediate(()=>{e.asyncDrainScheduled=!1;let t=e.asyncQueue.splice(0,vf);for(let n of t)dispatchDiagnosticEvent(e,n.event,n.metadata,n.privateData,n);e.asyncQueue.length>0?scheduleAsyncDiagnosticDrain(e):dispatchAsyncDiagnosticDropSummary(e)}))}function dispatchAsyncDiagnosticDropSummary(e){if(e.asyncDroppedEvents<=0)return;let t=e.asyncDroppedEvents,n=e.asyncDroppedTrustedEvents,r=e.asyncDroppedUntrustedEvents,i=e.asyncDroppedPriorityEvents;e.asyncDroppedEvents=0,e.asyncDroppedTrustedEvents=0,e.asyncDroppedUntrustedEvents=0,e.asyncDroppedPriorityEvents=0,dispatchDiagnosticEvent(e,enrichDiagnosticEvent(e,{type:`diagnostic.async_queue.dropped`,droppedEvents:t,...n>0?{droppedTrustedEvents:n}:{},...r>0?{droppedUntrustedEvents:r}:{},...i>0?{droppedPriorityEvents:i}:{},queueLength:e.asyncQueue.length,maxQueueLength:_f,drainBatchSize:vf}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=Sf,i=t&&isToolExecutionEventInput(e)?dispatchTrustedToolExecutionEvent(r,e):void 0;if(!r.enabled||e.type===`security.event`&&n.allowSecurityEvent!==!0)return;let a=hasInternalDiagnosticEventInterest(e.type,t);if(!a&&!(t&&!n.queuedPhase&&hasDiagnosticTracePropagationConsumer())){r.seq+=1;return}let s=enrichDiagnosticEvent(r,i??e,!n.queuedPhase);if(t&&s.type===`diagnostic.gc`){switch(s.kind){case`scavenge`:case`mark_sweep_compact`:case`incremental`:case`weak_processing`:break;default:s.kind=void 0}switch(s.reason){case`none`:case`forced`:case`synchronous_phantom_processing`:case`all_available_garbage`:case`all_external_memory`:case`schedule_idle`:case`construct_retained`:case`other`:break;default:s.reason=`other`}s.thread=s.thread===void 0||s.thread===`main`?`main`:normalizeDiagnosticWorkerScript(s.thread),(s.thread!==`code-mode-node.worker.js`||typeof s.workerSlot!=`number`||!Number.isInteger(s.workerSlot)||s.workerSlot<1||s.workerSlot>64)&&(s.workerSlot=void 0)}let{hostPluginId:c,internal:l=!1,privateData:u}=n,d=n.trustedTraceContext===!0,f=Object.freeze({...l?{internal:!0}:{},trusted:t,...n.toolExecutionLiveness?{[Md]:n.toolExecutionLiveness}:{},...n.coreModelRequestLifecycle?{[Cd]:n.coreModelRequestLifecycle}:{},...n.coreSemanticRunProgress?{[kd]:n.coreSemanticRunProgress}:{},...d?{trustedTraceContext:d}:{}}),p=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(s),m=a&&(n.queuedPhase||bf.has(s.type));if(m){if(r.asyncQueue.length>=_f){if(!t||!xf.has(s.type)){noteAsyncDiagnosticDrop(r,{event:s,metadata:f,privateData:u,hostPluginId:c});return}let e=makeRoomForPriorityAsyncDiagnosticEvent(r);e&&noteAsyncDiagnosticDrop(r,e)}let e={event:s,metadata:f,privateData:u,hostPluginId:c};if(!captureQueuedDiagnosticEvent(e,r.trustedListeners.values()))return;s=e.event,r.asyncQueue.push(e)}p&&(m||(s=cloneDiagnosticValueForListener(s,!0)),prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(s),f)),m?scheduleAsyncDiagnosticDrain(r):a&&dispatchDiagnosticEvent(r,s,f,u,{hostPluginId:c})}function isToolExecutionEventInput(e){return e.type===`tool.execution.started`||e.type===`tool.execution.completed`||e.type===`tool.execution.error`||e.type===`tool.execution.blocked`}function dispatchTrustedToolExecutionEvent(e,t){if(e.toolExecutionSeq+=1,e.toolExecutionListeners.size===0)return;let n;try{n=cloneDiagnosticValueForListener({...t,seq:e.toolExecutionSeq,ts:Date.now()},!0)}catch(e){console.error(`[diagnostic-events] tool execution clone error type=${t.type}: ${String(e)}`);return}let r=createDiagnosticValueForListeners(n);for(let t of e.toolExecutionListeners)try{t(r())}catch(e){console.error(`[diagnostic-events] tool execution listener error type=${n.type} seq=${n.seq}: ${String(e)}`)}return n}function emitDiagnosticEvent(e){emitDiagnosticEventWithTrust(e,!1)}function emitDiagnosticEventWithTrustedTraceContext(e){emitDiagnosticEventWithTrust(e,!1,{trustedTraceContext:!0})}function emitTrustedDiagnosticEvent(e){e.type===`model.usage`&&recordDiagnosticModelUsageTimeline(e);let t=consumeToolExecutionLivenessDiagnosticEvent(e),n=consumeHostPluginUsageDiagnosticEvent(e),r=consumeCoreSemanticRunProgressDiagnosticEvent(e);emitDiagnosticEventWithTrust(e,!0,{...t?{toolExecutionLiveness:t}:{},...n?{hostPluginId:n,internal:!0}:{},...r?{coreSemanticRunProgress:r}:{}})}var gf,_f,vf,yf,bf,xf,Sf,Cf=__esmMin((()=>{O(),od(),B(),td(),ud(),Sd(),wd(),Ed(),Od(),jd(),Pd(),vd(),Ld(),of(),hf(),gf=Object.freeze({}),_f=1e4,vf=100,yf=Symbol.for(`openclaw.diagnosticEvents.state.v1`),bf=new Set(cd),xf=new Set(ld),Sf=resolveGlobalSingleton(yf,()=>({marker:yf,enabled:!0,seq:0,listeners:/* @__PURE__ */ new Map,trustedListeners:/* @__PURE__ */ new Map,toolExecutionListeners:/* @__PURE__ */ new Set,toolExecutionSeq:0,dispatchDepth:0,asyncQueue:[],asyncDrainScheduled:!1,asyncDroppedEvents:0,asyncDroppedTrustedEvents:0,asyncDroppedUntrustedEvents:0,asyncDroppedPriorityEvents:0}))}));function restoreTerminalState(e,t={}){let n=t.resumeStdinIfPaused??t.resumeStdin??!1,r=t.resetStream??process.stdout,restore=(t,n)=>{try{n()}catch(n){let r=e?` (${e})`:``,i=`[terminal] restore ${t} failed${r}: ${String(n)}`;try{process.stderr.write(`${i}\n`)}catch(e){console.error(`[terminal] restore reporting failed${r}: ${String(e)}`)}}};restore(`progress line`,clearActiveProgressLine);let i=process.stdin;i.isTTY&&typeof i.setRawMode==`function`&&(restore(`raw mode`,()=>i.setRawMode(!1)),n&&typeof i.isPaused==`function`&&i.isPaused()&&restore(`stdin resume`,()=>i.resume())),r.isTTY&&restore(`terminal reset`,()=>r.write(wf))}var wf,Tf=__esmMin((()=>{Zu(),wf=`\x1B[0m\x1B[?25h\x1B[?1000l\x1B[?1002l\x1B[?1003l\x1B[?1006l\x1B[?2004l\x1B[<u\x1B[>4;0m`}));function createUnownedAppliedLoggingConfig(){return Df}function createLoggingState(){return{appliedConfig:createUnownedAppliedLoggingConfig(),cachedLogger:null,cachedSettings:null,cachedConsoleSettings:null,overrideSettings:null,invalidEnvLogLevelValue:null,consolePatched:!1,forceConsoleToStderr:!1,earlyConsoleRoutingRestore:null,consoleTimestampPrefix:!1,consoleSubsystemFilter:null,streamErrorHandlersInstalled:!1,rawConsole:null}}var Ef,Df,Of,kf,Af=__esmMin((()=>{Ef=Symbol.for(`openclaw.loggingState`),Df=`unowned`,Of=globalThis,kf=Of[Ef]??createLoggingState(),Of[Ef]=kf}));function shouldEmitRuntimeLog(e=process.env){return e.VITEST!==`true`||e.OPENCLAW_TEST_RUNTIME_LOG===`1`||typeof console.log.mock==`object`}function shouldEmitRuntimeStdout(e=process.env){return e.VITEST!==`true`||e.OPENCLAW_TEST_RUNTIME_LOG===`1`||typeof process.stdout.write.mock==`object`}function isPipeClosedError(e){let t=e?.code;return t===`EPIPE`||t===`EIO`}function writeStdout(e){if(!shouldEmitRuntimeStdout())return;clearActiveProgressLine();let t=e.endsWith(`
`)?e:`${e}\n`;try{process.stdout.write(t)}catch(e){if(isPipeClosedError(e))return;throw e}}function createRuntimeIo(){return{log:(...e)=>{shouldEmitRuntimeLog()&&(clearActiveProgressLine(),console.log(...e))},error:(...e)=>{clearActiveProgressLine(),console.error(...e)},writeStdout,writeJson:(e,t=2)=>{writeStdout(JSON.stringify(e,void 0,t>0?t:void 0))}}}function restoreRuntimeTerminalState(e,t={}){let n=t.resetStream??(kf.forceConsoleToStderr?process.stderr:void 0);restoreTerminalState(e,{...t,...n?{resetStream:n}:{}})}var jf,ExitError,Mf=__esmMin((()=>{Zu(),Tf(),Af(),jf={...createRuntimeIo(),exit:(e,t)=>{throw restoreRuntimeTerminalState(`runtime exit`,{resumeStdinIfPaused:!1,...t?.resetStream?{resetStream:t.resetStream}:{}}),new ExitError(e)}},ExitError=class extends Error{constructor(e,t){super(t??`exit ${e}`),this.code=e,this.name=`ExitError`}}}));function matchAnsiOscAt(e,t){return Lf.lastIndex=t,Lf.exec(e)?.[0]}function scanAnsiCsiAt(e,t){let n=e.charCodeAt(t);if(n!==155&&(n!==27||e.charCodeAt(t+1)!==91))return;let r=t+(n===155?1:2),i=[],a=!1;for(;r<e.length;){let t=e.charCodeAt(r);if(t===24||t===26){r+=1,a=!0;break}if(t===27||t===155){a=!0;break}if(t<=31||t===127)i.push(e.charAt(r)),r+=1;else if(t>=32&&t<=63)r+=1;else{t>=64&&t<=126&&(r+=1),a=!0;break}}return{controls:i,ended:a,value:e.slice(t,r)}}var Nf,Pf,Ff,If,Lf,Rf=__esmMin((()=>{Nf=`(?:\\x1b\\]|\\x9d)`,Pf=`(?:\\x1b\\\\|\\x07|\\x9c)`,Ff=`${Nf}[^\\x07\\x1b\\x9c]*${Pf}`,If=`[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,Lf=new RegExp(Ff,`y`)}));function hasAnsiIntroducer(e){return e.includes(`\x1B`)||e.includes(`›`)||e.includes(``)}function stripAnsiInternal(e,t){if(!hasAnsiIntroducer(e))return e;let n=[],r=0,i=0;for(;i<e.length;){let a=e.charCodeAt(i);if(a!==27&&a!==155&&a!==157){i+=1;continue}let s=matchAnsiOscAt(e,i),c=s?void 0:scanAnsiCsiAt(e,i);Bf.lastIndex=i;let l=!s&&t.compatibilityGrammar?Bf.exec(e)?.[0]:void 0,u=s?.length??c?.value.length??l?.length;if(u===void 0)i+=1;else{if(c&&!c.ended&&t.preserveIncompleteCsi)break;c?.controls.length===0&&l&&(u=Math.max(u,l.length)),n.push(e.slice(r,i),...c?.controls??[]),i+=u,r=i}}return n.push(e.slice(r)),n.join(``)}function stripAnsi(e){return stripAnsiInternal(e,{compatibilityGrammar:!1})}var zf,Bf,Vf=__esmMin((()=>{Rf(),zf=`${Nf}[\\s\\S]*?${Pf}`,Bf=RegExp(`${zf}|${If}`,`y`),new Intl.Segmenter(void 0,{granularity:`grapheme`})}));function registerSignalExitFinalizer(e){return Hf.add(e),()=>Hf.delete(e)}var Hf,Uf=__esmMin((()=>{B(),resolveGlobalSingleton(Symbol.for(`openclaw.signalExitOwner`),()=>({})),resolveGlobalSet(Symbol.for(`openclaw.signalExitBarriers`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitGates`),`close-and-restart`),Hf=resolveGlobalSet(Symbol.for(`openclaw.signalExitFinalizers`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitObservers`),`close-and-restart`),resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStartupSignals`),()=>({}))}));function isPlainObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.prototype.toString.call(e)===`[object Object]`}var Wf=__esmMin((()=>{}));function getSealedRuntimeJson5(){return Gf?.json5}function getSealedRuntimeSecureTempRoot(){return Gf?.resolveSecureTempRoot}var Gf,Kf=__esmMin((()=>{}));function isJson5Parser(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`}function setJson5Runtime(e){let t=isJson5Parser(e)?e:typeof e==`object`&&e&&`default`in e?e.default:void 0;if(!isJson5Parser(t))throw Error(`json5 parser unavailable`);return qf=t,t}function loadJson5Parser(){if(qf)return qf;let t=getSealedRuntimeJson5();if(t!==void 0)return setJson5Runtime(t);if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`sealed JSON5 runtime was not registered before use`);return setJson5Runtime(e(import.meta.url)(`json5`))}function parseJsonWithJson5Fallback(e,t){try{return JSON.parse(e)}catch{return(t??loadJson5Parser()).parse(e)}}var qf,Jf=__esmMin((()=>{Kf()}));function appendConfigPathSegment(e,t){return typeof t==`number`?`${e}[${t}]`:/^[A-Za-z_$][A-Za-z0-9_$:-]*$/.test(t)?e?`${e}.${t}`:t:`${e}[${JSON.stringify(t)}]`}var Yf=__esmMin((()=>{})),Xf,Zf=__esmMin((()=>{Xf=`default`}));function parseEnvTemplateSecretRef(e,t=Xf){if(typeof e!=`string`)return null;let n=e.trim(),r=Qf.exec(n)??$f.exec(n);return r?{source:`env`,provider:t.trim()||`default`,id:expectDefined(r[1],`types.secrets regex capture 1`)}:null}var Qf,$f,ep=__esmMin((()=>{Yu(),Zf(),Qf=/^\$\{([A-Z][A-Z0-9_]{0,127})\}$/,$f=/^\$([A-Z][A-Z0-9_]{0,127})$/}));function renderEnvTemplateToken(e){return e.defaultValue===void 0?`\${${e.name}}`:`\${${e.name}${np}${e.defaultValue}}`}function*iterateEnvTemplateTokens(e){for(let t=e.indexOf(`$`);t!==-1;t=e.indexOf(`$`,t+1)){let n=e[t+1]===`$`&&e[t+2]===`{`;if(!n&&e[t+1]!==`{`)continue;let r=t+(n?3:2),i=e.indexOf(`}`,r);if(i===-1)continue;let a=e.slice(r,i),s=a.indexOf(np),c=s===-1?a:a.slice(0,s),l=s===-1?void 0:a.slice(s+2);!tp.test(c)||l?.includes(`$`)||l?.includes(`{`)||(yield{kind:n?`escaped`:`substitution`,name:c,defaultValue:l,start:t,end:i},t=i)}}function substituteString(e,t,n,r){if(!e.includes(`$`))return e;let i=parseEnvTemplateSecretRef(e);i&&!containsEnvVarReference(e)&&r?.onPendingEnvSecretRef?.(i.id,n);let a=[],s=0;for(let c of iterateEnvTemplateTokens(e)){if(a.push(e.slice(s,c.start)),s=c.end+1,c.kind===`escaped`){a.push(renderEnvTemplateToken(c));continue}let l=t[c.name];if(l===void 0||l===``){if(c.defaultValue!==void 0){a.push(c.defaultValue);continue}if(r?.onMissing){r.onMissing({varName:c.name,configPath:n}),i?.id===c.name&&r.onPendingEnvSecretRef?.(c.name,n),a.push(renderEnvTemplateToken(c));continue}throw new MissingEnvVarError(c.name,n)}i?.id===c.name&&r?.onResolvedEnvSecretRef?.(c.name,n),a.push(l)}return a.push(e.slice(s)),a.join(``)}function containsEnvVarReference(e){for(let t of iterateEnvTemplateTokens(e))if(t.kind===`substitution`)return!0;return!1}function resolveConfigEnvVars(e,t=process.env,n){let r=[],visit=(e,i)=>{if(typeof e==`string`)return substituteString(e,t,i,n);if(Array.isArray(e)){let t=e.length,n=[];n.length=t;let a=0;return r.push(()=>{for(;a<t;){let t=a++;if(t in e)return n[t]=visit(e[t],`${i}[${t}]`),!0}return!1}),n}if(isPlainObject$1(e)){let t={},n=Object.entries(e)[Symbol.iterator]();return r.push(()=>{let e=n.next();if(e.done)return!1;let[r,a]=e.value;return t[r]=visit(a,appendConfigPathSegment(i,r)),!0}),t}return e},i=visit(e,``);for(let e=r.at(-1);e;e=r.at(-1))e()||r.pop();return i}var tp,np,MissingEnvVarError,rp=__esmMin((()=>{Wf(),Yf(),ep(),tp=/^[A-Z_][A-Z0-9_]*$/,np=`:-`,MissingEnvVarError=class extends Error{constructor(e,t){super(`Missing env var "${e}" referenced at config path: ${t}`),this.varName=e,this.configPath=t,this.name=`MissingEnvVarError`}}})),ip=__esmMin((()=>{}));function isMissingPathError(e){return w(e,`ENOENT`)||w(e,`ENOTDIR`)||w(e,`not-found`)}function ignoreMissingPath(e){if(!w(e,`ENOENT`))throw e}var H=__esmMin((()=>{}));function realpathExistingAncestorSync(e){let t=[],n=e;for(;;)try{return S.join(r.realpathSync.native(n),...t.toReversed())}catch{let e=S.dirname(n);if(e===n)return;t.push(S.basename(n)),n=e}}async function realpathExistingAncestor(e){let t=[],n=e;for(;;)try{return S.join(await T.realpath(n),...t.toReversed())}catch{let e=S.dirname(n);if(e===n)return;t.push(S.basename(n)),n=e}}function canAccessSync(e,t){try{return r.accessSync(e,t),!0}catch{return!1}}var ap=__esmMin((()=>{H()}));function resolvePathViaExistingAncestorSync$1(e){return op(Ne,e)}function resolveIdentityPathViaExistingAncestorSync(e){let t=S.resolve(e);return realpathExistingAncestorSync(t)??t}async function resolveIdentityPathViaExistingAncestor(e){let t=S.resolve(e);return await realpathExistingAncestor(t)??t}var op,sp=__esmMin((()=>{ap(),op=C.snapshot()}));function sanitizePlainObject(e){let t={};for(let[n,r]of Object.entries(e))isBlockedObjectKey(n)||(t[n]=isPlainObject$1(r)?sanitizePlainObject(r):r);return t}function mergeDeep(e,t,n={}){let r=n.arrays??`replace`,i=n.undefinedValues??`skip`;if(Array.isArray(e)&&Array.isArray(t))return r===`concat`?[...e,...t]:t;if(!isPlainObject$1(e)||!isPlainObject$1(t))return t===void 0&&i===`skip`?e:t;let a=sanitizePlainObject(e);for(let[e,s]of Object.entries(t)){if(isBlockedObjectKey(e)||s===void 0&&i===`skip`)continue;let t=a[e];a[e]=isPlainObject$1(s)?isPlainObject$1(t)?mergeDeep(t,s,n):sanitizePlainObject(s):r===`concat`&&Array.isArray(t)&&Array.isArray(s)?[...t,...s]:s}return a}var cp=__esmMin((()=>{Wf(),bd()})),lp=__esmMin((()=>{}));function normalizeHomeDirValue(e){let t=e?.trim();return t&&t!==`undefined`&&t!==`null`?t:void 0}function normalizeSafe(e){try{return normalizeHomeDirValue(e())}catch{return}}function resolveTermuxHome(e){let t=normalizeHomeDirValue(e.PREFIX);if(t&&normalizeHomeDirValue(e.ANDROID_DATA)&&/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(t.replace(/\\/gu,`/`)))return S.resolve(t,`..`,`home`)}function resolveRawOsHomeDir(e,t){return normalizeHomeDirValue(e.HOME)??normalizeHomeDirValue(e.USERPROFILE)??resolveTermuxHome(e)??normalizeSafe(t)}function resolveOsHomeDir(e=process.env,t=Xe.homedir){let n=resolveRawOsHomeDir(e,t);return n?S.resolve(n):void 0}function resolveEffectiveHomeDir(e=process.env,t=Xe.homedir,n){let r=normalizeHomeDirValue(e.OPENCLAW_HOME);if(!r)return resolveOsHomeDir(e,t);if(r===`~`||r.startsWith(`~/`)||r.startsWith(`~\\`)){let i=resolveRawOsHomeDir(e,t);return i?S.resolve(r.replace(/^~(?=$|[\\/])/,()=>i)):n?.preserveUnresolvedTilde?S.resolve(r):void 0}return S.resolve(r)}var up=__esmMin((()=>{}));function sanitizeTerminalText(e){return stripAnsi(e).replace(/[\p{Cc}\p{Bidi_Control}]/gu,e=>e===`\r`?`\\r`:e===`
`?`\\n`:e===`	`?`\\t`:``)}var dp=__esmMin((()=>{Vf()}));function tryProcessCwd(){try{return process.cwd()}catch{return}}var fp=__esmMin((()=>{}));function getUserPathBaseDirectory(){return resolveGlobalSingleton(Symbol.for(`openclaw.userPathBaseDirectory`),()=>{let{AsyncLocalStorage:e}=process.getBuiltinModule(`async_hooks`);return new e})}function resolveRequiredHomeDir(e=process.env,t=Xe.homedir){let n=resolveEffectiveHomeDir(e,t)??tryProcessCwd();if(n)return S.resolve(n);throw Error(`Unable to resolve an OpenClaw home: set OPENCLAW_HOME, HOME, or USERPROFILE, or run from an existing directory.`)}function resolveRequiredOsHomeDir(e=process.env,t=Xe.homedir){let n=resolveOsHomeDir(e,t)??tryProcessCwd();if(n)return S.resolve(n);throw Error(`Unable to resolve an OS home: set HOME or USERPROFILE, or run from an existing directory.`)}function expandHomePrefix(e,t){if(!e.startsWith(`~`))return e;let n=normalizeHomeDirValue(t?.home)??resolveEffectiveHomeDir(t?.env??process.env,t?.homedir??Xe.homedir);return n?e.replace(/^~(?=$|[\\/])/,()=>n):e}function resolveAgainstUserBase(e){let t=getUserPathBaseDirectory().getStore();return t?S.resolve(t,e):S.resolve(e)}function resolvePathWithHome(e,t,n,r=resolveAgainstUserBase){let i=e.trim();return i&&r(i.startsWith(`~`)?expandHomePrefix(i,{home:n(t?.env??process.env,t?.homedir??Xe.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=Xe.homedir){return e?resolveHomeRelativePath(e,{env:t,homedir:n}):``}var pp=__esmMin((()=>{up(),B(),fp()}));function isValidProfileName(e){return mp.test(e)}function normalizeProfileName(e){let t=e?.trim();return!t||normalizeLowercaseStringOrEmpty(t)==="default"||!isValidProfileName(t)?null:t}function resolveProfileStateDir(e,t,n){let r=e.trim();if(!isValidProfileName(r))throw Error(`Invalid profile name: ${JSON.stringify(e)}`);let i=normalizeLowercaseStringOrEmpty(r)==="default"?``:`-${r}`;return S.join(resolveRequiredHomeDir(t,n),`.openclaw${i}`)}var mp,hp=__esmMin((()=>{Lt(),pp(),mp=/^[a-z0-9][a-z0-9_-]{0,63}$/i})),LruCache,gp=__esmMin((()=>{LruCache=class{#e;#t;#n;#r=/* @__PURE__ */ new Map;#i=0;constructor(e,t){this.#e=Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):1,this.#t=t?.maxBytes??1/0,this.#n=t?.sizeOf}get size(){return this.#r.size}clear(){this.#r.clear(),this.#i=0}keys(){return this.#r.keys()}delete(e){return this.#r.has(e)?(this.#i-=this.#n?.(this.#r.get(e))??0,this.#r.delete(e)):!1}deleteValue(e){for(let[t,n]of this.#r)n===e&&this.delete(t)}peek(e){return this.#r.get(e)}get(e){if(!this.#r.has(e))return;let t=this.#r.get(e);return this.#r.delete(e),this.#r.set(e,t),t}set(e,t){this.delete(e),this.#r.set(e,t),this.#i+=this.#n?.(t)??0;for(let e of this.#r.keys()){if(this.#r.size<=this.#e&&this.#i<=this.#t)break;this.delete(e)}}}}));function resolveNewStateDir(e=resolveRequiredHomeDir){return S.join(e(),`.openclaw`)}function resolveStateDir(e=process.env,t=Xe.homedir){let n=e.OPENCLAW_STATE_DIR?.trim();if(n&&process.platform!==`win32`&&S.isAbsolute(n)){let e=_p.peek(n);if(e!==void 0)return e;let t=S.resolve(n);return _p.set(n,t),t}return n?resolveHomeRelativePath(n,{env:e,homedir:t}):resolveStateDirFromHome(e,()=>resolveRequiredHomeDir(e,t))}function resolveStateDirFromHome(e,t){let n=normalizeProfileName(e.OPENCLAW_PROFILE);return n?resolveProfileStateDir(n,e,t):resolveNewStateDir(t)}var _p,vp=__esmMin((()=>{hp(),pp(),gp(),_p=new LruCache(64)}));function resolveConfigDir(e=process.env,t=Xe.homedir){let n=e.OPENCLAW_STATE_DIR?.trim();if(n)return resolveUserPath(n,e,t);let r=e.OPENCLAW_CONFIG_PATH?.trim();return r?S.dirname(resolveUserPath(r,e,t)):resolveStateDir(e,t)}var yp=__esmMin((()=>{vp(),pp()}));function normalizeWindowsPathPreservingCase(e){let t=S.win32.normalize(e);if(!t.startsWith(`\\\\?\\`))return t;let n=t.slice(4);return n.toUpperCase().startsWith(`UNC\\`)?`\\\\${n.slice(4)}`:n}var bp=__esmMin((()=>{}));function shortenPathWithHome(e,{home:t,prefix:n}){if(e===t)return n;if(e.startsWith(`${t}/`)||process.platform===`win32`&&e.startsWith(`${t}\\`))return`${n}${e.slice(t.length)}`;if(process.platform===`win32`&&S.win32.isAbsolute(e)&&Ve(t,e)){let r=S.win32.relative(normalizeWindowsPathPreservingCase(t),normalizeWindowsPathPreservingCase(e));return S.win32.join(n,r)}return e}var xp=__esmMin((()=>{bp()}));function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var Sp=__esmMin((()=>{}));function createAbortError(e,t){let n=Error(e,t);return n.name=`AbortError`,n}function racePromiseWithAbortSignal(e,t,n=e=>createAbortError(`Operation aborted`,{cause:e.reason})){let run=()=>{try{return typeof e==`function`?e():e}catch(e){return Promise.reject(e)}};if(!t)return run();let abortError=()=>n(t);if(t.aborted){let t=Promise.reject(abortError());return typeof e==`function`?t:Promise.race([t,e])}let onAbort,r=new Promise((e,n)=>{onAbort=()=>n(abortError()),t.addEventListener(`abort`,onAbort,{once:!0})});return Promise.race([run(),r]).finally(()=>{t.removeEventListener(`abort`,onAbort)})}async function raceWithTimeout(e,t,n,r={}){let i,onAbort;try{let a=new Promise((e,a)=>{let settle=t=>{try{e(t())}catch(e){a(e)}};i=setTimeout(()=>settle(n),t),r.ref===!1&&i.unref?.();let s=r.signal;s&&(onAbort=()=>settle(()=>{if(r.onAbort)return r.onAbort(s);throw createAbortError(`Operation aborted`,{cause:s.reason})}),s.addEventListener(`abort`,onAbort,{once:!0}),s.aborted&&onAbort())}),s;try{s=typeof e==`function`?e():e}catch(e){throw a.catch(()=>{}),e}return await Promise.race([s,a])}finally{clearTimeout(i),onAbort&&r.signal?.removeEventListener(`abort`,onAbort)}}function resolveSleepDelayMs(e){return Number.isFinite(e)&&e>0?Math.min(Math.max(Math.floor(e),1),Cp):0}async function sleepWithAbort(e,t,n={}){let r=resolveSleepDelayMs(e);r!==0&&await new Promise((e,i)=>{let cleanup=()=>t?.removeEventListener(`abort`,onAbort),a=setTimeout(()=>{cleanup(),e()},r),onAbort=()=>{clearTimeout(a),cleanup(),i(createAbortError(`aborted`,{cause:t?.reason??/* @__PURE__ */ Error(`aborted`)}))};t?.addEventListener(`abort`,onAbort,{once:!0}),t?.aborted?onAbort():n.ref===!1&&a.unref?.()})}function clampNumber(e,t,n,r){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(Math.max(e,n??-1/0),r??1/0)}function resolveRetryDelayMs(e){return Math.min(Math.max(Math.round(e===1/0?Cp:Number.isFinite(e)?e:0),0),Cp)}function resolveRetryConfig(e=wp,t){let n=Math.max(1,Math.round(clampNumber(t?.attempts,e.attempts))),r=resolveRetryDelayMs(clampNumber(t?.minDelayMs,e.minDelayMs,0)),i=Math.max(r,resolveRetryDelayMs(clampNumber(t?.maxDelayMs,e.maxDelayMs,0))),a=t?.jitter,s=e.jitter;return{attempts:n,minDelayMs:r,maxDelayMs:i,jitter:a===`full`?a:typeof a==`number`&&Number.isFinite(a)?Math.min(Math.max(a,0),1):s}}function applyJitter(e,t,n,r){if(t===`full`)return n===`symmetric`?Math.max(0,Math.round(e*(.5+r()*.5))):Math.max(0,Math.ceil(e*(1+r())));if(t<=0)return n===`positive`?Math.ceil(e):e;let i=r(),a=e*(1+(n===`positive`?i*t:(i*2-1)*t));return Math.max(0,n===`positive`?Math.ceil(a):Math.round(a))}function toRetryError(e,t=`Non-Error thrown`){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);let n=Error(t,{cause:e});return(typeof e==`object`&&e||typeof e==`function`)&&Object.assign(n,e),n}function createRetryRunner(e={}){let t=e.sleep??defaultSleep,n=e.random??Math.random,r=e.createFailure??(e=>toRetryError(e.at(-1)??/* @__PURE__ */ Error(`Retry failed`)));return async function(i,a=3,s=300){let c=[],l=typeof a==`number`,u=typeof a==`number`?{attempts:a}:a,d=resolveRetryConfig(wp,u),f=d.attempts,p=d.minDelayMs,m=d.maxDelayMs>0?d.maxDelayMs:1/0,h=u.retryAfterMaxDelayMs===void 0?m:Math.max(p,resolveRetryDelayMs(clampNumber(u.retryAfterMaxDelayMs,m,0))),g=u.random??n,v=u.sleep??t,y=u.shouldRetry??(()=>!0);for(let n=1;n<=f;n+=1)try{return await i()}catch(r){if(c.push(r),n>=f||e.shouldRetry?.(r)===!1||!y(r,n))break;if(l){await t(resolveRetryDelayMs(s*2**(n-1)));continue}let i={attempt:n,maxAttempts:f,err:r,label:u.label},a=u.retryAfterMs?.(r),b=typeof a==`number`&&Number.isFinite(a),x=typeof u.delayMs==`function`?u.delayMs(i):u.delayMs,ee=x===void 0?void 0:resolveRetryDelayMs(x),te=b?Math.max(a,p):ee===void 0?p*2**(n-1):Math.max(ee,p),ne=b?h:m,re=Math.min(te,ne),ie=b&&(a??0)<=ne,ae=d.jitter===`full`&&!b||ie;re=applyJitter(re,d.jitter,ae?`positive`:`symmetric`,g),re=Math.min(Math.max(re,p),ne),await u.onRetry?.({...i,delayMs:re}),re>0&&await v(re)}throw r(c)}}var Cp,wp,defaultSleep,Tp=__esmMin((()=>{Cp=2147e6,wp={attempts:3,minDelayMs:300,maxDelayMs:3e4,jitter:0},defaultSleep=async e=>{let t=e;do{let e=Math.min(t,Cp);await new Promise(t=>{setTimeout(t,e)}),t-=e}while(t>0)},createRetryRunner()}));function isAbortError(e){if(!e||typeof e!=`object`)return!1;try{return(`name`in e?String(e.name):``)===`AbortError`||(`message`in e&&typeof e.message==`string`?e.message:``)===`This operation was aborted`}catch{return!1}}var Ep=__esmMin((()=>{Tp()})),Dp=__esmMin((()=>{Uu(),Tp(),Ep()}));function resolveHomeDir(){return resolveEffectiveHomeDir(process.env,Xe.homedir)}function resolveHomeDisplayPrefix(){let e=resolveHomeDir();if(e)return normalizeHomeDirValue(process.env.OPENCLAW_HOME)?{home:e,prefix:`$OPENCLAW_HOME`}:{home:e,prefix:`~`}}function shortenHomePath(e){let t=resolveHomeDisplayPrefix();return t?shortenPathWithHome(e,t):e}var Op=__esmMin((()=>{up(),dp(),yp(),pp(),xp(),Wf(),Dp(),String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`,String.raw`[\s"'\x60)\]}>]`,String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`,resolveConfigDir()}));function isConfigContainer(e){return Array.isArray(e)||isPlainObject$1(e)}function includeLogicalPath(e){let t=[];for(let n=e;n;n=n.parent)t.push(n.key);return t.toReversed()}function deepMerge(e,t){return mergeDeep(e,t,{arrays:`concat`,undefinedValues:`replace`})}function safeRealpath(e){try{return r.realpathSync(e)}catch{return e}}function createConfigIncludeBoundary(e,t=[]){let n=S.normalize(S.dirname(e));return{configRoot:{rootDir:n,rootRealDir:S.normalize(safeRealpath(n))},allowedRoots:t.filter(e=>typeof e==`string`&&e.length>0&&S.isAbsolute(e)).map(e=>{let t=S.normalize(e);return{rootDir:t,rootRealDir:S.normalize(safeRealpath(t))}})}}function readConfigIncludeFileWithGuards(e){let t=e.ioFs??r,n=e.maxBytes??Ap;if(!De(t)){let n=t.readFileSync(e.resolvedPath,`utf-8`);try{e.onResolvedPath?.(S.normalize(t.realpathSync(e.resolvedPath)))}catch{}return n}let i=Ae({absolutePath:e.resolvedPath,rootPath:e.rootRealDir,rootRealPath:e.rootRealDir,boundaryLabel:`config directory`,skipLexicalRootCheck:!0,rejectSymlinks:!1,maxBytes:n,ioFs:t});if(!i.ok)throw i.reason===`validation`?new ConfigIncludeError(`Include file failed security checks (regular file, max ${n} bytes, no hardlinks): ${e.includePath}`,e.includePath):new ConfigIncludeReadError(`Failed to read include file: ${e.includePath} (resolved: ${e.resolvedPath})`,e.includePath,i.error instanceof Error?i.error:void 0);try{let n=t.readFileSync(i.fd,`utf-8`);return e.onResolvedPath?.(S.normalize(i.path)),n}finally{t.closeSync(i.fd)}}function resolveConfigIncludes(e,t,n=Mp,r={}){let i=createConfigIncludeBoundary(t,r.allowedRoots??[]);return new IncludeProcessor(t,n,i).process(e)}function resolveConfigIncludesForTopLevelKey(e,t,n,r=Mp,i={}){let a=createConfigIncludeBoundary(t,i.allowedRoots??[]);return new IncludeProcessor(t,r,a,/* @__PURE__ */ new Set([n])).process(e)}var kp,Ap,jp,ConfigIncludeError,ConfigIncludeReadError,CircularIncludeError,IncludeProcessor,Mp,Np=__esmMin((()=>{Yu(),ip(),sp(),cp(),H(),lp(),Op(),Jf(),kp=`$include`,Ap=2097152,jp=4096,ConfigIncludeError=class extends Error{constructor(e,t,n){super(e),this.includePath=t,this.cause=n,this.name=`ConfigIncludeError`}},ConfigIncludeReadError=class extends ConfigIncludeError{constructor(...e){super(...e),this.name=`ConfigIncludeReadError`}},CircularIncludeError=class extends ConfigIncludeError{constructor(e){super(`Circular include detected: ${e.join(` -> `)}`,expectDefined(e[e.length-1],`chain entry at chain.length 1`)),this.chain=e,this.name=`CircularIncludeError`}},IncludeProcessor=class{constructor(e,t,n,r){this.basePath=e,this.resolver=t,this.boundary=n,this.rootProjectionKeys=r}get rootDir(){return this.boundary.configRoot.rootDir}process(e){let t=[],n=this.traverseValue(e,null,!1,{basePath:this.basePath,visited:/* @__PURE__ */ new Set([S.normalize(this.basePath)]),depth:0}),r;for(;;){let e=n.next(r);if(e.done){let i=t.pop();if(!i)return e.value;r=e.value,n=i}else t.push(n),n=this.traverseValue(e.value.value,e.value.pathLink,e.value.hasArrayAncestor,e.value.context)}}*traverseValue(e,t,n,r){if(Array.isArray(e)){let n=[];for(let[i,a]of e.entries())n.push(isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:String(i)},hasArrayAncestor:!0,context:r}:a);return n}if(!isPlainObject$1(e))return e;if(!(`$include`in e)){let i=t===null,a={};for(let[s,c]of Object.entries(e))i&&this.rootProjectionKeys&&!this.rootProjectionKeys.has(s)||(a[s]=isConfigContainer(c)?yield{value:c,pathLink:{parent:t,key:s},hasArrayAncestor:n,context:r}:c);return a}return yield*this.traverseInclude(e,t,n,r)}*traverseInclude(e,t,n,r){let i=e[kp],a=t===null,s=Object.keys(e).filter(e=>e!==`$include`&&(!a||!this.rootProjectionKeys||this.rootProjectionKeys.has(e))),c=Array.isArray(i);if(!c&&typeof i!=`string`)throw new ConfigIncludeError(`Invalid $include value: expected string or array of strings, got ${typeof i}`,String(i));let l=[];for(let e of c?i:[i]){if(typeof e!=`string`)throw new ConfigIncludeError(`Invalid $include array item: expected string, got ${typeof e}`,String(e));let i=this.loadFileSync(e,r);l.push({value:yield{value:i.parsed,pathLink:t,hasArrayAncestor:n,context:i.nestedContext},targetPath:i.resolvedPath})}let u=c?l.reduce((e,t)=>deepMerge(e,t.value),{}):l[0].value;if(this.resolver.onIncludeResolved?.({path:includeLogicalPath(t),value:u,kind:c?`multiple`:`single`,hasSiblingOverrides:s.length>0,hasArrayAncestor:n,...c?{targetPaths:l.map(e=>e.targetPath)}:{targetPath:l[0].targetPath}}),s.length===0)return u;if(!isPlainObject$1(u))throw new ConfigIncludeError(`Sibling keys require included content to be an object`,typeof i==`string`?i:kp);let d={};for(let i of s){let a=e[i];d[i]=isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:i},hasArrayAncestor:n,context:r}:a}return deepMerge(u,d)}loadFileSync(e,t){let{resolvedPath:n,root:r}=this.resolvePath(e,t);if(t.visited.has(n))throw new CircularIncludeError([...t.visited,n]);if(t.depth>=10)throw new ConfigIncludeError(`Maximum include depth (10) exceeded at: ${e}`,e);let i=this.readFile(e,n,r);return{parsed:this.parseFile(e,n,i),resolvedPath:n,nestedContext:{basePath:n,visited:/* @__PURE__ */ new Set([...t.visited,n]),depth:t.depth+1}}}resolvePath(e,t){if(e.includes(`\0`))throw new ConfigIncludeError(`Include path must not contain null bytes`,e);if(e.length>=jp)throw new ConfigIncludeError(`Include path exceeds maximum length (${jp} characters)`,e);let n=S.dirname(t.basePath),i=S.isAbsolute(e)?e:S.resolve(n,e),a=S.normalize(this.resolver.mapPath?.(i)??i);if(a.length>=jp)throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${jp} characters)`,e);let s=this.findContainingRoot(a,`rootDir`);if(!s)throw new ConfigIncludeError(`Include path escapes config directory: ${e} (root: ${this.rootDir})`,e);this.resolver.onLexicalPath?.(a);try{let t=r.realpathSync(a),n=this.findContainingRoot(t,`rootRealDir`);if(!n)throw new ConfigIncludeError(`Include path resolves outside config directory (symlink): ${e} (root: ${this.rootDir})`,e);return{resolvedPath:a,root:n}}catch(t){if(t instanceof ConfigIncludeError)throw t;if(isMissingPathError(t))return{resolvedPath:a,root:s};throw new ConfigIncludeReadError(`Failed to resolve include file realpath: ${e} (resolved: ${a})`,e,t instanceof Error?t:void 0)}}findContainingRoot(e,t){if(He(this.boundary.configRoot[t],e))return this.boundary.configRoot;for(let n of this.boundary.allowedRoots)if(He(n[t],e))return n;return null}readFile(e,t,n){try{return this.resolver.readFileWithGuards?this.resolver.readFileWithGuards({includePath:e,resolvedPath:t,rootRealDir:n.rootRealDir}):this.resolver.readFile(t)}catch(n){throw n instanceof ConfigIncludeError?n:new ConfigIncludeReadError(`Failed to read include file: ${e} (resolved: ${t})`,e,n instanceof Error?n:void 0)}}parseFile(e,t,n){try{return this.resolver.parseJson(n)}catch(n){throw new ConfigIncludeError(`Failed to parse include file: ${e} (resolved: ${t})`,e,n instanceof Error?n:void 0)}}},Mp={readFile:e=>r.readFileSync(e,`utf-8`),readFileWithGuards:readConfigIncludeFileWithGuards,parseJson:parseJsonWithJson5Fallback}}));function normalizeGatewayProfile(e){let t=e?.trim();return t&&normalizeLowercaseStringOrEmpty(t)!=="default"?t:null}function resolveGatewayProfileSuffix(e){let t=normalizeGatewayProfile(e);return t?`-${t}`:``}function resolveNodeLaunchAgentLabel(e){let t=normalizeGatewayProfile(e);return t?`${Pp}.${t}`:Pp}function resolveNodeSystemdServiceName(e){return`${Fp}${resolveGatewayProfileSuffix(e)}`}function resolveNodeWindowsTaskName(e){let t=normalizeGatewayProfile(e);return t?`${Ip} (${t})`:Ip}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:zp,OPENCLAW_LOG_PREFIX:`node${resolveGatewayProfileSuffix(t)}`,OPENCLAW_SERVICE_MARKER:Lp,OPENCLAW_SERVICE_KIND:Rp}}var Pp,Fp,Ip,Lp,Rp,zp,Bp=__esmMin((()=>{Lt(),Pp=`ai.openclaw.node`,Fp=`openclaw-node`,Ip=`OpenClaw Node`,Lp=`openclaw`,Rp=`node`,zp=`node.cmd`})),Vp=__esmMin((()=>{Uu()}));function resolveIsNixMode(e=process.env){return e.OPENCLAW_NIX_MODE===`1`}function envHomedir(e){return()=>resolveRequiredHomeDir(e,Xe.homedir)}function normalizePathForComparison(e){let t=S.resolve(e);try{return r.realpathSync.native(t)}catch{return t}}function resolveIncludeRoots(e=process.env,t=envHomedir(e)){let n=e.OPENCLAW_INCLUDE_ROOTS?.trim();if(!n)return[];let effectiveHomedir=()=>resolveRequiredHomeDir(e,t),r=/* @__PURE__ */ new Set,i=[];for(let t of n.split(S.delimiter)){let n=t.trim();if(!n)continue;let a=S.resolve(resolveHomeRelativePath(n,{env:e,homedir:effectiveHomedir}));r.has(a)||(r.add(a),i.push(a))}return i}function resolveConfigPathCandidate(e=process.env,t=envHomedir(e)){return resolveConfigPath(e,void 0,t)}function resolveConfigPath(e=process.env,t,n=envHomedir(e)){let r=e.OPENCLAW_CONFIG_PATH?.trim();return r?resolveUserPath(r,e,n):S.join(t??resolveStateDir(e,n),Hp)}function resolveGatewayLockDir(e=resolveStateDir(),t=typeof process.getuid==`function`?process.getuid():void 0){return resolveGatewayLockDirForCanonicalStateDir(normalizePathForComparison(e),t)}function resolveGatewayLockDirForCanonicalStateDir(e,t=typeof process.getuid==`function`?process.getuid():void 0){let n=t==null?`openclaw`:`openclaw-${t}`;return S.join(e,`tmp`,n)}var Hp,Up=__esmMin((()=>{pp(),Vp(),vp(),resolveIsNixMode(),Hp=`openclaw.json`,resolveStateDir(),resolveConfigPathCandidate()}));function resolveLoggingConfigSelector(){let e=process.env;return[e.OPENCLAW_CONFIG_PATH,e.OPENCLAW_STATE_DIR,e.OPENCLAW_HOME,e.OPENCLAW_PROFILE,e.HOME,e.USERPROFILE,e.HOMEDRIVE,e.HOMEPATH,e.PREFIX,e.ANDROID_DATA,e.OPENCLAW_TEST_FAST,tryProcessCwd()??``].map(e=>e??``).join(`\0`)}function resolvePartialDiagnosticLoggingConfig(e){if(!isRecord(e))return;let t={};if(typeof e.consoleStyle==`string`)try{let n=resolveConfigEnvVars({consoleStyle:e.consoleStyle});isRecord(n)&&(n.consoleStyle===`pretty`||n.consoleStyle===`compact`||n.consoleStyle===`json`)&&(t.consoleStyle=n.consoleStyle)}catch{}if(Array.isArray(e.redactPatterns))try{let n=resolveConfigEnvVars({redactPatterns:e.redactPatterns});isRecord(n)&&Array.isArray(n.redactPatterns)&&n.redactPatterns.every(e=>typeof e==`string`)&&(t.redactPatterns=n.redactPatterns)}catch{}return Object.keys(t).length>0?t:void 0}function readLoggingConfig(){try{if(kf.appliedConfig!==`unowned`)return kf.appliedConfig;let e=resolveLoggingConfigSelector();if(Wp?.selector===e)return Wp.logging;let t=resolveConfigPath();if(!r.existsSync(t)){Wp={selector:e,logging:void 0};return}let n=parseJsonWithJson5Fallback(r.readFileSync(t,`utf8`)),i=resolveIncludeRoots(),a;try{a=resolveConfigIncludesForTopLevelKey(n,t,`logging`,void 0,{allowedRoots:i})}catch{let e=isRecord(n)?n.logging:void 0;if(e===void 0)return;try{a=resolveConfigIncludes({logging:e},t,void 0,{allowedRoots:i})}catch{return resolvePartialDiagnosticLoggingConfig(e)}}let s;try{s=resolveConfigEnvVars(a)}catch{return resolvePartialDiagnosticLoggingConfig(isRecord(a)?a.logging:void 0)}let c=isRecord(s)?s.logging:void 0,l=isRecord(c)?c:void 0;return Wp={selector:e,logging:l},l}catch{return}}var Wp,Gp=__esmMin((()=>{D(),rp(),Np(),Up(),fp(),Jf(),Af()}));function normalizeUrlQueryParamName(e){let t=e.replace(qp,``);for(let e=0;e<=Yp;e+=1){let e;try{e=decodeURIComponent(t).replace(qp,``)}catch{break}if(e===t)return{value:normalizeLowercaseStringOrEmpty(t).replaceAll(`-`,`_`),unresolvedEncoding:!1};t=e}return{value:normalizeLowercaseStringOrEmpty(t).replaceAll(`-`,`_`),unresolvedEncoding:t.includes(`%`)}}function isSensitiveUrlQueryParamName(e){let t=normalizeUrlQueryParamName(e);return t.unresolvedEncoding||Kp.has(t.value)||Jp.test(t.value)}var Kp,qp,Jp,Yp,Xp=__esmMin((()=>{Lt(),Kp=/* @__PURE__ */ new Set(/* @__PURE__ */ `token.key.api_key.apikey.secret.access_token.auth_token.password.pass.passwd.auth.jwt.session.id_token.code.client_secret.app_secret.hook_token.refresh_token.signature.x_amz_signature.x_amz_security_token.private_key.credential.authorization.sig.x_api_key.x_access_token.x_auth_token`.split(`.`)),qp=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,Jp=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u,Yp=8}));function skipHorizontalWhitespace(e,t){let n=t;for(;e[n]===` `||e[n]===`	`;)n+=1;return n}function skipSerializedBackslashes(e,t){let n=t;for(;n-t<64&&e[n]===`\\`;)n+=1;return n}function readSerializedLineEnd(e,t){let n=skipSerializedBackslashes(e,t);if(n===t)return null;if(e[n]===`n`)return n+1;if(e[n]!==`r`)return null;let r=skipSerializedBackslashes(e,n+1);return r>n+1&&e[r]===`n`?r+1:null}function readSerializedTabEnd(e,t){let n=skipSerializedBackslashes(e,t);return n>t&&e[n]===`t`?n+1:null}function skipAuthWhitespace(e,t){let n=t;for(;;){n=skipHorizontalWhitespace(e,n);let t=readSerializedTabEnd(e,n);if(t!==null){n=t;continue}let r=e[n]===`\r`&&e[n+1]===`
`?n+2:e[n]===`
`?n+1:readSerializedLineEnd(e,n);if(r===null||e[r]!==` `&&e[r]!==`	`&&readSerializedTabEnd(e,r)===null)return n;n=r}}function readAuthParamName(e,t){let n=om.exec(e.slice(t));return n?{name:n[0].toLowerCase(),end:t+n[0].length}:null}function isAuthHeaderStart(e,t){let n=e[t-1];if((n!==`n`&&n!==`r`||e[t-2]!==`\\`)&&n!==void 0&&/[A-Za-z0-9_-]/u.test(n))return!1;let r=`proxy-authorization`,i=`authorization`,a=e.slice(t,t+19).toLowerCase(),s=a===r?r:a.startsWith(i)?i:null;if(!s)return!1;let c=t+s.length,l=skipSerializedBackslashes(e,c);if(e[l]===`"`||e[l]===`'`)l+=1;else if(l>c)return!1;return l=skipHorizontalWhitespace(e,l),e[l]===`:`||e[l]===`=`}function findNextAuthParamStart(e,t){let n=t;for(;;){if(n=skipAuthWhitespace(e,n),n>t&&isAuthHeaderStart(e,n)||n>=e.length||e[n]===`\r`||e[n]===`
`||e[n]===`;`)return null;if(e[n]===`,`){n+=1;continue}let r=readAuthParamName(e,n);if(r){let t=skipAuthWhitespace(e,r.end);if(e[t]===`=`&&e[t+1]!==`=`)return n}for(;n<e.length;){let r=skipAuthWhitespace(e,n);if(r>n){n=r;continue}if(n>t&&isAuthHeaderStart(e,n))return null;let i=e[n];if(i===`\r`||i===`
`||i===`;`)return null;if(n+=1,i===`,`)break}}}function usesAuthParams(e){return e===`digest`||e===`hawk`||e.startsWith(`aws4-`)}function isAuthFieldEnd(e){return e===void 0||e===`\r`||e===`
`||e===`;`||e===`\\`||e===`"`||e===`'`||e===`}`||e===`]`}function findAuthFieldEnd(e,t){let n=t;for(;n<e.length;){let r=skipAuthWhitespace(e,n);if(r>n)n=r;else{if(n>t&&isAuthHeaderStart(e,n)||isAuthFieldEnd(e[n]))break;n+=1}}return n}function readParamValue(e,t,n){let r=0;for(;e[t+r]===`\\`;)r+=1;let i=r>0&&e[t+r]===`"`,a=e[t]===`"`||e[t]===`'`?e[t]:void 0;if(a||i){let n=t+(i?r+1:1);for(;n<e.length;)if(e[n]===`\r`||e[n]===`
`){let t=skipAuthWhitespace(e,n);if(t===n)break;n=t}else if(i&&e[n]===`\\`){let t=n+1;for(;e[t]===`\\`;)t+=1;if(e[t]===`"`){if((t-n)%(2*(r+1))===r)return t+1;n=t+1;continue}n=t}else if(!i&&e[n]===`\\`&&n+1<e.length)n+=2;else{if(!i&&e[n]===a)return n+1;n+=1}return n>t+1?n:null}if(n.signedHeaders){let n=/^:?[A-Za-z0-9!#$%&'*+.^_`|~-]+(?:;:?[A-Za-z0-9!#$%&'*+.^_`|~-]+)*/u.exec(e.slice(t));if(!n)return null;let r=t+n[0].length,i=e[r];return i===void 0||i===`,`||i===` `||i===`	`||i===`\r`||i===`
`?r:null}let s=(n.awsScope?sm:om).exec(e.slice(t));return s?t+s[0].length:null}function findStructuredAuthParamRanges(e){let t=[];for(let n of e.matchAll(am)){let r=(n[2]??``).toLowerCase(),i=(n.index??0)+n[0].length,a=i,s=i,c=readAuthParamName(e,i),l=c?skipAuthWhitespace(e,c.end):void 0;if(!c||l===void 0||e[l]!==`=`||e[l+1]===`=`){if(e[skipAuthWhitespace(e,i)]!==`,`&&!usesAuthParams(r))continue;let t=findNextAuthParamStart(e,i);if(t===null)continue;i=t}for(;;){let t=readAuthParamName(e,i);if(!t||(i=skipAuthWhitespace(e,t.end),e[i]!==`=`))break;i=skipAuthWhitespace(e,i+1);let n=readParamValue(e,i,{awsScope:r.startsWith(`aws4-`)&&t.name===`credential`,signedHeaders:t.name===`signedheaders`});if(n===null){let t=findNextAuthParamStart(e,i);if(t!==null){i=t;continue}s=Math.max(s,findAuthFieldEnd(e,i));break}s=n;let a=skipAuthWhitespace(e,n);if(e[a]!==`,`){if(!isAuthFieldEnd(e[a])){let t=findNextAuthParamStart(e,a);if(t!==null){i=t;continue}s=Math.max(s,findAuthFieldEnd(e,a))}break}let c=findNextAuthParamStart(e,a+1);if(c===null)break;i=c}s>a&&t.push({start:a,end:s})}return t}function redactStructuredAuthHeaders(e,t){let n=[],r=0;for(let i of findStructuredAuthParamRanges(e))(n.length===0||i.start>r)&&n.push(e.slice(r,i.start),t),r=Math.max(r,i.end);return n.push(e.slice(r)),n.join(``)}var Zp,Qp,$p,em,tm,nm,rm,im,U,am,om,sm,cm=__esmMin((()=>{Zp="[A-Za-z0-9!#$%&'*+.^_`|~-]+",Qp=String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`,$p=String.raw`\\{1,64}t`,em=String.raw`(?:[ \t]+|${$p})`,tm=String.raw`(?:[ \t]*\r?\n${em}|[ \t]*\\{1,64}r\\{1,64}n${em}|[ \t]*\\{1,64}n${em}|[ \t]*${$p}[ \t]*|[ \t]*)`,nm=String.raw`(?:[ \t]*\r?\n${em}|[ \t]*\\{1,64}r\\{1,64}n${em}|[ \t]*\\{1,64}n${em}|[ \t]*${$p}[ \t]*|[ \t]+)`,rm=String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${$p})|[ \t]*\\{1,64}n(?:[ \t]*|${$p})|[ \t]*${$p}[ \t]*)`,im=String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`,U=String.raw`(?:\\{1,64}["']|["']|)`,String.raw`${im}(?:x-goog-api-key|api-key|apikey|x-api-token|x-access-token)${U}[ \t]*[:=]${tm}${U}([^\s\\"',;]+)`,am=new RegExp(String.raw`${im}(?:Proxy-)?Authorization${U}[ \t]*[:=]${tm}${U}(${Zp})${nm}`,`giu`),om=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u,sm=/^[A-Za-z0-9!#$%&'*+.^_`|~:/-]+/u}));function pruneMapToMaxSize(e,t){if(Number.isNaN(t)||t===1/0)return;let n=Math.max(0,Math.floor(t));if(n<=0)e.clear();else for(let t of e.keys()){if(e.size<=n)break;e.delete(t)}}var lm=__esmMin((()=>{}));function createParseFrame(){return{lastToken:null,containsRepetition:!1,hasAlternation:!1,branchMinLength:0,branchMaxLength:0,altMinLength:null,altMaxLength:null}}function addLength(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?1/0:e+t}function multiplyLength(e,t){return Number.isFinite(e)?e*t:t===0?0:1/0}function recordAlternative(e){e.altMinLength===null||e.altMaxLength===null?(e.altMinLength=e.branchMinLength,e.altMaxLength=e.branchMaxLength):(e.altMinLength=Math.min(e.altMinLength,e.branchMinLength),e.altMaxLength=Math.max(e.altMaxLength,e.branchMaxLength))}function readQuantifier(e,t){let n=e[t],r=e[t+1]===`?`?2:1;if(n===`*`)return{consumed:r,minRepeat:0,maxRepeat:null};if(n===`+`)return{consumed:r,minRepeat:1,maxRepeat:null};if(n===`?`)return{consumed:r,minRepeat:0,maxRepeat:1};if(n!==`{`)return null;let i=t+1;for(;i<e.length&&/\d/.test(e.charAt(i));)i+=1;if(i===t+1)return null;let a=Number.parseInt(e.slice(t+1,i),10),s=a;if(e[i]===`,`){i+=1;let t=i;for(;i<e.length&&/\d/.test(e.charAt(i));)i+=1;s=i===t?null:Number.parseInt(e.slice(t,i),10)}return e[i]!==`}`||(i+=1,e[i]===`?`&&(i+=1),s!==null&&s<a)?null:{consumed:i-t,minRepeat:a,maxRepeat:s}}function hasNestedRepetition(e){let t=[createParseFrame()],n=!1,emitToken=e=>{let n=expectDefined(t[t.length-1],`frames entry at frames.length 1`);n.lastToken=e,e.containsRepetition&&(n.containsRepetition=!0),n.branchMinLength=addLength(n.branchMinLength,e.minLength),n.branchMaxLength=addLength(n.branchMaxLength,e.maxLength)},emitSimpleToken=()=>{emitToken({containsRepetition:!1,hasAmbiguousAlternation:!1,minLength:1,maxLength:1})};for(let r=0;r<e.length;r+=1){let i=e[r];if(n){i===`\\`?r+=1:i===`]`&&(n=!1);continue}if(i===`\\`){r+=1,emitSimpleToken();continue}if(i===`[`){n=!0,emitSimpleToken();continue}if(i===`(`){t.push(createParseFrame());continue}if(i===`)`){if(t.length>1){let e=t.pop();e.hasAlternation&&recordAlternative(e);let n=e.hasAlternation?e.altMinLength??0:e.branchMinLength,r=e.hasAlternation?e.altMaxLength??0:e.branchMaxLength;emitToken({containsRepetition:e.containsRepetition,hasAmbiguousAlternation:e.hasAlternation&&e.altMinLength!==null&&e.altMaxLength!==null&&e.altMinLength!==e.altMaxLength,minLength:n,maxLength:r})}continue}if(i===`|`){let e=expectDefined(t[t.length-1],`frames entry at frames.length 1`);e.hasAlternation=!0,recordAlternative(e),e.branchMinLength=0,e.branchMaxLength=0,e.lastToken=null;continue}let a=readQuantifier(e,r);if(!a){emitSimpleToken();continue}r+=a.consumed-1;let s=expectDefined(t[t.length-1],`frames entry at frames.length 1`),c=s.lastToken;if(!c)continue;if(c.containsRepetition||c.hasAmbiguousAlternation&&a.maxRepeat===null)return!0;let l=c.minLength,u=c.maxLength;c.minLength=multiplyLength(c.minLength,a.minRepeat),c.maxLength=a.maxRepeat===null?1/0:multiplyLength(c.maxLength,a.maxRepeat),c.containsRepetition=!0,s.containsRepetition=!0,s.branchMinLength=s.branchMinLength-l+c.minLength,s.branchMaxLength=addLength(Number.isFinite(s.branchMaxLength)&&Number.isFinite(u)?s.branchMaxLength-u:1/0,c.maxLength)}return!1}function compileSafeRegexDetailed(e,t=``){let n=e.trim();if(!n)return{regex:null,source:n,flags:t,reason:`empty`};let r=`${t}::${n}`,i=dm.get(r);if(i)return i;let a;if(hasNestedRepetition(n))a={regex:null,source:n,flags:t,reason:`unsafe-nested-repetition`};else try{a={regex:new RegExp(n,t),source:n,flags:t,reason:null}}catch{a={regex:null,source:n,flags:t,reason:`invalid-regex`}}return dm.set(r,a),pruneMapToMaxSize(dm,um),a}var um,dm,fm=__esmMin((()=>{Yu(),lm(),um=256,dm=/* @__PURE__ */ new Map}));function compileConfigRegex(e,t=``){let n=compileSafeRegexDetailed(e,t);return n.reason===`empty`?null:{regex:n.regex,pattern:n.source,flags:n.flags,reason:n.reason}}var pm=__esmMin((()=>{fm()}));function clampMessage(e){return e.length>mm?`${truncateUtf16Safe(e,mm)}...(truncated)`:e}function stringifyFileLogMessagePart(e,t){if(t)return JSON.stringify(e);if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(isRecord(e)&&typeof e.message==`string`)return e.message}function serializeFileLogRecord(e,t=[]){let n=[],r=JSON.parse(JSON.stringify(e,function(e,t){for(;n.length>0&&n.at(-1)!==this;)n.pop();if(typeof t==`bigint`)return String(t);if(typeof t==`object`&&t){if(n.includes(t))return`[Circular]`;n.push(t)}return t}));if(!isRecord(r))throw TypeError(`File log records must serialize to objects`);let i=[];for(let{key:e,json:n,primitiveText:a}of t){let t=a??stringifyFileLogMessagePart(r[e],n);t?.trim()&&i.push(t)}if(i.length>0){let e=clampMessage(i.join(` `));if(Object.hasOwn(r,`message`))r.message=e;else{let t=Object.entries(r);return t.splice(t.findIndex(([e])=>e===`hostname`)+1,0,[`message`,e]),JSON.stringify(Object.fromEntries(t))}}return JSON.stringify(r)}var mm,hm=__esmMin((()=>{D(),Ju(),mm=4096}));function replacePatternBounded(e,t,n){if(e.length<=gm)return e.replace(t,n);let r;for(let i=0;i<e.length;i+=_m){let a=e.slice(i,i+_m),s=a.replace(t,n);r===void 0?s!==a&&(r=e.slice(0,i)+s):r+=s}return r??e}var gm,_m,vm=__esmMin((()=>{gm=32768,_m=16384}));function composeRedactionEdits(e,t,n){if(t.length===0)return n;let r=[],i=0;for(let e of t)i<e.start&&r.push({start:i,end:e.start}),r.push(e),i=e.end;i<e&&r.push({start:i,end:e});let a=[],s=0,c=0,l=0,consume=(t,n)=>{if(t===l){let t=r[s];if(!t)return{start:e,end:e};let n=t.replacement===void 0?t.start+c:t.start;return{start:n,end:t.replacement!==void 0&&c>0?t.end:n}}let i,u=0;for(;l<t;){let e=expectDefined(r[s],`current redaction piece`),d=e.replacement?.length??e.end-e.start,f=Math.min(d-c,t-l),p=e.replacement===void 0?e.start+c:e.start,m=e.replacement===void 0?p+f:e.end;i??=p,u=m,n&&f>0&&a.push({start:p,end:m,replacement:e.replacement?.slice(c,c+f)}),l+=f,c+=f,c===d&&(s+=1,c=0)}return{start:i??u,end:u}};for(let e of n)consume(e.start,!0),a.push({...consume(e.end,!1),replacement:e.replacement});for(;s<r.length;){let e=expectDefined(r[s],`remaining redaction piece`);consume(l+(e.replacement?.length??e.end-e.start)-c,!0)}let u=[],d=[],f,flush=()=>{f&&(f.replacement=d.join(``),u.push(f),f=void 0,d=[])};for(let e of a){if(e.replacement===void 0){flush();continue}let t=f&&f.start===e.start&&f.end===e.end&&e.start===e.end;!f||e.start>=f.end&&!t?(flush(),f={start:e.start,end:e.end,replacement:``}):f.end=Math.max(f.end,e.end),d.push(e.replacement)}return flush(),u}function rebaseRedactionEdits(e,t){let n=0,r=e.map(e=>{let t=e.start+n;return n+=e.replacement.length-(e.end-e.start),{...e,currentStart:t,currentEnd:e.end+n}}),boundary=(e,t)=>{let n=0,i=r.length;for(;n<i;){let t=n+i>>>1,a=expectDefined(r[t],`source redaction span`);a.end<e||a.end===e&&a.start!==a.end?n=t+1:i=t}let a=r[n];if(a&&(e>a.start||e===a.start&&a.start===a.end))return t?a.currentEnd:a.currentStart;let s=r[n-1];return e+(s?s.currentEnd-s.end:0)};return t.map(e=>({start:boundary(e.start,!1),end:boundary(e.end,!0),replacement:e.replacement}))}function mergeRedactionEdits(e){e.sort((e,t)=>e.start-t.start||e.end-t.end);let t=[];for(let n of e){let e=t.at(-1);!e||n.start>=e.end?t.push({...n}):(n.start!==e.start||n.end!==e.end||n.replacement!==e.replacement)&&(e.end=Math.max(e.end,n.end),e.replacement=`***`)}return t}function applyRedactionEdits(e,t){let n=[],r=0;for(let i of mergeRedactionEdits(t))n.push(e.slice(r,i.start),i.replacement),r=i.end;return n.join(``)+e.slice(r)}var ym=__esmMin((()=>{Yu()}));function skipWhitespace(e,t){let n=t;for(;e[n]===` `||e[n]===`	`||e[n]===`\r`||e[n]===`
`;)n+=1;return n}function readScalarTokens(e,t){let n=[],r=[],i={key:``,path:[],origins:t,origin:t.value,objectPath:!0},valueContext=e=>e?e.array?{...e.context,origin:e.context.origins?.value??e.context.origin,origins:e.context.origins?.children.get(String(e.nextIndex++))}:expectDefined(e.field,`JSON object field context`):i;for(let t of e.matchAll(bm)){let i=t[0],a=r.at(-1);if(i===`{`||i===`[`){let e=valueContext(a),s=i===`[`;r.push({array:s,nextIndex:0,context:s?{...e,objectPath:!1}:e,start:t.index,tokenStart:n.length});continue}if(i===`}`||i===`]`){let i=expectDefined(r.pop(),`JSON container`);if(i.tokenStart===n.length){let r=t.index+1,a=e.slice(i.start,r);n.push({...i.context,isKey:!1,string:!1,value:a,start:i.start,end:r,escaped:!1,edits:[],projectedEdits:[],currentValue:a,currentStart:i.start,currentEnd:r})}continue}let s=t.index,c=s+i.length,l=i.startsWith(`"`),u=l?JSON.parse(i):i,d=skipWhitespace(e,c),f=l&&e[d]===`:`,p;if(f){let t=expectDefined(a,`JSON property container`),n=t.context;p={key:``,path:[],origin:n.origin,objectPath:!1,rootKey:n.rootKey,rootValueStart:n.rootValueStart};let i=skipWhitespace(e,d+1);t.field={key:u,path:[...n.path,u],origins:n.origins?.children.get(u),origin:n.origins?.value??n.origin,objectPath:n.objectPath,rootKey:r.length===1?u:n.rootKey,rootValueStart:r.length===1?i:n.rootValueStart}}else p=valueContext(a);let m=f?{structured:!1,primitiveMask:!1}:p.origins?.value??p.origin;n.push({...p,origin:m,start:s,end:c,isKey:f,string:l,value:u,escaped:l&&i.includes(`\\`),edits:[],projectedEdits:[],currentValue:u,currentStart:s,currentEnd:c})}return n}function readBatchTokens(e,t,n=!1){let r=[],i=0;for(let a of e.split(`
`)){let e=!1;try{JSON.parse(a),e=!0}catch{}if(e)for(let e of readScalarTokens(a,t))e.deferEncoding=!e.string,e.start+=i,e.end+=i,e.currentStart+=i,e.currentEnd+=i,r.push(e);else{let e=r.at(-1);!n&&e?.raw&&e.end+1===i?(e.value+=`\n${a}`,e.currentValue=e.value,e.end=e.currentEnd=i+a.length):r.push({raw:!0,origin:t.value,key:``,path:[],objectPath:!1,isKey:!1,string:!1,value:a,escaped:!1,start:i,end:i+a.length,currentStart:i,currentEnd:i+a.length,currentValue:a,edits:[],projectedEdits:[]})}i+=a.length+1}return r}var bm,xm=__esmMin((()=>{Yu(),bm=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\]]/g}));function parseRedactPatternSource(e){let t=e.match(/^\/(.+)\/([gimsuy]*)$/);if(!t)return[e,`gi`];let n=t[1]??``,r=t[2]??``;return[n,r.includes(`g`)?r:`${r}g`]}function escapeAtomEnd(e,t){let n=e[t+1];if(n===void 0)return-1;if(Tm.has(n))return t+2;if(n===`x`)return wm.test(e[t+2]??``)&&wm.test(e[t+3]??``)?t+4:t+2;if((n===`u`||n===`p`||n===`P`)&&e[t+2]===`{`){let n=e.indexOf(`}`,t+3);return n===-1?t+2:n+1}if(n===`u`){let n=t+2;for(;n<t+6&&wm.test(e[n]??``);)n+=1;return n}if(n===`c`)return t+3;if(n===`k`&&e[t+2]===`<`){let n=e.indexOf(`>`,t+3);return n===-1?t+2:n+1}if(n>=`0`&&n<=`9`){let n=t+2;for(let t=n;t<e.length;t+=1){let r=e[t];if(r===void 0||r<`0`||r>`9`)break;n=t+1}return n}return t+2}function classAtomEnd(e,t){let n=t+1;if(e[n]===`^`&&(n+=1),e[n]===`]`)return-1;for(;n<e.length;){let t=e[n];if(t===`\\`)n+=2;else{if(t===`]`)return n+1;n+=1}}return e.length}function rewriteOpenEndedRepeats(e,t=``){if(!e.includes(`{`))return e;let n=``,r=-1,i=-1,a=0;for(;a<e.length;){let s=e[a],c=a+1,l=!0;if(s===`\\`)c=escapeAtomEnd(e,a),c<0?(c=a+1,l=!1):t.includes(`u`)&&isHighSurrogateEscape(e,a)&&e[c]===`\\`&&isLowSurrogateEscape(e,c)?c=escapeAtomEnd(e,c):l=!Tm.has(e[a+1]);else if(s===`[`){if(c=classAtomEnd(e,a),c<0)return e}else if(s===`{`){let t=Sm.exec(e.slice(a)),s=t&&r>=0?t:Cm.exec(e.slice(a));if(s){n+=s===t?`{${t[1]}}${e.slice(r,i)}*`:s[0],a+=s[0].length,e[a]===`?`&&(n+=`?`,a+=1),r=-1;continue}}else t.includes(`u`)&&s>=`\ud800`&&s<=`\udbff`&&a+1<e.length&&e[a+1]>=`\udc00`&&e[a+1]<=`\udfff`?c=a+2:l=!`*+?()|^$`.includes(s);n+=e.slice(a,c),r=l?a:-1,i=c,a=c}return n}function readRedactMatch(e){let t=e.length>0&&typeof e[e.length-1]==`object`&&e[e.length-1]!==null?e.length-2:e.length-1,n=t-1,r=typeof e[0]==`string`?e[0]:``,i=e.slice(1,n).map(e=>typeof e==`string`?e:``),a=typeof e[n]==`number`?e[n]:-1;return{match:r,groups:i,input:typeof e[t]==`string`?e[t]:``,offset:a}}function setRedactPatternPrefilter(e,t){if(Em.has(e))return;let n=e.source,r=e.exec,i=e instanceof RegExp?e.flags:void 0,a=e instanceof RegExp?e[Symbol.replace]:void 0;Em.set(e,s=>e.source!==n||e.exec!==r||e instanceof RegExp&&(e.flags!==i||e[Symbol.replace]!==a)||t(s))}function selectSecretCapture(e,t){let n={index:-1,value:e};for(let e=0;e<t.length;e++){let r=t[e];typeof r==`string`&&r.length>0&&(n.index=e,n.value=r)}return n}function getSecretCaptureStart(e,t,n,r,i){let a=i.index;if(!(e instanceof RegExp)||r<0||!t)return n.lastIndexOf(i.value);let s=Dm.get(e);s||(s=new RegExp(e.source,`${e.flags.replace(`d`,``).replace(`g`,``)}dg`),Dm.set(e,s)),s.lastIndex=r;let c=s.exec(t),l=c?.indices?.[a+1];return c?.index===r&&c[0]===n&&l?l[0]-r:n.lastIndexOf(i.value)}function visitRedactMatches(e,t,n){if(Em.get(t)?.(e)===!1)return;if(!(t instanceof RegExp)){for(let r of t.exec(e))n(r,t);return}let r=t.global?t:Om.get(t);r||(r=new RegExp(t.source,`${t.flags}g`),Om.set(t,r));let i=r.unicode||r.flags.includes(`v`),a=0;for(;a<=e.length;){let s=r.lastIndex,c;try{r.lastIndex=a,c=r.exec(e)}finally{r.lastIndex=s}if(!c)return;if(a=c.index+c[0].length,!c[0]){let t=e.codePointAt(a);a+=i&&t!==void 0&&t>65535?2:1}n({match:c[0],groups:c.slice(1).map(e=>e??``),input:e,offset:c.index},t)}}function replaceRedactPattern(e,t,n,r){if(t instanceof RegExp)return Em.get(t)?.(e)===!1?(t.lastIndex=0,e):e.replace(t,r??((...e)=>n(readRedactMatch(e))));let i=[],a=0;return visitRedactMatches(e,t,t=>{i.push(e.slice(a,t.offset),n(t)),a=t.offset+t.match.length}),i.length?i.join(``)+e.slice(a):e}function redactPemBlock(e,t){let n=e.split(/\r?\n/).filter(Boolean);return n.length<2?`***`:`${n[0]}\n${t}\n${n[n.length-1]}`}var Sm,Cm,wm,Tm,escapeHexValue,isHighSurrogateEscape,isLowSurrogateEscape,Em,Dm,Om,km=__esmMin((()=>{Sm=/^\{(\d+),\}/,Cm=/^\{(?:\d+(?:,\d*)?|,\d+)\}/,wm=/[0-9A-Fa-f]/,Tm=/* @__PURE__ */ new Set([`b`,`B`]),escapeHexValue=(e,t)=>{let n=0;for(let r=0;r<4;r+=1){let i=e[t+r];if(i===void 0||!wm.test(i))return null;n=n*16+Number.parseInt(i,16)}return n},isHighSurrogateEscape=(e,t)=>{let n=escapeHexValue(e,t+2);return n!==null&&n>=55296&&n<=56319},isLowSurrogateEscape=(e,t)=>{let n=escapeHexValue(e,t+2);return n!==null&&n>=56320&&n<=57343},Em=/* @__PURE__ */ new WeakMap,Dm=/* @__PURE__ */ new WeakMap,Om=/* @__PURE__ */ new WeakMap}));function stringBoundaries(e,t,n){let r=/* @__PURE__ */ new Map,i=0;for(let a=t;a<n;i+=1)r.set(a,i),a+=e[a]===`\\`?e[a+1]===`u`?6:2:1;return r.set(n,i),r}function decodedBoundary(e,t,n){return t.escaped?(t.boundaries??=stringBoundaries(e,t.start+1,t.end-1),t.boundaries.get(n)):n-t.start-1}function encodedBoundary(e,t,n){if(!t.escaped)return t.start+1+n;if(!t.encodedBoundaries){t.boundaries??=stringBoundaries(e,t.start+1,t.end-1),t.encodedBoundaries=[];for(let[e,n]of t.boundaries)t.encodedBoundaries[n]=e}return expectDefined(t.encodedBoundaries[n],`decoded JSON edit boundary`)}function projectMessageEdits(e,t,n,r){let i=new Map(n.parts.map(e=>[e.key,e])),a=[];for(let s of t){if(!s.isKey&&s.path.length===1&&s.key===`message`)continue;let t=s.rootKey===void 0?void 0:i.get(s.rootKey);if(!t||!t.json&&(s.isKey||(t.messageField?s.path.length!==2||s.key!==`message`:s.path.length!==1)))continue;let c=r(s);for(let r of c){let i,c,l=r.replacement;if(t.json){let n=t.start-expectDefined(s.rootValueStart,`displayed JSON argument`);s.string?(i=n+encodedBoundary(e,s,r.start),c=n+encodedBoundary(e,s,r.end),l=JSON.stringify(l).slice(1,-1)):(i=n+s.start,c=n+s.end,l=JSON.stringify(l))}else i=t.start+r.start,c=t.start+r.end;i<n.contentLength&&a.push({start:i,end:Math.min(c,n.contentLength),replacement:l,scalar:t.json&&!s.string})}}return a.toSorted((e,t)=>e.start-t.start||e.end-t.end)}function firstIntersectingToken(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;expectDefined(e[i],`bounded JSON token search`).currentEnd<=t?n=i+1:r=i}return n}function updateCurrentToken(e,t){if(t.raw||t.deferEncoding){t.currentRaw=t.currentValue;return}let n=[],r=[],i=t.start+ +!!t.string,a=0,s=0;for(let c of t.edits){let l=t.string?encodedBoundary(e,t,c.start):t.start+c.start,u=t.string?encodedBoundary(e,t,c.end):t.start+c.end,d=JSON.stringify(c.replacement).slice(1,-1),f=a+l-i,p=f+d.length;r.push({start:f,end:p,decodedStart:c.start+s,decodedEnd:c.start+s+c.replacement.length,sourceEnd:u,sourceDecodedEnd:c.end,replacement:d}),n.push(e.slice(i,l),d),a=p,s+=c.replacement.length-(c.end-c.start),i=u}n.push(e.slice(i,t.end-+!!t.string)),t.currentRaw=`"${n.join(``)}"`,t.encodedEdits=r}function currentDecodedBoundary(e,t,n,r){let i=n-t.currentStart-1,a=t.encodedEdits;if(!a)return decodedBoundary(e,t,t.start+1+i);let s=0,c=a.length;for(;s<c;){let e=s+c>>>1;expectDefined(a[e],`current encoded edit`).end<i?s=e+1:c=e}let l=a[s];if(l&&i>=l.start){let e=i-l.start;if(!l.replacement.includes(`\\`))return l.decodedStart+e;let t=r.get(l.replacement);t||(t=stringBoundaries(l.replacement,0,l.replacement.length),r.set(l.replacement,t));let n=t.get(e);return n===void 0?void 0:l.decodedStart+n}let u=a[s-1],d=decodedBoundary(e,t,i+(u?u.sourceEnd-u.end:t.start+1));return d===void 0?void 0:d+(u?u.decodedEnd-u.sourceDecodedEnd:0)}function commitPatternEdits(e){let t=e.pending;if(e.pending=void 0,!t)return!1;let n=mergeRedactionEdits(t),r=applyRedactionEdits(e.currentValue,n);return r!==e.currentValue&&(e.edits=composeRedactionEdits(e.value.length,e.edits,n),e.currentValue=r,!0)}function changedRedactionEdits(e,t){let n=0;return t.filter(t=>{for(;e[n]&&expectDefined(e[n],`previous configured edit`).start<t.start;)n+=1;let r=e[n];return!r||r.start!==t.start||r.end!==t.end||r.replacement!==t.replacement})}function commitOriginalEdits(e,t){if(t.length===0)return!1;let n=mergeRedactionEdits([...e.edits,...t]),r=applyRedactionEdits(e.value,n);return r!==e.currentValue&&(e.edits=n,e.currentValue=r,!0)}function updateCurrentRecord(e,t,n,r){let i=[],a=0,s=0;for(let c of n){let n=c.currentStart,l=c.currentEnd;if(r.has(c)){updateCurrentToken(e,c);let r=expectDefined(c.currentRaw,`changed JSON token`);i.push(t.slice(a,n),r),a=l,c.currentStart=n+s,s+=r.length-(l-n)}else c.currentStart=n+s;c.currentEnd=l+s}return i.push(t.slice(a)),i.join(``)}function projectedStringEnd(e,t,n,r,i,a){let s=new Set(n.parts.filter(e=>e.json).map(e=>e.key)),c=projectMessageEdits(e,t,n,e=>e.string&&!e.isKey&&e.rootKey!==void 0&&s.has(e.rootKey)?[{start:0,end:e.value.length,replacement:``}]:[]).filter(e=>e.end<n.contentLength),l=rebaseRedactionEdits(r.edits,c).filter(e=>e.start<=i&&i<e.end&&a<=e.end);return l.length===1?expectDefined(l[0],`displayed source string`).end:r.currentValue.length}function redactJsonRecord(e,t,n,r,i,a,s,c,l,u){let d=u?[]:readScalarTokens(e,t),f=l?d.find(e=>!e.isKey&&e.path.length===1&&e.key===`message`):void 0,p=/* @__PURE__ */ new Map,m=[],h=f?.value??``,g=e,v=/* @__PURE__ */ new Set;for(let e of d)commitOriginalEdits(e,s(e))&&v.add(e);v.size>0&&(g=updateCurrentRecord(e,g,d,v));let y=d.filter(e=>!e.isKey&&e.string&&!c(e,e.currentValue)),projectMessage=()=>{if(!f||!l)return!1;let t=projectMessageEdits(e,d,l,e=>{let t=changedRedactionEdits(e.projectedEdits,e.edits);return e.projectedEdits=e.edits,t});if(t.length===0)return!1;let n=rebaseRedactionEdits(m,t),r=rebaseRedactionEdits(f.edits,t),i=0;for(let e=0;e<r.length;e+=1){let a=expectDefined(r[e],`projected message edit`),s=expectDefined(n[e],`projected source edit`),c=expectDefined(t[e],`source projection`);for(;f.edits[i]&&expectDefined(f.edits[i],`generated message span`).start<c.start;)i+=1;let l=f.edits[i],u=c.scalar&&l?.start===c.start&&l.end===c.end&&a.replacement===JSON.stringify(l.replacement),d=f.currentValue.slice(a.start,a.end);!u&&d!==a.replacement&&d!==h.slice(s.start,s.end)&&(a.replacement=c.scalar?JSON.stringify(`***`):`***`)}return f.pending=r,h=applyRedactionEdits(h,n),m=composeRedactionEdits(f.value.length,m,n),commitPatternEdits(f)};for(let[s,c]of n.entries()){let n=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Set,add=(e,t)=>{(e.pending??=[]).push(t),m.add(e)},h,visitDecodedMatch=(e,t)=>{let n=r(e,t),i=n?.redact(n);i&&i.end>=i.start&&add(h,i)};for(let i of c)if(!i.couldMatch||i.couldMatch(g))for(let a of i.patterns){if(s===0)for(h of y)visitRedactMatches(h.currentValue,a,visitDecodedMatch);else visitRedactMatches(g,a,n=>{let i=r(n,a);if(!(!i||i.end<i.start)){u&&d.length===0&&(d=readBatchTokens(e,t,u.preserveLines));for(let t=firstIntersectingToken(d,i.start);t<d.length;t+=1){let n=expectDefined(d[t],`serialized capture token`);if(n.currentStart>=i.end)break;let r=n.raw||n.deferEncoding,a=+!r,s=i.start>=n.currentStart+a&&i.end<=n.currentEnd-a;if(u&&n.isKey&&!s)continue;let c=n.currentValue;if(!n.raw&&!n.string&&n.edits.length===0){add(n,{start:0,end:c.length,replacement:`***`});continue}let m=Math.max(i.start,n.currentStart+a),h=r?m-n.currentStart:currentDecodedBoundary(e,n,m,p),v=Math.min(i.end,n.currentEnd-a),y=r?v-n.currentStart:currentDecodedBoundary(e,n,v,p);if(h===void 0||y===void 0){for(;h===void 0;)h=currentDecodedBoundary(e,n,--m,p);for(;y===void 0;)y=currentDecodedBoundary(e,n,++v,p);let t=n===f&&l?projectedStringEnd(e,d,l,n,h,y):c.length;add(n,{start:h,end:t,replacement:`***`});continue}if(y<h||u&&y===h)continue;let{start:b,end:x}=i,ee=i.redact({start:h,end:y,value:g.slice(Math.max(b,n.currentStart+a),Math.min(x,n.currentEnd-a))});if(!ee)continue;let te=`***`;if(s)try{te=r?ee.replacement:JSON.parse(`"${ee.replacement}"`)}catch{}add(n,{...ee,replacement:te})}}});if(m.size!==0){for(let e of m)commitPatternEdits(e)?s===0&&n.add(e):m.delete(e);s!==0&&m.size>0&&(g=updateCurrentRecord(e,g,d,m)),m.clear()}}for(let e of d)s===0?(e.pending=i(e,e.currentValue),commitPatternEdits(e)&&n.add(e)):commitOriginalEdits(e,a(e))&&n.add(e);(s!==0||v.size>0||n.size>0)&&projectMessage()&&f&&n.add(f),n.size>0&&(g=updateCurrentRecord(e,g,d,n))}if(f&&l){let e=l.finish(f.currentValue);if(e!==f.currentValue)return applyRedactionEdits(g,[{start:f.currentStart,end:f.currentEnd,replacement:JSON.stringify(e)}])}return applyRedactionEdits(g,d.flatMap(e=>e.deferEncoding&&e.edits.length>0?[{start:e.currentStart,end:e.currentEnd,replacement:JSON.stringify(e.currentValue)}]:[]))}var Am=__esmMin((()=>{Yu(),ym(),xm(),km()}));function createState(){return{scanner:{offset:0,phase:`search`,dashes:0,keyword:`BEGIN `,keywordOffset:0,start:0,suffix:``},matchEnd:0}}function resetScanner(e,t){e.phase=`search`,e.dashes=+(t===`-`),e.suffix=``}function*readDelimiters(e,t){for(let n=0;n<e.length;n+=1){if(t.phase===`search`&&t.dashes===0){let r=e.indexOf(`-`,n);if(r===-1){t.offset+=e.length-n;return}t.offset+=r-n,n=r}let r=e.charCodeAt(n),i=r>=97&&r<=122?String.fromCharCode(r-32):e.charAt(n),a=t.offset++;switch(t.phase){case`search`:i===`-`?t.dashes=Math.min(5,t.dashes+1):t.dashes===5&&(i===`B`||i===`E`)?(t.phase=`keyword`,t.keyword=i===`B`?`BEGIN `:`END `,t.keywordOffset=1,t.start=a-5):t.dashes=0;break;case`keyword`:i===t.keyword.charAt(t.keywordOffset)?++t.keywordOffset===t.keyword.length&&(t.phase=`label`,t.suffix=``):resetScanner(t,i);break;case`label`:i>=`A`&&i<=`Z`||i===` `?t.suffix=(t.suffix+i).slice(-11):i===`-`&&t.suffix===`PRIVATE KEY`?(t.phase=`close`,t.dashes=1):resetScanner(t,i);break;case`close`:i===`-`?++t.dashes===5&&(t.phase=`search`,t.suffix=``,yield{kind:t.keyword===`BEGIN `?`begin`:`end`,start:t.start,end:a+1}):resetScanner(t,i)}}}function consumeDelimiter(e,t){if(!e.open){t.kind===`begin`&&t.start>=e.matchEnd&&(e.open={start:t.start,end:t.end});return}if(t.kind!==`end`||t.start<=e.open.end)return;let n={start:e.open.start,end:t.end,bodyStart:e.open.end,bodyEnd:t.start};return e.open=void 0,e.matchEnd=t.end,n}function*matchPem(e,t,n){let r={...t,scanner:{...t.scanner},open:t.open&&{...t.open}},i=r.scanner.offset;for(let t of readDelimiters(e,r.scanner)){let a=consumeDelimiter(r,t);if(!a)continue;let s=Math.max(0,(n?a.bodyStart:a.start)-i),c=(n?a.bodyEnd:a.end)-i;c<=s||(yield{match:e.slice(s,c),groups:[],input:e,offset:s,...n?{replacement:`…redacted…`}:{}})}if(n&&r.open){let t=Math.max(0,r.open.end-i);t<e.length&&(yield{match:e.slice(t),groups:[],input:e,offset:t,replacement:`…redacted…`})}}var jm,Mm,Nm=__esmMin((()=>{jm=String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----`,Mm={source:jm,exec(e){return matchPem(e,createState(),!1)},createContext(){let e=!1,t=!0;return{resolve(n){e=n?t:e,t=e},advance(t){let n=createState();e&&(n.open={start:-1,end:-1});for(let e of readDelimiters(t,n.scanner))consumeDelimiter(n,e);return n.open!==void 0},prepend(){let n=createState(),r=createState();return r.open={start:-1,end:-1},{consume(e){for(let t of readDelimiters(e,n.scanner))consumeDelimiter(n,t),consumeDelimiter(r,t)},finish(){let i=n.open?t:e,a=r.open?t:e;return e=i,t=a,e===t}}},pattern:{source:jm,exec(t){let n=createState();return e&&(n.open={start:-1,end:-1}),matchPem(t,n,!0)}}}}}}));function isAwsValueCharacter(e){let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122||t>=48&&t<=57||e===`/`||e===`+`||e===`=`}function couldMatchAwsSecretAccessKey(e){for(let t=39;t<e.length;){let n=t;for(;n>t-40&&isAwsValueCharacter(e[n]);)n--;if(n===t-40)return lh.test(e);t=n+40}return!1}function*matchAwsSecretAccessKeys(e){if(!couldMatchAwsSecretAccessKey(e))return;let t={'"':`"`,"'":`'`,"`":"`","<":`>`,"(":`)`,"[":`]`,"{":`}`},n=-1,r=-1,i,a=0,s=[];for(let c=0;c<=e.length;c++){let l=e[c]??``,u=c===e.length||uh.test(l),d=a;if(a=l===`\\`?a+1:0,l&&isAwsValueCharacter(l)?n===-1&&(n=c):n!==-1&&(c-n===40?s.push({start:n,end:c,origin:n,url:i}):c-n>40&&l===`@`&&e[c-41]===`/`&&s.push({start:c-40,end:c,origin:n,url:i}),n=-1),u){i&&(i.end=Math.min(i.end,c));for(let t of s){let n=t.url,r=n&&!n.hasAt&&n.portValid&&(n.portStart===-1||(n.authorityEnd===-1?n.end:n.authorityEnd)>n.portStart+1),i=e[t.start-1]??``,a=e[t.end]??``,s=t.start!==t.origin,c=n&&n.portStart!==-1&&t.origin===n.portStart+1&&n.authorityEnd>t.origin&&t.end>n.authorityEnd&&a===`@`;if(!s&&(i===`_`||isAwsValueCharacter(i))||a===`_`||e.slice(t.origin-8,t.origin)===`;base64,`||r&&!c&&t.start>=n.start&&t.end<=n.end)continue;let l=e.slice(t.start,t.end);lh.test(l)&&(yield{match:l,groups:[l],input:e,offset:t.start})}s.length=0,r=-1,i=void 0}else if(i&&c>=i.start&&(l===i.closing&&d===i.closingEscapeDepth?(i.end=Math.min(i.end,c),i=void 0):(`?#"'<>\`|()[]{}`.includes(l)&&(i.end=Math.min(i.end,c)),i.queryOrFragment||=l===`?`||l===`#`,i.authorityEnd===-1&&(i.hasAt||=l===`@`,`/?#`.includes(l)?i.authorityEnd=c:c<i.end&&(l===`:`?(i.portValid&&=i.portStart===-1,i.portStart=c):i.portStart!==-1&&(l<`0`||l>`9`)&&(i.portValid=!1))))),dh.test(l))r===-1&&(r=c);else{if((!i||c>=i.end&&!i.queryOrFragment)&&l===`:`&&e.startsWith(`//`,c+1)&&r!==-1&&fh.test(e[r])){let n=e[r-1],a=0;for(let t=r-2;t>=0&&e[t]===`\\`;t--)a++;i={start:c+3,end:e.length,authorityEnd:-1,portStart:-1,portValid:!0,hasAt:!1,queryOrFragment:!1,closing:n?t[n]:void 0,closingEscapeDepth:a}}r=-1}}}function*matchBarePassAssignments(e){if(!/pass\s*:/.test(e))return;let t=[...e.matchAll(mh)];if(t.length===0)return;let n=0,r=!1;for(let i=0;i<e.length;i++){let a=t[n];if(!a)return;if(i===a.index){n++;let s=e[i-1]??``,c=a[1]!==`pass`||s===`.`||s===`-`||s===`_`;if(c||r||s!==` `||!gh.test(e[i-2]??``)){r=!0;let s=i+a[0].length;if(!c){hh.lastIndex=s;let t=hh.exec(e)?.[0];t&&(s+=t.length,yield{match:e.slice(i,s),groups:[t],input:e,offset:i})}let l=t[n];for(;l&&l.index<s;)n++,l=t[n];i=s-1;continue}}let s=e[i];s===`
`||s===`\r`?r=!1:(s===`=`||s===`:`&&!_h.test(e[i+1]??` `))&&(r=!0)}}function createBackendRedactPatterns(){let e=/* @__PURE__ */ new Set(/* @__PURE__ */ `access_token.auth_token.awssecretaccesskey.aws_secret_access_key.hook_token.refresh_token.id_token.token.api_key.apikey.client_secret.app_secret.password.pass.passwd.auth.jwt.session.code.signature.x_amz_signature.x_amz_security_token.secret.secretaccesskey.credential.private_key.authorization.key.card_number.card_cvc.card_cvv.cvc.cvv.security_code.payment_credential.shared_payment_token`.split(`.`)),t=RegExp(`^(?:${xh}|${Sh})$`,`i`),n=/* @__PURE__ */ new Set([Th,Dh]),r=/* @__PURE__ */ new Set([qm,Jm,Ym,Xm]),i=new RegExp(String.raw`[:=](?<=(?:${Vm})\s*[:=])`),a=new RegExp(String.raw`[:=](?<=(?:${Vm})\s*[:=])\s*["'\x60]`),s=new RegExp(String.raw`[:=](?<=\.(?:${Vm})\s*[:=])`),c=new RegExp(String.raw`=(?<=(?:^|[\s,;({\["])(?:${Bm})=)`,`i`);return{bodySecretKeys:e,credentialHeaderField:t,formAware:n,shellReferencePreserving:r,prefilters:new Map([[qm,e=>/KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD|CVC|CVV|SECURITY|PAYMENT/.test(e)],[Jm,e=>e.includes(`\\`)],[Ym,e=>/[=]["'`]/.test(e)],[Xm,e=>c.test(e)],[Qm,e=>/["'`]/.test(e)&&a.test(e)],[$m,e=>(e.includes(`:`)||e.includes(`=`))&&i.test(e)],[eh,e=>e.includes(`=`)],[th,e=>/[-_](?:password|passphrase|pass|passwd)\s*[:=]/.test(e)],[nh,e=>s.test(e)],[ah,e=>/["']/.test(e)],[oh,e=>/["']/.test(e)],...Oh.slice(0,4).map(e=>[e,e=>/authorization/i.test(e)]),[wh,e=>/api-key|apikey|api-token|access-token/i.test(e)],[Th,e=>/api-key|apikey|api-token|access-token/i.test(e)],[rh,e=>e.includes(`"`)],[ih,e=>e.includes(`"`)],[Eh,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)],[Dh,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)]]),chunkUnsafe:/* @__PURE__ */ new Set([yh,bh,kh,Ah,jh,Mh,...Oh,...Ph.filter(e=>e.startsWith(sh))])}}var Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,base64SafeToken,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih=__esmMin((()=>{cm(),Nm(),Pm=String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`,Fm=String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`,Im=String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`,Lm=String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`,Rm=String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${Lm}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`,zm=String.raw`${Rm}|app[-_]?secret|credential|${Fm}`,Bm=String.raw`access_token|refresh_token|id_token|auth[-_]?token|hook[-_]?token|api[-_]?key|client[-_]?secret|app[-_]?secret|private[-_]?key|authorization|jwt|token|secret|password|pass|passwd|credential|${Fm}`,Vm=String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|credential|${Fm}`,Hm=String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|passwd|credential|${Fm}`,Um=String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`,Wm=String.raw`password|passphrase|pass|passwd`,Gm=String.raw`${Lm}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${Fm}`,Km=String.raw`\p{C}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0`,qm=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Pm})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`,Jm=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Pm})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`,Ym=String.raw`(^|[\s,;({\["])(?:${Bm})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`,Xm=String.raw`(^|[\s,;({\["])(?:${Bm})=(["'\x60]?[^\s&#"'\x60<>]+)`,Zm=String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|${Fm}`,Qm=String.raw`/(^|[\s,{])(?:(?:${Zm})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${Wm})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${Vm})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`,$m=String.raw`/(^|[\s,{])(?:(?:${Hm})\s*:\s*|(?:${Vm})(?:\s+=\s*|=\s+))([^\s#"'\x60<>]+)/g`,eh=String.raw`/(^|[\s,{])(?:${Um})=([^\s#"'\x60<>]+)/g`,th=String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${Wm})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,nh=String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${Vm})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,rh=String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${Lm}|credential|authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|authToken|auth_token|clientSecret|client_secret|privateKey|private_key|secret_value|raw_secret|secret_input|key_material)"\s*:\s*"([^"]+)"`,ih=String.raw`"(?:${Im})"\s*:\s*"([^"]+)"`,ah=String.raw`(^|[\s,{])["']?(?:api[-_]key|access[-_]token|refresh[-_]token|id[-_]token|authToken|auth[-_]token|clientSecret|client[-_]secret|appSecret|app[-_]secret|private[-_]key|credential|authorization|secret[-_]value|raw[-_]secret|secret[-_]input|key[-_]material)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,oh=String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,sh=String.raw`(^|[^A-Za-z0-9])`,base64SafeToken=e=>String.raw`${sh}(?=${e})(?<!;base64,[A-Za-z0-9+/=]*)(${e})`,ch=String.raw`(^|[^A-Za-z0-9_])`,lh=/(?=[A-Za-z0-9/+=]{0,39}[A-Z])(?=[A-Za-z0-9/+=]{0,39}[a-z])(?=[A-Za-z0-9/+=]{0,39}[0-9/+=])(?=[A-Za-z0-9/+=]{0,39}[G-Zg-z/+=])[A-Za-z0-9/+=]{40}/u,uh=/\s/,dh=/[A-Za-z0-9+.-]/,fh=/[A-Za-z]/,ph=Object.freeze({source:`aws-secret-access-key`,exec:matchAwsSecretAccessKeys,couldMatch:couldMatchAwsSecretAccessKey}),mh=new RegExp(String.raw`(?<![A-Za-z0-9])(pass|${Hm})\s*:\s*`,`gi`),hh=/[^\s#"'\x60<>]+/y,gh=/[A-Za-z0-9]/,_h=/[ \t\r\n]/,vh=Object.freeze({source:`bare-pass-assignment`,exec:matchBarePassAssignments}),yh=String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`,bh=String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`,xh=`x-goog-api-key|api-key|apikey|x-api-token|x-access-token`,Sh=`X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token`,Ch=String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`,wh=String.raw`${Ch}(?:${xh})${U}[ \t]*:${tm}${U}([^\s\\"',;]+)`,Th=String.raw`${Ch}(?:${xh})${U}[ \t]*=${tm}${U}([^\s\\"',;]+)`,Eh=String.raw`${Ch}(?:${Sh})\s*:\s*([^\s"',;]+)`,Dh=String.raw`${Ch}(?:${Sh})\s*=\s*([^\s"',;]+)`,Oh=[String.raw`${im}Proxy-Authorization${U}[ \t]*[:=]${tm}${U}${Zp}${nm}(${Qp})`,String.raw`${im}Proxy-Authorization${U}[ \t]*[:=]${tm}${U}(${Qp})[ \t]*(?=${U}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,String.raw`${im}Authorization${U}[ \t]*[:=]${tm}${U}(?!(?:Bearer|Basic|Bot)(?=${nm}))${Zp}${nm}(${Qp})`,String.raw`${im}Authorization${U}[ \t]*[:=]${tm}${U}(?!(?:Bearer|Basic|Bot)(?=${nm}))(${Qp})[ \t]*(?=${U}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,wh,Th],kh=String.raw`Authorization${U}[ \t]*[:=]${rm}${U}Bearer${nm}(${Qp})`,Ah=String.raw`Authorization${U}[ \t]*[:=]${rm}${U}Basic${nm}(${Qp})`,jh=String.raw`Authorization${U}[ \t]*[:=]${rm}${U}Bot${nm}(${Qp})`,Mh=String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`,Nh=[qm,Jm,rh,ih,ah,oh,String.raw`--(?:${Gm})=([^\s"']+)`,String.raw`--(?:${Gm})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,kh,Ah,jh,...Oh,Eh,Dh,Mh,String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,String.raw`(^|[\s,;])(?:${zm})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,Ym,Xm,Qm,$m,vh,eh,th,nh,jm,String.raw`(^|[\s,{])["']?(?:${Lm})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`],Ph=[String.raw`\b(sk-[A-Za-z0-9_-]{8,})\b`,String.raw`(ghp_[A-Za-z0-9]{10,})`,String.raw`(github_pat_[A-Za-z0-9_]{10,})`,String.raw`(gho_[A-Za-z0-9]{10,})`,String.raw`(ghu_[A-Za-z0-9]{10,})`,String.raw`(ghs_[A-Za-z0-9]{10,})`,String.raw`(ghr_[A-Za-z0-9]{10,})`,String.raw`(glpat-[A-Za-z0-9._=\-]{20,})`,String.raw`(gloas-(?:[A-Fa-f0-9]{65,}|[A-Za-z0-9_-]{64}|[A-Fa-f0-9]{32,}))`,String.raw`(gldt-[A-Za-z0-9_-]{20,})`,String.raw`(glcbt-[A-Za-z0-9]{1,5}_[A-Za-z0-9_-]{20,})`,String.raw`(glptt-[A-Za-z0-9_-]{40,})`,String.raw`(glft-(?:[A-Za-z0-9_-]{20,}|[a-h0-9]+-[0-9]+_))`,String.raw`(glimt-[A-Za-z0-9_-]{25,})`,String.raw`(glagent-[A-Za-z0-9_-]{50,})`,String.raw`(glwt-[A-Za-z0-9_-]{20,})`,String.raw`(glsoat-[A-Za-z0-9_-]{20,})`,String.raw`(glffct-[A-Za-z0-9_-]{20,})`,String.raw`(glrt-[A-Za-z0-9._-]{20,})`,String.raw`(glrtr?-[A-Za-z0-9_-]{27,300}\.[0-9a-z]{2}\.[0-9a-z]{9})`,String.raw`(GR1348941[A-Za-z0-9_-]{20,})`,String.raw`(_gitlab_session=[A-Za-z0-9%._-]{20,})`,String.raw`(xox[baprs]-[A-Za-z0-9-]{10,})`,String.raw`(xapp-[A-Za-z0-9-]{10,})`,String.raw`(https:\/\/hooks\.slack\.com\/(?:services\/T[A-Z0-9]+\/B[A-Z0-9]+|workflows\/T[A-Z0-9]+\/A[A-Z0-9]+\/[0-9]{17,19})\/[A-Za-z0-9]{20,})`,String.raw`(https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_-]{60,})`,String.raw`discord(?:.|\n|\r){0,40}?\b([A-Za-z0-9_-]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27})\b`,String.raw`(gsk_[A-Za-z0-9_-]{10,})`,String.raw`(AIza[0-9A-Za-z\-_]{20,})`,String.raw`(ya29\.[0-9A-Za-z_\-./+=]{10,})`,String.raw`(1//0[0-9A-Za-z_\-./+=]{10,})`,String.raw`(GOCSPX-[A-Za-z0-9_-]{20,})`,String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,String.raw`(pplx-[A-Za-z0-9_-]{10,})`,String.raw`(fal_[A-Za-z0-9_-]{10,})`,String.raw`${ch}(fc-[A-Za-z0-9]{10,})`,String.raw`(bb_live_[A-Za-z0-9_-]{10,})`,base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),String.raw`(sk_live_[A-Za-z0-9]{10,})`,String.raw`(sk_test_[A-Za-z0-9]{10,})`,String.raw`(rk_live_[A-Za-z0-9]{10,})`,String.raw`(SG\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,String.raw`(npm_[A-Za-z0-9]{10,})`,String.raw`(pypi-[A-Za-z0-9_-]{10,})`,String.raw`(dop_v1_[A-Za-z0-9]{10,})`,String.raw`(doo_v1_[A-Za-z0-9]{10,})`,String.raw`(dor_v1_[A-Za-z0-9]{10,})`,String.raw`(dp\.(?:ct|pt|sa|scim|audit)\.[A-Za-z0-9]{40,44})`,String.raw`(dp\.st\.[A-Za-z0-9]{40,44})`,String.raw`(dp\.st\.[a-z0-9_-]{2,35}\.[A-Za-z0-9]{40,44})`,String.raw`(dckr_(?:pat|oat)_[A-Za-z0-9_-]{27,32})`,String.raw`(bkua_[a-z0-9]{40})`,String.raw`(CCIPAT_[A-Za-z0-9]{22}_[A-Fa-f0-9]{40})`,String.raw`(sbp_[a-z0-9]{40})`,base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),String.raw`(dd[pw]_[A-Za-z0-9]{36})`,String.raw`(glsa_[A-Za-z0-9_]{41})`,String.raw`(glc_eyJ[A-Za-z0-9+/=]{60,160})`,String.raw`(nfp_[A-Za-z0-9_]{36})`,String.raw`(CFPAT-[A-Za-z0-9_\-]{40,})`,base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),String.raw`(BBDC-[A-Za-z0-9+/@_-]{40,50})`,String.raw`(HRKU-AA[A-Za-z0-9_-]{20,})`,String.raw`(pat-(?:eu|na)1-[A-Za-z0-9]{8}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{12})`,String.raw`(apify_api_[A-Za-z0-9\-]{20,})`,String.raw`(FlyV1 fm\d+_[A-Za-z0-9+/=,_-]{100,})`,String.raw`(fio-u-[A-Za-z0-9_-]{40,})`,String.raw`(^|[^A-Za-z0-9_])(am_[A-Za-z0-9_-]{10,})`,String.raw`(^|[^A-Za-z0-9_])(sk_[A-Za-z0-9_]{10,})`,String.raw`(tvly-[A-Za-z0-9]{10,})`,String.raw`(exa_[A-Za-z0-9]{10,})`,String.raw`(syt_[A-Za-z0-9]{10,})`,String.raw`(retaindb_[A-Za-z0-9]{10,})`,String.raw`(hsk-[A-Za-z0-9]{10,})`,String.raw`(mem0_[A-Za-z0-9]{10,})`,String.raw`(brv_[A-Za-z0-9]{10,})`,String.raw`(xai-[A-Za-z0-9]{30,})`,String.raw`${ch}(fw-[A-Za-z0-9]{30,})`,String.raw`${ch}(fw_[A-Za-z0-9]{30,})`,String.raw`${ch}(fpk_[A-Za-z0-9]{30,})`,base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),String.raw`(AKID[A-Za-z0-9]{10,})`,String.raw`(LTAI[A-Za-z0-9]{10,})`,String.raw`(hf_[A-Za-z0-9]{10,})`,String.raw`(api_org_[A-Za-z0-9]{20,})`,String.raw`(r8_[A-Za-z0-9]{10,})`,yh,bh],Fh=[...Nh,...Ph,ph]}));function isJsWhitespaceAt(e,t){if(t>=e.length)return!1;let n=e.charCodeAt(t);return Lh.has(n)||n>=8192&&n<=8202}function isJsWhitespaceChar(e){return e!==void 0&&isJsWhitespaceAt(e,0)}function isAlnumChar(e){if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function isLetterChar(e){if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function isWordChar(e){return e===`_`||isAlnumChar(e)}function isHexChar(e){if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function isDigitChar(e){return e!==void 0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57}function isBase64UrlChar(e){return isAlnumChar(e)||e===`+`||e===`/`||e===`=`}function*scanPrefixOccurrences(e,t){let n=Rh.get(t);n||(n=[],Rh.set(t,n));let r=n.pop()??new RegExp(t,`gi`);try{r.lastIndex=0;for(let t=r.exec(e);t;t=r.exec(e))yield t.index}finally{r.lastIndex=0,n.push(r)}}function isDataUrlPrefix(e,t){return t>=8&&e.slice(t-8,t).toLowerCase()===`;base64,`}function runEndOf(e,t,n){let r=t;for(;r<e.length&&n(e[r]);)r+=1;return r}function makeCachedRunEnd(e,t){let n=-1,r=-1;return i=>((i<n||i>=r)&&(n=i,r=runEndOf(e,i,t)),r)}function makeBase64SafeTokenMatcher(e,t,n){function*exec(e){let r=n(),i=-1,a=-1,s=0;for(let n of scanPrefixOccurrences(e,t)){if(n<s||n>0&&isAlnumChar(e[n-1]))continue;if(n>0){let t;if(isBase64UrlChar(e[n-1])){if(n-1>=i&&n-1<a)t=i;else{let r=n-1;for(;r>0&&isBase64UrlChar(e[r-1]);)--r;i=r,a=runEndOf(e,n,isBase64UrlChar),t=r}}else t=n;if(isDataUrlPrefix(e,t))continue}let t=r(e,n);if(t===null)continue;let c=n>0?n-1:0;yield{match:e.slice(c,t),groups:[n>0?e[n-1]:``,e.slice(n,t)],input:e,offset:c},s=t+1}}return Object.freeze({source:e,exec})}function fixedTailTokenEnd(e,t,n){return(r,i)=>{let a=i+e+t;for(let t=i+e;t<a;t++)if(!n(r[t]))return null;return a}}function dapiTokenEnd(e,t){let n=zh(e,t);return n===null?null:e[n]===`-`&&isDigitChar(e[n+1])?n+2:n}function makeAtEqualsTokenMatcher(e,t){let n=t.length,r=fixedTailTokenEnd(1,8,isAlnumChar);return makeBase64SafeTokenMatcher(e,t,()=>{let e=-1,t=-1,i;return(a,s)=>{let c=s+n;if(c<e||c>=t){t=runEndOf(a,c,AT_VALUE_CHAR),e=c,i=void 0;for(let e=c;e<t;e++)a[e]===`=`&&r(a,e)!==null&&(i=e)}let l=c+1;return i!==void 0&&i>=l?i+9:null}})}function makeUserInfoMatcher(e,t,n){function*exec(e){let r=0,i=-1,a=e.indexOf(`://`);for(;a!==-1;){let s=a;for(;s>0&&isWordChar(e[s-1]);)--s;let c=e.slice(s,a).toLowerCase(),l=s;if(!t.has(c)&&s>=8&&c===`srv`&&e.slice(s-8,s).toLowerCase()===`mongodb+`&&(c=`mongodb+srv`,l=s-8),a>=r&&t.has(c)&&(l===0||!isWordChar(e[l-1]))){let t=a+3;for(;t<e.length&&e[t]!==`:`&&e[t]!==`/`&&e[t]!==`@`&&!isJsWhitespaceAt(e,t);)t+=1;if(e[t]===`:`){let s=t+1;if(s>=i){let t=runEndOf(e,s,e=>!n(e));if(e[t]===`@`&&t>s){yield{match:e.slice(l,t+1),groups:[e.slice(s,t)],input:e,offset:l},r=t+1,a=e.indexOf(`://`,t+1);continue}i=t}}}a=e.indexOf(`://`,a+1)}}return Object.freeze({source:e,exec})}function isFormPairBoundary(e,t){let n=e[t+1];return n===void 0||!isLetterChar(n)&&n!==`_`?!1:e[runEndOf(e,t+2,FORM_FIRST_PAIR_TAIL_CHAR)]===`=`}function makeQuotedAssignmentMatcher(e,t,n){let r=[];function*exec(e){let i=r.pop()??new RegExp(t,n),a=/* @__PURE__ */ new Map,s=0;try{for(;;){i.lastIndex=s;let t=i.exec(e);if(!t)return;let n=t.index,r=t[2],c=n+t[0].length,l=a.get(r),u=-1;if(!(l!==void 0&&c>=l.start&&c<l.end))for(u=c;u<e.length;){let t=e[u];if(t===r||t===`\r`||t===`
`)break;u+=1}if(u>c&&e[u]===r){let i=u+1;yield{match:e.slice(n,i),groups:[t[1]??``,r,e.slice(c,u)],input:e,offset:n},s=i}else u!==-1&&a.set(r,{start:c,end:u}),s=n+1}}finally{i.lastIndex=0,r.push(i)}}return Object.freeze({source:e,exec})}var Lh,Rh,GAAAA_VALUE_CHAR,ATBB_VALUE_CHAR,AT_VALUE_CHAR,zh,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,JWT_SEGMENT_CHAR,Jh,Yh,Xh,Zh,Qh,$h,eg,tg,ng,FORM_FIRST_PAIR_KEY_CHAR,FORM_FIRST_PAIR_TAIL_CHAR,rg,ig,ag,og,sg,cg,lg=__esmMin((()=>{Ih(),Lh=/* @__PURE__ */ new Set([9,10,11,12,13,32,160,5760,8232,8233,8239,8287,12288,65279]),Rh=/* @__PURE__ */ new Map,GAAAA_VALUE_CHAR=e=>isAlnumChar(e)||e===`_`||e===`=`||e===`-`,ATBB_VALUE_CHAR=e=>isAlnumChar(e)||e===`_`||e===`=`||e===`.`||e===`-`,AT_VALUE_CHAR=e=>isAlnumChar(e)||e===`+`||e===`/`||e===`=`||e===`-`||e===`_`,zh=fixedTailTokenEnd(4,32,isHexChar),Bh=makeBase64SafeTokenMatcher(`vendor-token gAAAA (linear)`,`gAAAA`,()=>(e,t)=>{let n=runEndOf(e,t+5,GAAAA_VALUE_CHAR);return n-(t+5)>=20?n:null}),Vh=makeBase64SafeTokenMatcher(`vendor-token ATBB (linear)`,`ATBB`,()=>(e,t)=>{let n=runEndOf(e,t+4,ATBB_VALUE_CHAR);return n-(t+4)>=16?n:null}),Hh=makeBase64SafeTokenMatcher(`vendor-token AKIA (linear)`,`AKIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),Uh=makeBase64SafeTokenMatcher(`vendor-token ASIA (linear)`,`ASIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),Wh=makeBase64SafeTokenMatcher(`vendor-token dapi (linear)`,`dapi`,()=>dapiTokenEnd),Gh=makeAtEqualsTokenMatcher(`vendor-token ATCTT3xFfG (linear)`,`ATCTT3xFfG`),Kh=makeAtEqualsTokenMatcher(`vendor-token ATATT (linear)`,`ATATT`),qh=String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,JWT_SEGMENT_CHAR=e=>isAlnumChar(e)||e===`_`||e===`-`,Jh=Object.freeze({source:`jwt (linear)`,*exec(e){let t=makeCachedRunEnd(e,JWT_SEGMENT_CHAR),n=makeCachedRunEnd(e,JWT_SEGMENT_CHAR),r=makeCachedRunEnd(e,JWT_SEGMENT_CHAR),i=0;for(let a of scanPrefixOccurrences(e,`eyj`)){if(a<i)continue;let s=t(a+3);if(s-(a+3)<10||e[s]!==`.`)continue;let c=n(s+1);if(c-(s+1)<10||e[c]!==`.`)continue;let l=r(c+1);if(l-(c+1)<10)continue;let u=e.slice(a,l);yield{match:u,groups:[u],input:e,offset:a},i=l}}}),Yh=String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,Xh=String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,Zh=/* @__PURE__ */ new Set([`http`,`https`,`ws`,`wss`,`ftp`]),Qh=/* @__PURE__ */ new Set([`postgres`,`postgresql`,`mysql`,`mongodb`,`mongodb+srv`,`redis`,`rediss`,`amqp`,`amqps`]),$h=makeUserInfoMatcher(`url-userinfo (linear)`,Zh,e=>e===`/`||e===`@`||isJsWhitespaceChar(e)),eg=makeUserInfoMatcher(`connection-string (linear)`,Qh,e=>e===`@`||isJsWhitespaceChar(e)),tg=String.raw`(^|[\s,;])(?:${zm})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,ng=RegExp(`^(?:${zm})$`,`i`),FORM_FIRST_PAIR_KEY_CHAR=e=>isAlnumChar(e)||e===`-`||e===`_`,FORM_FIRST_PAIR_TAIL_CHAR=e=>isAlnumChar(e)||e===`_`||e===`.`||e===`-`,rg=Object.freeze({source:`form-body-first-pair (linear)`,*exec(e){let t=makeCachedRunEnd(e,e=>e!==`&`&&!isJsWhitespaceChar(e)),n=0,r=e.indexOf(`=`);for(;r!==-1;){let i=r;for(;i>0&&FORM_FIRST_PAIR_KEY_CHAR(e[i-1]);)--i;let a=e.slice(i,r);if(r>=n&&a.length>0&&ng.test(a)&&(i===0||e[i-1]===`,`||e[i-1]===`;`||isJsWhitespaceAt(e,i-1))){let a=r+1,s=t(a);if(s>a&&s<e.length&&e[s]===`&`&&isFormPairBoundary(e,s)){let t=i>0?i-1:0;yield{match:e.slice(t,s),groups:[i>0?e[i-1]:``,e.slice(a,s)],input:e,offset:t},n=s,r=e.indexOf(`=`,s);continue}}r=e.indexOf(`=`,r+1)}}}),ig=String.raw`(^|[\s,;({\["])(?:${Bm})=(["'\x60])`,ag=String.raw`(^|[\s,{])(?:(?:${Zm})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${Wm})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${Vm})\s*[:=]\s*)(["'\x60])`,og=makeQuotedAssignmentMatcher(`standalone-quoted-assignment (linear)`,ig,`gi`),sg=makeQuotedAssignmentMatcher(`config-quoted-assignment (linear)`,ag,`g`),cg=/* @__PURE__ */ new Map([[base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),Bh],[base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Gh],[base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Kh],[base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),Vh],[base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),Wh],[base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),Hh],[base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),Uh],[qh,Jh],[Yh,$h],[Xh,eg],[tg,rg],[Ym,og],[Qm,sg]])}));function maskToken(e){return e.length<ug?`***`:`${sliceUtf16Safe(e,0,dg)}…${sliceUtf16Safe(e,-4)}`}function splitSecretValueForMask(e){let t=e[0]??``,n=+!!mg.has(t);if(n){let n=e.lastIndexOf(t);if(n>0){let t=e.slice(n+1);if(pg.test(t))return{maskable:e.slice(1,n),suffix:t,maskStart:0,maskEnd:n+1}}}let r=e.slice(n),i=r.match(fg)?.[1]??``,a=i&&i.length<r.length?r.slice(0,-i.length):r;return{maskable:a,suffix:a===r?``:i,maskStart:0,maskEnd:n+a.length}}function splitFormAwareCredentialValue(e){let t=e.search(/&[A-Za-z_][A-Za-z0-9_.-]*=/u);return t<0?{secret:e,suffix:``}:{secret:e.slice(0,t),suffix:e.slice(t)}}function maskSecretValue(e){let{maskable:t,suffix:n}=splitSecretValueForMask(e);return`${maskToken(t)}${n}`}var ug,dg,fg,pg,mg,hg=__esmMin((()=>{Ju(),ug=18,dg=6,fg=/(["'`,;)}\]]+)$/u,pg=/^["'`,;)}\]]*$/u,mg=/* @__PURE__ */ new Set([`"`,`'`,"`"])}));function startRedactionMeasurement(e){if(!gg.hasSubscribers)return;let t=we.now(),n=process.threadCpuUsage();return(r,i,a)=>{let s=we.now()-t,c=process.threadCpuUsage(n);gg.publish({operation:e,outcome:r,pid:process.pid,threadId:E,isMainThread:at,elapsedMs:s,threadCpuMs:(c.user+c.system)/1e3,...i===void 0?{}:{inputChars:i},...a===void 0?{}:{patternCount:a}})}}var gg,_g=__esmMin((()=>{gg=$e(`openclaw.redaction`)}));function couldMatchDefaultRedactPatterns(e){return vg.test(e)||(e.includes(`-`)||e.includes(`_`))&&yg.test(e)||bg.test(e)||e.includes(`://`)&&e.includes(`@`)||e.includes(`=`)&&xg.test(e)||ph.couldMatch(e)}function couldMatchDefaultFullContextPatterns(e){return couldMatchDefaultRedactPatterns(e)||Sg.test(e)}function couldMatchVendorRedactPatterns(e){return(e.includes(`-`)||e.includes(`_`))&&yg.test(e)||bg.test(e)||Sg.test(e)}function createRedactPrefilter(e){let t=/* @__PURE__ */ new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}var vg,yg,bg,xg,Sg,Cg=__esmMin((()=>{Ih(),vg=/KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|COOKIE|SIGNATURE|CREDENTIAL|CARD|CVC|CVV|PAYMENT|security[-_]?code|\bpass\s*[=:]|\bpassphrase\s*[=:]|_(?:password|pass|passphrase|passwd)\s*[=:]|jwt\s*[=:]|session=|code=|\bsig\s*=/iu,yg=/sk-|GOCSPX-|gh[opsur]_|github_pat_|glpat-|gloas-|gldt-|glcbt-|glptt-|glft-|glimt-|glagent-|glwt-|glsoat-|glffct-|glrt-|glrtr-|_gitlab_session=|xox[baprs]-|xapp-|gsk_|pplx-|fal_|fc-|bb_live_|[sr]k_(?:live|test)_|npm_|pypi-|do[opr]_v1_|dckr_|bkua_|CCIPAT_|sbp_|dd[pw]_|glsa_|nfp_|CFPAT-|BBDC-|HRKU-|pat-(?:eu|na)1-|apify_api_|fio-u-|tvly-|exa_|syt_|retaindb_|mem0_|brv_|xai-|fw-|fw_|fpk_|(?:^|[^A-Za-z0-9_])(?:am_|sk_)|hf_|api_org_|r8_/iu,bg=/PRIVATE KEY|\bBearer\s+|GR1348941|hooks\.slack\.com|discord|AIza|ya29\.|1\/\/0|eyJ|gAAAA|SG\.|dp\.(?:ct|pt|sa|st|scim|audit)\.|dapi[0-9a-f]|ATCTT3|ATATT|ATBB|FlyV1|A[KS]IA[A-Z0-9]|AKID|LTAI|\bbot\d{6,}:|\b\d{6,}:[A-Za-z0-9_-]{20,}/iu,xg=RegExp(`[${Km}+%]`,`u`),Sg=/JWT|Bearer\s+|am_|sk_|(?<!\d)\d{6,}:[A-Za-z0-9_-]{20,}/i}));function groupPluginRecords(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}var wg=__esmMin((()=>{}));function invalidateMatcher(){Eg.revision+=1,Eg.registeredValueRedactor=void 0}function redactRegisteredSecretValues(e,t){return!e||Eg.registeredValues.size===0?e:(Eg.registeredValueRedactor??=createSecretValueRedactor([...Eg.registeredValues.keys()]),Eg.registeredValueRedactor(e,t))}function createSecretValueRedactor(e){let t,n;return(r,i)=>{if(!r||e.length===0)return r;let a=!1;n??=new Set(e.map(e=>e.charAt(0)));for(let e of n)if(r.includes(e)){a=!0;break}if(!a)return r;if(!t){let n=groupPluginRecords(e.toSorted((e,t)=>t.length-e.length),e=>e.slice(0,Tg));t={prefixes:new RegExp([...n.keys()].map(escapeRegExp).join(`|`),`g`),buckets:n}}let{prefixes:s,buckets:c}=t,l=[];s.lastIndex=0;for(let e=s.exec(r);e;e=s.exec(r)){let t=e.index,n=c.get(e[0])?.find(e=>r.startsWith(e,t));n!==void 0&&l.push({index:t,value:n}),s.lastIndex=t+(n?.length??1)}let u=``,d=0;for(let e of l)u+=`${r.slice(d,e.index)}${i(e.value,e.index)}`,d=e.index+e.value.length;return u+r.slice(d)}}function resetSecretRedactionRegistryForTest(){Eg.registeredValues.clear(),invalidateMatcher()}var Tg,Eg,Dg=__esmMin((()=>{wg(),B(),Sp(),Tg=6,Eg=resolveGlobalSingleton(Symbol.for(`openclaw.secretRedactionRegistry`),()=>({revision:0,registeredValues:/* @__PURE__ */ new Map,registeredValueRedactor:void 0})),process.env.VITEST&&(globalThis[Symbol.for(`openclaw.secretRedactionRegistryTestApi`)]={resetSecretRedactionRegistryForTest})}));function classifyCode(e){return Og.has(e)?`hostname_mismatch`:kg.has(e)?`certificate_invalid`:null}function classifyMessage(e){return Ag.some(t=>t.test(e))?`hostname_mismatch`:jg.some(t=>t.test(e))?`certificate_invalid`:null}function inspectTlsCertificateErrorInternal(e,t,n){if(n>Mg)return null;if(typeof e==`string`){let t=classifyMessage(e);return t?{kind:t,message:e}:null}if(!e||typeof e!=`object`||t.has(e))return null;t.add(e);let r=e,i=typeof r.code==`string`?r.code.trim().toUpperCase():void 0,a=typeof r.message==`string`&&r.message.trim()?r.message:void 0,s=i?classifyCode(i):null;if(i&&s)return{kind:s,code:i,message:a??i};let c=Array.isArray(r.errors)?r.errors:[];for(let e of[r.cause,r.error,...c]){let r=inspectTlsCertificateErrorInternal(e,t,n+1);if(r)return r}let l=a?classifyMessage(a):null;return l&&a?{kind:l,message:a}:null}function inspectTlsCertificateError(e){return inspectTlsCertificateErrorInternal(e,/* @__PURE__ */ new Set,0)}var Og,kg,Ag,jg,Mg,Ng=__esmMin((()=>{Og=/* @__PURE__ */ new Set([`ERR_TLS_CERT_ALTNAME_INVALID`,`HOSTNAME_MISMATCH`]),kg=/* @__PURE__ */ new Set(/* @__PURE__ */ `CERT_CHAIN_TOO_LONG.CERT_HAS_EXPIRED.CERT_NOT_YET_VALID.CERT_REJECTED.CERT_REVOKED.CERT_SIGNATURE_FAILURE.CERT_UNTRUSTED.CRL_HAS_EXPIRED.CRL_NOT_YET_VALID.CRL_SIGNATURE_FAILURE.DEPTH_ZERO_SELF_SIGNED_CERT.ERROR_IN_CERT_NOT_AFTER_FIELD.ERROR_IN_CERT_NOT_BEFORE_FIELD.ERROR_IN_CRL_LAST_UPDATE_FIELD.ERROR_IN_CRL_NEXT_UPDATE_FIELD.INVALID_CA.INVALID_PURPOSE.PATH_LENGTH_EXCEEDED.SELF_SIGNED_CERT_IN_CHAIN.UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY.UNABLE_TO_DECRYPT_CERT_SIGNATURE.UNABLE_TO_DECRYPT_CRL_SIGNATURE.UNABLE_TO_GET_CRL.UNABLE_TO_GET_ISSUER_CERT.UNABLE_TO_GET_ISSUER_CERT_LOCALLY.UNABLE_TO_VERIFY_LEAF_SIGNATURE`.split(`.`)),Ag=[/hostname\/ip does not match certificate(?:'s)? altnames/i,/hostname mismatch/i,/host: .+ is not in the cert(?:ificate)?(?:'s)? altnames/i],jg=[/certificate has expired/i,/certificate is not yet valid/i,/self[- ]signed certificate/i,/unable to get local issuer certificate/i,/unable to verify the first certificate/i],Mg=8}));function isKnownTransportErrorCode(e){return Ig.some(({code:t})=>t.exec(e)?.[0]===e)||inspectTlsCertificateError({code:e})?.code===e}var Pg,Fg,Ig,Lg=__esmMin((()=>{Ng(),Pg=/(?:\s*:\s*|\s+)/,RegExp(`^(?:http\\s*)?(\\d{3})${Pg.source}(.+)$`,`i`),RegExp(`^(?:http\\s*)?(\\d{3})(?:${Pg.source}([\\s\\S]+))?$`,`i`),Fg="Couldn't connect to the AI service. Check your connection, then try again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`.",Ig=[{code:/\beconnrefused\b/i,phrases:/connection refused|actively refused/i,message:Fg},{code:/\beconnreset\b|\beconnaborted\b|\benetreset\b|\bepipe\b/i,phrases:/socket hang up|connection reset|connection aborted/i,message:"Lost the connection to the AI service. Check the conversation before trying again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`."},{code:/\benotfound\b|\beai_again\b|\benetunreach\b|\behostunreach\b|\behostdown\b/i,phrases:/getaddrinfo|no such host|\bdns\b|network is unreachable|host is unreachable|fetch failed|connection error|network request failed/i,message:Fg}]}));function shouldRedactStructuredAuthorizationCode(e,t,n){if(e!==`code`)return!1;let r=t.map(e=>e.toLowerCase());return r.length===1||r.at(-1)===`code`&&[`error`,`nodeerror`,`status`,`details`,`warnings`].includes(r.at(-2)??``)?!1:!(n!==void 0&&r.length>1&&r.slice(0,-1).every(e=>e===`cause`)&&isKnownTransportErrorCode(n))}var Rg=__esmMin((()=>{Lg()}));function parsePattern(e){if(e===jm)return Mm;if(typeof e!=`string`&&!(e instanceof RegExp))return typeof e==`object`&&e&&typeof e.exec==`function`?e:null;let t=typeof e==`string`?cg.get(e)??null:null,n=!0;if(e instanceof RegExp)t=e.flags.includes(`g`)?e:new RegExp(e.source,`${e.flags}g`);else if(!t&&e.trim()){let[r,i]=parseRedactPatternSource(e),a=Kg.has(e)?rewriteOpenEndedRepeats(r,i):r;t=compileConfigRegex(a,i)?.regex??null,n=t!==null&&t.source===a&&t.flags===i&&t.exec===RegExp.prototype.exec&&t[Symbol.replace]===RegExp.prototype[Symbol.replace]}if(t&&typeof e==`string`&&Bg.shellReferencePreserving.has(e)&&Vg.add(t),t&&typeof e==`string`&&Bg.formAware.has(e)&&qg.add(t),t&&typeof e==`string`&&(e.startsWith(ch)||Bg.chunkUnsafe.has(e))&&Gg.add(t),t&&typeof e==`string`){if(Kg.has(e)&&Hg.add(t),n&&Wg.has(e)&&!Ug.has(t)){let e=t.source,n=t.exec,r=t instanceof RegExp?t.flags:void 0,i=t instanceof RegExp?t[Symbol.replace]:void 0;Ug.set(t,()=>t.source===e&&t.exec===n&&(!(t instanceof RegExp)||t.flags===r&&t[Symbol.replace]===i))}let r=Bg.prefilters.get(e);n&&r&&setRedactPatternPrefilter(t,r)}return t}function resolvePatterns(e){if(usesBuiltInRedactPatterns(e))return Jg??=Fh.map(parsePattern).filter(e=>!!e),Jg;let t=/* @__PURE__ */ new Set,n=!Array.isArray(e);for(let r of Array.isArray(e)?e:[]){let e=parsePattern(r);e?t.add(e):n=!0}if(n){for(let e of resolvePatterns())t.add(e);if(!Yg){Yg=!0;try{console.warn(`[openclaw] Ignoring invalid logging.redactPatterns entries; keeping valid patterns and built-in redaction. Fix logging.redactPatterns in your config.`)}catch{}}}return t.add(ph),[...t]}function usesBuiltInRedactPatterns(e){return e===void 0||e===Fh||Array.isArray(e)&&e.length===0}function normalizeSensitiveKeyName(e){let t=e.replace(Zg,``);try{return decodeURIComponent(t).replace(Zg,``).toLowerCase().replaceAll(`-`,`_`)}catch{return t.toLowerCase().replaceAll(`-`,`_`)}}function isSensitiveBodyKey(e){return isSensitiveUrlQueryParamName(e)||Bg.bodySecretKeys.has(normalizeSensitiveKeyName(e))}function hasEncodedOrInvisibleFormKey(e){return Qg.test(e)||e.replace(Xg,``)!==e}function visitSensitiveAssignments(e,t,n){if(!e||t===`url`&&!e.includes(`?`)||t===`encoded`&&!e.includes(`%`)&&e.replace(Xg,``)===e||t===`context`&&!/[=:]/u.test(e))return;let visitPair=(e,r,i)=>{if(t===`encoded`&&!hasEncodedOrInvisibleFormKey(e)||!isSensitiveBodyKey(e))return;let{maskable:a,maskStart:s,maskEnd:c}=splitSecretValueForMask(r);n(i+s,i+c,a)};if(t===`form`){let t=0;for(let n of e.split(`&`)){let e=n.indexOf(`=`);e>=0&&visitPair(n.slice(0,e),n.slice(e+1),t+e+1),t+=n.length+1}return}let r=t===`url`?s_:t===`encoded`?a_:o_,i=t===`context`?3:2;r.lastIndex=0;try{for(let t=r.exec(e);t;t=r.exec(e)){let e=t[1]??``,n=t[i]??``;visitPair(n,t[i+1]??``,t.index+e.length+n.length+1)}}finally{r.lastIndex=0}}function redactAssignmentValues(e,t,n){let r=[],i=[],a=0;return visitSensitiveAssignments(e,t,(s,c,l)=>{let u=t===`url`?maskToken(l):`***`;r.push(e.slice(a,s),u),n&&i.push({start:s,end:c,replacement:u}),a=c}),i.length>0&&n?.(i),r.length>0?r.join(``)+e.slice(a):e}function redactFormBodyLine(e,t){if(!e.includes(`=`))return e;let n=redactAssignmentValues(redactAssignmentValues(e,`encoded`,t),`context`,t);if(!n.includes(`&`))return n;if(r_.test(n))return redactAssignmentValues(n,`form`,t);let r=[],i=n.replace(i_,(e,n,i,a)=>{let s=redactAssignmentValues(i,`form`,t?e=>{for(let t of e)r.push({...t,start:a+n.length+t.start,end:a+n.length+t.end})}:void 0);return s===i?e:`${n}${s}`});return r.length>0&&t?.(r),redactAssignmentValues(redactAssignmentValues(i,`encoded`,t),`context`,t)}function redactFormBody(e,t){if(!e.includes(`=`))return e;if(c_.test(e)){let n=0;return e.split(c_).map(e=>{let r=l_.test(e)?e:redactFormBodyLine(e,t?e=>t(e.map(e=>({...e,start:n+e.start,end:n+e.end}))):void 0);return n+=r.length,r}).join(``)}return redactFormBodyLine(e,t)}function isShellReferenceToKey(e,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(e))return!1;let n=t.match(/^\$([A-Z_][A-Z0-9_]*)$/);return n?n[1]===e:t.match(/^\$\{([A-Z_][A-Z0-9_]*)(?::[-=?+])?\}$/)?.[1]===e}function maskSecretFieldValue(e,t){let n=t.match(/^\$\{([A-Z_][A-Z0-9_]*):[-=?+][^{}]+\}(?![\s\S])/);return n&&n[1]===e?`${t.slice(0,t.indexOf(`:`)+2)}***}`:`***`}function shouldPreserveShellReferenceMatch(e,t){let n=e.match(/\b([A-Z_][A-Z0-9_]*)\b\s*[=:]/)?.[1];return n?isShellReferenceToKey(n,t):!1}function isEmptyShellParameterExpansionTail(e){return/^[-=?+]\}$/.test(e)}function prepareRedactionCapture({match:e,groups:t,input:n,offset:r,replacement:i},a){if(e.includes(`PRIVATE KEY-----`))return{start:r,end:r+e.length,value:e,redact:e=>({start:e.start,end:e.end,value:e.value,replacement:i??redactPemBlock(e.value,`…redacted…`)})};let s=selectSecretCapture(e,t);if(s.value===`***`)return;let c=s.value===e?0:getSecretCaptureStart(a,n,e,r,s);if(c<0)return;let l=r+c;return{start:l,end:l+s.value.length,value:s.value,redact:t=>{let n=t.value,r=qg.has(a)?splitFormAwareCredentialValue(n):{secret:n,suffix:``};if(splitSecretValueForMask(r.secret).maskable===`***`)return;let s=Vg.has(a);if(s&&(shouldPreserveShellReferenceMatch(e,n)||isEmptyShellParameterExpansionTail(n)))return;let c=i??(s?maskToken(n):`${maskSecretValue(r.secret)}${r.suffix}`);return{start:t.start,end:t.end,replacement:c}}}}function redactMatch(e,t){let n=prepareRedactionCapture(e,t),r=n?.redact(n);return r?e.match.slice(0,r.start-e.offset)+r.replacement+e.match.slice(r.end-e.offset):e.match}function redactText(e,t,n){let r=startRedactionMeasurement(`text`),i=`error`;try{let r=redactFormBody(redactAssignmentValues(redactStructuredAuthHeaders(e,`***`),`url`)),a,replace=e=>redactMatch(e,a),replaceRegex=(...e)=>replace(readRedactMatch(e)),s,c=!1;for(a of t)Ug.get(a)?.()&&(s!==r&&(s=r,c=couldMatchVendorRedactPatterns(r)),!c)?a instanceof RegExp&&(a.lastIndex=0):r=a instanceof RegExp&&!n?.fullContext&&!Hg.has(a)&&!Gg.has(a)?replacePatternBounded(r,a,replaceRegex):replaceRedactPattern(r,a,replace,replaceRegex);return i=`ok`,r}finally{r?.(i,e.length,t.length)}}function looksLikeAppSpecificPassword(e){return e.split(`-`).every(e=>!m_.has(e.toLowerCase()))}function redactAppSpecificPasswords(e){return e.includes(`-`)?e.replace(p_,(e,t)=>looksLikeAppSpecificPassword(t)?maskToken(t):e):e}function resolveConfigRedaction(){let e=readLoggingConfig();return{mode:zg,patterns:e?.redactPatterns}}function resolveRedactOptions(e){let t=e??resolveConfigRedaction(),n=t.mode===`off`?`off`:zg;return{mode:n,patterns:n===`off`?[]:resolvePatterns(t.patterns)}}function redactSensitiveText(e,t){return e&&redactSensitiveTextWithOptions(redactRegisteredSecretValues(e,maskToken),t??resolveConfigRedaction())}function redactSensitiveTextWithOptions(e,t){return t.mode===`off`||usesBuiltInRedactPatterns(t.patterns)&&!couldMatchDefaultRedactPatterns(e)?e:redactText(e,resolveRedactOptions(t).patterns)}function resolveToolPayloadRedaction(e=readLoggingConfig()){let t=e?.redactPatterns;return{mode:`tools`,patterns:Array.isArray(t)&&t.length>0?[...t,...Fh]:t}}function redactToolPayloadText(e){return redactToolPayloadTextWithConfig(e,readLoggingConfig())}function redactToolPayloadTextWithConfig(e,t){return redactSensitiveText(e,resolveToolPayloadRedaction(t))}function isSensitiveFieldKey(e){return u_.test(e)||h_.test(e)}function isPublicShareIdPath(e){return e.at(-1)?.toLowerCase()===`id`&&e.at(-2)?.toLowerCase().replaceAll(`-`,``).replaceAll(`_`,``)===`publicshare`}function redactSensitiveFieldValueWithOptions(e,t,n,r=[e],i=!0,a=couldMatchDefaultRedactPatterns){let s=redactRegisteredSecretValues(t,maskToken);if(isPublicShareIdPath(r))return maskToken(s);let c=resolveRedactOptions(n);if(c.mode===`off`)return s;let l=!usesBuiltInRedactPatterns(n.patterns)||a(s)?redactText(s,c.patterns):s;if(l!==t||f_.test(e)){let e=redactAppSpecificPasswords(l);if(e!==t)return e}return l===t?shouldRedactStructuredStringField(e,s,r,i)?maskToken(s):s:l}function shouldRedactStructuredPrimitiveField(e,t){let n=e.toLowerCase();return isPublicShareIdPath(t)||shouldRedactStructuredAuthorizationCode(n,t)||isSensitiveFieldKey(e)}function isPlainRedactableObject(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function redactStructuredSecretValue(e,t,n,r,i,a=e?[e]:[],s=!0){if(typeof t==`string`)return redactSensitiveFieldValueWithOptions(e,t,r,a,s,i);if(t==null)return t;if(typeof t==`number`||typeof t==`boolean`||typeof t==`bigint`)return shouldRedactStructuredPrimitiveField(e,a)?`***`:t;if(Array.isArray(t)){if(n.has(t))return`[Circular]`;n.add(t);let s=t.map(t=>redactStructuredSecretValue(e,t,n,r,i,a,!1));return n.delete(t),s}if(typeof t==`object`){if(n.has(t))return`[Circular]`;if(!isPlainRedactableObject(t))return t;n.add(t);let e=Object.entries(t);for(let t of e){let[e,c]=t;t[1]=redactStructuredSecretValue(e,c,n,r,i,[...a,e],s)}return n.delete(t),Object.fromEntries(e)}return t}function redactSecretsWithOptions(e,t){return typeof e==`string`?redactSensitiveText(e,t):typeof e!=`object`||!e?e:redactStructuredSecretValue(``,e,/* @__PURE__ */ new WeakSet,t,createRedactPrefilter(couldMatchDefaultRedactPatterns))}function redactSecrets(e){return redactSecretsWithOptions(e,resolveToolPayloadRedaction())}function preservesStructuredReference(e,t){return e.toLowerCase()===`session`&&d_.test(t)||isShellReferenceToKey(e,t)}function shouldRedactStructuredStringField(e,t,n,r){return shouldRedactStructuredAuthorizationCode(e.toLowerCase(),n,r?t:void 0)||isSensitiveFieldKey(e)&&!preservesStructuredReference(e,t)}function classifyLogFieldProtection(e,t,n,r){return(r===void 0?shouldRedactStructuredPrimitiveField(e,t):isPublicShareIdPath(t)||shouldRedactStructuredStringField(e,r,t,n))?`legacy`:Bg.credentialHeaderField.test(e)?`header`:void 0}function getFieldRecordEdits(e,t){let{key:n,value:r,path:i,objectPath:a}=e;return t===`off`||!e.string&&r===`null`||!classifyLogFieldProtection(n,i,a,e.string?r:void 0)?[]:[{start:0,end:r.length,replacement:maskSecretFieldValue(n,r)}]}function getTextRecordEdits(e,t,n){let{value:r}=e;if(e.isKey||n&&!e.origin.structured)return[];if(n&&e.origin.primitiveMask)return[{start:0,end:r.length,replacement:`***`}];if(!e.string)return[];let i=[],a=redactRegisteredSecretValues(r,(e,t)=>{let n=maskToken(e);return i.push({start:t,end:t+e.length,replacement:n}),n});if(n&&isPublicShareIdPath(e.path))return[{start:0,end:r.length,replacement:maskToken(a)}];if(t===`off`)return i;let s=i,receive=e=>{s=composeRedactionEdits(r.length,s,e)},c=findStructuredAuthParamRanges(a).map(({start:e,end:t})=>({start:e,end:t,replacement:`***`}));return receive(c),redactFormBody(redactAssignmentValues(applyRedactionEdits(a,c),`url`,receive),receive),s}function getLegacyFieldRecordEdits(e,t){let{key:n,value:r,path:i,objectPath:a}=e;if(e.isKey||!e.origin.structured||!e.string||isPublicShareIdPath(i))return[];let s=[];if(t!==r||f_.test(n))for(let e of t.matchAll(p_))looksLikeAppSpecificPassword(e[0])&&s.push({start:e.index,end:e.index+e[0].length,replacement:maskToken(e[0])});return s.length>0||t!==r?s:classifyLogFieldProtection(n,i,a,t)===`legacy`?[{start:0,end:t.length,replacement:maskToken(t)}]:[]}function*redactionEditMatches(e,t){for(let n of t)yield{match:e.slice(n.start,n.end),groups:[],input:e,offset:n.start,replacement:n.replacement}}function redactLogRecordForTransport(e,t){let n=startRedactionMeasurement(`log-record`),r=`error`,i;try{let n=t?.redaction??resolveRedactOptions(),a={value:{structured:!0,primitiveMask:!1},children:/* @__PURE__ */ new Map},s=[],c=JSON.stringify(e,function(e,t){for(;s.length>0&&s.at(-1)?.value!==this;)s.pop();let n=s.at(-1),r=Array.isArray(this),i=r&&n?n.key:e,c=r&&n?n.path:n?[...n.path,e]:[],l=t,u=(n?.structured??!0)&&(typeof l!=`object`||!l||Array.isArray(l)||isPlainRedactableObject(l)),d=u&&[`number`,`boolean`,`bigint`].includes(typeof l)&&classifyLogFieldProtection(i,c,!r,void 0)===`legacy`,f=typeof t==`object`&&!!t&&s.some(e=>e.value===t),p=f?`[Circular]`:typeof t==`bigint`?String(t):t,m=typeof p==`object`&&!!p,h=a;return n&&n.structured&&(m||!u||d||f)?(h={value:{structured:u&&!f,primitiveMask:d},children:/* @__PURE__ */ new Map},n.origins.children.set(e,h)):n?h=n.origins:a.value={structured:u,primitiveMask:d},m&&s.push({value:p,path:c,key:i,origins:h,structured:u}),p});i=c.length;let l=createRedactPrefilter(couldMatchDefaultFullContextPatterns),u=JSON.parse(redactJsonRecord(c,a,[[{patterns:n.patterns}],[{patterns:g_},{patterns:n.patterns,...n.patterns===Jg?{couldMatch:l}:{}}]],prepareRedactionCapture,t?getLegacyFieldRecordEdits:()=>[],e=>getFieldRecordEdits(e,n.mode),e=>getTextRecordEdits(e,n.mode,t!==void 0),(e,t)=>e.path.length===1&&__.has(e.key)||n.patterns===Jg&&!l(t),t?.message));return r=`ok`,u}finally{n?.(r,i)}}var zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg,$g,e_,t_,n_,r_,i_,a_,o_,s_,c_,l_,u_,d_,f_,p_,m_,h_,g_,__,v_=__esmMin((()=>{Xp(),cm(),pm(),Gp(),vm(),ym(),Am(),lg(),hg(),km(),Ih(),Nm(),_g(),Cg(),Dg(),Rg(),zg=`tools`,Bg=createBackendRedactPatterns(),Vg=/* @__PURE__ */ new WeakSet,Hg=/* @__PURE__ */ new WeakSet,Ug=/* @__PURE__ */ new WeakMap,Wg=new Set(Ph),Gg=/* @__PURE__ */ new WeakSet,Kg=new Set(Fh.filter(e=>typeof e==`string`)),qg=/* @__PURE__ */ new WeakSet,Yg=!1,Xg=new RegExp(String.raw`[${Km}+]`,`gu`),Zg=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,Qg=/%[0-9A-Fa-f]{2}/u,$g=String.raw`[${Km}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${Km}+])*`,e_=`[^&\\s<>]*`,t_=`[^&#\\s<>]*`,n_=String.raw`${$g}=${e_}`,r_=new RegExp(String.raw`^${n_}(?:&${n_})+$`,`u`),i_=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`])(${n_}(?:&${n_})+)`,`gu`),a_=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`&])(${$g})=(${e_})`,`gu`),o_=new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${$g})=(${e_})(["'\x60]?)`,`giu`),s_=new RegExp(String.raw`([?&])(${$g})=(${t_})`,`gu`),c_=/(\r\n|\r|\n)/u,l_=/^(?:\r\n|\r|\n)$/u,u_=new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${Lm}|credential|authorization|private[-_]?key|privateKey|access[-_]?token|accessToken|refresh[-_]?token|refreshToken|id[-_]?token|idToken|auth[-_]?token|authToken|client[-_]?secret|clientSecret|app[-_]?secret|appSecret|secret[-_]?value|secretValue|raw[-_]?secret|rawSecret|secret[-_]?input|secretInput|key|key[-_]?material|keyMaterial|jwt|session|signature|cookie|set[-_]?cookie|${Fm}|${Im})$`,`i`),d_=/^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u,f_=/^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i,p_=/\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g,m_=/* @__PURE__ */ new Set([`case`,`claw`,`demo`,`file`,`main`,`name`,`open`,`path`,`slug`,`test`]),h_=new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Pm})$`,`i`),g_=[{source:`registered secret values`,*exec(e){let t=[];redactRegisteredSecretValues(e,(n,r)=>(t.push({match:n,groups:[],input:e,offset:r,replacement:maskToken(n)}),n)),yield*t}},{source:`structured authorization parameters`,*exec(e){for(let{start:t,end:n}of findStructuredAuthParamRanges(e))yield{match:e.slice(t,n),groups:[],input:e,offset:t,replacement:`***`}}},{source:`URL query assignments`,*exec(e){let t=[];redactAssignmentValues(e,`url`,e=>t.push(...e)),yield*redactionEditMatches(e,t)}},{source:`form bodies`,*exec(e){let t=[];redactFormBody(e,n=>{t=composeRedactionEdits(e.length,t,n)}),yield*redactionEditMatches(e,t)}}],__=/* @__PURE__ */ new Set([`time`,`level`])}));function isValidTimeZone(e){let t=y_.get(e);if(t!==void 0)return t;let n;try{new Intl.DateTimeFormat(`en`,{timeZone:e}).format(),n=!0}catch{n=!1}return y_.set(e,n),n}function resolveEffectiveTimeZone(e){let t=e??process.env.TZ;return t&&isValidTimeZone(t)?t:x_??=Intl.DateTimeFormat().resolvedOptions().timeZone}function getTimestampParts(e,t){let n=resolveEffectiveTimeZone(t),r=Math.floor(e.getTime()/1e3);if(S_?.second===r&&S_.timeZone===n)return S_.parts;let i=b_.get(n);i||(i=new Intl.DateTimeFormat(`en`,{timeZone:n,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1,fractionalSecondDigits:3,timeZoneName:`longOffset`}),b_.set(n,i));let a={};for(let t of i.formatToParts(e))a[t.type]=t.value;return S_={second:r,timeZone:n,parts:a},a}function formatTimestamp(e,t){let n=t?.style??`medium`,r=getTimestampParts(e,t?.timeZone),i=r.timeZoneName??`GMT`,a=i===`GMT`?`+00:00`:i.slice(3),s=String(e.getUTCMilliseconds()).padStart(3,`0`);switch(n){case`short`:return`${r.hour}:${r.minute}:${r.second}${a}`;case`medium`:return`${r.hour}:${r.minute}:${r.second}.${s}${a}`;case`long`:return`${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}.${s}${a}`}throw Error(`Unsupported timestamp style`)}var y_,b_,x_,S_,C_=__esmMin((()=>{y_=/* @__PURE__ */ new Map,b_=/* @__PURE__ */ new Map}));function formatJsonConsoleLine(e){let t={...e.meta,time:formatTimestamp(/* @__PURE__ */ new Date,{style:`long`}),level:e.level,...e.subsystem?{subsystem:e.subsystem}:{},message:e.message};return JSON.stringify(redactLogRecordForTransport(t))}function formatConsoleDiagnosticLine(e){return(kf.overrideSettings?.consoleStyle??readLoggingConfig()?.consoleStyle)===`json`?formatJsonConsoleLine(e):e.message}var w_=__esmMin((()=>{Gp(),v_(),Af(),C_()}));function tryParseLogLevel(e){if(typeof e!=`string`)return;let t=e.trim();return T_.includes(t)?t:void 0}function normalizeLogLevel(e,t=`info`){return tryParseLogLevel(e)??t}function levelToMinLevel(e){return E_[e]}function isLogLevelEnabled(e,t){return e!==`silent`&&t!==`silent`&&levelToMinLevel(e)>=levelToMinLevel(t)}var T_,E_,D_=__esmMin((()=>{T_=[`silent`,`fatal`,`error`,`warn`,`info`,`debug`,`trace`],E_={trace:1,debug:2,info:3,warn:4,error:5,fatal:6,silent:1/0}}));function resolveEnvLogLevelOverride(){let e=normalizeOptionalString(process.env.OPENCLAW_LOG_LEVEL)??``;if(!e){kf.invalidEnvLogLevelValue=null;return}let t=tryParseLogLevel(e);if(t)return kf.invalidEnvLogLevelValue=null,t;if(kf.invalidEnvLogLevelValue!==e){kf.invalidEnvLogLevelValue=e;let t=`[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${redactToolPayloadText(e)}" (allowed: ${T_.join(`|`)}).`;process.stderr.write(`${formatConsoleDiagnosticLine({level:`warn`,message:t})}\n`)}}var O_=__esmMin((()=>{Lt(),w_(),D_(),v_(),Af()}));function loadResolveSecureTempRoot(){if(A_)return A_;let e=getSealedRuntimeSecureTempRoot();if(e)return A_=e,e;if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`sealed temp-root runtime was not registered before use`);if(typeof process.getBuiltinModule!=`function`)throw Error(`Node module loading is unavailable for secure temp-root resolution`);return A_=process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@openclaw/fs-safe/secure-temp-root`).resolveSecureTempRoot,A_}function assertSafeTempAncestors(e,t){let n=t.platform??process.platform;if(n===`win32`||n===`android`)return;let r=process.getBuiltinModule(`fs`),i=t.lstatSync??r.lstatSync,a=t.lstatSync?S.resolve(e):r.realpathSync.native(e);for(let e=S.dirname(a);;e=S.dirname(e)){let t=i(e);if(t.mode!==void 0&&t.mode&18&&!(t.mode&512)){let t=`'${e.replaceAll(`'`,`'\\''`)}'`;throw Error(`Temp workspace ancestor ${JSON.stringify(e)} is group/world writable without sticky protection; have its owner run chmod +t ${t} for a shared temp directory or chmod go-w ${t} for a private ancestor.`)}if(S.dirname(e)===e)return}}function resolvePreferredOpenClawTmpDir(e={}){let t=loadResolveSecureTempRoot(),n={...e,preferredDir:e.preferredDir??`/tmp/openclaw`,fallbackPrefix:`openclaw`,warningPrefix:`[openclaw]`,unsafeFallbackLabel:`OpenClaw temp dir`,skipPreferredOnWindows:!0},r=t(n);if(e.purpose===`coordination`)return r;let i;try{return assertSafeTempAncestors(r,e),r}catch(e){i=e}let a=resolveStateDir();try{let r=t({...n,preferredDir:void 0,tmpdir:()=>S.join(a,`tmp`)});return assertSafeTempAncestors(r,e),(e.warn??console.warn)(`[openclaw] ${String(i)} Using private state temp dir: ${r}`),r}catch(e){throw Error(`No safe OpenClaw temp root is available. Default root: ${String(i)} State fallback ${JSON.stringify(a)}: ${String(e)}`,{cause:e})}}var k_,A_,j_=__esmMin((()=>{vp(),Kf(),k_=`/tmp/openclaw`}));function readParsedField(e,t,n){for(let r of typeof t==`string`?[t]:t){let t=n(e[r]);if(t!==void 0)return t}}var M_=__esmMin((()=>{}));function ensureLogDirectorySync(e,t=!0,n=511){try{r.mkdirSync(e,{mode:n})}catch(i){let a=extractErrorCode(i);if(a===`EEXIST`&&r.statSync(e).isDirectory())return;let s=S.dirname(e);if(!t||a!==`ENOENT`||s===e)throw i;ensureLogDirectorySync(s,!0,n),ensureLogDirectorySync(e,!1,n)}}var N_=__esmMin((()=>{O()}));function canUseNodeFs(){try{return process.getBuiltinModule?.(`fs`)!==void 0}catch{return!1}}function formatLocalDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}var P_,F_,I_=__esmMin((()=>{P_=`openclaw`,F_=`.log`}));function encodeLogProfileSegment(e){let t=``;for(let n of e)/^[a-z0-9]$/u.test(n)?t+=n:n===`-`?t+=`--`:n===`_`?t+=`-0`:/^[A-Z]$/u.test(n)?t+=`-1${n.toLowerCase()}`:t+=`-2${n.codePointAt(0)?.toString(16)??`0`}-`;return t}function resolveLogProfileSegment(){let e=process.env.OPENCLAW_PROFILE?.trim();if(!e||e.toLowerCase()==="default")return null;let t=encodeLogProfileSegment(e);return t.length<=R_?t:`-3${ye(`sha256`).update(e).digest(`hex`)}`}function resolveDefaultRollingLogFile(e){let t=/* @__PURE__ */ new Date,n=k_;if(canUseNodeFs()){let t=resolveStateDir();n=S.join(t,`logs`),e?.prepare!==!1&&(ensureLogDirectorySync(t,!0,448),n=resolvePreferredOpenClawTmpDir({preferredDir:n,tmpdir:()=>S.join(t,`tmp`)}))}let r=resolveLogProfileSegment(),i=r?`-${r}`:``;return S.join(n,`${P_}${i}-${formatLocalDate(t)}${F_}`)}function isLegacyRollingLogFilePath(e){let t=S.basename(e);return t===`openclaw-YYYY-MM-DD.log`||L_.exec(t)?.[1]===`openclaw`}function resolveRollingLogFilePathForDate(e,t){let n=L_.exec(S.basename(e));return n?S.join(S.dirname(e),`${n[1]}-${formatLocalDate(t)}${F_}`):isLegacyRollingLogFilePath(e)?S.join(S.dirname(e),`${P_}-${formatLocalDate(t)}${F_}`):e}var L_,R_,z_=__esmMin((()=>{vp(),j_(),N_(),I_(),L_=/^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u,R_=220}));function rotatedLogPath(e,t){let n=S.extname(e);return`${e.slice(0,e.length-n.length)}.${t}${n}`}function rotateLogFile(e){try{ensureLogDirectorySync(S.dirname(e)),r.rmSync(rotatedLogPath(e,H_),{force:!0});for(let t=4;t>=1;--t){let n=rotatedLogPath(e,t);r.existsSync(n)&&r.renameSync(n,rotatedLogPath(e,t+1))}return r.existsSync(e)&&r.renameSync(e,rotatedLogPath(e,1)),!0}catch{return!1}}async function getCurrentLogFileBytes(e){try{return(await T.stat(e)).size}catch{return 0}}function getCurrentLogFileBytesSync(e){try{return r.statSync(e).size}catch{return 0}}function buildDroppedMarker(e,t){let n=/* @__PURE__ */ new Date,r=`[openclaw] file log queue overflow; dropped ${t} oldest record${t===1?``:`s`}`,i={0:r,_meta:{date:n,hostname:e.hostname,logLevelName:`WARN`,name:`openclaw`},time:formatTimestamp(n,{style:`long`}),hostname:e.hostname,message:r,dropped:t};return{...e,payload:`${JSON.stringify(i)}\n`}}function writeFileTransportWarning(e,t){try{let n=`${formatConsoleDiagnosticLine({level:`warn`,message:redactSensitiveText(e)})}\n`;return t?r.writeSync(process.stderr.fd,n):process.stderr.write(n),!0}catch{return!1}}function warnAboutRotationFailure(e,t){ev.get(e.file)!==e.maxFileBytes&&(ev.set(e.file,e.maxFileBytes),writeFileTransportWarning(`[openclaw] log file rotation failed; continuing writes file=${e.file} maxFileBytes=${e.maxFileBytes}`,t))}function warnAboutAppendFailure(e,t){if(tv.has(e.file))return;let n=tv.size>=U_;n&&nv||writeFileTransportWarning(n?`[openclaw] log file append failure diagnostics saturated; suppressing new file targets`:`[openclaw] log file append failed; records dropped; check that the path is a writable regular file; file=${e.file}`,t)&&(n?nv=!0:tv.add(e.file))}function clearAppendFailure(e){tv.delete(e.file)&&(nv=!1)}function claimQueuedEntries(){let e=G_===0?W_:[...W_.slice(G_),...W_.slice(0,G_)];return W_=[],G_=0,J_>0&&Y_&&e.unshift(buildDroppedMarker(Y_,J_)),J_=0,Y_=null,e}function prepareWrite(e,t,n,r,i){let a=Buffer.byteLength(e.payload,`utf8`);t.bytes>0&&t.bytes+a>e.maxFileBytes&&(rotateLogFile(e.file)?(t.bytes=0,ev.delete(e.file)):warnAboutRotationFailure(e,n));let s=i+1;if(n)return{payload:e.payload,payloadBytes:a,nextIndex:s};let c=[e.payload];for(;s<r.length;s+=1){let n=r[s];if(!n||n.file!==e.file||n.maxFileBytes!==e.maxFileBytes)break;let i=Buffer.byteLength(n.payload,`utf8`);if(a+i>V_||t.bytes+a+i>e.maxFileBytes)break;c.push(n.payload),a+=i}return{payload:c.join(``),payloadBytes:a,nextIndex:s}}async function writeEntries(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){if(Q_)return;let r=e[n];if(!r)return;let i=t.get(r.file);if(!i){if(i={bytes:await getCurrentLogFileBytes(r.file)},Q_)return;t.set(r.file,i)}let a=prepareWrite(r,i,!1,e,n);q_=a.nextIndex;try{await Te({filePath:r.file,content:a.payload}),i.bytes+=a.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!1)}finally{for(let t of e.slice(n,a.nextIndex))t.payload=``;n=a.nextIndex}}}function writeEntriesSync(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){let r=e[n];if(!r)return;let i=t.get(r.file);i||(i={bytes:getCurrentLogFileBytesSync(r.file)},t.set(r.file,i));let a=prepareWrite(r,i,!0,e,n);try{Ee({filePath:r.file,content:a.payload}),i.bytes+=a.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!0)}r.payload=``,n=a.nextIndex}}async function runFlushLoop(){for(;;){if(Q_)return;let e=claimQueuedEntries();if(e.length===0)return;K_=e,q_=0,await writeEntries(e),K_=null,q_=0}}function startFlush(){if(Z_||Q_)return;let e=runFlushLoop().catch(()=>void 0);Z_=e,e.then(()=>{Z_=null,(W_.length>0||J_>0)&&scheduleFlush()})}function scheduleFlush(){X_||Z_||Q_||(X_=setImmediate(()=>{X_=null,startFlush()}))}function handleProcessBeforeExit(){flushFileLogQueue()}function handleProcessExit(){Q_=!0,drainFileLogQueueSync()}function installProcessHooks(){$_||($_=!0,process.on(`beforeExit`,handleProcessBeforeExit),process.on(`exit`,handleProcessExit))}function enqueueFileLog(e){if(Q_)writeEntriesSync([e]);else{if(installProcessHooks(),W_.length>=B_){let t=W_[G_];t&&(t.payload=``,Y_??=t,J_+=1),W_[G_]=e,G_=(G_+1)%W_.length}else W_.push(e);scheduleFlush()}}async function flushFileLogQueue(){for(;;){X_&&=(clearImmediate(X_),null),!Z_&&(W_.length>0||J_>0)&&startFlush();let e=Z_;if(!e)return;await e}}function drainFileLogQueueSync(){X_&&=(clearImmediate(X_),null);let e=K_?K_.slice(q_):[];K_=null,q_=0,e.push(...claimQueuedEntries()),writeEntriesSync(e)}var B_,V_,H_,U_,W_,G_,K_,q_,J_,Y_,X_,Z_,Q_,$_,ev,tv,nv,rv,iv=__esmMin((()=>{B(),w_(),N_(),v_(),C_(),B_=4096,V_=65536,H_=5,U_=64,W_=[],G_=0,K_=null,q_=0,J_=0,Y_=null,X_=null,Z_=null,Q_=!1,$_=!1,ev=/* @__PURE__ */ new Map,tv=/* @__PURE__ */ new Set,nv=!1,rv=resolveGlobalSingleton(Symbol.for(`openclaw.fileLogTransport`),()=>(process.env.VITEST!==`true`&&installProcessHooks(),{drainSync:drainFileLogQueueSync,enqueue:enqueueFileLog,flush:flushFileLogQueue}))}));function clampLogText(e,t){return e.length>t?`${truncateUtf16Safe(e,t)}...(truncated)`:e}function sanitizeDiagnosticLogText(e,t){return clampLogText(redactSensitiveText(clampLogText(e,t)),t)}function normalizeDiagnosticLogName(e){if(!e||e.trim().startsWith(`{`))return;let t=sanitizeDiagnosticLogText(e.trim(),pv);return hv.test(t)?t:void 0}function assignDiagnosticLogAttribute(e,t,n,r){if(t.count>=dv)return;let i=n.trim();if(isBlockedObjectKey(i)||redactSensitiveText(i)!==i||!hv.test(i))return;let a;if(typeof r==`string`)a=sanitizeDiagnosticLogText(r,fv);else if(typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r))a=r;else return;e[i]=a,t.count+=1}function addDiagnosticLogAttributesFrom(e,t,n){if(n)for(let r in n){if(t.count>=dv)break;Object.hasOwn(n,r)&&r!==`trace`&&assignDiagnosticLogAttribute(e,t,r,n[r])}}function isPlainLogRecordObject(e){if(!isRecord(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function normalizeTraceContext(e){let t=asOptionalRecord(e);if(t&&isValidDiagnosticTraceId(t.traceId)&&(t.spanId===void 0||isValidDiagnosticSpanId(t.spanId))&&(t.parentSpanId===void 0||isValidDiagnosticSpanId(t.parentSpanId))&&(t.traceFlags===void 0||isValidDiagnosticTraceFlags(t.traceFlags)))return{traceId:t.traceId,...t.spanId?{spanId:t.spanId}:{},...t.parentSpanId?{parentSpanId:t.parentSpanId}:{},...t.traceFlags?{traceFlags:t.traceFlags}:{}}}function extractTraceContext(e){return normalizeTraceContext(e)??normalizeTraceContext(asOptionalRecord(e)?.trace)}function getSortedNumericLogEntries(e){return Object.entries(e).filter(([e])=>/^\d+$/.test(e)).toSorted((e,t)=>Number(e[0])-Number(t[0]))}function normalizeFileLogContextValue(e){if(typeof e==`string`){let t=e.trim();return t?clampLogText(t,mv):void 0}if(typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function readFirstContextString(e,t){for(let n of e){let e=n?readParsedField(n,t,normalizeFileLogContextValue):void 0;if(e)return e}}function resolveLogHostname(){if(cv)return cv;let e=Xe.hostname().trim();return e?(cv=e,e):`unknown`}function withResolvedLogMetaHostname(e,t){return isRecord(e)?{...e,hostname:t}:e}function extractLogBindingPrefix(e){if(typeof e[0]==`string`&&e[0].length<=lv&&e[0].trim().startsWith(`{`))try{let t=JSON.parse(e[0]);if(isRecord(t))return{bindings:t,args:e.slice(1)}}catch{}return{args:e}}function resolveLogTraceContext(e,t){for(let n of[e,...t]){let e=extractTraceContext(n);if(e)return{trace:e,trustedTraceContext:!1}}let n=getActiveDiagnosticTraceContext();return n?{trace:n,trustedTraceContext:!0}:{trustedTraceContext:!1}}function prepareFileLogRecord(e){let t=getSortedNumericLogEntries(e),{bindings:n,args:r}=extractLogBindingPrefix(t.map(([,e])=>e)),{trace:i}=resolveLogTraceContext(n,r),a=isPlainLogRecordObject(r[0])?r[0]:void 0,s=[a,n,e],c=a&&typeof a.message!=`string`?1:0,l=t.slice(t.length-r.length+c).map(([e,t])=>{let n={key:e,json:t!=null&&![`string`,`number`,`boolean`,`bigint`].includes(typeof t)&&!(t instanceof Error)&&!(isPlainLogRecordObject(t)&&typeof t.message==`string`)};return typeof t==`number`&&!Number.isFinite(t)&&(n.primitiveText=String(t)),n}),u=readFirstContextString(s,[`agent_id`,`agentId`]),d=readFirstContextString(s,[`session_id`,`sessionId`,`sessionKey`]),f=readFirstContextString(s,[`channel`,`messageProvider`]);return{fields:{hostname:resolveLogHostname(),...u?{agent_id:u}:{},...d?{session_id:d}:{},...f?{channel:f}:{},...i},messageParts:l}}function buildDiagnosticLogRecord(e){let t=e._meta,{bindings:n,args:r}=extractLogBindingPrefix(getSortedNumericLogEntries(e).map(([,e])=>e)),{trace:i,trustedTraceContext:a}=resolveLogTraceContext(n,r),s=r[0],c=isPlainLogRecordObject(s)?s:void 0;c&&r.shift();let l=``;r.length>0&&typeof r[r.length-1]==`string`?l=sanitizeDiagnosticLogText(String(r.pop()),uv):r.length===1&&(typeof r[0]==`number`||typeof r[0]==`boolean`)&&(l=String(r[0]),r.length=0),l||=`log`;let u=Object.create(null),d={count:0};addDiagnosticLogAttributesFrom(u,d,n),addDiagnosticLogAttributesFrom(u,d,c);let f={};if(t?.path?.fileLine){let e=Number(t.path.fileLine);Number.isFinite(e)&&(f.line=e)}t?.path?.method&&(f.functionName=sanitizeDiagnosticLogText(t.path.method,pv));let p=normalizeDiagnosticLogName(t?.name),m=t?.parentNames?.map(normalizeDiagnosticLogName).filter(e=>!!e);return{event:{type:`log.record`,level:t?.logLevelName??`INFO`,message:l,...p?{loggerName:p}:{},...m?.length?{loggerParents:m}:{},...Object.keys(u).length>0?{attributes:u}:{},...Object.keys(f).length>0?{code:f}:{},...i?{trace:i}:{}},trustedTraceContext:a}}function attachDiagnosticEventTransport(e){e.attachTransport({format:()=>``,write:e=>{if(areDiagnosticsEnabledForProcess()&&hasInternalDiagnosticEventInterest(`log.record`))try{let t=buildDiagnosticLogRecord(redactSecrets(e));(t.trustedTraceContext?emitDiagnosticEventWithTrustedTraceContext:emitDiagnosticEvent)(t.event)}catch{}}})}function canUseSilentVitestFileLogFastPath(e){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`&&!e&&!kf.overrideSettings}function resolveDefaultActiveLogFile(e=!1){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG===`1`?S.join(process.cwd(),`.artifacts`,`test-logs`,`${P_}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date)}${F_}`):resolveDefaultRollingLogFile(e?void 0:{prepare:!1})}function resolveSettings(e=!1){if(!canUseNodeFs())return{level:`silent`,file:av,maxFileBytes:sv,rolling:!1,defaultFile:!1};let t=resolveEnvLogLevelOverride();if(canUseSilentVitestFileLogFastPath(t))return{level:`silent`,file:resolveDefaultRollingLogFile(e?void 0:{prepare:!1}),maxFileBytes:sv,rolling:!0,defaultFile:!0};let n=kf.overrideSettings??readLoggingConfig(),r=process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`?`silent`:`info`,i=normalizeLogLevel(n?.level,r),a=t??i,s=!n?.file||isLegacyRollingLogFilePath(n.file);return{level:a,file:resolveActiveLogFileWithMode(n?.file??resolveDefaultActiveLogFile(e),s),maxFileBytes:resolveMaxLogFileBytes(n?.maxFileBytes),rolling:s,defaultFile:!n?.file}}function getRuntimeSettings(){let e=kf.cachedSettings??resolveSettings();return kf.cachedSettings=e,e}function isFileLogLevelEnabled(e){return isLogLevelEnabled(e,getRuntimeSettings().level)}function inheritLogLevel(e,t){let resolveLevel=t;Object.defineProperty(e.settings,"minLevel",{configurable:!0,enumerable:!0,get:()=>resolveLevel(),set:e=>{resolveLevel=()=>e}})}function buildLogger(){let e=new RuntimeLogger({name:`openclaw`,mask:{keys:[]},meta:{property:`_meta`},minLevel:levelToMinLevel(`fatal`),type:`hidden`});inheritLogLevel(e,()=>levelToMinLevel(getRuntimeSettings().level));let t,n;return e.attachTransport({format:()=>``,write:e=>{try{let r=getRuntimeSettings();if(r.level===`silent`)return;n?.settings!==r&&(n={settings:r,file:r.defaultFile?resolveDefaultActiveLogFile(!0):r.file});let i=resolveActiveLogFileWithMode(n.file,r.rolling);if(i!==t){t=i;try{ensureLogDirectorySync(S.dirname(t)),r.rolling&&pruneOldRollingLogs(S.dirname(t))}catch{}}let a=formatTimestamp(e.date??/* @__PURE__ */ new Date,{style:`long`}),{fields:s,messageParts:c}=prepareFileLogRecord(e),l=serializeFileLogRecord({...e,_meta:withResolvedLogMetaHostname(e._meta,s.hostname),time:a,...s},c);rv.enqueue({file:t,hostname:s.hostname,maxFileBytes:r.maxFileBytes,payload:`${l}\n`})}catch{}}}),attachDiagnosticEventTransport(e),e}function resolveMaxLogFileBytes(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):sv}function getLogger(){let e=kf.cachedLogger;if(e)return e;getRuntimeSettings();let t=buildLogger();return kf.cachedLogger=t,t}function getChildLogger(e,t){let n=getLogger(),r=e?JSON.stringify(e):void 0;return n.getSubLogger({name:r,prefix:e?[r??``]:[],...t?.level?{minLevel:levelToMinLevel(t.level)}:{}})}function resolveActiveLogFileWithMode(e,t){let n=expandHomePrefix(e);return t?resolveRollingLogFilePathForDate(n,/* @__PURE__ */ new Date):n}function pruneOldRollingLogs(e){try{let t=r.readdirSync(e,{withFileTypes:!0}),n=Date.now()-ov;for(let i of t){if(!i.isFile()||!i.name.startsWith(`openclaw-`)||!i.name.endsWith(`.log`))continue;let t=S.join(e,i.name);try{r.statSync(t).mtimeMs<n&&r.rmSync(t,{force:!0})}catch{}}}catch{}}var av,ov,sv,cv,lv,uv,dv,fv,pv,mv,hv,RuntimeLogger,gv=__esmMin((()=>{D(),Ju(),td(),Cf(),vd(),pp(),bd(),j_(),M_(),Gp(),O_(),D_(),N_(),z_(),I_(),hm(),iv(),v_(),Af(),C_(),av=`${k_}/openclaw.log`,ov=864e5,sv=104857600,cv=null,lv=8192,uv=4096,dv=32,fv=2048,pv=120,mv=512,hv=/^[A-Za-z0-9_.:-]{1,64}$/u,RuntimeLogger=class extends ut{getSubLogger(e,t){let n=e?.minLevel??this.settings.minLevel,r=super.getSubLogger({...e,minLevel:n===1/0?levelToMinLevel(`fatal`):n},t);return e?.minLevel==null?inheritLogLevel(r,()=>this.settings.minLevel):n===1/0&&(r.settings.minLevel=n),r}}}));function normalizeConsoleLevel(e){return isVerbose()?`debug`:!e&&process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_CONSOLE!==`1`?`silent`:normalizeLogLevel(e,`info`)}function normalizeConsoleStyle(e){return e===`compact`||e===`json`||e===`pretty`?e:process.stdout.isTTY?`pretty`:`compact`}function resolveConsoleSettings(){let e=resolveEnvLogLevelOverride();if(process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_CONSOLE!==`1`&&!isVerbose()&&!e&&!kf.overrideSettings)return{level:`silent`,style:normalizeConsoleStyle(void 0)};let t=kf.overrideSettings??readLoggingConfig();return{level:e??normalizeConsoleLevel(t?.consoleLevel),style:normalizeConsoleStyle(t?.consoleStyle)}}function getConsoleSettings(){let e=kf.cachedConsoleSettings;if(e)return e;let t=resolveConsoleSettings();return kf.cachedConsoleSettings=t,t}function shouldLogSubsystemToConsole(e){let t=kf.consoleSubsystemFilter;if(!t||t.length===0)return!0;let n=normalizeOptionalString(e);return n?t.some(e=>n===e||n.startsWith(`${e}/`)):!1}function formatConsoleTimestamp(e){let t=/* @__PURE__ */ new Date;return e===`pretty`?formatTimestamp(t,{style:`short`}).replace(/[+-]\d{2}:\d{2}$/,``):formatTimestamp(t,{style:`long`})}var _v=__esmMin((()=>{Lt(),Vf(),Uf(),$u(),Gp(),O_(),w_(),D_(),gv(),v_(),Af(),C_(),`${process.release.name}${process.pid}`})),vv=/* @__PURE__ */ __exportAll({createSubsystemLogger:()=>createSubsystemLogger,runtimeForLogger:()=>runtimeForLogger});function formatRuntimeArg(e){return typeof e==`string`?e:me.inspect(e)}function isRichConsoleEnv(){let e=normalizeLowercaseStringOrEmpty(process.env.TERM);return process.env.COLORTERM||process.env.TERM_PROGRAM?!0:e.length>0&&e!==`dumb`}function pickSubsystemColor(e){let t=xv.get(e);if(t)return t;let n=0;for(let t=0;t<e.length;t+=1)n=n*31+e.charCodeAt(t)|0;let r=Math.abs(n)%bv.length;return expectDefined(bv[r],`subsystem colors entry at idx`)}function formatSubsystemForConsole(e){let t=e.split(`/`).filter(Boolean),n=t.join(`/`)||e;for(;t[0]!==void 0&&Sv.has(t[0]);)t.shift();let r=t.at(0);return r===void 0?n:Cv.has(normalizeLowercaseStringOrEmpty(r))?r:t.slice(-2).join(`/`)}function stripRedundantSubsystemPrefixForConsole(e,t){if(!t)return e;if(e.startsWith(`[`)){let n=e.indexOf(`]`);if(n>1&&normalizeLowercaseStringOrEmpty(e.slice(1,n))===normalizeLowercaseStringOrEmpty(t))return e.slice(n+1).replace(/^ */,``)}if(normalizeLowercaseStringOrEmpty(e.slice(0,t.length))!==normalizeLowercaseStringOrEmpty(t))return e;let n=e.slice(t.length,t.length+1);return n!==`:`&&n!==` `?e:e.slice(t.length).replace(/^ *:? */,``)}function createConsoleLineFormatter(e){let t=formatSubsystemForConsole(e),n=`[${t}]`,r=pickSubsystemColor(t);return(e,i,a)=>{let s=typeof process.env.FORCE_COLOR==`string`&&process.env.FORCE_COLOR.trim().length>0&&process.env.FORCE_COLOR.trim()!==`0`||!process.env.NO_COLOR&&(process.stdout.isTTY||process.stderr.isTTY||isRichConsoleEnv())?1:0,c=yv[s]??=new ve({level:s}),l=e===`error`||e===`fatal`?c.red:e===`warn`?c.yellow:e===`debug`||e===`trace`?c.gray:c.cyan,u=stripRedundantSubsystemPrefixForConsole(redactSensitiveText(i),t),d=a===`pretty`||kf.consoleTimestampPrefix?c.gray(formatConsoleTimestamp(a)):``,f=c[r](n);return`${d?`${d} ${f}`:f} ${l(u)}`}}function writeConsoleLine(e,t,n={}){clearActiveProgressLine();let r=process.platform===`win32`&&process.env.GITHUB_ACTIONS===`true`?t.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,`?`).replace(/[\uD800-\uDFFF]/g,`?`):t,i=n.redacted?r:redactSensitiveText(r),a=kf.rawConsole??console;kf.forceConsoleToStderr||e===`error`||e===`fatal`?(a.error??console.error)(i):e===`warn`?(a.warn??console.warn)(i):(a.log??console.log)(i)}function shouldSuppressProbeConsoleLine(e){if(isVerbose()||e.level===`error`||e.level===`fatal`)return!1;let t=typeof e.message==`string`?e.message:``;return e.suppressProbeMessages?(typeof e.meta?.runId==`string`?e.meta.runId:typeof e.meta?.sessionId==`string`?e.meta.sessionId:void 0)?.startsWith(`probe-`)?!0:/(sessionId|runId)=probe-/.test(t):!1}function formatConsoleMetaValue(e){if(e!==void 0)return typeof e==`string`?/\s|=/.test(e)||e.length===0?JSON.stringify(e):e:e===null||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function prepareLogMetaRecord(e,t=!1){let n;for(let[r,i]of Object.entries(e))i instanceof Error&&(n??={...e},n[r]={name:i.name,message:i.message,errorCode:extractErrorCode(i),stack:t?i.stack?.split(`
`).slice(0,6).join(`
`):i.stack});return n??e}function formatConsoleMeta(e){let t;try{t=redactLogRecordForTransport(e)}catch{return``}let n=[];for(let[e,r]of Object.entries(t)){let t=formatConsoleMetaValue(r);t!==void 0&&n.push(`${e}=${t}`)}let r=n.join(` `);return r.length>Tv?`${r.slice(0,Tv)}...(truncated)`:r}function logToFile(e,t,n,r){t!==`silent`&&(r&&Object.keys(r).length>0?e[t](r,n):e[t](n))}function createSubsystemLogger(e){let t=normalizeOptionalString(e)??`unknown`,n=t===`agent/embedded`||t.startsWith(`agent/embedded/`)||t===`model-fallback`||t.startsWith(`model-fallback/`),r,i,a,getFileLogger=e=>(r??=getChildLogger({subsystem:t}),e===`error`||e===`fatal`||e!==`info`&&areDiagnosticsEnabledForProcess()&&hasInternalDiagnosticEventInterest(`log.record`)?r:(i||(i=r.getSubLogger({stack:{capture:`off`}}),i.settings.parentNames=r.settings.parentNames),i)),emitLog=(e,r,i)=>{let s=getConsoleSettings(),c=i?.consoleMessage!==!1&&isLogLevelEnabled(e,s.level)&&shouldLogSubsystemToConsole(t),l=isFileLogLevelEnabled(e);if(!c&&!l)return;let u,d=i,f=i;if(i&&Object.keys(i).length>0){let{consoleMessage:e,...t}=i;typeof e==`string`&&(u=e),d=Object.keys(t).length>0?prepareLogMetaRecord(t):void 0,f=d&&c?prepareLogMetaRecord(t,!0):void 0}if(l&&logToFile(getFileLogger(e),e,r,d),!c)return;let p=s.style!==`json`&&u===void 0&&f&&wv.has(e)?formatConsoleMeta(f):``,m=u??(p?`${r} ${p}`:r);shouldSuppressProbeConsoleLine({level:e,suppressProbeMessages:n,message:m,meta:f})||writeConsoleLine(e,s.style===`json`?formatJsonConsoleLine({level:e,subsystem:t,message:r,meta:f}):(a??=createConsoleLineFormatter(t))(e,m,s.style),{redacted:!0})};return{subsystem:t,isEnabled(e,n=`any`){let r=isLogLevelEnabled(e,getConsoleSettings().level)&&shouldLogSubsystemToConsole(t),i=isFileLogLevelEnabled(e);return n===`console`?r:n===`file`?i:r||i},trace(e,t){emitLog(`trace`,e,t)},debug(e,t){emitLog(`debug`,e,t)},info(e,t){emitLog(`info`,e,t)},warn(e,t){emitLog(`warn`,e,t)},error(e,t){emitLog(`error`,e,t)},fatal(e,t){emitLog(`fatal`,e,t)},raw(e){isFileLogLevelEnabled(`info`)&&logToFile(getFileLogger(`info`),`info`,e,{raw:!0});let r=getConsoleSettings();if(isLogLevelEnabled(`info`,r.level)&&shouldLogSubsystemToConsole(t)){if(shouldSuppressProbeConsoleLine({level:`info`,suppressProbeMessages:n,message:e}))return;writeConsoleLine(`info`,r.style===`json`?formatJsonConsoleLine({level:`info`,subsystem:t,message:e}):e,{redacted:r.style===`json`})}},child(e){return createSubsystemLogger(`${t}/${e}`)}}}function runtimeForLogger(e,t=jf.exit){return{log(...t){e.isEnabled(`info`)&&e.info(t.map(formatRuntimeArg).join(` `).trim())},error(...t){e.isEnabled(`error`)&&e.error(t.map(formatRuntimeArg).join(` `).trim())},writeStdout(t){e.info(t)},writeJson(t,n=2){e.isEnabled(`info`)&&e.info(JSON.stringify(t,void 0,n>0?n:void 0))},exit:t}}var yv,bv,xv,Sv,Cv,wv,Tv,Ev=__esmMin((()=>{Yu(),O(),Lt(),Zu(),$u(),td(),Cf(),Mf(),_v(),D_(),gv(),v_(),Af(),yv=[],bv=[`cyan`,`green`,`yellow`,`blue`,`magenta`,`red`],xv=/* @__PURE__ */ new Map([[`gmail-watcher`,`blue`]]),Sv=/* @__PURE__ */ new Set([`gateway`,`channels`,`providers`]),Cv=/* @__PURE__ */ new Set(/* @__PURE__ */ `clickclack.discord.feishu.googlechat.imessage.irc.line.matrix.mattermost.msteams.nextcloud-talk.nostr.openclaw-weixin.qqbot.signal.slack.synology-chat.telegram.tlon.twitch.webchat.wecom.whatsapp.yuanbao.zalo.zalouser`.split(`.`)),wv=/* @__PURE__ */ new Set([`warn`,`error`,`fatal`]),Tv=2048}));function classifyRetiredSqliteSnapshotRemovalError(e,t){let n=extractErrorCode(t);return t instanceof Error&&`syscall`in t&&(t.syscall===`rmdir`||t.syscall===`unlink`)&&(n===`EBUSY`||n===`ENOTEMPTY`)?new SqliteSnapshotDirectoryBusyError(`SQLite retired snapshot directory removal is busy: ${e}`,{cause:t}):t}function createSqliteLifecycleAggregateError(e,t,n){return AggregateError(e,t,{cause:n})}function throwSqliteLifecycleErrors(e,t){if(e.length===1)throw e[0];if(e.length>1)throw createSqliteLifecycleAggregateError(e,t,e[0])}function runWithSqliteCleanup(e,t,n){let r;try{if(r=n(),isPromiseLike(r))throw new Dv(`${t} must remain synchronous`)}catch(n){try{e.release()}catch(e){throw createSqliteLifecycleAggregateError([n,e],`${t} and resource release both failed`,n)}throw n}try{e.release()}catch(e){throw new Dv(`${t} completed, but releasing its resource failed`,e)}return r}var SqliteSnapshotCleanupError,SqliteSnapshotDirectoryBusyError,OpenClawStateOwnershipError,OpenClawStateOwnershipMetadataError,OpenClawStateExternalOwnershipError,Dv,W=__esmMin((()=>{O(),mu(),B(),SqliteSnapshotCleanupError=class extends Error{},SqliteSnapshotDirectoryBusyError=class extends SqliteSnapshotCleanupError{constructor(...e){super(...e),this.name=`SqliteSnapshotDirectoryBusyError`}},OpenClawStateOwnershipError=class extends Error{},OpenClawStateOwnershipMetadataError=class extends OpenClawStateOwnershipError{constructor(e,t){super(`OpenClaw shared state ownership metadata is invalid at ${e}: ${t}. Repair it with OPENCLAW_SUPERVISOR_MODE=external openclaw database ownership claim --manager <manager-id>.`),this.databasePath=e,this.name=`OpenClawStateOwnershipMetadataError`}},OpenClawStateExternalOwnershipError=class extends OpenClawStateOwnershipError{constructor(e,t){super(`OpenClaw shared state database ${e} is externally supervised by ${t}. Use that external supervisor with OPENCLAW_SUPERVISOR_MODE=external for writable operations.`),this.databasePath=e,this.managerId=t,this.name=`OpenClawStateExternalOwnershipError`}},Dv=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteCoordinatorError`),()=>class extends Error{constructor(e,t){super(e),this.cause=t,this.name=`SqliteCoordinatorError`}})}));function installCommittedState(e,t){let n=/* @__PURE__ */ new Map,install=(e,t)=>{try{t?.()}catch(t){n.set(e,t)}};for(let t of e)install(t,t.commit);let invalidate=()=>{let e=!0;for(let[t,r]of n)try{t.invalidate?t.invalidate(r):e=!1}catch{e=!1}return e};invalidate();for(let t of e)n.has(t)||install(t,t.prepareObservers);let r=invalidate();if(n.size>0)try{Ov.error(`Committed SQLite facts could not be installed`,{count:n.size,fenced:r})}catch{}if(r)for(let e of t)try{e()}catch{try{Ov.error(`SQLite post-commit notification failed`)}catch{}}}function hasSqlitePostCommitScope(e){return kv.has(sqlPublicationAnchor(e))}function stageSqliteTransactionState(e,t){let n=Av.get(sqlPublicationAnchor(e));return n?(t.stage?.(),n.push({prepareCommit:t.prepareCommit,commit:t.commit,prepareObservers:t.prepareObservers,invalidate:t.invalidate,rollback:t.rollback}),!0):!1}function prepareSqliteTransactionCommit(e){for(let t of Av.get(sqlPublicationAnchor(e))??[])t.prepareCommit?.()}function rollbackTransactionState(e,t,n=`rolled-back`){let r=[];for(let i of e.toReversed())try{n===`unknown`&&i.invalidate?i.invalidate(t):i.rollback?.(t)}catch(e){r.push(e)}if(r.length>0)throw createSqliteLifecycleAggregateError([t,...r],`SQLite transaction and rollback observers failed`,t)}function discardSqliteTransactionState(e,t,n=`unknown`){let r=sqlPublicationAnchor(e);kv.get(r)?.splice(0);let i=Av.get(r)?.splice(0)??[];kv.delete(r),Av.delete(r),rollbackTransactionState(i,t,n)}function withSqlitePostCommitPublications(e,t){let n=sqlPublicationAnchor(e),r=e.isTransaction||kv.has(n),i=r?kv.get(n):[],a=r?Av.get(n):[],s=i?.length??0,c=a?.length??0;!r&&i&&a&&(kv.set(n,i),Av.set(n,a));let l;try{l=t()}catch(e){throw i?.splice(s),rollbackTransactionState(a?.splice(c)??[],e),e}finally{r||(kv.delete(n),Av.delete(n))}return r||installCommittedState(a??[],i??[]),l}var Ov,kv,Av,jv=__esmMin((()=>{Ev(),B(),gu(),W(),Ov=createSubsystemLogger(`sqlite/publication`),kv=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePostCommitPublications`),()=>/* @__PURE__ */ new WeakMap),Av=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteTransactionState`),()=>/* @__PURE__ */ new WeakMap)}));function sqliteReaderDatabasePathKey(e){let t=S.resolve(e);return process.platform===`win32`?Ue(t):t}function boundedOperation(e){return(e.trim()||`sqlite reader`).slice(0,120)}function captureSqliteReaderOwner(){let e=Mv.getStore();if(!e)return;let{timing:t,...n}=e;return n}function currentSqliteOperationTiming(){return Mv.getStore()?.timing}function currentOwner(e,t){let n=t??Mv.getStore();return{operation:boundedOperation(n?.operation??e),ownerKind:n?.ownerKind??(at?`main`:`worker`),...n?.actorId===void 0?{}:{actorId:n.actorId}}}function connectionFor(e){let t=Nv.byDatabase.get(e);if(!t){let n=Date.now(),r=e.location();t={id:++Nv.nextId,path:r?sqliteReaderDatabasePathKey(r):void 0,database:new WeakRef(e),owner:currentOwner(`sqlite connection`),openedAtMs:n,readers:/* @__PURE__ */ new Map},Nv.byDatabase.set(e,t),Nv.finalizer.register(e,t,t)}if(t.path){let e=Nv.byPath.get(t.path)??/* @__PURE__ */ new Map;e.set(t.id,t),Nv.byPath.set(t.path,e)}return t}function forgetConnection(e){if(e.path){let t=Nv.byPath.get(e.path);t?.delete(e.id),t?.size===0&&Nv.byPath.delete(e.path)}}function registerSqliteReaderConnection(e){e.isOpen&&connectionFor(e)}function retainSqliteReader(e,t,n){let r=connectionFor(e),i=Date.now(),a={...currentOwner(t,n),kind:`iterator`,connectionId:r.id,threadId:E,startedAtMs:i,lastProgressAtMs:i},s=Symbol(a.operation),c=r.readers;return c.set(s,a),{progress(){c.has(s)&&(a.lastProgressAtMs=Date.now())},release(){c.delete(s)}}}function diagnostics(e){let t=Date.now();return[...e].map(({startedAtMs:e,lastProgressAtMs:n,...r})=>Object.assign(r,{ageMs:Math.max(0,t-e),idleMs:Math.max(0,t-n)})).toSorted((e,t)=>t.ageMs-e.ageMs).slice(0,8)}function assertNoActiveSqliteReaders(e,t){let n=diagnostics(Nv.byDatabase.get(e)?.readers.values()??[]);if(n.length===0)return;let r=n[0];throw Error(`${t} retained ${n.length} active SQLite reader(s); oldest operation=${r.operation} ageMs=${r.ageMs}`)}var Mv,Nv,Pv=__esmMin((()=>{fd(),B(),Mv=new AsyncContext(Symbol.for(`openclaw.sqliteReaderOwners`)),Nv=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteReaderConnections`),()=>({nextId:0,byDatabase:/* @__PURE__ */ new WeakMap,byPath:/* @__PURE__ */ new Map,finalizer:new FinalizationRegistry(e=>forgetConnection(e))}))}));function getNodeSqliteKysely(e){if(isPostgresSqlConnection(e)){let t=Rv.get(e);return t||(t=new Xc({dialect:zv}),Rv.set(e,t)),t}let t=_u.get(e);if(t)return t;let n=new Xc({dialect:Lv});return _u.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{vu.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 toErrorObject(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(isPostgresSqlConnection(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&&I.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(I.is(t.query)||i.columns().length>0){if(Iv)return{rows:i.all(...r)};let t=i.iterate(...r),n=retainSqliteReader(e,`kysely eager query`),a=!1,s,c=[];try{for(let e of t)n.progress(),c.push(e)}catch(e){a=!0,s=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw toErrorObject(s,`SQLite query failed`);return{rows:c}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:s,lastInsertRowid:c}=a,l={numAffectedRows:BigInt(s),rows:[]};return qr.is(t.query)&&s>0?{...l,insertId:BigInt(c)}:l})}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),al`${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]}var Fv,Iv,Lv,Rv,zv,G=__esmMin((()=>{O(),ou(),du(),Du(),gu(),Au(),jv(),Pv(),Fv=parseNodeReleaseVersion(process.versions.node),Iv=!process.versions.bun&&(Fv?.major===24&&isNodeVersionAtLeast(Fv,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(Fv,{major:26,minor:6,patch:0})),Lv=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),Rv=/* @__PURE__ */ new WeakMap,zv=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}})}));function withEngineStoreAdmission(e){Vv+=1;try{let t=e();if(isPromiseLike(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--Vv}}function assertEngineStoreExecutionAllowed(){if(E===0&&Vv===0&&Bv.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`)}var Bv,Vv,Hv=__esmMin((()=>{mu(),B(),Bv=resolveGlobalSingleton(Symbol.for(`openclaw.databaseProcessRole`),()=>({})),Vv=0})),Uv,Wv=__esmMin((()=>{Uv=`openclaw.sqliteDatabaseAdmissions.v1`}));function changedAdmissionEntries(e,t){let n=/* @__PURE__ */ new Map;for(let[r,i]of e)t.get(r)!==i&&n.set(r,i);return n}function changedAdmissionWriteScopes(e,t){let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{e!==t[r]&&e.forEach((e,i)=>{t[r].get(i)!==e&&n.set(i,e)})}),n}var Gv=__esmMin((()=>{}));function databaseFileIdentityKey(e){return`${e.dev}:${e.ino}`}function readDatabaseIdentityBirthtime(e){return Kv?e.birthtimeNs.toString():`0`}function normalizeDatabasePath(e){let t=process.platform===`win32`?normalizeWindowsPathPreservingCase(e):e;return process.platform===`win32`&&!/^(?:[a-z]:[\\/]|[\\/]{2})/iu.test(t)?e:t}function readDatabaseFileIdentity(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`key`in e)||typeof e.key!=`string`||!/^file:(?:0|[1-9]\d{0,19}):(?:0|[1-9]\d{0,19})$/.test(e.key)||`birthtime`in e&&e.birthtime!==void 0&&(typeof e.birthtime!=`string`||!/^-?(?:0|[1-9]\d{0,29})$/.test(e.birthtime)))throw Error(`SQLite snapshot requires a captured physical file identity`);return{key:e.key,...`birthtime`in e&&typeof e.birthtime==`string`?{birthtime:e.birthtime}:{}}}function assertDatabaseFileIdentity(e,t){if(!e.isFile()||`file:${databaseFileIdentityKey(e)}`!==t.key||t.birthtime!==void 0&&readDatabaseIdentityBirthtime(e)!==t.birthtime)throw Error(`SQLite database file identity changed before existing-only open`)}function existingIdentity(e,t,n){if(!e.isFile())throw Error(`SQLite worker database path must identify a regular file`);if(e.dev!==t.dev||e.ino!==t.ino||readDatabaseIdentityBirthtime(e)!==readDatabaseIdentityBirthtime(t))throw Error(`SQLite database pathname changed during admission`);return{key:`file:${databaseFileIdentityKey(e)}`,canonicalPath:normalizeDatabasePath(n),birthtime:readDatabaseIdentityBirthtime(e)}}function missingAncestorParent(e,t,n){if(!w(n,`ENOENT`))throw n;t.unshift(S.basename(e));let r=S.dirname(e);if(r===e)throw n;return r}function resolveDatabasePathKey(e){let t=S.resolve(e),n=[];for(;;)try{return normalizeDatabasePath(S.join(m.native(t),...n))}catch(e){t=missingAncestorParent(t,n,e)}}function inspectDatabasePathIdentitySync(e){let t=S.resolve(e),n;try{n=h(t,{bigint:!0})}catch(e){if(!w(e,`ENOENT`))throw e}if(n){if(!n.isFile())return;let e=resolveDatabasePathKey(t);return existingIdentity(n,h(e,{bigint:!0}),e)}let r=resolveDatabasePathKey(t);return{key:`path:${r}`,canonicalPath:r}}function readDatabasePathIdentitySync(e){let t=inspectDatabasePathIdentitySync(e);if(!t)throw Error(`SQLite worker database path must identify a regular file`);return t}function findChangedDatabasePaths(e,t){return[...e].filter(e=>inspectDatabasePathIdentitySync(e)?.key!==t.key)}async function readDatabasePathIdentity(e){let t=await inspectDatabasePathIdentity(e);if(!t)throw Error(`SQLite worker database path must identify a regular file`);return t}async function inspectDatabasePathIdentity(e){let t=await Je(e,{bigint:!0}).catch(e=>{if(!w(e,`ENOENT`))throw e});if(t){if(!t.isFile())return;try{let n=await Ke(e);return existingIdentity(t,await Je(n,{bigint:!0}),n)}catch(e){throw w(e,`ENOENT`)?Error(`SQLite database pathname changed during admission`,{cause:e}):e}}let n=await resolveDatabasePathKeyAsync(e);return{key:`path:${n}`,canonicalPath:n}}async function resolveDatabasePathKeyAsync(e){let t=[],n=S.resolve(e);for(;;)try{return normalizeDatabasePath(S.join(await Ke(n),...t))}catch(e){n=missingAncestorParent(n,t,e)}}function assertExistingDatabaseIdentity(e,t,n){assertDatabaseFileIdentity(h(e,{bigint:!0}),{key:t,birthtime:n})}function isSoleDatabaseFileDescriptor(e,t,n){if(process.platform!==`linux`)return!1;try{for(let r of p(`/proc/self/fd`))if(/^\d+$/u.test(r)&&Number(r)!==e&&!n?.has(Number(r)))try{let e=u(Number(r),{bigint:!0});if(e.dev===t.dev&&e.ino===t.ino)return!1}catch(e){if(!w(e,`EBADF`))return!1}return!0}catch{return!1}}var Kv,qv=__esmMin((()=>{H(),bp(),Kv=process.platform!==`linux`&&process.platform!==`android`}));function readSqliteDatabaseAdmissionIdentity(e){return`${e.dev}:${e.ino}:${readDatabaseIdentityBirthtime(e)}`}function readSqliteDatabaseAdmissionFact(e,t){return e[Xv]??={value:t.read?t.read(e.value):e.value},e[Xv].value}function admitSqliteDatabaseFactValue(e,t){let n={value:t};return readSqliteDatabaseAdmissionFact(n,e),n}function retainSqliteDatabaseWriteScope(e,t,n){let r=e.writeScopes,i=Qv.get(r);i||(i={bytes:[...r.keys()].reduce((e,t)=>e+writeScopeBytes(t),0),retired:/* @__PURE__ */ new Set},Qv.set(r,i)),r.delete(t)||(i.bytes+=writeScopeBytes(t)),r.set(t,n),pruneSqliteDatabaseWriteScopes(e)}function pruneSqliteDatabaseWriteScopes(e){let t=Qv.get(e.writeScopes);if(t.bytes<=Zv)return!1;let n=!1;for(let[r,i]of e.writeScopes)if(!(Atomics.compareExchange(i.state,2,0,-1)>0&&Atomics.load(i.state,1)===0)&&(Atomics.store(i.state,1,1),advanceSqliteDatabaseGeneration(e,`writeScopeRevision`),e.writeScopes.delete(r),t.bytes-=writeScopeBytes(r),t.retired.add(r),n=!0,t.bytes<=Zv))break;return n}function readSqliteDatabaseAdmissions(e){return Array.isArray(e)?e:void 0}function isSqliteDatabaseAdmissionRetired(e){return readSqliteDatabaseGeneration(e,`retired`)!==0}function isSqliteDatabaseAdmissionFactCurrent(e,t){return!isSqliteDatabaseAdmissionRetired(e)&&Atomics.load(new Int32Array(t.current),0)===1&&t.revision===readSqliteDatabaseFactRevision(e,t.schemaDependent)}function hasSqliteDatabaseSchemaAdmission(e){let t=e?.facts.get(`sqlite-schema`);return!!(e&&t&&isSqliteDatabaseAdmissionFactCurrent(e,t))}function readSqliteDatabaseFactRevision(e,t){return readSqliteDatabaseGeneration(e,t?`schemaRevision`:`factRevision`)}function readSqliteDatabaseGeneration(e,t){return Atomics.load(new Int32Array(e.generation),Jv[t])}function advanceSqliteDatabaseGeneration(e,t){return Atomics.add(new Int32Array(e.generation),Jv[t],1)}function publishSqliteDatabaseFact(e,t,n,r,i){if(isSqliteDatabaseAdmissionRetired(e)||r!==readSqliteDatabaseFactRevision(e,t.schemaDependent))return!1;t.writer===`host`&&advanceSqliteDatabaseGeneration(e,`hostRevision`);let a=e.facts.get(t.name);a&&Atomics.store(new Int32Array(a.current),0,0);let s=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);return Atomics.store(new Int32Array(s),0,1),e.facts.set(t.name,{...n,revision:r,schemaDependent:t.schemaDependent===!0,lifetime:t.lifetime,publication:i,current:s}),advanceSqliteDatabaseGeneration(e,`publicationRevision`),!0}function revokeSqliteDatabaseAdmissionFacts(e){if(e){for(let t of e.facts.values())Atomics.store(new Int32Array(t.current),0,0);advanceSqliteDatabaseGeneration(e,`schemaRevision`),advanceSqliteDatabaseGeneration(e,`factRevision`)}}function snapshotWriteScopes(e,t=$v,n){let r=t,i=Qv.get(e),visit=(n,a)=>{let s=0;for(let e=0;e<a.length;e++)s=s*31+a.charCodeAt(e)|0;let c=s&$v.length-1,l=!n||Atomics.load(n.state,1)!==0;l&&e.delete(a)&&i&&(i.bytes-=writeScopeBytes(a)),!(l?!t[c].has(a):t[c].get(a)===n)&&(r===t&&(r=t.slice()),r[c]===t[c]&&(r[c]=new Map(t[c])),l?r[c].delete(a):r[c].set(a,n))};if(n)for(let t of n)visit(e.get(t),t);else e.forEach(visit);for(let t of i?.retired??[])visit(e.get(t),t);return i?.retired.clear(),r}function createSqliteDatabaseAdmissionCursor(){return{revision:-1,records:/* @__PURE__ */ new WeakMap}}var Jv,Yv,Xv,Zv,Qv,writeScopeBytes,$v,SqliteDatabaseAdmissionRegistry,ey=__esmMin((()=>{B(),Gv(),Wv(),qv(),Jv={schemaRevision:0,factRevision:1,publicationRevision:2,retired:3,writeRevision:4,hostRevision:5,unscopedWriteRevision:6,writeScopeRevision:7,sealPresent:8},Yv=Object.keys(Jv).length,Xv=Symbol.for(`openclaw.sqliteDatabaseAdmission.decodedValue`),Zv=1048576,Qv=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseWriteScopeRetention`),()=>/* @__PURE__ */ new WeakMap),writeScopeBytes=e=>e.length*2+256,$v=Array.from({length:128},()=>/* @__PURE__ */ new Map),SqliteDatabaseAdmissionRegistry=class{constructor(){this.records=/* @__PURE__ */ new Map,this.exchangeCursor=createSqliteDatabaseAdmissionCursor(),this.locations=/* @__PURE__ */ new Map,this.published=/* @__PURE__ */ new Map,this.scopeSweeps=/* @__PURE__ */ new WeakMap,this.descriptors=/* @__PURE__ */ new Map,this.revision=0,this.retainProcessFacts=!0}useConnectionScopedFacts(){this.retainProcessFacts=!1}changeReferences(e,t){let n=e.references.get(E);return n||(n=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),e.references.set(E,n)),Atomics.add(new Int32Array(n),0,t)+t===+(t===1)&&(t===-1&&this.retireUnreferenced(e),this.publish(e),!0)}retireUnreferenced(e){if(E!==0||isSqliteDatabaseAdmissionRetired(e)||[...e.references.values()].some(e=>Atomics.load(new Int32Array(e),0)>0))return;for(let[t,n]of e.facts)(!this.retainProcessFacts||n.lifetime!==`process`||!isSqliteDatabaseAdmissionFactCurrent(e,n))&&e.facts.delete(t);let t=this.descriptors.get(e.identity);t&&(t.facts=e.facts),Atomics.compareExchange(new Int32Array(e.generation),Jv.retired,0,2),e.writeScopes.clear()}releaseWorker(e){let t=/* @__PURE__ */ new Map;for(let n of this.records.values()){let r=e>0?n.references.get(e):void 0;r&&(Atomics.store(new Int32Array(r),0,-1),this.retireUnreferenced(n),t.set(n,void 0))}t.size>0&&this.publish(t)}observeLocation(e,t){let n=normalizeDatabasePath(S.resolve(e));t===void 0?this.locations.delete(n):this.locations.set(n,t)}forLocation(e){let t=this.locations.get(normalizeDatabasePath(S.resolve(e))),n=t===void 0?void 0:this.records.get(t);return n&&!isSqliteDatabaseAdmissionRetired(n)?n:void 0}hasSchemaAdmissionForIdentity(e){if(!e.key.startsWith(`file:`)||e.birthtime===void 0)return!1;let t=`${e.key.slice(5)}:${e.birthtime}`;return hasSqliteDatabaseSchemaAdmission(this.records.get(t))}forget(e){this.records.delete(e),this.published.delete(e);for(let[t,n]of this.locations)n===e&&this.locations.delete(t)}retainDescriptorCustody(e,t){let n=readSqliteDatabaseAdmissionIdentity(t),r=this.descriptors.get(n);r&&r.descriptor!==e&&(r.additionalDescriptors??=/* @__PURE__ */ new Set).add(e),r||this.descriptors.set(n,{descriptor:e,file:t,facts:/* @__PURE__ */ new Map})}retainDescriptor(e,t,n){let r=this.descriptors.get(readSqliteDatabaseAdmissionIdentity(n)),i={identity:readSqliteDatabaseAdmissionIdentity(n),physicalIdentity:{key:`file:${n.dev}:${n.ino}`,birthtime:readDatabaseIdentityBirthtime(n)},location:e,descriptor:t,descriptorOwner:0,generationId:Se(),generation:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*Yv),writeScopes:/* @__PURE__ */ new Map,writeScopeRevision:0,references:/* @__PURE__ */ new Map,facts:new Map([...r?.facts??[]].filter(([,e])=>Atomics.load(new Int32Array(e.current),0)===1).map(([e,t])=>[e,{...t,revision:0}]))};this.records.set(i.identity,i);let a=r?.descriptor===t?r:{descriptor:t,file:n,facts:/* @__PURE__ */ new Map};return a.file=n,a.facts=/* @__PURE__ */ new Map,this.descriptors.set(i.identity,a),this.observeLocation(e,i.identity),this.publish(i),i}retireDescriptor(e,t){let n=this.records.get(e),i=this.descriptors.get(e),a=i?.descriptor??n?.descriptor;if(a===void 0)return!1;let s=r.fstatSync(a,{bigint:!0});return s.nlink>1n||t.requireSoleDescriptor&&!isSoleDatabaseFileDescriptor(a,s,i?.additionalDescriptors)?!1:(n&&Atomics.store(new Int32Array(n.generation),Jv.retired,1),r.closeSync(a),i?.additionalDescriptors?.forEach(e=>r.closeSync(e)),this.descriptors.delete(e),this.forget(e),this.publish(),!0)}publish(e,t){let n=e instanceof Map;if(!e||n||this.records.get(e.identity)===e){for(let i of this.records.values()){if(isSqliteDatabaseAdmissionRetired(i)){readSqliteDatabaseGeneration(i,`retired`)===1&&(this.descriptors.get(i.identity)?.additionalDescriptors?.forEach(r.closeSync),this.descriptors.delete(i.identity)),this.forget(i.identity);continue}if(e&&e!==i&&!(n&&e.has(i)))continue;let a=e===i||n;for(let[e,t]of i.references)Atomics.load(new Int32Array(t),0)<0&&(i.references.delete(e),a=!0);let s=this.published.get(i.identity),c=readSqliteDatabaseGeneration(i,`writeScopeRevision`),l=s&&e?n?e.get(i):t:void 0,u=l===void 0&&this.scopeSweeps.get(i)!==c,d=snapshotWriteScopes(i.writeScopes,s?.writeScopes,l??(u?void 0:[]));if(u&&this.scopeSweeps.set(i,c),a||=d!==s?.writeScopes,!a)continue;E===0&&(i.writeScopeRevision=readSqliteDatabaseGeneration(i,`writeScopeRevision`));let{writeScopes:f,...p}=i,m={...p,facts:new Map(i.facts),references:new Map(i.references),hostRevision:E===0?readSqliteDatabaseGeneration(i,`hostRevision`):i.hostRevision},h={...m,writeScopes:d.filter(e=>e.size>0)};this.published.set(i.identity,{metadata:m,writeScopes:d,snapshot:h})}this.revision++,ct(Uv,[...this.published.values()].map(e=>e.snapshot))}}capture(e,t){let n=t?/* @__PURE__ */ new Set([...t.admissions?.map(e=>e.identity)??[],...t.location===void 0?[]:[this.forLocation(t.location)?.identity].filter(e=>e!==void 0)]):void 0;if(!n&&!e&&this.publish(),!n&&e?.revision===this.revision)return[];let r=n?[...n].flatMap(e=>{let t=this.published.get(e);return t&&!isSqliteDatabaseAdmissionRetired(t.snapshot)?[t]:[]}):[...this.published.values()];return e?(n||(e.revision=this.revision),r.flatMap(t=>{let n=e.records.get(t.metadata.generation);return n===t?[]:(e.records.set(t.metadata.generation,t),[n?{...t.metadata,facts:changedAdmissionEntries(t.metadata.facts,n.metadata.facts),writeScopes:[changedAdmissionWriteScopes(t.writeScopes,n.writeScopes)],references:changedAdmissionEntries(t.metadata.references,n.metadata.references)}:t.snapshot])})):r.map(e=>e.snapshot)}captureExchange(e,t){return t&&typeof t!=`string`&&isSqliteDatabaseAdmissionRetired(t)?[{...t,facts:/* @__PURE__ */ new Map,writeScopes:[],references:/* @__PURE__ */ new Map}]:this.capture(this.exchangeCursor,e)}resetExchangeCursor(){this.exchangeCursor=createSqliteDatabaseAdmissionCursor()}install(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=this.records.get(n.identity);if(n.descriptorOwner!==0||isSqliteDatabaseAdmissionRetired(n)){e&&isSqliteDatabaseAdmissionRetired(e)&&t.set(e,void 0);continue}let r=!1;if(e&&isSqliteDatabaseAdmissionRetired(e)&&(e=void 0),!e)e={...n,facts:new Map(n.facts),writeScopes:/* @__PURE__ */ new Map,references:new Map(n.references),hostRevision:void 0},this.records.set(n.identity,e),this.observeLocation(n.location,n.identity),r=!0;else if(e.generationId!==n.generationId)continue;!e.cleanCloseRefusal&&n.cleanCloseRefusal&&(e.cleanCloseRefusal=n.cleanCloseRefusal,r=!0);for(let[t,i]of n.facts)isSqliteDatabaseAdmissionFactCurrent(n,i)&&e.facts.get(t)?.publication!==i.publication&&(e.facts.set(t,i),r=!0);let i=t.get(e)??[];for(let t of n.writeScopes)for(let[n,a]of t){if(Atomics.load(a.state,1)!==0)continue;let t=e.writeScopes.get(n);if(!(t?.identity===a.identity||E===0&&t&&Atomics.load(t.state,1)===0)){if(E===0){let t=advanceSqliteDatabaseGeneration(e,`writeScopeRevision`);this.scopeSweeps.get(e)===t&&this.scopeSweeps.set(e,t+1|0)}retainSqliteDatabaseWriteScope(e,n,a),i.push(n),r=!0}}let a=readSqliteDatabaseGeneration(e,`writeScopeRevision`);(E===0||n.writeScopeRevision===a)&&(r||=e.writeScopeRevision!==a,e.writeScopeRevision=a);for(let[t,i]of n.references)!e.references.has(t)&&Atomics.load(new Int32Array(i),0)>=0&&(e.references.set(t,i),r=!0);E!==0&&n.hostRevision!==void 0&&n.hostRevision!==e.hostRevision&&n.hostRevision===readSqliteDatabaseGeneration(e,`hostRevision`)&&(e.hostRevision=n.hostRevision,r=!0),this.retireUnreferenced(e),(r||isSqliteDatabaseAdmissionRetired(e))&&t.set(e,i.length>0?i:void 0)}return t.size>0&&this.publish(t),t.size>0}}}));function captureSqliteDatabaseAdmissions(e,t){return K.registry.capture(e,t)}function installSqliteDatabaseAdmissions(e){K.registry.install(e)}function exchangeSqliteDatabaseAdmission(e,t,n=!1,r){let i=K.exchange.getStore();if(i&&!K.exchanging){K.exchanging=!0;try{let a=typeof e==`string`?{location:e}:{admissions:[e]},s=K.registry.captureExchange(a,e);if(n&&s.length===0)return;installSqliteDatabaseAdmissions(i(s,typeof e==`string`?e:void 0,t,r))}catch(e){throw K.registry.resetExchangeCursor(),e}finally{K.exchanging=!1}}}function canShareSqliteDatabaseAdmissions(){return E===0||K.exchange.getStore()!==void 0}var K,ty,ny=__esmMin((()=>{B(),Wv(),ey(),K=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissions`),()=>({registry:new SqliteDatabaseAdmissionRegistry,descriptorPreparation:Promise.resolve(),connections:/* @__PURE__ */ new WeakMap,openedIdentities:/* @__PURE__ */ new WeakMap,unproven:/* @__PURE__ */ new WeakSet,suspended:/* @__PURE__ */ new WeakSet,local:/* @__PURE__ */ new WeakMap,rolledBack:/* @__PURE__ */ new WeakSet,dataWriters:/* @__PURE__ */ new WeakMap,localWriteRevisions:/* @__PURE__ */ new WeakMap,writeListeners:/* @__PURE__ */ new WeakMap,ddlRevisions:/* @__PURE__ */ new WeakMap,schemaDirty:/* @__PURE__ */ new WeakSet,localSchemaRevisions:/* @__PURE__ */ new Map,misses:/* @__PURE__ */ new WeakMap,exchange:new C,exchanging:!1,publication:0})),ty=readSqliteDatabaseAdmissions(it(Uv)),ty&&(installSqliteDatabaseAdmissions(ty),K.registry.captureExchange())}));function fileFields(e){return{dev:e.dev.toString(),ino:e.ino.toString(),birthtime:readDatabaseIdentityBirthtime(e),size:e.size.toString(),mtimeNs:e.mtimeNs.toString()}}function checksum(e){return ye(`sha256`).update(e).digest(`hex`).slice(0,16)}function hasNoJournal(e){return[`-wal`,`-journal`].every(t=>{try{let n=r.statSync(`${e}${t}`,{bigint:!0});return n.isFile()&&n.size===0n}catch(e){if(w(e,`ENOENT`))return!0;throw e}})}function readSqliteCleanCloseSeal(e,t,n){let refuse=e=>{n?.(e)};try{let n=`${e}.seal`;return r.lstatSync(n).isFile()?decodeSqliteCleanCloseSeal(r.readFileSync(n,`utf8`),t,hasNoJournal(e),refuse):refuse(`malformed-proof`)}catch(e){return refuse(w(e,`ENOENT`)?`no-proof`:`malformed-proof`)}}function decodeSqliteCleanCloseSeal(e,t,n,r){let i=JSON.parse(e);if(!isRecord(i)||typeof i.payload!=`string`||i.checksum!==checksum(i.payload))return r(`malformed-proof`);let a=JSON.parse(i.payload);if(!isRecord(a)||a.version!==1||typeof a.schemaIdentity!=`string`||typeof a.verifiedAt!=`number`||!Number.isSafeInteger(a.verifiedAt)||!(`facts`in a)||!t.isFile())return r(`malformed-proof`);let s=Date.now()-a.verifiedAt;return s<0||s>ry?r(`expired-proof`):Object.entries(fileFields(t)).every(([e,t])=>a[e]===t)?n?{schemaIdentity:a.schemaIdentity,verifiedAt:a.verifiedAt,facts:a.facts,...a.identity===void 0?{}:{identity:a.identity}}:r(`journal-present`):r(`file-mismatch`)}async function readSqliteCleanCloseSealAsync(e,t,n){let refuse=e=>{n?.(e)};try{let n=e+`.seal`;return(await r.promises.lstat(n)).isFile()?decodeSqliteCleanCloseSeal(await r.promises.readFile(n,`utf8`),t,(await Promise.all([`-wal`,`-journal`].map(async t=>{try{let n=await r.promises.stat(e+t,{bigint:!0});return n.isFile()&&n.size===0n}catch(e){if(w(e,`ENOENT`))return!0;throw e}}))).every(Boolean),refuse):refuse(`malformed-proof`)}catch(e){return refuse(w(e,`ENOENT`)?`no-proof`:`malformed-proof`)}}function invalidateSqliteCleanCloseSeal(e){try{r.unlinkSync(`${e}.seal`)}catch(e){if(!w(e,`ENOENT`))throw e}}function writeSqliteCleanCloseSeal(e,t,n,i){try{let a=`${e}.seal`,s=r.lstatSync(a,{throwIfNoEntry:!1});if(!n.isFile()||s&&!s.isFile()||!hasNoJournal(e))return invalidateSqliteCleanCloseSeal(e),!1;let c=JSON.stringify({version:1,schemaIdentity:t,...fileFields(n),verifiedAt:i.verifiedAt,facts:i.facts,identity:i.identity});return r.writeFileSync(a,JSON.stringify({payload:c,checksum:checksum(c)})),!0}catch{try{invalidateSqliteCleanCloseSeal(e)}catch{}return!1}}var ry,iy=__esmMin((()=>{D(),H(),qv(),ry=6048e5}));function resolveSqliteDatabaseFilePath(e){if(!e.startsWith(`file:`))return e;let[t=``]=e.slice(5).split(/[?#]/u,1);return t.startsWith(`/`)?Ie(e):decodeURIComponent(t)}function createSqliteDatabaseDescriptorOwner(e){function prepareSqliteDatabaseAdmissionAsync(t){let n=resolveAdmissionTarget(t.location,t.create!==void 0);if(!n)return Promise.resolve(void 0);let{filename:i,create:a}=n,s=t.identity,prepare=async()=>{t.assertCurrent();let n=s??await inspectDatabasePathIdentity(i);if(s=void 0,t.assertCurrent(),!n)return;if(t.expectedIdentity&&(n.key!==t.expectedIdentity.key||t.expectedIdentity.birthtime!==void 0&&n.birthtime!==t.expectedIdentity.birthtime))throw Error(`SQLite Worker path no longer matches its borrowed native owner`);let c=n.key.startsWith(`file:`),l=!c&&a?t.create:void 0;if(!c&&!l)return n;let u=`${n.key.slice(5)}:${n.birthtime}`;if(t.observedLocation&&t.observedLocation.identity!==u)throw Error(`SQLite database changed while retaining its admission identity`);if(E!==0){if(l)throw Error(`SQLite descriptor creation belongs to the host`);return pathAdmission(i,u),t.assertCurrent(),n}let d=c?K.registry.descriptors.get(u):void 0;if(d&&(assertDatabaseFileIdentity(d.file,n),retainPreparedSqliteDatabaseAdmissionLocation(i,void 0,{identity:u,canonicalPath:n.canonicalPath})))return n;let f,p;if(d)f=d.descriptor,p=d.file;else{l&&await l.authorize(n.canonicalPath),t.assertCurrent();let e=l?createDeferredCore():void 0;e&&l?.retain(e.promise);let a;try{a=await new Promise((e,t)=>{r.open(i,l?`wx`:`r`,420,(n,r)=>n?t(n):e(r))}),f=a,p=await new Promise((e,t)=>{r.fstat(f,{bigint:!0},(n,r)=>n?t(n):e(r))}),c&&assertDatabaseFileIdentity(p,n),K.registry.retainDescriptorCustody(f,p),e?.resolve()}catch(t){if(a===void 0){if(e?.resolve(),l&&w(t,`EEXIST`))return prepare()}else e?.reject(t);throw t}}let m=c?n:{key:`file:${p.dev}:${p.ino}`,canonicalPath:n.canonicalPath,birthtime:readDatabaseIdentityBirthtime(p)},h,g=c?await readSqliteCleanCloseSealAsync(n.canonicalPath,p,e=>{h=e}):void 0,v=await inspectDatabasePathIdentity(i);if(!v||v.key!==m.key||v.birthtime!==m.birthtime||v.canonicalPath!==m.canonicalPath)throw Error(`SQLite database changed identity during admission`);t.assertCurrent();let y=K.registry.records.get(readSqliteDatabaseAdmissionIdentity(p)),b=y&&!isSqliteDatabaseAdmissionRetired(y)?y:K.registry.retainDescriptor(m.canonicalPath,K.registry.descriptors.get(readSqliteDatabaseAdmissionIdentity(p))?.descriptor??f,p);return K.registry.observeLocation(i,b.identity),c?e.load(b,{seal:g,refusal:h}):e.markLoaded(b),m},c=K.descriptorPreparation.then(prepare);return K.descriptorPreparation=c.then(()=>{},()=>{}),c}function retainPreparedSqliteDatabaseAdmissionLocation(t,n,r){let i=!r&&K.registry.forLocation(t),a=i&&K.registry.descriptors.get(i.identity);if(i&&n?.birthtime!==void 0&&i.physicalIdentity.key===n.key&&i.physicalIdentity.birthtime===n.birthtime&&a&&a.descriptor===i.descriptor&&e.isLoaded(a))return e.load(i),!0;let s=r&&K.registry.descriptors.get(r.identity);if(r&&s&&e.isLoaded(s)){n&&assertDatabaseFileIdentity(s.file,n);let i=K.registry.records.get(r.identity),a=i&&!isSqliteDatabaseAdmissionRetired(i)?i:K.registry.retainDescriptor(r.canonicalPath,s.descriptor,s.file);return K.registry.observeLocation(t,a.identity),e.markLoaded(a),!0}return!1}function retainSqliteDatabaseAdmissionLocation(t,n,i){if(retainPreparedSqliteDatabaseAdmissionLocation(t,n,i))return;let a=r.statSync(t,{bigint:!0});if(!a.isFile())return;let s=readSqliteDatabaseAdmissionIdentity(a),c=K.registry.records.get(s);if(c&&!isSqliteDatabaseAdmissionRetired(c)){K.registry.observeLocation(t,s),e.load(c);return}if(E!==0)return;let l=K.registry.descriptors.get(s)?.descriptor??r.openSync(t,`r`),u=r.fstatSync(l,{bigint:!0});if(!u.isFile()||readSqliteDatabaseAdmissionIdentity(u)!==s)throw Error(`SQLite database changed while retaining its admission identity`);let d=K.registry.retainDescriptor(r.realpathSync.native(t),l,u);K.registry.observeLocation(t,d.identity),e.load(d)}function pathAdmission(t,n){try{let i=K.registry.forLocation(t);if(!i){let e=n;if(e===void 0&&E!==0){let n=r.statSync(t,{bigint:!0});if(!n.isFile())return;e=readSqliteDatabaseAdmissionIdentity(n)}exchangeSqliteDatabaseAdmission(t,void 0,!1,e!==void 0&&E!==0?{identity:e,canonicalPath:r.realpathSync.native(t)}:void 0),i=K.registry.forLocation(t)}return i?(e.load(i),i):(retainSqliteDatabaseAdmissionLocation(t),K.registry.forLocation(t))}catch(e){if(w(e,`ENOENT`))return;throw e}}function resolveAdmissionTarget(e,t){let n=e,r=t;if(n&&n!==`:memory:`){if(n.startsWith(`file:`)){let e=new URL(n);if(e.searchParams.get(`mode`)===`memory`||([`ro`,`rw`].includes(e.searchParams.get(`mode`)??``)&&(r=!1),n=resolveSqliteDatabaseFilePath(n),!n||n===`:memory:`))return}return{filename:n,create:r}}}function prepareSqliteDatabaseAdmission(t,n={}){let i=resolveAdmissionTarget(t,n.create);if(!i)return;let{filename:a,create:s}=i;try{let e=r.statSync(a,{bigint:!0});if(!e.isFile()){K.registry.observeLocation(a,void 0);return}let t=readSqliteDatabaseAdmissionIdentity(e);return K.registry.observeLocation(a,t),t}catch(t){if(w(t,`ENOENT`)){if(K.registry.observeLocation(a,void 0),!s)return;if(E!==0){let e=K.exchange.getStore()!==void 0;exchangeSqliteDatabaseAdmission(a,!0);let n=prepareSqliteDatabaseAdmission(a);if(e&&n===void 0)throw Error(`SQLite worker file creation requires host authority: ${a}`,{cause:t});return n}let n;try{n=r.openSync(a,`wx`,420)}catch(e){if(w(e,`EEXIST`))return prepareSqliteDatabaseAdmission(a);throw e}let i=r.fstatSync(n,{bigint:!0}),c=K.registry.retainDescriptor(r.realpathSync.native(a),n,i);if(e.markLoaded(c),prepareSqliteDatabaseAdmission(a)!==c.identity)throw Error(`SQLite database changed identity during file creation`,{cause:t});return c.identity}throw t}}return{prepareSqliteDatabaseAdmissionAsync,retainSqliteDatabaseAdmissionLocation,prepareSqliteDatabaseAdmission,pathAdmission}}var ay=__esmMin((()=>{It(),H(),iy(),ny(),ey(),qv()}));function getSqliteNativeAdmissionFacts(e){return oy.operations.get(e)?.facts}function beginSqliteDatabaseAdmissionOperation(e){let t=oy.operations.get(e)??{depth:0,facts:/* @__PURE__ */ new Map};return t.depth+=1,oy.operations.set(e,t),()=>{--t.depth,t.depth===0&&oy.operations.delete(e)}}var oy,sy=__esmMin((()=>{B(),oy=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeAdmissions`),()=>({operations:/* @__PURE__ */ new WeakMap}))}));function createSqliteDatabaseAdmissionReader(e){let{state:t,admission:n,pathAdmission:r,exchange:i,retain:a,release:s,publishFact:c}=e;function withPathAdmission(e,t){let n=r(e);if(!n)return t(void 0);try{return a(n),t(n)}finally{s(n)}}function getSqliteDatabaseAdmission(e,r,a={}){let s=sqlPublicationAnchor(e);if(!s.isOpen||t.suspended.has(s))return;let c=n(s,a.existingOnly!==!0&&!e.isTransaction);if(!c)return;let l=(isPostgresSqlConnection(e)?void 0:getSqliteNativeAdmissionFacts(e))?.get(r.name)??t.local.get(s)?.get(r.name);if(l&&l.revision===readSqliteDatabaseFactRevision(c,l.schemaDependent)&&(!l.schemaDependent||l.ddlRevision===(t.ddlRevisions.get(s)??0)))return readSqliteDatabaseAdmissionFact(l,r);if(r.schemaDependent&&t.schemaDirty.has(s))return;if(t.rolledBack.has(s)){if(e.isTransaction)return;t.rolledBack.delete(s)}let u=c.facts.get(r.name);if(!u||!isSqliteDatabaseAdmissionFactCurrent(c,u)||a.refresh&&r.writer!==`host`){if(r.writer===`host`)return e.isTransaction||E===0||c.hostRevision===readSqliteDatabaseGeneration(c,`hostRevision`)?void 0:(i(c),u=c.facts.get(r.name),u&&isSqliteDatabaseAdmissionFactCurrent(c,u)?readSqliteDatabaseAdmissionFact(u,r):void 0);let n=readSqliteDatabaseGeneration(c,`publicationRevision`),s=t.misses.get(c)??/* @__PURE__ */ new Map;t.misses.set(c,s),r.writer!==`connection`&&!e.isTransaction&&(a.refresh||s.get(r.name)!==n)&&(i(c),u=c.facts.get(r.name),s.set(r.name,readSqliteDatabaseGeneration(c,`publicationRevision`)))}return u&&isSqliteDatabaseAdmissionFactCurrent(c,u)?readSqliteDatabaseAdmissionFact(u,r):void 0}function getOrLoadSqliteDatabaseAdmissionForPath(e,t,n){let read=e=>{if(!e)return n();let r=e.facts.get(t.name),i=r&&isSqliteDatabaseAdmissionFactCurrent(e,r)?readSqliteDatabaseAdmissionFact(r,t):void 0;if(i!==void 0)return i;let a=readSqliteDatabaseFactRevision(e,t.schemaDependent),s=n();return s!==void 0&&c(e,t,admitSqliteDatabaseFactValue(t,s),a),s};return t.lifetime===`process`?withPathAdmission(e,read):read(r(e))}function peekSqliteDatabaseAdmissionForPath(e,n){let r=t.registry.forLocation(e),i=r?.facts.get(n.name);return r&&i&&isSqliteDatabaseAdmissionFactCurrent(r,i)?readSqliteDatabaseAdmissionFact(i,n):void 0}function prepareSqliteDatabaseAdmissionForPath(e,t){let n=r(e);if(!n)return()=>void 0;let i=new Int32Array(n.generation),a=t.schemaDependent?Jv.schemaRevision:Jv.factRevision,s=n.facts.get(t.name),c=s&&new Int32Array(s.current);return()=>{if(Atomics.load(i,Jv.retired)!==0)return;let e=n.facts.get(t.name);return e!==s&&(s=e,c=s&&new Int32Array(s.current)),s&&c&&Atomics.load(c,0)===1&&s.revision===Atomics.load(i,a)?readSqliteDatabaseAdmissionFact(s,t):void 0}}function getSqliteDatabaseSchemaRevision(e,r={}){let i=sqlPublicationAnchor(e),a=n(i,r.existingOnly!==!0);if(a)return readSqliteDatabaseGeneration(a,`schemaRevision`);let s=t.openedIdentities.get(i);return s?t.localSchemaRevisions.get(s)??0:void 0}function hasSqliteDatabaseSchemaAdmissionForPath(e){return hasSqliteDatabaseSchemaAdmission(r(e))}function getSqliteDatabaseAdmissionIdentityForPath(e){return t.registry.forLocation(e)?.physicalIdentity}function hasSqliteDatabaseSchemaAdmissionForIdentity(e){return t.registry.hasSchemaAdmissionForIdentity(e)}return{getSqliteDatabaseAdmission,getSqliteDatabaseSchemaRevision,getOrLoadSqliteDatabaseAdmissionForPath,peekSqliteDatabaseAdmissionForPath,prepareSqliteDatabaseAdmissionForPath,hasSqliteDatabaseSchemaAdmissionForPath,getSqliteDatabaseAdmissionIdentityForPath,hasSqliteDatabaseSchemaAdmissionForIdentity}}var cy=__esmMin((()=>{gu(),ey(),sy()}));function extractSqliteTableSchema(e,t,n={}){let r=e.indexOf(`CREATE TABLE IF NOT EXISTS ${t} (`),i=n.endMarker??e.slice(r).match(/\n\) STRICT(?:, WITHOUT ROWID)?;/u)?.[0],a=i?e.indexOf(i,r):-1;if(r<0||!i||a<r)throw Error(n.errorMessage??`Canonical schema markers are missing for ${t}`);return e.slice(r,a+(n.includeEndMarker===!1?0:i.length))}function readTableConstraintKeyword(e,t){let n=t;if(n.keyword===`CONSTRAINT`){let t=readSqlToken(e,n.end);n=t?readSqlToken(e,t.end):null}return n?.keyword&&ly.has(n.keyword)?n.keyword:null}function readSqlToken(e,t){let n=t;for(;n<e.length&&/\s/u.test(e[n]??``);)n+=1;let r=e[n];if(!r)return null;if(r===`"`||r==="`"||r===`[`){let t=skipSqlQuoted(e,n,r);return{end:t,keyword:null,raw:e.slice(n,t)}}let i=n;for(;i<e.length&&!/[\s(,]/u.test(e[i]??``);)i+=1;let a=e.slice(n,i);return{end:i,keyword:a.toUpperCase(),raw:a}}function normalizeSqlIdentifier(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1).replaceAll(`""`,`"`).toLowerCase():e.startsWith("`")&&e.endsWith("`")?e.slice(1,-1).replaceAll("``","`").toLowerCase():e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1).toLowerCase():e.toLowerCase()}function normalizeSchemaSql(e){return e===null?null:normalizeSqlWhitespace(e).replace(/;\s*$/u,``).trim().replace(/^(CREATE (?:TABLE|VIRTUAL TABLE|UNIQUE INDEX|INDEX|TRIGGER)) IF NOT EXISTS /iu,`$1 `)}function splitSqlList(e){let t=[],n=0,r=0;for(let i of unquotedSqlIndexes(e,0)){let a=e[i];a===`(`?n+=1:a===`)`?--n:a===`,`&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function findSqlCharacter(e,t){for(let n of unquotedSqlIndexes(e,0))if(e[n]===t)return n;return-1}function hasUnquotedSqlKeyword(e,t){let n=/* @__PURE__ */ new Set;for(let r of e.matchAll(t))n.add(r.index);if(n.size===0)return!1;for(let t of unquotedSqlIndexes(e,0))if(n.has(t))return!0;return!1}function findSqlClosingParenthesis(e,t){let n=0;for(let r of unquotedSqlIndexes(e,t)){let t=e[r];if(t===`(`)n+=1;else if(t===`)`&&(--n,n===0))return r}throw Error(`SQLite schema contains an unterminated table definition.`)}function normalizeSqlWhitespace(e){let t=``,n=!1,r=/[^\s'"`[/-]+|\s+|./gsu,i;for(;i=r.exec(e);){let a=i.index,s=i[0][0]??``,c=skipSqlQuoted(e,a,s),l=i[0];if(c!==a)l=e.slice(a,c),r.lastIndex=c;else{let t=skipSqlComment(e,a);if(t!==a){n=!0,r.lastIndex=t;continue}if(/\s/u.test(s)){n=!0;continue}}n&&t.length>0&&(t+=` `),t+=l,n=!1}return t.trim()}function quoteSqliteIdentifier(e){return`"${e.replaceAll(`"`,`""`)}"`}function*unquotedSqlIndexes(e,t){let n=t;for(;n<e.length;){let t=skipSqlQuoted(e,n,e[n]??``),r=t===n?skipSqlComment(e,n):t;r===n?(yield n,n+=1):n=r}}function skipSqlQuoted(e,t,n){if(n!==`'`&&n!==`"`&&n!=="`"&&n!==`[`)return t;let r=n===`[`?`]`:n,i=t+1;for(;i<e.length;)if(e[i]!==r)i+=1;else if(n!==`[`&&e[i+1]===r)i+=2;else return i+1;return e.length}function skipSqlComment(e,t){if(e.startsWith(`--`,t)){let n=e.indexOf(`
`,t+2);return n===-1?e.length:n+1}if(e.startsWith(`/*`,t)){let n=e.indexOf(`*/`,t+2);return n===-1?e.length:n+2}return t}var ly,uy=__esmMin((()=>{ly=/* @__PURE__ */ new Set([`CHECK`,`FOREIGN`,`PRIMARY`,`UNIQUE`])}));function createSqliteTableContract(e,t,n,r,i,a,s){let c=i.map(e=>({name:e.name,sql:normalizeSchemaSql(e.sql)})),l=t.sql?.startsWith(`CREATE TABLE `)?null:normalizeSchemaSql(t.sql),u=l!==null&&/^CREATE VIRTUAL TABLE /iu.test(l);return{definition:u?null:parseSqliteTableDefinition(t.sql,e),indexes:r,columns:a,foreignKeys:s,strict:n.strict,triggers:c,virtualTableSql:u?l:null,withoutRowid:n.wr}}function createSqliteIndexContract(e,t,n){let r=n.map(({cid:e,coll:t,desc:n,key:r,name:i,seqno:a})=>({coll:t,desc:n,key:r,kind:e===-2?`expression`:e===-1?`rowid`:`column`,name:i,seqno:a}));return{name:e.name.startsWith(`sqlite_autoindex_`)?null:e.name,origin:e.origin,partial:e.partial,sql:normalizeSchemaSql(t),terms:r,unique:e.unique}}function parseSqliteTableDefinition(e,t){if(e===null)throw Error(`Could not inspect SQLite table definition for ${t}.`);let n=findSqlCharacter(e,`(`);if(n===-1)throw Error(`SQLite table ${t} has no column definition.`);let r=findSqlClosingParenthesis(e,n),i=/* @__PURE__ */ new Map,a=[];for(let s of splitSqlList(e.slice(n+1,r))){let e=normalizeSqlWhitespace(s);if(!e)continue;let n=readSqlToken(e,0);if(!n)throw Error(`SQLite table ${t} contains an unreadable definition.`);if(readTableConstraintKeyword(e,n)){a.push(e);continue}let r=normalizeSqlIdentifier(n.raw);if(i.has(r))throw Error(`SQLite table ${t} contains duplicate column ${r}.`);i.set(r,e)}return{columns:new Map([...i].toSorted(([e],[t])=>e.localeCompare(t))),constraints:a.toSorted()}}var dy=__esmMin((()=>{uy()}));function hasPendingAgentStartupColumns(e){let t=/* @__PURE__ */ new Map;return py.some(({tableName:n,columnName:r})=>{if(!e.has(n))return!1;let i=e.get(n);if(!i)return!0;let a=t.get(n);return a||(a=parseSqliteTableDefinition(i,n).columns,t.set(n,a)),!a.has(r)})}var fy,py,my=__esmMin((()=>{dy(),fy=[{columnName:`owner_actor_type`,dataType:`TEXT`,tableName:`session_nodes`},{columnName:`owner_actor_id`,dataType:`TEXT`,tableName:`session_nodes`},{columnName:`owner_assigned_by_type`,dataType:`TEXT`,tableName:`session_nodes`},{columnName:`owner_assigned_by_id`,dataType:`TEXT`,tableName:`session_nodes`},{columnName:`owner_assigned_at`,dataType:`INTEGER`,tableName:`session_nodes`}],[...fy],py=[{tableName:`session_pending_inputs`,columnName:`consumed_event_id`,dataType:`TEXT`},{tableName:`session_transcript_active_events`,columnName:`context_eligible`,dataType:`INTEGER`},{tableName:`session_nodes`,columnName:`project_id`,dataType:`TEXT`},{tableName:`session_windows`,columnName:`row_transcript_json`,dataType:`TEXT`},{tableName:`session_windows`,columnName:`row_transcript_updated_at`,dataType:`INTEGER`},{tableName:`session_conversations`,columnName:`route_context_json`,dataType:`TEXT`}]})),hy,gy,_y=__esmMin((()=>{hy=1e4,gy=1e3}));function getCliParentPid(){return globalThis[vy]?.pid}function requestCliParentTermination(e=()=>{process.emit(`SIGTERM`)||process.kill(process.pid,`SIGTERM`)}){xy||(xy=!0,setTimeout(()=>process.kill(process.pid,`SIGKILL`),hy).unref(),e())}var vy,yy,by,xy,Sy=__esmMin((()=>{_y(),vy=Symbol.for(`openclaw.cliRespawnParent`),yy=`OPENCLAW_CLI_RESPAWN_PARENT`,by=process.env[yy],delete process.env[yy],by===String(process.ppid)&&(globalThis[vy]={pid:process.ppid}),xy=!1}));function parseNodeOptionsEnvVar(e){let t=[],n=``,r=!1,i=e??``;for(let e=0;e<i.length;e+=1){let a=i.charAt(e);if(a===`\\`&&r){if(e+=1,e>=i.length)return null;a=i.charAt(e)}else if(a===` `&&!r){n.length>0&&(t.push(n),n=``);continue}else if(a===`"`){r=!r;continue}n+=a}return r?null:(n.length>0&&t.push(n),t)}function isNodeStartupHook(e){return/^(?:--(?:import|require|(?:experimental-)?loader)(?:=|$)|-r)/u.test(e.replaceAll(`_`,`-`))}function hasNodeStartupHooks(e,t){let n=parseNodeOptionsEnvVar(t);return n===null||[...e,...n].some(isNodeStartupHook)}var Cy=__esmMin((()=>{}));function readStandaloneRuntimeManifest(e=process.execPath){return readStandaloneManifest({executable:e})}function projectStandaloneBuildInfo(e){let nonBlank=e=>typeof e==`string`&&e.trim().length>0,stringList=e=>Array.isArray(e)&&e.every(nonBlank),t={mode:e.mode,openclaw:{version:e.openclaw.version,...nonBlank(e.openclaw.commit)?{commit:e.openclaw.commit}:{}},bun:{version:e.bun.version}};for(let n of[`revision`,`commit`,`executableSha256`])nonBlank(e.bun[n])&&(t.bun[n]=e.bun[n]);if(e.build!==void 0){let{id:n,flavor:r,pluginSetSha256:i,moduleGraphSha256:a}=e.build;if(!nonBlank(n)||![`standard`,`support`].includes(r)||!/^[a-f0-9]{64}$/.test(i)||!/^[a-f0-9]{64}$/.test(a))throw Error(`Invalid standalone build provenance`);if(t.build={id:n,flavor:r,pluginSetSha256:i,moduleGraphSha256:a},e.build.debugEntry!==void 0){let n=e.build.debugEntry;if(typeof n!=`string`||!n.startsWith(`debug/`)||n.includes(`\\`)||n.split(`/`).some(e=>!e||e===`.`||e===`..`))throw Error(`Invalid standalone debugger entry`);t.build.debugEntry=n}}if(e.target!==void 0){if(!nonBlank(e.target.platform)||!nonBlank(e.target.arch))throw Error(`Invalid standalone build target`);t.target={platform:e.target.platform,arch:e.target.arch}}if(e.plugins!==void 0){if(!stringList(e.plugins.embedded)||!stringList(e.plugins.omitted))throw Error(`Invalid standalone plugin inventory`);t.plugins={embedded:[...e.plugins.embedded],omitted:[...e.plugins.omitted]}}if(e.nativeModules!==void 0){if(!Array.isArray(e.nativeModules)||e.nativeModules.some(e=>!e||!nonBlank(e.name)||!nonBlank(e.version)||!stringList(e.artifacts)||e.qualification!==`unverified`||!nonBlank(e.backend)))throw Error(`Invalid standalone native inventory`);t.nativeModules=e.nativeModules.map(({name:e,version:t,artifacts:n,qualification:r,backend:i})=>({name:e,version:t,artifacts:[...n],qualification:r,backend:i}))}return t}function readStandaloneManifest({executable:e,runtimeRoot:t,includeBuild:n=!1}){let r=e??t;if(!S.isAbsolute(r))return;let i=S.dirname(r),a=S.join(i,`manifest.json`),s;try{s=f(a,`utf8`)}catch(e){if(e?.code===`ENOENT`||e?.code===`ENOTDIR`)return;throw e}let c;try{c=JSON.parse(s)}catch(e){throw Error(`Invalid standalone runtime manifest: ${a}`,{cause:e})}let nonBlank=e=>typeof e==`string`&&e.trim().length>0;if(c?.schemaVersion!==1||![`jit`,`bytecode`,`aot`].includes(c.mode)||!nonBlank(c.executable?.path)||!nonBlank(c.runtime?.path)||!nonBlank(c.openclaw?.version)||!nonBlank(c.bun?.version))throw Error(`Invalid standalone runtime manifest: ${a}`);let l=S.relative(i,S.resolve(i,c.executable.path)),u=S.relative(i,S.resolve(i,c.runtime.path));if(S.isAbsolute(c.executable.path)||!l||l===`..`||l.startsWith(`..${S.sep}`)||e&&S.resolve(i,c.executable.path)!==S.resolve(e)||t&&S.resolve(i,c.runtime.path)!==S.resolve(t)||S.isAbsolute(c.runtime.path)||!u||u===`..`||u.startsWith(`..${S.sep}`))throw Error(`Invalid standalone runtime manifest: ${a}`);return{schemaVersion:1,mode:c.mode,executable:{path:c.executable.path,...nonBlank(c.executable.sha256)?{sha256:c.executable.sha256}:{}},runtime:{path:c.runtime.path,...nonBlank(c.runtime.sha256)?{sha256:c.runtime.sha256}:{}},openclaw:{version:c.openclaw.version,...nonBlank(c.openclaw.commit)?{commit:c.openclaw.commit}:{}},bun:{version:c.bun.version},...n?projectStandaloneBuildInfo(c):{}}}function getEmbeddedStandaloneRuntimeRoot(){let e=globalThis.__openclawStandaloneRootUrl;return typeof e==`string`?Ie(e):void 0}function isEmbeddedStandaloneModule(e){let t=e.startsWith(`file:`)?Ie(e):e;return globalThis.__openclawStandaloneIsEmbeddedModule?.(t)===!0}function resolveStandaloneSidecarRoot(e=process.execPath){if(e===process.execPath){let e=getEmbeddedStandaloneRuntimeRoot();if(e!==void 0)return e}let t=readStandaloneRuntimeManifest(e);return t?S.resolve(S.dirname(e),t.runtime.path):void 0}function isStandaloneRuntimeExecutable(e=process.execPath){return resolveStandaloneSidecarRoot(e)!==void 0}function runtimeHasSourceLoader(){return process.env.BUN_BE_BUN!==`1`&&isStandaloneRuntimeExecutable()?!1:hasNodeStartupHooks(process.execArgv,process.env.NODE_OPTIONS)}function resolveRuntimeScriptEnv(e){return isStandaloneRuntimeExecutable()?{...e,BUN_BE_BUN:`1`}:{...e}}var wy=__esmMin((()=>{Sy(),Cy()})),Ty,Ey=__esmMin((()=>{Ty=`import{createRequire}from"node:module";try{const candidate=process.argv[2];if(!candidate||process.argv.length!==3){throw new Error("Expected one SQLite library path")}const require2=createRequire(import.meta.url);const{Database}=require2("bun:sqlite");Database.setCustomSQLite(candidate);const database=new Database(":memory:");let facts;try{facts=database.query("SELECT sqlite_version() AS version, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted").get()}finally{database.close()}process.stdout.write(JSON.stringify({protocol:1,version:facts.version,extensionLoadingSupported:facts.omitted===0}))}catch(error){process.stdout.write(JSON.stringify({protocol:1,error:(error instanceof Error?error.message:String(error)).slice(0,512)}));process.exitCode=1}
`}));function materializeRuntimeProcessScriptFile(e,t={}){let n=r.mkdtempSync(S.join(t.parentDirectory??Xe.tmpdir(),`openclaw-script-`)),i=S.join(n,e.fileName),a=!1,dispose=()=>{if(!a)try{r.rmSync(n,{recursive:!0,force:!0}),a=!0}catch(e){process.emitWarning(`Runtime script cleanup failed at ${n}: ${e instanceof Error?e.message:String(e)}`)}};try{return r.writeFileSync(i,e.source,{mode:384,flag:`wx`}),{url:Le(i),dispose}}catch(e){throw dispose(),e}}var Dy=__esmMin((()=>{}));function probeBunSqliteLibrary(e){let t=materializeRuntimeProcessScriptFile({fileName:cf.bunSqliteLibraryProbe.fileName,source:Ty});try{let n=Ie(t.url),i=S.dirname(n),a=S.join(i,`bunfig.toml`);r.writeFileSync(a,``,{mode:384,flag:`wx`});let s={};for(let e of[`SystemRoot`,`SYSTEMROOT`,`WINDIR`,`TEMP`,`TMP`,`TMPDIR`])process.env[e]&&(s[e]=process.env[e]);let c=re(process.execPath,[`--no-install`,`--no-env-file`,`--config=${a}`,n,S.resolve(e)],{cwd:i,env:resolveRuntimeScriptEnv(s),encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,killSignal:`SIGKILL`,maxBuffer:4096});if(c.error)throw c.error;let l;try{l=JSON.parse(c.stdout)}catch{throw Error(`SQLite library probe returned invalid output`)}if(typeof l!=`object`||!l||Array.isArray(l)||!(`protocol`in l)||l.protocol!==1)throw Error(`SQLite library probe returned invalid output`);if(c.status!==0)throw Error(`error`in l&&typeof l.error==`string`?l.error.slice(0,512):`SQLite library probe failed (${c.signal??c.status})`);if(!(`version`in l)||typeof l.version!=`string`||l.version.length>64||!(`extensionLoadingSupported`in l)||typeof l.extensionLoadingSupported!=`boolean`)throw Error(`SQLite library probe returned invalid output`);return{version:l.version,extensionLoadingSupported:l.extensionLoadingSupported}}finally{t.dispose()}}var Oy=__esmMin((()=>{wy(),Ey(),lf(),Dy()}));function readProcessMachineIdentity(){let e=it(ky);return e?.platform!==process.platform&&(e={platform:process.platform,value:probeMachineIdentity()},ct(ky,e)),e.value}function probeMachineIdentity(){try{let e;if(process.platform===`linux`){let t=f(`/etc/machine-id`,`utf8`).trim();/^[a-f0-9]{32}$/u.test(t)&&(e=t)}else if(process.platform===`darwin`){let t=re(`/usr/sbin/ioreg`,[`-rd1`,`-c`,`IOPlatformExpertDevice`],{encoding:`utf8`,timeout:1e3,maxBuffer:65536,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]}),n=[...(t.stdout??``).matchAll(/"IOPlatformUUID"\s*=\s*"([^"]+)"/gu)],r=n.length===1?n[0]?.[1]?.toLowerCase():void 0;!t.error&&t.status===0&&r&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(r)&&(e=r)}return!e||/^0+$/u.test(e.replaceAll(`-`,``))?null:be(`sha256`,`openclaw:state-lease-process-owner:machine:v1`).update(`${process.platform}\0${e}`).digest(`hex`)}catch{return null}}var ky,Ay=__esmMin((()=>{ky=`openclaw.processMachineIdentity`}));function isSqliteWalResetSafeVersion(e){let t=/^(\d+)\.(\d+)\.(\d+)$/u.exec(e.trim());if(!t)return!1;let[n,r,i]=t.slice(1).map(Number);return[n,r,i].every(Number.isSafeInteger)?n>3||n===3&&(r>51||r===51&&i>=3||r===50&&i>=7||r===44&&i>=6):!1}var jy=__esmMin((()=>{})),My=__esmMin((()=>{jy()})),Ny,Py,Fy=__esmMin((()=>{lf(),Ny=`--openclaw-sqlite-readonly-child`,Py=createRuntimeProcessEntrypoints(import.meta.url)}));function resolveRuntimeProcessDistRoot(e){let t=e.replaceAll(S.sep,`/`).lastIndexOf(`/dist/`);return t>=0?e.slice(0,t+6):void 0}var Iy=__esmMin((()=>{resolveRuntimeProcessDistRoot(Ie(import.meta.url))}));function normalizeRuntimeBasename(e){let t=e.trim().replace(/^["']|["']$/g,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return(n===-1?t:t.slice(n+1)).trim().toLowerCase()}function isNodeRuntime(e){let t=normalizeRuntimeBasename(e);return/^node(?:js)?(?:\.exe)?$/.test(t)||Ly.test(t)}function isBunRuntime(e){let t=normalizeRuntimeBasename(e);return t===`bun`||t===`bun.exe`}function resolveRuntimeScriptPosition(e){let t=[],n=e[0]??``,r=n.replaceAll(`\\`,`/`).trim().toLowerCase().split(`/`).at(-1),i=isBunRuntime(n),a=r===`tsx`||r===`tsx.cmd`,s=i?`run`:a?`watch`:void 0,c,l=[];if(!isNodeRuntime(n)&&!i&&!a)return{position:{kind:`not-runtime`},operands:t,sourceIndices:l};for(let n=1;n<e.length;n++){let r=e[n];if(r===`--`){if(!c)return{position:l.length===0&&e[n+1]?n+1:{kind:`other`},operands:t,sourceIndices:l};t.push(...e.slice(n+1).map(e=>({value:e,module:!1})));break}if(r===`-e`||r===`-p`||/^--(?:eval|print|run)(?:=|$)/.test(r)){r.includes(`=`)||n++,l.push(n);continue}let a=r.indexOf(`=`),u=a<0?r:r.slice(0,a);if(r.startsWith(`-r`)&&!r.startsWith(`--`)&&r.length>2)t.push({value:r.slice(2),module:!0});else if(zy.has(u)){let s=a<0?e[++n]??``:r.slice(a+1),c=!i&&u===`--test-reporter`&&/^(?:dot|spec|tap)$/.test(s);Ry.has(u)&&!c&&(!i||u!==`--loader`)&&t.push({value:s,module:!0})}else if(r.startsWith(`-`)){let e=`--no-${u.replace(/^--(?:no-)?/,``)}`,n=!i&&process.allowedNodeEnvironmentFlags.has(u),s=By.has(u)||i&&(u===`--hot`||u===`--no-install`)||n&&process.allowedNodeEnvironmentFlags.has(e);l.length===0&&!s&&!/^--[^=]+=/.test(r)&&(c??={kind:`unclassified`,reason:`unsupported runtime option ${r}`}),a>=0&&!s&&!n&&t.push({value:r.slice(a+1),module:!0})}else if(l.length===0&&r===s)s=void 0;else if(l.length===0){if(!c)return{position:n,operands:t,sourceIndices:l};s=void 0,t.push({value:r,module:!1})}else break}return{position:c??{kind:`other`},operands:t,sourceIndices:c?[]:l}}var Ly,Ry,zy,By,Vy=__esmMin((()=>{Ly=/^node(?:-\d+|\d+)(?:\.\d+)*(?:\.exe)?$/,Ry=/* @__PURE__ */ new Set([`-r`,`--preload`,`--require`,`--import`,`--loader`,`--experimental-loader`,`--test-reporter`,`--test-global-setup`]),zy=/* @__PURE__ */ new Set([...Ry,`-C`,`--env-file`,`--env-file-if-exists`,`--tsconfig`,`--cwd`,`--conditions`,`--icu-data-dir`,`--openssl-config`,`--title`,`--disable-warning`,`--disable-proto`,`--cpu-prof-name`,`--max-old-space-size`,`--max-semi-space-size`]),By=/* @__PURE__ */ new Set([`--inspect`,`--inspect-brk`,`--inspect-wait`,`--expose-gc`,`--jitless`,`--no-opt`,`--experimental-strip-types`,`--watch`,`--no-warnings`,`--trace-uncaught`,`--bun`])}));function resolveRuntimeWorkerUrl(e){if(e.root!==void 0)return Le(S.join(e.root,`dist`,e.distWorkerPath));let t=Ie(e.currentModuleUrl),n=resolveRuntimeProcessDistRoot(t);if(n!==void 0){let t=e.distWorkerPath;if(e.package){let r=S.resolve(n,`..`),i=pt({rootDir:r,relativePath:`package.json`,boundaryLabel:`runtime worker package`,rejectHardlinks:!1});if(!i.ok)throw Error(`Cannot resolve runtime worker package: ${r}/package.json`);i.value.name===e.package.name&&(t=e.package.distWorkerPath)}return Le(S.join(n,t))}let r=e.sourceExtension??(S.extname(t)||`.js`);return new URL(`./${e.sourceWorkerName}${r}`,e.currentModuleUrl)}function isBunTargetRuntime(e){return e===process.execPath?!!process.versions.bun:isBunRuntime(e)}function resolveRuntimeArgs(e=process.execPath){return isBunTargetRuntime(e)?[`--no-install`]:[]}function runtimeNeedsTypeScriptLoader(e,t=process.execPath){return/\.[cm]?ts$/.test(e)&&!isBunTargetRuntime(t)}function resolveRuntimeWorkerArgv(e,t=process.execPath){let n=Ie(e);return runtimeNeedsTypeScriptLoader(n,t)?[`--import`,import.meta.resolve(`tsx`),n]:[...resolveRuntimeArgs(t),n]}function resolveRuntimeWorkerThreadExecArgv(e,t=process.execPath){return e.protocol===`file:`&&runtimeNeedsTypeScriptLoader(Ie(e),t)?[`--import`,import.meta.resolve(`tsx/esm`)]:[]}var Hy=__esmMin((()=>{wy(),Iy(),Vy()})),Uy=/* @__PURE__ */ __exportAll({probeSqliteNativeClose:()=>probeSqliteNativeClose});async function cleanupProbe(e,t,n){try{e&&(n&&e.unref(),await raceWithTimeout(e.terminate(),5e3,()=>{throw Error(`SQLite close check termination timed out after 5000ms`)},{ref:!n}),await dt(void 0,{ref:!n})),t&&await qe(t,{recursive:!0,force:!0})}catch(n){e?.unref();let r=`SQLite close check cleanup failed: ${String(n)}; retained ${t}`;return process.emitWarning(r,{code:`SQLITE_CLOSE_PROBE_CLEANUP`}),r}}async function probeSqliteNativeClose(){let e,t,n,r;try{e=await Ge(ue(Qe(),`openclaw-sqlite-close-`)),e=await Ke(e),Wy.publish({phase:`start`}),t=new rt(resolveRuntimeWorkerUrl(Py.sqliteCloseProbe),{workerData:e,execArgv:[]});let i=t;r=await new Promise((e,t)=>{i.once(`message`,n=>{typeof n==`string`?e({explicitSqliteCloseReleasesNativeResources:n===``,reason:n||`Native close check passed`}):t(/* @__PURE__ */ Error(`Invalid SQLite close check reply`))}),i.once(`error`,t),i.once(`exit`,e=>t(/* @__PURE__ */ Error(`SQLite close check exited before its reply (${e})`))),n=setTimeout(()=>t(/* @__PURE__ */ Error(`SQLite close check timed out after 10000ms`)),1e4)})}catch(e){r={explicitSqliteCloseReleasesNativeResources:!1,reason:String(e)}}finally{clearTimeout(n)}let i=!r.explicitSqliteCloseReleasesNativeResources,a=cleanupProbe(t,e,i);if(i)return r;let s=await a;return s?{explicitSqliteCloseReleasesNativeResources:!1,reason:s}:r}var Wy,Gy=__esmMin((()=>{Tp(),Fy(),Hy(),Wy=$e(`openclaw.sqlite.close-probe`)}));function createCapabilities(e){let t,n,r=0,i=Object.freeze({explicitSqliteCloseReleasesNativeResources:!1,decided:!1,reason:`SQLite close capability has not been decided`});function decide(e){return t||(t=Object.freeze(e),ct(qy,t),t.explicitSqliteCloseReleasesNativeResources&&r>0&&process.emitWarning(`SQLite close became capable after ${r} topology owners were created; those owners remain conservative`,{code:`SQLITE_EARLY_TOPOLOGY`})),t}function conservative(e){return{explicitSqliteCloseReleasesNativeResources:!1,decided:!0,reason:e}}function settled(){if(t)return t;if(!process.versions.bun)return decide({explicitSqliteCloseReleasesNativeResources:!0,decided:!0,reason:`Node runtime`});if(process.platform===`win32`)return decide(conservative(`Bun Windows native-close conformance is not qualified`));if(!at)return decide({...i,reason:`Parent did not complete SQLite close admission`,...it(qy)})}return{get(){return settled()??i},capture(){let e=settled()??i;return e.decided||(r+=1),e.explicitSqliteCloseReleasesNativeResources},initialize(){return n??=(async()=>{e();let t=settled();if(t)return t;try{if(parseDiagnosticEnvFlags(process.env.OPENCLAW_DIAGNOSTICS).flags.some(e=>e.toLowerCase()===`sqlite.close.conservative`))return decide(conservative(`SQLite close optimization disabled by internal diagnostic flag`));let{probeSqliteNativeClose:e}=await Promise.resolve().then(()=>(Gy(),Uy));return decide({...await e(),decided:!0})}catch(e){return decide(conservative(`SQLite close check failed: ${String(e)}`))}})(),n}}}function selectLibrary(t){let{Database:n}=e(import.meta.url)(`bun:sqlite`);n.setCustomSQLite(t)}function createSelector(){let e,t;return(n={})=>{if(t)throw t;if(e)return e;let r=n.explicitPath??(process.env.OPENCLAW_SQLITE_LIBRARY?.trim()||void 0);if(!process.versions.bun||process.platform!==`darwin`)return e=r?{source:`runtime`,ignoredOverride:`OPENCLAW_SQLITE_LIBRARY requires Bun on macOS`}:{source:`runtime`},e;let i=n.standaloneRoot??resolveStandaloneSidecarRoot(),a=r===void 0&&i!==void 0?de.join(i,`lib/libsqlite3.dylib`):void 0,s=process.env.HOMEBREW_PREFIX?.trim(),c=r===void 0?[.../* @__PURE__ */ new Set([...a?[a]:[],...s?[de.join(s,`opt/sqlite/lib/libsqlite3.dylib`)]:[],`/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib`,`/usr/local/opt/sqlite/lib/libsqlite3.dylib`,`/opt/local/lib/libsqlite3.dylib`])]:[r],u=[];for(let n of c){let i=r===void 0?n===a?`bundled`:`discovered`:`env`,s,c=!0;try{try{s=probeBunSqliteLibrary(n)}catch(e){throw c=l(n),c?e:Error(`missing file`,{cause:e})}if(!isSqliteWalResetSafeVersion(s.version))throw Error(`SQLite version ${s.version} below the WAL safety floor`);if(!s.extensionLoadingSupported)throw Error(`built with SQLITE_OMIT_LOAD_EXTENSION`)}catch(e){if(r===void 0){(c||n===a)&&u.push(`${n} (${e instanceof Error?e.message:String(e)})`);continue}throw t=selectionError(n,e,i===`bundled`),t}try{selectLibrary(n)}catch(e){throw t=selectionError(n,e,i===`bundled`),t}return e={source:i,path:n,version:s.version,extensionLoadingSupported:!0},e}throw t=/* @__PURE__ */ Error(`No supported SQLite library for Bun on macOS (${process.arch})`+(u.length>0?`; unusable: ${u.join(`, `)}`:``)+`. Apple's system SQLite fails OpenClaw's read-only database connections. `+(a?`Rebuild or replace the complete standalone artifact to restore its bundled SQLite library. `:``)+`Install one with brew install sqlite, or set OPENCLAW_SQLITE_LIBRARY to a libsqlite3.dylib built for ${process.arch}.`),t}}function selectionError(e,t,n=!1){let r=n?`Rebuild or replace the complete standalone artifact (openclaw and runtime/), or set OPENCLAW_SQLITE_LIBRARY to a supported library.`:`Fix or unset OPENCLAW_SQLITE_LIBRARY; install a supported library with brew install sqlite.`;return Error(`Cannot use ${n?`bundled `:``}SQLite library ${e}: ${t instanceof Error?t.message:String(t)}. ${r}`,{cause:t})}function createRuntimeSelector(){let e=!!process.versions.bun&&process.platform===`darwin`,t;e&&!at&&(t=it(Ky));let n=createSelector(),r=!1;return i=>{let a=t??n(i);return e&&at&&!r&&(ct(Ky,Object.freeze({...a})),r=!0),a}}function runtimeSelector(){return resolveGlobalSingleton(Symbol.for(`openclaw.bunSqliteLibrarySelection`),createRuntimeSelector)}function capabilities$1(){let e=runtimeSelector();return e.capabilities??=createCapabilities(e)}function getSqliteRuntimeCapabilities(){return capabilities$1().get()}function captureSqliteWorkerClosePolicy(){return capabilities$1().capture()}function ensureSqliteLibrarySelected(e){return runtimeSelector()(e)}var Ky,qy,Jy,Yy=__esmMin((()=>{wy(),B(),Oy(),Bd(),My(),Ky=`openclaw.bunSqliteLibrarySelection`,qy=`openclaw.sqliteRuntimeCapabilities`,Jy=`openclaw.sqliteNativeRuntimeAdmission`}));function formatErrorMessage(e){return formatErrorMessage$1(e,{redact:redactSensitiveText})}var Xy=__esmMin((()=>{O(),v_(),H()}));function compareValidSemver(e,t){let n=mt(e),r=mt(t);return n&&r?n.compare(r):null}var Zy=__esmMin((()=>{}));function shouldIgnoreWarning(e){return!!(e.code===`DEP0040`&&e.message?.includes(`punycode`)||e.code===`DEP0060`&&e.message?.includes(`util._extend`)||e.name===`ExperimentalWarning`&&e.message?.includes(`SQLite is an experimental feature`))}function normalizeWarningArgs(e){let t=e[0],n=e[1],r=e[2],i,a,s;return t instanceof Error?(i=t.name,s=t.message,a=t.code):typeof t==`string`&&(s=t),isRecord(n)?(typeof n.type==`string`&&(i=n.type),typeof n.code==`string`&&(a=n.code)):(typeof n==`string`&&(i=n),typeof r==`string`&&(a=r)),{name:i,code:a,message:s}}function installProcessWarningFilter(){let e=resolveGlobalSingleton(Qy,()=>({installed:!1}));if(e.installed)return;let t=process.emitWarning.bind(process),wrappedEmitWarning=((...e)=>{if(!shouldIgnoreWarning(normalizeWarningArgs(e))){if(e[0]instanceof Error&&isRecord(e[1])){let t=e[0],n=Object.assign(Error(t.message),{name:t.name,code:t.code});process.emit(`warning`,n)}else Reflect.apply(t,process,e)}});process.emitWarning=wrappedEmitWarning,e.installed=!0}var Qy,$y=__esmMin((()=>{D(),B(),Qy=Symbol.for(`openclaw.warning-filter`)}));function assertSqliteWalResetSafeVersion(e,t){if(isSqliteWalResetSafeVersion(e))return;let n=process.config.variables,r=n.node_shared_sqlite===!0||n.node_shared_sqlite===`true`;throw Error(`OpenClaw requires SQLite 3.51.3+, 3.50.7+ within 3.50.x, or 3.44.6+ within 3.44.x for WAL safety; Node ${t} ${r?`uses shared system`:`embeds`} SQLite ${e}, which is affected by the upstream WAL-reset database corruption bug. ${r?`Upgrade the system SQLite library to one of those safe versions, or use a Node build embedding a safe version.`:`Upgrade to Node 24.22.1+ or 26.12.1+ before retrying.`}`)}function sqliteNativeRuntimeIdentity(){return{pid:process.pid,executable:process.execPath,nodeVersion:process.versions.node,bunVersion:process.versions.bun,library:ensureSqliteLibrarySelected()}}function parseSqliteNativeRuntimeAdmission(e){if(!isRecord(e)||e.format!==1||typeof e.version!=`string`||typeof e.extensionLoadingSupported!=`boolean`)return;let t=sqliteNativeRuntimeIdentity();if(he(e.runtime,t))return{format:1,runtime:t,version:e.version,storageIdentity:isRecord(e.storageIdentity)&&typeof e.storageIdentity.sourceId==`string`&&typeof e.storageIdentity.compileOptions==`string`?{sourceId:e.storageIdentity.sourceId,compileOptions:e.storageIdentity.compileOptions}:void 0,extensionLoadingSupported:e.extensionLoadingSupported}}function safeSqliteNativeRuntimeAdmission(e){try{let t=parseSqliteNativeRuntimeAdmission(e);return t&&isSqliteWalResetSafeVersion(t.version)?t:void 0}catch{return}}function captureSqliteNativeRuntimeAdmission(){return safeSqliteNativeRuntimeAdmission(it(Jy))}function installSqliteNativeRuntimeAdmission(e){let t=safeSqliteNativeRuntimeAdmission(e);t&&ct(Jy,t)}function assertSafeSqliteRuntime(e){if(tb===e)return;let t=parseSqliteNativeRuntimeAdmission(it(Jy));if(t){assertSqliteWalResetSafeVersion(t.version,process.versions.node),rb=(compareValidSemver(t.version,`3.45.0`)??-1)>=0,nb=t.extensionLoadingSupported,tb=e;return}let n=new e.DatabaseSync(`:memory:`),r,i,a;try{let e=n.prepare(`SELECT sqlite_version() AS version, sqlite_source_id() AS sourceId, (SELECT group_concat(compile_options, ',') FROM (SELECT compile_options FROM pragma_compile_options ORDER BY compile_options)) AS compileOptions, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted`).get();r=typeof e?.version==`string`?e.version:`unknown`,assertSqliteWalResetSafeVersion(r,process.versions.node),typeof e?.sourceId==`string`&&e.sourceId&&typeof e.compileOptions==`string`&&(i={sourceId:e.sourceId,compileOptions:e.compileOptions}),a=e?.omitted===0}finally{n.close()}rb=(compareValidSemver(r,`3.45.0`)??-1)>=0,nb=a,tb=e,ct(Jy,{format:1,runtime:sqliteNativeRuntimeIdentity(),version:r,storageIdentity:i,extensionLoadingSupported:a})}function requireNodeSqlite(){installProcessWarningFilter();try{ensureSqliteLibrarySelected();let e=eb("node:sqlite");return assertSafeSqliteRuntime(e),e}catch(e){let t=formatErrorMessage(e);throw Error(`SQLite support is unavailable or unsafe in this Node runtime. ${t}`,{cause:e})}}var eb,tb,nb,rb,ib=__esmMin((()=>{D(),Yy(),Xy(),Zy(),My(),$y(),eb=e(import.meta.url)})),ab,ob=__esmMin((()=>{ab=`-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;
-- session_entry_snapshots owns keyed cold values. Promoted node columns are query
-- indexes; session_windows and their children own transcript generations.
-- Legacy ACP provenance is private import evidence carried with its logical session.

CREATE TABLE IF NOT EXISTS schema_meta (
  meta_key TEXT NOT NULL PRIMARY KEY,
  role TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  agent_id TEXT,
  app_version TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS session_nodes (
  session_key TEXT NOT NULL PRIMARY KEY,
  current_session_id TEXT NOT NULL,
  entry_json TEXT NOT NULL,
  session_started_at INTEGER,
  has_optional_references INTEGER NOT NULL DEFAULT 0,
  snapshot_revision INTEGER NOT NULL DEFAULT 0,
  legacy_acp_migration_json TEXT,
  entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),
  updated_at INTEGER NOT NULL,
  status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
  created_at INTEGER,
  created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),
  created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),
  created_actor_id TEXT,
  owner_actor_type TEXT,
  owner_actor_id TEXT,
  owner_assigned_by_type TEXT,
  owner_assigned_by_id TEXT,
  owner_assigned_at INTEGER,
  project_id TEXT,
  parent_session_key TEXT,
  spawned_by TEXT,
  fork_source_session_key TEXT,
  fork_source_session_id TEXT,
  fork_source_entry_id TEXT,
  label TEXT,
  display_name TEXT,
  category TEXT,
  icon TEXT,
  pinned_at INTEGER,
  archived_at INTEGER,
  last_read_at INTEGER,
  last_interaction_at INTEGER,
  last_activity_at INTEGER
) STRICT;

CREATE TABLE IF NOT EXISTS session_entry_snapshots (
  session_key TEXT NOT NULL,
  field TEXT NOT NULL CHECK (field IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')),
  value_json TEXT NOT NULL,
  PRIMARY KEY (session_key, field),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;

CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_insert
AFTER INSERT ON session_entry_snapshots
BEGIN
  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
  WHERE session_key = NEW.session_key;
END;

CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_update
AFTER UPDATE OF session_key, field, value_json ON session_entry_snapshots
WHEN NEW.session_key IS NOT OLD.session_key
  OR NEW.field IS NOT OLD.field OR NEW.value_json IS NOT OLD.value_json
BEGIN
  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
  WHERE session_key IN (OLD.session_key, NEW.session_key);
END;

CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_delete
AFTER DELETE ON session_entry_snapshots
BEGIN
  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
  WHERE session_key = OLD.session_key;
END;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at
  ON session_nodes(updated_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label
  ON session_nodes(label, session_key)
  WHERE label IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_parent_session_key
  ON session_nodes(parent_session_key, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_spawned_by
  ON session_nodes(spawned_by, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_status
  ON session_nodes(status, session_key)
  WHERE status IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_archived_at
  ON session_nodes(archived_at, session_key)
  WHERE archived_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_active
  ON session_nodes(session_key)
  WHERE archived_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_current_session_id
  ON session_nodes(current_session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_valid_pending
  ON session_nodes(session_key)
  WHERE entry_valid = 0;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_not_valid
  ON session_nodes(session_key)
  WHERE entry_valid != 1;

CREATE TABLE IF NOT EXISTS session_participants (
  session_key TEXT NOT NULL,
  identity_namespace TEXT NOT NULL,
  actor_id TEXT NOT NULL,
  contribution_count INTEGER NOT NULL,
  first_prompted_at INTEGER,
  last_prompted_at INTEGER,
  PRIMARY KEY (session_key, identity_namespace, actor_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS session_key_contract (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  main_key TEXT NOT NULL,
  canonical_ready TEXT,
  updated_at INTEGER NOT NULL
) STRICT;

INSERT OR IGNORE INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0);

CREATE TABLE IF NOT EXISTS session_windows (
  session_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  previous_session_id TEXT,
  reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),
  session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  transcript_updated_at INTEGER DEFAULT NULL,
  row_transcript_json TEXT,
  row_transcript_updated_at INTEGER,
  transcript_observed_at INTEGER DEFAULT NULL,
  session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),
  acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),
  plugin_owner_id TEXT,
  hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),
  started_at INTEGER,
  ended_at INTEGER,
  status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
  chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),
  channel TEXT,
  account_id TEXT,
  primary_conversation_id TEXT,
  model_provider TEXT,
  model TEXT,
  agent_harness_id TEXT,
  parent_session_key TEXT,
  spawned_by TEXT,
  display_name TEXT,
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
  FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_updated_at
  ON session_windows(updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_session_key
  ON session_windows(session_key, updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_created_at
  ON session_windows(created_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_conversation
  ON session_windows(primary_conversation_id)
  WHERE primary_conversation_id IS NOT NULL;

-- Offline imports and repairs queue explicit work; admission also settles keys
-- removed during repair, so the queue deliberately has no node foreign key.
CREATE TABLE IF NOT EXISTS session_canonical_validation_pending (
  session_key TEXT NOT NULL PRIMARY KEY
) STRICT;

CREATE TABLE IF NOT EXISTS conversations (
  conversation_id TEXT NOT NULL PRIMARY KEY,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('direct', 'group', 'channel')),
  peer_id TEXT NOT NULL,
  delivery_target TEXT NOT NULL,
  parent_conversation_id TEXT,
  thread_id TEXT,
  native_channel_id TEXT,
  native_direct_user_id TEXT,
  label TEXT,
  metadata_json TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_conversations_lookup
  ON conversations(channel, account_id, kind, peer_id, thread_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_conversations_identity
  ON conversations(
    channel,
    account_id,
    kind,
    peer_id,
    IFNULL(parent_conversation_id, ''),
    IFNULL(thread_id, '')
  );

CREATE INDEX IF NOT EXISTS idx_agent_conversations_updated
  ON conversations(updated_at DESC, conversation_id);

CREATE TABLE IF NOT EXISTS conversation_deliveries (
  operation_id TEXT NOT NULL PRIMARY KEY,
  operation_kind TEXT NOT NULL CHECK (operation_kind IN ('send', 'turn')),
  conversation_id TEXT NOT NULL,
  source_session_key TEXT,
  message_hash TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied')),
  prepared_message_id TEXT,
  platform_message_id TEXT,
  queue_id TEXT,
  rejection_error TEXT,
  reply_message_id TEXT,
  reply_to_id TEXT,
  reply_thread_id TEXT,
  reply_text TEXT,
  reply_timestamp INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  CHECK (
    (status = 'rejected' AND rejection_error IS NOT NULL) OR
    (status != 'rejected' AND rejection_error IS NULL)
  ),
  FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_reply
  ON conversation_deliveries(conversation_id, platform_message_id, prepared_message_id)
  WHERE status IN ('queued', 'sent', 'replied');

CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_updated
  ON conversation_deliveries(updated_at DESC, operation_id);

CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_source_session
  ON conversation_deliveries(source_session_key, operation_id);

CREATE TABLE IF NOT EXISTS session_conversations (
  session_id TEXT NOT NULL,
  conversation_id TEXT NOT NULL,
  role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')),
  route_context_json TEXT,
  first_seen_at INTEGER NOT NULL,
  last_seen_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, conversation_id, role),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
  FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;

-- Older same-version writers preserve the envelope while updating the association.
CREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update
AFTER UPDATE OF role, last_seen_at ON session_conversations
WHEN NEW.route_context_json IS OLD.route_context_json
BEGIN
  UPDATE session_conversations
  SET route_context_json = NULL
  WHERE session_id = NEW.session_id
    AND conversation_id = NEW.conversation_id
    AND role = NEW.role;
END;

CREATE INDEX IF NOT EXISTS idx_agent_session_conversations_conversation
  ON session_conversations(conversation_id, last_seen_at DESC, session_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_session_conversations_primary
  ON session_conversations(session_id)
  WHERE role = 'primary';

CREATE TABLE IF NOT EXISTS session_members (
  session_key TEXT NOT NULL,
  identity_id TEXT NOT NULL,
  added_by TEXT NOT NULL,
  added_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, identity_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_members_identity
  ON session_members(identity_id, session_key);

CREATE TABLE IF NOT EXISTS session_suggestions (
  id TEXT PRIMARY KEY,
  session_key TEXT NOT NULL,
  author_id TEXT NOT NULL,
  author_label TEXT,
  text TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'dismissed')),
  dispatch_token TEXT,
  dispatch_started_at INTEGER,
  dispatch_resolution TEXT CHECK (dispatch_resolution IN ('send', 'queue', 'edit', 'dismiss')),
  CHECK (
    (dispatch_token IS NULL AND dispatch_started_at IS NULL AND dispatch_resolution IS NULL)
    OR (dispatch_token IS NOT NULL AND dispatch_started_at IS NOT NULL AND dispatch_resolution IS NOT NULL)
  ),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_session_state_created
  ON session_suggestions(session_key, state, created_at, id);

CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_author_created
  ON session_suggestions(author_id, created_at, id);

CREATE TABLE IF NOT EXISTS session_reactions (
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  message_id TEXT NOT NULL,
  emoji TEXT NOT NULL,
  identity_id TEXT NOT NULL,
  identity_label TEXT,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, session_id, message_id, emoji, identity_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS board_tabs (
  session_key TEXT NOT NULL,
  tab_id TEXT NOT NULL,
  title TEXT NOT NULL,
  position INTEGER NOT NULL CHECK (position >= 0),
  chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),
  created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
  revision INTEGER NOT NULL CHECK (revision >= 0),
  PRIMARY KEY (session_key, tab_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS board_widgets (
  session_key TEXT NOT NULL,
  name TEXT NOT NULL,
  tab_id TEXT NOT NULL,
  title TEXT,
  content_kind TEXT NOT NULL CHECK (content_kind IN ('html', 'mcp-app', 'plugin')),
  html BLOB,
  descriptor_json TEXT,
  sha256 TEXT NOT NULL,
  view_generation TEXT,
  revision INTEGER NOT NULL CHECK (revision >= 1),
  size_w INTEGER NOT NULL CHECK (size_w BETWEEN 1 AND 12),
  size_h INTEGER NOT NULL CHECK (size_h BETWEEN 1 AND 20),
  position INTEGER NOT NULL CHECK (position >= 0),
  manifest TEXT NOT NULL DEFAULT '{}',
  grant_state TEXT NOT NULL DEFAULT 'none' CHECK (grant_state IN ('none', 'pending', 'granted', 'rejected')),
  granted_sha TEXT,
  created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, name),
  FOREIGN KEY (session_key, tab_id) REFERENCES board_tabs(session_key, tab_id) ON DELETE CASCADE,
  CHECK (
    (content_kind = 'html' AND html IS NOT NULL AND descriptor_json IS NULL AND view_generation IS NOT NULL) OR
    (content_kind = 'mcp-app' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL) OR
    (content_kind = 'plugin' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position
  ON board_widgets(session_key, tab_id, position);

CREATE TABLE IF NOT EXISTS session_progress_cards (
  session_key TEXT NOT NULL PRIMARY KEY,
  markdown TEXT,
  steps_json TEXT,
  revision INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS heartbeat_outcomes (
  session_key TEXT NOT NULL PRIMARY KEY,
  run_session_key TEXT NOT NULL,
  outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),
  summary TEXT NOT NULL,
  response_reason TEXT,
  priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),
  next_check TEXT,
  task_names_json TEXT,
  wake_source TEXT,
  wake_reason TEXT,
  occurred_at INTEGER NOT NULL,
  context_run_id TEXT,
  context_claimed_at INTEGER,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS message_tool_run_outcomes (
  id INTEGER PRIMARY KEY,
  run_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  provider TEXT NOT NULL,
  model TEXT NOT NULL,
  outcome TEXT NOT NULL CHECK (outcome IN ('tool_delivered', 'mute')),
  run_status TEXT NOT NULL CHECK (run_status IN ('completed', 'errored', 'aborted')),
  occurred_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_message_tool_run_outcomes_occurred
  ON message_tool_run_outcomes(occurred_at DESC, id DESC);

-- Receipts outlive Goal clear and session reset so a delayed retry cannot recreate a Goal.
-- They intentionally have no session FK; bounded retention belongs to the operation owner.
CREATE TABLE IF NOT EXISTS session_goal_operations (
  session_key TEXT NOT NULL,
  operation_id TEXT NOT NULL,
  session_id TEXT NOT NULL,
  request_fingerprint TEXT NOT NULL,
  result_json TEXT NOT NULL,
  expires_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, operation_id)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_goal_operations_expiry
  ON session_goal_operations(expires_at);

CREATE TABLE IF NOT EXISTS transcript_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_json TEXT,
  created_at INTEGER NOT NULL,
  event_zstd BLOB,
  event_utf8_bytes INTEGER CHECK (event_utf8_bytes IS NULL OR event_utf8_bytes >= 0),
  navigation_json TEXT,
  navigation_type TEXT,
  navigation_custom_type TEXT,
  navigation_display INTEGER NOT NULL DEFAULT 0,
  message_role TEXT,
  navigation_last_type TEXT,
  navigation_last_custom_type TEXT,
  navigation_valid INTEGER NOT NULL DEFAULT 1,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
  CHECK (
    (event_json IS NOT NULL AND event_zstd IS NULL)
    OR (
      event_json IS NULL AND event_zstd IS NOT NULL
      AND event_utf8_bytes IS NOT NULL
      AND event_utf8_bytes BETWEEN 1 AND 4194304
      AND length(event_zstd) BETWEEN 1 AND 4194304
      AND navigation_json IS NOT NULL
    )
  ),
  CHECK (
    navigation_json IS NULL OR CASE WHEN json_valid(navigation_json) THEN coalesce(
      octet_length(navigation_json) <= 16384
      AND json_type(navigation_json, '$.version') = 'integer'
      AND json_extract(navigation_json, '$.version') = 1
      AND json_type(navigation_json, '$.report') = 'object'
      AND json_extract(navigation_json, '$.report.kind') IN ('canonical', 'leaf', 'link', 'ignored')
      AND json_type(navigation_json, '$.navigation') = 'object'
      AND json_type(navigation_json, '$.reset') = 'object'
      AND json_type(navigation_json, '$.model') = 'object'
      AND json_type(navigation_json, '$.modelBytes') = 'integer'
      AND json_extract(navigation_json, '$.modelBytes') BETWEEN 0 AND 4194304
      AND json_type(navigation_json, '$.modelWithoutCheckpointBytes') = 'integer'
      AND json_extract(navigation_json, '$.modelWithoutCheckpointBytes') BETWEEN 0 AND 4194304
      AND json_type(navigation_json, '$.withoutCustomDataBytes') = 'integer'
      AND json_extract(navigation_json, '$.withoutCustomDataBytes') BETWEEN 0 AND 4194304,
      0) ELSE 0 END
  )
) STRICT;

-- Canonical cold-tier owner for reclaimed transcript generations. The derived
-- .deleted/.reset file may be recreated from this row after a crash.
CREATE TABLE IF NOT EXISTS session_transcript_archives (
  session_id TEXT NOT NULL,
  generation TEXT NOT NULL,
  session_key TEXT NOT NULL,
  reason TEXT NOT NULL CHECK (reason IN ('deleted', 'reset')),
  encoding TEXT NOT NULL CHECK (encoding IN ('identity', 'zstd')),
  archive_blob BLOB NOT NULL,
  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
  archive_name TEXT NOT NULL UNIQUE,
  created_at INTEGER NOT NULL,
  published_at INTEGER,
  publish_attempts INTEGER NOT NULL DEFAULT 0 CHECK (publish_attempts >= 0),
  last_publish_attempt_at INTEGER,
  last_publish_error TEXT,
  PRIMARY KEY (session_id, generation),
  CHECK (archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_pending
  ON session_transcript_archives(created_at, session_id, generation)
  WHERE published_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_retention
  ON session_transcript_archives(created_at, session_id, generation);

CREATE TABLE IF NOT EXISTS session_transcript_cold_archives (
  session_id TEXT NOT NULL PRIMARY KEY,
  generation TEXT NOT NULL,
  archive_name TEXT NOT NULL UNIQUE,
  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
  event_count INTEGER NOT NULL CHECK (event_count >= 1),
  raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
  archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
  last_seq INTEGER NOT NULL,
  archived_at INTEGER NOT NULL,
  storage TEXT NOT NULL CHECK (storage IN ('file', 'sqlite')),
  archive_blob BLOB,
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
  CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%'),
  CHECK ((storage = 'file' AND archive_blob IS NULL) OR (storage = 'sqlite' AND archive_blob IS NOT NULL))
) STRICT;

CREATE TABLE IF NOT EXISTS session_transcript_cold_archive_chunks (
  session_id TEXT NOT NULL,
  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
  archive_name TEXT NOT NULL UNIQUE,
  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
  first_seq INTEGER NOT NULL,
  last_seq INTEGER NOT NULL CHECK (last_seq >= first_seq),
  event_count INTEGER NOT NULL CHECK (event_count >= 1),
  raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
  archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
  archive_blob BLOB,
  PRIMARY KEY (session_id, chunk_index),
  FOREIGN KEY (session_id) REFERENCES session_transcript_cold_archives(session_id) ON DELETE CASCADE,
  CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT, WITHOUT ROWID;

CREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (
  session_id TEXT NOT NULL PRIMARY KEY,
  generation TEXT NOT NULL,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS trajectory_runtime_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  run_id TEXT,
  event_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  event_utf8_bytes INTEGER,
  event_payload BLOB,
  event_codec TEXT,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_trajectory_runtime_run
  ON trajectory_runtime_events(session_id, run_id, created_at, COALESCE(event_utf8_bytes, octet_length(event_json)));

CREATE TABLE IF NOT EXISTS acp_parent_stream_events (
  session_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, run_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_acp_parent_stream_run
  ON acp_parent_stream_events(run_id, seq);

CREATE TABLE IF NOT EXISTS transcript_event_identities (
  session_id TEXT NOT NULL,
  event_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_type TEXT,
  parent_id TEXT,
  message_idempotency_key TEXT,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, event_id),
  FOREIGN KEY (session_id, seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_message_idempotency
  ON transcript_event_identities(session_id, message_idempotency_key)
  WHERE message_idempotency_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_identity_sequence
  ON transcript_event_identities(session_id, seq);

CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence
  ON transcript_event_identities(session_id, event_type, seq DESC);

CREATE TABLE IF NOT EXISTS context_engine_turn_outbox (
  enqueue_sequence INTEGER PRIMARY KEY,
  advancement_key TEXT NOT NULL UNIQUE,
  engine_id TEXT NOT NULL,
  owner_plugin_id TEXT,
  session_id TEXT NOT NULL,
  payload_json TEXT NOT NULL,
  payload_state TEXT,
  attempt_count INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  created_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_context_engine_turn_outbox_engine
  ON context_engine_turn_outbox(engine_id, created_at);

CREATE TABLE IF NOT EXISTS cache_entries (
  scope TEXT NOT NULL,
  key TEXT NOT NULL,
  value_json TEXT,
  blob BLOB,
  expires_at INTEGER,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (scope, key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_cache_expiry
  ON cache_entries(scope, expires_at, key)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_cache_updated
  ON cache_entries(scope, updated_at DESC, key);

CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_scope
  ON cache_entries(CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.agentId') END,
    CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.sessionKey') END, CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.origin') END)
  WHERE scope = 'talk-client-voice-sessions'
    AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';

CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_updated
  ON cache_entries(scope, updated_at)
  WHERE scope = 'talk-client-voice-sessions'
    AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';

CREATE TABLE IF NOT EXISTS auth_profile_store (
  store_key TEXT NOT NULL PRIMARY KEY,
  store_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS auth_profile_state (
  state_key TEXT NOT NULL PRIMARY KEY,
  state_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_meta (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_sources (
  id INTEGER PRIMARY KEY,
  path TEXT NOT NULL,
  source TEXT NOT NULL DEFAULT 'memory',
  hash TEXT NOT NULL,
  mtime REAL NOT NULL,
  size INTEGER NOT NULL,
  UNIQUE (path, source)
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_chunks (
  chunk_rowid INTEGER PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  path TEXT NOT NULL,
  source TEXT NOT NULL DEFAULT 'memory',
  start_line INTEGER NOT NULL,
  end_line INTEGER NOT NULL,
  hash TEXT NOT NULL,
  model TEXT NOT NULL,
  text TEXT NOT NULL,
  embedding BLOB NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_chunk_recall_metadata (
  chunk_id TEXT PRIMARY KEY,
  importance INTEGER CHECK (importance IS NULL OR importance BETWEEN 1 AND 10),
  triggers TEXT,
  project_key TEXT,
  FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_chunk_provenance (
  chunk_id TEXT PRIMARY KEY,
  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
  session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),
  observed_at INTEGER NOT NULL,
  supersedes_key TEXT,
  FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS memory_entry_origins (
  entry_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_key TEXT,
  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
  observed_at INTEGER NOT NULL,
  PRIMARY KEY (entry_key, agent_id, session_id)
) STRICT, WITHOUT ROWID;

CREATE TABLE IF NOT EXISTS memory_session_tombstones (
  session_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  reason TEXT NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_embedding_cache (
  provider TEXT NOT NULL,
  model TEXT NOT NULL,
  provider_key TEXT NOT NULL,
  hash TEXT NOT NULL,
  embedding BLOB NOT NULL,
  dims INTEGER,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (provider, model, provider_key, hash)
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_state (
  id INTEGER PRIMARY KEY CHECK (id = 1),
  revision INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS standing_intents (
  intent_key INTEGER PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  description TEXT NOT NULL,
  trigger_keywords TEXT NOT NULL,
  trigger_embedding TEXT,
  channel_scope TEXT,
  sender_scope TEXT,
  creator_sender TEXT CHECK (creator_sender IS NULL OR length(trim(creator_sender)) > 0),
  status TEXT NOT NULL CHECK (status IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired')),
  expires_at INTEGER NOT NULL,
  max_fires INTEGER NOT NULL CHECK (max_fires > 0),
  fire_count INTEGER NOT NULL DEFAULT 0 CHECK (fire_count >= 0),
  cooldown_seconds INTEGER NOT NULL DEFAULT 86400 CHECK (cooldown_seconds >= 0),
  last_fired_at INTEGER,
  created_at INTEGER NOT NULL,
  source_session_id TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_standing_intents_lifecycle
  ON standing_intents(status, expires_at, last_fired_at);

CREATE INDEX IF NOT EXISTS idx_standing_intents_scope
  ON standing_intents(status, channel_scope, sender_scope);

CREATE VIRTUAL TABLE IF NOT EXISTS standing_intents_fts USING fts5(
  trigger_keywords,
  content = 'standing_intents',
  content_rowid = 'intent_key',
  tokenize = 'unicode61 remove_diacritics 2'
);

CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_insert
AFTER INSERT ON standing_intents
BEGIN
  INSERT INTO standing_intents_fts(rowid, trigger_keywords)
  VALUES (new.intent_key, new.trigger_keywords);
END;

CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_delete
AFTER DELETE ON standing_intents
BEGIN
  INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
  VALUES ('delete', old.intent_key, old.trigger_keywords);
END;

CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_update
AFTER UPDATE OF trigger_keywords ON standing_intents
BEGIN
  INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
  VALUES ('delete', old.intent_key, old.trigger_keywords);
  INSERT INTO standing_intents_fts(rowid, trigger_keywords)
  VALUES (new.intent_key, new.trigger_keywords);
END;

CREATE TABLE IF NOT EXISTS session_transcript_index_state (
  session_id TEXT NOT NULL PRIMARY KEY,
  indexed_seq INTEGER NOT NULL,
  leaf_event_id TEXT,
  needs_rebuild INTEGER NOT NULL DEFAULT 0,
  active_event_count INTEGER NOT NULL DEFAULT 0,
  active_message_count INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS session_transcript_active_events (
  session_id TEXT NOT NULL,
  active_position INTEGER NOT NULL CHECK (active_position >= 0),
  event_seq INTEGER NOT NULL,
  message_position INTEGER CHECK (message_position IS NULL OR message_position >= 0),
  context_eligible INTEGER,
  PRIMARY KEY (session_id, active_position),
  FOREIGN KEY (session_id, event_seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_event_seq
  ON session_transcript_active_events(session_id, event_seq);

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_messages
  ON session_transcript_active_events(session_id, message_position)
  WHERE message_position IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_transcript_context_pending
  ON session_transcript_active_events(session_id)
  WHERE context_eligible IS NULL;

CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(
  text,
  session_id UNINDEXED,
  message_id UNINDEXED,
  role UNINDEXED,
  timestamp UNINDEXED,
  tokenize = 'unicode61 remove_diacritics 2'
);

CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (
  id INTEGER PRIMARY KEY,
  session_id TEXT NOT NULL,
  message_id TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_transcript_fts_rows_session_message
  ON session_transcript_fts_rows(session_id, message_id);

CREATE TRIGGER IF NOT EXISTS session_transcript_fts_rows_after_delete
AFTER DELETE ON session_transcript_fts_rows
BEGIN
  DELETE FROM session_transcript_fts WHERE rowid = OLD.id;
END;

INSERT OR IGNORE INTO memory_index_state (id, revision) VALUES (1, 0);

CREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at
  ON memory_embedding_cache(updated_at);

CREATE INDEX IF NOT EXISTS idx_memory_index_sources_source
  ON memory_index_sources(source);

CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path_source
  ON memory_index_chunks(path, source);

CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_source
  ON memory_index_chunks(source);

-- Accepted input stays outside the active transcript until its exact turn owns execution.
CREATE TABLE IF NOT EXISTS session_pending_inputs (
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
  input_id TEXT NOT NULL UNIQUE,
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  idempotency_key TEXT NOT NULL,
  run_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  message_json TEXT NOT NULL,
  lifecycle_generation TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('queued', 'interrupted', 'cancelled')),
  accepted_at INTEGER NOT NULL,
  consumed_event_id TEXT,
  UNIQUE (session_id, idempotency_key),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_pending_inputs_session
  ON session_pending_inputs(session_key, session_id, seq DESC);

-- Processing completion is separate from input consumption; neither schedules replay.
CREATE TABLE IF NOT EXISTS session_input_completions (
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  idempotency_key TEXT NOT NULL,
  run_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  outcome_json TEXT NOT NULL,
  succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
  completed_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, idempotency_key),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_input_completions_session_key
  ON session_input_completions(session_key);
`})),sb=__esmMin((()=>{})),cb,lb=__esmMin((()=>{cb=`

CREATE TABLE IF NOT EXISTS mcp_oauth_stores (
  store_key TEXT NOT NULL PRIMARY KEY,
  format_version INTEGER NOT NULL CHECK (format_version = 1),
  store_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS mcp_oauth_pending_authorizations (
  state TEXT NOT NULL PRIMARY KEY,
  store_key TEXT NOT NULL,
  create_time INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS diagnostic_events (
  scope TEXT NOT NULL,
  event_key TEXT NOT NULL,
  payload_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  sequence INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (scope, event_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_diagnostic_events_scope_sequence
  ON diagnostic_events(scope, sequence, event_key);

CREATE TABLE IF NOT EXISTS skill_usage (
  skill_file TEXT NOT NULL PRIMARY KEY,
  skill_key TEXT NOT NULL,
  skill_name TEXT NOT NULL,
  skill_source TEXT NOT NULL,
  first_used_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER NOT NULL,
  use_count INTEGER NOT NULL,
  last_agent_id TEXT
) STRICT;

-- Profile-owned skill library: additive, absent until first publication/import.
CREATE TABLE IF NOT EXISTS skill_library_entries (
  skill_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT,
  author_profile_id TEXT NOT NULL,
  slug TEXT NOT NULL,
  current_revision TEXT NOT NULL,
  shared INT NOT NULL,
  enabled INT NOT NULL,
  removed INT NOT NULL,
  created_at INT NOT NULL,
  updated_at INT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_revisions (
  skill_id TEXT NOT NULL,
  revision TEXT NOT NULL,
  description TEXT NOT NULL,
  files_json TEXT NOT NULL,
  created_at INT NOT NULL,
  PRIMARY KEY (skill_id, revision)
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_events (
  event_id TEXT NOT NULL PRIMARY KEY,
  skill_id TEXT NOT NULL,
  revision TEXT NOT NULL,
  action TEXT NOT NULL,
  actor_profile_id TEXT NOT NULL,
  created_at INT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_uploads (
  upload_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT NOT NULL,
  slug TEXT NOT NULL,
  size_bytes INT NOT NULL,
  sha256 TEXT NOT NULL,
  archive_blob BLOB NOT NULL,
  expires_at INT NOT NULL,
  published_skill_id TEXT
) STRICT;
-- End profile-owned skill library.

CREATE TABLE IF NOT EXISTS skill_workshop_changes (
  cursor_id INTEGER NOT NULL,
  change_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  skill_name TEXT NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore')),
  actor TEXT NOT NULL CHECK (actor IN ('agent', 'review', 'curator', 'user')),
  summary TEXT NOT NULL,
  version_id TEXT,
  session_key TEXT,
  run_id TEXT,
  created_at_ms INTEGER NOT NULL
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS skill_workshop_changes_cursor_id_idx
  ON skill_workshop_changes(cursor_id);

CREATE INDEX IF NOT EXISTS idx_skill_workshop_changes_agent_time
  ON skill_workshop_changes(agent_id, created_at_ms);

CREATE TABLE IF NOT EXISTS audit_events (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  event_id TEXT NOT NULL UNIQUE,
  source_id TEXT NOT NULL UNIQUE,
  schema_version INTEGER NOT NULL DEFAULT 1,
  source_sequence INTEGER NOT NULL,
  occurred_at INTEGER NOT NULL,
  kind TEXT NOT NULL,
  action TEXT NOT NULL,
  status TEXT NOT NULL,
  error_code TEXT,
  actor_type TEXT NOT NULL,
  actor_id TEXT NOT NULL,
  agent_id TEXT,
  session_key TEXT,
  session_id TEXT,
  run_id TEXT,
  tool_call_id TEXT,
  tool_name TEXT,
  direction TEXT,
  channel TEXT,
  conversation_kind TEXT,
  message_outcome TEXT,
  reason_code TEXT,
  delivery_kind TEXT,
  failure_stage TEXT,
  duration_ms INTEGER,
  result_count INTEGER,
  account_ref TEXT,
  conversation_ref TEXT,
  message_ref TEXT,
  target_ref TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_audit_events_time
  ON audit_events(occurred_at DESC, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_agent_sequence
  ON audit_events(agent_id, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_session_sequence
  ON audit_events(session_key, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_run_sequence
  ON audit_events(run_id, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_kind_sequence
  ON audit_events(kind, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_status_sequence
  ON audit_events(status, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_channel_sequence
  ON audit_events(channel, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_direction_sequence
  ON audit_events(direction, sequence DESC);

CREATE TABLE IF NOT EXISTS outbound_message_execution_bindings (
  event_id TEXT NOT NULL PRIMARY KEY,
  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  FOREIGN KEY (event_id) REFERENCES audit_events(event_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS outbound_message_execution_bindings_execution_event_idx
  ON outbound_message_execution_bindings (context_id, execution_id, run_id, event_id);

CREATE TABLE IF NOT EXISTS outbound_message_progress (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  progress_id TEXT NOT NULL UNIQUE CHECK (length(progress_id) BETWEEN 1 AND 256),
  source_id TEXT NOT NULL UNIQUE CHECK (length(source_id) BETWEEN 1 AND 512),
  source_sequence INTEGER NOT NULL CHECK (source_sequence >= 1),
  schema_version INTEGER NOT NULL CHECK (schema_version = 1),
  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
  action TEXT NOT NULL CHECK (
    action IN ('message.outbound.queued', 'message.outbound.platform-started')
  ),
  outcome TEXT NOT NULL CHECK (outcome IN ('queued', 'platform_started')),
  actor_type TEXT NOT NULL CHECK (actor_type IN ('agent', 'system')),
  actor_id TEXT NOT NULL CHECK (length(actor_id) BETWEEN 1 AND 256),
  agent_id TEXT CHECK (agent_id IS NULL OR length(agent_id) BETWEEN 1 AND 256),
  run_id TEXT CHECK (run_id IS NULL OR length(run_id) BETWEEN 1 AND 256),
  context_id TEXT,
  execution_id TEXT,
  channel TEXT NOT NULL CHECK (length(channel) BETWEEN 1 AND 256),
  conversation_kind TEXT NOT NULL CHECK (
    conversation_kind IN ('direct', 'group', 'channel', 'unknown')
  ),
  duration_ms INTEGER CHECK (duration_ms IS NULL OR duration_ms >= 0),
  account_ref TEXT,
  conversation_ref TEXT,
  target_ref TEXT,
  UNIQUE (occurred_at, progress_id)
) STRICT;
CREATE INDEX IF NOT EXISTS outbound_message_progress_occurred_idx
  ON outbound_message_progress (occurred_at, sequence);
CREATE INDEX IF NOT EXISTS outbound_message_progress_run_occurred_idx
  ON outbound_message_progress (run_id, occurred_at, sequence);

CREATE TABLE IF NOT EXISTS audit_identity_keys (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  key_id TEXT NOT NULL,
  key BLOB NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS config_revision_keys (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  hmac_key BLOB NOT NULL CHECK (length(hmac_key) = 32)
) STRICT;

CREATE TABLE IF NOT EXISTS execution_identity_contexts (
  context_id TEXT NOT NULL PRIMARY KEY CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL UNIQUE CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  created_at INTEGER NOT NULL CHECK (created_at >= 0),
  coverage_state TEXT NOT NULL CHECK (
    coverage_state IN ('attribution-only', 'unattributed', 'unknown', 'unsupported')
  ),
  context_bytes INTEGER NOT NULL CHECK (context_bytes BETWEEN 1 AND 16384),
  context_json TEXT NOT NULL CHECK (length(context_json) > 0),
  UNIQUE (created_at, context_id)
) STRICT;
CREATE INDEX IF NOT EXISTS execution_identity_contexts_run_created_idx
  ON execution_identity_contexts (run_id, created_at, execution_id);

CREATE TABLE IF NOT EXISTS execution_decision_facts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT NOT NULL PRIMARY KEY CHECK (length(receipt_id) BETWEEN 1 AND 256),
  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  action_id TEXT CHECK (action_id IS NULL OR length(action_id) BETWEEN 1 AND 256),
  action_family TEXT NOT NULL CHECK (length(action_family) BETWEEN 1 AND 256),
  decision_outcome TEXT NOT NULL CHECK (
    decision_outcome IN ('allowed', 'denied', 'not-applicable', 'unknown')
  ),
  coverage_state TEXT NOT NULL CHECK (
    coverage_state IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported')
  ),
  reason_code TEXT NOT NULL CHECK (length(reason_code) BETWEEN 1 AND 256),
  owner TEXT NOT NULL CHECK (length(owner) BETWEEN 1 AND 256),
  source_ref TEXT NOT NULL CHECK (length(source_ref) BETWEEN 1 AND 256),
  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
  receipt_bytes INTEGER NOT NULL CHECK (receipt_bytes BETWEEN 1 AND 16384),
  receipt_json TEXT NOT NULL CHECK (length(receipt_json) > 0),
  UNIQUE (occurred_at, receipt_id)
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS execution_decision_facts_cursor_id_idx
  ON execution_decision_facts(cursor_id);

CREATE INDEX IF NOT EXISTS execution_decision_facts_context_occurred_idx
  ON execution_decision_facts (context_id, occurred_at, receipt_id);
CREATE INDEX IF NOT EXISTS execution_decision_facts_run_occurred_idx
  ON execution_decision_facts (run_id, occurred_at, receipt_id);

-- Exact admission identity stays separate from owner-native lifecycle rows so
-- older readers retain byte-compatible cron/task/flow table definitions.
CREATE TABLE IF NOT EXISTS execution_owner_lifecycle_bindings (
  owner_kind TEXT NOT NULL,
  owner_id TEXT NOT NULL,
  context_id TEXT NOT NULL,
  execution_id TEXT NOT NULL,
  PRIMARY KEY (owner_kind, owner_id)
) STRICT;

CREATE TABLE IF NOT EXISTS session_state_events (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  dedupe_key TEXT UNIQUE,
  session_key TEXT NOT NULL,
  session_id TEXT,
  agent_id TEXT NOT NULL,
  kind TEXT NOT NULL,
  actor_type TEXT NOT NULL,
  actor_id TEXT,
  run_id TEXT,
  occurred_at INTEGER NOT NULL,
  summary TEXT NOT NULL,
  payload_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_state_events_session_sequence
  ON session_state_events(session_key, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_session_state_events_time
  ON session_state_events(occurred_at DESC, sequence DESC);

CREATE TABLE IF NOT EXISTS session_state_heads (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  last_sequence INTEGER NOT NULL,
  pruned_max_sequence INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, agent_id)
) STRICT, WITHOUT ROWID;

-- Notifiable watcher identity is the bare session key, matching the process-local
-- system-event queue it feeds. Provenance distinguishes explicit immediate-wake
-- watches from ambient queue-only group watches. Other bare keys
-- (session.scope="global") are ambiguous across agents and excluded until watcher
-- identity is agent-scoped end-to-end.
CREATE TABLE IF NOT EXISTS session_watch_cursors (
  watcher_session_key TEXT NOT NULL,
  watcher_store_path TEXT,
  target_session_key TEXT NOT NULL,
  last_seen_sequence INTEGER NOT NULL DEFAULT 0,
  notified_sequence INTEGER NOT NULL DEFAULT 0,
  material_sequence INTEGER NOT NULL DEFAULT 0,
  provenance TEXT NOT NULL DEFAULT 'explicit' CHECK (provenance IN ('explicit', 'ambient-group')),
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (watcher_session_key, target_session_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_watch_cursors_target
  ON session_watch_cursors(target_session_key);

CREATE TABLE IF NOT EXISTS session_upstream_links (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  catalog_id TEXT NOT NULL,
  host_id TEXT NOT NULL,
  thread_id TEXT NOT NULL,
  upstream_kind TEXT NOT NULL,
  upstream_ref_json TEXT,
  last_marker_json TEXT,
  last_scanned_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  -- (session_key, agent_id) composite identity: under session.scope="global" agents
  -- share bare keys; a key-only row would let one agent overwrite another's upstream.
  PRIMARY KEY (session_key, agent_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_upstream_links_catalog_id
  ON session_upstream_links(catalog_id);

CREATE TABLE IF NOT EXISTS state_leases (
  scope TEXT NOT NULL,
  lease_key TEXT NOT NULL,
  owner TEXT NOT NULL,
  expires_at INTEGER,
  heartbeat_at INTEGER,
  payload_json TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (scope, lease_key)
) STRICT;

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

CREATE INDEX IF NOT EXISTS idx_state_leases_owner
  ON state_leases(owner);

CREATE TABLE IF NOT EXISTS exec_approvals_config (
  config_key TEXT NOT NULL PRIMARY KEY,
  raw_json TEXT NOT NULL,
  socket_path TEXT,
  has_socket_token INTEGER NOT NULL,
  default_security TEXT,
  default_ask TEXT,
  default_ask_fallback TEXT,
  auto_allow_skills INTEGER,
  agent_count INTEGER NOT NULL,
  allowlist_count INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS operator_approvals (
  cursor_id INTEGER NOT NULL,
  approval_id TEXT NOT NULL PRIMARY KEY CHECK (
    length(approval_id) > 0 AND approval_id NOT IN ('.', '..')
  ),
  resolution_ref TEXT NOT NULL CHECK (
    length(resolution_ref) = 43 AND resolution_ref NOT GLOB '*[^A-Za-z0-9_-]*'
  ),
  kind TEXT NOT NULL CHECK (kind IN ('exec', 'plugin', 'system-agent')),
  status TEXT NOT NULL CHECK (status IN ('pending', 'allowed', 'denied', 'expired', 'cancelled')),
  presentation_json TEXT NOT NULL,
  requested_by_device_id TEXT,
  requested_by_client_id TEXT,
  requested_by_device_token_auth INTEGER NOT NULL DEFAULT 0,
  reviewer_device_ids_json TEXT NOT NULL,
  source_agent_id TEXT,
  source_session_key TEXT,
  source_session_id TEXT,
  source_run_id TEXT,
  source_tool_call_id TEXT,
  source_tool_name TEXT,
  audience_session_keys_json TEXT NOT NULL,
  runtime_epoch TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  decision TEXT CHECK (decision IN ('allow-once', 'allow-always', 'deny')),
  terminal_reason TEXT CHECK (
    terminal_reason IN (
      'user',
      'timeout',
      'malformed-verdict',
      'no-route',
      'run-aborted',
      'gateway-restart',
      'storage-corrupt'
    )
  ),
  resolved_at_ms INTEGER,
  resolver_kind TEXT CHECK (resolver_kind IN ('device', 'channel', 'runtime', 'system')),
  resolver_id TEXT,
  consumed_at_ms INTEGER,
  consumed_by TEXT,
  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
    )
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_cursor_id
  ON operator_approvals(cursor_id);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_status_expiry
  ON operator_approvals(status, expires_at_ms, approval_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref
  ON operator_approvals(resolution_ref);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_source_session_created
  ON operator_approvals(source_session_key, created_at_ms DESC, approval_id);

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

CREATE INDEX IF NOT EXISTS idx_operator_approvals_resolved
  ON operator_approvals(resolved_at_ms, approval_id)
  WHERE resolved_at_ms IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_operator_approvals_runtime_pending
  ON operator_approvals(runtime_epoch, approval_id)
  WHERE status = 'pending';

CREATE TABLE IF NOT EXISTS operator_approval_execution_identities (
  approval_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  source_context_id TEXT NOT NULL CHECK (
    length(source_context_id) BETWEEN 1 AND 256 AND source_context_id = trim(source_context_id)
  ),
  source_execution_id TEXT NOT NULL CHECK (
    length(source_execution_id) BETWEEN 1 AND 256 AND source_execution_id = trim(source_execution_id)
  )
) STRICT;

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;

CREATE TABLE IF NOT EXISTS schema_meta (
  meta_key TEXT NOT NULL PRIMARY KEY,
  role TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  agent_id TEXT,
  app_version TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS config_machine_state (
  state_key TEXT NOT NULL PRIMARY KEY,
  value_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_pending (
  request_id TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  public_key TEXT NOT NULL,
  display_name TEXT,
  platform TEXT,
  device_family TEXT,
  client_id TEXT,
  client_mode TEXT,
  browser_origin TEXT,
  role TEXT,
  roles_json TEXT,
  scopes_json TEXT,
  remote_ip TEXT,
  silent INTEGER,
  is_repair INTEGER,
  ts INTEGER NOT NULL,
  refreshed_at_ms INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_pairing_pending_device
  ON device_pairing_pending(device_id, ts DESC);

CREATE TABLE IF NOT EXISTS device_pairing_paired (
  device_id TEXT NOT NULL PRIMARY KEY,
  public_key TEXT NOT NULL,
  display_name TEXT,
  operator_label TEXT,
  platform TEXT,
  device_family TEXT,
  client_id TEXT,
  client_mode TEXT,
  browser_origin TEXT,
  role TEXT,
  roles_json TEXT,
  scopes_json TEXT,
  approved_scopes_json TEXT,
  remote_ip TEXT,
  tokens_json TEXT,
  approved_via TEXT,
  node_surface_json TEXT,
  pending_node_surface_json TEXT,
  created_at_ms INTEGER NOT NULL,
  approved_at_ms INTEGER NOT NULL,
  last_seen_at_ms INTEGER,
  last_seen_reason TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_pairing_paired_approved
  ON device_pairing_paired(approved_at_ms DESC, device_id);

CREATE TABLE IF NOT EXISTS device_bootstrap_tokens (
  token_key TEXT NOT NULL PRIMARY KEY,
  token TEXT NOT NULL,
  setup_id TEXT,
  ts INTEGER NOT NULL,
  device_id TEXT,
  public_key TEXT,
  profile_json TEXT,
  redeemed_profile_json TEXT,
  pending_profile_json TEXT,
  issued_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_bootstrap_tokens_ts
  ON device_bootstrap_tokens(ts);

-- Terminal outcome of a redeemed setup credential. The bootstrap row is deleted
-- on redemption, so this is the only durable proof a setup code succeeded; the
-- presenting client reconciles it when the completion broadcast is missed.
-- Non-secret only: never the bootstrap token or anything derived from it.
-- Bounded by retention to a handful of live rows, so the primary key is the
-- only access path worth having.
CREATE TABLE IF NOT EXISTS device_pair_setup_completions (
  setup_id TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  device_name TEXT,
  access TEXT NOT NULL,
  completed_at_ms INTEGER NOT NULL,
  delivery_state TEXT NOT NULL CHECK (delivery_state IN ('uncertain', 'confirmed')),
  retain_until_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_join_codes (
  shortcode TEXT,
  payload_json TEXT,
  created_at_ms INTEGER,
  expires_at_ms INTEGER
) STRICT;

CREATE TABLE IF NOT EXISTS macos_port_guardian_records (
  pid INTEGER NOT NULL PRIMARY KEY,
  port INTEGER NOT NULL,
  command TEXT NOT NULL,
  mode TEXT NOT NULL,
  timestamp REAL NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_macos_port_guardian_records_port
  ON macos_port_guardian_records(port, timestamp DESC);

CREATE TABLE IF NOT EXISTS workspace_setup_state (
  workspace_key TEXT NOT NULL PRIMARY KEY,
  -- NULL only for attestation-only rows whose legacy source never recorded a
  -- path (orphan hashed-key attestations); setup rows always carry one.
  workspace_path TEXT,
  -- NULL setup columns mean an attestation-only row: replaceWorkspaceAttestation
  -- may record hashes before any setup milestone exists for the workspace.
  version INTEGER,
  bootstrap_seeded_at TEXT,
  setup_completed_at TEXT,
  updated_at INTEGER,
  attested_at_ms INTEGER,
  attestation_updated_at_ms INTEGER,
  CHECK (version IS NULL OR workspace_path IS NOT NULL)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_workspace_setup_state_path
  ON workspace_setup_state(workspace_path);

CREATE TABLE IF NOT EXISTS workspace_path_aliases (
  alias_key TEXT NOT NULL PRIMARY KEY,
  alias_path TEXT NOT NULL,
  workspace_key TEXT NOT NULL,
  workspace_path TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_workspace_path_aliases_workspace
  ON workspace_path_aliases(workspace_key);



CREATE TABLE IF NOT EXISTS workspace_generated_bootstrap_hashes (
  workspace_key TEXT NOT NULL,
  filename TEXT NOT NULL,
  sha256 TEXT NOT NULL,
  PRIMARY KEY (workspace_key, filename),
  FOREIGN KEY (workspace_key) REFERENCES workspace_setup_state(workspace_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS native_hook_relay_bridges (
  relay_id TEXT NOT NULL PRIMARY KEY,
  pid INTEGER NOT NULL,
  hostname TEXT NOT NULL,
  port INTEGER NOT NULL,
  token TEXT NOT NULL,
  expires_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_native_hook_relay_bridges_expires
  ON native_hook_relay_bridges(expires_at_ms, relay_id);

CREATE TABLE IF NOT EXISTS managed_outgoing_image_records (
  attachment_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  agent_id TEXT,
  message_id TEXT,
  created_at TEXT NOT NULL,
  updated_at TEXT,
  retention_class TEXT,
  alt TEXT NOT NULL,
  original_media_root TEXT NOT NULL,
  original_media_id TEXT NOT NULL,
  original_media_subdir TEXT NOT NULL,
  original_content_type TEXT NOT NULL,
  original_width INTEGER,
  original_height INTEGER,
  original_size_bytes INTEGER,
  original_filename TEXT,
  record_json TEXT NOT NULL,
  cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))
) STRICT;

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_session
  ON managed_outgoing_image_records(session_key, created_at DESC, attachment_id);

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

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_session
  ON managed_outgoing_image_records(session_key, agent_id, created_at DESC, attachment_id);

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_message
  ON managed_outgoing_image_records(session_key, agent_id, message_id, attachment_id)
  WHERE message_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS channel_pairing_requests (
  channel_key TEXT NOT NULL,
  account_id TEXT NOT NULL,
  request_id TEXT NOT NULL,
  code TEXT NOT NULL,
  created_at TEXT NOT NULL,
  last_seen_at TEXT NOT NULL,
  meta_json TEXT,
  PRIMARY KEY (channel_key, account_id, request_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_code
  ON channel_pairing_requests(channel_key, code);

CREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_created
  ON channel_pairing_requests(channel_key, created_at, request_id);

CREATE TABLE IF NOT EXISTS channel_pairing_allow_entries (
  channel_key TEXT NOT NULL,
  account_id TEXT NOT NULL,
  entry TEXT NOT NULL,
  sort_order INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (channel_key, account_id, entry)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_pairing_allow_account
  ON channel_pairing_allow_entries(channel_key, account_id, sort_order, entry);

CREATE TABLE IF NOT EXISTS web_push_subscriptions (
  endpoint_hash TEXT NOT NULL PRIMARY KEY,
  subscription_id TEXT NOT NULL UNIQUE,
  endpoint TEXT NOT NULL,
  p256dh TEXT NOT NULL,
  auth TEXT NOT NULL,
  device_id TEXT,
  user_profile_id TEXT,
  preferences_json TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_updated
  ON web_push_subscriptions(updated_at_ms DESC, subscription_id);

CREATE TABLE IF NOT EXISTS web_push_approval_deliveries (
  approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  subscription_id TEXT NOT NULL
    REFERENCES web_push_subscriptions(subscription_id) ON DELETE CASCADE,
  device_id TEXT NOT NULL,
  user_profile_id TEXT,
  prepared_at_ms INTEGER NOT NULL,
  PRIMARY KEY (approval_id, subscription_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_web_push_approval_deliveries_subscription
  ON web_push_approval_deliveries(subscription_id, approval_id);

CREATE TABLE IF NOT EXISTS apns_registrations (
  node_id TEXT NOT NULL PRIMARY KEY,
  transport TEXT NOT NULL,
  token TEXT,
  relay_handle TEXT,
  send_grant TEXT,
  installation_id TEXT,
  relay_origin TEXT,
  topic TEXT NOT NULL,
  environment TEXT NOT NULL,
  distribution TEXT,
  token_debug_suffix TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_apns_registrations_updated
  ON apns_registrations(updated_at_ms DESC, node_id);

CREATE TABLE IF NOT EXISTS apns_registration_tombstones (
  node_id TEXT NOT NULL PRIMARY KEY,
  deleted_at_ms INTEGER NOT NULL
) STRICT;

-- Node-host-owned launch journal. The descriptor and its credential remain
-- process memory only; this table records bounded supervision facts.
CREATE TABLE IF NOT EXISTS node_worker_launches (
  launch_id TEXT NOT NULL PRIMARY KEY
    CHECK (length(launch_id) BETWEEN 1 AND 256 AND instr(launch_id, char(0)) = 0),
  plan_hash TEXT NOT NULL
    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),
  gateway_namespace TEXT NOT NULL
    CHECK (
      length(gateway_namespace) BETWEEN 1 AND 128
      AND gateway_namespace NOT GLOB '*[^A-Za-z0-9._-]*'
      AND gateway_namespace GLOB '[A-Za-z0-9]*'
    ),
  environment_id TEXT NOT NULL
    CHECK (length(environment_id) BETWEEN 1 AND 256 AND instr(environment_id, char(0)) = 0),
  session_id TEXT NOT NULL
    CHECK (length(session_id) BETWEEN 1 AND 256 AND instr(session_id, char(0)) = 0),
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),
  placement_generation INTEGER NOT NULL
    CHECK (placement_generation BETWEEN 0 AND 9007199254740991),
  run_id TEXT NOT NULL
    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),
  state TEXT NOT NULL
    CHECK (state IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled')),
  supervisor_pid INTEGER NOT NULL CHECK (supervisor_pid BETWEEN 1 AND 2147483647),
  supervisor_start_time INTEGER NOT NULL
    CHECK (supervisor_start_time BETWEEN 0 AND 9007199254740991),
  worker_pid INTEGER CHECK (worker_pid IS NULL OR worker_pid BETWEEN 1 AND 2147483647),
  worker_start_time INTEGER CHECK (
    worker_start_time IS NULL OR worker_start_time BETWEEN 0 AND 9007199254740991
  ),
  result_json TEXT CHECK (
    result_json IS NULL
    OR (
      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536
      AND instr(result_json, char(0)) = 0
      AND json_valid(result_json)
    )
  ),
  error_text TEXT CHECK (
    error_text IS NULL
    OR (
      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096
      AND instr(error_text, char(0)) = 0
      AND instr(error_text, char(10)) = 0
      AND instr(error_text, char(13)) = 0
    )
  ),
  completed_at_ms INTEGER CHECK (
    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991
  ),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  updated_at_ms INTEGER NOT NULL 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)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_node_worker_launches_terminal_completed
  ON node_worker_launches(completed_at_ms, launch_id)
  WHERE completed_at_ms IS NOT NULL;

CREATE TABLE IF NOT EXISTS node_worker_launch_boots (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  boot_id TEXT CHECK (boot_id IS NULL OR length(boot_id) BETWEEN 1 AND 128)
) STRICT;

CREATE TABLE IF NOT EXISTS node_worker_launch_containers (
  launch_id TEXT PRIMARY KEY,
  container_json TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS node_worker_launch_cleanup (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  cleanup_mode TEXT NOT NULL CHECK (cleanup_mode IN ('process-group', 'owned-anchor')),
  lineage_settled INTEGER CHECK (lineage_settled IS NULL OR lineage_settled = 1)
) STRICT;

-- Older readers retain owned-anchor custody: lineage EOF is not this certificate.
CREATE TABLE IF NOT EXISTS node_worker_launch_process_scopes (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  scope_kind TEXT NOT NULL CHECK (scope_kind = 'linux-subreaper'),
  descendants_reaped INTEGER CHECK (descendants_reaped IS NULL OR descendants_reaped = 1)
) STRICT;

-- Turn receipts have a shorter lifetime than their physical worker owner.
-- Keeping the launch running preserves capacity and predecessor cleanup semantics.
CREATE TABLE IF NOT EXISTS node_worker_turns (
  turn_id TEXT NOT NULL PRIMARY KEY
    CHECK (length(turn_id) BETWEEN 1 AND 256 AND instr(turn_id, char(0)) = 0),
  owner_launch_id TEXT NOT NULL
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  plan_hash TEXT NOT NULL
    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),
  run_id TEXT NOT NULL
    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),
  state TEXT NOT NULL
    CHECK (state IN ('running', 'completed', 'failed', 'interrupted', 'cancelled')),
  result_json TEXT CHECK (
    result_json IS NULL
    OR (
      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536
      AND instr(result_json, char(0)) = 0
      AND json_valid(result_json)
    )
  ),
  error_text TEXT CHECK (
    error_text IS NULL
    OR (
      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096
      AND instr(error_text, char(0)) = 0
      AND instr(error_text, char(10)) = 0
      AND instr(error_text, char(13)) = 0
    )
  ),
  completed_at_ms INTEGER CHECK (
    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991
  ),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  updated_at_ms INTEGER NOT NULL 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)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_node_worker_turns_terminal_completed
  ON node_worker_turns(completed_at_ms, turn_id)
  WHERE completed_at_ms IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_node_worker_turns_active_owner
  ON node_worker_turns(owner_launch_id)
  WHERE state = 'running';

CREATE TABLE IF NOT EXISTS config_health_entries (
  config_path TEXT NOT NULL PRIMARY KEY,
  last_known_good_json TEXT,
  last_promoted_good_json TEXT,
  last_observed_suspicious_signature TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS clawhub_promotion_claims (
  slug TEXT NOT NULL PRIMARY KEY,
  provider TEXT,
  model_keys_json TEXT NOT NULL,
  ends_at_ms INTEGER NOT NULL,
  claimed_at_ms INTEGER NOT NULL
) STRICT;



CREATE TABLE IF NOT EXISTS official_external_plugin_catalog_snapshots (
  feed_url TEXT NOT NULL PRIMARY KEY,
  body TEXT NOT NULL,
  status INTEGER NOT NULL,
  etag TEXT,
  last_modified TEXT,
  checksum TEXT NOT NULL,
  saved_at TEXT NOT NULL,
  trust_mode TEXT,
  trust_key_id TEXT,
  trust_signature_count INTEGER,
  trust_threshold INTEGER,
  trust_verified_at TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_official_external_plugin_catalog_snapshots_updated
  ON official_external_plugin_catalog_snapshots(updated_at_ms DESC, feed_url);

CREATE TABLE IF NOT EXISTS update_runs (
  run_id TEXT PRIMARY KEY NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  trigger TEXT NOT NULL CHECK (trigger IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api')),
  phase TEXT NOT NULL CHECK (phase IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished')),
  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped')),
  reason TEXT,
  origin_json TEXT NOT NULL CHECK (length(CAST(origin_json AS BLOB)) <= 16384),
  target_json TEXT NOT NULL CHECK (length(CAST(target_json AS BLOB)) <= 16384),
  before_json TEXT NOT NULL CHECK (length(CAST(before_json AS BLOB)) <= 16384),
  after_json TEXT NOT NULL CHECK (length(CAST(after_json AS BLOB)) <= 16384),
  steps_json TEXT NOT NULL CHECK (length(CAST(steps_json AS BLOB)) <= 16384),
  verification_json TEXT NOT NULL CHECK (length(CAST(verification_json AS BLOB)) <= 16384),
  repair_json TEXT NOT NULL CHECK (length(CAST(repair_json AS BLOB)) <= 16384),
  confirmed_at_ms INTEGER,
  finished_at_ms INTEGER,
  downtime_ms INTEGER,
  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))
) STRICT;

CREATE INDEX IF NOT EXISTS idx_update_runs_created
  ON update_runs(created_at_ms DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_update_runs_active
  ON update_runs(status, created_at_ms DESC, run_id);

CREATE TABLE IF NOT EXISTS gateway_restart_sentinel (
  sentinel_key TEXT NOT NULL PRIMARY KEY,
  version INTEGER NOT NULL,
  kind TEXT NOT NULL,
  status TEXT NOT NULL,
  ts INTEGER NOT NULL,
  session_key TEXT,
  thread_id TEXT,
  delivery_channel TEXT,
  delivery_to TEXT,
  delivery_account_id TEXT,
  message TEXT,
  continuation_json TEXT,
  doctor_hint TEXT,
  stats_json TEXT,
  payload_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_restart_sentinel_ts
  ON gateway_restart_sentinel(ts DESC, sentinel_key);

CREATE TABLE IF NOT EXISTS gateway_restart_intent (
  intent_key TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  pid INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  reason TEXT,
  force INTEGER,
  wait_ms INTEGER,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS gateway_restart_handoff (
  handoff_key TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  version INTEGER NOT NULL,
  intent_id TEXT NOT NULL,
  pid INTEGER NOT NULL,
  process_instance_id TEXT,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL,
  reason TEXT,
  restart_trace_started_at INTEGER,
  restart_trace_last_at INTEGER,
  source TEXT NOT NULL,
  restart_kind TEXT NOT NULL,
  supervisor_mode TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_restart_handoff_expiry
  ON gateway_restart_handoff(expires_at, pid);

CREATE TABLE IF NOT EXISTS gateway_boot_lifecycle (
  boot_id TEXT NOT NULL PRIMARY KEY,
  pid INTEGER NOT NULL,
  started_at_ms INTEGER NOT NULL,
  completed_at_ms INTEGER,
  outcome TEXT,
  startup_reason TEXT,
  reason TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_boot_lifecycle_started
  ON gateway_boot_lifecycle(started_at_ms);

CREATE TABLE IF NOT EXISTS acp_sessions (
  session_key TEXT NOT NULL PRIMARY KEY,
  session_id TEXT,
  backend TEXT NOT NULL,
  agent TEXT NOT NULL,
  runtime_session_name TEXT NOT NULL,
  identity_json TEXT,
  resume_agent_session_id TEXT,
  resume_acpx_session_id TEXT,
  mode TEXT NOT NULL,
  runtime_options_json TEXT,
  cwd TEXT,
  state TEXT NOT NULL,
  last_activity_at INTEGER NOT NULL,
  last_error TEXT,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_acp_sessions_state_activity
  ON acp_sessions(state, last_activity_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_agent_activity
  ON acp_sessions(agent, last_activity_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_agent
  ON acp_sessions(resume_agent_session_id);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_acpx
  ON acp_sessions(resume_acpx_session_id);

CREATE TABLE IF NOT EXISTS acp_replay_sessions (
  session_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  cwd TEXT NOT NULL,
  complete INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  next_seq INTEGER NOT NULL,
  -- Running estimate of this session's ledger footprint (row overhead plus
  -- all event rows), maintained at insert/trim so budget checks never scan
  -- acp_replay_events (#100622).
  estimated_bytes INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_key_updated
  ON acp_replay_sessions(session_key, complete, updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_updated
  ON acp_replay_sessions(updated_at DESC, session_id);

CREATE TABLE IF NOT EXISTS acp_replay_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  at INTEGER NOT NULL,
  session_key TEXT NOT NULL,
  run_id TEXT,
  update_json TEXT NOT NULL,
  estimated_bytes INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES acp_replay_sessions(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS agent_databases (
  agent_id TEXT NOT NULL,
  path TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  last_seen_at INTEGER NOT NULL,
  size_bytes INTEGER,
  PRIMARY KEY (agent_id, path)
) STRICT;

CREATE TABLE IF NOT EXISTS agent_deletion_journal (
  agent_id TEXT PRIMARY KEY,
  operation_id TEXT NOT NULL DEFAULT '',
  phase TEXT,
  agent_dir TEXT NOT NULL,
  workspace_dir TEXT NOT NULL,
  sessions_dir TEXT NOT NULL,
  database_paths_json TEXT NOT NULL DEFAULT '[]',
  cleanup_paths_json TEXT NOT NULL DEFAULT '[]',
  created_at INTEGER NOT NULL,
  cleanup_completed INTEGER NOT NULL DEFAULT 0,
  delete_files INTEGER NOT NULL DEFAULT 1
) STRICT;

CREATE TABLE IF NOT EXISTS agent_provenance (
  agent_id TEXT PRIMARY KEY,
  created_via TEXT NOT NULL CHECK (created_via IN ('operator', 'agent', 'template')),
  creator_agent_id TEXT,
  created_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS agent_database_leases (
  lease_id TEXT PRIMARY KEY,
  agent_id TEXT NOT NULL,
  path TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  opened_at INTEGER NOT NULL,
  provenance TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS plugin_state_entries (
  plugin_id TEXT NOT NULL,
  namespace TEXT NOT NULL,
  entry_key TEXT NOT NULL,
  value_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER,
  PRIMARY KEY (plugin_id, namespace, entry_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_state_expiry
  ON plugin_state_entries(expires_at)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_state_listing
  ON plugin_state_entries(plugin_id, namespace, created_at, entry_key, expires_at);

CREATE TABLE IF NOT EXISTS channel_ingress_events (
  queue_name TEXT NOT NULL,
  event_id TEXT NOT NULL,
  channel_id TEXT NOT NULL,
  account_id TEXT NOT NULL,
  status TEXT NOT NULL,
  lane_key TEXT,
  payload_json TEXT NOT NULL,
  metadata_json TEXT,
  received_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  claim_token TEXT,
  claim_owner TEXT,
  claimed_at INTEGER,
  attempts INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  failed_reason TEXT,
  failed_at INTEGER,
  completed_at INTEGER,
  completed_metadata_json TEXT,
  PRIMARY KEY (queue_name, event_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_ingress_pending
  ON channel_ingress_events(queue_name, status, received_at, event_id);

CREATE INDEX IF NOT EXISTS idx_channel_ingress_claims
  ON channel_ingress_events(queue_name, status, claimed_at);

CREATE INDEX IF NOT EXISTS idx_channel_ingress_lane
  ON channel_ingress_events(queue_name, status, lane_key);

CREATE TABLE IF NOT EXISTS plugin_blob_entries (
  plugin_id TEXT NOT NULL,
  namespace TEXT NOT NULL,
  entry_key TEXT NOT NULL,
  metadata_json TEXT NOT NULL,
  blob BLOB NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER,
  PRIMARY KEY (plugin_id, namespace, entry_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_blob_expiry
  ON plugin_blob_entries(expires_at)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_blob_listing
  ON plugin_blob_entries(plugin_id, namespace, created_at, entry_key);

CREATE TABLE IF NOT EXISTS skill_uploads (
  upload_id TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  slug TEXT NOT NULL,
  force INTEGER NOT NULL,
  size_bytes INTEGER NOT NULL,
  sha256 TEXT,
  actual_sha256 TEXT,
  received_bytes INTEGER NOT NULL,
  archive_blob BLOB NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL,
  committed INTEGER NOT NULL,
  committed_at INTEGER,
  idempotency_key_hash TEXT UNIQUE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_skill_uploads_expiry
  ON skill_uploads(expires_at);

CREATE INDEX IF NOT EXISTS idx_skill_uploads_idempotency
  ON skill_uploads(idempotency_key_hash)
  WHERE idempotency_key_hash IS NOT NULL;

CREATE TABLE IF NOT EXISTS skill_upload_chunks (
  upload_id TEXT NOT NULL,
  byte_offset INTEGER NOT NULL CHECK (byte_offset >= 0),
  size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
  chunk_blob BLOB NOT NULL,
  PRIMARY KEY (upload_id, byte_offset),
  FOREIGN KEY (upload_id) REFERENCES skill_uploads(upload_id) ON DELETE CASCADE,
  CHECK (length(chunk_blob) = size_bytes)
) STRICT;

CREATE TABLE IF NOT EXISTS capture_sessions (
  id TEXT NOT NULL PRIMARY KEY,
  started_at INTEGER NOT NULL,
  ended_at INTEGER,
  mode TEXT NOT NULL,
  source_scope TEXT NOT NULL,
  source_process TEXT NOT NULL,
  proxy_url TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS capture_blobs (
  blob_id TEXT NOT NULL PRIMARY KEY,
  content_type TEXT,
  encoding TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  sha256 TEXT NOT NULL,
  data BLOB NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS capture_events (
  id INTEGER NOT NULL PRIMARY KEY,
  session_id TEXT NOT NULL,
  ts INTEGER NOT NULL,
  source_scope TEXT NOT NULL,
  source_process TEXT NOT NULL,
  protocol TEXT NOT NULL,
  direction TEXT NOT NULL,
  kind TEXT NOT NULL,
  flow_id TEXT NOT NULL,
  method TEXT,
  host TEXT,
  path TEXT,
  status INTEGER,
  close_code INTEGER,
  content_type TEXT,
  headers_json TEXT,
  data_text TEXT,
  data_blob_id TEXT,
  data_sha256 TEXT,
  error_text TEXT,
  meta_json TEXT,
  FOREIGN KEY (session_id) REFERENCES capture_sessions(id) ON DELETE CASCADE,
  FOREIGN KEY (data_blob_id) REFERENCES capture_blobs(blob_id) ON DELETE SET NULL
) STRICT;

CREATE INDEX IF NOT EXISTS capture_events_session_ts_idx
  ON capture_events(session_id, ts);

CREATE INDEX IF NOT EXISTS capture_events_flow_idx
  ON capture_events(flow_id, ts);

CREATE TABLE IF NOT EXISTS sandbox_registry_entries (
  registry_kind TEXT NOT NULL,
  container_name TEXT NOT NULL,
  session_key TEXT,
  backend_id TEXT,
  runtime_label TEXT,
  image TEXT,
  created_at_ms INTEGER,
  last_used_at_ms INTEGER,
  config_label_kind TEXT,
  config_hash TEXT,
  cdp_port INTEGER,
  no_vnc_port INTEGER,
  entry_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (registry_kind, container_name)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_updated
  ON sandbox_registry_entries(registry_kind, updated_at DESC, container_name);

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_session
  ON sandbox_registry_entries(registry_kind, session_key, last_used_at_ms DESC, container_name)
  WHERE session_key IS NOT NULL;

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

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

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container
  ON sandbox_persistent_execs(container_id, owner_key);

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container_name
  ON sandbox_persistent_execs(container_name, owner_key);

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_source
  ON sandbox_persistent_execs(source_identity, owner_key);

CREATE TABLE IF NOT EXISTS cron_jobs (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  declaration_key TEXT,
  owner_agent_id TEXT,
  name TEXT NOT NULL,
  description TEXT,
  enabled INTEGER NOT NULL,
  agent_id TEXT,
  payload_kind TEXT NOT NULL,
  job_json TEXT NOT NULL,
  grant_definition_revision TEXT,
  grant_definition_generation INTEGER,
  grant_definition_updated_at INTEGER,
  state_json TEXT NOT NULL DEFAULT '{}',
  runtime_updated_at_ms INTEGER,
  schedule_identity TEXT,
  sort_order INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_cron_jobs_store_order
  ON cron_jobs(store_key, sort_order ASC, updated_at ASC, job_id);

-- One owner-native receipt is also the durable execution fence. Receipts
-- survive job deletion so operators can distinguish a run from log inference.
CREATE TABLE IF NOT EXISTS cron_run_receipts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT PRIMARY KEY,
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  config_revision TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  request_run_id TEXT,
  delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started')),
  status TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  started_at_ms INTEGER NOT NULL,
  finished_at_ms INTEGER,
  error_text TEXT,
  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)
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS cron_run_receipts_cursor_id_idx
  ON cron_run_receipts(cursor_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_cron_run_receipts_active_job
  ON cron_run_receipts(store_key, job_id)
  WHERE status = 'running';

CREATE INDEX IF NOT EXISTS idx_cron_run_receipts_job_history
  ON cron_run_receipts(store_key, job_id, started_at_ms DESC, receipt_id DESC);

-- Retirement follows the receipt's retention without changing its released shape.
CREATE TABLE IF NOT EXISTS cron_run_trigger_state_retirements (
  receipt_id TEXT PRIMARY KEY
    REFERENCES cron_run_receipts(receipt_id) ON DELETE CASCADE
) STRICT;

-- Runtime-private authority is independent of job_json so downgraded writers
-- can rewrite recognized job config without erasing or silently widening it.
CREATE TABLE IF NOT EXISTS cron_job_runtime_authorities (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  authority_json TEXT,
  authority_input_fingerprint TEXT,
  recovery_required INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  FOREIGN KEY (store_key, job_id)
    REFERENCES cron_jobs(store_key, job_id) ON DELETE CASCADE,
  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)
  )
) STRICT;

-- Scratch is separate from cron_jobs so scheduler state writes and downgraded
-- full-row replacement preserve it. New builds prune rows explicitly on job removal.
-- content NULL is a tombstone: it keeps the revision lineage monotonic across
-- unset/recreate so stale compare-and-swap writes cannot resurrect old content.
CREATE TABLE IF NOT EXISTS cron_job_scratch (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  content TEXT,
  revision INTEGER NOT NULL,
  source_sha256 TEXT,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  CHECK (revision >= 1),
  CHECK (content IS NULL OR length(CAST(content AS BLOB)) <= 262144)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_cron_job_scratch_store_updated
  ON cron_job_scratch(store_key, updated_at_ms DESC, job_id);

CREATE TABLE IF NOT EXISTS delivery_queue_entries (
  queue_name TEXT NOT NULL,
  id TEXT NOT NULL,
  status TEXT NOT NULL,
  entry_kind TEXT,
  session_key TEXT,
  channel TEXT,
  target TEXT,
  account_id TEXT,
  retry_count INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  recovery_state TEXT,
  platform_send_started_at INTEGER,
  entry_json TEXT NOT NULL,
  retention_id_prefix TEXT,
  retention_max_age_ms INTEGER,
  retention_max_entries INTEGER,
  enqueued_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  failed_at INTEGER,
  PRIMARY KEY (queue_name, id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_pending
  ON delivery_queue_entries(queue_name, status, enqueued_at, id);

CREATE INDEX IF NOT EXISTS idx_delivery_queue_failed
  ON delivery_queue_entries(status, queue_name, failed_at, id);

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

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

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

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

CREATE INDEX IF NOT EXISTS idx_task_runs_runtime_run
  ON task_runs(runtime, run_id, source_id, created_at, task_id);
CREATE INDEX IF NOT EXISTS idx_task_runs_cron_runtime_order
  ON task_runs(runtime, created_at, task_id) WHERE runtime = 'cron';
CREATE INDEX IF NOT EXISTS idx_task_runs_cron_source_order
  ON task_runs(source_id, created_at, task_id) WHERE runtime = 'cron';

CREATE TABLE IF NOT EXISTS subagent_runs (
  run_id TEXT NOT NULL PRIMARY KEY,
  child_session_key TEXT NOT NULL,
  controller_session_key TEXT,
  controller_store_path TEXT,
  requester_session_key TEXT NOT NULL,
  requester_store_path TEXT,
  created_at INTEGER NOT NULL,
  payload_json TEXT NOT NULL DEFAULT '{}'
) STRICT;

CREATE INDEX IF NOT EXISTS idx_subagent_runs_child_session_key
  ON subagent_runs(child_session_key, created_at DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_subagent_runs_requester_session_key
  ON subagent_runs(requester_session_key, created_at DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_subagent_runs_controller_session_key
  ON subagent_runs(controller_session_key, created_at DESC, run_id);

CREATE TABLE IF NOT EXISTS current_conversation_bindings (
  binding_key TEXT NOT NULL PRIMARY KEY,
  binding_id TEXT NOT NULL,
  target_session_key TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  conversation_kind TEXT NOT NULL,
  parent_conversation_id TEXT,
  conversation_id TEXT NOT NULL,
  target_kind TEXT NOT NULL,
  status TEXT NOT NULL,
  bound_at INTEGER NOT NULL,
  expires_at INTEGER,
  metadata_json TEXT,
  record_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_target
  ON current_conversation_bindings(target_session_key, updated_at DESC, binding_key);
CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_conversation
  ON current_conversation_bindings(channel, account_id, conversation_kind, conversation_id);
CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_expires
  ON current_conversation_bindings(expires_at, binding_key);

CREATE TABLE IF NOT EXISTS plugin_binding_approvals (
  plugin_root TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  plugin_id TEXT NOT NULL,
  plugin_name TEXT,
  approved_at INTEGER NOT NULL,
  PRIMARY KEY (plugin_root, channel, account_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_binding_approvals_plugin
  ON plugin_binding_approvals(plugin_id, approved_at DESC);

CREATE TABLE IF NOT EXISTS task_delivery_state (
  task_id TEXT NOT NULL PRIMARY KEY,
  requester_origin_json TEXT,
  last_notified_event_at INTEGER,
  FOREIGN KEY (task_id) REFERENCES task_runs(task_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS flow_runs (
  flow_id TEXT NOT NULL PRIMARY KEY,
  shape TEXT,
  sync_mode TEXT NOT NULL DEFAULT 'managed',
  owner_key TEXT NOT NULL,
  requester_origin_json TEXT,
  controller_id TEXT,
  revision INTEGER NOT NULL DEFAULT 0,
  status TEXT NOT NULL,
  notify_policy TEXT NOT NULL,
  goal TEXT NOT NULL,
  current_step TEXT,
  blocked_task_id TEXT,
  blocked_summary TEXT,
  state_json TEXT,
  wait_json TEXT,
  cancel_requested_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  ended_at INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_flow_runs_status ON flow_runs(status);
CREATE INDEX IF NOT EXISTS idx_flow_runs_owner_key ON flow_runs(owner_key);
CREATE INDEX IF NOT EXISTS idx_flow_runs_updated_at ON flow_runs(updated_at);

-- Durable meeting-capture sessions are gateway-global rather than agent-session
-- transcripts. JSON/JSONL files are doctor import inputs or explicit CLI exports.
CREATE TABLE IF NOT EXISTS meeting_transcript_sessions (
  started_at_ms INTEGER,
  session_id TEXT NOT NULL,
  started_at TEXT NOT NULL,
  selector TEXT NOT NULL UNIQUE,
  export_key TEXT NOT NULL,
  session_slug TEXT NOT NULL,
  provider_id TEXT NOT NULL,
  title TEXT,
  source_json TEXT NOT NULL,
  source_account_id TEXT,
  source_guild_id TEXT,
  source_channel_id TEXT,
  source_meeting_url TEXT,
  source_thread_ts TEXT,
  source_file_id TEXT,
  stopped_at TEXT,
  metadata_json TEXT,
  metadata_agent_id TEXT,
  export_manifest_json TEXT NOT NULL DEFAULT '{}',
  export_pending_json TEXT NOT NULL DEFAULT '[]',
  next_utterance_seq INTEGER NOT NULL DEFAULT 0 CHECK (next_utterance_seq >= 0),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, started_at)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_started
  ON meeting_transcript_sessions(started_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_chronology
  ON meeting_transcript_sessions(started_at_ms DESC, session_id ASC, started_at ASC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_id
  ON meeting_transcript_sessions(session_id, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_slug
  ON meeting_transcript_sessions(session_slug, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_export_key
  ON meeting_transcript_sessions(export_key);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_source
  ON meeting_transcript_sessions(provider_id, source_account_id, source_guild_id,
    source_channel_id, source_meeting_url, source_thread_ts, source_file_id,
    stopped_at DESC, started_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_account
  ON meeting_transcript_sessions(source_account_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_agent
  ON meeting_transcript_sessions(metadata_agent_id);

CREATE TABLE IF NOT EXISTS meeting_transcript_utterances (
  session_id TEXT NOT NULL,
  session_started_at TEXT NOT NULL,
  sequence INTEGER NOT NULL CHECK (sequence >= 0),
  utterance_id TEXT,
  started_at TEXT,
  ended_at TEXT,
  speaker_id TEXT,
  speaker_label TEXT,
  text TEXT NOT NULL,
  final INTEGER CHECK (final IN (0, 1)),
  metadata_json TEXT,
  PRIMARY KEY (session_id, session_started_at, sequence),
  FOREIGN KEY (session_id, session_started_at)
    REFERENCES meeting_transcript_sessions(session_id, started_at)
    ON DELETE CASCADE
) STRICT;

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

CREATE TABLE IF NOT EXISTS meeting_transcript_summaries (
  session_id TEXT NOT NULL,
  session_started_at TEXT NOT NULL,
  generated_at TEXT,
  summary_json TEXT,
  overview TEXT,
  markdown TEXT,
  utterance_count INTEGER NOT NULL CHECK (utterance_count >= 0),
  PRIMARY KEY (session_id, session_started_at),
  FOREIGN KEY (session_id, session_started_at)
    REFERENCES meeting_transcript_sessions(session_id, started_at)
    ON DELETE CASCADE,
  CHECK (summary_json IS NOT NULL OR markdown IS NOT NULL)
) STRICT;

CREATE TABLE IF NOT EXISTS migration_runs (
  id TEXT NOT NULL PRIMARY KEY,
  started_at INTEGER NOT NULL,
  finished_at INTEGER,
  status TEXT NOT NULL,
  report_json TEXT NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_migration_runs_started
  ON migration_runs(started_at DESC, id);

CREATE TABLE IF NOT EXISTS migration_sources (
  source_key TEXT NOT NULL PRIMARY KEY,
  migration_kind TEXT NOT NULL,
  source_path TEXT NOT NULL,
  target_table TEXT NOT NULL,
  source_sha256 TEXT,
  source_size_bytes INTEGER,
  source_record_count INTEGER,
  last_run_id TEXT NOT NULL,
  status TEXT NOT NULL,
  imported_at INTEGER NOT NULL,
  removed_source INTEGER NOT NULL DEFAULT 0,
  report_json TEXT NOT NULL,
  FOREIGN KEY (last_run_id) REFERENCES migration_runs(id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_migration_sources_path
  ON migration_sources(source_path, migration_kind, target_table);

CREATE INDEX IF NOT EXISTS idx_migration_sources_run
  ON migration_sources(last_run_id, source_path);

CREATE TABLE IF NOT EXISTS backup_runs (
  id TEXT NOT NULL PRIMARY KEY,
  created_at INTEGER NOT NULL,
  archive_path TEXT NOT NULL,
  status TEXT NOT NULL,
  manifest_json TEXT NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_backup_runs_created
  ON backup_runs(created_at DESC, id);

CREATE TABLE IF NOT EXISTS worktrees (
  id TEXT NOT NULL PRIMARY KEY,
  repo_fingerprint TEXT NOT NULL,
  repo_root TEXT NOT NULL,
  path TEXT NOT NULL,
  branch TEXT NOT NULL,
  base_ref TEXT NOT NULL,
  owner_kind TEXT NOT NULL CHECK (owner_kind IN ('manual', 'workboard', 'session')),
  owner_id TEXT,
  snapshot_ref TEXT,
  provisioned_paths_json TEXT,
  created_at INTEGER NOT NULL,
  last_active_at INTEGER NOT NULL,
  removed_at INTEGER,
  run_end_cleanup_json TEXT,
  gc_protection_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_worktrees_repo_fingerprint
  ON worktrees(repo_fingerprint);

CREATE INDEX IF NOT EXISTS idx_worktrees_removed_at
  ON worktrees(removed_at);

CREATE TABLE IF NOT EXISTS worktree_provisioned_file_chunks (
  worktree_id TEXT NOT NULL,
  path TEXT NOT NULL,
  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
  data BLOB NOT NULL,
  PRIMARY KEY (worktree_id, path, chunk_index)
) STRICT;

CREATE TABLE IF NOT EXISTS worktree_templates (
  cache_key TEXT NOT NULL PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  repo_root TEXT NOT NULL,
  common_dir TEXT NOT NULL,
  worktree_root TEXT NOT NULL,
  path TEXT NOT NULL,
  backend TEXT NOT NULL,
  source_commit TEXT NOT NULL,
  content_key TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('preparing', 'ready')),
  created_at INTEGER NOT NULL,
  last_used_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS projects (
  id TEXT NOT NULL PRIMARY KEY,
  display_name TEXT NOT NULL,
  repo_root TEXT NOT NULL,
  origin_url TEXT,
  source TEXT NOT NULL CHECK (source IN ('registered', 'cloned')),
  created_at_ms INT NOT NULL,
  updated_at_ms INT NOT NULL
) STRICT;

-- One explicitly retained, normalized private background per durable profile.
CREATE TABLE IF NOT EXISTS user_background_images (
  profile_id TEXT NOT NULL PRIMARY KEY REFERENCES user_profiles(id) ON DELETE CASCADE,
  asset_id TEXT NOT NULL UNIQUE,
  image BLOB NOT NULL CHECK (length(image) BETWEEN 1 AND 2097152),
  width INTEGER NOT NULL CHECK (width BETWEEN 1 AND 2560),
  height INTEGER NOT NULL CHECK (height BETWEEN 1 AND 2560)
) STRICT;

CREATE TABLE IF NOT EXISTS user_preferences (
  profile_id TEXT NOT NULL,
  pref_key TEXT NOT NULL,
  value_json TEXT NOT NULL,
  updated_at_ms INT NOT NULL,
  PRIMARY KEY (profile_id, pref_key)
) STRICT;

-- Gateway-owned custom session group catalog (names + display order).
-- Membership stays on each session entry's category field; this table only
-- owns which groups exist and how operator UIs order them.
CREATE TABLE IF NOT EXISTS session_groups (
  name TEXT NOT NULL PRIMARY KEY,
  position INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  cwd TEXT,
  worktree INTEGER
) STRICT;

-- Gateway-owned durable cloud worker lifecycle. Provider-specific execution
-- stays in plugins; this table records only core reconciliation facts.
CREATE TABLE IF NOT EXISTS worker_environments (
  environment_id TEXT NOT NULL PRIMARY KEY,
  provider_id TEXT NOT NULL,
  profile_id TEXT NOT NULL,
  profile_snapshot_json TEXT NOT NULL,
  last_activated_at_ms INTEGER,
  preparation_key TEXT,
  preparation_purpose TEXT,
  preparation_demand_at_ms INTEGER,
  preparation_expires_at_ms INTEGER,
  preparation_consumed_at_ms INTEGER 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 length(preparation_key) = 64
      AND preparation_key NOT GLOB '*[^0-9a-f]*'
      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)))
  ),
  provision_operation_id TEXT NOT NULL UNIQUE,
  lease_id TEXT,
  node_setup_id TEXT,
  node_device_id TEXT,
  ssh_host TEXT,
  ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)),
  ssh_user TEXT,
  ssh_host_key TEXT,
  ssh_key_ref_json TEXT,
  desktop_json TEXT,
  state TEXT NOT NULL CHECK (
    state IN (
      'requested',
      'provisioning',
      'bootstrapping',
      'ready',
      'attached',
      'idle',
      'draining',
      'destroying',
      'destroyed',
      'failed',
      'orphaned'
    )
  ),
  bootstrap_bundle_hash TEXT,
  bootstrap_openclaw_version TEXT,
  bootstrap_protocol_features_json TEXT,
  bootstrap_install_kind TEXT,
  owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0),
  teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed')),
  attached_session_ids_json TEXT NOT NULL DEFAULT '[]',
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  state_changed_at_ms INTEGER NOT NULL,
  idle_since_at_ms INTEGER,
  destroy_requested_at_ms INTEGER,
  last_error TEXT,
  shared_host INTEGER
) STRICT;

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

CREATE INDEX IF NOT EXISTS idx_worker_environments_terminal_changed
  ON worker_environments(state_changed_at_ms, environment_id);

-- A dedicated node registers its fixed build paths before ready, then binds
-- them once. The environment belongs to the Gateway's separate database.
CREATE TABLE IF NOT EXISTS node_worker_prepared_workspaces (
  preparation_key TEXT NOT NULL PRIMARY KEY CHECK (
    length(preparation_key) = 64 AND preparation_key NOT GLOB '*[^0-9a-f]*'
  ),
  cache_key TEXT NOT NULL CHECK (
    length(cache_key) = 64 AND cache_key NOT GLOB '*[^0-9a-f]*'
  ),
  gateway_namespace TEXT NOT NULL CHECK (length(gateway_namespace) > 0),
  workspace_dir TEXT NOT NULL UNIQUE CHECK (length(workspace_dir) > 0),
  home_dir TEXT NOT NULL CHECK (length(home_dir) > 0),
  source_manifest_ref TEXT NOT NULL CHECK (
    length(source_manifest_ref) = 71 AND substr(source_manifest_ref, 1, 7) = 'sha256:'
      AND substr(source_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'
  ),
  prepared_manifest_ref TEXT NOT NULL CHECK (
    length(prepared_manifest_ref) = 71 AND substr(prepared_manifest_ref, 1, 7) = 'sha256:'
      AND substr(prepared_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'
  ),
  state TEXT NOT NULL CHECK (state IN ('available', 'bound', 'retiring', 'retired')),
  environment_id TEXT NOT NULL CHECK (length(environment_id) > 0),
  session_id TEXT,
  session_key TEXT,
  owner_epoch INTEGER CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  bound_at_ms INTEGER CHECK (bound_at_ms BETWEEN created_at_ms AND 9007199254740991),
  retired_at_ms INTEGER 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 length(session_id) > 0
      AND session_key IS NOT NULL AND 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)
  )
) STRICT;

-- Provider-advertised fallback ports preserve stable retry order separately
-- from the downgrade-sensitive canonical worker environment row.
CREATE TABLE IF NOT EXISTS worker_environment_ssh_fallback_ports (
  environment_id TEXT NOT NULL,
  position INTEGER NOT NULL CHECK (position >= 0 AND position <= 9),
  port INTEGER NOT NULL CHECK (port >= 1 AND port <= 65535),
  PRIMARY KEY (environment_id, position),
  UNIQUE (environment_id, port),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;

-- Logical sessions own repository intent and accepted artifact references,
-- independently of the worker or rotating transcript session id.
CREATE TABLE IF NOT EXISTS session_repository_workspaces (
  workspace_id TEXT NOT NULL PRIMARY KEY CHECK (length(workspace_id) = 36),
  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),
  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),
  url TEXT NOT NULL CHECK (length(url) BETWEEN 1 AND 4096),
  requested_ref TEXT CHECK (requested_ref IS NULL OR length(requested_ref) BETWEEN 1 AND 1024),
  run_setup_script INTEGER NOT NULL DEFAULT 0 CHECK (run_setup_script IN (0, 1)),
  base_commit TEXT CHECK (base_commit IS NULL OR length(base_commit) IN (40, 64)),
  base_manifest_hash TEXT,
  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),
  checkpoint_ref TEXT,
  manifest_hash TEXT,
  revision INTEGER NOT NULL CHECK (revision >= 0),
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  UNIQUE (agent_id, session_key),
  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))
) STRICT;

CREATE TABLE IF NOT EXISTS github_repository_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT,
  connection_generation TEXT,
  idempotency_key TEXT NOT NULL,
  request_digest TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_lifecycle_revision TEXT,
  requester_authority_json TEXT,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  workspace_id TEXT NOT NULL,
  checkpoint_ref TEXT,
  checkpoint_digest TEXT,
  claim_id TEXT,
  run_id TEXT,
  environment_id TEXT,
  owner_epoch INTEGER,
  placement_generation INTEGER,
  identity_source TEXT NOT NULL CHECK (identity_source IN ('system-detected', 'system-configured', 'agent-override', 'personal')),
  identity_profile_id TEXT,
  identity_account_id INTEGER NOT NULL,
  identity_login TEXT NOT NULL,
  title TEXT,
  body TEXT,
  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),
  gateway_instance_id TEXT,
  execution_id TEXT,
  last_effect TEXT CHECK (last_effect IN ('push', 'pull_request')),
  effect_state TEXT CHECK (effect_state IN ('dispatched', 'observed')),
  push_repository TEXT,
  repository TEXT,
  branch TEXT NOT NULL,
  base_branch TEXT,
  source_head_commit TEXT,
  source_index_tree TEXT,
  workspace_tree TEXT,
  previous_head_commit TEXT,
  pushed_head_commit TEXT,
  head_commit TEXT,
  pull_request_url TEXT,
  error_code TEXT,
  next_action TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  reported_at_ms INTEGER,
  draft INTEGER,
  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))
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_shared_request
  ON github_repository_publication_requests(session_id, idempotency_key) WHERE owner_profile_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_personal_request
  ON github_repository_publication_requests(owner_profile_id, session_id, idempotency_key) WHERE owner_profile_id IS NOT NULL;

-- Session placement lives in the shared state database so local admission,
-- worker admission, and environment attachment use one durable authority.
CREATE TABLE IF NOT EXISTS worker_session_placements (
  session_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  execution_mode TEXT CHECK (execution_mode IN ('worker-turn', 'remote-exec')),
  state TEXT NOT NULL CHECK (
    state IN (
      'local',
      'requested',
      'provisioning',
      'syncing',
      'starting',
      'active',
      'draining',
      'reconciling',
      'reclaimed',
      'failed'
    )
  ),
  environment_id TEXT,
  transition_generation INTEGER NOT NULL DEFAULT 0 CHECK (transition_generation >= 0),
  active_owner_epoch INTEGER CHECK (active_owner_epoch IS NULL OR active_owner_epoch >= 1),
  workspace_base_manifest_ref TEXT,
  remote_workspace_dir TEXT,
  worker_bundle_hash TEXT,
  last_transcript_ack_cursor INTEGER CHECK (
    last_transcript_ack_cursor IS NULL OR last_transcript_ack_cursor >= 0
  ),
  last_live_event_ack_cursor INTEGER CHECK (
    last_live_event_ack_cursor IS NULL OR last_live_event_ack_cursor >= 0
  ),
  recovery_error TEXT,
  turn_claim_owner TEXT CHECK (turn_claim_owner IN ('local', 'worker')),
  turn_claim_id TEXT,
  turn_claim_run_id TEXT,
  turn_claim_generation INTEGER CHECK (
    turn_claim_generation IS NULL OR turn_claim_generation >= 0
  ),
  turn_claim_owner_epoch INTEGER CHECK (
    turn_claim_owner_epoch IS NULL OR turn_claim_owner_epoch >= 1
  ),
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  state_changed_at_ms INTEGER NOT NULL,
  terminal_reason TEXT,
  terminal_at_ms INTEGER,
  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 '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 '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 '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 '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 '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 '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 '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 'local' AND (
      state IN ('local', 'requested', 'failed')
      OR (state IN ('active', 'draining') AND execution_mode IS 'remote-exec')
    ))
    OR
    (turn_claim_owner IS 'worker' AND state IN ('active', 'draining')
      AND (execution_mode IS NULL OR execution_mode IS 'worker-turn')
      AND turn_claim_owner_epoch IS active_owner_epoch)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_session_key
  ON worker_session_placements(agent_id, session_key);

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_reconcile
  ON worker_session_placements(updated_at_ms, session_id);

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_environment
  ON worker_session_placements(environment_id)
  WHERE environment_id IS NOT NULL;

-- Planned placement moves retain their exact source CAS and bounded target
-- without widening the stable placement-state vocabulary. The opaque operation
-- id fences stale asynchronous completion; it is correlation, never authority.
CREATE TABLE IF NOT EXISTS worker_session_placement_moves (
  operation_id TEXT NOT NULL PRIMARY KEY,
  session_id TEXT NOT NULL UNIQUE
    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE,
  source_generation INTEGER NOT NULL CHECK (source_generation >= 0),
  source_environment_id TEXT NOT NULL CHECK (
    length(source_environment_id) BETWEEN 1 AND 256
    AND source_environment_id = trim(source_environment_id)
  ),
  source_owner_epoch INTEGER NOT NULL CHECK (source_owner_epoch >= 1),
  target_kind TEXT NOT NULL CHECK (target_kind IN ('gateway', 'profile', 'device')),
  target_id TEXT,
  -- Keep these nullable columns constraint-free so lazy ALTER TABLE produces the
  -- same shape as fresh databases; placement-move code validates their values.
  target_machine_class TEXT,
  target_os TEXT,
  -- Explicit source abandonment is a durable operator decision. Keep the bit
  -- bare and nullable so same-version older readers can safely omit it.
  abandon_source INTEGER,
  last_error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  CHECK (
    (target_kind IS 'gateway' AND target_id IS NULL)
    OR
    (target_kind IN ('profile', 'device')
      AND target_id IS NOT NULL
      AND length(target_id) BETWEEN 1 AND 256
      AND target_id = trim(target_id))
  )
) STRICT;

-- Worker-visible session RPC authority is persisted against the exact turn
-- claim. The launch descriptor is informative only; Gateway dispatch always
-- revalidates this record and the live placement claim before executing.
CREATE TABLE IF NOT EXISTS worker_turn_tool_authorities (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  claim_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  tool_names_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- Tool-call ids are idempotency keys only within one exact source turn claim.
-- A running operation from another Gateway instance is ambiguous and is never
-- replayed. A persisted random seed separates durable downstream identities
-- from Gateway authentication keys and survives ordinary process restarts.
CREATE TABLE IF NOT EXISTS worker_session_tool_operations (
  source_session_id TEXT NOT NULL,
  source_claim_id TEXT NOT NULL,
  tool_call_id TEXT NOT NULL,
  tool_name TEXT NOT NULL CHECK (tool_name IN ('sessions_spawn', 'sessions_send')),
  request_digest TEXT NOT NULL,
  operation_seed TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'unknown')),
  child_session_key TEXT,
  result_json TEXT,
  gateway_instance_id TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (source_session_id, source_claim_id, tool_call_id),
  FOREIGN KEY (source_session_id)
    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- Local sandbox execution is a projection of a session-owned managed worktree.
-- No cascade: an older binary must not discard pending edits with a session row.
CREATE TABLE IF NOT EXISTS local_workspace_projections (
  worktree_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  projection_path TEXT NOT NULL UNIQUE,
  base_commit TEXT NOT NULL,
  source_paths_json TEXT NOT NULL,
  baseline_json TEXT,
  baseline_ref TEXT,
  pending_ref TEXT,
  pending_target TEXT CHECK (pending_target IN ('canonical', 'projection')),
  paused_runtimes_json TEXT,
  journal_json TEXT,
  journal_pack BLOB CHECK (journal_pack IS NULL OR length(journal_pack) <= 268435456),
  revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),
  created_at_ms INTEGER NOT NULL,
  checkpoint_json TEXT,
  tree_root_digest BLOB,
  source_paths_digest BLOB,
  canonical_fingerprints BLOB,
  projection_fingerprints BLOB,
  CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL),
  CHECK ((journal_json IS NULL) = (journal_pack IS NULL))
) STRICT;

-- The projection owner advances changed nodes and its root in one acceptance.
-- Legacy baseline_json remains only until that owner's resumable conversion.
CREATE TABLE IF NOT EXISTS local_workspace_manifest_nodes (
  worktree_id TEXT NOT NULL,
  path TEXT NOT NULL,
  node_json TEXT NOT NULL,
  PRIMARY KEY (worktree_id, path),
  FOREIGN KEY (worktree_id)
    REFERENCES local_workspace_projections(worktree_id) ON DELETE CASCADE
) STRICT;

-- Immutable subtrees and source inventories are shared across projections and revisions.
-- Large JSON packs measured 410k VFS reads/load WITHOUT ROWID versus 10k with rowid.
CREATE TABLE IF NOT EXISTS local_workspace_tree_packs (
  tree_digest BLOB NOT NULL PRIMARY KEY CHECK (length(tree_digest) = 32),
  records_json TEXT NOT NULL,
  children_json TEXT NOT NULL,
  sweep_epoch INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS local_workspace_source_path_sets (
  path_digest BLOB NOT NULL PRIMARY KEY CHECK (length(path_digest) = 32),
  paths_zstd BLOB NOT NULL,
  sweep_epoch INTEGER NOT NULL
) STRICT, WITHOUT ROWID;

-- A reconciliation journal is written before managed-worktree mutation. The
-- bounded Git base snapshot repairs any subset left by an interrupted apply.
CREATE TABLE IF NOT EXISTS worker_workspace_reconciliations (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  base_manifest_ref TEXT NOT NULL,
  current_manifest_ref TEXT NOT NULL,
  plan_json TEXT NOT NULL,
  base_pack BLOB NOT NULL CHECK (length(base_pack) <= 268435456),
  created_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- A completed remote turn is fenced from stale-claim teardown until its
-- workspace result is durably reconciled into the managed worktree.
CREATE TABLE IF NOT EXISTS worker_workspace_pending_results (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  claim_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  gateway_instance_id TEXT NOT NULL,
  recovery_requested_at_ms INTEGER,
  workspace_accepted_at_ms INTEGER,
  staged_result_ref TEXT,
  repository_workspace_id TEXT,
  created_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- GitHub publication intent records the authoritative session worktree. Cloud
-- requests execute only after the exact turn claim's result is accepted locally.
-- Secrets stay in the effective Gateway-owned GitHub profile and never enter
-- this row or the worker protocol.
CREATE TABLE IF NOT EXISTS github_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  idempotency_key TEXT NOT NULL,
  request_digest TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  worktree_id TEXT NOT NULL,
  repository_fingerprint TEXT NOT NULL,
  claim_id TEXT,
  run_id TEXT,
  environment_id TEXT,
  owner_epoch INTEGER CHECK (owner_epoch IS NULL OR owner_epoch >= 1),
  placement_generation INTEGER CHECK (
    placement_generation IS NULL OR placement_generation >= 0
  ),
  identity_source TEXT NOT NULL CHECK (
    identity_source IN ('system-detected', 'system-configured', 'agent-override')
  ),
  identity_profile_id TEXT,
  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),
  identity_login TEXT NOT NULL,
  title TEXT,
  body TEXT,
  status TEXT NOT NULL CHECK (
    status IN ('requested', 'publishing', 'published', 'failed')
  ),
  gateway_instance_id TEXT,
  repository TEXT,
  branch TEXT NOT NULL,
  base_branch TEXT,
  source_head_commit TEXT,
  source_index_tree TEXT,
  workspace_tree TEXT,
  head_commit TEXT,
  pull_request_url TEXT,
  error_code TEXT,
  next_action TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  reported_at_ms INTEGER,
  draft INTEGER,
  UNIQUE (session_id, idempotency_key),
  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 '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 'published' AND pull_request_url IS NOT NULL AND error_code IS NULL
      AND next_action IS NULL)
    OR
    (status IS '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)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_github_publication_requests_pending
  ON github_publication_requests(status, updated_at_ms, request_id);

-- Personal requests cannot be interpreted or resumed by older shared publishers.
CREATE TABLE IF NOT EXISTS github_personal_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY CHECK (length(request_id) = 36),
  owner_profile_id TEXT NOT NULL CHECK (length(owner_profile_id) BETWEEN 1 AND 128),
  connection_generation TEXT NOT NULL CHECK (length(connection_generation) = 36),
  idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) BETWEEN 1 AND 128),
  request_digest TEXT NOT NULL CHECK (length(request_digest) = 64),
  session_id TEXT NOT NULL CHECK (length(session_id) BETWEEN 1 AND 128),
  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),
  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),
  worktree_id TEXT NOT NULL CHECK (length(worktree_id) BETWEEN 1 AND 128),
  repository_fingerprint TEXT NOT NULL CHECK (length(repository_fingerprint) BETWEEN 1 AND 256),
  identity_source TEXT NOT NULL CHECK (identity_source = 'personal'),
  identity_profile_id TEXT NOT NULL CHECK (length(identity_profile_id) = 36),
  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),
  identity_login TEXT NOT NULL CHECK (length(identity_login) BETWEEN 1 AND 39),
  title TEXT CHECK (title IS NULL OR length(title) BETWEEN 1 AND 256),
  body TEXT CHECK (body IS NULL OR length(body) BETWEEN 1 AND 8192),
  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),
  gateway_instance_id TEXT CHECK (gateway_instance_id IS NULL OR length(gateway_instance_id) BETWEEN 1 AND 128),
  execution_id TEXT CHECK (execution_id IS NULL OR length(execution_id) = 36),
  last_effect TEXT CHECK (last_effect IS NULL OR last_effect IN ('push', 'pull_request')),
  effect_state TEXT CHECK (effect_state IS NULL OR effect_state IN ('dispatched', 'observed')),
  push_repository TEXT NOT NULL CHECK (length(push_repository) BETWEEN 3 AND 256),
  repository TEXT NOT NULL CHECK (length(repository) BETWEEN 3 AND 256),
  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),
  base_branch TEXT NOT NULL CHECK (length(base_branch) BETWEEN 1 AND 256),
  source_head_commit TEXT NOT NULL CHECK (length(source_head_commit) IN (40, 64)),
  source_index_tree TEXT NOT NULL CHECK (length(source_index_tree) IN (40, 64)),
  workspace_tree TEXT NOT NULL CHECK (length(workspace_tree) IN (40, 64)),
  head_commit TEXT CHECK (head_commit IS NULL OR length(head_commit) IN (40, 64)),
  pull_request_url TEXT CHECK (pull_request_url IS NULL OR length(pull_request_url) BETWEEN 1 AND 2048),
  error_code TEXT CHECK (error_code IS NULL OR length(error_code) BETWEEN 1 AND 64),
  next_action TEXT CHECK (next_action IS NULL OR length(next_action) BETWEEN 1 AND 1024),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= created_at_ms),
  reported_at_ms INTEGER,
  draft INTEGER,
  UNIQUE (owner_profile_id, session_id, idempotency_key),
  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))
) STRICT;
CREATE INDEX IF NOT EXISTS idx_github_personal_publication_owner_session
  ON github_personal_publication_requests(owner_profile_id, session_id, created_at_ms);
CREATE INDEX IF NOT EXISTS idx_github_personal_publication_pending
  ON github_personal_publication_requests(status, updated_at_ms, request_id);

-- Older readers validate both local receipt tables exactly. Their immutable
-- lifecycle binding stays in a first-use companion so those schemas remain readable.
CREATE TABLE IF NOT EXISTS github_publication_session_lifecycles (
  publication_kind TEXT NOT NULL CHECK (publication_kind IN ('shared', 'personal')),
  request_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  requester_authority_json TEXT,
  PRIMARY KEY (publication_kind, request_id)
) STRICT;

-- One active, opaque admission credential per worker environment. Plaintext
-- may be retried until delivery acknowledgement but never enters durable state.
CREATE TABLE IF NOT EXISTS worker_environment_credentials (
  environment_id TEXT NOT NULL PRIMARY KEY,
  credential_hash TEXT NOT NULL UNIQUE,
  bundle_hash TEXT NOT NULL,
  session_id TEXT,
  rpc_set_version INTEGER NOT NULL CHECK (rpc_set_version >= 1),
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 0),
  expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms >= 0),
  delivered_at_ms INTEGER CHECK (delivered_at_ms >= 0),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;

-- One durable sequence cursor per attached session owner epoch. The environment
-- binding prevents independent workers with coincident epochs from sharing replay state.
CREATE TABLE IF NOT EXISTS worker_transcript_commit_heads (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  environment_id TEXT NOT NULL,
  next_seq INTEGER NOT NULL CHECK (next_seq >= 1),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch)
) STRICT;

-- Pending rows preserve a claimed request across gateway restarts. Terminal rows
-- cache the exact result returned for deterministic at-least-once replay.
CREATE TABLE IF NOT EXISTS worker_transcript_commits (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  seq INTEGER NOT NULL CHECK (seq >= 1),
  request_hash TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),
  result_json TEXT,
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch, seq),
  FOREIGN KEY (session_id, run_epoch)
    REFERENCES worker_transcript_commit_heads(session_id, run_epoch)
    ON DELETE CASCADE,
  CHECK (
    (state = 'pending' AND result_json IS NULL) OR
    (state = 'terminal' AND result_json IS NOT NULL)
  )
) STRICT;

-- Pending rows preserve a claimed inference turn across gateway restarts.
-- Terminal rows cache the exact outcome returned for deterministic replay.
CREATE TABLE IF NOT EXISTS worker_inference_turns (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  run_id TEXT NOT NULL,
  turn_id TEXT NOT NULL,
  environment_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),
  terminal_json TEXT,
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch, run_id, turn_id),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE,
  CHECK (
    (state = 'pending' AND terminal_json IS NULL) OR
    (state = 'terminal' AND terminal_json IS NOT NULL)
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_inference_turns_pending_run
  ON worker_inference_turns(session_id, run_epoch, run_id)
  WHERE state = 'pending';

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

CREATE TABLE IF NOT EXISTS template_workspace_files (
  agent_id TEXT NOT NULL,
  target_path TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  workspace TEXT NOT NULL,
  source_path TEXT NOT NULL,
  content_digest TEXT NOT NULL,
  status TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, target_path)
) STRICT;

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

CREATE TABLE IF NOT EXISTS template_cron_refs (
  agent_id TEXT NOT NULL,
  manifest_id TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  declaration_key TEXT NOT NULL UNIQUE,
  scheduler_job_id TEXT UNIQUE,
  status TEXT NOT NULL,
  job_json TEXT NOT NULL,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, manifest_id)
) STRICT;

CREATE TABLE IF NOT EXISTS template_mcp_server_refs (
  agent_id TEXT NOT NULL,
  name TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  config_digest TEXT NOT NULL,
  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),
  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),
  independent_owner INTEGER NOT NULL DEFAULT 0 CHECK (independent_owner IN (0, 1)),
  status TEXT NOT NULL,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, name)
) STRICT;

CREATE TABLE IF NOT EXISTS user_profile_identities (
  provider TEXT NOT NULL,
  subject TEXT NOT NULL,
  profile_id TEXT NOT NULL,
  canonical_login TEXT,
  -- Host-scoped verified credit evidence; current profile bindings govern attribution.
  verified_email_json TEXT,
  created_at INTEGER NOT NULL,
  authorization_id TEXT,
  authorization_basis_json TEXT,
  PRIMARY KEY (provider, subject)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_user_profile_identities_profile_id
  ON user_profile_identities(profile_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_profile_identities_authorization
  ON user_profile_identities(authorization_id);

CREATE TABLE IF NOT EXISTS outbound_media_provenance (
  realpath TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  version INTEGER NOT NULL,
  sha256 TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  created_at_ms INTEGER NOT NULL
) STRICT;

-- scope_id is non-null because SQLite treats NULLs as distinct in unique indexes/PKs,
-- which would allow duplicate team rows. This PK also avoids a rebuild for identity scope.
CREATE TABLE IF NOT EXISTS secret_store_entries (
  scope_kind TEXT NOT NULL CHECK (scope_kind IN ('team', 'identity')),
  scope_id TEXT NOT NULL,
  name TEXT NOT NULL,
  value TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('secret', 'env')),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  updated_by TEXT,
  deleted_at_ms INTEGER,
  allowed_hosts TEXT,
  CHECK ((scope_kind = 'team' AND scope_id = '') OR (scope_kind = 'identity' AND length(scope_id) > 0)),
  PRIMARY KEY (scope_kind, scope_id, name)
) STRICT;
CREATE INDEX IF NOT EXISTS secret_store_entries_live_idx
  ON secret_store_entries (scope_kind, scope_id, name) WHERE deleted_at_ms IS NULL;
`}));function sqliteDatabaseSealSchemaFor(e){requireNodeSqlite();let t=captureSqliteNativeRuntimeAdmission(),n=t?.storageIdentity;if(!t||!n)return;let r=[t.runtime.nodeVersion,t.runtime.bunVersion??null],i=JSON.stringify([t.version,n.sourceId,n.compileOptions,...r]),a=ye(`sha256`).update(JSON.stringify([ub,i,e])),s=ye(`sha256`).update(e);return e!==`state`&&(a.update(`38`),a.update(ab),s.update(`38`),s.update(ab)),e!==`agent`&&(a.update(`36`),a.update(cb),s.update(`36`),s.update(cb)),{schemaIdentity:a.digest(`hex`),identity:{runtime:JSON.stringify(r),sqlite:{version:t.version,sourceId:n.sourceId,compileOptions:n.compileOptions.split(`,`).filter(e=>!e.startsWith(`COMPILER=`)).join(`,`)},schema:s.digest(`hex`),policy:ub}}}var ub,db=__esmMin((()=>{ib(),ob(),sb(),lb(),ub=3}));function sealSchema(e){let t=e.includes(`agent.schema-metadata`),n=t===e.includes(`state.schema-version`)?`other`:t?`agent`:`state`;return fb[n]??=sqliteDatabaseSealSchemaFor(n)}function isSealedKey(e){return hb.has(e)||e.startsWith(`memory.index-schema:`)}function encodeSealValue(e,t){return t instanceof Map?{sealType:`map`,entries:[...t]}:t instanceof Set?{sealType:`set`,entries:[...t]}:t instanceof SharedArrayBuffer?{sealType:`shared`,entries:[...new Int32Array(t)]}:t}function decodeSealValue(e,t){if(!isRecord(t)||!Array.isArray(t.entries))return t;if(t.sealType===`map`)return new Map(t.entries);if(t.sealType===`set`)return new Set(t.entries);if(t.sealType===`shared`){let e=new SharedArrayBuffer(t.entries.length*Int32Array.BYTES_PER_ELEMENT);return new Int32Array(e).set(t.entries),e}return t}var fb,pb,mb,hb,SqliteDatabaseCleanCloseSeals,gb=__esmMin((()=>{D(),my(),db(),iy(),ey(),fb={},pb={name:`sqlite.full-verification`,lifetime:`process`,read:e=>typeof e==`number`&&Number.isSafeInteger(e)?e:void 0},mb={...pb,name:`sqlite.quick-verification`},hb=/* @__PURE__ */ new Set([`sqlite-schema`,`sqlite.full-verification`,`sqlite.quick-verification`,`state.schema-version`,`state.runtime-schema`,`state.integrity`,`agent.completed-validation`,`agent.canonical-validation-receipt`,`agent.schema-metadata`]),SqliteDatabaseCleanCloseSeals=class{constructor(e,t){this.publishFact=e,this.references=t,this.loaded=/* @__PURE__ */ new WeakMap}isLoaded(e){return this.loaded.has(e)}markLoaded(e){let t=this.references.descriptor(e)??e,n=this.loaded.get(t);n&&n!==e.generation&&Atomics.store(new Int32Array(e.generation),Jv.sealPresent,Atomics.load(new Int32Array(n),Jv.sealPresent)),this.loaded.set(t,e.generation)}load(e,t){if(E!==0)return;let n=this.references.descriptor(e)??e;if(this.loaded.has(n))this.markLoaded(e);else{this.markLoaded(e),e.cleanCloseRefusal=`malformed-proof`;try{t?.refusal&&(e.cleanCloseRefusal=t.refusal);let n=t?t.seal:readSqliteCleanCloseSeal(e.location,r.fstatSync(e.descriptor,{bigint:!0}),t=>{e.cleanCloseRefusal=t});if(!n||typeof n.facts!=`string`)return;let i=JSON.parse(n.facts,decodeSealValue);if(!Array.isArray(i)||!i.every(e=>Array.isArray(e)&&e.length===3&&typeof e[0]==`string`&&isSealedKey(e[0])&&typeof e[1]==`boolean`)||!i.some(([e,,t])=>(e===pb.name||e===mb.name)&&t===n.verifiedAt)||!i.some(([e,,t])=>e===`sqlite-schema`&&isRecord(t)))return;let a=sealSchema(i.map(([e])=>e));if(!a){e.cleanCloseRefusal=`identity-mismatch`;return}let s=n.identity;if(s!==void 0&&(!isRecord(s)||typeof s.runtime!=`string`||typeof s.schema!=`string`||typeof s.policy!=`number`))return;if(isRecord(s)&&typeof s.sqlite!=`string`){if(!isRecord(s.sqlite)||typeof s.sqlite.version!=`string`||typeof s.sqlite.sourceId!=`string`||typeof s.sqlite.compileOptions!=`string`)return;let t=s.schema!==a.identity.schema,n=s.policy!==a.identity.policy,r=s.sqlite.compileOptions!==a.identity.sqlite.compileOptions;if(t||n||r){e.cleanCloseRefusal=t?`schema-mismatch`:n?`policy-mismatch`:`feature-mismatch`;return}}else if(n.schemaIdentity!==a.schemaIdentity){e.cleanCloseRefusal=`identity-mismatch`;return}let c=i.find(([e])=>e===`sqlite-schema`)?.[2];if(!(c.tableSql instanceof Map))return;if(hasPendingAgentStartupColumns(c.tableSql)){e.cleanCloseRefusal=`schema-mismatch`;return}delete e.cleanCloseRefusal;for(let[t,n,r]of i)this.publishFact(e,{name:t,schemaDependent:n,lifetime:`process`},{value:r},readSqliteDatabaseFactRevision(e,n));Atomics.store(new Int32Array(e.generation),Jv.sealPresent,1)}catch{}finally{this.references.publish(e)}}}invalidate(e,t){invalidateSqliteCleanCloseSeal(t?.location??e),t&&Atomics.store(new Int32Array(t.generation),Jv.sealPresent,0)}prepare(e,t,n){let r=this.preparePublication(e,t,n);t&&this.references.retain(t);let i=t;return{publish:()=>i!==void 0&&r(),[Symbol.dispose]:()=>{let e=i;i=void 0,e&&this.references.release(e)}}}preparePublication(e,t,n){if(!t||e.isTransaction||n===void 0)return()=>!1;let i=[...t.facts].filter(([e,n])=>isSealedKey(e)&&isSqliteDatabaseAdmissionFactCurrent(t,n));if(!i.some(([e])=>e===`sqlite-schema`))return()=>!1;let a=JSON.stringify(i.map(([e,t])=>[e,t.schemaDependent,t.value]),encodeSealValue),s=sealSchema(i.map(([e])=>e));return s?()=>{if(e.isOpen||readSqliteDatabaseGeneration(t,`retired`)!==0||i.some(([,e])=>Atomics.load(new Int32Array(e.current),0)!==1||e.revision!==readSqliteDatabaseFactRevision(t,e.schemaDependent)))return!1;try{let e=r.fstatSync(t.descriptor,{bigint:!0});if(readSqliteDatabaseAdmissionIdentity(r.statSync(t.location,{bigint:!0}))!==t.identity)return!1;let i=writeSqliteCleanCloseSeal(t.location,s.schemaIdentity,e,{verifiedAt:n,facts:a,identity:s.identity});return Atomics.store(new Int32Array(t.generation),Jv.sealPresent,+!!i),i}catch{return!1}}:()=>!1}}}));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);e.code===`57014`&&(t.name=_b);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}var _b,vb=__esmMin((()=>{_b=`PostgresQueryCanceledError`}));function wrapSqliteWorkerError(e,t,...n){let r=n.filter(e=>e!==void 0).map(t=>toErrorObject(t,e)).filter((e,t,n)=>n.findIndex(t=>he(t,e))===t);return Object.assign(t===void 0?Error(e):new SqliteWorkerError(e,t),{cause:r.length>1?AggregateError(r,e):r[0]})}function retainSqliteWorkerErrorCode(e,t){let n;try{n=Object.getOwnPropertyDescriptor(t,yb)?.value}catch{return e}return(n===`closed`||n===`overloaded`||n===`unavailable`||n===`outcome-unknown`)&&(Object.defineProperty(e,yb,{value:n}),Object.assign(e,{code:n})),e}function hasSqliteWorkerOutcomeUnknown(e){let t=[e],n=/* @__PURE__ */ new Set;for(;t.length>0;){let e=t.pop();if(n.has(e)||_t(e)||!ht(e))continue;if(n.add(e),Object.getOwnPropertyDescriptor(e,yb)?.value===`outcome-unknown`)return!0;let r=Object.getOwnPropertyDescriptor(e,`cause`);r&&`value`in r&&t.push(r.value);let i=Object.getPrototypeOf(e),a=!1;for(;i&&!_t(i);){let e=Object.getOwnPropertyDescriptor(i,`constructor`)?.value;if(i===AggregateError.prototype||typeof e==`function`&&!_t(e)&&Object.getOwnPropertyDescriptor(e,`name`)?.value===`AggregateError`&&Object.getOwnPropertyDescriptor(e,`prototype`)?.value===i&&Object.getOwnPropertyDescriptor(i,`name`)?.value===`AggregateError`){a=!0;break}i=Object.getPrototypeOf(i)}if(!a)continue;let s=Object.getOwnPropertyDescriptor(e,`errors`)?.value;if(!_t(s)&&Array.isArray(s))for(let e of Object.keys(s)){if(!/^(0|[1-9][0-9]*)$/.test(e))continue;let n=Object.getOwnPropertyDescriptor(s,e);n&&`value`in n&&t.push(n.value)}}return!1}var yb,SqliteWorkerError,bb=__esmMin((()=>{O(),yb=Symbol.for(`openclaw.sqliteWorkerErrorCode`),SqliteWorkerError=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`SqliteWorkerError`,Object.defineProperty(this,yb,{value:t})}}}));function markSqliteNativeOpenFailure(e){typeof e==`object`&&e&&Sb.add(e)}function withSqliteNativeOpen(e){try{return e()}catch(e){throw markSqliteNativeOpenFailure(e),e}}function markSqliteInspectionOperation(e,t){return typeof e==`object`&&e&&!xb.has(e)&&xb.set(e,t),e}function readSqliteInspectionOperation(e){return readSqliteErrorDetails(e).operation}function readSqliteErrorDetails(e){let t=/* @__PURE__ */ new Set,n;for(let r=e,i=0;i<8&&isRecord(r);i+=1){n=xb.get(r)??n;let e=extractErrorCode(r);e&&/^[A-Z0-9_]{1,64}$/u.test(e)&&t.add(`code=${e}`);let{errcode:i}=r;typeof i==`number`&&Number.isInteger(i)&&i>=0&&i<=2147483647&&t.add(`errcode=${i}`),r=r.cause}return{suffix:t.size>0?` (${[...t].join(`, `)})`:``,operation:n}}function sqliteErrorCode(e){let t=asOptionalObjectRecord(e)?.code;return typeof t==`string`?t:void 0}function sqliteExtendedResultCode(e){let t=asOptionalObjectRecord(e)?.errcode;return typeof t==`number`&&Number.isInteger(t)?t:void 0}function sqlitePrimaryResultCode(e){let t=sqliteExtendedResultCode(e);return t===void 0?void 0:t&Ob}function isSqliteLockError(e){let t=sqliteErrorCode(e);if(t!==void 0&&Cb.has(t))return!0;let n=sqlitePrimaryResultCode(e);return n===wb||n===Tb}function isSqliteCorruptionError(e){let t=sqlitePrimaryResultCode(e);return t===Eb||t===Db}var xb,Sb,Cb,wb,Tb,Eb,Db,Ob,kb=__esmMin((()=>{O(),D(),B(),xb=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteInspectionOperations`),()=>/* @__PURE__ */ new WeakMap),Sb=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeOpenFailures`),()=>/* @__PURE__ */ new WeakSet),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotFailureScopes`),()=>new C),Cb=/* @__PURE__ */ new Set([`SQLITE_BUSY`,`SQLITE_LOCKED`]),wb=5,Tb=6,Eb=11,Db=26,Ob=255}));function schemaStatement(e){if(/^(?:CREATE|ALTER|DROP|REINDEX|VACUUM)\b/iu.test(e))return!0;let t=/^(?:INSERT(?: OR \w+)? INTO|UPDATE(?: OR \w+)?|DELETE FROM|REPLACE INTO)\s+/iu.exec(e);if(t){let n=readSqlToken(e,t[0].length)?.raw??``,r=n.slice(findSqlCharacter(n,`.`)+1);return[`sqlite_schema`,`sqlite_master`].includes(normalizeSqlIdentifier(r))}if(!/^PRAGMA\b/iu.test(e))return!1;let n=[findSqlCharacter(e,`=`),findSqlCharacter(e,`(`)].filter(e=>e>=0);if(n.length===0)return!1;let r=e.slice(6,Math.min(...n)).trim(),i=r.slice(findSqlCharacter(r,`.`)+1).trim(),a=i.startsWith(`'`)&&i.endsWith(`'`)?i.slice(1,-1).toLowerCase():normalizeSqlIdentifier(i);return[`user_version`,`schema_version`].includes(a)}function changesSchema(e){if(!/\b(?:CREATE|ALTER|DROP|REINDEX|VACUUM|PRAGMA|INSERT|UPDATE|DELETE|REPLACE)\b/iu.test(e))return!1;let t=normalizeSqlWhitespace(e);for(;t;){t=t.replace(/^[\s;]+/u,``);let e=findSqlCharacter(t,`;`);if(schemaStatement(e<0?t:t.slice(0,e)))return!0;t=e<0?``:t.slice(e+1)}return!1}function createsOnlyTemporaryObject(e){let t=normalizeSqlWhitespace(e),n=/^\s*CREATE\s+(?:TEMP|TEMPORARY)\s+(TABLE|TRIGGER)\b/iu.exec(t)?.[1]?.toUpperCase();if(!n)return!1;let r=findSqlCharacter(t,`;`);if(n===`TABLE`)return r<0||t.slice(r+1).trim()===``;for(;r>=0;){t=t.slice(r+1).trim(),r=findSqlCharacter(t,`;`);let e=(r<0?t:t.slice(0,r)).trim();if(/^END$/iu.test(e))return r<0||t.slice(r+1).trim()===``}return!1}function changesOnlyTemporaryTable(e){let t=normalizeSqlWhitespace(e),n=findSqlCharacter(t,`;`);return n>=0&&t.slice(n+1).trim()!==``?!1:/^CREATE\s+(?:TEMP|TEMPORARY)\s+TABLE\b/iu.test(t)||/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:temp|"temp"|`temp`|\[temp\])\s*\./iu.test(t)}function changesData(e){return hasUnquotedSqlKeyword(e,/\b(?:INSERT|UPDATE|DELETE|REPLACE)\b/giu)}function temporaryWriteTables(e){let t=[],n=normalizeSqlWhitespace(e);for(;n;){n=n.replace(/^[\s;]+/u,``);let e=findSqlCharacter(n,`;`),r=e<0?n:n.slice(0,e);if(changesData(r)){let e=/^(?:INSERT(?: OR \w+)? INTO|REPLACE INTO|UPDATE(?: OR \w+)?|DELETE FROM)\s+(?:temp|"temp"|`temp`|\[temp\])\s*\.\s*("(?:[^"]|"")+"|`(?:[^`]|``)+`|\[[^\]]+\]|[a-z_]\w*)(?=\s|\(|$)/iu.exec(r)?.[1];if(e===void 0)return;t.push(normalizeSqlIdentifier(e))}n=e<0?``:n.slice(e+1)}return t}function readTransactionControl(e,t){let n,r=!1,i=!1,a=0,s=e;for(;s&&(s=s.replace(Ab,``),s);){a+=1;let e=s.includes(`;`)?findSqlCharacter(s,`;`):-1,c=e<0?s:s.slice(0,e),l=jb.exec(c)?.[1]?.toUpperCase();if(l===`ROLLBACK`?(n=l,i||=r,r=!/^ROLLBACK(?: TRANSACTION)? TO\b/iu.test(normalizeSqlWhitespace(c)),i||=!r):(l||!/^SELECT\b/iu.test(c)&&(changesSchema(c)||changesData(c)))&&(i=!0),n||=l,e<0||t===`statement`)break;s=s.slice(e+1)}return n?{kind:n,single:a===1,outerRollback:r&&!i}:void 0}function canPreserveTransactionSnapshot(e,t){return!(!t||!e?.single||e.kind!==`SAVEPOINT`&&e.kind!==`RELEASE`&&e.kind!==`ROLLBACK`)}function classifySqliteMutation(e,t){let n=changesSchema(e),r=changesData(e),i=n&&changesOnlyTemporaryTable(e);return{schemaChange:n,mainSchemaChange:n&&!i&&!createsOnlyTemporaryObject(e),temporaryTableSchemaChange:i,dataChange:r,temporaryWriteTables:r?temporaryWriteTables(e):void 0,control:readTransactionControl(e,t)}}var Ab,jb,Mb=__esmMin((()=>{uy(),Ab=/^(?:\s|;|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/u,jb=/^(BEGIN|SAVEPOINT|COMMIT|END|RELEASE|ROLLBACK)\b/i}));function isPreparingSqliteNativeMutation(e){return Pb.get(e)?.phase===`preparing`}function createIteratorLifetime(e,t){let n={finished:!1,invalidated:!1,pause:()=>n.stopObservation(),invalidate:()=>{n.invalidated=!0,n.finish()},stopObservation:(e=!1,r=!1)=>{let i=n.observed;n.observed=void 0,t.delete(n),i?.finish(e,r)},finish:(t=!1,r=!1)=>{n.finished||(n.finished=!0,e.delete(n),n.stopObservation(t,r))}};return e.add(n),n}function observeSqliteNativeClose(e,t){for(let n of[`close`,Symbol.dispose]){if(typeof e[n]!=`function`)continue;let r=e[n].bind(e);e[n]=()=>{try{r()}finally{e.isOpen||t()}}}}function callStatement(e,t){return Reflect.apply(e,void 0,t)}function observeSqliteNativeOperations(e,t,n){let begin=(t,r)=>{let i=Pb.get(e);if(i){if(i.phase!==`armed`||r!==`execute`||!t.dataChange||t.schemaChange||t.control)throw Error(`Prepared SQLite mutations must execute exactly one data statement`);i.phase=`observing`}let a=n(t,r);return Nb.set(e,(Nb.get(e)??0)+1),{...a,finish(t,n,r){try{a.finish(t,n,r)}finally{let t=(Nb.get(e)??1)-1;t===0?Nb.delete(e):Nb.set(e,t)}}}},r=/* @__PURE__ */ new Set,execute=(t,n,r=`execute`)=>{let i=Pb.get(e),a=begin(n,r),s=!1,c=!1,l=!1;try{i&&(i.phase=`preparing`,i.prepare(),i.phase=`executing`);let e=t();return c=!0,r!==`bind`&&a.stepped?.(),s=!0,e}catch(t){if(l=!(!i||i.phase!==`preparing`&&(c||!isSqliteLockError(t)&&sqlitePrimaryResultCode(t)!==19)),i&&!l){let n=wrapSqliteWorkerError(`Prepared SQLite mutation outcome is unknown`,`outcome-unknown`,t);throw discardSqliteTransactionState(e,n),n}throw t}finally{i&&(i.phase=`finished`),a.finish(s,!1,l)}};return e.exec=n=>execute(()=>t.DatabaseSync.prototype.exec.call(e,n),classifySqliteMutation(n,`batch`),`exec`),e.prepare=(...n)=>{let i=t.DatabaseSync.prototype.prepare.call(e,...n),a=classifySqliteMutation(n[0],`statement`),s=Object.hasOwn(i,`run`)?i.run.bind(i):void 0,c=Object.hasOwn(i,`get`)?i.get.bind(i):void 0,l=Object.hasOwn(i,`all`)?i.all.bind(i):void 0,u=Object.hasOwn(i,`iterate`)?i.iterate.bind(i):void 0,d=/* @__PURE__ */ new Set,f=!1,reset=(e,t=`reuse`)=>{if(d.size===0)return e();let n=[...d],r=e();for(let e of n)t===`return`?e.pause():e.invalidate();return r},wrap=e=>(...t)=>execute(()=>reset(()=>callStatement(e(),t)),a);i.run=wrap(()=>s??t.StatementSync.prototype.run.bind(i)),i.get=wrap(()=>c??t.StatementSync.prototype.get.bind(i)),i.all=wrap(()=>l??t.StatementSync.prototype.all.bind(i)),i.iterate=(...n)=>{f||=(Fb.register(i,d),!0);let s=execute(()=>reset(()=>callStatement(u??t.StatementSync.prototype.iterate.bind(i),n)),Ib,`bind`),c=new WeakRef(s),l=createIteratorLifetime(d,r),p=s.next,m=s.return,h;return s.next=function(...t){if(h&&this===c.deref()&&e.isOpen)return{...h};if(this!==c.deref()||l.invalidated||!e.isOpen)return p.apply(this,t);l.finished&&(l.finished=!1,d.add(l)),l.observed??=begin(a,`iterate`),r.add(l);let n=p.apply(this,t);return n.done?(m?.call(this),h={...n},l.finish(!0)):l.observed?.stepped?.(),n},m&&(s.return=function(...t){if(h&&this===c.deref()&&e.isOpen)return{...h};if(this!==c.deref()||!e.isOpen)return m.apply(this,t);let n=execute(()=>l.finished||l.invalidated?m.apply(this,t):reset(()=>m.apply(this,t),`return`),Ib,`bind`);return n.done&&(h={...n}),l.finish(),n}),s};for(let e of[`close`,Symbol.dispose]){let t=i[e]?.bind(i);t&&(i[e]=()=>reset(t,`finalize`))}return i},observeSqliteNativeClose(e,()=>{for(let e of r)e.invalidate()}),execute}var Nb,Pb,Fb,Ib,Lb=__esmMin((()=>{B(),kb(),jv(),Mb(),bb(),Nb=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeExecution`),()=>/* @__PURE__ */ new WeakMap),Pb=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePreparedNativeMutation`),()=>/* @__PURE__ */ new WeakMap),Fb=new FinalizationRegistry(e=>{for(let t of e)t.finish(!1,!0)}),Ib={schemaChange:!1,mainSchemaChange:!1,temporaryTableSchemaChange:!1,dataChange:!1,temporaryWriteTables:void 0,control:void 0}}));function createSqliteDatabaseWriteReceipts(e){function onSqliteDatabaseWriteSettled(t,n){let r=sqlPublicationAnchor(t),i=e.admission(r);if(!i)return;let a=e.writeListeners.get(i);return a||(a=/* @__PURE__ */ new Set,e.writeListeners.set(i,a)),registerListener(a,n)}function settleWorker(t,n){let r=n>0?t.references.get(n):void 0;if(r&&Atomics.exchange(new Int32Array(r),1,0)>0){advanceSqliteDatabaseGeneration(t,`writeRevision`),advanceSqliteDatabaseGeneration(t,`unscopedWriteRevision`);let n=e.writeListeners.get(t);n&&notifyListeners(n,void 0)}}function withSqliteDatabaseWriteScope(t,n,r){let i=sqlPublicationAnchor(t),a=e.admission(i);if(!(a?readSqliteDatabaseGeneration(a,`writeScopeRevision`)>0:q.localScopeRevisions.has(i))){let e=r();if(e instanceof Promise)throw Error(`SQLite write scopes cannot await work`);return e}let s=normalizedWriteScopes(n),c=q.writeScopes.get(i);q.writeScopes.set(i,s);try{let e=r();if(e instanceof Promise)throw Error(`SQLite write scopes cannot await work`);return e}finally{c?q.writeScopes.set(i,c):q.writeScopes.delete(i)}}function withoutSqliteDatabaseWriteScope(e,t){let n=sqlPublicationAnchor(e),r=q.writeScopes.get(n);q.writeScopes.delete(n);try{return t()}finally{r&&q.writeScopes.set(n,r)}}function ensureWriteScopes(t,n,r){let i=!1;for(let e of n){let n=t.writeScopes.get(e);(!n||Atomics.load(n.state,1)!==0||r&&!pinWriteScope(n))&&(n=createScopeRevision(),r&&Atomics.store(n.state,2,1),E===0&&advanceSqliteDatabaseGeneration(t,`writeScopeRevision`),i=!0),r&&r.push(n),retainSqliteDatabaseWriteScope(t,e,n)}i&&(advanceSqliteDatabaseGeneration(t,`publicationRevision`),e.publish(t,n))}function pinWriteScope(e){let t=Atomics.load(e.state,2);for(;t>=0;){let n=Atomics.compareExchange(e.state,2,t,t+1);if(n===t)return!0;t=n}return!1}function createScopeRevision(){return{identity:Se(),state:new Int32Array(new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT))}}function retainSqliteDatabaseWriteScopesForPath(t,n){let r=e.pathAdmission(t);if(!r||isSqliteDatabaseAdmissionRetired(r))return;let i=[],a=!1,release=()=>{if(!a){a=!0;try{for(let e of i)Atomics.sub(e.state,2,1);i.length>0&&!isSqliteDatabaseAdmissionRetired(r)&&pruneSqliteDatabaseWriteScopes(r)&&(advanceSqliteDatabaseGeneration(r,`publicationRevision`),e.publish(r,[]))}finally{e.release(r)}}};try{return e.retain(r),ensureWriteScopes(r,normalizedWriteScopes(n),i),release}catch(e){throw release(),e}}function retireSqliteDatabaseWriteScopes(t,n){let r=sqlPublicationAnchor(t),i=normalizedWriteScopes(n),a=e.admission(r),retire=()=>{let t=a?.writeScopes??q.localScopeRevisions.get(r),s=n.flatMap(e=>typeof e!=`string`&&e.partition===void 0?[normalizedWriteScopes([e])[0].slice(0,-1)+`,`]:[]);for(let e of t?.keys()??[])s.some(t=>e.startsWith(t))&&i.push(e);if(!a){let e=q.localScopeRevisions.get(r);for(let t of i)e?.delete(t);return}if(isSqliteDatabaseAdmissionRetired(a))return;let c=!1;for(let e of i){let t=a.writeScopes.get(e);t&&Atomics.exchange(t.state,1,1)===0&&(c=!0)}c&&(advanceSqliteDatabaseGeneration(a,`writeScopeRevision`),advanceSqliteDatabaseGeneration(a,`publicationRevision`),e.publish(a,i))};!stageSqliteTransactionState(r,{commit:retire})&&!t.isTransaction&&retire()}function scopedWriteToken(e,t,n,r=0){let i=readSqliteDatabaseGeneration(e,`schemaRevision`)+r|0,a=[];for(let r of t){let s=e.writeScopes.get(r);if(!s||Atomics.load(s.state,1)!==0)return JSON.stringify([e.identity,e.generationId,i,`database`,readSqliteDatabaseGeneration(e,`writeRevision`)+(n===void 0?0:1)|0,t]);a.push([r,s.identity,Atomics.load(s.state,0)+ +!!n?.has(r)|0])}return JSON.stringify([e.identity,e.generationId,i,readSqliteDatabaseGeneration(e,`unscopedWriteRevision`)+ +(n===null)|0,a])}function localScopedWriteToken(e,t,n){return JSON.stringify([`memory`,(q.localUnscopedRevisions.get(e)??0)+ +(n===null),t.map(t=>[t,q.localScopeRevisions.get(e).get(t).identity,Atomics.load(q.localScopeRevisions.get(e).get(t).state,0)+ +!!n?.has(t)|0])])}function normalizedWriteScopes(e){return[...new Set((typeof e==`string`?[e]:e).map(e=>JSON.stringify(typeof e==`string`?[`key`,ge(e)]:[`session-id`,ge(e.sessionId),...e.partition===void 0?[]:[ge(e.partition)]])))].toSorted()}function ensureLocalWriteScopes(e,t){let n=q.localScopeRevisions.get(e)??/* @__PURE__ */ new Map;for(let e of t)n.has(e)||n.set(e,createScopeRevision());q.localScopeRevisions.set(e,n)}function readScopedWriteToken(t,n,r,i=0){let a=normalizedWriteScopes(n),s=e.admission(t);if(s?ensureWriteScopes(s,a):ensureLocalWriteScopes(t,a),e.readRevision(t)!==void 0)return s?scopedWriteToken(s,a,r,i):localScopedWriteToken(t,a,r)}function readSqliteDatabaseScopedWriteToken(e,t){return readScopedWriteToken(sqlPublicationAnchor(e),t)}function readSqliteDatabaseScopedWriteTokenForPath(t,n){let r=normalizedWriteScopes(n),i=e.pathAdmission(t);if(i&&!isSqliteDatabaseAdmissionRetired(i))return ensureWriteScopes(i,r),scopedWriteToken(i,r)}function readSqliteDatabaseScopedWriteTokensForPath(t,n){let r=e.pathAdmission(t);if(!r||isSqliteDatabaseAdmissionRetired(r))return;let i=n.map(normalizedWriteScopes);return ensureWriteScopes(r,i.flat()),i.map(e=>scopedWriteToken(r,e))}function readSqliteDatabasePendingScopedWriteToken(t,n){let r=sqlPublicationAnchor(t);return readScopedWriteToken(r,n,q.pendingWriteScopes.get(r),+!!e.hasPendingSchemaMutation(r))}function readSqliteDatabaseWriteTokenForPath(t){let n=e.pathAdmission(t);if(n&&!isSqliteDatabaseAdmissionRetired(n))return`${n.identity}:${n.generationId}:${readSqliteDatabaseGeneration(n,`writeRevision`)}`}function readSqliteDatabasePendingWriteToken(t){let n=sqlPublicationAnchor(t);if(!t.isOpen||!t.isTransaction&&!isPreparingSqliteNativeMutation(n)||!hasSqlitePostCommitScope(n)||e.suspended(n))return;let r=e.writer(n);if(r&&!isSqliteDatabaseAdmissionRetired(r))return`${r.identity}:${r.generationId}:${readSqliteDatabaseGeneration(r,`writeRevision`)+1|0}`}return{cancel(e){q.pendingWriteScopes.delete(e)},begin(e,t){let n=t?void 0:q.writeScopes.get(e),r=q.pendingWriteScopes.get(e);if(!n||r===null)q.pendingWriteScopes.set(e,null);else{let t=r??/* @__PURE__ */ new Set;for(let e of n)t.add(e);q.pendingWriteScopes.set(e,t)}},finish(e,t){let n=q.pendingWriteScopes.get(e);q.pendingWriteScopes.delete(e);let r=!n;if(n){let i=q.localScopeRevisions.get(e);for(let e of n){let n=i?.get(e);n&&Atomics.add(n.state,0,1);let a=t?.writeScopes.get(e);a&&Atomics.load(a.state,1)===0?Atomics.add(a.state,0,1):t&&(a||t.writeScopeRevision!==readSqliteDatabaseGeneration(t,`writeScopeRevision`))&&(r=!0)}}r&&(q.localUnscopedRevisions.set(e,(q.localUnscopedRevisions.get(e)??0)+1),t&&advanceSqliteDatabaseGeneration(t,`unscopedWriteRevision`))},settleWorker,onSqliteDatabaseWriteSettled,retireSqliteDatabaseWriteScopes,retainSqliteDatabaseWriteScopesForPath,withSqliteDatabaseWriteScope,withoutSqliteDatabaseWriteScope,readSqliteDatabaseScopedWriteToken,readSqliteDatabaseScopedWriteTokenForPath,readSqliteDatabaseScopedWriteTokensForPath,readSqliteDatabasePendingScopedWriteToken,readSqliteDatabaseWriteTokenForPath,readSqliteDatabasePendingWriteToken}}var q,Rb=__esmMin((()=>{B(),pu(),gu(),ey(),Lb(),jv(),q=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseWriteScopes`),()=>({writeScopes:/* @__PURE__ */ new WeakMap,pendingWriteScopes:/* @__PURE__ */ new WeakMap,localScopeRevisions:/* @__PURE__ */ new WeakMap,localUnscopedRevisions:/* @__PURE__ */ new WeakMap}))}));function observeSqliteTransactionState(e,t){let n=e.isTransaction;t.transactionOpen!==n&&(t.transactionOpen&&(t.mutationRevision+=1),t.transactionOpen=n,t.transactionMutationRevision=void 0,t.transactionSnapshot=void 0,t.transactionRead=!1,t.transactionCatalogBound=!1)}function finishSqliteReadScope(e,t,n,r,i,a){let s=e.isTransaction;!i&&n&&!s&&(t.mutationRevision+=1),t.transactionOpen=s,(!n||!s)&&(t.transactionMutationRevision=s?a:void 0),(n!==s||r)&&(t.transactionSnapshot=void 0,t.transactionRead=!1,t.transactionCatalogBound=!1)}var zb,Bb=__esmMin((()=>{B(),zb=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSchemaFacts`),()=>/* @__PURE__ */ new WeakMap)}));function recordSqliteDatabaseIntegrity(e,t=Date.now()){publishSqliteDatabaseAdmission(e,pb,t)}function prepareSqliteDatabaseCleanClose(e){return Vb.prepare(e,admission$1(e),Jb(e,pb)??Jb(e,mb))}function settleSqliteDatabaseAdmissionPublication(e){if(e.isTransaction||getSqliteNativeAdmissionFacts(e)||hasSqlitePostCommitScope(e)||K.exchanging)return!1;let t=admission$1(e);return t&&exchangeSqliteDatabaseAdmission(t,void 0,!0),!0}function bindSqliteDatabaseAdmission(e,t){K.connections.delete(e),K.openedIdentities.delete(e),K.unproven.delete(e);let n=e.location();if(!n||n===`:memory:`)return;let r=Wb(n);if(t!==void 0&&r!==t)throw Error(`SQLite database changed identity during native open`);if(!r)return;if(K.openedIdentities.set(e,r),t===void 0){K.unproven.add(e);return}let i=K.registry.records.get(r);(i&&!isSqliteDatabaseAdmissionRetired(i)||K.registry.descriptors.get(r)?.facts.size)&&admission$1(e)}function admission$1(e,t=!0){let n=K.openedIdentities.get(e);if(!e.isOpen||n===void 0||K.unproven.has(e))return;let r=K.connections.get(e);if(r)return isSqliteDatabaseAdmissionRetired(r)?void 0:r;let i=e.location();if(!i||i===`:memory:`)return;let a=t&&!e.isTransaction?Kb(i):K.registry.records.get(n);if(a&&a.identity!==n)throw Error(`SQLite database changed identity before admission`);return a&&!isSqliteDatabaseAdmissionRetired(a)?retainConnection(e,a):void 0}function retainConnection(e,t){let n=t.identity,r=t;try{for(;;){if(r.identity!==n)throw Error(`SQLite database changed identity during native open`);let t=K.registry.changeReferences(r,1),i=!1;try{t&&exchangeSqliteDatabaseAdmission(r);let n=readSqliteDatabaseGeneration(r,`retired`);if(n===0)return K.connections.set(e,r),i=!0,r;if(n!==2)throw Error(`SQLite database admission retired during native open`)}finally{i||K.registry.changeReferences(r,-1)}let a=e.location(),s=e.isTransaction?K.registry.records.get(n):a?Kb(a):void 0;if(!s||isSqliteDatabaseAdmissionRetired(s))throw Error(`SQLite database admission unavailable during native open`);r=s}}catch(t){throw K.openedIdentities.delete(e),t}}function releaseSqliteDatabaseAdmission(e){let t=K.connections.get(e);K.openedIdentities.delete(e)&&t&&(K.local.delete(e),releaseReference(t))}function retainReference(e){K.registry.changeReferences(e,1)&&exchangeSqliteDatabaseAdmission(e)}function releaseReference(e){K.registry.changeReferences(e,-1)&&(K.localSchemaRevisions.delete(e.identity),exchangeSqliteDatabaseAdmission(e))}function publishFact(e,t,n,r){if(t.writer===`host`&&E!==0)throw Error(`SQLite host-owned admission facts require the host publisher`);publishSqliteDatabaseFact(e,t,n,r,`${E}:${++K.publication}`)&&(K.registry.publish(e),t.writer!==`connection`&&exchangeSqliteDatabaseAdmission(e))}function beginSqliteDatabaseWrite(e,t=!1){let n=admission$1(e);n&&Atomics.load(new Int32Array(n.generation),Jv.sealPresent)===1&&Vb.invalidate(n.location,n),nx.begin(e,t),!K.dataWriters.has(e)&&(K.dataWriters.set(e,n),n&&Atomics.add(new Int32Array(n.references.get(E)),1,1))}function finishSqliteDatabaseWrite(e,t=!1){if(!K.dataWriters.has(e))return;let n=K.dataWriters.get(e);if(K.dataWriters.delete(e),t)nx.cancel(e),n&&Atomics.sub(new Int32Array(n.references.get(E)),1,1);else if(K.localWriteRevisions.set(e,(K.localWriteRevisions.get(e)??0)+1),nx.finish(e,n),n){advanceSqliteDatabaseGeneration(n,`writeRevision`),Atomics.sub(new Int32Array(n.references.get(E)),1,1);let e=K.writeListeners.get(n);e&&notifyListeners(e,void 0)}}function readSqliteDatabaseWriteRevision(e){let t=sqlPublicationAnchor(e);if(!t.isOpen||K.suspended.has(t))return;let n=admission$1(t);if(!n){let e=t.location();return!e||e===`:memory:`?K.localWriteRevisions.get(t)??0:void 0}return readSqliteDatabaseGeneration(n,`writeRevision`)}function trackSqliteDatabaseAdmissionWorker(e){let t=e.threadId;e.once(`exit`,()=>{for(let e of K.registry.records.values())nx.settleWorker(e,t);K.registry.releaseWorker(t)})}function hasPendingSqliteDatabaseSchemaMutation(e){let t=sqlPublicationAnchor(e);return e.isTransaction&&K.schemaDirty.has(t)}function publishSqliteDatabaseAdmission(e,t,n,r={}){let i=sqlPublicationAnchor(e),a=admission$1(i,!e.isTransaction);if(!a||isSqliteDatabaseAdmissionRetired(a)||K.suspended.has(i))return;if(t.writer===`host`&&E!==0)throw Error(`SQLite host-owned admission facts require the host publisher`);let s=(t.schemaDependent?r.schemaRevision:void 0)??readSqliteDatabaseFactRevision(a,t.schemaDependent),c=isPostgresSqlConnection(e)?void 0:getSqliteNativeAdmissionFacts(e),l=admitSqliteDatabaseFactValue(t,n);if(!c&&!e.isTransaction&&!hasSqlitePostCommitScope(e)){publishFact(a,t,l,s);return}let u={...l,revision:s,schemaDependent:t.schemaDependent===!0,ddlRevision:K.ddlRevisions.get(i)??0};if(c){c.set(t.name,u);return}let d=K.local.get(i)??/* @__PURE__ */ new Map;K.local.set(i,d);let f=d.get(t.name);stageSqliteTransactionState(i,{stage:()=>d.set(t.name,u),rollback:()=>{K.local.get(i)===d&&(f===void 0?d.delete(t.name):d.set(t.name,f))},commit:()=>{K.local.get(i)===d&&d.get(t.name)===u&&(d.delete(t.name),u.revision===readSqliteDatabaseFactRevision(a,u.schemaDependent)&&(!u.schemaDependent||u.ddlRevision===(K.ddlRevisions.get(i)??0))&&publishFact(a,t,u,u.revision))}})}function invalidateLocalSqliteSchemaAdmissions(e){let t=sqlPublicationAnchor(e),n=K.ddlRevisions.get(t)??0,r=K.schemaDirty.has(t),stage=()=>{K.ddlRevisions.set(t,n+1),K.schemaDirty.add(t)};stageSqliteTransactionState(t,{stage,commit:()=>{},rollback:()=>{K.ddlRevisions.set(t,n),r||K.schemaDirty.delete(t)}})||stage()}function discardSqliteDatabaseTransactionAdmissions(e){let t=sqlPublicationAnchor(e),n=admission$1(t,!1);for(let r of[isPostgresSqlConnection(e)?void 0:getSqliteNativeAdmissionFacts(e),K.local.get(t)]){for(let e of r?.keys()??[]){let t=n?.facts.get(e);t&&Atomics.store(new Int32Array(t.current),0,0)}r?.clear()}K.local.delete(t),K.rolledBack.add(t),e.isTransaction||K.schemaDirty.delete(t)}function publishSqliteDatabaseSchemaChange(e){let t=sqlPublicationAnchor(e),n=admission$1(t,!1);if(n){let e=advanceSqliteDatabaseGeneration(n,`schemaRevision`),r=K.ddlRevisions.get(t)??0;for(let n of K.local.get(t)?.values()??[])n.schemaDependent&&n.revision===e&&n.ddlRevision===r&&(n.revision=e+1)}else{let e=K.openedIdentities.get(t);e&&K.localSchemaRevisions.set(e,(K.localSchemaRevisions.get(e)??0)+1)}e.isTransaction||K.schemaDirty.delete(t)}function revoke(e,t=e?.location){t&&Vb.invalidate(t,e),revokeSqliteDatabaseAdmissionFacts(e)}function revokeSqliteDatabaseAdmissions(e){revoke(K.connections.get(e)??admission$1(e)),K.local.delete(e)}function revokeSqliteDatabaseAdmissionsForPath(e){revoke(Kb(e),e)}function retireSqliteDatabaseAdmissionForPath(e,t={}){let n=Wb(e);if(!n)return;K.localSchemaRevisions.delete(n);let r=E===0?K.registry.records.get(n):Kb(e);K.registry.retireDescriptor(n,t)&&r&&exchangeSqliteDatabaseAdmission(r)}function suspendSqliteDatabaseAdmission(e,t){t?K.suspended.add(e):K.suspended.delete(e)}var Vb,Hb,Ub,Wb,Gb,Kb,qb,Jb,Yb,Xb,Zb,Qb,$b,ex,tx,nx,rx,ix,ax,ox,sx,cx,lx,ux,dx,fx,px,J=__esmMin((()=>{B(),pu(),gu(),ny(),ay(),cy(),ey(),gb(),Rb(),sy(),jv(),Bb(),Vb=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseCleanCloseSeals`),()=>new SqliteDatabaseCleanCloseSeals(publishFact,{retain:e=>K.registry.changeReferences(e,1),release:releaseReference,publish:e=>K.registry.publish(e),descriptor:e=>K.registry.descriptors.get(e.identity)})),Hb=createSqliteDatabaseDescriptorOwner(Vb),{prepareSqliteDatabaseAdmissionAsync:Ub,prepareSqliteDatabaseAdmission:Wb,retainSqliteDatabaseAdmissionLocation:Gb}=Hb,{pathAdmission:Kb}=Hb,qb=createSqliteDatabaseAdmissionReader({state:K,admission:admission$1,pathAdmission:Kb,exchange:exchangeSqliteDatabaseAdmission,publishFact,retain:retainReference,release:releaseReference}),{getSqliteDatabaseAdmission:Jb,getSqliteDatabaseSchemaRevision:Yb,getOrLoadSqliteDatabaseAdmissionForPath:Xb,peekSqliteDatabaseAdmissionForPath:Zb,prepareSqliteDatabaseAdmissionForPath:Qb,hasSqliteDatabaseSchemaAdmissionForPath:$b,getSqliteDatabaseAdmissionIdentityForPath:ex,hasSqliteDatabaseSchemaAdmissionForIdentity:tx}=qb,nx=createSqliteDatabaseWriteReceipts({admission:admission$1,pathAdmission:Kb,retain:retainReference,release:releaseReference,writeListeners:K.writeListeners,readRevision:readSqliteDatabaseWriteRevision,writer:e=>K.dataWriters.get(e),suspended:e=>K.suspended.has(e),hasPendingSchemaMutation:e=>e.isTransaction&&zb.get(e)?.transactionalSchema===!0,publish(e,t){K.registry.publish(e,t),exchangeSqliteDatabaseAdmission(e)}}),{onSqliteDatabaseWriteSettled:rx,retireSqliteDatabaseWriteScopes:ix,retainSqliteDatabaseWriteScopesForPath:ax,withSqliteDatabaseWriteScope:ox,withoutSqliteDatabaseWriteScope:sx,readSqliteDatabaseScopedWriteToken:cx,readSqliteDatabaseScopedWriteTokenForPath:lx,readSqliteDatabaseScopedWriteTokensForPath:ux,readSqliteDatabasePendingScopedWriteToken:dx,readSqliteDatabaseWriteTokenForPath:fx,readSqliteDatabasePendingWriteToken:px}=nx})),mx,hx=__esmMin((()=>{mx={name:`database.engine.schema`,schemaDependent:!0}}));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(!he(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 gx=__esmMin((()=>{})),DatabaseSearchCapabilityUnavailableError,_x=__esmMin((()=>{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`}}}));function postgresSearchVectorSql(e,t,n=1){let r=`coalesce(${t}, '')`;return`to_tsvector(${e}::regconfig, ${n===2?`regexp_replace(${r}, '${yx}', ' ', '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, '${vx}')`,`NEW.${n}`,2)};
  RETURN NEW;
END $$;
CREATE TRIGGER ${r} BEFORE INSERT OR UPDATE OF ${n} ON ${t} FOR EACH ROW EXECUTE FUNCTION ${r}();`}function admitPostgresSearch(e,t,n,r=1){let i=JSON.stringify(t);if(Jb(e,bx)?.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??{})){let t=e.postgres?.dimensions;if(!Number.isInteger(t)||t<1||t>16e3)throw Error(`PostgreSQL vector capability unavailable: dimensions must be 1–16000; choose a supported embedding dimension and rebuild the derived index.`)}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=Jb(e,bx)??[],a=i.find(e=>e.signature===r);publishSqliteDatabaseAdmission(e,bx,[...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(vx)}`,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=`INSERT INTO ${n}(id, embedding) SELECT ${a}, openclaw_vector(${c}, ${e.dimensions}) FROM ${r} WHERE octet_length(${c}) > 0`,d=i===2?`, embedding_bits bit(${e.dimensions}) GENERATED ALWAYS AS (CASE WHEN ${s}.vector_norm(embedding) > 0 THEN ${s}.binary_quantize(embedding)::bit(${e.dimensions}) 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(${e.dimensions}) NOT NULL${d});
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}, ${e.dimensions}))
    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`)}();
${l};`)}return u.join(`
`)}var pgSearchName,vx,yx,bx,xx=__esmMin((()=>{J(),_x(),pgSearchName=e=>`"${e.replaceAll(`"`,`""`)}"`,vx=`openclaw_simple_unaccent`,yx=`[[:punct:]]+`,bx={name:`database.postgres.search`,schemaDependent:!0}}));function postgresStoreNamespace(e,t,n){return`${e}_${t}_${n.replaceAll(`-`,``).slice(0,16)}`}function admitPostgresCapabilities(e){let t=Tx.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 Tx.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. ${Cx}`);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}`});return[e.postgres??``,...a.values(),...l].join(`
`)}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);e.prepare(`UPDATE openclaw_schema_meta SET fingerprint = ?, ddl_hash = ?, server_major = ? WHERE store = ?`).run(postgresSchemaFingerprint(i.catalog),hash$1(postgresSchemaSql(n,wx,i.catalog)),admitPostgresCapabilities(e).serverMajor,n.id)}function verifyPostgresSchema(e,t,n,r,i=!1){let a=postgresSchemaFingerprint(r.catalog),s=postgresSchemaSql(n,wx,r.catalog),{metadata:c}=r,l=admitPostgresCapabilities(e).serverMajor;if(c.server_major===l&&c.fingerprint&&c.fingerprint!==a)throw Error(`PostgreSQL schema drift detected. ${Cx}`);c.server_major===l&&c.fingerprint&&c.ddl_hash===hash$1(s)||(i?e.runTransaction(()=>verifyPostgresSchemaDefinition(e,t,n,r)):verifyAndRecordPostgresSchema(e,t,n,r))}function verifyPostgresSchemaDefinition(e,t,n,r){let i=postgresSchemaFingerprint(r.catalog,{from:t,to:t}),a=`openclaw_check_${Se().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. ${Cx}`)}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}var Sx,Cx,wx,quote,hash$1,Tx,Ex,getAdmittedPostgresSchema,retainPostgresSchema,Dx=__esmMin((()=>{J(),gx(),xx(),Sx=`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)`,Cx=`Use a compatible OpenClaw binary or restore the matching PostgreSQL schema and anchor; do not edit schema metadata.`,wx=`openclaw_schema`,quote=e=>`"${e.replaceAll(`"`,`""`)}"`,hash$1=e=>ye(`sha256`).update(e).digest(`hex`),Tx=/* @__PURE__ */ new WeakMap,Ex={name:`database.postgres.schema`,schemaDependent:!0},getAdmittedPostgresSchema=e=>Jb(e,Ex),retainPostgresSchema=(e,t)=>{let{postgresMigrations:n,...r}=t;publishSqliteDatabaseAdmission(e,Ex,r)}}));function getPostgresPhysicalFacts(e,t){return Jb(e,mx,t)}function admitPostgresPhysicalFacts(e){let t=getPostgresPhysicalFacts(e.db);if(t)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. ${Ox}`,{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. ${Ox}`);if(e.schema){let t=withPostgresSearchExtensions(e.schema,r);e.recordSchema?recordPostgresSchema(e.db,e.namespace,t,r):verifyPostgresSchema(e.db,e.namespace,t,r,e.preserveSchemaSeal),retainPostgresSchema(e.db,t)}let s={engine:`postgres`,admissionId:Se(),store:e.store,namespace:e.namespace,storeId:i.store_id,version:i.version,capabilities:n,catalog:a};return publishSqliteDatabaseAdmission(e.db,mx,s),s}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).`)}var Ox,kx=__esmMin((()=>{J(),hx(),Dx(),Ox=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`}));function rememberSqliteBusyTimeout(e,t){Mx.has(e)||(Mx.add(e),registerNodeSqliteDisposeCallback(e,()=>jx.delete(e))),jx.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=jx.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`);jx.get(e)!==n&&(e.exec(`PRAGMA busy_timeout = ${n}`),rememberSqliteBusyTimeout(e,n))}function shouldReportSqliteLockFailure(e){return Ax.get(e)!==`suppress`}function runWithSqliteBusyTimeout(e,t,n,r={}){let i=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`),a=readSqliteBusyTimeout(e),s=Ax.get(e);r.lockFailureReporting&&Ax.set(e,r.lockFailureReporting),setSqliteBusyTimeout(e,i);let c=!1,restore=()=>{c||=(e.isOpen&&a!==i&&setSqliteBusyTimeout(e,a),s?Ax.set(e,s):Ax.delete(e),!0)};try{return n(restore)}finally{restore()}}var Ax,jx,Mx,Nx=__esmMin((()=>{B(),Du(),Ax=/* @__PURE__ */ new WeakMap,{busyTimeoutByDatabase:jx,trackedDatabases:Mx}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}))}));function allowsMaintenanceLiveAuthorityReads(e,t){let n=resolveIdentityPathViaExistingAncestorSync(t);for(let t=e;t;t=Fx.parents.get(t))if(Px.get(t)?.has(n))return!0;return!1}function maintenanceOwnerHasSourceCustody(e,t){return e?.ownsSchemaMaintenance?(e.assertReadAdmission(),!allowsMaintenanceLiveAuthorityReads(e,t)):!1}function getOpenClawDatabaseMaintenanceScope(){return Fx.current.getStore()?.scope}function isOpenClawDatabaseMaintenanceWorkerAccess(){return Fx.current.getStore()?.workerAccess===!0}function isOpenClawDatabaseMaintenanceResourceOwned(e,t){return Fx.claims.get(e)?.scope===t}function getOpenClawDatabaseMaintenanceResourceScope(e){return Fx.claims.get(e)?.scope}function runMaintenance(e,t,n=isOpenClawDatabaseMaintenanceWorkerAccess()){let r={scope:e,active:!0,workerAccess:n};try{let n=Fx.current.run(r,t);if(n instanceof Promise){let settled=()=>{r.active=!1};n.then(settled,settled),e.track(n)}else r.active=!1;return n}catch(e){throw r.active=!1,e}}function captureOpenClawDatabaseMaintenanceResource(e,t){let n=Fx.claims.get(e),assertCurrent=()=>{if(t.assertOwnerCurrent(),n?.scope!==t||Fx.claims.get(e)!==n)throw Error(`Database maintenance resource owner changed`)};return assertCurrent(),{assertCurrent,async run(e){return assertCurrent(),runMaintenance(t,e)},async runWorker(e){return assertCurrent(),runMaintenance(t,e,!0)}}}function observeOpenClawDatabaseMaintenanceResource(e){if(!e)return;let t=Fx.claims.get(e),n=getOpenClawDatabaseMaintenanceScope();if(!t)return;let r=commonMaintenanceAncestor(t.scope,n);r!==t.scope&&(t.scope.assertAdmission(),t.release(),Fx.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=Fx.parents.get(t))n.add(t);for(let e=t;e;e=Fx.parents.get(e))if(n.has(e))return e}var Px,Fx,Ix=__esmMin((()=>{sp(),B(),Px=resolveGlobalSingleton(Symbol.for(`openclaw.maintenanceLiveAuthorityReads`),()=>/* @__PURE__ */ new WeakMap),Fx=resolveGlobalSingleton(Symbol.for(`openclaw.databaseMaintenanceResources`),()=>({current:new C,claims:/* @__PURE__ */ new WeakMap,parents:/* @__PURE__ */ new WeakMap}))}));function sameFileMutationFingerprint(e,t){return e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.dev===t.dev&&e.ino===t.ino&&e.mtimeNs===t.mtimeNs&&e.size===t.size}function hashFileDescriptorSync(e,t){let{digest:n,bytes:r}=vt(e,{maxBytes:t});return{sha256:n,sizeBytes:r}}function flushAndHashFileSync(e){let t=r.openSync(e,`r+`);try{return r.fsyncSync(t),hashFileDescriptorSync(t)}finally{r.closeSync(t)}}var Lx=__esmMin((()=>{}));function getSqlitePinnedReadSnapshot(e){return Rx.get(e)}function runSqliteSchemaReadSnapshotSync(e,t){let n=Rx.get(e);for(let r=0;;r+=1){Rx.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(!at&&r<4&&(sqliteExtendedResultCode(e)===261||sqliteErrorCode(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||Rx.delete(e)}}}var Rx,zx=__esmMin((()=>{B(),Du(),kb(),Rx=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap)}));function readSqliteTextEncoding(e){let t=Jb(e,Vx);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=Jb(e,Vx),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:Se(),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)&&publishSqliteDatabaseAdmission(e,Vx,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}var Bx,Vx,Hx=__esmMin((()=>{D(),Du(),J(),zx(),Bx={name:`sqlite-schema`,writer:`connection`,lifetime:`process`,schemaDependent:!0,read:e=>isRecord(e)?e:void 0},Vx={name:`sqlite-text-encoding`,writer:`connection`,lifetime:`process`,read:e=>typeof e==`string`?e: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=Yb(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&&publishSqliteDatabaseSchemaChange(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema=!1,t.transactionalTempSchema=!1,t.transactionalFacts=!1),i)}var Ux=__esmMin((()=>{J(),Hx()}));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`||normalizeSchemaSql(e.sql)!==normalizeSchemaSql(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=quoteSqliteIdentifier(e.statusTable),n=quoteSqliteIdentifier(e.pendingTable),r=quoteSqliteIdentifier(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 ${quoteSqliteIdentifier(r)} AFTER ${t} ON main.${quoteSqliteIdentifier(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.${quoteSqliteIdentifier(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}`}))]}}var Wx=__esmMin((()=>{Du(),uy()}));function beginPostgresReadSnapshotScope(e){let t=getPostgresPhysicalFacts(e),n=readSqliteDatabaseWriteRevision(e);return t&&n!==void 0&&Gx.set(e,{schema:t,writeRevision:n,mutationRevision:e.mutationRevision,snapshot:{}}),()=>Gx.delete(e)}function invalidateSqliteSchemaFacts(e){Yb(e),invalidateSchemaFacts(e,!0)}function invalidateSchemaFacts(e,t,n=`main`,r=n!==`temp`){let i=zb.get(e);if(i){let a=n===`main`;if(i.isolatedTempTables.clear(),e.isTransaction&&(i.transactionMutationRevision=void 0),a&&invalidateLocalSqliteSchemaAdmissions(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&&publishSqliteDatabaseSchemaChange(e)}}function registerSqliteSchemaMutationListener(e,t){let n=zb.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);discardSqliteDatabaseTransactionAdmissions(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&&publishSqliteDatabaseSchemaChange(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema&&=e.isTransaction,t.transactionalTempSchema&&=e.isTransaction,t.transactionalFacts=!1)},i=observeSqliteNativeOperations(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;observeSqliteTransactionState(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!==Yb(e))t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.transactionalFacts=!0;else if(observeSchemaLifetime(e,t,void 0),!t.facts&&!t.transactionalSchema){let n=Jb(e,Bx);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=Yb(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&&!canPreserveTransactionSnapshot(a,f),h=a?.kind===`ROLLBACK`,g=h&&t.transactionalSchema&&!a.outerRollback,v=c&&!n.temporaryTableSchemaChange||h&&t.transactionalSchema,y=l||g?`main`:h?t.transactionalTempSchema&&!t.transactionalSchema?`temp`:`rollback`:n.temporaryTableSchemaChange?`temp`:`local`;h&&discardSqliteDatabaseTransactionAdmissions(e),(c||h)&&invalidateSchemaFacts(e,!1,y,v),(s||n.temporaryTableSchemaChange||a?.kind===`ROLLBACK`)&&(t.mutationRevision+=1),i!==`bind`&&f&&!a&&!t.transactionCatalogBound&&(t.transactionRead=!0);let b=c||s||a!==void 0,x=n.temporaryWriteTables?.every(e=>t.isolatedTempTables.has(e));(s&&!x||l)&&beginSqliteDatabaseWrite(e,l||t.nativeDepth>0),b&&(t.mutationDepth+=1),t.nativeDepth+=1;let ee=beginSqliteDatabaseAdmissionOperation(e),te=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),ee(),--t.nativeDepth,b&&--t.mutationDepth,!e.isOpen)return;(c||h)&&(h&&discardSqliteDatabaseTransactionAdmissions(e),invalidateSchemaFacts(e,!1,y,v));let s=n&&f&&a?.outerRollback===!0&&!e.isTransaction&&!l&&t.schemaMutationRevision===te;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&&publishSqliteDatabaseSchemaChange(e),s||settle(m),i&&!e.isTransaction&&!s&&(invalidateTrackedSqliteSchemaFacts(t),n||discardSqliteDatabaseTransactionAdmissions(e),t.admitted&&!t.authorizerActive&&!r&&(getAdmittedSqliteSchemaFacts(e),t.transactionBaseFacts=void 0)),t.pendingSchema=!1}finally{t.settling=!1}}finishSqliteReadScope(e,t,f,m,n,p),t.mutationDepth===0&&!e.isTransaction&&finishSqliteDatabaseWrite(e,i),t.transactionRead||=e.isTransaction&&!(!a||a.single)}}});observeSqliteNativeClose(e,()=>{finishSqliteDatabaseWrite(e),releaseSqliteDatabaseAdmission(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,suspendSqliteDatabaseAdmission(e,t.authorizerActive),invalidateTrackedSqliteSchemaFacts(t)}),registerNodeSqliteDisposeCallback(e,()=>{invalidateTrackedSqliteSchemaFacts(t),t.readRevision=void 0,t.transactionSnapshot=void 0})}function readSqliteNativeMutationRevision(e){return isPostgresSqlConnection(e)?e.mutationRevision:zb.get(e)?.mutationRevision}function runSqliteReadOperationSync(e,t){if(isPostgresSqlConnection(e))return t();let n=zb.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(!zb.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};zb.set(e,r),trackSchemaChanges(e,r,t,n);let i=Yb(e,{existingOnly:!0}),a=Jb(e,Bx,{existingOnly:!0});a&&(r.admitted=!0,r.facts={...a,revision:r.revision},r.processRevision=i)}}function isSqliteSchemaAdmissionCold(e){let t=zb.get(e);return!(!t||t.admitted||t.authorizerActive)}function admitSqliteSchema(e,t){let n=zb.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=settleSqliteDatabaseAdmissionPublication(e))}function getAdmittedSqliteSchemaFacts(e,t){if(isPostgresSqlConnection(e))return;let n=zb.get(e);if(!n?.admitted||n.authorizerActive)return;let r=getSqlitePinnedReadSnapshot(e),i=e.isTransaction&&(n.transactionRead||n.transactionCatalogBound)&&n.processRevision!==Yb(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:Jb(e,Bx);if(c)return t?.(c.userVersion),n.facts={...c,revision:n.revision},n.facts;let l=Yb(e);n.facts=captureTrackedSqliteSchemaFacts(e,n,t),n.iteratorFacts||=n.unmanagedSnapshots.size>0,n.qualifiedSnapshot=r,n.transactionCatalogBound||=e.isTransaction,s||publishSqliteDatabaseAdmission(e,Bx,n.facts,{schemaRevision:l})}return n.facts}var Gx,Y=__esmMin((()=>{B(),kx(),Du(),gu(),J(),Lb(),zx(),jv(),Hx(),Ux(),Mb(),Bb(),Wx(),Gx=resolveGlobalSingleton(Symbol.for(`openclaw.postgresReadSnapshots`),()=>/* @__PURE__ */ new WeakMap)})),Kx=__esmMin((()=>{Ix(),Lx(),Y()}));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||readSqliteDatabaseWriteRevision(e)===void 0)return;let i=fx(r);if(i===void 0)return;let a=qx.get(t);if(a||(a={committed:/* @__PURE__ */ new Map,transactions:/* @__PURE__ */ new WeakMap},qx.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 qx,Jx=__esmMin((()=>{Ix(),J(),Y(),qx=/* @__PURE__ */ new WeakMap}));function assertSqliteIntegrity(e,t,n={}){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(t){if(!n.ftsSchemas||!(t instanceof SqliteIntegrityError)||!t.findings||!classifySqliteFtsIntegrityFindings(e,t.findings,n.ftsSchemas))throw t;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&&recordSqliteDatabaseIntegrity(e),{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=findSqlClosingParenthesis(e,t.index+t[0].length-1),a=i.get(n)??/* @__PURE__ */ new Set;a.add(normalizeSchemaSql(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(normalizeSchemaSql(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){let r=e instanceof Error?e.message:String(e);throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${r}`,e)}if(a.length===1&&a[0]===`ok`)return`ok`;let s=a.map(e=>String(e)).join(`; `)||`no result`;throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${s}`,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){let n=e instanceof Error?e.message:String(e);throw new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${n}`,e)}if(a.length===0)return;if(r)throw new SqliteRepairableForeignKeyError(t,n);let s=a.map(formatSqliteForeignKeyViolation);throw n>Yx&&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}function retainSortedForeignKeyViolation(e,t){e.push(t),e.sort(compareSqliteForeignKeyViolations),e.length>Yx&&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()})`}var Yx,SqliteRepairableForeignKeyError,SqliteIntegrityError,Xx=__esmMin((()=>{gb(),J(),kb(),Kx(),Hx(),uy(),Jx(),Yx=5,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}}},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 readSqliteAgentFingerprint(e){let t=Qx[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Zx[e][0]),indexNames:i.flatMap(e=>Zx[e][1])}}function readSqliteAgentCatalog(t){if(!Qx[t])return;$x??=e(import.meta.url)(Ie(new URL(`../../assets/sqlite-schema/sqlite-agent-catalogs.json`,import.meta.url).href));let n=$x.catalogs[t];return{tables:n.tables.map(e=>$x.tables[e]),views:n.views}}var Zx,Qx,$x,eS=__esmMin((()=>{Zx=[[`acp_parent_stream_events`,[`idx_agent_acp_parent_stream_run`]],[`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_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_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`]],[`state_leases`,[]]],Qx={d6ea4f25014de415b806f2b77b529b838444f8aacf44cb2192ba6990fdfab566:[`agent`,`22365c27fbdfb45c71d0df7692b8c8c1dee844c2b27297710612cb2484f52e1b`,[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],[]],"0d8863d033ed867b9e5410fbf5653fff5668cde5bc9933efdc54a948ef28b3a7":[`agent-version-1`,`0ac0c6eca2bd401dba88942343f73a31b0c1fa320b4ef72672a421775667f341`,[0,1,2,3,4,5,57,58,8,9,59,60,12,13,61,15,62,17,18,19,20,22,24,63,26,27,64,65,30,31,66,33,34,35,37,38,39,40,41,42,43,45,67,47,48,49,50,51,52,68,69,70,56],[]],"987c7895f0acfaa27bdd4af5532a6a9d7364cbbefe8fe63fa9775b9520b25f85":[`agent-version-18`,`516c6a0cbc9a63134e84a65c3af806fbc6b526292c614c84109f4a2b2c106afc`,[0,1,2,3,4,5,57,58,8,9,59,60,12,13,61,15,62,17,18,19,20,22,24,63,26,27,64,29,30,31,66,33,34,35,37,38,39,40,41,42,43,45,67,47,48,49,50,51,52,68,69,70,56],[]],"7a92498057481f996a0c0716dd078ea69694645fbdb3a011dadaee411478b7ad":[`agent-version-21`,`fd83bd56e757e27046bc16f16e0dfd056a4bdb4c187672807f9286089fd4c130`,[0,1,2,3,4,5,57,58,8,9,59,60,12,13,61,15,62,17,18,19,20,21,22,24,63,71,27,72,29,30,31,66,33,34,35,37,38,39,40,41,42,43,45,73,47,48,49,50,51,52,68,69,70,56],[]],"789a67b22bc47d0b58acb19a6041b3ba55bd68c7e7271a4043573739edae02d1":[`agent-version-22`,`1571750d60d036d5b09e53c9d062396551d72f79642ee52ae104e9213da8592c`,[0,1,2,3,4,5,57,58,8,9,59,60,12,13,61,15,62,17,18,19,20,21,22,24,63,71,27,72,29,30,31,66,33,34,35,37,38,39,40,41,42,43,74,75,73,47,48,49,50,51,52,68,69,70,56],[]],dd91f9df477a6b80f156003269b951f0d4e55d62e6dec37ad23dc909ed61f71f:[`agent-version-23`,`4cd5cf45ce55fd199d3025021381ad10187c3a5db5340aec56aa108c5a315611`,[0,1,2,3,4,5,57,58,8,9,10,60,12,13,76,15,62,17,18,19,20,21,22,24,63,71,27,72,29,30,31,66,33,34,35,37,38,39,40,41,42,43,44,45,73,47,48,49,50,51,52,68,69,77,56],[]],"9b51fb6f3b7692ed5b1d114c9123184aacb35d5c8450f896b5d289fd46f0ae60":[`agent-version-24`,`7ba969c7ed61eb3596c809150d7c46676bfb3d8310052ca5f07141762b345e9b`,[0,1,2,3,4,5,57,58,8,9,10,60,12,13,76,15,62,17,18,19,20,21,22,23,24,63,71,27,78,29,30,31,66,33,34,35,37,38,39,40,41,42,43,44,45,73,47,48,49,50,51,52,68,69,77,56],[]],"17cbb50319db12e22248e0397cb068ce670687a96328f502ce3577e4798ae299":[`agent-version-25`,`f4118fc6b09e2d36542335eec66c82e9846b7f50e69e56076814dea6e1244aeb`,[0,1,2,3,4,5,57,58,8,9,10,60,12,13,76,15,62,17,18,19,20,21,22,23,24,63,26,27,79,29,30,31,66,33,34,35,37,38,39,40,41,42,43,44,45,67,47,48,49,50,51,52,68,69,77,56],[]],ff21eb3fb5a5836d520af3ea0777944cbcfa61aff52a64d0726a4d6b527823c3:[`agent-version-26`,`86dbc086643d83045d9397da12e5e7a5d197b08a10a8aea4942ee7473f03d9ee`,[0,1,2,3,4,5,80,58,8,9,10,60,12,13,76,15,62,17,18,19,20,21,22,23,24,63,26,27,81,29,30,31,66,33,34,35,37,38,39,40,41,42,43,44,45,67,47,48,49,50,51,52,68,69,55,56],[]],"227fcd299f5dfd3012abd0f110cd028ba6add9155bc74e2e558aadeae2761349":[`agent-version-27`,`40d0b84e2467b65ff57c4e8171af1a6b0cc54e0e1b5602b6abbe53fc8c10e151`,[0,1,2,3,4,5,6,58,8,9,10,60,12,13,76,15,62,17,18,19,20,21,22,23,24,63,26,27,81,29,30,31,66,33,34,35,37,38,39,40,41,42,43,44,45,67,47,48,49,50,51,52,68,69,55,56],[]],b2e17ebad450773253e5dddaeb87e6baef26b1c20a48982ed9df7ffea4210511:[`agent-version-28`,`a48c6c4d7bc63bb0c14eb2010893f31aa216e4a0ee135e40c81598a39c64b61f`,[0,1,2,3,4,5,6,58,8,9,10,11,12,13,76,15,62,17,18,19,20,21,22,23,24,63,26,27,81,29,30,31,66,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,68,54,55,56],[]],abf65b8c18ccb84f0e65b8e4faa6fef6abc23b6bab5e93086339f640d2146082:[`agent-version-29`,`ede47c9558c7c22dfd89ed56f0bc28a9d22e512aa69af0ae3acacc989337dc0e`,[0,1,2,3,4,5,6,58,8,9,10,11,12,13,76,15,62,17,18,19,20,21,22,23,24,63,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,68,54,55,56],[]],dbab54723ad6be5e0146085df0789ef92d03b867c53bed915d804fb4c60b3068:[`agent-version-30`,`afa4044fdeabdb3042002c27a39be73d1f2edf8c4135515266cf6613adc7f0ba`,[0,1,2,3,4,5,6,58,8,9,10,11,12,13,76,15,62,17,18,19,20,21,22,23,24,63,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],[]],"57f4523156caf6b8446afbd95e0fede01f1c917771242cd05c61c1b48b7e157e":[`agent-version-31`,`4ac0d88399760668d6021213299ff6897bcfd672d2373d5c47b6f0afa31e04a1`,[0,1,2,3,4,5,6,58,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,63,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],[]],"9ffa671518cafee606f88dd17bfdfa9792d9deece5f6773e3cae4de2c10fc84b":[`agent-version-37`,`08f828422ad38a4ad92a46abdd793fd45ce6c9e09e72d83177130079588ea41e`,[0,1,2,3,4,5,6,58,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,63,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],[]],"067f95cffb76737d9084b726b640bc79b266b19279e6b1a3d2322d0e298c6ab6":[`agent-v14-core`,`14b30834a4c01ee92da4b3390aebbd49d9a8f4d0fb3a40fb517b8093ffb11c76`,[0,1,2,5,57,58,8,9,59,60,12,13,61,15,62,17,18,19,20,22,24,63,26,64,65,30,34,35,37,38,39,40,41,42,43,45,67,47,48,49,50,51,52,68,69,70,56],[]],aca181a3ea4d5a94d263653e1b75d2327bd449673d631e9d22c6cb9fe25e40ea:[`agent-v14-session-sharing`,`dcd6c30e5c80fa6647cf4b3257fc0c5a6e3440c20333797263b813add4f43fa2`,[27],[]],be5d39d4389597fcfe2942f51a97d5b1f4e0aa1d6b184677e6abcedc162a2cf0:[`agent-v14-additive`,`08e596f53eef1390bb3048a8c3807ea2413fde157899e0feb314aeebeb26e132`,[66,33],[]],"9b07b30dc725415736f5873babff2b98a1e8bf40e0afbf4eb8cf3d3cf700dc0b":[`agent-v14-board`,`535e952ff0024800a42260733be4f1ab5095d5f7578d78555e351c3c336b4f5a`,[3,4],[]],"83673559dc6bba9fdf13d5a9131b030103935b04d7c81620b0a67f43cb49f970":[`agent-progress-card`,`cbda56cf07f5a79268f761f3c0478fd5c3a6ddefde2cb72a933d9eef110a17a1`,[31],[]],fdc21b6dc361c491311c11d91fbda296535a9c34dd20f0ab03b949b8a698ded0:[`agent-retired-state-leases`,`6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc`,[82],[]],c45b82b3c3aa8ecc3b2cc09dcf38bd568edfa8305f54b5bb959c975a55571ece:[`agent-legacy-participants`,`30851780a54c5bd9b7bd3be1f420fc2b3e61839901e1a726e6cb24a10f8d4276`,[65],[]],"6ce6f0ae658b1b77759d335e07e75d9371e27363c998bbf9b0e5fc5a132bc4cb":[`agent-deployed-fts-rows`,`81df0b00eeb5ae756a6acce81b099c432f6127233d47582dd60ca32eed304768`,[74],[]],"0e9e5f47efa71d187ed505aee8d1e423865a5de8df5387a15759194561307e72":[`agent-legacy-transcript-events`,`6e5d060cc60439ef893bf9bcf395552be213733a1021f82d9ea1173e6103ed2e`,[70],[]]}}));function readSqliteClientFingerprint(e){let t=nS[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>tS[e][0]),indexNames:i.flatMap(e=>tS[e][1])}}function readSqliteClientCatalog(t){if(!nS[t])return;rS??=e(import.meta.url)(Ie(new URL(`../../assets/sqlite-schema/sqlite-client-catalogs.json`,import.meta.url).href));let n=rS.catalogs[t];return{tables:n.tables.map(e=>rS.tables[e]),views:n.views}}var tS,nS,rS,iS=__esmMin((()=>{tS=[[`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`,[]]],nS={"8e4004e9307fcb7ad18d0b12c076f008afd89a8dcacff53e9d40a3b7881acab9":[`client-credentials-v1`,`a00fccb1a356c0d0f77c40341f320602e4f73396bd88865a238b7f4187edd949`,[0,1,2,3,4],[]]}}));function readSqliteDaemonFingerprint(e){let t=oS[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>aS[e][0]),indexNames:i.flatMap(e=>aS[e][1])}}function readSqliteDaemonCatalog(t){if(!oS[t])return;sS??=e(import.meta.url)(Ie(new URL(`../../assets/sqlite-schema/sqlite-daemon-catalogs.json`,import.meta.url).href));let n=sS.catalogs[t];return{tables:n.tables.map(e=>sS.tables[e]),views:n.views}}var aS,oS,sS,cS=__esmMin((()=>{aS=[[`daemon_runtime_pin_migration`,[]],[`daemon_runtime_pins`,[]]],oS={"2da8e5914c65eb868e035a1ebbab7a104fceca3c4b4c1e44dccd14c3387c3376":[`daemon-runtime-pins-v1`,`126cb31aa1921bcac9c54618fdbb59cc157d4d86a456508eea2879db32a716e0`,[0,1],[]]}}));function readSqliteMemoryFingerprint(e){let t=uS[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>lS[e][0]),indexNames:i.flatMap(e=>lS[e][1])}}function readSqliteMemoryCatalog(t){if(!uS[t])return;dS??=e(import.meta.url)(Ie(new URL(`../../assets/sqlite-schema/sqlite-memory-catalogs.json`,import.meta.url).href));let n=dS.catalogs[t];return{tables:n.tables.map(e=>dS.tables[e]),views:n.views}}var lS,uS,dS,fS=__esmMin((()=>{lS=[[`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`,[]]],uS={"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],[]]}}));function readSqliteStateFingerprint(e){let t=mS[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>pS[e][0]),indexNames:i.flatMap(e=>pS[e][1])}}function readSqliteStateCatalog(t){if(!mS[t])return;hS??=e(import.meta.url)(Ie(new URL(`../../assets/sqlite-schema/sqlite-state-catalogs.json`,import.meta.url).href));let n=hS.catalogs[t];return{tables:n.tables.map(e=>hS.tables[e]),views:n.views}}var pS,mS,hS,gS=__esmMin((()=>{pS=[[`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_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`]],[`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`]],[`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`,[]],[`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`]]],mS={b2ec9b58da4e49ede387db0c7345fe2dcf3a2e228736ca92a5223fc8bf518a6b:[`state`,`d331f5ba5e6b472b8358da366fe5cd66dd556f78630b407e7cd5fe8104edba06`,[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],[]],d436399d596dabc437f6a66024912269ba78d4cebcdb8603202b041185ba4d2d:[`state-before-v36`,`5c2559369839679bb534edddc847180532b37bd1b0ae419a715a860d0be92972`,[0,1,2,3,4,5,132,7,8,9,10,11,12,13,14,15,16,17,133,134,135,136,137,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,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],"9a869616f3471fe3b5f06a7c5d026a1940080a5df0e58a4b6c2088ab5ca745ff":[`state-before-v35`,`9f90b9db5bceba7fba5559f518caea2b58e6fc363d6ddf160e4793ab4a08aa33`,[0,1,2,3,4,5,132,7,8,9,10,11,12,13,14,15,16,17,133,134,135,136,137,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,138,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,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],"36936a3edd8896ac1f8a0f73b6c8334385f9262f8eb7f1ddb1e83298554e2656":[`state-before-v31`,`587dd22498db1b171f12a7838200384e50360089996b15307855845552be952d`,[0,1,2,3,4,5,132,7,8,9,10,11,12,13,14,15,16,17,133,134,135,136,137,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,139,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,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],"0fd39f9f198388f809574b23fd5532e4c762071e830d1da5c26a0ff7629c8032":[`state-before-v27`,`7c96f5aeee1c1410ac0dd23b2a9534ab346f6528f34ab00fb9d724b74d6a3f59`,[140,1,2,3,4,5,132,7,8,9,10,11,12,13,14,15,16,17,133,134,135,136,137,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,139,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,141,98,142,100,101,102,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],"79517c2d72c03b744524b3dd9d78389ec065e25ff619698a3b10e8cb252f5255":[`state-before-v26`,`13c4baab95b591ab2bb07e7e06557f456b0b2207741bb7554e0f08e5d247b12e`,[140,1,2,3,4,5,132,7,8,9,10,11,12,13,14,15,16,17,133,134,135,136,137,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,139,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,143,89,90,91,92,93,94,95,96,141,98,142,100,101,102,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],"54911300fd4efbb44a652d781badc61c60be05619fba7bd6a64b1d1bc2121a81":[`fragment-local_workspace_projections`,`39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497`,[48,49,50,51],[]],f0e11a6fff0a4b79b69a28a0f2ec4694fa1ee88672cac3b7338bc0a3bb9f8d19:[`state-feature-local_workspace_projections`,`39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497`,[48,49,50,51],[]],e119e5203e18e9fba13d43368408775eca1d809807579a697482ab2b7011e840:[`state-feature-local_workspace_manifest_nodes`,`8db5abfb2c2f4c380c80647305b1e4bb5e6af7ac2fec71205a52a97d86835291`,[48],[]],"3142caa54d9bd7d285b37ed3338ed9f4307ad3b32469bd88deecb8725301861e":[`state-feature-local_workspace_tree_packs`,`a63984593fd118417812466c9ee0c189fd7d819401af1943a6f9c11730c47d87`,[51],[]],e95059f2306c8231ee92ef3d76dfcb434a80885f08cbf39380f88a287f98bade:[`state-feature-local_workspace_source_path_sets`,`ead9623df4d41d649f8e4af2351694db5bc8c4e70edb7d2322ba76c11d0dfddb`,[50],[]],bc86e378ea153c42527b6106b01ba4cb8285cca40378ffa0142656577309723e:[`fragment-user_profiles`,`268e6f3b53eb2048a3edf527da424f8df229a01166befc8137ea94dbb560227e`,[144,111,145],[]],f5b54f0fedd88d94c24add8a1fd987ac8592b05d4615424bab9dbc0d19c9cd4a:[`state-feature-user_profiles`,`2c2611b7d0c64f467494ae3922f763dee7fc023a5ee6b92d5821639b18e825aa`,[144,146,145],[]],"9eaae0feb245733106045a2c6766d2a2a729a9bdb22b98ec4434c09d76663264":[`state-feature-user_profile_emails`,`202fadb0df4fc5da385edddbda27e96126d0d7a2db6a63375fa506221163a4fb`,[147],[]],"45451969c6ea5bebf37bbfba310467e482af74731a7cb0f2affb316059e21528":[`state-feature-user_profile_identities`,`3a24e89bd446dffbef50b7bd4b87288abc6eb470c290eaabcb1761fbe5244c06`,[146],[]],"561e14603e294368a12a2b5f6ecb0cc509d0b8847a93817286bd5a14d076ad0f":[`fragment-skill_library_entries`,`c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d`,[91,92,93,94],[]],"6b07280274e87ca0fa5bbc1887818497375298fa700b24852dc981f3da1da555":[`state-feature-skill_library_entries`,`c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d`,[91,92,93,94],[]],"43645abd05379894c2982bcd88b8dff0cd6c9802e5bf2ab6cc54af87a7e6a37d":[`state-feature-skill_library_revisions`,`533218405c3e483d687da824cf15f9ebcb76ba69675946e95c134702dc199890`,[93],[]],ea1b1fb7d6d8256ec58bc7c28541312c1a543e88bf9ed7e4366791ea243d8ec0:[`state-feature-skill_library_events`,`e5269a0f2846007c0b3eef62963979fa7a2cdd01ced20906ec4ac407ace66c03`,[92],[]],"31318a62bdb75dccad514a02adde07df11d26b756f51d1d50d0e6b19d399b26e":[`state-feature-skill_library_uploads`,`ba066e91b42e768b5f705703783cce87eb90fac71a37cad9dfdf308a19ccceb6`,[94],[]],ed3d9e7b13809b3a9b91d48d63816b26354681d727b96e39496d02c775343e1f:[`fragment-operator_approval_standing_grants`,`9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa`,[71,72],[]],be37db3a4634164c401b2d8e5ac3c2d712cd9eb973e3f2b39daa578adedff0ae:[`state-feature-operator_approval_standing_grants`,`9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa`,[71,72],[]],e23a5880a289da464471db5cfff10b9a6962b4d52c99260a3e366746c023de76:[`state-feature-operator_approval_standing_grant_generations`,`0d525f0400a30f0582698e91e78f63063c08a8c06b3bcfe624dbd2f2fbe7834c`,[71],[]],"7b8bf2fd3ae786c589bf138b32270450c1a2582bcb9a825c1eaf7fb3a7bcea06":[`fragment-worker_environment_session_attachments`,`b95d7054311f0f2d1e0885104c66ff243dfe4f68b84ed2d814ae68e748574417`,[148],[]],"6496f80e29da252472af802873996fc3cd761f245f4dcf6fefb1c7aee38e720b":[`fragment-sandbox_persistent_execs`,`f885f117e199277aa5c23a9095f55e742797249d13e2f4e4df8fbef1daba399d`,[81],[]],"156673e9396f27223073abdbbd2e13269bd7f45f577ed6aff00e017ab232d940":[`state-feature-sandbox_persistent_execs`,`026ac7355b83187c8f7eef5cbd48ab36ba7de1b4fe40413ee1168ebff6c2d67a`,[149],[]],"61e308c5a715e5ee5ff29b65a31d2e7ccd039498494d9afe120129f62f86b764":[`fragment-user_background_images`,`1da03995969350f59b3f8a64d9144b781d467e6ea75f70d5abcd6e18734678e1`,[109],[]],b36f4fc0be0d53e48e207f50a3cba34df76c4028a2d85201f7b262b1c7a4c2ab:[`fragment-update_runs`,`7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55`,[108],[]],c3db4ffcf4092146e5d923b60516a00a8db41825f8bffb138b848195576b987b:[`state-feature-update_runs`,`4caad814f837565106a1a17b982bf4ff004bbdba00a6ff05a3b9c5ef2e5a5945`,[150],[]],"7d47dc1ae79e1c40ab11a56da183af8e8e5dd1435e044ac4e44be2c6595783e0":[`fragment-session_repository_workspaces`,`7f1a1b36d06c7c4cb5e84d6a16ca23de89dbac6b68c97c31897d1d1825a17d01`,[86],[]],d62b52a34e2626a7983ae5c48268f04567e93170457e63502b7096486a6ce9f7:[`fragment-github_repository_publication_requests`,`1ae034bde6e00a9b919bcbb987df8aebc5856ab6f4c979743355ecb682418a99`,[47],[]],"6d205ed705fcf89e34e2679f192b2dd50e4cbcb9b06b473c3e81dd48c8811102":[`state-feature-github_repository_publication_requests`,`bc5c46f3cc22c0572b25d10344108465509d7189e1d51b0f6fa335b1d86497cf`,[151],[]],"079ee34fc1ed4ca27e807b01c7456deceacc57fead388917ff1b275b5047ab06":[`fragment-github_publication_session_lifecycles`,`755e9a26722c11b5edd9d4f6bf270bfdc706428593de4216c311f85fad0a8e69`,[46],[]],fc4d434c6c76c4e5c5b1fb9c54ebe7e98a395fea6370ada7ac4767ad755051ac:[`fragment-github_personal_publication_requests`,`eda486fc6d1c12adfe86012cfa6d0f6afb64906b1d4c75e3785bda082281a4e1`,[44],[]],"8a4a42e9e8549a0f2e73b33b4031673e2e939624d95586693bc2ac43742bf30f":[`state-feature-github_personal_publication_requests`,`aeb05b8ff41f64e5bab165feac6f1abcdb6dfefc2a5bfbbe88e34861cc40922e`,[152],[]],"0f3d662483be17f95f492157a8ba28b163afab9c52429ab6ff277ebe8b0a27fd":[`fragment-cron_job_runtime_authorities`,`ebce08da69716c0011c0db38decb38e5eaa0069c6f8360e85afdec8c624a360e`,[22],[]],e16c741ca5371718cf7d95114ee1043ad33db04c470f268ccbe3130f699998d9:[`fragment-cron_run_trigger_state_retirements`,`0e85a9fecddeef5129569f503fb32cc0d94e9c98877286be10e15eb657e682bb`,[26],[]],"632466e72325a428d8b4c4dfa1b7a14be9f57236bee791e9412ea07b24fca254":[`fragment-execution_identity_contexts`,`15be6a7de30d2ecb9b15fed1eb13dd65da858f1eb378e95f737f14241c11b3d9`,[37],[]],"7683ab1fd0bccb8e29499c3b6df0070d9cc7cd6249c8c103d654b015ce309417":[`state-feature-execution_identity_contexts`,`2dc283d04b315fd0199a9e13653edb03c8614d12be2ca6f005c7e110aab62d2a`,[153],[]],b796607c50ccb0e85abdec5d76b88b8076596077afe71e238b7831edd061f9e8:[`fragment-mcp_oauth_pending_authorizations`,`39eae7dacb98a3cc36bd7598c4e416fc3f180c95aa78b7fd5a1f11afecf2d5b9`,[54],[]],"15f660904a6ff5b2e08b57e7e1979ae85d7476426da0e6aa8fc35a013d557501":[`fragment-node_worker_launch_containers`,`bae513184057ef120b3b7ff1f08fc0affa1293461353ac060f1c0148346225f5`,[64],[]],"2703e870e99174d91597e44b5619574373f3da7030c4cd9907a8ac341f00802f":[`fragment-node_worker_launch_boots`,`ce110d8dd52daad838b24137dc43979dafe784dd08348e09482093f47dd5d98b`,[62],[]],"7c1c6d4fbba2f48e6ad4003bbc7d22b3b543034a8c2456fc542d2dac90c46aad":[`fragment-node_worker_launch_cleanup`,`d45196104873c5924d0fddabdce7a4f08b8fab2c68880492de968c978ef031c8`,[63],[]],"16bb8bbf8eb97d4a3895c031f758ca37106c072cd78e18b99e4f68463679c153":[`fragment-node_worker_launch_process_scopes`,`d9ce1d80156505cb99854d410b48f37b0cf82d0259417bd3c64e1ff91d5b05b2`,[65],[]],b6d0283d081e77179a54f4e54847168156095e3ec4a487d17feea8dfe26a1626:[`fragment-node_worker_launches`,`cac88014114f03cee09470505617bc58f893efc072306d0b4c6fb48e259fb17c`,[66],[]],"5dc1cf9bb59834e9497e191514c7bfb850e062f7744047c7a4289516b4b0e214":[`state-feature-node_worker_launches`,`f07514c3996f79e89f46d771b58859826342f72a12f024b29726a82f6481d6f9`,[154],[]],"5e238c5c57f8e1bfc2d5fc91ad2a4ad3ae421ca1f36a84f973a8299f99ee7015":[`fragment-node_worker_prepared_workspaces`,`1ab2c378547ad29580b84dcebbc4ed9c99008c8a242446cdad0553a24bf06eec`,[67],[]],"865397a51b0e47eda5349293c3fc590226718cdad61afe420c578ab3ec786732":[`fragment-node_worker_turns`,`cb3eaac1dc2492905a55c037ba7c09748bbdbc9c6a13cbb92e3cbec80c94f5d6`,[68],[]],"64cf0d044c7dede24d58a370a2f52cf19616efc9523343a698f7127c4d187f1d":[`state-feature-node_worker_turns`,`d1d9be01c96d9dd47e4e23d0099074f561aedb976de062622daffd173443c17d`,[155],[]],eee176fa30fb315a218b50f12be8d9e4e5561441d59250cf7029aac4edd9eb38:[`fragment-operator_approval_execution_identities`,`0f2bc5e4d656eda1ad36b778905e7e55f8685c0b41a68883f6e9fb1b838a874c`,[70],[]],"57562a3e6f834f876e5c03711f50dc514c8bdd432a87f1f54cbac2901642d5d4":[`fragment-web_push_approval_deliveries`,`f11526f4044590884acc313f8a8fb921ce93fb2372e2e64a635989af93d3012e`,[112],[]],"74b05c720f6b4a8ff88824c9843816992d5233b93ccd85bea66c2fbd2a3480c5":[`state-feature-web_push_approval_deliveries`,`92bd2e9265be63167980a22960aa201502864ec59e283821ad3eab6e765744ce`,[156],[]],"0b710f9ea230c2d23182de151edebc06dfb2800ad6207647d27ccb2c900b5d6a":[`fragment-execution_decision_facts`,`251fe6aa9c0c1ef726ab36810df59e644d472757b269b7e6ac36a5b7b1864ccc`,[36],[]],"9cd9f63b1002094a7e0538c52b75f2c8d26664937ff5559f64a004feabe47816":[`state-feature-execution_decision_facts`,`8235ed3d9eb951894768fa49670db7390f7950e96618daded2851a55c2e827ed`,[157],[]],"49e2b7094b1bf25586bc63b3ce3e971873c26584de40bd96654a31b945b3881f":[`fragment-execution_owner_lifecycle_bindings`,`83228457b7900a349a7a60693f5be9fe5ce2b86f8ea3be6bd1b3bcbae9381c73`,[38],[]],c222191b2157eb84fae227b67417210870ff546ce38b799805cd32e63e198bcd:[`fragment-outbound_message_execution_bindings`,`90715ffad8419a713baa7a63aa0d15038b16391bba0c3739bdae7c3196cc5fe5`,[75],[]],f782e56e1dca81426ff88a94a9702580d0c6bdd1a420e8c1741fef3aa7c18b81:[`state-feature-outbound_message_execution_bindings`,`c29af535c3d6cf16bb31a085c7b68d150c132921b51f560495e75dd1f5451f2d`,[158],[]],"733bbcfcce8373ce968a993fc1f4d3f911d0011c8a60833f613f9cdb7de22d9e":[`fragment-outbound_message_progress`,`07938ecb7fa35203a80bf93cb28900b5eb0c35dcf47bfa476b436fd39d881135`,[76],[]],"6e2c6c197a77c179716d6ddead9a7226c49db5e8b69c1775ea8808e5e24cf271":[`state-feature-outbound_message_progress`,`b1fdd16f1d29ceeed6d32e873b0ef54831ad693b4e910c1fe55bc59aa60c4709`,[159],[]],ab3748daca8019e0908cc9906304f50a26cffd9d5e9ea3ba1ea3a759315737cb:[`fragment-agent_provenance`,`da5d017b6840d65ebd1bc234ae3fdf4540bd00256bfc50c599a4195d15066c17`,[6],[]],be11d3e5a672ca34875c1f06cfc6d5d5a1293a7077302a759c12c2c17b2cdcb6:[`fragment-cron_run_receipts`,`593a0b293257e23cf22f14e308c7f75a7032d5f0bdbba0fa3d307f3382e3bd4c`,[25],[]],"41824738e9d17ef8abfa9bda96824ab259ca9e81d3ad647b16b407a6bc4dc28f":[`state-feature-cron_run_receipts`,`1c1c9f4b60d18e51e0db6940a6813c5a7a1a14dffbe38921318e61c295597112`,[160],[]],"8b28fd18dffd5b09fb5a09d8e0d04b2dbf1372081b356131f1df2f4c41895745":[`fragment-config_revision_keys`,`8b416bf248c7702519e58249d29725d42d52a95d8a22084964637f3ed57cae9d`,[21],[]],"443ee39ca023c21d0234f2897e3790e8e9757daf427989b731f97074c5bf28fe":[`fragment-secret_store_entries`,`45f2e66f10baf9470316cb216a91ef6ffa865a2c2f25b181e37f20171348576b`,[84],[]],"10e3ba9552ac35206e3f3d467a44f71602f4b1d3404204836f72106155b5fe6d":[`state-feature-secret_store_entries`,`1eefc2ba0eecf91c8fd96442e750b4e555fb97485569f3bd2bf7205c02466cee`,[161],[]],ecb98cd64bfc2fc0828eaaac59c122a4a9381d752dfdc4166d1fe287e9f1cecb:[`fragment-projects`,`9ac5c2cc1d8a72b975287fe40d1f9cf5929671ee033dd68538315e9770df9f36`,[80],[]],"7b5e9bd4ec7f91f71f2fcea1deaa9058d06f907e460e2d1a2a8fa333bf6942c0":[`fragment-worktree_templates`,`a9481ceaf044b2db824f5df1823d0619c7b9e53310b83a32c4399421cc6a7e18`,[130],[]],"85b0f3fbf9815fa0125a5a823eacebc68306ac4864d89047bb2699611b0044c5":[`fragment-user_preferences`,`24c5cd67b1014eb8ca50a492d93a9b9ec5e5a3b936722c35c7b0768a8b1823e2`,[110],[]],"1f164add8aeb9d28f7c779f88fe40dc7a344e14479fe9a017181151330bca6fd":[`fragment-device_pair_setup_completions`,`3400a6259bccdb3546a778b36215284bd14c9613a1ece543e9deaf3539e3b288`,[30],[]],"54a593978142e9fdd957d9aff2368fd3b9d26702968b4ede856df3a933023139":[`fragment-github_publication_requests`,`81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e`,[45],[]],"4c1eb061476b0ecbfc022fb1bd4c927c7c4b3868f40702507c9911ccd3504b2f":[`state-feature-github_publication_requests`,`0375d1a5a88363e5cd216f3addbf170f8be1098ea8626e0e0f95ebb91768588d`,[162],[]],"1f844843f7e4c042331e07eb663873d85bfb1291db181f98c0834a0d01bbf2e2":[`fragment-device_pairing_join_codes`,`4ada0f17fe210baff80cc7da940a58ef4bd27911312469dd15a3473ef1119ad0`,[31],[]],ddfc4231357afb56d903eca77fbfebf817ffafa47d491193e6948b5032ccfefe:[`fragment-skill_workshop_changes`,`993cb9d62f11305ca322f0c76e895a37604132572f2f651c635d0d72eb416b85`,[98],[]],d3bf805006eb83550c1d4a662610e8897cd41ce52de6e370424d3f3ed26e3d80:[`state-feature-skill_workshop_changes`,`01b83680a33b4f2e7d46a70f3e122ebe40044b44ff733891a29a340bdcbba3fb`,[163],[]],"59c7fa24ee5aa93144f936173f6efde68e9d2af33d074d5e208f971d500ac5d3":[`fragment-worker_environment_ssh_fallback_ports`,`18ead5da9eec5f58b75326fdaf9ed55a3d0433facc14dad465add6bd80dff080`,[115],[]],"62bf1862f7ce3c0abcaaf4cc070834c5f402e1696b78d22e7ca7bd23b0fec36d":[`fragment-worker_session_placement_moves`,`8188e7a581a51d08faad38cdf6b07041e2b2e760d17bcfa109df49ec0c83c430`,[118],[]],"8763a734bf095bbda0f3fa1a7d1631a65323a168bf2030ed9dd9621f0103317d":[`state-runtime-0-0`,`1f1007124ef4e9db30a71d38092481cada2fdf2aef59351ee8b475b405bd3dee`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,32,33,34,35,39,40,41,42,43,52,53,55,56,57,58,59,60,61,69,73,74,77,78,79,82,83,85,87,88,89,90,95,96,97,99,100,101,102,103,104,105,106,107,113,114,116,117,119,120,121,122,123,124,125,126,127,128,129,131],[]],"7031b5e534f38b6cdc4a012878201c32a79d5e515e11e83081bfe9935a2f06ad":[`state-runtime-0-1`,`741627bdc2f473f47e87dd3b3ca67742bf56a22066820db2c5ed2952d438cdc1`,[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,32,33,34,35,39,40,41,42,43,52,53,55,56,57,58,59,60,61,69,73,74,77,78,79,82,83,85,87,88,89,90,95,96,97,99,100,101,102,103,104,105,106,107,113,114,116,117,119,120,121,122,123,124,125,126,127,128,129,131],[]],a2808797bda845d26c780b295629ca43bc8e1b38e6fc95e70af677a570f077d7:[`state-runtime-1-0`,`a8c7ee28ea1e28d3b3af47cdf9d8a04deb4af779a63c9c0a5c4414be3bd971f7`,[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,39,40,41,42,43,45,52,53,55,56,57,58,59,60,61,69,73,74,77,78,79,80,82,83,84,85,87,88,89,90,95,96,97,98,99,100,101,102,103,104,105,106,107,110,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],e806fdb2b73d6e4f80d506dfe64875f70b8818e8a6457694a76d40804adc8e39:[`state-runtime-1-1`,`9f6ac7b37f192e6c559b25e3a9cc61899135fcfdb8bd24bda7458a33462fcbb8`,[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,39,40,41,42,43,45,52,53,55,56,57,58,59,60,61,69,73,74,77,78,79,80,82,83,84,85,87,88,89,90,95,96,97,98,99,100,101,102,103,104,105,106,107,110,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131],[]],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`,[42],[]],df93d6687254de2f31ff263b2dafdd67656caa6ac10180f95801bde2dce8f7f0:[`state-table-schema_meta`,`df4efc2e7d50f8bde377f55f5a020ae5ba98cfda938879054cf02d9b4905b793`,[83],[]],cb1f3279e7e3b90290d5ab10856edf532f9c69f278116dd1a8002a4b050f2c1c:[`state-table-state_leases`,`6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc`,[164],[]],a503e610cfb224030ab2473b374631cefa4972377d9d04e07b5d5efb07cee14c:[`state-table-worker_session_tool_operations`,`a146f78ad23ec99bfcb50819c65478b5e94c4a8e4159086ef5073fc76e26cc2d`,[120],[]],"4f45746754bef21a88b4fdfc0932df58b22bf31590a961e4a53957cce7ccd873":[`state-table-worker_turn_tool_authorities`,`fef54ec7cc72bf3869c78b67f31ce96ed842a1ba872f7090e52feff5f547560c`,[123],[]],"8cbef48665eec155650765377478b38fde1c87ef57fadb423438f85f8c91ad66":[`state-indexed-github_publication_requests`,`81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e`,[45],[]],c7c1408a52e8649cf030b636ee3d984e969c5fdb96f6834634e7cb4807e624f2:[`state-indexed-update_runs`,`7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55`,[108],[]],d40fd26bedb861443248d33289dc8d89a1750f3631730dfde2ae285f2c7988ca:[`state-existing-state_leases`,`4289076cebb114b14ac96672941b2be0679f1033e23fe059eedce8dc2b1eea57`,[83,164],[]],"13150d745ef24ab5e6aafe0b365af15d6c5d471a659e5eb2a1c38e359984a47f":[`state-existing-agent_database_leases`,`9fe50268db674b01265b7e77701aedcfffe36567086fc763de8b89f87f4cb67d`,[3,83,164],[]],"789bdcc904f4b35b57f9cb829909f2c9cda541c86179beb6904977146665c0c9":[`state-node-worker-lineage`,`f235501e3f5767c362c7aebce3e678d33cdb45e3b776391980019cdf7cc0f37d`,[63,154],[]],"7c5c2640b3ec45cbac611c07c67f478f0ddc85a4bbfceb9c3576f0d7aa3bd14a":[`state-node-worker-descendants`,`0991532bbc3ca042fc5c1c2026b8aa8d50b24a5bccf26e53675340a4853a665e`,[63,65,154],[]],"72c354791974ce88794c96c16135a89f07b48b9b03542f968beadf05b76aae1e":[`state-retired-commitments`,`19bef9367d336bb367e75740610741cb67deeef86a7f54065758609d67ae8a38`,[165],[]],"2309aff06f4bac77072697764926a0042e6b6069c9504d5bb8c6a0601e9d1314":[`state-retired-commitments-shipped`,`f4d088664f133eea8b1e83fd342d1effaa86d836f8593e02778531468372a303`,[166],[]]}}));function readGeneratedSqliteFingerprint(e){let t=ye(`sha256`).update(e).digest(`hex`);return readSqliteStateFingerprint(t)??readSqliteAgentFingerprint(t)??readSqliteDaemonFingerprint(t)??readSqliteClientFingerprint(t)??readSqliteMemoryFingerprint(t)}function readGeneratedSqliteCatalog(e){let t=ye(`sha256`).update(e).digest(`hex`);return readSqliteStateCatalog(t)??readSqliteAgentCatalog(t)??readSqliteDaemonCatalog(t)??readSqliteClientCatalog(t)??readSqliteMemoryCatalog(t)}var _S=__esmMin((()=>{eS(),iS(),cS(),fS(),gS()}));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,createSqliteTableContract(e.name,e,{schema:`main`,name:e.name,strict:e.strict,wr:e.withoutRowid},e.indexes.map(e=>createSqliteIndexContract(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:groupPluginRecords(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:groupPluginRecords(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=groupPluginRecords(n.filter(e=>e.type===`trigger`),e=>e.tbl_name),g=new Map(n.filter(e=>e.type===`index`).map(e=>[e.name,e.sql])),normalizedRow=e=>({name:e.name,sql:normalizeSchemaSql(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(${quoteSqliteIdentifier(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=groupPluginRecords(u?.get(t.name)??[],e=>e.index_seq);return{name:t.name,sql:normalizeSchemaSql(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(${quoteSqliteIdentifier(t.name)})`).all(),indexes:r.map(t=>({name:t.name,origin:t.origin,partial:t.partial,unique:t.unique,sql:normalizeSchemaSql(g.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(${quoteSqliteIdentifier(t.name)})`).all()})).toSorted((e,t)=>e.name.localeCompare(t.name)),triggers:readTriggers(t.name)}}),views:i.map(e=>({name:e.name,sql:normalizeSchemaSql(e.sql),columns:readColumns(e.name),triggers:readTriggers(e.name)}))}}function readSqliteColumnCatalog(e,t){return e.prepare(`PRAGMA main.table_xinfo(${quoteSqliteIdentifier(t)})`).all()}function compareJson(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}var vS=__esmMin((()=>{wg(),dy(),uy()}));function sha256Hex(e){return xe(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}var yS=__esmMin((()=>{}));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:normalizeSchemaSql(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:normalizeSchemaSql(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:normalizeSchemaSql(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:normalizeSchemaSql(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 bS=__esmMin((()=>{yS(),uy()}));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`${xS[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.`)}var SqliteSchemaMismatchError,xS,SS=__esmMin((()=>{SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}},xS={"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 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),g=m.filter(e=>e.optional).flatMap(e=>e.triggers);for(let e of r.triggers)g.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 normalizeSchemaSql(e)?.replace(/^(CREATE TRIGGER) main\./iu,`$1 `)??null}function getSqliteSchemaContract(e){if(typeof e==`string`){let t=wS.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=CS.get(t);return n||(n={catalog:t,tables:sqliteSchemaContractFromCatalog(t)},CS.set(t,n)),typeof e==`string`&&wS.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=readSqlToken(e.sql,t[0].length);if(!n||normalizeSqlIdentifier(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:normalizeSqlIdentifier(t),type:n.toUpperCase(),dflt_value:r===null?null:normalizeSqlWhitespace(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:normalizeSqlIdentifier(r),table:normalizeSqlIdentifier(i),to:a===null?null:normalizeSqlIdentifier(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=>normalizeSqlWhitespace(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=>normalizeSqlWhitespace(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=>normalizeSqlWhitespace(e)===c)||add(`column-definition-drift`,n))}return JSON.stringify(t.constraints)!==JSON.stringify(n.constraints)&&add(`table-constraint-drift`,e),a}function isCompatibleAdditiveColumnDefinition(e){let t=readSqlToken(e,0),n=t?readSqlToken(e,t.end):null;return!!(n?.keyword&&TS.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}var CS,wS,TS,ES=__esmMin((()=>{_S(),Du(),zx(),vS(),bS(),SS(),uy(),CS=/* @__PURE__ */ new WeakMap,wS=/* @__PURE__ */ new Map,TS=/* @__PURE__ */ new Set([`ANY`,`BLOB`,`INT`,`INTEGER`,`REAL`,`TEXT`])}));function assertTransactionUsable(e){if(isPostgresSqlConnection(e))return;let t=e[kS];if(t)throw t.error}function writeAdmissionLocation(e){let t=MS.get(e);if(t!==void 0)return t;let n=e.location(),r=n===null?null:normalizeDatabasePath(n);return MS.set(e,r),r}function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(normalizeDatabasePath))].map(e=>{let n=jS.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),jS.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&&jS.get(e)===t&&jS.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=jS.size>0?writeAdmissionLocation(e):null,r=n===null?void 0:jS.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(!isSqliteLockError(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 assertSyncTransactionResult(e){if(isPromiseLike(e))throw Error(`SQLite write transactions must be synchronous; Promise returns are not supported.`)}function slowBusyWaitThresholdMs(e){return e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0?DS:Math.min(DS,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||captureSqliteReaderOwner()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;let n=t?sqliteExtendedResultCode(t.error):void 0,r=t?sqlitePrimaryResultCode(t.error):void 0;(e.options?.logger??AS).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:sqliteErrorCode(t.error)}:{},elapsedMs:e.elapsedMs,...t?{failureKind:`lock-contention`}:{},isMainThread:at,pid:process.pid,...n===void 0?{}:{sqliteErrcode:n},...r===void 0?{}:{sqlitePrimaryCode:r},step:e.step,threadId:E,...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;try{n?beginImmediateTransaction(e.db,n):e.db.exec(e.sql);let r=Date.now()-t;return logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:r,options:e.options,step:e.step}),r}catch(r){let i=Date.now()-t;throw isSqliteLockError(r)&&shouldReportSqliteLockFailure(e.db)&&(e.step!==`begin`||e.options?.beginLockFailureReporting!==`suppress`)&&logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,options:e.options,step:e.step},{error:r}),r}}function discardUnsafeConnection(e,t){let n={error:t};e[kS]??=n;try{discardSqliteTransactionState(e,t)}catch(t){throw e[kS]===n&&(n.error=t),t}finally{clearNodeSqliteKyselyCacheForDatabase(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(!e[kS]){if(!n&&e.isOpen&&!e.isTransaction)discardSqliteTransactionState(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 assertSyncTransactionResult(n),assertTransactionUsable(e),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`),n}catch(t){let n=e[kS];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=currentSqliteOperationTiming(),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=currentSqliteOperationTiming(),l=Date.now(),u=c?.hostAdmissionWaitMs??0,d=c?.databaseAdmissionWaitMs??0,f=0,commit=()=>{let t=Date.now(),n=c?.databaseAdmissionWaitMs??0;try{prepareSqliteTransactionCommit(e),execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{f+=Date.now()-t-((c?.databaseAdmissionWaitMs??0)-n)}},p=!1;try{let n=s?t():runSqliteReadOperationSync(e,t);return assertSyncTransactionResult(n),assertTransactionUsable(e),p=!0,a?.withCommit?assertSyncTransactionResult(a.withCommit(commit)):commit(),n}catch(t){throw abortImmediateTransaction(e,t,p),assertTransactionUsable(e),t}finally{try{let t=Date.now()-l,s=(c?.hostAdmissionWaitMs??0)-u,p=(c?.databaseAdmissionWaitMs??0)-d;t<(a?.slowTransactionHoldMs??OS)||(a?.logger??AS).warn(`slow SQLite transaction hold`,{async:!1,callbackKind:`application-transaction`,...transactionDiagnosticLabels(e,a),elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:Math.max(0,t-s-p-f),hostAdmissionWaitMs:s,databaseAdmissionWaitMs:p,commitMs:f},isMainThread:at,mode:n,pid:process.pid,threadId:E,thresholdMs:a?.slowTransactionHoldMs??OS})}catch{}finally{c&&(c.preparedAtMs=Date.now())}}}function runSqliteDeferredTransactionSync(e,t,n){return isPostgresSqlConnection(e)?e.runTransaction(t,n):(assertTransactionUsable(e),withSqlitePostCommitPublications(e,()=>runSqliteTransactionSync(e,t,`deferred`,n)))}function runSqliteReadSnapshotSync(e,t,n){if(isPostgresSqlConnection(e)){if(e.isTransaction){let e=t();return assertSyncTransactionResult(e),e}return e.runTransaction(t,n,!0)}if(assertTransactionUsable(e),!e.isTransaction)return runSqliteDeferredTransactionSync(e,t,n);let r=runSqliteReadOperationSync(e,t);return assertSyncTransactionResult(r),assertTransactionUsable(e),r}function runSqliteImmediateTransactionSync(e,t,n){return isPostgresSqlConnection(e)?e.runTransaction(t,n):(assertTransactionUsable(e),withSqlitePostCommitPublications(e,()=>runSqliteTransactionSync(e,t,`immediate`,n)))}function runSqliteSingleStatementSync(e,t){return isPostgresSqlConnection(e)?e.runTransaction(t):(assertTransactionUsable(e),withSqlitePostCommitPublications(e,()=>{let n=jS.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&jS.has(n))return runSqliteTransactionSync(e,t,`immediate`);let r=runSqliteReadOperationSync(e,t);return assertSyncTransactionResult(r),r}))}var DS,OS,kS,AS,jS,MS,NS=__esmMin((()=>{mu(),Ev(),B(),Du(),gu(),Nx(),kb(),jv(),Pv(),Y(),qv(),DS=1e3,OS=1e3,kS=Symbol.for(`openclaw.sqliteAbortedTransaction`),AS=createSubsystemLogger(`sqlite/transaction`),jS=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map),MS=/* @__PURE__ */ new WeakMap}));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)=>{isPostgresSqlConnection(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))})}}var PS=__esmMin((()=>{kx(),gu(),Y(),NS()}));function resolveDatabasePath(e={}){return e.path===void 0?resolveOpenClawStateSqlitePath(e.env??process.env):normalizeDatabasePath(S.resolve(e.path))}function resolveOpenClawStateSqliteDir(e=process.env){return S.dirname(resolveOpenClawStateSqlitePath(e))}function resolveOpenClawStateSqlitePath(e=process.env){let t=resolveStateDir(e),n=FS.peek(t);if(n!==void 0)return n;let r=normalizeDatabasePath(S.join(t,`state`,`openclaw.sqlite`));return FS.set(t,r),r}function resolveOpenClawStateDirForDatabasePath(e){let t=S.dirname(S.resolve(e));return S.basename(t)===`state`?S.dirname(t):t}function resolveQuarantineStorePath(e){return S.join(resolveOpenClawStateSqliteDir(e),`openclaw-quarantine.sqlite`)}var FS,X=__esmMin((()=>{Up(),sp(),H(),gp(),bp(),qv(),FS=new LruCache(64)}));function isStateDatabaseReadAdmissionInvalidatedError(e){return extractErrorCode(e)===IS}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 findChangedDatabasePaths(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,readDatabasePathIdentitySync(e)):i;let a=r??readDatabasePathIdentitySync(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 readDatabasePathIdentitySync(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=inspectDatabasePathIdentitySync(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}}}},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??inspectDatabasePathIdentitySync(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 a=resolveDatabasePath({path:e}),s=r??readDatabasePathIdentitySync(a),c=n.get(a),l=r&&c?.identity.key===s.key?t.get(s.key):findPhysicalRecord(s);if(c&&c.identity.key!==s.key){if(c.identity.key.startsWith(`path:`)&&!l)publishCreatedIdentity(c,s),l=c;else{let e=i.get(c);e?(e.superseded=!0,e.seal??=seal(c)):invalidate(c),forget(c)}}return l||=resolve(a,s),bindPath(l,a),bindPath(l,r?l.identity.canonicalPath:s.canonicalPath),{identity:s,admission:captureRecord(l,a)}},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){let t=n.get(e),r=t?.admissions.get(e);if(t&&r&&t.identity.key.startsWith(`file:`))return r.assertCurrent(),r;let i=resolveDatabasePath({path:e}),a=resolve(i);return assertOpen(a),captureRecord(a,i)},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),throwSqliteLifecycleErrors(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}}}var IS,StateDatabaseReadAdmissionInvalidatedError,LS=__esmMin((()=>{O(),W(),qv(),X(),Ix(),IS=`STATE_DATABASE_READ_ADMISSION_INVALIDATED`,StateDatabaseReadAdmissionInvalidatedError=class extends Error{constructor(...e){super(...e),this.code=IS}}})),RS,zS,BS,VS,HS,US,WS,Z=__esmMin((()=>{sb(),RS=[`agent_deletion_journal`],zS=/* @__PURE__ */ `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(`.`),BS=[`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`],VS=[...zS,`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`,`skill_workshop_changes`,`worker_environment_ssh_fallback_ports`,`worker_session_placement_moves`],HS=[...BS,`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`],US=5e3,WS=`https://docs.openclaw.ai/reference/database-schemas`}));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}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,``)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}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}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`)}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}function codePointLength(e){let t=e.length;if(!XS.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}function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&ZS!==e._zod?ZS=void 0:(ZS=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,$S);let e=QS;QS=!1;try{let r=n(this);return QS?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),QS||=e,r}catch(n){throw delete this[t],QS||=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[eC]=!0,fn}var Cached,GS,KS,qS,JS,YS,XS,ZS,QS,$S,eC,tC=__esmMin((()=>{oC(),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}},GS=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{},KS=/* @__PURE__*/ cached(()=>{if(aC.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}}),qS=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]),JS={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},YS={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]},XS=/[\uD800-\uDBFF]/,QS=!1,$S={configurable:!0,get(){QS=!0}},eC=`~constantCatch`}));function newError(e){let t=iC;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return iC=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){rC.value=new Internals(r);try{Object.defineProperty(n,"_zod",rC)}finally{rC.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}),_}function config(e){return e&&Object.assign(aC,e),aC}var nC,rC,iC,$ZodAsyncError,$ZodEncodeError,aC,oC=__esmMin((()=>{tC(),rC={value:void 0,enumerable:!1},iC=`captureStackTrace`in Error?Error:null,$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`}},(nC=globalThis).__zod_globalConfig??(nC.__zod_globalConfig={}),aC=globalThis.__zod_globalConfig}));function _getMessage(){let e=this._zod;return e.message??=JSON.stringify(e.def,jsonStringifyReplacer,2),e.message}function _setMessage(e){this._zod.message=e}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}var sC,cC,lC,initializer$1,uC,dC=__esmMin((()=>{oC(),tC(),sC={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},cC={value:void 0,enumerable:!1},lC=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),initializer$1=(e,t)=>{e.name=`$ZodError`,cC.value=t,Object.defineProperty(e,"issues",cC),cC.value=void 0,Object.defineProperty(e,"message",sC);let n=Object.getPrototypeOf(e);lC.has(n)||(lC.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})}}))},uC=/* @__PURE__ */ $constructor(`$ZodError`,initializer$1)}));function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}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}}}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[pC]=!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}var _parse,_parseAsync,_safeParse,_safeParseAsync,fC,pC,validate,validateAsync$1,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,mC=__esmMin((()=>{oC(),tC(),_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 GS(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 GS(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}},_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}},fC=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),pC=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),validate=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==fC)return!0;if(r.definite===!0&&n===void 0)return!1}return validateFallback(e,t,n)}),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)}));function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}function emoji(){return new RegExp(wC,`u`)}function anchor(e){return RegExp(`^${e}$`)}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(`^${NC}T(?:${r})$`)}var hC,gC,_C,vC,yC,bC,xC,SC,uuid,CC,wC,TC,EC,DC,OC,kC,AC,jC,MC,NC,PC,FC,IC,LC,RC,zC,BC,VC=__esmMin((()=>{hC=/^[cC][0-9a-z]{6,}$/,gC=/^[0-9a-z]+$/,_C=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,vC=/^[0-9a-vA-V]{20}$/,yC=/^[A-Za-z0-9]{27}$/,bC=/^[a-zA-Z0-9_-]{21}$/,xC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,SC=/^([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)$/,CC=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,wC=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,TC=/^(?:(?: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])$/,EC=/^(([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}|:))$/,DC=/^((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])$/,OC=/^(([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])$/,kC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,AC=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,jC=/^https?$/,MC=/^\+[1-9]\d{6,14}$/,NC=`(?:(?:\\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])))`,PC=/*@__PURE__*/ anchor(NC),FC=/^[\s\S]{0,}$/,IC=/^-?\d+$/,LC=/^-?\d+(?:\.\d+)?$/,RC=/^(?:true|false)$/i,zC=/^[^A-Z]*$/,BC=/^[^a-z]*$/})),HC,_whenHasLength,UC,WC,GC,KC,qC,JC,YC,XC,ZC,QC,$C,ew,tw,nw,rw,iw,aw=__esmMin((()=>{oC(),VC(),tC(),HC=/*@__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},UC={number:`number`,bigint:`bigint`,object:`date`},WC=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{HC.init(e,t);let n=UC[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:UC[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})}}),GC=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{HC.init(e,t);let n=UC[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:UC[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})}}),KC=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{HC.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})}}),qC=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{HC.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=JS[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})}}),JC=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;HC.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})}}),YC=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;HC.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})}}),XC=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;HC.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})}}),ZC=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;HC.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=()=>{})}),QC=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{ZC.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})}}),$C=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=zC,ZC.init(e,t)}),ew=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=BC,ZC.init(e,t)}),tw=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{HC.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})}}),nw=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{HC.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})}}),rw=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{HC.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})}}),iw=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{HC.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}})})),Doc,ow=__esmMin((()=>{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))}}})),sw,cw=__esmMin((()=>{sw={major:4,minor:6,patch:7}}));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}}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===jC.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}}function stripTabAndNewline(e){return e.replace(hw,``)}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)}function isValidIPv6(e){return kw.test(e)?canParseURL(`http://[${e}]`):!1}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)}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}}function isValidBase64URL(e){if(!Fw.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}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}}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)}}function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}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}}function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Gw,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}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)}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}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}function handleOptionalResult(e,t){return e.value=t.issues.length?void 0:t.value,e}function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),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)}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)}function handleReadonlyResult(e){return e.memo||(e.value=Object.freeze(e.value)),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 lw,toStandardResult,uw,dw,fw,pw,mw,hw,gw,_w,vw,yw,bw,xw,Sw,Cw,ww,Tw,Ew,Dw,Ow,kw,Aw,jw,Mw,Nw,Pw,Fw,Iw,Lw,Rw,zw,Bw,Vw,Hw,Uw,arraySize,Ww,Gw,Kw,qw,Jw,Yw,Xw,Zw,Qw,$w,eT,tT,nT,rT,iT,aT,oT,sT,cT,lT,uT,dT=__esmMin((()=>{aw(),oC(),ow(),VC(),tC(),cw(),lw=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=sw;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},uw=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{lw.init(e,t),e._zod.pattern=t.pattern??FC,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}}),dw=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{ZC.init(e,t),uw.init(e,t)}),fw=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??=SC,dw.init(e,t)}),pw=/*@__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();dw.init(e,t)}),mw=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??=CC,dw.init(e,t)}),hw=/[\t\n\r]/g,gw=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{dw.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})}}}),_w=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),dw.init(e,t)}),vw=/*@__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?bC:nanoidOfLength(t.length),dw.init(e,t)}),yw=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??=hC,dw.init(e,t)}),bw=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=gC,dw.init(e,t)}),xw=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??=_C,dw.init(e,t)}),Sw=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??=vC,dw.init(e,t)}),Cw=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=yC,dw.init(e,t)}),ww=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),dw.init(e,t)}),Tw=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??=PC,dw.init(e,t)}),Ew=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),dw.init(e,t)}),Dw=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=xC,dw.init(e,t)}),Ow=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=TC,dw.init(e,t)}),kw=/^[0-9a-fA-F:.]+$/,Aw=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=EC,dw.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})}}),jw=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=DC,dw.init(e,t)}),Mw=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=OC,dw.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})}}),Nw=/^[0-9a-zA-Z+/]*={0,2}$/,Pw=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??=Nw,dw.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})}}),Fw=/^[A-Za-z0-9_-]*$/,Iw=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=Fw,dw.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})}}),Lw=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??=MC,dw.init(e,t)}),Rw=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{dw.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})}}),zw=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{lw.init(e,t),e._zod.pattern=LC,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}}),Bw=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{qC.init(e,t),zw.init(e,t)}),Vw=/*@__PURE__*/ $constructor(`$ZodBoolean`,(e,t)=>{lw.init(e,t),e._zod.pattern=RC,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}}),Hw=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{lw.init(e,t),e._zod.parse=e=>e}),Uw=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{lw.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)}),arraySize=e=>Array.isArray(e)?e.length:-1,Ww=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{lw.init(e,t);let n=aC.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)}),Gw=[],Kw=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{lw.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=aC.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}}),qw=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{Kw.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=aC.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=!aC.jitless,l=c&&KS.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)}}),Jw=/*@__PURE__*/ $constructor(`$ZodUnion`,(e,t)=>{lw.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)}}),Yw=/*@__PURE__*/ $constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Jw.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)}}),Xw=/*@__PURE__*/ $constructor(`$ZodIntersection`,(e,t)=>{lw.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)}}),Zw=/*@__PURE__*/ $constructor(`$ZodRecord`,(e,t)=>{lw.init(e,t);let n=aC.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`&&LC.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}}),Qw=/*@__PURE__*/ $constructor(`$ZodEnum`,(e,t)=>{lw.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=>qS.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}}),$w=/*@__PURE__*/ $constructor(`$ZodLiteral`,(e,t)=>{lw.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}}),eT=/*@__PURE__*/ $constructor(`$ZodTransform`,(e,t)=>{lw.init(e,t),e._zod.optin=`optional`,aC.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}}),tT=/*@__PURE__*/ $constructor(`$ZodOptional`,(e,t)=>{lw.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)}}),nT=/*@__PURE__*/ $constructor(`$ZodExactOptional`,(e,t)=>{tT.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)}),rT=/*@__PURE__*/ $constructor(`$ZodNullable`,(e,t)=>{lw.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)}),iT=/*@__PURE__*/ $constructor(`$ZodDefault`,(e,t)=>{lw.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)}}),aT=/*@__PURE__*/ $constructor(`$ZodPrefault`,(e,t)=>{lw.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))}),oT=/*@__PURE__*/ $constructor(`$ZodNonOptional`,(e,t)=>{lw.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)}}),sT=/*@__PURE__*/ $constructor(`$ZodCatch`,(e,t)=>{lw.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)}}),cT=/*@__PURE__*/ $constructor(`$ZodPipe`,(e,t)=>{lw.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)}}),lT=/*@__PURE__*/ $constructor(`$ZodReadonly`,(e,t)=>{lw.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)}}),uT=/*@__PURE__*/ $constructor(`$ZodCustom`,(e,t)=>{HC.init(e,t),lw.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 isRef(e){return typeof e==`object`&&!!e}function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}function isRecursive(e,t,n){let r=mT.get(e);if(r!==void 0)return r?_T:hT;if(t.has(e))return _T;t.add(e);let i=hT,check=e=>{if(i!==_T&&e?._zod){let r=isRecursive(e,t,n);r>i&&(i=r)}},shape=(e,r)=>{let i=hT;for(let a of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,a);if(r&&!s.enumerable)continue;let c=s.get?gT:s.value?._zod?isRecursive(s.value,t,n):hT;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):gT),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):gT);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!==gT&&mT.set(e,t===_T),t}function bucketFor(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}function memoizer(){return bT}function isBackEdge(e,t){let n=e[fT]?.backEdges;return n!==void 0&&isRef(t)&&n.has(t)}var $ZodCyclicError,fT,pT,mT,hT,gT,_T,vT,yT,bT,xT=__esmMin((()=>{tC(),$ZodCyclicError=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},fT=`~memo`,pT=[],mT=/*@__PURE__*/ new WeakMap,hT=0,gT=1,_T=2,yT=[],bT={alloc(e,t,n){let r=vT;if(!r)return n;vT=void 0;let i={value:n,issues:null};return r.set(t.value,i),yT.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===hT)return e._zod.parse=t,e._zod.run===wrapped&&(e._zod.run=t),t(s,c);i===_T||r?n=!0:r=!0}let l=s.value;if(!isRef(l))return t(s,c);let u=c[fT];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[fT]=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;vT=d;let p=yT.length,m=t(s,c);vT=void 0;let h=yT.length>p?yT.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?cloneIssues(e.issues):pT),e)):(h&&(h.issues=m.issues.length?cloneIssues(m.issues):pT),m)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})}}}));function en_default(){return{localeError:error()}}var error,ST=__esmMin((()=>{tC(),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 registry(){return new $ZodRegistry}var CT,$ZodRegistry,wT,TT=__esmMin((()=>{$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)}},(CT=globalThis).__zod_globalRegistry??(CT.__zod_globalRegistry=registry()),wT=globalThis.__zod_globalRegistry})),ET=__esmMin((()=>{}));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 WC({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _lte(e,t){return new WC({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _gt(e,t){return new GC({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _gte(e,t){return new GC({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _multipleOf(e,t){return new KC({check:`multiple_of`,...normalizeParams(t),value:e})}// @__NO_SIDE_EFFECTS__
function _maxLength(e,t){return new JC({check:`max_length`,...normalizeParams(t),maximum:e})}// @__NO_SIDE_EFFECTS__
function _minLength(e,t){return new YC({check:`min_length`,...normalizeParams(t),minimum:e})}// @__NO_SIDE_EFFECTS__
function _length(e,t){return new XC({check:`length_equals`,...normalizeParams(t),length:e})}// @__NO_SIDE_EFFECTS__
function _regex(e,t){return new QC({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}// @__NO_SIDE_EFFECTS__
function _lowercase(e){return new $C({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _uppercase(e){return new ew({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _includes(e,t){return new tw({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}// @__NO_SIDE_EFFECTS__
function _startsWith(e,t){return new nw({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}// @__NO_SIDE_EFFECTS__
function _endsWith(e,t){return new rw({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}// @__NO_SIDE_EFFECTS__
function _overwrite(e){return new iw({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 HC({check:`custom`,...normalizeParams(t)});return n._zod.check=e,n}var DT=__esmMin((()=>{aw(),tC()}));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??wT,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}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(!OT.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 OT)if(t in e)return;let n=t.filter(e=>kT.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=kT.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}var OT,kT,createToJSONSchemaMethod,createStandardJSONSchemaMethod,AT=__esmMin((()=>{TT(),tC(),OT=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),kT=[`oneOf`,`anyOf`],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)}}));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)jT[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}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}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`)?LC:IC).source)),m}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 PT.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)}}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`),FT):JSON.parse(s)}var narrowMin,narrowMax,narrowBoth,addDivisor,addPattern,intersectMime,setFormat,minContributor,maxContributor,formatContributor,jT,MT,NT,exactPattern,stringProcessor,numberProcessor,booleanProcessor,neverProcessor,unknownProcessor,enumProcessor,literalProcessor,customProcessor,transformProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,PT,recordProcessor,nullableProcessor,nonoptionalProcessor,FT,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,optionalProcessor,IT=__esmMin((()=>{VC(),dT(),AT(),tC(),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)},jT={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(JS),bigint_format:formatContributor(YS),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)},MT={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},NT=/* @__PURE__ */ new Map([[Nw,kC],[Fw,AC]]),exactPattern=e=>NT.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=MT[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={}},unknownProcessor=(e,t,n,r)=>{},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`]})},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)},PT=/* @__PURE__ */ new WeakMap,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=PT.get(t);n||(n=[],PT.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},FT=Symbol(),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!==FT&&(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!==FT&&(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}})),LT=__esmMin((()=>{oC(),mC(),dC(),dT(),xT(),aw(),cw(),tC(),VC(),ST(),TT(),ow(),ET(),DT(),AT(),IT(),AT()})),RT=__esmMin((()=>{LT()}));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})}})}var zT,initializer,BT,VT=__esmMin((()=>{LT(),tC(),zT=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),initializer=(e,t)=>{uC.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);zT.has(n)||(zT.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}}))},BT=/*@__PURE__*/ $constructor(`ZodError`,initializer,void 0,{Parent:Error})})),HT,UT,WT,GT,KT,qT,JT,YT,XT,ZT,QT,$T,eE=__esmMin((()=>{LT(),VT(),HT=/* @__PURE__ */ _parse(BT),UT=/* @__PURE__ */ _parseAsync(BT),WT=/* @__PURE__ */ _safeParse(BT),GT=/* @__PURE__ */ _safeParseAsync(BT),KT=/* @__PURE__ */ _encode(BT),qT=/* @__PURE__ */ _decode(BT),JT=/* @__PURE__ */ _encodeAsync(BT),YT=/* @__PURE__ */ _decodeAsync(BT),XT=/* @__PURE__ */ _safeEncode(BT),ZT=/* @__PURE__ */ _safeDecode(BT),QT=/* @__PURE__ */ _safeEncodeAsync(BT),$T=/* @__PURE__ */ _safeDecodeAsync(BT)}));function _ensureDefaultLocale(){aC.localeError||config(en_default())}function _ensureDefaultMemoizer(){aC.memoizer||config({memoizer:memoizer()})}function string(e){return/* @__PURE__ */ _string(rE,e)}function number(e){return/* @__PURE__ */ _number(OE,e)}function int(e){return/* @__PURE__ */ _int(kE,e)}function boolean(e){return/* @__PURE__ */ _boolean(AE,e)}function unknown(){return/* @__PURE__ */ _unknown(jE)}function never(e){return/* @__PURE__ */ _never(ME,e)}function array(e,t){return/* @__PURE__ */ _array(NE,e,t)}function object(e,t){let n={type:`object`,shape:e??{},...normalizeParams(t)};return new PE(n)}function strictObject(e,t){return new PE({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new PE({type:`object`,shape:e,catchall:unknown(),...normalizeParams(t)})}function union(e,t){return new FE({type:`union`,options:e,...normalizeParams(t)})}function discriminatedUnion(e,t,n){return new IE({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}function intersection(e,t){return new LE({type:`intersection`,left:e,right:t})}function record(e,t,n){return!t||!t._zod?new RE({type:`record`,keyType:string(),valueType:e,...normalizeParams(t)}):new RE({type:`record`,keyType:e,valueType:t,...normalizeParams(n)})}function _enum(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new zE({type:`enum`,entries:n,...normalizeParams(t)})}function literal$1(e,t){return new BE({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}function transform(e){return new VE({type:`transform`,transform:e})}function optional(e){return new HE({type:`optional`,innerType:e})}function exactOptional(e){return new UE({type:`optional`,innerType:e})}function nullable(e){return new WE({type:`nullable`,innerType:e})}function _default(e,t){return new GE({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}function prefault(e,t){return new KE({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}function nonoptional(e,t){return new qE({type:`nonoptional`,innerType:e,...normalizeParams(t)})}function _catch(e,t){return new JE({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}function pipe(e,t){return new YE({type:`pipe`,in:e,out:t})}function readonly(e){return new XE({type:`readonly`,innerType:e})}function custom(e,t){return/* @__PURE__ */ _custom(ZE,e??(()=>!0),t)}function refine(e,t={}){return/* @__PURE__ */ _refine(ZE,e,t)}function superRefine(e,t){return/* @__PURE__ */ _superRefine(e,t)}var tE,nE,rE,iE,aE,oE,sE,cE,lE,uE,dE,fE,pE,mE,hE,gE,_E,vE,yE,bE,xE,SE,CE,wE,TE,EE,DE,OE,kE,AE,jE,ME,NE,PE,FE,IE,LE,RE,zE,BE,VE,HE,UE,WE,GE,KE,qE,JE,YE,XE,ZE,QE=__esmMin((()=>{LT(),IT(),AT(),ST(),RT(),eE(),tE=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),lw.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 wT.add(t,{description:e}),t},meta(...e){if(e.length===0)return wT.get(this);let t=this.clone();return wT.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 HT(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await UT(this,e,t,{callee:_parseAsync})},safeParse(e,t){return WT(this,e,t)},async safeParseAsync(e,t){return GT(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 KT(this,e,t,{callee:_encode})},decode:function _decode(e,t){return qT(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await JT(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await YT(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return XT(this,e,t)},safeDecode(e,t){return ZT(this,e,t)},async safeEncodeAsync(e,t){return QT(this,e,t)},async safeDecodeAsync(e,t){return $T(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return wT.get(this)?.description},get _def(){return this._zod.def}}),nE=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{uw.init(e,t),tE.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())}})),rE=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{uw.init(e,t),nE.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _email(lE,e))},url(e){return this.check(/* @__PURE__ */ _url(fE,e))},jwt(e){return this.check(/* @__PURE__ */ _jwt(DE,e))},emoji(e){return this.check(/* @__PURE__ */ _emoji(pE,e))},guid(e){return this.check(/* @__PURE__ */ _guid(uE,e))},uuid(e){return this.check(/* @__PURE__ */ _uuid(dE,e))},uuidv4(e){return this.check(/* @__PURE__ */ _uuidv4(dE,e))},uuidv6(e){return this.check(/* @__PURE__ */ _uuidv6(dE,e))},uuidv7(e){return this.check(/* @__PURE__ */ _uuidv7(dE,e))},nanoid(e){return this.check(/* @__PURE__ */ _nanoid(mE,e))},cuid(e){return this.check(/* @__PURE__ */ _cuid(hE,e))},cuid2(e){return this.check(/* @__PURE__ */ _cuid2(gE,e))},ulid(e){return this.check(/* @__PURE__ */ _ulid(_E,e))},base64(e){return this.check(/* @__PURE__ */ _base64(wE,e))},base64url(e){return this.check(/* @__PURE__ */ _base64url(TE,e))},xid(e){return this.check(/* @__PURE__ */ _xid(vE,e))},ksuid(e){return this.check(/* @__PURE__ */ _ksuid(yE,e))},ipv4(e){return this.check(/* @__PURE__ */ _ipv4(bE,e))},ipv6(e){return this.check(/* @__PURE__ */ _ipv6(xE,e))},cidrv4(e){return this.check(/* @__PURE__ */ _cidrv4(SE,e))},cidrv6(e){return this.check(/* @__PURE__ */ _cidrv6(CE,e))},e164(e){return this.check(/* @__PURE__ */ _e164(EE,e))},datetime(e){return this.check(/* @__PURE__ */ _isoDateTime(aE,e))},date(e){return this.check(/* @__PURE__ */ _isoDate(oE,e))},time(e){return this.check(/* @__PURE__ */ _isoTime(sE,e))},duration(e){return this.check(/* @__PURE__ */ _isoDuration(cE,e))}}),iE=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{dw.init(e,t),nE.init(e,t)}),aE=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{ww.init(e,t),iE.init(e,t)}),oE=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{Tw.init(e,t),iE.init(e,t)}),sE=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{Ew.init(e,t),iE.init(e,t)}),cE=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{Dw.init(e,t),iE.init(e,t)}),lE=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{mw.init(e,t),iE.init(e,t)}),uE=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{fw.init(e,t),iE.init(e,t)}),dE=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{pw.init(e,t),iE.init(e,t)}),fE=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{gw.init(e,t),iE.init(e,t)}),pE=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{_w.init(e,t),iE.init(e,t)}),mE=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{vw.init(e,t),iE.init(e,t)}),hE=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{yw.init(e,t),iE.init(e,t)}),gE=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{bw.init(e,t),iE.init(e,t)}),_E=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{xw.init(e,t),iE.init(e,t)}),vE=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{Sw.init(e,t),iE.init(e,t)}),yE=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{Cw.init(e,t),iE.init(e,t)}),bE=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{Ow.init(e,t),iE.init(e,t)}),xE=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{Aw.init(e,t),iE.init(e,t)}),SE=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{jw.init(e,t),iE.init(e,t)}),CE=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{Mw.init(e,t),iE.init(e,t)}),wE=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{Pw.init(e,t),iE.init(e,t)}),TE=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{Iw.init(e,t),iE.init(e,t)}),EE=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{Lw.init(e,t),iE.init(e,t)}),DE=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{Rw.init(e,t),iE.init(e,t)}),OE=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{zw.init(e,t),tE.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}})),kE=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{Bw.init(e,t),OE.init(e,t)}),AE=/*@__PURE__*/ $constructor(`ZodBoolean`,(e,t)=>{Vw.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)}),jE=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{Hw.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unknownProcessor(e,t,n,r)}),ME=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{Uw.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)}),NE=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),Ww.init(e,t),tE.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}}),PE=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),qw.init(e,t),tE.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(HE,this,e[0])},exactPartial(...e){return partial(UE,this,e[0],`exactPartial`)},required(...e){return required(qE,this,e[0])}}),FE=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{Jw.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options}),IE=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{FE.init(e,t),Yw.init(e,t)}),LE=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{Xw.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)}),RE=/*@__PURE__*/ $constructor(`ZodRecord`,(e,t)=>{_ensureDefaultMemoizer(),Zw.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>recordProcessor(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),zE=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{Qw.init(e,t),tE.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 zE({...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 zE({...t,checks:[],...normalizeParams(r),entries:i})}}),BE=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{$w.init(e,t),tE.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]}})}),VE=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),eT.init(e,t),tE.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)}}),HE=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{tT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),UE=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{nT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),WE=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{rT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),GE=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{iT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),KE=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{aT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),qE=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{oT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),JE=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{sT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),YE=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{cT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out}),XE=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{lT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),ZE=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{uT.init(e,t),tE.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)})})),$E=__esmMin((()=>{LT()})),eD=__esmMin((()=>{LT(),QE(),RT(),VT(),eE(),$E(),IT(),TT(),tC(),RT(),QE(),dT(),ST()})),tD=__esmMin((()=>{eD(),eD()}));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}}var nD=__esmMin((()=>{}));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??isPidDefinitelyDead)(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??getFileLockProcessStartTime)(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}var rD=__esmMin((()=>{on()})),iD,aD,oD,sD,cD,lD,uD,dD,fD,pD,mD,hD,gD,_D,vD,yD,bD,xD=__esmMin((()=>{tD(),nD(),iD=string().min(1).max(4096),aD={pid:number().int().positive(),startIdentity:iD.max(128)},oD=strictObject({...aD,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:`)),sD=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}$/)})]),cD=strictObject({kind:literal$1(`native`),unit:iD,scope:iD,placement:discriminatedUnion(`kind`,[strictObject({kind:literal$1(`pending`)}),strictObject({kind:literal$1(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])}),lD=literal$1(`original-cancellation-v1`),uD=strictObject({kind:literal$1(`update`),mutationProtocol:lD}).extend({mutationProtocol:lD.optional(),custody:_enum([`reserved`,`bound`]).optional()}),dD=discriminatedUnion(`kind`,[uD,strictObject({kind:literal$1(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal$1(`foreground`),boot:sD}),cD])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),fD=iD.refine(S.isAbsolute,`Native source path must be absolute`),pD=string().regex(/^[a-f0-9]{64}$/),mD=strictObject({runId:iD,transactionId:iD,claimId:iD,revision:number().int().nonnegative(),recordSha256:pD,serviceKey:fD,configPaths:array(fD).min(1).max(512),lifetimeId:iD}),hD=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:mD}),gD={executor:oD,helper:oD,action:dD},_D=strictObject({version:literal$1(2),executor:oD,helper:oD,action:uD}),vD=strictObject({key:iD,owner:iD,payload:string().min(1),updatedAt:number().int().nonnegative()}),yD=strictObject({version:literal$1(4),executor:oD,helper:oD,action:uD,cancellation:vD}).refine(e=>{let t=safeParseJsonWithSchema(_D,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`)}),bD=strictObject({version:literal$1(2),...gD,mutationOriginal:vD.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(_D,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`}),discriminatedUnion(`version`,[yD,bD,strictObject({version:literal$1(3),...gD,action:strictObject({kind:literal$1(`update`)}),nativeBorrower:hD})]),strictObject({version:literal$1(1),...aD})}));function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=r.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=re(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`]: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 i={platform:n,identity:n===`win32`?t:t?.toLowerCase()},a=sD.safeParse(i);if(!a.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return a.data}}var SD=__esmMin((()=>{xD()}));function readGatewayLockProcessNamespace(){if(AD?.platform===process.platform&&(AD.value!==null||process.platform!==`linux`&&process.platform!==`android`))return AD.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=kD.parse({host:Xe.hostname(),...e,...e.platform===`linux`?{pidNsInode:r.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return AD={platform:process.platform,value:t},t}catch{return AD={platform:process.platform,value:null},null}}function describeGatewayLockHolder(e,t,n){let i=kD.safeParse(e.processNamespace).data,a=e.heartbeatAt;if(t)try{a=r.statSync(t).mtimeMs}catch{}let s=a===void 0?void 0:Date.now()-a,c=`${i?.host??e.host??`unknown host`}${i?.platform===`linux`?`/pid-ns ${i.pidNsInode}`:``}`,l=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?"Stop the holder before retrying; if it has already stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner":"Run this command inside the Gateway container or with a shared PID namespace; if the holder has stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner";return`holder ${e.pid??`unknown`} at ${c}, last renewed ${s===void 0?`at an unknown time`:`${Math.max(0,Math.floor(s/1e3))} s ago`}. ${l}.`}function classifyGatewayLockProcessNamespace(e,t){if(process.platform===`win32`&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-r.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity})}function classifyGatewayOwnerProcessNamespace(e,t={}){let n=kD.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(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=OD.safeParse(t.machineIdentity).data,i=readProcessMachineIdentity();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`}function parseGatewayLockPayload(e){return safeParseJsonWithSchema(jD,e)}var CD,wD,TD,ED,DD,OD,kD,AD,GatewayLockNamespaceError,jD,MD=__esmMin((()=>{tD(),nD(),Ay(),rD(),SD(),xD(),CD=15e3,[wD,TD,ED]=sD.options,DD=string().min(1),OD=string().regex(/^[a-f0-9]{64}$/u),kD=discriminatedUnion(`platform`,[wD.extend({host:DD,platform:literal$1(`linux`),pidNsInode:string().min(1)}),wD.extend({host:DD,platform:literal$1(`darwin`)}),TD.extend({host:DD,identity:TD.shape.identity.optional()}),ED.extend({host:DD})]),GatewayLockNamespaceError=class extends Error{constructor(e,t){super(`cannot verify Gateway ownership from this process; heartbeat age does not prove that the holder stopped. ${describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`}},jD=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:kD.nullable().optional(),machineIdentity:OD.nullable().optional()})})),ND=__esmMin((()=>{yS()}));function hasRestrictivePermissions(e){try{return!(h(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=h(e).isDirectory()?e:S.dirname(e);t=S.join(n,`.openclaw-chmod-probe-${Se()}`),v(t,``,{flag:`wx`,mode:FD})}catch{return!1}try{return a(t,FD),!1}catch(e){return ze(e)&&e.code===`EPERM`}finally{try{g(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&PD.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((h(e).mode&4095)===t)return{applied:!0};try{return a(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,ze(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}var PD,FD,ID=__esmMin((()=>{H(),PD=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]),FD=384}));function ensureOwnerDirectory(e,t){let n=r.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let i=S.toNamespacedPath(n),a=[];for(let t=e;;){let{dev:e,ino:n}=r.lstatSync(t,{bigint:!0});if(a.push({path:t,dev:e,ino:n}),S.toNamespacedPath(t)===i)break;let s=S.dirname(t);if(s===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=s}for(let e of a){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let i=r.lstatSync(e),a=process.getuid?.();if(!i.isDirectory()||a!==void 0&&i.uid!==a)throw Error(`State ownership directory must be a user-owned real directory`);if(process.platform!==`win32`&&(i.mode&4095)!=448&&(applyPrivateModeSync(e,448),r.lstatSync(e).mode&63))throw Error(`State ownership directory permissions are not private`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=r.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&r.rmdirSync(t.path)}catch(e){let t=extractErrorCode(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=resolveIdentityPathViaExistingAncestorSync(e);return stateOwnerIdentity(t,resolveIdentityPathViaExistingAncestorSync(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await resolveIdentityPathViaExistingAncestor(e);return stateOwnerIdentity(t,await resolveIdentityPathViaExistingAncestor(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:S.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?We(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?S.join(Xe.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):resolveGatewayLockDirForCanonicalStateDir(resolveOpenClawStateDirForDatabasePath(e))}var LD=__esmMin((()=>{O(),Up(),X(),sp(),ND(),bp(),ID()}));function createGatewayStateProcessOwnerRetiredError(){return/* @__PURE__ */ Error(RD)}var RD,StateDatabaseAccessError,zD,BD,VD,HD,UD=__esmMin((()=>{B(),RD=`OpenClaw state process owner is no longer current`,StateDatabaseAccessError=class extends Error{constructor(...e){super(...e),this.name=`StateDatabaseAccessError`}},zD=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateOwnerContentionError`),()=>class extends Error{constructor(e,t,n,r){super(`OpenClaw state database is busy at ${e}. ${n?`${n} `:``}Wait for the other OpenClaw process to finish, then retry. If it persists, run \`openclaw gateway status\` and check for other OpenClaw processes using the same state directory. A running Gateway can hold this ownership until it stops; stop it through its service manager or original terminal before retrying.`),this.databasePath=e,this.cause=t,this.holderDetail=n,this.holder=r,this.name=`GatewayStateOwnerContentionError`}}),BD=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseMaintenanceScopeError`),()=>class extends StateDatabaseAccessError{constructor(e){super(`Internal state ownership error at ${e}: this process holds maintenance ownership without an active schema lease or maintenance scope. Retry the command; if it persists, report this error.`),this.name=`StateDatabaseMaintenanceScopeError`}}),VD=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseAdmissionPendingError`),()=>class extends StateDatabaseAccessError{constructor(e,t){super(t),this.databasePath=e}}),HD=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseOfflineMaintenanceError`),()=>class extends StateDatabaseAccessError{constructor(e,t){super(t),this.databasePath=e}})}));async function settlesWithin(e,t){return await raceWithTimeout(e.then(()=>!0),t,()=>!1,{ref:!1})}var WD=__esmMin((()=>{Tp()}));function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}var GD=__esmMin((()=>{Sy(),H(),MD()}));function resolveRuntimeProcessEntrypointUrl(e){return KD.get(e)??resolveRuntimeWorkerUrl(Py[e])}var KD,qD=__esmMin((()=>{wy(),Fy(),lf(),df(),Hy(),KD=/* @__PURE__ */ new Map}));function resolveRuntimeWorkerGenerationUrl(e,t){return isEmbeddedStandaloneModule(e.href)?e:t?.resolve(e)??e}function captureRuntimeWorkerSource(e){let t=JD.getStore()?.generation,n=resolveRuntimeWorkerGenerationUrl(e,t);return n.href===e.href?{moduleUrl:e}:{moduleUrl:n,runtimeGeneration:t}}var JD,YD=__esmMin((()=>{wy(),Tp(),Uf(),B(),JD=resolveGlobalSingleton(Symbol.for(`openclaw.runtimeWorkerGeneration`),()=>new C)})),XD,ZD,QD,$D=__esmMin((()=>{XD=`${process.execArgv.join(` `)} ${process.env.NODE_OPTIONS??``}`,ZD=/--max[-_](?:old[-_]space[-_]size(?:[-_]percentage)?|heap[-_]size)(?:=|\s)/u,QD=/--(?:freeze[-_]flags[-_]after[-_]init|(?:abort|exit)[-_]on[-_]contradictory[-_]flags)(?:=(?:true|1))?(?:\s|$)/u,at&&!process.versions.bun&&ZD.test(XD)&&(QD.test(XD)?process.emitWarning(`V8 startup flags prevent enforcing per-worker heap limits.`):wt(`--max-old-space-size=0 --max-heap-size=0`))}));function createRetainedOperation(e,t={}){let n=Promise.withResolvers(),r=Object.freeze({status:`pending`});return t.observeRejection!==!1&&n.promise.catch(()=>void 0),{operation:{result:n.promise,read:()=>r,service:e},resolve(e){r.status===`pending`&&(r=Object.freeze({status:`fulfilled`,value:e}),n.resolve(e))},reject(e){r.status===`pending`&&(r=Object.freeze({status:`rejected`,error:e}),n.reject(e))}}}function driveRetainedOperation(e,t,n){let r=C.snapshot(),i=!1,serviceInContext=()=>r(service),a=createRetainedOperation(serviceInContext);function service(){if(!(i||a.operation.read().status!==`pending`)){i=!0;try{t(a,serviceInContext)}catch(e){try{a.reject(n?n(e):e)}catch(e){a.reject(e)}}finally{i=!1}}}return e.result.then(serviceInContext,serviceInContext),a.operation.service(),a.operation}function mapRetainedOperation(e,t){return driveRetainedOperation(e,n=>{e.service();let r=e.read();r.status===`fulfilled`?n.resolve(t(r.value)):r.status===`rejected`&&n.reject(r.error)})}var eO=__esmMin((()=>{})),tO=__esmMin((()=>{eO()}));function classifySqliteWorkerExecute(e){if(iO.has(e))return e;let t=e.indexOf(`.`),n=t===-1?e:e.slice(0,t);return iO.has(n)?n:`execute`}function classifyWorkerRequest(e,t){if(typeof e!=`string`)return`execute`;if(aO.has(e))return e;if(e===`auth-profile-rows`)return`auth_profiles`;if(e===`database.domain.execute`||e===`database.domain.publish`){let n=isRecord(t)?t:void 0,r=n&&isRecord(n.command)?n.command:void 0,i=n?.moduleUrl;if(e===`database.domain.publish`&&typeof i==`string`&&typeof r?.type==`string`&&sO.some(e=>i.endsWith(e))){let e=oO.get(r.type);if(e)return e}let a=r?classifyWorkerRequest(r.type):`execute`;return a===`execute`?`domain_execute`:a}for(let[t,n]of cO)if(e.startsWith(t))return n;return classifySqliteWorkerExecute(e)}function normalizeWorkerRequestClass(e){return e!==void 0&&lO.has(e)?e:`other`}var nO,rO,iO,aO,oO,sO,cO,lO,uO=__esmMin((()=>{D(),nO=/* @__PURE__ */ `admit,audit.events.list,audit.writer.process,audit.writer.prune,database.domain.bind,database.domain.close,database.domain.publish,database.prepareWrite,database.walMaintenance,stateLease.acquire,stateLease.release,stateLease.renew,stateLease.verify,worktrees.assertPredicates,worktrees.delete,worktrees.slotCount,worktrees.pendingSlots,worktrees.reservePending,worktrees.releasePending,worktrees.insert,worktrees.update,worktrees.claimRemoval,worktrees.finalizeRemoval,worktrees.abortRemoval,worktrees.findLiveByOwner,worktrees.get,worktrees.sessionBinding,worktrees.findLiveByPath,worktrees.list,worktrees.liveIds,worktrees.provisionedPaths,worktrees.provisionedState,worktrees.provisionedChunk,worktrees.writeProvisionedSnapshot,worktrees.retireMissing,worktrees.deferCleanup,worktrees.admitRunLease,worktrees.releaseRunLease,worktrees.reapRunLeases,worktrees.reserveCapacity,worktrees.recoverPending,worktrees.templates.read,worktrees.templates.has,worktrees.templates.list,worktrees.templates.reserve,worktrees.templates.ready,worktrees.templates.delete,worktrees.templates.retainReader,worktrees.templates.releaseReader,worktrees.templates.hasReaders`.split(`,`),rO=/* @__PURE__ */ `acp.acpSessions.agentDatabaseDeletion.agentDatabaseRegistry.agentDatabases.agentDeletionJournal.agentProvenance.apns.audit.authProfiles.backup.bootstrap.capture.channelIngress.templates.config.conversation.conversationBindings.database.deliveryQueue.deviceAuth.deviceIdentity.devicePairing.diagnostic.doctor.exec-approvals.execApprovals.generatedHtmlProvenance.githubPublication.githubRepository.legacyMcpOAuth.localWorkspace.managedImages.mcpOAuth.mentions.modelCatalog.nativeHookRelay.node.nodeHost.nodeWorker.onboardingRecommendations.operator.operatorApprovals.pairing.placementJournals.placementTools.placementTranscript.placementTurns.pluginBlob.pluginModelCatalogCredentials.plugins.preparedPoolPresence.projects.promotions.repositoryWorkspaces.restartSentinel.sandboxRegistry.secrets.sessionDelivery.sessionGroups.sessionRepositoryWorkspaces.sessionState.sessionUpstream.skillLibrary.skillUploads.skills.stateLease.subagents.telemetry.tts.tui.updateRuns.usageCache.userModelAccounts.userPreferences.userProfiles.webPush.workerEnvironments.workerInference.workerPlacements.workers.workspace.workshop.worktrees`.split(`.`),iO=/* @__PURE__ */ new Set([...nO,...rO]),aO=/* @__PURE__ */ new Set(/* @__PURE__ */ `devicePairing.lookup,devicePairing.list,devicePairing.updateMetadata,devicePairing.updatePresence,devicePairing.verifyToken,devicePairing.ensureToken,session.actor.read,session.actor.acceptInput,session.actor.adoptRun,session.actor.appendToolResult,session.actor.appendTranscriptEvent,session.actor.completeTurn,session.actor.deliveryPending,session.actor.deliverySettled,session.actor.patch,session.entry.read,session.entry.patch.prepare,session.entry.patch.commit,session.entry.replacements.prepare,session.entry.replacements.commit,session.lifecycle.project,session.maintenance.metadata,session.maintenance.prepare,session.maintenance.finalize,session.maintenance.size,session.rowTranscript.backfill,usageCache.writeRollup,usageCache.writeQuarters,usageCache.prune,trajectory.events.append,trajectory.retention.begin,trajectory.retention.delete,session.pendingInputs.read,session.pendingInputs.mutate,session.turn.prepare,session.turn.commit,transcript.prepare,transcript.commit`.split(`,`)),oO=/* @__PURE__ */ new Map([[`preflight`,`transcript-projection.preflight`],[`sweep`,`transcript-projection.sweep`],[`claim`,`transcript-projection.claim`],[`deleteChunk`,`transcript-projection.deleteChunk`],[`appendChunk`,`transcript-projection.appendChunk`],[`finalize`,`transcript-projection.finalize`]]),sO=[`/config/sessions/session-transcript-projection-publication.worker.js`,`/config/sessions/session-transcript-projection-publication.worker.ts`],cO=[[`pluginState.`,`plugin_state`],[`session.history.`,`transcript_read`],[`trajectory.`,`transcripts`],[`session.transcript.`,`transcripts`],[`transcripts.`,`transcripts`],[`session.`,`sessions`],[`cron.`,`cron`]],lO=/* @__PURE__ */ new Set([...aO,...oO.values(),...iO,...cO.map(([,e])=>e),`task`,`open`,`close`,`execute`,`domain_execute`,`auth_profiles`])}));function recordWorkerMessage(e,t,n,r){if(!at)return;let i=dO.get(e);i||(i={},dO.set(e,i));let a=i[t]??={kind:e,direction:t,messages:0,payloadBytes:0,unmeasuredMessages:0};if(a.messages++,n===void 0)a.unmeasuredMessages++;else if(a.payloadBytes+=n,e===`sqlite_request`||e===`sqlite_reply`||e===`authority`){let e=a.payloadBytesByRequestClass??={},t=normalizeWorkerRequestClass(r);e[t]=(e[t]??0)+n}}function messageData(e){return isRecord(e)&&!_e.isProxy(e)?e:void 0}function dataProperty(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function messageBody(e){let t=messageData(e),n=t&&dataProperty(t,`type`);return t&&(n===`post`||n===`message`)?dataProperty(t,`value`):e}function workerMessagePayloadBytes(e){if(!at)return;let t=messageBody(e),n=messageData(t),r=n&&(Object.getOwnPropertyDescriptor(n,`value`)??Object.getOwnPropertyDescriptor(n,`input`));if(r&&!(`value`in r))return;let i=r?r.value:t;if(!_e.isProxy(i)){if(ArrayBuffer.isView(i)||i instanceof ArrayBuffer){let e=n&&dataProperty(n,`type`)===`open`?dataProperty(n,`preparation`):void 0;return i.byteLength+(ArrayBuffer.isView(e)?e.byteLength:0)}if(typeof i==`string`)return i.length*2;if(i==null)return 0}}function messageKind(e,t){let n=messageData(messageBody(e));if(!n)return t;switch(dataProperty(n,`status`)){case`ok`:case`failed`:return`task_reply`;case`request`:return`task_request`;case`notification`:return`task_notification`;case`consumed`:return`task_consumed`;case`memory`:return`memory`;case`ready`:return`lifecycle`}if(typeof dataProperty(n,`taskId`)==`number`)return`task_input`;if(typeof dataProperty(n,`actor`)==`number`)return`sqlite_request`;if(typeof dataProperty(n,`id`)==`number`&&typeof dataProperty(n,`ok`)==`boolean`)return`sqlite_reply`;if(typeof dataProperty(n,`operationId`)==`number`)switch(dataProperty(n,`type`)){case`prepare`:case`reclaim`:case`canonical-validation`:return`sqlite_request`;case`reclaimed`:case`refused`:case`checkpoint`:return`sqlite_reply`;case`admission`:case`admission-request`:case`admission-release`:return`admission`;case`commit-request`:return`authority`}switch(dataProperty(n,`type`)){case`resource-owner`:case`resource-message`:case`resource-closed`:return`resource`;case`cpu`:case`heap`:return`memory`;case`create`:case`created`:case`stop`:case`stopped`:case`close`:case`closed`:case`release`:case`execution-exit`:case`error`:case`messageerror`:case`create-error`:case`stop-error`:case`request-error`:return`lifecycle`}return dataProperty(n,`closeResource`)===!0?`resource`:t}function observeWorkerMessage(e,t,n=`other`,r,i){at&&recordWorkerMessage(messageKind(e,n),t,r===void 0?workerMessagePayloadBytes(e):r??void 0,i)}function canObserveWorkerMessages(e){if(!Object.isExtensible(e))return!1;for(let t of[`postMessage`,`emit`]){let n=e;for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(!e.writable||typeof e.value!=`function`)return!1;break}n=Reflect.getPrototypeOf(n)}if(!n)return!1}return!0}var dO,fO=__esmMin((()=>{D(),B(),uO(),dO=resolveGlobalSingleton(Symbol.for(`openclaw.workerMessageMetrics`),()=>/* @__PURE__ */ new Map)}));function readPostgresBridgeCounters(e){return Array.isArray(e)?e.filter(e=>isRecord(e)&&typeof e.threadId==`number`&&Number.isSafeInteger(e.threadId)&&e.threadId!==E&&e.count instanceof Int32Array&&e.count.length===1&&e.count.buffer instanceof SharedArrayBuffer&&(e.selfRootCount===void 0||e.selfRootCount instanceof Int32Array&&e.selfRootCount.length===1&&e.selfRootCount.buffer instanceof SharedArrayBuffer)):[]}var pO=__esmMin((()=>{D()}));function jsonUtf8BytesOrInfinity(e){try{let t=JSON.stringify(e);return typeof t==`string`?Buffer.byteLength(t,`utf8`):1/0}catch{return 1/0}}function jsonStringByteLengthUpToLimit(e,t){return e.length+2>t||e.length*3+2>t&&Buffer.byteLength(e,`utf8`)+2>t?t+1:jsonUtf8BytesOrInfinity(e)}function boundedJsonUtf8Bytes(e,t){let n=0,r,add=e=>{if(n+=e,n>t)throw Error(`json_byte_limit_exceeded`)},visit=(e,i)=>{if(e===null){add(4);return}switch(typeof e){case`string`:add(jsonStringByteLengthUpToLimit(e,t-n));return;case`number`:add(jsonUtf8BytesOrInfinity(Number.isFinite(e)?e:null));return;case`boolean`:add(e?4:5);return;case`undefined`:case`function`:case`symbol`:i&&add(4);return;case`bigint`:throw Error(`json_byte_length_unsupported`)}let a=e;if((r??=/* @__PURE__ */ new WeakSet).has(a))throw Error(`json_byte_length_circular`);if(typeof a.toJSON==`function`&&!(a instanceof Date))throw Error(`json_byte_length_custom_to_json`);r.add(a);try{if(a instanceof Date){visit(a.toJSON(),i);return}let e=Array.isArray(a);if(add(1),e)for(let e=0;e<a.length;e+=1)e>0&&add(1),visit(a[e],!0);else{let e=!1,r=a;for(let i in r){if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=r[i];a!==void 0&&typeof a!=`function`&&typeof a!=`symbol`&&(e&&add(1),e=!0,add(jsonStringByteLengthUpToLimit(i,t-n)),add(1),visit(a,!1))}}add(1)}finally{r.delete(a)}};try{return visit(e,!1),{bytes:n,complete:!0}}catch{return{bytes:Math.max(n,t+1),complete:!1}}}var mO=__esmMin((()=>{})),hO=__esmMin((()=>{wy(),B(),resolveGlobalSingleton(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=it(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return ct(e,n),new Int32Array(n)})})),gO=__esmMin((()=>{wy(),hO()}));function throwSettledAggregate(e,t){let n=e.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length)throw AggregateError(n,t)}function materializeErrorStack(e){try{for(let t of collectNestedErrorCandidates(e))try{if(!(t instanceof Error))continue;try{t.stack=String(t.stack)}catch{t.stack=`Stack trace unavailable: custom formatter failed`}}catch{}}catch{}}function collectSynchronousErrors(e,t){let n=[];for(let r of e)try{t(r)}catch(e){n.push(e)}return n}var _O=__esmMin((()=>{O()}));function runOutsideAsyncWorkScope(e){return vO.getStore()===void 0?yO.getStore()===void 0?e():yO.exit(e):runWithAsyncStore(vO,void 0,()=>(yO.enterWith(void 0),e()))}var vO,yO,bO,xO,SO=__esmMin((()=>{_O(),Qd(),nd(),It(),B(),WD(),vO=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScope`),()=>new C),yO=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new C),bO=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}}),xO=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=vO.getStore();if(t===this)return e();let n=yO.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return runWithAsyncStore(vO,this,()=>(yO.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new bO;if(this.pending.size>0)return this.enter(e);let t=createDeferredCore();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 bO);let t=createDeferredCore();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(materializeErrorStack(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),materializeErrorStack(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`}},resolveGlobalSingleton(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}})}));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})}var CO=__esmMin((()=>{}));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}}}var wO=__esmMin((()=>{})),TO,EO=__esmMin((()=>{B(),resolveGlobalSingleton(Symbol.for(`openclaw.pluginInventoryRetiredError`),()=>class extends Error{constructor(){super(`Plugin inventory has retired; begin a new plugin operation.`),this.name=`PluginInventoryRetiredError`}}),resolveGlobalSingleton(Symbol.for(`openclaw.pluginSourceRecoveryUnavailableError`),()=>class extends Error{constructor(e){super(`Captured plugin source is missing; its previous code cannot be recovered.`,{cause:e}),this.name=`PluginSourceRecoveryUnavailableError`}}),TO=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceDrainTimeoutError`),()=>class extends Error{constructor(e,t,n,r){super(e,n),this.settled=t,this.forcedRetirement=r,this.name=`PluginInstanceDrainTimeoutError`}})}));function releasePluginCacheInstance(e,t){let n=kO.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&&kO.delete(e)}function getPluginCacheRetainers(e){let t=OO.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:createDeferredCore()},OO.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},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 DO.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return ad()?.cacheScope?.cache}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function retirePluginCache(e,t,n){let r=getPluginCacheRetainers(e);if(r.retirement)return r.retirement;let i=createDeferredCore();return r.retirement=i.promise,r.controller.abort(),materializeErrorStack(r.controller.signal.reason),runOutsideAsyncWorkScope(async()=>{r.references.size&&await r.settled.promise;let i=new xO;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=createDeferredCore();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 TO?[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}var DO,OO,kO,AO=__esmMin((()=>{_O(),SO(),It(),B(),CO(),wO(),EO(),od(),DO=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),OO=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),kO=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap)})),jO=__esmMin((()=>{}));function parsePackageName(e){let t=JSON.parse(e);return typeof t.name==`string`?t.name:null}async function readPackageName(e,t){t?.throwIfAborted();let n=getPluginCache().sdk.packageNames,r=S.join(S.resolve(e),`package.json`);if(n.has(r))return n.get(r)??null;try{let e=parsePackageName(await Ye.readFile(r,{encoding:`utf-8`,signal:t}));return t?.throwIfAborted(),n.set(r,e),e}catch{return t?.throwIfAborted(),n.set(r,null),null}}function readPackageNameSync(e){let t=getPluginCache().sdk.packageNames,n=S.join(S.resolve(e),`package.json`);if(t.has(n))return t.get(n)??null;try{let e=parsePackageName(y.readFileSync(n,`utf-8`));return t.set(n,e),e}catch{return t.set(n,null),null}}async function findPackageRoot(e,t){for(let n of iterAncestorDirs(e))if(await readPackageName(n,t)===`openclaw`)return n;return null}function findPackageRootSync(e){for(let t of iterAncestorDirs(e))if(readPackageNameSync(t)===`openclaw`)return t;return null}function*iterAncestorDirs(e){let t=S.resolve(e);for(let e=0;e<12&&(yield t,S.basename(t)!==`node_modules`);e+=1){let e=S.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,n=S.resolve(e),r=t.get(n);if(r)return[...r];let i=n,a=[];try{let e=y.realpathSync(i);e!==i&&a.push(S.dirname(e))}catch{}a.push(S.dirname(i));let s=i.split(S.sep),c=s.lastIndexOf(`.bin`);if(c>0&&s[c-1]===`node_modules`){let e=S.basename(i),t=s.slice(0,c).join(S.sep);a.push(S.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}}}async function resolveOpenClawPackageRoot(e){e.signal?.throwIfAborted();let t=preparePackageRootSearch(e,!0);if(t.first!==void 0)return t.first;for(let n of t.candidates){let r=await findPackageRoot(n,e.signal);if(r)return t.complete(r)}return t.complete(null)}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(S.dirname(Ie(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=>S.resolve(e)))]}var MO=__esmMin((()=>{AO(),jO(),lf()}));function assertProfile(e){if(!e)throw new ProfileFailure(`invalid-profile`)}function createInspectorProfileCapture(e,t){let n=new e.Session;return n.connect(),{setup:()=>t.setup(n),start:()=>t.start(n),stop:()=>t.stop(n),close:async()=>{let e=!1;try{await t.disable(n),e=!0}catch{}if(n.disconnect(),!e)throw new ProfileFailure(`cleanup-failed`)}}}function hasProfilerConflict(){let e=parseNodeOptionsEnvVar(process.env.NODE_OPTIONS);return e===null||!!process.env.NODE_V8_COVERAGE||!!(process.versions.bun&&(process.env.BUN_INSPECT||process.env.BUN_INSPECT_CONNECT_TO))||[...process.execArgv,...e??[]].some(e=>/^--(?:inspect|cpu-prof|heap-prof|prof|perf-|.*coverage)/.test(e.replaceAll(`_`,`-`)))}function codeUrl(e,t){if(/^node:[a-zA-Z0-9_./-]+$/.test(e))return e;if(e.length>2048||/[?#]/.test(e))return;let n=e;if(e.startsWith(`file:`))try{n=Ie(e)}catch{return}if(!S.isAbsolute(n))return;let r=t?S.relative(t,n).split(S.sep).join(`/`):``,i=(t&&!r.startsWith(`..`)?`/${r}`:S.normalize(n).split(S.sep).join(`/`)).match(/.*\/node_modules\/((?:@[a-zA-Z0-9_-][a-zA-Z0-9._-]*\/)?[a-zA-Z0-9_-][a-zA-Z0-9._-]*)\//)?.[1];return i?`node_modules/${i}`:/^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?(?:src|dist)\/[a-zA-Z0-9_@./+-]+\.[cm]?js$/.test(r)||/^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?src\/[a-zA-Z0-9_@./+-]+\.ts$/.test(r)?`openclaw:${r}`:void 0}function sanitizeDiagnosticProfileFrame(e,t){assertProfile(!!e&&typeof e.functionName==`string`&&typeof e.url==`string`&&typeof e.scriptId==`string`&&/^-?\d{1,32}$/.test(e.scriptId)&&Number.isSafeInteger(e.lineNumber)&&Number.isSafeInteger(e.columnNumber));let n=codeUrl(e.url,t),r=e.url===``&&NO.has(e.functionName),i=n?.startsWith(`node_modules/`)?`[dep:${n.slice(13)}]`:e.scriptId===`0`&&e.url===``&&e.lineNumber<0&&!r?`[native]`:void 0,a=r||n!==void 0&&e.functionName.length<=256&&/^(?:(?:(?:get|set) )?[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*)?$/.test(e.functionName);return{redacted:!a&&!i,callFrame:{functionName:i??(a?e.functionName:`[redacted]`),scriptId:e.scriptId,url:n??``,lineNumber:e.lineNumber,columnNumber:e.columnNumber}}}async function captureDiagnosticProfile(e){let unavailable=(e,t=!1)=>({status:`unavailable`,reason:e,cleanupFailed:t});if(PO)return unavailable(`busy`);PO=!0;let t,n=!1,r=!1,i,a=!1,s,c,l,u=0,d=0,f=null,assertActive=()=>{if(e.signal?.aborted||!e.hasAuthority())throw new ProfileFailure(`cancelled`)};try{assertActive();let i=await import(`node:inspector/promises`).catch(()=>{throw new ProfileFailure(`unsupported`)}),a=!at&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(a())throw new ProfileFailure(`tracing-active`)};if(f=await resolveOpenClawPackageRoot({moduleUrl:import.meta.url}),assertActive(),i.url()||hasProfilerConflict())throw new ProfileFailure(`conflict`);assertTracingInactive(),t=e.create(i),await t.setup?.(),assertActive(),assertTracingInactive(),c={...process.memoryUsage(),heapSpaces:xt.getHeapSpaceStatistics()};let p=performance.now();n=!0;let m=t.start();d=performance.now()-p,await m,e.durationMs>0&&await ft(e.durationMs,void 0,{signal:e.signal}),assertActive(),r=!0;let h=await t.stop();if(!h)throw new ProfileFailure(`capture-failed`);({profile:s}=h),u=performance.now()-p,l={...process.memoryUsage(),heapSpaces:xt.getHeapSpaceStatistics()}}catch(t){i=t instanceof ProfileFailure?t.reason:e.signal?.aborted?`cancelled`:t instanceof Error&&t.message.startsWith(`Inspector error -32601:`)?`unsupported`:`capture-failed`}finally{if(t){if(n&&!r)try{await t.stop()}catch{a=!0}try{await t.close()}catch{a=!0}}}if(i||a)return PO=!1,unavailable(i??`cleanup-failed`,a);try{assertActive();let t=await e.sanitize(s,f,{durationMs:u,startBlockedMs:d,before:c,after:l});return assertActive(),{status:`complete`,result:t}}catch(e){return unavailable(e instanceof ProfileFailure?e.reason:`invalid-profile`)}finally{PO=!1}}var NO,PO,ProfileFailure,FO=__esmMin((()=>{Cy(),MO(),NO=/* @__PURE__ */ new Set([`(root)`,`(program)`,`(idle)`,`(garbage collector)`,`(GC)`,`(PARSER)`,`(COMPILER)`,`(BYTECODE_COMPILER)`,`(V8 API)`,`(EXTERNAL)`,`(LOGGING)`,`(IDLE_EXTERNAL)`,`(IDLE)`,`(JS)`,`(deopt)`]),PO=!1,ProfileFailure=class extends Error{constructor(e){super(e),this.reason=e}}}));function sanitizeDiagnosticCpuProfile(e,t,{startBlockedMs:n}){if(assertProfile(e.samples!==void 0&&e.timeDeltas!==void 0),e.nodes.length>RO||e.samples.length>zO)throw new ProfileFailure(`profile-too-large`);let r=0,i=e.nodes.map(e=>{let{callFrame:n,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);return r+=Number(i||e.deoptReason!==void 0),{id:e.id,callFrame:n,...e.children===void 0?{}:{children:e.children},...e.hitCount===void 0?{}:{hitCount:e.hitCount},...e.positionTicks===void 0?{}:{positionTicks:e.positionTicks},...e.deoptReason===void 0?{}:{deoptReason:`[redacted]`}}}),a={requestedDurationMs:IO,actualDurationMs:(e.endTime-e.startTime)/1e3,startBlockedMs:n,samplingIntervalMicros:LO,sampleLossCount:null,redactedNodeCount:r,profile:{nodes:i,startTime:e.startTime,endTime:e.endTime,samples:e.samples,timeDeltas:e.timeDeltas}};if(boundedJsonUtf8Bytes(a,1048576).complete)return a;let s=new Map(i.map(e=>[e.id,e])),c=/* @__PURE__ */ new Map;for(let e of i)for(let t of e.children??[])c.set(t,e.id);let l=/* @__PURE__ */ new Map;for(let t of e.samples)l.set(t,(l.get(t)??0)+1);let u=/* @__PURE__ */ new Map;for(let[e,t]of l){let n=[],r=s.get(e);for(;r&&n.length<BO;)n.push(r.callFrame),r=s.get(c.get(r.id));let i=0;if(!n.some(e=>e.url.startsWith(`openclaw:`))){let e=0;for(;r&&!r.callFrame.url.startsWith(`openclaw:`);)e++,r=s.get(c.get(r.id));r&&(n.push(r.callFrame),i=e)}let a=JSON.stringify({stack:n,elidedFrameCount:i}),l=u.get(a);l?l.sampleCount+=t:u.set(a,{stack:n,elidedFrameCount:i,sampleCount:t})}let d=[],f={...a,profile:void 0,truncated:!0,originalNodeCount:i.length,sampleCount:e.samples.length,omittedSampleCount:e.samples.length,summary:d},p=Buffer.byteLength(JSON.stringify(f));for(let e of[...u.values()].toSorted((e,t)=>t.sampleCount-e.sampleCount)){let t=Buffer.byteLength(JSON.stringify(e))+Number(f.summary.length>0);if(f.summary.length===VO||p+t>1048576)break;f.summary.push(e),f.omittedSampleCount-=e.sampleCount,p+=t}return f}var IO,LO,RO,zO,BO,VO,HO=__esmMin((()=>{mO(),gO(),FO(),IO=5e3,LO=1e4,RO=16384,zO=65536,BO=8,VO=128}));async function sortAllocationSummaries(e){let compare=(e,t)=>t.totalBytes-e.totalBytes||t.selfBytes-e.selfBytes,t=[],n=[];for(let r of e)n.push(r),n.length===2048&&(t.push(n.toSorted(compare)),n=[],await dt());for(n.length&&t.push(n.toSorted(compare));t.length>1;){let e=[];for(let n=0;n<t.length;n+=2){let r=t[n],i=t[n+1];if(!i){e.push(r);continue}let a=[],s=0,c=0;for(;s<r.length||c<i.length;)a.push(c===i.length||s<r.length&&compare(r[s],i[c])<=0?r[s++]:i[c++]),a.length%2048==0&&await dt();e.push(a)}t=e}return t[0]??[]}async function sanitizeDiagnosticHeapProfile(e,t,n){let r=e.samples,i=/* @__PURE__ */ new Map,a=[{source:e.head}],s=0,c=0;for(let{source:e,parent:n}of a){++c%1024==0&&await dt();let{callFrame:r,redacted:l}=sanitizeDiagnosticProfileFrame(e.callFrame,t);s+=Number(l);let u={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]},d={node:u,parent:n,totalBytes:u.selfSize,count:0,frameId:0};i.set(u.id,d),n?.node.children.push(u);for(let t of e.children)a.push({source:t,parent:d}),++c%1024==0&&await dt()}a.length=0;let l=[],u=0,d=0;for(let e of r){++c%1024==0&&await dt();let t=i.get(e.nodeId);t?(t.count++,l.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})):(u++,d+=e.size)}let f=[...i.values()];i.clear();for(let e=f.length-1;e>=0;e--){++c%1024==0&&await dt();let t=f[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let p={...n,redactedNodeCount:s,unattributedSampleCount:u,unattributedSampleBytes:d},m={...p,truncated:u>0,profile:{head:f[0].node,samples:l}};if(boundedJsonUtf8Bytes(m,1048576).complete)return m;let h=/* @__PURE__ */ new Map,g=/* @__PURE__ */ new Map,v=[];for(let e of f){++c%1024==0&&await dt();let t=JSON.stringify(e.node.callFrame),n=h.get(t);n===void 0&&(n=h.size,h.set(t,n)),e.frameId=n;let{totalBytes:r,count:i}=e;if(r===0)continue;let a=e.node.selfSize,s=[e.node.callFrame];v.length=0,v.push(n);for(let t=e.parent;t&&s.length<8;t=t.parent)s.push(t.node.callFrame),v.push(t.frameId);let l=v.join(`,`),u=g.get(l);u?(u.selfBytes+=a,u.totalBytes+=r,u.count+=i):g.set(l,{stack:s,selfBytes:a,totalBytes:r,count:i})}h.clear(),f.length=0;let y={...p,truncated:!0,summary:[]},b=Buffer.byteLength(JSON.stringify(y));for(let e of await sortAllocationSummaries(g.values())){++c%1024==0&&await dt();let t=Buffer.byteLength(JSON.stringify(e))+Number(y.summary.length>0);if(b+t>1048576)break;y.summary.push(e),b+=t}return y}var UO=__esmMin((()=>{mO(),gO(),FO()})),WO=/* @__PURE__ */ __exportAll({captureWorkerGcProfiles:()=>captureWorkerGcProfiles,reportWorkerGcStorm:()=>reportWorkerGcStorm,writeWorkerGcProfiles:()=>writeWorkerGcProfiles});async function reportWorkerGcStorm(e,t,n){let{profiles:r,...i}=e,a={...i,workerThreadId:t,workerSlot:n},s=createSubsystemLogger(`agents/code-mode`);if(r)try{let e=await writeWorkerGcProfiles(r);s.warn(`Code Mode worker GC storm`,{...a,profileFiles:e})}catch{s.warn(`Code Mode worker GC storm`,{...a,captureStatus:`unavailable`,captureReason:`profile-write-failed`})}else s.warn(`Code Mode worker GC storm`,a);if(i.captureStatus===`requested`){let{getEnabledCategories:e}=await import(`node:trace_events`);if(e())s.warn(`Code Mode worker GC storm`,{...a,captureStatus:`unavailable`,captureReason:`tracing-active`});else return i}}function captureWorkerGcProfiles(){return captureDiagnosticProfile({hasAuthority:()=>!0,durationMs:GO,workerTracingInactive:!0,create:e=>createInspectorProfileCapture(e,{setup:async e=>{await e.post(`HeapProfiler.enable`),await e.post(`Profiler.enable`),await e.post(`Profiler.setSamplingInterval`,{interval:1e4})},start:async e=>{await e.post(`HeapProfiler.startSampling`,{samplingInterval:KO,includeObjectsCollectedByMajorGC:!0,includeObjectsCollectedByMinorGC:!0}),await e.post(`Profiler.start`)},stop:async e=>{let[t,n]=await Promise.all([e.post(`HeapProfiler.stopSampling`),e.post(`Profiler.stop`)]);return{profile:{heap:t.profile,cpu:n.profile}}},disable:e=>Promise.all([e.post(`HeapProfiler.disable`),e.post(`Profiler.disable`)])}),sanitize:async({heap:e,cpu:t},n,r)=>({heap:JSON.stringify(await sanitizeDiagnosticHeapProfile(e,n,{durationMs:r.durationMs,requestedDurationMs:GO,effectiveDurationMs:GO,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:KO,includeObjectsCollectedByMajorGC:!0,includeObjectsCollectedByMinorGC:!0,heapUsedBefore:r.before.heapUsed,heapUsedAfter:r.after.heapUsed,heapSpacesBefore:r.before.heapSpaces,heapSpacesAfter:r.after.heapSpaces,rssBefore:r.before.rss,rssAfter:r.after.rss})),cpu:JSON.stringify(sanitizeDiagnosticCpuProfile(t,n,r))})})}function writeWorkerGcProfiles(e){let t=YO.then(async()=>{let t=S.join(resolveStateDir(),`diagnostics`);await T.mkdir(t,{recursive:!0,mode:448});let n=(await T.readdir(t)).filter(e=>JO.test(e)).toSorted();for(let e of n.slice(0,Math.max(0,n.length-qO+2)))await T.unlink(S.join(t,e));let r=`code-mode-gc-${Date.now()}-${Se()}`,i=[];for(let[n,a]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${r}.${n}profile.json`;await Tt({filePath:S.join(t,e),content:a,mode:384,dirMode:448}),i.push(e)}return i});return YO=t.catch(()=>{}),t}var GO,KO,qO,JO,YO,XO=__esmMin((()=>{vp(),HO(),UO(),FO(),Ev(),GO=5e3,KO=262144,qO=20,JO=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/,YO=Promise.resolve()}));function createCpuTrackedWorker(e,t,n){let r=runWithMainThreadTask(`worker:${workerScriptName(e,t?.eval)}`,()=>new rt(e,t));return trackNativeWorkerForCpu(r,e,t?.eval),Object.assign(QO.workers.get(r),{internalMessages:!0,requestClass:n}),r}function trackNativeWorkerForCpu(e,t,n=!1){trackWorker(e);let r=QO.workers.get(e),i=workerScriptName(t,n);if(r.script!==i&&(r.script===`bridge.worker.js`&&Atomics.sub(QO.postgresBridgeCount,0,1),i===`bridge.worker.js`&&Atomics.add(QO.postgresBridgeCount,0,1),r.script=i),r.script===`code-mode-node.worker.js`&&r.workerSlot===void 0){let e=new Set([...QO.workers.values()].map(e=>e.workerSlot));for(let t=1;t<=64;t++)if(!e.has(t)){r.workerSlot=t;break}}r.lifecycleMessages=r.script===`openclaw-state-lease-heartbeat.worker.js`||r.script===`gateway-state-owner-heartbeat.worker.js`}function recordPostgresPoolSelfRoot(){return Atomics.compareExchange(QO.postgresPoolSelfRootCount,0,0,1)===0}function publishPostgresBridgeCounters(){for(let e of QO.postgresBridgeObservers)e()}function receivePostgresBridgeCounters(e,t){let n=readPostgresBridgeCounters(t),r=e.postgresBridgeCounters;n.length===(r?.length??0)&&n.every((e,t)=>e.threadId===r?.[t]?.threadId)||(e.postgresBridgeCounters=n,publishPostgresBridgeCounters())}function forgetWorker(e){let t=QO.workers.get(e);if(!t)return;let n=countWorkerStart(t),r=t.retirementReason??`exit`;n.retired.set(r,(n.retired.get(r)??0)+1),t.script===`bridge.worker.js`&&Atomics.sub(QO.postgresBridgeCount,0,1),t.memoryFlush?.resolve(),t.memoryPort?.close(),QO.workers.delete(e),QO.revision++,QO.cpuSources=void 0,t.postgresBridgeCounters&&publishPostgresBridgeCounters()}function countWorkerStart(e){let t=QO.lifecycle.get(e.script);return t||(t={started:0,retired:/* @__PURE__ */ new Map},QO.lifecycle.set(e.script,t)),e.started||(e.started=!0,t.started++),t}function trackWorker(e){if(QO.workers.has(e))return;if(at&&e instanceof rt&&recordWorkerMessage(`lifecycle`,`to_worker`),at&&e instanceof rt&&canObserveWorkerMessages(e)){let t=Object.getPrototypeOf(e)===rt.prototype,r=!t||Object.hasOwn(e,`postMessage`)?e.postMessage:void 0;e.postMessage=function(e,t){let i=n.internalMessages?workerMessagePayloadBytes(e):void 0;(r??rt.prototype.postMessage).call(this,e,t),n.lifecycleMessages?recordWorkerMessage(`lifecycle`,`to_worker`,i):n.internalMessages?observeWorkerMessage(e,`to_worker`,`other`,i??null,n.requestClass?.()):recordWorkerMessage(`other`,`to_worker`)};let i=!t||Object.hasOwn(e,`emit`)?e.emit:void 0;e.emit=function(e,...t){if(e===`error`&&n.script===`code-mode-node.worker.js`){let e=t[0];n.retirementReason??=isRecord(e)&&e.code===`ERR_CODE_MODE_GC_THRASH`?`gc-thrash`:`crash`}return e===`message`&&(n.lifecycleMessages?recordWorkerMessage(`lifecycle`,`from_worker`,workerMessagePayloadBytes(t[0])):n.internalMessages?observeWorkerMessage(t[0],`from_worker`,`other`,void 0,n.requestClass?.()):recordWorkerMessage(`other`,`from_worker`)),(i??rt.prototype.emit).call(this,e,...t)}}let t=!1,finishCpuUsage=e=>(t=!1,e),failCpuUsage=()=>finishCpuUsage(void 0),n={script:`other`,cpuUsage(){if(t)return Promise.resolve(void 0);t=!0;try{return e.cpuUsage().then(finishCpuUsage,failCpuUsage)}catch{return Promise.resolve(failCpuUsage())}}};QO.workers.set(e,n),queueMicrotask(()=>countWorkerStart(n)),QO.revision++,QO.cpuSources=void 0,e.once(`exit`,()=>forgetWorker(e))}function recordWorkerGc(e,t){let n=e.taskMetrics;if(n)for(let e of t){if(!e||![`scavenge`,`mark_sweep_compact`,`incremental`,`weak_processing`].includes(e.kind)||!Number.isFinite(e.durationMs)||e.durationMs<0)continue;let t=n.gc.find(t=>t.kind===e.kind);t||(t={kind:e.kind,count:0,durationMs:0,reclaimedBytes:0},n.gc.push(t)),t.count++,t.durationMs+=e.durationMs,Number.isFinite(e.reclaimedBytes)&&e.reclaimedBytes>=0&&(t.reclaimedBytes+=e.reclaimedBytes),n.heapUsedHighWaterBytes=Math.max(n.heapUsedHighWaterBytes,Number.isFinite(e.heapUsedBeforeBytes)?e.heapUsedBeforeBytes:0)}QO.gcObserver?.(t,e.script,e.workerSlot)}function receiveWorkerMemoryPort(e,t){if(isRecord(t)&&(t.status===`ok`||t.status===`failed`)&&t.diagnostics===!0){let t=QO.workers.get(e);return t?.taskMetrics&&t.taskMetrics.tasksCompleted++,!1}if(!isRecord(t)||t.status!==`memory`||!(t.port instanceof nt))return!1;let n=t.port,r=QO.workers.get(e);if(!r||r.memoryPort||e.threadId===-1)return n.close(),!0;receivePostgresBridgeCounters(r,t.postgresBridgeCounters),r.memoryPort=n,r.memoryPending=!0;let close=()=>{r.memoryPort=void 0,r.memoryPending=!1,r.memoryUnavailable=!0,r.memoryFlush?.resolve(),n.close()};return n.on(`message`,t=>{if(`postgresBridgeCounters`in t)receivePostgresBridgeCounters(r,t.postgresBridgeCounters),recordWorkerMessage(`memory`,`from_worker`);else if(`flushed`in t)recordWorkerMessage(`memory`,`from_worker`,8),r.taskMetrics&&(r.taskMetrics.heapUsedHighWaterBytes=Math.max(r.taskMetrics.heapUsedHighWaterBytes,t.heapUsed)),r.memoryFlush?.resolve();else if(`retireWorkerId`in t)recordWorkerMessage(`memory`,`from_worker`),ZO.publish(t.retireWorkerId);else if(`gcStorm`in t){recordWorkerMessage(`memory`,`from_worker`);let i=e.threadId,a=r.workerSlot;Promise.resolve().then(()=>(XO(),WO)).then(async({reportWorkerGcStorm:e})=>{let s=await e(t.gcStorm,i,a);s&&r.memoryPort===n&&n.postMessage({captureGcProfile:s})})}else recordWorkerMessage(`memory`,`from_worker`,(`heapUsed`in t?32+(t.heapSizeLimitBytes===void 0?0:8):0)+(`heapUsed`in t&&t.oldGenerationAfterGcBytes!==void 0?8:0)+(`heapUsed`in t?(t.heapSpaces?.length??0)*8:0)+(`heapUsed`in t?t.retainedData?.reduce((e,t)=>e+16+(t.stringBytes===void 0?0:8)+(t.objects===void 0?0:8)+(t.generations===void 0?0:8)+(t.providers===void 0?0:8)+(t.accounts===void 0?0:8)+(t.truncated===void 0?0:1),0)??0:0)+(t.gc?.length??0)*8),t.gc&&recordWorkerGc(r,t.gc),`heapUsed`in t&&(r.taskMetrics&&(r.taskMetrics.heapUsedHighWaterBytes=Math.max(r.taskMetrics.heapUsedHighWaterBytes,t.heapUsed)),delete t.gc,r.heap={value:t,sampledAt:performance.now()},r.memoryPending=!1,r.memoryUnavailable=!1)}),n.once(`close`,close),n.once(`messageerror`,close),n.unref(),QO.gcObserver&&(n.postMessage({gc:!0}),recordWorkerMessage(`memory`,`to_worker`,1)),!0}var ZO,QO,$O=__esmMin((()=>{$D(),D(),B(),ef(),hf(),fO(),pO(),ZO=$e(`openclaw.code-mode.gc-storm`),QO=resolveGlobalSingleton(Symbol.for(`openclaw.workerCpuSources`),()=>(process.on(`worker`,trackWorker),{gcObserver:void 0,postgresBridgeCount:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),postgresPoolSelfRootCount:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),postgresBridgeObservers:/* @__PURE__ */ new Set,revision:0,cpuSources:void 0,nextPoolId:0,poolIds:/* @__PURE__ */ new WeakMap,workers:/* @__PURE__ */ new Map,lifecycle:/* @__PURE__ */ new Map,taskMetrics:/* @__PURE__ */ new Map}))}));function captureLock(e){let t=r.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,t){let n={};for(let t of e)n[t.lockPath]=captureLock(t);let i=Object.keys(n)[0];if(!i)throw Error(`Gateway state ownership requires a held lock`);let a=r.statSync(i,{bigint:!0}),{moduleUrl:s,runtimeGeneration:c}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(`gatewayStateOwnerHeartbeat`));return runInDetachedAsyncContext(()=>{let l=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(l,0,BigInt(ek()));let{port1:u,port2:d}=new tt,f=createCpuTrackedWorker(s,{workerData:{clock:`epoch`,locks:n,intervalMs:CD,failureMs:6e4,lastBeat:l.buffer,events:d},transferList:[d],execArgv:resolveRuntimeWorkerThreadExecArgv(s)}),p=createDeferredCore();f.on(`message`,e=>{e===`closed`&&p.resolve()}),f.unref();let m=0,h=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of h.values())t.reject(e);h.clear(),u.unref()};u.on(`message`,e=>{if(recordWorkerMessage(`lifecycle`,`from_worker`),e===`parent-lost`)requestCliParentTermination();else if(e&&typeof e==`object`&&e.type===`lost`)t(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=h.get(e.id);h.delete(e.id),h.size===0&&u.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),u.unref(),f.on(`error`,e=>{let n=/* @__PURE__ */ Error(`${coerceErrorMessage(e)}; restart Gateway.`);rejectPending(n),t(n)}),f.once(`exit`,()=>{p.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let g,remainingUntilInspection=()=>{let e=Atomics.load(l,0),t=ek()-Number(e);return t<0?0:6e4-t},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 t=ek(),s=new Date(t);for(let t of e)try{let c=n[t.lockPath];if(c===void 0)throw Error(`owner acquisition bytes were not registered`);let l=await r.promises.open(t.lockPath,`r+`);try{let n=await l.stat({bigint:!0}),u=await r.promises.lstat(t.lockPath,{bigint:!0}),d=Buffer.alloc(Buffer.byteLength(c)+1),{bytesRead:f}=await l.read(d,0,d.length,0),p=await r.promises.lstat(t.lockPath,{bigint:!0});if(g||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,u,c,d.subarray(0,f).toString(`utf8`))||!p.isFile()||p.dev!==n.dev||p.ino!==n.ino||t.lockPath===i&&(n.dev!==a.dev||n.ino!==a.ino)){if(t.lockPath!==i)continue;throw Error(`owner lock was removed or replaced`)}await l.utimes(s,s)}finally{await l.close()}}catch(e){if(t.lockPath!==i&&w(e,`ENOENT`))continue;throw e}!g&&e.size>0&&Atomics.store(l,0,BigInt(t))},v,y,watch=()=>{let e=remainingUntilInspection();e>0?(v=setTimeout(watch,e),v.unref()):y??=renewAsync().then(()=>{y=void 0,g||watch()},e=>{y=void 0,g||t(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${i}: ${coerceErrorMessage(e)}; restart the Gateway.`))})};watch();let stop=()=>(g||=(clearTimeout(v),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),u.close(),f.ref(),f.postMessage(`stop`,[]),(async()=>(await settlesWithin(p.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${gy}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),f.terminate()))()),Promise.all([g,y]).then(()=>void 0));c?.retain(f,async()=>async()=>{await stop()});let assertActive=()=>{if(g||f.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},b=new Set(Object.keys(n));return{worker:f,paths:b,register(e){let t=captureLock(e);n[e.lockPath]=t,f.postMessage([e.lockPath,t],[]),b.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++m;return new Promise((n,r)=>{h.set(t,{resolve:n,reject:r}),u.ref();try{f.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){h.delete(t),h.size===0&&u.unref(),r(toErrorObject(e,`Gateway state ownership verification failed`))}})},stop}})}var ek,tk=__esmMin((()=>{O(),Sy(),_y(),It(),Qd(),WD(),H(),MD(),GD(),qD(),YD(),Hy(),$O(),fO(),ek=Date.now.bind(Date)}));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)}function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,rk.clear(),e.heartbeat?.stop(),nk.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)}var nk,rk,ik,ak=__esmMin((()=>{Ev(),B(),nk=createSubsystemLogger(`gateway/state`),rk=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),ik=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map)}));function isValueToken(e){return!e||e===`--`?!1:!e.startsWith(`-`)||/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){let n=e[t];return n?sk.has(n)||n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`)?1:ck.has(n)?isValueToken(e[t+1])?2:1:0:0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,sk,ck,`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}var sk,ck,lk=__esmMin((()=>{sk=/* @__PURE__ */ new Set([`--dev`,`--no-color`]),ck=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`])}));function isForegroundGatewayRunArgv(e){let t=getCommandPositionalsWithRootOptions(e,{commandPath:[`gateway`],booleanFlags:[...dk,`--task-supervisor`],valueFlags:[...uk,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}var uk,dk,fk=__esmMin((()=>{lk(),uk=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),dk=/* @__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`])})),pk=__esmMin((()=>{}));function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}var mk=__esmMin((()=>{sp(),ND(),bp()})),hk=__esmMin((()=>{lk()}));function normalizeProcArg(e){return normalizeLowercaseStringOrEmpty(e.replaceAll(`\\`,`/`))}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(r.readFileSync(S.join(n,`package.json`),`utf8`))}catch(e){let r=S.dirname(n);if(t&&extractErrorCode(e)===`ENOENT`){if(r===n)return{kind:`absent`};if(S.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!isRecord(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:isRecord(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,r.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){let e=re(`/usr/sbin/lsof`,[`-a`,`-p`,[...t].join(`,`),`-d`,`cwd`,`-F0pn`],{encoding:`utf8`,timeout:5e3,maxBuffer:4194304,env:resolveDiagnosticProcessEnv()});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`)&&S.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:resolveRuntimeScriptPosition(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&&S.isAbsolute(t.cwd)&&isBunRuntime(e[0]??``)&&!/[\\/]/u.test(i)&&!S.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 i=[...gk,...t.additionalEntrypoints??[]],a=e;if(!S.isAbsolute(e)){let n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!S.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};a=S.resolve(n,e)}let s,c;try{if(s=r.realpathSync(a),t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(s))return{kind:`openclaw`,artifactPath:s};let n=t.requirePackageIdentity||t.inspectPackage?r.statSync(s):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};c=n?.isDirectory()??!1}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}let l=normalizeProcArg(s);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let u=c?void 0:i.find(e=>l.endsWith(`/${e}`));if(!u&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};let d=u?s.slice(0,-u.length):c?s:S.dirname(s),f=readProcessPackageIdentity(d,t.inspectPackage&&!t.requirePackageIdentity||!u&&!c);return f.kind===`unknown`?{kind:`unclassified`,cause:`package-identity`,reason:f.reason}:f.kind===`package`&&f.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:S.resolve(d),entrypoint:s}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){let{command:n,owner:i,pid:a,port:s}=t;if(!t.requirePackageIdentity&&n===`gateway`&&i?.pid===a&&i?.state===`live`&&(s===void 0||i.port===s))return{kind:`openclaw`};let c=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(c))return!n||c===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};let l=classifyEntrypoint(e,t);if(n)return l.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(l.entryIndex)],1)[0]??``)!==n?{kind:`other`}:l;if(l.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return l.kind===`openclaw`?l:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let u=t.serviceMarker;if(a!==void 0&&process.platform===`linux`&&(isNodeRuntime(c)||isBunRuntime(c)||c===`tsx`))try{u=r.readFileSync(`/proc/${a}/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 (${extractErrorCode(e)??`unavailable`})`}}return!t.requirePackageIdentity&&u===`openclaw`?{kind:`openclaw`}:l}var gk,_k=__esmMin((()=>{O(),D(),Lt(),Vy(),mk(),hk(),Yt(),gk=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`]}));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){let n=isRecord(e)?e:null;if(!n)return!1;let r=classifyGatewayLockProcessNamespace(n,t);if(r===`unknown`)throw new GatewayLockNamespaceError(n,t);return comparableStateOwnerStaleReason(n,r)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:t,ownerPath:n,assertMaintenance:i}=e,a=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`,s;try{s=r.readFileSync(n,`utf8`)}catch(e){if(extractErrorCode(e)===`ENOENT`)return;throw new StateDatabaseAccessError(a,{cause:e})}let c=vk.getStore();if(c?.deadOwner?.path===n&&c.deadOwner.raw===s)return;let l=parseGatewayLockPayload(s);if(!l)throw new VD(t,a);if(!Number.isSafeInteger(l.pid)||l.pid<=0)throw new StateDatabaseAccessError(a);let u=classifyGatewayLockProcessNamespace(l,n),d=comparableStateOwnerStaleReason(l,u);if(d){c&&d===`owner-process-exited`&&(c.deadOwner={path:n,raw:s});return}if(u===`same`&&l.pid===process.pid&&!at)return;if(u===`same`&&!isPidAlive(l.pid))throw new VD(t,a);let f=l.role??`gateway`;if(f===`gateway`||f===`agent-embedded`)return;if(u===`same`&&l.pid===process.pid){i();return}let p=`OpenClaw state at ${t} is undergoing offline maintenance by ${f} process ${l.pid} (ownerKind=${l.stateOwnerKind??`process`}); retry when it finishes. For update progress, run \`openclaw update status --json\`.`;throw l.stateOwnerKind===`schema`&&l.role===`sqlite-maintenance`?new VD(t,p):new HD(t,p)}function defaultPayload(e){let t=resolveOpenClawStateDirForDatabasePath(e),n=getFileLockProcessStartTime(process.pid),r=getCliParentPid(),i=r===void 0?null:getFileLockProcessStartTime(r);return{pid:process.pid,ownerId:Se(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:S.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?readProcessMachineIdentity():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 i;try{i=r.readFileSync(t,`utf8`)}catch(e){if(extractErrorCode(e)===`ENOENT`)return;throw e}let a=parseGatewayLockPayload(i);if(!(isGatewayStateOwnerDefinitelyStale(a,t)||a?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&classifyOpenClawArgv(process.argv,{command:`gateway`}).kind===`openclaw`))throw new VD(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,i=0,a){let s=performance.now()+i,c=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,c,n),ensureOwnerDirectory(S.dirname(t),a);let l={holder:null},stale=({payload:e})=>(l.holder=jD.safeParse(e).data??null,isGatewayStateOwnerDefinitelyStale(l.holder,t));if(i>0)try{let n=l.holder=parseGatewayLockPayload(r.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&isPidAlive(n.pid)))throw new zD(e)}catch(e){if(extractErrorCode(e)!==`ENOENT`)throw e}for(let r=!1;;)try{return Et(t,{lockPath:t,retry:i>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(s-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>(assertGatewayRestorationPriority(e,c,n),n),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){let i=extractErrorCode(n);if(i===`ENOENT`&&!r){r=!0,ensureOwnerDirectory(S.dirname(t),a);continue}if(i===`file_lock_timeout`||i===`file_lock_stale`){let{holder:r}=l,i=describeGatewayLockHolder(r??{},t,r&&isPidAlive(r.pid)?`live`:`unknown`);throw new zD(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}var vk,yk=__esmMin((()=>{O(),D(),Sy(),fk(),on(),X(),Ay(),pk(),MD(),_k(),LD(),UD(),rD(),vk=new C}));function getStateDatabaseSchemaLease(e){let t=bk.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(),rk.clear();let t=new Map(bk.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,rk.clear()};try{let n=bk.run(t,e);return isPromiseLike(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||ik.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){rk.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&ik.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,ik.delete(n.key))),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){rk.clear();let n=resolveStateOwnerIdentity(e),r=ik.get(n.key),i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new zD(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 zD)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof VD)throw e}throw t}let l=r?.projectionPath??S.join(resolveGatewayLockDir(resolveOpenClawStateDirForDatabasePath(resolveIdentityPathViaExistingAncestorSync(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 runWithSqliteCleanup({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},ik.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 runWithSqliteCleanup(d,`state schema ownership verification`,()=>{throw e})}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(ik.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=S.resolve(e);if(rk.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=ik.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.`);rk.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=ik.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||ik.get(e.key)!==r)throw createGatewayStateProcessOwnerRetiredError()}}:void 0,prepareAccess:async r=>{let i=t??ik.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&&ik.get(e.key)!==i)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseReadAtOwnerPath(n,t,e)};let s=i.heartbeat,c=i.locks.values().next().value,l=i.getProjection?.();if(!s||!c)throw createGatewayStateProcessOwnerRetiredError();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),s.assertActive(),ik.get(e.key)!==i||i.heartbeat!==s)throw createGatewayStateProcessOwnerRetiredError();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(c)||i.getProjection?.()!==l)throw createGatewayStateProcessOwnerRetiredError()};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 rk.set(S.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 BD(e);r.assertDatabaseAccess(e)},r=ik.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})}var bk,xk=__esmMin((()=>{mu(),Up(),B(),LS(),Z(),X(),sp(),MD(),LD(),UD(),tk(),ak(),yk(),bp(),Nx(),W(),bk=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new C)}));function readSqliteWorkerMonotonicNs(){return Sk.bigint()}var Sk,Ck,wk,Tk=__esmMin((()=>{B(),bb(),Sk=process.hrtime,Ck=33554432,resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerOpenRefusedError`),()=>class extends Error{constructor(e){super(`SQLite worker admission was refused before agent open`,{cause:e}),this.originalError=e,this.name=`SqliteWorkerOpenRefusedError`}}),wk=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerAdmissionTimeoutError`),()=>class extends Error{constructor(){super(`SQLite host admission timed out; retry after transaction rollback`),this.code=`admission-timeout`,this.name=`SqliteWorkerAdmissionTimeoutError`}})}));function withSqliteDatabaseAdmissionWait(e,t){let n={wait:e,parent:Ak.getStore(),active:!0},close=()=>{n.active=!1},r=!1;try{let e=Ak.run(n,t);return gt(e)&&(r=!0,e.then(close,close)),e}finally{r||close()}}function readSqliteDatabaseAdmissionDeadline(){let e;for(let t=Ak.getStore();t;t=t.parent){if(!t.active)continue;let n=t.wait.deadlineAtMs;n!==void 0&&(e=Math.min(e??1/0,n))}return e}function assertSqliteDatabaseAdmissionWaitActive(){try{for(let e=Ak.getStore();e;e=e.parent)e.active&&e.wait.assertActive?.()}catch(e){throw wrapSqliteWorkerError(`SQLite admission facts exchange cancelled by its caller`,`unavailable`,e)}}function getSqliteDatabaseAdmissionUpstream(){return jk.connection}function exchangeDatabaseAdmissions(e,t,n,r){let{port1:i,port2:a}=new tt,s=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),c=currentSqliteOperationTiming(),l=Date.now(),u=readSqliteDatabaseAdmissionDeadline(),d=u===void 0?kk:Math.max(0,u-Date.now()),f=readSqliteWorkerMonotonicNs()+BigInt(Math.ceil(d))*1000000n,remaining=()=>{assertSqliteDatabaseAdmissionWaitActive();let e=Number(f-readSqliteWorkerMonotonicNs())/1e6;if(e<=0)throw new SqliteDatabaseAdmissionTimeoutError;return e};try{for(remaining(),e.postMessage({kind:`sqlite-database-admissions`,admissions:t,location:n,create:r,deadlineAtMs:u,port:a,decision:s.buffer},[a]);Atomics.load(s,0)===Ek;){let e=remaining();Atomics.wait(s,0,Ek,Ak.getStore()?Math.min(100,e):e)}remaining();let c=Atomics.load(s,0);if(c===4&&n&&r===!0)throw new VD(n,`OpenClaw state at ${n} is undergoing schema admission; retry when it finishes.`);if(c!==Dk)throw new SqliteWorkerError(`SQLite admission facts exchange failed`,`unavailable`);let l=readSqliteDatabaseAdmissions(st(i)?.message);if(!l)throw new SqliteWorkerError(`SQLite admission facts reply is unavailable`,`unavailable`);return l}finally{Atomics.compareExchange(s,0,Ek,Ok),c&&(c.databaseAdmissionWaitMs+=Date.now()-l),i.close(),a.close()}}var Ek,Dk,Ok,kk,SqliteDatabaseAdmissionTimeoutError,Ak,jk,Mk=__esmMin((()=>{B(),UD(),ey(),Pv(),Tk(),Ek=0,Dk=1,Ok=2,kk=6e5,SqliteDatabaseAdmissionTimeoutError=class extends SqliteWorkerError{constructor(){super(`SQLite admission facts exchange timed out; the host did not reply`,`unavailable`)}},Ak=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionWait`),()=>new C),jk=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionUpstream`),()=>({}))}));function isNativeCommitReceipt(e){return isRecord(e)&&e.version===1&&typeof e.sequence==`number`&&Number.isSafeInteger(e.sequence)&&e.sequence>=1&&Object.hasOwn(e,`facts`)}function resolveSqliteWorkerFinishSettlement(e,t,n){return e??(n===`not-entered`&&!t?{kind:`completed`}:void 0)}var Nk,Pk=__esmMin((()=>{D(),B(),jv(),Tk(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerNativeCommitReceipts`),()=>/* @__PURE__ */ new WeakMap),Nk=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerOperationAdmission`),()=>new C)}));function readAgentDatabaseExecutionAuthority(e){return Atomics.load(e.logical,0)===Fk&&Atomics.load(e.native,0)===Fk&&Atomics.load(e.logical,0)===Fk&&Atomics.load(e.native,0)===Fk}var Fk,Ik=__esmMin((()=>{Fk=0}));function active(e){return(e&Lk)!==0&&!(e&24)}function readSqliteWorkerRequestCustody(e){return Atomics.load(e.slot,0)===1&&active(Atomics.load(e.request,0))}var Lk,Rk,zk,Bk,Vk,SqliteWorkerSlotCustody,SqliteWorkerRequestCustody,Hk=__esmMin((()=>{Tk(),Lk=1,Rk=2,zk=4,Bk=8,Vk=16,SqliteWorkerSlotCustody=class{constructor(){this.state=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),Atomics.store(this.state,0,1)}createRequest(){return new SqliteWorkerRequestCustody(this.state)}retire(){Atomics.store(this.state,0,0)}},SqliteWorkerRequestCustody=class{constructor(e){this.descriptor={slot:e,request:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))}}activate(){if(Atomics.compareExchange(this.descriptor.request,0,0,Lk)!==0)throw new SqliteWorkerError(`SQLite worker request custody was already used`,`closed`)}assertCurrent(){if(!readSqliteWorkerRequestCustody(this.descriptor))throw new SqliteWorkerError(`SQLite worker job is no longer current`,`closed`)}get dispatched(){return(Atomics.load(this.descriptor.request,0)&Rk)!==0}get postAttempted(){return(Atomics.load(this.descriptor.request,0)&zk)!==0}accept(){this.assertCurrent(),Atomics.or(this.descriptor.request,0,Rk)}post(){Atomics.or(this.descriptor.request,0,zk)}cancel(){this.dispatched||Atomics.or(this.descriptor.request,0,Bk)}retire(){Atomics.or(this.descriptor.request,0,Vk)}}}));function assertSqliteWorkerDatabaseIdentity(e){let t=e.databaseIdentity;if(t)try{assertExistingDatabaseIdentity(t.databasePath,t.key,t.birthtime)}catch(t){let n=new SqliteWorkerError(`SQLite cleanup database no longer matches its borrowed native owner`,`closed`);throw n.cause=t,e.refusal=n,n}}function assertRequestCustody(e){if(e.requestCustody&&!readSqliteWorkerRequestCustody(e.requestCustody)){let t=new SqliteWorkerError(`SQLite worker request custody is revoked`,`closed`);throw e.refusal=t,t}if(e.executionAuthority&&!readAgentDatabaseExecutionAuthority(e.executionAuthority)){let t=new SqliteWorkerError(`SQLite execution authority is revoked`,`closed`);throw e.refusal=t,t}assertSqliteWorkerDatabaseIdentity(e)}function requestSqliteWorkerOperationAdmission(e,t=[]){let n=Nk.getStore();if(!n?.active)throw new SqliteWorkerError(`SQLite operation requires its retained admission`,`unavailable`);if(n.owner.sourceReservations)throw new SqliteWorkerError(`SQLite source reservations prohibit host admission`,`closed`);assertRequestCustody(n.owner);let r=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),i=Date.now(),a=e.deadlineMs===void 0?void 0:readSqliteWorkerMonotonicNs()+BigInt(e.deadlineMs)*1000000n;for(n.port.postMessage({...e,decision:r.buffer,ports:t.filter(e=>e instanceof nt)},t);Atomics.load(r,0)===Uk;){let e=a===void 0?void 0:Number(a-readSqliteWorkerMonotonicNs())/1e6;e!==void 0&&e<=0?Atomics.compareExchange(r,0,Uk,Gk):Atomics.wait(r,0,Uk,e)}let s=currentSqliteOperationTiming();s&&(s.hostAdmissionWaitMs+=Date.now()-i);let c=Atomics.load(r,0);if(c===4&&e.stage===`prepare`&&isRecord(e.facts)&&e.facts.kind===`schema-maintenance`&&typeof e.facts.databasePath==`string`){let t=e.facts.databasePath;throw new VD(t,`OpenClaw state at ${t} is undergoing schema admission; retry when it finishes.`)}if(c!==Wk){let e=c===Gk?new wk:new SqliteWorkerError(`SQLite transaction admission was refused`,`closed`);throw n.owner.refusal=e,e}assertRequestCustody(n.owner),delete n.owner.refusal}var Uk,Wk,Gk,Kk=__esmMin((()=>{D(),Ik(),UD(),Pv(),Tk(),Mk(),qv(),Pk(),Hk(),Uk=0,Wk=1,Gk=3}));function requestSqliteWorkerSchemaMaintenance(e){return Nk.getStore()?(requestSqliteWorkerOperationAdmission({stage:`prepare`,facts:{kind:`schema-maintenance`,databasePath:e}}),!0):!1}var qk=__esmMin((()=>{J(),Tk(),Mk(),Pk(),Kk()}));function bindSqliteWorkerDatabaseAdmissionCursor(e,t,n){eA.set(e,{cursor:t,reset:n})}function readSqliteWorkerExecutionAuthority(e){return $k.get(e)}function createOperationAdmission(e,t,n,r){let{port1:i,port2:a}=new tt,s=C.snapshot(),c=/* @__PURE__ */ new Set,l=createSqliteDatabaseAdmissionCursor(),u=[],d=!1,f=!1,p,m=[],h=!1,g,v,y=0,b,x,ee=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),recordFailure=(e,t)=>{(!g||g.source===`domain`&&t!==`domain`)&&(g={error:e,source:t})},refuse=(e,t,n)=>{Atomics.compareExchange(e,0,Jk,Xk)===Jk?(recordFailure(t,n),Atomics.notify(e,0)):Atomics.load(e,0)===Yk&&u.push(t)},invalidProtocol=(e,t=`outcome-unknown`)=>recordFailure(new SqliteWorkerError(`SQLite worker ${e} is invalid`,t),`protocol`),installCommitted=e=>{if(e.sequence<=y)return;y=e.sequence;let t={facts:e.facts};v=t,h=!0;try{s(()=>{for(let e of m)e(t)})}catch(e){recordFailure(Object.assign(new SqliteWorkerError(`SQLite committed facts publication failed`,`outcome-unknown`),{cause:e}),`protocol`)}finally{h=!1}},receive=(t,i=!1)=>{let a=isRecord(t)?t:void 0;if(recordWorkerMessage(a?.kind===`sqlite-database-admissions`?`admission`:`authority`,`from_worker`,typeof a?.payloadBytes==`number`?a.payloadBytes:void 0,te.requestClass),f=!0,isRecord(t)&&t.kind===`sqlite-database-admissions`){if(!(t.port instanceof nt)||!(t.decision instanceof SharedArrayBuffer)||t.decision.byteLength!==Int32Array.BYTES_PER_ELEMENT||t.location!==void 0&&typeof t.location!=`string`||t.deadlineAtMs!==void 0&&(typeof t.deadlineAtMs!=`number`||!Number.isFinite(t.deadlineAtMs))||t.create!==void 0&&typeof t.create!=`boolean`&&t.create!==`admitted`){recordFailure(new SqliteWorkerError(`SQLite admission facts request is invalid`,`unavailable`),`protocol`);return}let{location:e,port:r}=t,a=new Int32Array(t.decision);c.add(a);let u=t.deadlineAtMs,assertWaiting=()=>{if(d)throw new SqliteWorkerError(`SQLite worker admission is closed`,`closed`);if(Atomics.load(a,0)!==Jk||u!==void 0&&Date.now()>=u)throw new SqliteWorkerError(`SQLite admission requester stopped waiting`,`unavailable`)};(async()=>{let d,assertCreationCurrent;try{assertWaiting();let c=t.create===`admitted`?n:void 0;if(t.create===`admitted`&&!c)throw new SqliteWorkerError(`SQLite creation relay is not admitted`,`closed`);let f=readSqliteDatabaseAdmissions(t.admissions);if(!f)throw new SqliteWorkerError(`SQLite admission facts request is invalid`,`unavailable`);installSqliteDatabaseAdmissions(f);let p=e,m=!1;if(e&&t.create&&!Wb(e)){p=resolveIdentityPathViaExistingAncestorSync(e);let n=p,r=x,i=r?.assertCreate?.bind(r);t.create===`admitted`?m=!0:r&&i&&(r.coldOpenPath&&resolveIdentityPathViaExistingAncestorSync(r.coldOpenPath)===n&&(d=r.coldOpenPath),assertCreationCurrent=()=>s(()=>{r.assertRequest?.(),r.assertAccess()}),assertCreationCurrent(),s(()=>i(n)),d=void 0,m=!0)}m&&c?.();let h=getSqliteDatabaseAdmissionUpstream();if(h){if(h.closed)throw new SqliteWorkerError(`SQLite admission upstream is closed`,`closed`);installSqliteDatabaseAdmissions(withSqliteDatabaseAdmissionWait({deadlineAtMs:u,assertActive:assertWaiting},()=>exchangeDatabaseAdmissions(h.port,f,p,m?`admitted`:void 0)))}else if(p)try{assertWaiting(),m&&Wb(p,{create:!0});let e=x?.databaseIdentity,t=e&&(p===e.databasePath||p===x?.databasePath)?e:void 0;i?Gb(p,t):await Ub({location:p,expectedIdentity:t,assertCurrent:assertWaiting})}catch(e){if(!isRecord(e)||e.code!==`ENOENT`)throw e}assertWaiting(),assertCreationCurrent?.(),m&&c?.();let g=e===void 0&&f.length===0?void 0:{location:e,admissions:f},v=captureSqliteDatabaseAdmissions(eA.get(te)?.cursor??l,g);r.postMessage(v,[]),recordWorkerMessage(`admission`,`to_worker`),Atomics.compareExchange(a,0,Jk,Yk)}catch(e){let t=eA.get(te);t?t.cursor=t.reset():l=createSqliteDatabaseAdmissionCursor(),e instanceof VD&&e.databasePath===d?Atomics.compareExchange(a,0,Jk,4):(recordFailure(e,`protocol`),Atomics.compareExchange(a,0,Jk,Xk))}finally{c.delete(a),r.close(),Atomics.notify(a,0)}})();return}if(isRecord(t)&&t.kind===`native-commit`){let e=t.committed;if(!isNativeCommitReceipt(e)){invalidProtocol(`commit receipt`);return}installCommitted(e);return}if(isRecord(t)&&t.kind===`native-settlement`){let e=t.settlement;if(!isRecord(e)||e.kind!==`completed`&&e.kind!==`unknown`||e.committed!==void 0&&!isNativeCommitReceipt(e.committed)){invalidProtocol(`native settlement`);return}e.committed!==void 0&&installCommitted(e.committed),b={kind:e.kind,...v?{committed:v}:{}};return}if(!isRecord(t)||!(t.decision instanceof SharedArrayBuffer)||t.decision.byteLength!==Int32Array.BYTES_PER_ELEMENT||t.stage!==`open`&&t.stage!==`prepare`&&t.stage!==`transaction`&&t.stage!==`commit`){invalidProtocol(`admission request`,`unavailable`);return}let u=new Int32Array(t.decision),m=typeof t.deadlineMs==`number`&&Number.isFinite(t.deadlineMs)?readSqliteWorkerMonotonicNs()+BigInt(Math.max(0,Math.ceil(t.deadlineMs)))*1000000n:void 0,expired=()=>{if(m!==void 0&&readSqliteWorkerMonotonicNs()>=m&&Atomics.compareExchange(u,0,Jk,Zk)===Jk&&Atomics.notify(u,0),Atomics.load(u,0)!==Zk)return!1;if(Array.isArray(t.ports))for(let e of t.ports)e instanceof nt&&e.close();return!0};if(expired())return;c.add(u);let h={stage:t.stage,facts:t.facts};try{s(()=>p?.(h))}catch(e){refuse(u,e,`domain`);return}if(d){refuse(u,new SqliteWorkerError(`SQLite worker admission is closed`,`closed`),`authority`);return}let grant=e=>{if(d||expired()||Atomics.load(u,0)!==Jk)return!1;try{s(()=>x?.assertAccess())}catch(e){return refuse(u,e,`authority`),!1}if(d||expired()||Atomics.load(u,0)!==Jk||(e?.(),expired()))return!1;let t=Atomics.compareExchange(u,0,Jk,Yk)===Jk;return t&&Atomics.notify(u,0),t},g=!1,finishDecision=()=>{c.delete(u),Atomics.load(u,0)===Jk&&refuse(u,new SqliteWorkerError(`SQLite worker admission was not granted`,`closed`),`domain`)},y=`authority`;try{if(s(()=>{x?.assertRequest?.()}),h.stage===`prepare`&&isRecord(h.facts)&&h.facts.kind===`schema-maintenance`){let e=x;if(!e||typeof h.facts.databasePath!=`string`||resolveIdentityPathViaExistingAncestorSync(h.facts.databasePath)!==e.databasePath)throw new SqliteWorkerError(`SQLite schema maintenance target differs from its admitted database`,`closed`);s(()=>{e.lease??=e.acquireSchema(),e.assertAccess(),e.lease.assertCurrent(),grant()})}else{if(y=`domain`,r){g=!0,(async()=>{try{await s(r,h),!d&&!expired()&&Atomics.load(u,0)===Jk&&s(e,h,grant)}catch(e){refuse(u,e,`domain`)}finally{finishDecision()}})();return}s(e,h,grant)}}catch(e){e instanceof VD&&x?.coldOpenPath===e.databasePath&&!x.lease&&h.stage===`prepare`&&isRecord(h.facts)&&h.facts.kind===`schema-maintenance`&&typeof h.facts.databasePath==`string`&&resolveIdentityPathViaExistingAncestorSync(h.facts.databasePath)===x.databasePath?Atomics.compareExchange(u,0,Jk,4)===Jk&&Atomics.notify(u,0):refuse(u,e,y)}finally{g||finishDecision()}};i.on(`message`,receive).unref();let service=()=>{if(!h)for(let e=st(i);e;e=st(i))receive(e.message,!0)},te={port:a,attachment:t===void 0?void 0:{value:t},observeRequests(e){if(d||p)throw new SqliteWorkerError(`SQLite request observation is already bound or closed`,`closed`);p=e},bindDatabaseAuthority(e){if(d||x)throw new SqliteWorkerError(`SQLite database authority is already bound or closed`,`closed`);x={...e}},get failure(){return g?.error},get failureSource(){return g?.source},get cleanupFailures(){return u},get committed(){return service(),v},get settlement(){return b},waitForSettlement(e){for(;;){if(service(),g!==void 0)throw toErrorObject(g.error,`SQLite worker admission failed`);if(b?.kind===`completed`)return b;let t=e-performance.now();if(b?.kind===`unknown`||d||t<=0)throw new SqliteWorkerError(`SQLite worker native settlement is unknown`,`outcome-unknown`);Atomics.wait(ee,0,0,Math.min(5,t))}},service,finish(e){if(d=!0,service(),b=resolveSqliteWorkerFinishSettlement(b,v,e),c.size>0)for(let e of c)Atomics.load(e,0)===Jk&&refuse(e,new SqliteWorkerError(`SQLite worker admission is closed`,`closed`),`authority`);if(i.close(),a.close(),h?queueMicrotask(()=>m.splice(0)):m.length=0,p=void 0,x?.lease)try{x.lease.release(),x.lease=void 0}catch(e){u.push(e)}x?.lease||(x=void 0)}};return Qk.set(te,e=>{if(d||f)throw new SqliteWorkerError(`SQLite commit observation is closed or started`,`closed`);m.push(e)}),te}var Jk,Yk,Xk,Zk,Qk,$k,eA,createSqliteWorkerOperationAdmission,tA=__esmMin((()=>{O(),D(),B(),sp(),UD(),J(),Tk(),Mk(),Pk(),fO(),Kk(),qk(),Jk=0,Yk=1,Xk=2,Zk=3,Qk=/* @__PURE__ */ new WeakMap,$k=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerExecutionAuthorities`),()=>/* @__PURE__ */ new WeakMap),eA=/* @__PURE__ */ new WeakMap,createSqliteWorkerOperationAdmission=(e,t,n)=>createOperationAdmission(e,t,void 0,n)}));function acquireSchemaMaintenanceLease({databasePath:e,busyTimeoutMs:t}){if(requestSqliteWorkerSchemaMaintenance(e))return;let n=resolveIdentityPathViaExistingAncestorSync(e),r=getStateDatabaseSchemaLease(n);if(r)r.assertCurrent();else try{return acquireStateDatabaseSchemaLease(n,{busyTimeoutMs:t})}catch(e){throw e instanceof zD?new nA(n,e):e}}function withStateDatabaseSchemaMaintenance(e,t){let n=acquireSchemaMaintenanceLease(e);return n?runWithSqliteCleanup(n,`state schema mutation`,()=>n.run(t)):t()}var nA,rA=__esmMin((()=>{B(),sp(),xk(),W(),tA(),nA=resolveGlobalSingleton(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 isArtifactPreservingStateRead(e=`shared`,t){let n=iA.getStore();return!(!n||e!==`shared`&&!n.agentDatabases||t&&[...n.privateRoots].some(e=>Be(e,t)))}var iA,aA=__esmMin((()=>{W(),B(),iA=resolveGlobalSingleton(Symbol.for(`openclaw.artifactPreservingStateReads`),()=>new C)}));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}.`)}var oA=__esmMin((()=>{}));function assertExpectedContent(e,t,n){if(e.sizeBytes!==t.sizeBytes)throw Error(`SQLite snapshot size mismatch for ${n}: expected ${t.sizeBytes}, got ${e.sizeBytes}`);if(e.sha256!==t.sha256)throw Error(`SQLite snapshot hash mismatch for ${n}: expected ${t.sha256}, got ${e.sha256}`)}function assertPublishedFileIdentitySync(e,t,n){let i=r.lstatSync(e,{bigint:!0});if(!i.isFile()||!sameFileStatFingerprint(t,i))throw Error(`SQLite snapshot file changed: ${e}`);(t.mtimeMs!==i.mtimeMs||t.ctimeMs!==i.ctimeMs)&&assertExpectedContent(hashPublishedFileSync(e,t),n,e)}function assertOpenFileIdentitySync(e,t,n){let i=r.fstatSync(e,{bigint:!0}),a=r.lstatSync(t,{bigint:!0});if(!i.isFile()||!a.isFile()||!Fe(n,i)||!Fe(n,a))throw Error(`SQLite snapshot file changed: ${t}`)}function hashPublishedFileSync(e,t){let n=r.openSync(e,`r`);try{assertOpenFileIdentitySync(n,e,t);let i=r.fstatSync(n,{bigint:!0}),a=hashFileDescriptorSync(n),s=r.fstatSync(n,{bigint:!0});if(!sameFileMutationFingerprint(i,s)){if(!sameFileStatFingerprint(i,s))throw Error(`SQLite snapshot file changed while reading: ${e}`);assertExpectedContent(hashFileDescriptorSync(n),a,e)}return assertOpenFileIdentitySync(n,e,t),a}finally{r.closeSync(n)}}function sameFileStatFingerprint(e,t){return Fe(e,t)&&e.size===t.size}var sA=__esmMin((()=>{oA(),Lx()}));function canRetainDigest(e,t){let n=t-2000000000n;return typeof e.dev==`bigint`&&typeof e.ino==`bigint`&&typeof e.size==`bigint`&&e.dev!==0n&&e.ino!==0n&&typeof e.birthtimeNs==`bigint`&&typeof e.mtimeNs==`bigint`&&typeof e.ctimeNs==`bigint`&&e.mtimeNs>0n&&e.ctimeNs>0n&&e.mtimeNs<n&&e.ctimeNs<n}function timestampNs(e,t){return e??(typeof t==`bigint`?t*1000000n:BigInt(Math.trunc(t*1e6)))}function fingerprintFile(e,t){let n=BigInt(Date.now())*1000000n,i=r.openSync(e,`r`);try{let a=r.fstatSync(i,{bigint:!0});if(!a.isFile())throw Error(`SQLite generation target must be a regular file`);let s=t.get(e);if(s&&canRetainDigest(a,n)&&sameFileMutationFingerprint(s,a)){let t=r.fstatSync(i,{bigint:!0}),n=r.statSync(e,{bigint:!0});if(n.isFile()&&sameFileMutationFingerprint(a,t)&&sameFileMutationFingerprint(t,n))return s}let{sha256:c}=hashPublishedFileSync(r.realpathSync.native(e),a),l=r.fstatSync(i,{bigint:!0}),u=r.statSync(e,{bigint:!0});if(!sameFileStatFingerprint(a,l)||!sameFileStatFingerprint(l,u))throw Error(`SQLite generation target changed while hashing: ${e}`);let d={birthtimeNs:timestampNs(l.birthtimeNs,l.birthtimeMs),ctimeNs:timestampNs(l.ctimeNs,l.ctimeMs),dev:l.dev,ino:l.ino,mtimeNs:timestampNs(l.mtimeNs,l.mtimeMs),sha256:c,size:l.size};return canRetainDigest(a,n)&&sameFileMutationFingerprint(a,l)&&sameFileMutationFingerprint(l,u)?t.set(e,d):t.delete(e),d}finally{r.closeSync(i)}}function readOptionalFile(e,t){try{return fingerprintFile(e,t)}catch(n){if(n.code===`ENOENT`){t.delete(e);return}throw n}}function createSqliteFileGenerationReader(){let e=/* @__PURE__ */ new Map;return t=>{let n=fingerprintFile(t,e),r=readOptionalFile(`${t}-journal`,e),i=readOptionalFile(`${t}-wal`,e);return{database:n,...r?{journal:r}:{},...i?{wal:i}:{}}}}function readStableSqliteFileGeneration(e,t=createSqliteFileGenerationReader()){let n=t(e),r=t(e);if(!sameSqliteFileGeneration(n,r))throw Error(`SQLite file generation changed while reading: ${e}`);return r}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 serializeFileFingerprint(e){return{birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),dev:e.dev.toString(),ino:e.ino.toString(),mtimeNs:e.mtimeNs.toString(),sha256:e.sha256,size:e.size.toString()}}function serializeSqliteFileGeneration(e){return JSON.stringify({database:serializeFileFingerprint(e.database),...e.journal?{journal:serializeFileFingerprint(e.journal)}:{},...e.wal?{wal:serializeFileFingerprint(e.wal)}:{}})}function parseFileFingerprint(e){if(!isRecord(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(!isRecord(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)}}}var cA=__esmMin((()=>{D(),Lx(),sA()}));function resolveForwardedNodeCompilerArgs(){return process.execArgv.filter(e=>lA.has(e.replaceAll(`_`,`-`)))}var lA,uA=__esmMin((()=>{lA=/* @__PURE__ */ new Set([`--no-maglev`,`--maglev`,`--no-concurrent-sparkplug`,`--concurrent-sparkplug`])}));function executableIdentity(e){try{return formatExecutableIdentity(h(e))}catch{return}}function formatExecutableIdentity({dev:e,ino:t,size:n,mtimeMs:r,mode:i}){return`${e}:${t}:${n}:${r}:${i}`}function publishRuntimeViability(e,t){return(w(t,`ENOENT`)||w(t,`ENOTDIR`))&&recordUnavailableRuntime(e,t),{execPath:e,available:!(Q.execPath===e&&Q.failure)}}function readChildRuntimeViability(e){let t=e?.execPath??process.execPath;if(Q.execPath===t&&Q.failure)return{execPath:t,available:!1};try{i(t,c.X_OK)}catch(e){return publishRuntimeViability(t,e)}return publishRuntimeViability(t)}function recoverUnavailableRuntime(){if(Q.execPath!==process.execPath||!Q.failure||!Q.recover||Q.recoveryStarted)return;Q.recoveryStarted=!0;let e=Q.recover;runInDetachedAsyncContext(()=>Promise.resolve().then(e).catch(()=>({status:`report-only`,reason:`Automatic runtime recovery is report-only: service or restart preparation failed. Inspect the service runtime and restart through its owner.`})).then(e=>{createSubsystemLogger(`gateway/runtime`).warn(`${e.status}: ${e.reason}`)}))}function runtimeProbeOptions(e={}){return{encoding:`utf8`,cwd:e.cwd??S.parse(process.execPath).root,env:e.env??{...process.env,NODE_OPTIONS:void 0},timeout:1e3,maxBuffer:8192}}function formatMissingChildRuntimeWarning(e){return e.available?void 0:`The Node.js runtime this Gateway started with (${sanitizeTerminalText(e.execPath)}) can no longer start worker processes, likely because it was upgraded or removed. Restart the Gateway.`}function assertChildRuntimeAvailable(){if(Q.execPath===process.execPath&&Q.failure)throw Q.failure}function recordUnavailableRuntime(e,t,n){if(Q.execPath===e&&Q.failure)return Q.failure;Q.execPath=e;let r=formatMissingChildRuntimeWarning({execPath:e,available:!1}),i=n?.trim();return Q.failure=Object.assign(Error(i?`${r}\n${i}`:r,{cause:t}),{code:`NODE_RUNTIME_UNAVAILABLE`}),createSubsystemLogger(`gateway/runtime`).error(Q.failure.message),recoverUnavailableRuntime(),Q.failure}function needsRuntimeProbe(e){return!!(e.error||e.signal===`SIGABRT`||fA.test(e.stderr??``))}function classifyRuntimeProbe(e,t,n,r){if(Q.execPath===e&&Q.failure)return Q.failure;let i=e!==Q.initialPath||n!==Q.initialIdentity;return dA.test(t.stderr)||fA.test(t.stderr)||w(t.error,`ENOENT`)||w(t.error,`ENOTDIR`)||i&&(t.signal===`SIGABRT`||w(t.error,`ENOEXEC`)||w(t.error,`EACCES`)||w(t.error,`EPERM`))?recordUnavailableRuntime(e,r,t.stderr):void 0}function classifyChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(Q.execPath===t&&Q.failure)return Q.failure;if(dA.test(e.stderr??``)||e.error&&!readChildRuntimeViability({execPath:t}).available)return recordUnavailableRuntime(t,e.error,e.stderr);if(needsRuntimeProbe(e))return classifyRuntimeProbe(t,re(t,[`--version`],runtimeProbeOptions()),t===Q.initialPath?executableIdentity(t):void 0,e.error)}var Q,dA,fA,pA=__esmMin((()=>{dp(),Ev(),Qd(),B(),H(),Q=resolveGlobalSingleton(Symbol.for(`openclaw.childRuntimeViability`),()=>({observations:/* @__PURE__ */ new Map,initialPath:process.execPath,initialIdentity:executableIdentity(process.execPath)})),dA=/(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i,fA=/(?:dyld[^\n]*:\s*Symbol not found:|symbol lookup error:|Error loading shared library|version [`'"][^`'"\r\n]+[`'"] not found)/i})),mA=__esmMin((()=>{pA(),v_()}));function releasePipe(e){let t=restoreReader(e);t&&process.nextTick(()=>{e.destroyed||(e.emit(`readable`),t.resumed&&e.resume())})}function restoreReader(e){let t=hA.get(e);if(t)return e.read=t.read,hA.delete(e),e.removeListener(`resume`,t.onResume),e.removeListener(`readable`,holdReadable),t}var hA,holdReadable,gA=__esmMin((()=>{hA=/* @__PURE__ */ new WeakMap,holdReadable=()=>{}})),BrokerChild,_A=__esmMin((()=>{O(),It(),gA(),Wt(),BrokerChild=class extends t{constructor(e,t,n){super(),this.requestId=e,this.transmit=n,this.callbackContext=new Ce(`OpenClawSpawnBrokerChild`),this.stdin=null,this.stdout=null,this.stderr=null,this.connected=!1,this.killed=!1,this.exitCode=null,this.signalCode=null,this.stdio=[null,null,null,null,null],this.opened=createDeferredCore(),this.completion=createDeferredCore(),this.pipes=/* @__PURE__ */ new Set,this.sends=/* @__PURE__ */ new Map,this.sendSequence=0,this.spawnReceived=!1,this.eventsReleased=!1,this.pendingEventOverflow=!1,this.pendingEvents=[],this.exited=!1,this.closed=!1,this.processNotStarted=!1,this.spawnfile=t[0],this.spawnargs=[...t],this.opened.promise.catch(()=>{}),this.on(`error`,()=>{})}markNotStarted(){this.processNotStarted=!0}get notStarted(){return this.processNotStarted}ready(){return this.opened.promise}emit(e,...t){return this.callbackContext.runInAsyncScope(()=>super.emit(e,...t))}waitForClose(){return this.completion.promise}attachPipe(e,t){t.emit=this.callbackContext.bind(t.emit.bind(t)),this.stdio[e]=t,e===0&&(this.stdin=t),e===1&&(this.stdout=t),e===2&&(this.stderr=t),this.pipes.add(t);let n=!1,acknowledge=t=>{n||(n=!0,this.transmit({type:`output-drained`,id:this.requestId,fd:e,error:t?serializeBrokerError(t):void 0}).catch(()=>{}))};t.once(e===0?`finish`:`end`,()=>acknowledge()),t.on(`error`,acknowledge),t.once(`close`,()=>{acknowledge(),this.pipes.delete(t),this.finishClose()})}receive(e){if(e.type===`spawned`){if(this.spawnReceived||this.closed)return;for(this.spawnReceived=!0,this.pid=e.pid,this.spawnfile=e.spawnfile,this.spawnargs=e.spawnargs,this.connected=e.connected,this.stdio.splice(e.stdioLength);this.stdio.length<e.stdioLength;)this.stdio.push(null);this.connected&&(this.channel=Object.assign(new t,{ref(){},unref(){}})),this.opened.resolve(),setImmediate(()=>{this.closed||(this.emit(`spawn`),setImmediate(()=>{for(let[e,t]of this.stdio.entries())e>0&&t instanceof b&&!t.destroyed&&releasePipe(t);this.eventsReleased=!0;for(let e of this.pendingEvents.splice(0))e()}))})}else!this.eventsReleased&&(this.spawnReceived||e.type!==`error`)?this.deferEvent(()=>this.emitMessage(e)):this.emitMessage(e)}deferEvent(e){this.pendingEventOverflow||(this.pendingEvents.length>=64?(this.pendingEventOverflow=!0,this.pendingEvents.splice(0),this.pendingEvents.push(()=>{this.kill(`SIGKILL`),this.failNow(new SpawnBrokerError(`Spawn broker startup event capacity exceeded`))})):this.pendingEvents.push(e))}emitMessage(e){switch(e.type){case`error`:{let t=Object.assign(Error(e.error.message),e.error);this.opened.reject(t),this.emit(`error`,t),this.pid||(this.exited=!0,this.finishClose());break}case`exit`:this.exited=!0,this.exitCode=e.code,this.signalCode=e.signal,this.stdin?.destroy(),this.emit(`exit`,e.code,e.signal),process.nextTick(()=>{for(let e of this.pipes)e.readable&&e.resume()}),this.finishClose();break;case`ipc-sent`:this.finishSend(e.sequence,e.error?Object.assign(Error(e.error.message),e.error):null);break;case`disconnect`:this.failSends(/* @__PURE__ */ Error(`Child process IPC channel is closed`)),this.connected=!1,this.channel=void 0,this.emit(`disconnect`),this.finishClose();break;case`ipc`:this.emit(`message`,e.message);break;case`closed`:this.finishClose()}}fail(e){this.spawnReceived&&!this.eventsReleased?this.deferEvent(()=>this.failNow(e)):this.failNow(e)}failNow(e){if(this.closed)return;this.opened.reject(e),this.failSends(e);let t=this.connected;this.connected=!1,this.channel=void 0,t&&this.emit(`disconnect`),this.exited||this.emit(`error`,e);for(let t of this.pipes)t.destroy(e);this.exited=!0,this.finishClose()}finishClose(){!this.exited||this.channel||this.pipes.size>0||this.closed||(this.closed=!0,this.completion.resolve(),this.emit(`close`,this.exitCode,this.signalCode))}kill(e=`SIGTERM`){return!this.exited&&(this.killed=!0,this.transmit({type:`kill`,id:this.requestId,signal:e}).catch(e=>this.fail(toErrorObject(e,`Spawn broker signal delivery failed`))),!0)}send(e,t,n,r,i){let a=typeof t==`function`?t:typeof n==`function`?n:r;if(!this.connected||this.sends.size>=1024){let e=/* @__PURE__ */ Error(this.connected?`Child process IPC capacity exceeded`:`Child process IPC channel is closed`);return queueMicrotask(()=>a?a(e):this.emit(`error`,e)),!1}let s=++this.sendSequence;this.sends.set(s,Ce.bind(e=>{a?a(e):e&&this.emit(`error`,e)}));let c=typeof t==`function`?void 0:t;return this.transmit({type:`ipc`,id:this.requestId,sequence:s,message:e},c,i).catch(e=>this.finishSend(s,toErrorObject(e,`Spawn broker IPC delivery failed`))),!0}finishSend(e,t){let n=this.sends.get(e);this.sends.delete(e),n?.(t)}failSends(e){for(let t of this.sends.keys())this.finishSend(t,e)}disconnect(){this.connected&&(this.connected=!1,this.transmit({type:`disconnect`,id:this.requestId}).catch(e=>this.fail(toErrorObject(e,`Spawn broker disconnect failed`))))}ref(){}unref(){}[Symbol.dispose](){this.kill(`SIGTERM`)}}})),vA=__esmMin((()=>{H()})),yA=__esmMin((()=>{H(),vA()})),bA=__esmMin((()=>{on(),yA(),ln()})),xA=__esmMin((()=>{new Map([EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Error].map(e=>[e.name,e]))})),SA=__esmMin((()=>{process.hrtime.bigint.bind(process.hrtime)})),CA=__esmMin((()=>{xA(),SA()})),wA=__esmMin((()=>{pA(),H(),Fy(),Hy(),mA(),bA(),CA(),SA()})),TA=__esmMin((()=>{Fy(),fd(),wA(),new AsyncContext(Symbol(`spawnBroker`))}));function resolveSafeNodeCompileCacheDirectory(e){if(process.platform===`win32`&&S.resolve(e).length>200)process.stderr.write(`[openclaw] Compile cache disabled: Windows cache path exceeds 200 characters.
`);else return e}async function maintain(e){let t=S.dirname(S.dirname(e)),n=S.basename(S.dirname(e));if(S.basename(t)!==`openclaw`||sanitize(n)!==n||!MA.test(S.basename(e)))return;let r=Date.now(),i=await T.lstat(t).catch(()=>void 0);for(let n of[t,S.dirname(e),e]){let e=n===t?i:await T.lstat(n).catch(()=>void 0);if(e&&!e.isDirectory())return}if(i&&r-i.mtimeMs<OA)return;await T.mkdir(t,{recursive:!0});let a=`${t}.maintenance`,s=await T.lstat(a).catch(()=>void 0);if(s&&r-s.mtimeMs>3e5&&await T.rmdir(a).catch(()=>{}),!await T.mkdir(a).then(()=>!0,()=>!1))return;let c=[],l=0,u=0,d=!1;async function prune(){for(c.sort((e,t)=>t.mtimeMs-e.mtimeMs);c.length;){if(Date.now()-r>jA)return!1;let e=c[c.length-1];if(l<=EA&&c.length<=kA&&r-e.mtimeMs<=DA)break;await T.unlink(e.file).catch(e=>{if(e.code!==`ENOENT`)throw e}),l-=e.size,c.pop()}return!0}async function visit(e){for await(let t of await T.opendir(e)){if(++u>AA||Date.now()-r>jA)return!1;let n=S.join(e,t.name);if(t.isDirectory()){if(!await visit(n))return!1}else if(t.isFile()){let e=await T.lstat(n).catch(e=>{if(e.code!==`ENOENT`)throw e});if(!e)continue;if(l+=e.size,c.push({file:n,size:e.size,mtimeMs:e.mtimeMs}),c.length%256==0&&!await prune())return!1}}return!0}try{if(r-(await T.lstat(t)).mtimeMs<OA){d=!0;return}let e=await visit(t);if(await prune()&&e){let e=/* @__PURE__ */ new Date;await T.utimes(t,e,e),d=!0}}finally{d||await T.utimes(t,i?.atime??/* @__PURE__ */ new Date(0),i?.mtime??/* @__PURE__ */ new Date(0)).catch(()=>{}),await T.rmdir(a)}}var EA,DA,OA,kA,AA,jA,MA,sanitize,NA=__esmMin((()=>{at&&process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED===`gateway`&&(delete process.env.NODE_DISABLE_COMPILE_CACHE,delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED),EA=536870912,DA=6048e5,OA=36e5,kA=4096,AA=16384,jA=3e4,MA=/^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/,sanitize=e=>{let t=e.replace(/[^A-Za-z0-9._-]+/g,`_`).replace(/^_+|_+$/g,``);return t&&t!==`.`&&t!==`..`?t:`unknown`},process.argv[2]===`--maintain`&&process.argv[1]===Ie(import.meta.url)&&process.argv[3]&&maintain(process.argv[3]).catch(()=>{})}));function resolveNodeCompileCacheEnv(e=process.env){if(e.NODE_DISABLE_COMPILE_CACHE!==void 0)return e;let t=e.NODE_COMPILE_CACHE??resolveGlobalSingleton(PA,()=>({})).baseDirectory;if(t&&!resolveSafeNodeCompileCacheDirectory(t)){let t={...e,NODE_DISABLE_COMPILE_CACHE:`1`};return delete t.NODE_COMPILE_CACHE,t}return e.NODE_COMPILE_CACHE===void 0&&t?{...e,NODE_COMPILE_CACHE:t}:e}var PA,FA=__esmMin((()=>{NA(),B(),PA=Symbol.for(`openclaw.nodeCompileCacheBase`)}));function resolveSqliteFilesystemPath(e){return process.platform===`win32`?S.toNamespacedPath(S.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=S.win32.toNamespacedPath(S.win32.resolve(e));return`file:${encodeURIComponent(t)}`}return Le(S.resolve(e)).href}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){let n=requireNodeSqlite(),r=resolveNodeSqliteLocation(e),i=t?.open===!1?void 0:Wb(r,{create:t?.readOnly!==!0}),a=new n.DatabaseSync(r,t??{});if(a.isOpen)try{bindSqliteDatabaseAdmission(a,i)}catch(e){throw a.close(),e}return a.open=()=>{let e=Wb(r,{create:t?.readOnly!==!0});n.DatabaseSync.prototype.open.call(a);try{bindSqliteDatabaseAdmission(a,e)}catch(e){throw a.close(),e}},trackSqliteSchema(a,{DatabaseSync:n.DatabaseSync,StatementSync:n.StatementSync},t?.readOnly!==!0),a.isOpen&&t?.timeout!==void 0&&rememberSqliteBusyTimeout(a,Math.max(0,t.timeout)),getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources||registerNodeSqliteDisposeCallback(a,()=>{IA=!0}),registerSqliteReaderConnection(a),a}var IA,LA=__esmMin((()=>{Yy(),Du(),Nx(),J(),ib(),Pv(),Y()}));function acquireSqliteStagingToken(e,t,n={}){let i=S.join(e,RA[0]),readIdentity=(e,t)=>{let n=r.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},a=readIdentity(e,`directory`),s=RA.map(t=>r.lstatSync(S.join(e,t),{throwIfNoEntry:!1})),c=s[0];if(s.some(e=>e&&(!e.isFile()||process.getuid&&e.uid!==process.getuid()))||!c&&t!==`create`&&!n.allowMissing)throw Error(`SQLite snapshot token ownership is unknown`);t===`create`&&!c&&r.writeFileSync(i,``,{flag:`wx`,mode:420});let l=c!==void 0||t===`create`,u=l?readIdentity(i,`file`):void 0,d=withSqliteNativeOpen(()=>openNodeSqliteDatabase(l?resolveExistingSqliteFileUri(i):i,{timeout:0})),f,read=e=>executeWithCachedStatement(d,e,[],e=>e.get()),p=t===`reclaim`||t===`create`&&n.exclusiveCreate===!0,m=!1,assertIdentity=()=>{let t=readIdentity(e,`directory`);if(a.dev!==t.dev||a.ino!==t.ino)throw Error(`SQLite staging ownership changed before retirement`);let n=readIdentity(i,`file`);if(f.dev!==n.dev||f.ino!==n.ino)throw Error(`SQLite staging ownership changed before retirement`)},beginRetirement=()=>(assertIdentity(),(!d.isTransaction||!p)&&(d.isTransaction&&d.exec(`ROLLBACK`),d.exec(`BEGIN EXCLUSIVE`),p=!0),h),release=(e=!1)=>{d.isOpen&&(e?(beginRetirement(),m||d.exec(`PRAGMA user_version=1`),d.exec(`COMMIT`),m=!0):d.isTransaction&&d.exec(`ROLLBACK`),d.close(),e&&retireSqliteDatabaseAdmissionForPath(i))},h=Object.assign(release,{beginRetirement});try{if(f=u??readIdentity(i,`file`),p?d.exec(`BEGIN EXCLUSIVE`):t===`create`?d.exec(`BEGIN IMMEDIATE`):d.exec(`BEGIN`),t!==`create`||c){let e=read(`PRAGMA journal_mode`);if(!isRecord(e)||e.journal_mode!==`delete`)throw Error(`SQLite snapshot token journal mode is unknown`);let n=read(`PRAGMA user_version`),r=isRecord(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}}var RA,SqliteStagingRetiredError,zA=__esmMin((()=>{D(),Du(),LA(),J(),kb(),RA=[`owner.sqlite`,`owner.sqlite-journal`,`owner.sqlite-wal`,`owner.sqlite-shm`],SqliteStagingRetiredError=class extends Error{constructor(){super(`SQLite snapshot parent retired; aborting snapshot allocation`)}}}));function releaseTokens(e){let t=collectSynchronousErrors(e,e=>e());if(t.length)throw AggregateError(t,`SQLite snapshot retirement token release failed`)}function acquireSqliteSnapshotToken(e,t){return acquireSqliteStagingToken(e,t,{allowMissing:HA.test(S.basename(e))})}function beginSqliteSnapshotRetirement(e,t={}){let n=[],i=[],release=()=>releaseTokens(n.filter(e=>e!==t.token));if(!r.existsSync(e))return t.token?.(),{bytes:0,payload:i,release,retire:()=>{}};function inspect(a,s,c=``,l=!0){let u=r.lstatSync(a);if(!u.isDirectory()||process.getuid&&u.uid!==process.getuid())throw Error(`Snapshot directory ownership is unknown`);let d=!c&&HA.test(S.basename(a)),f=t.cutoff!==void 0&&d?Math.min(s,Date.now()-GA):s,p=d?`Legacy snapshot contains activity newer than 24 hours`:`Snapshot contains activity within the reclamation grace period`;if(u.mtimeMs>=f)throw Error(p);d&&l&&t.cutoff!==void 0&&inspect(a,f,c,!1),!c&&l&&n.push(a===e&&t.token?t.token.beginRetirement():acquireSqliteSnapshotToken(a,`reclaim`));let m=0,h=u.mtimeMs;for(let e of r.readdirSync(a,{withFileTypes:!0})){let n=S.join(a,e.name),s=r.lstatSync(n);if(process.getuid&&s.uid!==process.getuid())throw Error(`Snapshot file ownership is unknown`);if(c&&t.cutoff!==void 0||!s.isFile()||!RA.some(t=>t===e.name)){if(h=Math.max(h,s.mtimeMs),s.isDirectory()){let r=isSqliteSnapshotStagingName(e.name),i=r?``:[c,e.name].filter(Boolean).join(`/`);if(t.cutoff!==void 0&&(!r&&![`openclaw`,`openclaw-state`,`openclaw-state/state`].includes(i)||r&&c!==``&&c!==`openclaw`))throw Error(`Unrecognized snapshot directory`);let a=inspect(n,f,i,l);m+=a.bytes,h=Math.max(h,a.newest)}else if(t.cutoff===void 0||s.isFile()&&(c===`openclaw-state/state`?/^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(e.name):!c&&(/^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(e.name)||WA.test(e.name))))m+=s.size,l&&i.push(n);else throw Error(`Unrecognized snapshot artifact`)}}if(h>=f)throw Error(p);return{bytes:m,newest:h}}try{let{bytes:r}=inspect(e,t.cutoff??1/0);return{bytes:r,payload:i,release,retire:()=>{for(let e of n)e(!0)}}}catch(e){throw release(),e}}var BA,VA,HA,UA,WA,GA,isSqliteSnapshotStagingName,KA=__esmMin((()=>{_O(),zA(),BA=`openclaw-sqlite-readonly-v2-`,VA=`(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$`,HA=RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${VA}`,`u`),UA=RegExp(`^${BA}${VA}`,`u`),WA=/^\.fs-safe-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.tmp$/u,GA=864e5,isSqliteSnapshotStagingName=e=>HA.test(e)||UA.test(e)}));function snapshotDirectory(e){let t=JA.get(e);return t||(t={readers:/* @__PURE__ */ new Set},JA.set(e,t)),t}function completeSnapshotDirectoryRemoval(e){return JA.delete(e),!0}function cleanupSnapshotOperations(){return qA.pendingSignalCleanup??=(async()=>{let e=JA.entries();for(;;){for(;YA.size>0;){for(let e of YA.values())e();await Promise.allSettled(YA.keys())}let t=e.next();if(t.done)break;let[n]=t.value;await removeTempDirectoryAsync(n,e=>emitSnapshotCleanupFailure({cleanupRoot:n,operation:`rm`,code:extractErrorCode(e)}))}})().finally(()=>{qA.pendingSignalCleanup=void 0}),qA.pendingSignalCleanup}function retainSnapshotWork(e,t=()=>{}){registerSnapshotCleanup(),YA.set(e,t);let release=()=>YA.delete(e);return e.then(release,release),e}function registerSnapshotTempDirectory(e,t){let n=snapshotDirectory(e);n.release=t??n.release,registerSnapshotCleanup()}function registerSnapshotCleanup(){qA.exitHandlerInstalled||(qA.exitHandlerInstalled=!0,process.once(`exit`,()=>{for(let e of YA.values())e();if(YA.size===0)for(let e of JA.keys())removeTempDirectory(e)})),registerSignalExitFinalizer(qA.signalCleanup)}function retainSnapshotTempDirectory(e){registerSnapshotTempDirectory(e);let t=snapshotDirectory(e);if(t.retirementStarted)throw new SqliteSnapshotCleanupError(`SQLite snapshot retirement has started`);let n=Symbol(`sqlite.snapshot.reader`);return t.readers.add(n),()=>t.readers.delete(n)}function emitSnapshotCleanupFailure(e,t){if(t)try{t(e);return}catch{}try{getChildLogger({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 SqliteSnapshotCleanupError(`SQLite snapshot still belongs to an active reader`)}function prepareSnapshotRetirement(e,t){if(assertSnapshotReadersRetired(t),t?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot requires asynchronous cleanup`);if(!(t?.retired||!t?.release&&!r.existsSync(S.join(e,RA[0]))))return t&&(t.retirementStarted=!0),beginSqliteSnapshotRetirement(e,{token:t?.release})}function retireSqliteSnapshotPayload(e){for(let t of e.payload)retireSqliteDatabaseAdmissionForPath(t),r.rmSync(t,XA);e.retire()}function removeTempDirectory(e,t){let n=JA.get(e);n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{t&&(retireSqliteSnapshotPayload(t),n=snapshotDirectory(e),n.release=void 0,n.retired=!0);try{r.rmSync(e,XA)}catch(t){throw classifyRetiredSqliteSnapshotRemovalError(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=JA.get(e);if(n?.releaseRetained){let r=await startRemoveTempDirectory(e,t,n).result;return r&&JA.delete(e),r}n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{for(let e of t?.payload??[])retireSqliteDatabaseAdmissionForPath(e),await retainSnapshotWork(r.promises.rm(e,XA));t&&(t.retire(),n=snapshotDirectory(e),n.release=void 0,n.retired=!0);try{await retainSnapshotWork(r.promises.rm(e,XA))}catch(t){throw classifyRetiredSqliteSnapshotRemovalError(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=JA.get(e)){if(n?.retiringRetained)return n.retiringRetained;let r,i=createRetainedOperation(()=>{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 SqliteSnapshotCleanupError(`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=JA.get(e);if(!n?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot has no retained cleanup owner`);if(t?.requireRequested&&!n.retirementStarted)throw new SqliteSnapshotCleanupError(`SQLite snapshot is still owned; cleanup has not been requested`);let r=[...JA].filter(([t])=>Ve(e,t));for(let[,e]of r)assertSnapshotReadersRetired(e);for(let[,e]of r)e.retirementStarted=!0;for(let t of captureSqliteDatabaseAdmissions())Ve(e,t.location)&&retireSqliteDatabaseAdmissionForPath(t.location)}function preparationCleanupError(e,t){return createSqliteLifecycleAggregateError(e,`${t} and cleanup failed: ${coerceErrorMessage(e[0])}`,e[0])}function discardPreparedCopyPayload(e,t){try{for(let t of[`first`,`database.sqlite`,`database.sqlite.partial`])for(let n of t===`first`?[``]:[``,`-wal`,`-shm`,`-journal`]){let i=S.join(e,`${t}${n}`);retireSqliteDatabaseAdmissionForPath(i),r.rmSync(i,{force:!0})}}catch(e){throw preparationCleanupError([t,e],`SQLite snapshot preparation`)}}function publishPreparedCopy(e,t){let n=S.join(e,`database.sqlite`);for(let e of[`-wal`,`-shm`,`-journal`,``]){let t=`${n}.partial${e}`;r.existsSync(t)&&r.renameSync(t,`${n}${e}`)}let i;if(t){let e=r.lstatSync(n,{bigint:!0});assertExpectedContent(hashPublishedFileSync(n,e),t,n),i={...t,identity:e}}return{...adoptPreparedLocation(n,e),journalFreeContent:i}}function adoptPreparedLocation(e,t,n=!1,r){let i=t??S.dirname(e);registerSnapshotTempDirectory(i);let a=!0,s,c,l=!1,reportFailure=e=>{!n&&!l&&(l=!0,emitSnapshotCleanupFailure({cleanupRoot:i,operation:`rm`,code:extractErrorCode(e)},r))},complete=e=>{if(e)a=!1,JA.delete(i);else if(n)throw new SqliteSnapshotCleanupError(`SQLite read-only worker snapshot cleanup failed: ${i}`,{cause:JA.get(i)?.cleanupFailure});return e},startCleanup=()=>{if(c?.read().status===`pending`)return c;if(!a){let e=createRetainedOperation(()=>{});return e.resolve(complete(!0)),c=e.operation}return c=mapRetainedOperation(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:()=>JA.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}}var qA,JA,YA,XA,ZA=__esmMin((()=>{O(),tO(),Uf(),gv(),B(),bp(),J(),kb(),W(),sA(),KA(),zA(),qA=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotCleanup`),()=>({directories:/* @__PURE__ */ new Map,activeWork:/* @__PURE__ */ new Map,exitHandlerInstalled:!1,pendingSignalCleanup:void 0,signalCleanup:cleanupSnapshotOperations})),JA=qA.directories,YA=qA.activeWork,XA={force:!0,maxRetries:3,recursive:!0,retryDelay:20}})),QA,$A=__esmMin((()=>{fd(),QA=new AsyncContext(Symbol(`sqliteReadOnlyWorkerScope`))})),ej,tj,nj=__esmMin((()=>{ej=Symbol.for(`openclaw.workerTaskNativeSection`),tj=globalThis,tj[ej]??=new C})),rj=__esmMin((()=>{Uu()})),ij=__esmMin((()=>{rj(),$e(`openclaw.worker.task`)}));function isWorkerIdleForPressure(e,t=!1){return e!==void 0&&(t||performance.now()-e>=1e3)}var aj=__esmMin((()=>{nj()})),oj=__esmMin((()=>{nj()})),sj=__esmMin((()=>{nj(),ij(),rj(),aj(),oj(),C.snapshot(),$e(`openclaw.memory.critical`)})),cj=__esmMin((()=>{sj(),aj(),rj()}));function createStateWorkerMemoryPressureSubscription(e,t){let n=!1,onPressure=e=>t(e===!0);return()=>{let t=e();t!==n&&(n=t,t?lj.subscribe(onPressure):lj.unsubscribe(onPressure))}}var lj,uj=__esmMin((()=>{lj=$e(`openclaw.memory.critical`)}));function sqliteReadOnlyOperationRequiresProcessRetirement(e){return e in dj}var dj,fj=__esmMin((()=>{dj={"startupMetadata.readCurrent":`retire-after-result`}}));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(e){return e.flatMap(e=>{let t=normalizeLowercaseStringOrEmpty(e);return[`-${t}`,`--${t}`,`/${t}`]})}function countSeparateValueOptionChars(e){let t=0;for(let n=1;n<e.length;n+=1){let r=e[n];(r===`o`||r===`O`)&&(t+=1)}return t}function parseCombinedCommandFlag(e){if(e.length<2||e[0]!==`-`||e[1]===`-`)return null;let t=e.slice(1),n=t.indexOf(`c`);if(n===-1||t.includes(`-`))return null;let r=t.slice(n+1);return r&&!/^[A-Za-z]+$/.test(r)?{attachedCommand:r,separateValueCount:0}:{attachedCommand:null,separateValueCount:countSeparateValueOptionChars(e)}}function combinedSeparateValueOptionCount(e){return e.length<2||e[0]!==`-`&&e[0]!==`+`||e[1]===`-`||e.slice(1).includes(`-`)?0:countSeparateValueOptionChars(e)}function advancePosixInlineOptionScan(e){let t=combinedSeparateValueOptionCount(e);return t>0?1+t:xj.has(e)?2:1}function isPowerShellOptionToken(e){return e.startsWith(`-`)||/^\/[A-Za-z][A-Za-z0-9]*$/.test(e)}function resolveInlineCommandMatch(e,t,n={}){for(let r=1;r<e.length;){let i=e[r]?.trim();if(!i){r+=1;continue}let a=normalizeLowercaseStringOrEmpty(i);if(a===`--`)break;let s=n.allowCombinedC?i:a,c=t.has(s),l=!c&&n.allowCombinedC?parseCombinedCommandFlag(i):null;if(c||l){if(l&&l.attachedCommand!==null)return{command:l.attachedCommand.trim()||null,valueTokenIndex:r};let t=r+1+(l?.separateValueCount??0),i=!l&&t>=e.length?null:t;return{command:(c&&n.restValueFlags?.has(s)?e.slice(r+1).map(e=>e.trim()).join(` `).trim():e[t]?.trim())||null,valueTokenIndex:i}}if(n.valueOptions?.has(a)){r+=2;continue}let u=n.isOptionToken?.(i)??(i.startsWith(`-`)||i.startsWith(`+`));if(n.stopAtFirstNonOption&&!u||n.allowCombinedC&&!i.startsWith(`-`)&&!i.startsWith(`+`))break;r+=n.allowCombinedC?advancePosixInlineOptionScan(i):1}return{command:null,valueTokenIndex:null}}function resolvePowerShellInlineCommandMatch(e){return resolveInlineCommandMatch(e,vj,{isOptionToken:isPowerShellOptionToken,restValueFlags:yj,stopAtFirstNonOption:!0,valueOptions:bj})}function isPowerShellInlineFileCommandFlag(e){return gj.has(normalizeLowercaseStringOrEmpty(e))}var pj,mj,hj,gj,_j,vj,yj,bj,xj,Sj=__esmMin((()=>{Lt(),pj=/* @__PURE__ */ new Set([`-lc`,`-c`,`--command`,`--commands`,`--cmdline`]),[...pj],mj=[...expandPowerShellSwitchPrefixForms(`command`,`c`),...expandPowerShellSwitchPrefixForms(`commandwithargs`,`cwa`),...expandPowerShellSwitchForms([`cwa`])],hj=expandPowerShellSwitchPrefixForms(`file`,`f`),gj=new Set(hj),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`)],_j=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`encodedcommand`,`e`),...expandPowerShellSwitchPrefixForms(`ec`,`e`)]),vj=/* @__PURE__ */ new Set([...mj,...hj,..._j]),yj=new Set(mj),bj=/* @__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`])]),xj=/* @__PURE__ */ new Set([`--init-file`,`--rcfile`,`-O`,`-o`,`+O`,`+o`])}));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],pj,{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(!areDiagnosticsEnabledForProcess())return;let r=resolveOomScoreWrappedCommand(e,t),i=r?t.slice(3):t,a=S.win32.basename(r??e).toLowerCase().replace(/\.(exe|cmd)$/,``),s=wj.test(a)?a:`other`,c=s===`git`?Tj.getStore()??Ej.getStore()??unscopedGitOperation(i):n??Ej.getStore()??unscopedProcessOperation(s,a,i),l=`${s}:${c}`;return()=>{if(areDiagnosticsEnabledForProcess()){let e=Cj.counts.get(l);Cj.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)}var Cj,wj,Tj,Ej,Dj=__esmMin((()=>{Cf(),Sj(),B(),Cj=resolveGlobalSingleton(Symbol.for(`openclaw.childProcessSpawnCounts`),()=>({counts:/* @__PURE__ */ new Map,sampledAt:performance.now()})),wj=/^(node|bun|git|ps|pgrep|lsof|sh|bash|zsh|cmd|powershell|pwsh|npm|pnpm|python|python3|uv|ssh|openclaw)$/,Tj=resolveGlobalSingleton(Symbol.for(`openclaw.gitSpawnOperation`),()=>new C),Ej=resolveGlobalSingleton(Symbol.for(`openclaw.childSpawnOperation`),()=>new C)}));function ok(e){return{ok:!0,value:e}}function err(e){return{ok:!1,error:e}}var Oj=__esmMin((()=>{}));function normalizeAgentId(e){let t=normalizeAgentIdStrict(e);return t.ok?t.value:kj}function normalizeAgentIdStrict(e){let t=(e??``).trim(),n=t.toLowerCase();if(Aj.test(t))return ok(n);let r=n.replace(jj,`-`).replace(Mj,``).replace(Nj,``).slice(0,64);return r?ok(r):err(`unrepresentable`)}var kj,Aj,jj,Mj,Nj,Pj=__esmMin((()=>{Oj(),kj=`main`,Aj=/^[a-z0-9][a-z0-9_-]{0,63}$/i,jj=/[^a-z0-9_-]+/g,Mj=/^-+/,Nj=/-+$/}));function matchesAgentDatabaseReadCandidatePath(e,t){if(e.path===t)return!0;let n=S.resolve(e.path),r=S.resolve(t);if(n===r)return!0;if(e.scope!==`sibling-family`)return!1;let i=S.parse(n),a=S.parse(r);return a.dir===i.dir&&a.base.startsWith(`${i.name}.`)&&a.base.endsWith(i.ext)}function registerAgentDatabaseReaderCloser(e){return Fj.closers.add(e),()=>{Fj.closers.delete(e)}}var Fj,Ij=__esmMin((()=>{B(),Fj=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseReaders`),()=>({closers:/* @__PURE__ */ new Set,deleted:/* @__PURE__ */ new Map}))})),Lj,Rj=__esmMin((()=>{Up(),H(),bp(),Lj=/* @__PURE__ */ new Map,Lj.keys()}));function getActiveAgentCreationClaim(e,t){let n=zj.getStore();if(n&&n.kind===`host`&&n.isActive()&&n.agentId===normalizeAgentId(e)&&n.statePath===S.resolve(t))return n}function reserveAgentCreationClaimAdmission(e,t,n){let r=getActiveAgentCreationClaim(t.agentId,resolveOpenClawStateSqlitePath(t.env??process.env));if(r)return Bj.set(e,r),r.registerClose(async()=>{Bj.get(e)===r&&(await n(),Bj.delete(e))}),()=>{Bj.delete(e)}}var zj,Bj,Vj=__esmMin((()=>{Pj(),B(),Rj(),X(),zj=resolveGlobalSingleton(Symbol.for(`openclaw.agentCreationClaim`),()=>new C),Bj=resolveGlobalSingleton(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map)})),Hj,Uj=__esmMin((()=>{Xy(),B(),Hj=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class extends Error{}),resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}}),resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class extends Error{constructor(){super(`Invalid agent schema admission receipt`)}}),resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class extends Error{constructor(e){super(formatErrorMessage(e),{cause:e})}})}));function captureAgentDeletionResourceOwner(e){let t=Wj.getStore();if(t?.ownsDatabase&&(e(t)||t.canonicalPath&&e({agentId:t.agentId,path:t.canonicalPath})))return t.assertCurrentHost(),t}var Wj,Gj=__esmMin((()=>{qv(),B(),Rj(),X(),Wj=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new C),resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map),resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map)}));function matchesAgentDatabaseClose(e,t){return(e.path===void 0||e.path===t.path||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.path))&&(e.rootPath===void 0||Ve(e.rootPath,t.path)||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(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:S.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=()=>{Kj.active.delete(n),r?.()};return getOpenClawDatabaseMaintenanceScope()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n)),Kj.active.add(n),unregister}function assertAgentDatabaseResourceAdmission(e){if([...Kj.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...Kj.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.path)||e.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new Hj(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,t){if(e.ownership===`known`&&e.closeSync){Kj.closing.set(e,void 0);try{return e.revoke(),e.closeSync(),Kj.active.delete(e),Kj.closing.delete(e),Promise.resolve()}catch(n){t&&t(e.path,n);let r=Promise.reject(toErrorObject(n,`Agent database cleanup failed`));return r.catch(()=>{}),r}}let n=Kj.closing.get(e);return n||(n=Promise.resolve().then(()=>e.close()),Kj.closing.set(e,n),n.then(()=>{Kj.active.delete(e),Kj.closing.delete(e)},()=>{Kj.closing.set(e,void 0)}).catch(()=>{})),t&&n.catch(n=>t(e.path,n)).catch(()=>{}),e.revoke(),n}var Kj,qj=__esmMin((()=>{O(),Ij(),bp(),B(),Vj(),Uj(),Gj(),LS(),Kj=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map})),registerAgentDatabaseReaderCloser(async(e,t)=>{let n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...Kj.active,...Kj.closing.keys()])].filter(n=>!t?.has(S.resolve(n.path))&&e.some(e=>matchesAgentDatabaseReadCandidatePath(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 captureSqliteAuthSchema(e,t){if(ex(e)?.key!==t)return;let n=Xb(e,Bx,()=>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`)}}var Jj=__esmMin((()=>{J(),Hx()}));function isJsonTransferField(e){return isRecord(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}}}var Yj,Xj=__esmMin((()=>{D(),Yj=65536}));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)}throwSqliteLifecycleErrors(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:Ct(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+Zj);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=St(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}}}}var Zj,Qj=__esmMin((()=>{W(),Zj=8388608}));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:Yj,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(!isRecord(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||!isRecord(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}})}var $j=__esmMin((()=>{D(),Xj(),Qj()}));function markPrivateDirectoryCreationRefused(e){return typeof e==`object`&&e&&eM.add(e),e}function isPrivateDirectoryCreationRefused(e){return typeof e==`object`&&!!e&&eM.has(e)}var eM,tM=__esmMin((()=>{eM=/* @__PURE__ */ new WeakSet}));function hasSqliteSnapshotCapacityCode(e){let{code:t,errcode:n}=e;return t===`ENOSPC`||t===`EDQUOT`||n===13}var nM,SqliteSnapshotCapacityError,rM=__esmMin((()=>{nM=`SqliteSnapshotCapacityError`,SqliteSnapshotCapacityError=class extends Error{constructor(e,t){super(e,t),this.name=nM}}}));function isSqliteSnapshotStagingMode(e){return e===`staging-create`||e===`staging-create-legacy`||e===`staging-reconcile`||e===`staging-retire`}function sqliteReadOnlyWorkerRequestArgs(e,t){let n=[t.mode,S.resolve(e)],r=t.stagingRoot&&S.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(readDatabaseFileIdentity(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&&isRecord(e.engine)&&(e.engine.engine===`sqlite`||e.engine.engine===`postgres`&&typeof e.engine.storeId==`string`&&typeof e.engine.namespace==`string`)||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&&`warnings`in e&&isStringArray(e.warnings)}function createSqliteReadOnlyWorkerError(e,t,n){let r=ge(sliceUtf16Safe(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===`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===`reclaim`&&`warnings`in n)return n.warnings;throw createSqliteReadOnlyWorkerError(`returned a result for a different operation`,e.stderr)}var iM,SqliteReadOnlyInspectionContentionError,aM,oM=__esmMin((()=>{D(),Ju(),tM(),rM(),qv(),iM=1048576,SqliteReadOnlyInspectionContentionError=class extends Error{},aM=4e3}));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){assertChildRuntimeAvailable();let t={...e.env},n=e.cwd,r=process.execPath,i=e.transport.kind===`broker`?{kind:`broker`,owner:e.transport.owner}:{kind:`native`},a={env:t,cwd:n,transport:i,runtimeGeneration:e.runtimeGeneration},s=[...e.argv],c={env:t,...i.kind===`native`&&n===tryProcessCwd()?{}:{cwd:n},stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0},l=i.kind===`broker`?i.owner.spawn(r,s,c):ne(r,s,c);recordChildProcessSpawn(r,l,e.pooledRead?`sqlite.scoped-read.${i.kind}`:`sqlite.session.${i.kind}`);let setIdle=e=>{if(i.kind!==`native`)return;let t=e?`unref`:`ref`;l[t](),l.channel?.[t]?.();for(let e of[l.stdout,l.stderr])e instanceof b&&e[t]()},u=!1,d=0,f,p=``,m=0,h,{promise:g,resolve:v}=createDeferredCore(),y=/* @__PURE__ */ new Map,x=g.then(async()=>{i.kind===`broker`&&l instanceof BrokerChild&&!l.notStarted&&l.exitCode===null&&l.signalCode===null&&await i.owner.waitForCleanup();for(let e of y.values())e();y.clear()}),retire=e=>{setIdle(!1),u=!0,h&&e!==void 0&&(h.failure??=e),l.kill(`SIGKILL`)},sendMessage=e=>l.send(e,e=>{e&&retire(e)}),releasePending=t=>{if(h=void 0,f=void 0,t.cleanup(),e.pooledRead){for(let e of y.values())e();y.clear()}return t};e.retainLifetime!==!1&&retainSnapshotWork(x,()=>retire(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)));let ee=!1,te=!1,re=!1;l.once(`spawn`,()=>{te=!0}),l.on(`error`,e=>retire(te?e:Object.assign(Error([[`EACCES`,`ENOENT`,`EPERM`].includes(e.code??``)?`SQLite read-only worker runtime binary not executable: ${r} (${e.code}, cwd ${n}). Check runtime execute permissions and access to the working directory`:`SQLite read-only worker failed to start (executable ${r}, cwd ${n})`,e.message].join(`: `),{cause:e}),{code:e.code,path:e.path}))),l.once(`close`,(e,t)=>{re=!0,u=!0;let n=h?.failure??createSqliteReadOnlyWorkerError(`exited with ${t?`signal ${t}`:`code ${e}`}`,p),i=classifyChildRuntimeFailure({execPath:r,error:n,stderr:p,signal:t,started:ee});h&&releasePending(h).reject(i??n),v()});let captureOutput=(e,t)=>{m+=e.length,t&&(p=sliceUtf16Safe(p+e.toString(`utf8`),-aM)),m>1048576&&retire(createSqliteReadOnlyWorkerError(`exceeded its output buffer`,p))},attachOutput=()=>{l.stdout?.on(`data`,e=>captureOutput(e,!1)),l.stderr?.on(`data`,e=>captureOutput(e,!0))},ie=l instanceof BrokerChild?l.ready().then(attachOutput).catch(retire):void 0;ie||attachOutput(),l.on(`message`,t=>{if(ee=!0,!u){if(!h||!t||typeof t!=`object`||Object.keys(t).length!==2||!(`id`in t)||t.id!==h.id||!(`result`in t))retire(createSqliteReadOnlyWorkerError(`returned an unexpected response`,p));else try{let e;if(h.transfer&&`type`in t.result){let n=h.transfer.accept(t.result);if(`request`in n){sendMessage({id:h.id,transfer:n.request});return}e=n.value}else e=readSqliteReadOnlyWorkerValue({kind:`launched`,stdout:JSON.stringify(t.result),stderr:p,status:0},h.mode);releasePending(h).resolve(e)}catch(n){if(h&&e.retainOnOperationError&&isSqliteSnapshotStagingMode(h.mode)&&isSqliteReadOnlyWorkerResult(t.result)&&!t.result.ok){releasePending(h).reject(n);return}retire(n)}}});let ae={closed:x,isRetired(){return u},get notStarted(){return l instanceof BrokerChild?l.notStarted:re&&!te},createNativeReplacement(){return runInDetachedAsyncContext(()=>createSqliteReadOnlyWorkerSession({...e,env:t,cwd:n,argv:s,transport:{kind:`native`}}))},compatible(e){return!u&&isSameSqliteReadOnlyWorkerLaunch(a,e)},run(t,n){if(u)return Promise.reject(/* @__PURE__ */ Error(`SQLite read-only worker is closed`));if(n.mode===`auth-profile-rows`&&n.source===`canonical`&&!n.artifactPreserving){let e=S.resolve(t);y.has(e)||y.set(e,registerOpenClawAgentDatabaseReadCandidateResource({path:e,revoke:()=>retire(/* @__PURE__ */ Error(`Auth profile reader owner was revoked`)),close:()=>ae.close()}))}return f=new Promise((r,i)=>{p=``,m=0;let abort=()=>retire(n.signal?.reason),a,s=++d;h={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(u)return;a=setTimeout(()=>retire(e.timeoutError(t,n,r)),n)}if(ie&&(await ie,u))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:Ct(n.command).toString(`base64`)}:{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(ae.setIdle(!1),u){await x;return}u=!0;let t=setTimeout(()=>retire(),e.closeTimeoutMs);try{sendMessage(`close`)}catch(e){retire(e)}try{await x}finally{clearTimeout(t)}}};return e.runtimeGeneration?.retain(ae,async()=>(await f?.catch(()=>void 0),()=>ae.close())),ae}var sM=__esmMin((()=>{Ju(),_A(),Dj(),It(),Qd(),qj(),pA(),fp(),Jj(),$j(),ZA(),oM()}));function trackWorkerRequest(e,t,n){let r=normalizeWorkerRequestClass(t),i=e===`sqlite_writer`?lM.getStore():void 0,a=performance.now(),s=e===`sqlite_writer`&&(uM||cM.size>0||hasInternalDiagnosticEventInterest(`worker.request`,!0))?{enqueued:a}:void 0,c,l=!1,emit=(t,n,i)=>{if(!areDiagnosticsEnabledForProcess())return;let a=dM.get(e)??0,c=t===`completed`?s:void 0;for(let s of cM)try{s(e,r,t,a,n,i,c)}catch{}hasInternalDiagnosticEventInterest(`worker.request`,!0)&&emitTrustedDiagnosticEvent({type:`worker.request`,kind:e,requestClass:r,phase:t,queueDepth:a,...n===void 0?{}:{queueWaitMs:n},...i===void 0?{}:{durationMs:i},...c?{timing:c}:{}})},dequeue=()=>dM.set(e,(dM.get(e)??0)-1);dM.set(e,(dM.get(e)??0)+1),emit(`queued`);let u={requestClass:r,timing:s,...i?{recordTransactions:e=>{i.transactionCount=(i.transactionCount??0)+e}}:{},started:()=>{l||c!==void 0||(c=performance.now(),i&&i.operations.add(i.operations.has(r)||i.operations.size<8?r:`other`),s&&(s.dispatched=c),n?.removeEventListener(`abort`,u.completed),dequeue(),emit(`started`,c-a))},completed:()=>{l||(l=!0,n?.removeEventListener(`abort`,u.completed),c===void 0&&dequeue(),emit(`completed`,void 0,c===void 0?void 0:performance.now()-c))}};return n?.addEventListener(`abort`,u.completed,{once:!0}),n?.aborted&&u.completed(),u}var cM,lM,uM,dM,fM=__esmMin((()=>{B(),td(),Cf(),Hd(),uO(),hf(),resolveGlobalSingleton(Symbol.for(`openclaw.workerStartObservation`),()=>new C),cM=resolveGlobalSingleton(Symbol.for(`openclaw.workerRequestMetricsListeners`),()=>/* @__PURE__ */ new Set),lM=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerReservationObservation`),()=>new C),uM=isDiagnosticFlagEnabled(`sqlite.worker-timing`),dM=resolveGlobalSingleton(Symbol.for(`openclaw.workerRequestQueueDepth`),()=>/* @__PURE__ */ new Map)}));function trackSqliteRead(e){return trackWorkerRequest(`sqlite_read`,classifyWorkerRequest(e.mode===`operation`?e.command.type:e.mode),e.signal)}function createSqliteReadOnlyWorkerPool(e){let t=[],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new WeakSet,a=createStateWorkerMemoryPressureSubscription(()=>t.some(e=>e.idleSince!==void 0&&!e.session?.isRetired()),e=>{for(let n of t)n.session&&!n.leased&&!n.quarantined&&n.queued===0&&isWorkerIdleForPressure(n.idleSince,e)&&retireIdleSlot(n)}),assertBrokerOpen=e=>{if(e.transport.kind===`broker`&&i.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 r)e();throw t}}async function selectScopedReadWorker(e,i){assertBrokerOpen(i);let a=e.mode===`operation`&&(e.command.type===`pageCache.begin`||e.command.type===`pageCache.step`),s=QA.getStore();if(a){if(!s?.active)throw Error(`Database page-cache warm requires an active read-only worker scope`);let t=n.get(s);if(t){if(!isSameSqliteReadOnlyWorkerLaunch(t.launch,i))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(i),e.signal?.throwIfAborted();let c=t.filter(e=>!e.leased&&!e.quarantined),l=c.find(e=>isSameSqliteReadOnlyWorkerLaunch(e.launch,i));if(!l&&t.length<4&&(l={launch:i,tail:Promise.resolve(),queued:0},t.push(l)),l??=c.find(e=>e.queued===0&&!e.session),l??=c.reduce((e,t)=>!e||t.queued<e.queued?t:e,void 0),l){if(a&&s){let e=l,t={started:!1};e.leased=t,n.set(s,e),s.releaseReadWorker=async()=>{try{t.started&&(await e.tail,await closeSlot(e))}finally{e.leased=void 0,n.delete(s),s.releaseReadWorker=void 0,!e.quarantined&&e.queued===0&&e.session&&!e.session.isRetired()&&(e.session.setIdle(!0),armScopedReadWorkerIdle(e));for(let e of r)e()}}}return l}if(t.every(e=>e.quarantined))throw AggregateError(t.map(e=>e.quarantined?.error),`SQLite read-only worker capacity is held by unconfirmed cleanup`);let u,d=runInDetachedAsyncContext(()=>new Promise(e=>{u=e}));r.add(u);try{await racePromiseWithAbortSignal(d,e.signal,e=>e.reason)}finally{r.delete(u)}}}function retireIdleSlot(e){clearTimeout(e.idle),e.idleSince=void 0,a();let t=runInDetachedAsyncContext(()=>closeSlot(e));return e.tail=t.catch(()=>{pM.warn(`Idle SQLite read-only worker cleanup failed`)}),t}function armScopedReadWorkerIdle(e){e.launch.transport.kind===`broker`&&i.has(e.launch.transport.owner)?retireIdleSlot(e):(e.idleSince=performance.now(),a(),e.idle=runInDetachedAsyncContext(()=>setTimeout(()=>{retireIdleSlot(e)},6e4)),e.idle.unref())}return{run:async function(t,n,r,i=trackSqliteRead(n)){let s=n.mode===`operation`&&(n.command.type===`pageCache.begin`||n.command.type===`pageCache.step`),c;try{c=await selectScopedReadWorker(n,r),assertBrokerOpen(r)}catch(e){throw i.completed(),e}clearTimeout(c.idle),c.idleSince=void 0,a(),c.queued++;let l=c.tail,u=runInDetachedAsyncContext(()=>racePromiseWithAbortSignal(l,n.signal,e=>e.reason)).then(async()=>{if(n.signal?.throwIfAborted(),c.quarantined)throw c.quarantined.error;if(i.started(),c.leased&&n.mode===`operation`&&n.command.type===`pageCache.begin`&&(c.leased.started=!0),(!isSameSqliteReadOnlyWorkerLaunch(c.launch,r)||c.session?.isRetired())&&await closeSlot(c),n.signal?.throwIfAborted(),c.launch=r,!c.session){c.session=e({...r,pooledRead:!0});let{closed:t}=c.session;runInDetachedAsyncContext(()=>t.then(a,a))}let l=c.session;l.setIdle(!1);try{let e=await l.run(t,n);return n.signal?.throwIfAborted(),!s&&(n.mode===`operation`&&sqliteReadOnlyOperationRequiresProcessRetirement(n.command.type)||!getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources)&&await closeSlot(c),e}catch(e){try{await closeSlot(c)}catch(t){throw createSqliteLifecycleAggregateError([e,t],`SQLite read and child cleanup failed`,e)}throw e}}).finally(()=>{i.completed(),c.queued--,!c.leased&&!c.quarantined&&c.queued===0&&c.session&&!c.session.isRetired()&&(c.session?.setIdle(!0),armScopedReadWorkerIdle(c))});return c.tail=runInDetachedAsyncContext(()=>Promise.allSettled([l,u]).then(()=>{})),u},async closeBroker(e){i.add(e),throwSettledAggregate(await Promise.allSettled(t.filter(t=>t.launch.transport.kind===`broker`&&t.launch.transport.owner===e&&t.session&&t.queued===0&&!t.leased&&!t.quarantined).map(retireIdleSlot)),`SQLite read-only broker worker cleanup failed`)}}}var pM,mM=__esmMin((()=>{cj(),Ev(),Qd(),uj(),Ep(),Yy(),_O(),W(),fj(),$A(),sM(),uO(),fM(),pM=createSubsystemLogger(`state/sqlite`)}));function resolveSqliteInspectionBudget(e,t,n){let r=resolveTimerTimeoutMs(hM+Math.ceil(40*Number(n??0)/gM)*1e3,hM),i=n===void 0?`unknown size`:formatByteSize(Number(n),{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:n<1024n?0:1});return r>hM&&_M.debug(`SQLite ${e} for ${t}: ${i}, budget ${r/1e3} seconds`),{timeoutMs:r,size:i}}function readSqliteInspectionBudget(e,t,n){let i=n;try{i??=r.statSync(t,{bigint:!0}).size;for(let e of[`-wal`,`-shm`,`-journal`])try{i+=r.statSync(t+e,{bigint:!0}).size}catch(e){if(!w(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,i)}async function readSqliteInspectionBudgetAsync(e,t,n){let i=n;try{i??=(await r.promises.stat(t,{bigint:!0})).size;for(let e of[`-wal`,`-shm`,`-journal`])try{i+=(await r.promises.stat(t+e,{bigint:!0})).size}catch(e){if(!w(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,i)}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 QA.getStore()?.deadlineOwnedByCaller===!0}function sqliteReadOnlyWorkerArgv(e,t){let{moduleUrl:n,runtimeGeneration:r}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(t.mode===`content-version`||t.mode===`file-generation`?`sqliteSourceRevision`:`sqliteReadOnly`));return{runtimeGeneration:r,argv:[...resolveForwardedNodeCompilerArgs(),...resolveRuntimeWorkerArgv(n),Ny,...sqliteReadOnlyWorkerRequestArgs(e,t)]}}function createScopedSqliteReadOnlyWorker(e){let t=resolveRuntimeProcessEntrypointUrl(`sqliteReadOnly`);return runInDetachedAsyncContext(()=>createSqliteReadOnlyWorkerSession({...e,argv:[...resolveRuntimeWorkerArgv(resolveRuntimeWorkerGenerationUrl(t,e.runtimeGeneration)),Ny,`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:hM}))}function runSqliteReadOnlyWorkerSync(e,t,n=`sync`,r){assertChildRuntimeAvailable();let{timeoutMs:i,size:a}=readSqliteInspectionBudget(`read-only snapshot`,e),s=re(process.execPath,sqliteReadOnlyWorkerArgv(e,{mode:n,stagingRoot:t,expectedSourceIdentity:r}).argv,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,env:resolveNodeCompileCacheEnv(),maxBuffer:iM,timeout:i,killSignal:`SIGKILL`}),c=classifyChildRuntimeFailure({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(w(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)}var hM,gM,_M,vM=__esmMin((()=>{Yu(),Uu(),uA(),vp(),Ev(),TA(),Qd(),aA(),pA(),H(),FA(),Fy(),qD(),YD(),Hy(),ZA(),$A(),mM(),oM(),sM(),hM=3e5,gM=33554432,_M=createSubsystemLogger(`state/sqlite`),createSqliteReadOnlyWorkerPool(createScopedSqliteReadOnlyWorker)}));function readFiniteSqliteNumber(e){let t=typeof e==`bigint`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}var yM=__esmMin((()=>{BigInt(2**53-1)}));function checkpoint(e,t){return e.prepare(`PRAGMA wal_checkpoint(${t});`).get()}function truncateSqliteWal(e,t){let n=checkpoint(e,`TRUNCATE`),r=readFiniteSqliteNumber(n?.busy??(n?Object.values(n)[0]:void 0));if(r===void 0)throw Error(`SQLite checkpoint returned an invalid result for ${t}.`);if(r!==0)throw new SqliteWalCheckpointBusyError(`SQLite checkpoint remained busy for ${t}. Stop OpenClaw and retry.`)}var SqliteWalCheckpointBusyError,bM=__esmMin((()=>{B(),H(),Xy(),yM(),Pv(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWalCheckpointListeners`),()=>/* @__PURE__ */ new Set),SqliteWalCheckpointBusyError=class extends Error{}})),xM=__esmMin((()=>{LA()})),SM=__esmMin((()=>{})),CM=__esmMin((()=>{SM()}));function createPrivateWindowsDirectory(e){let t=!1;try{ke(S.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof Re&&e.code===`already-exists`?markPrivateDirectoryCreationRefused(e):e}}var wM=__esmMin((()=>{tM()}));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&&S.isAbsolute(t))return resolvePreferredOpenClawTmpDir({preferredDir:S.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&&S.isAbsolute(e))??S.join(resolveRequiredOsHomeDir(e),i);return resolvePreferredOpenClawTmpDir({preferredDir:S.join(a,`openclaw`),tmpdir:()=>a})}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return r.mkdtempSync(S.join(e,t))}catch(e){throw markPrivateDirectoryCreationRefused(e)}let n=S.join(e,`${t}${Se()}`);return createPrivateWindowsDirectory(n),n}var TM=__esmMin((()=>{pp(),tM(),rM(),j_(),wM()}));function readCanonicalTableDefinition(e,t){if(!/^CREATE TABLE\b/iu.test(e)||hasUnquotedSqlKeyword(e,/\bAS\b/giu))return;let n=parseSqliteTableDefinition(e,t);return[...n.columns.values()].every(e=>{let t=readSqlToken(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(isPostgresSqlConnection(e))return new Set(getPostgresPhysicalFacts(e)?.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=EM.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,EM.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(isPostgresSqlConnection(e)||sqlitePrimaryResultCode(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(isPostgresSqlConnection(e)){let n=getPostgresPhysicalFacts(e)?.catalog.find(e=>e.table===t&&e.kind===`primaryKey`)?.value;return Array.isArray(n)?n.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=readSqlToken(e,0);return t&&readTableConstraintKeyword(e,t)===`PRIMARY`});if(!e)return[...r.columns].flatMap(([e,t])=>hasUnquotedSqlKeyword(t,/\bPRIMARY\s+KEY\b/giu)?[e]:[]);let t=findSqlCharacter(e,`(`),n=splitSqlList(e.slice(t+1,findSqlClosingParenthesis(e,t))).map(e=>normalizeSqlIdentifier(readSqlToken(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(isPostgresSqlConnection(e))return getPostgresPhysicalFacts(e)?.catalog.some(e=>e.table===t&&e.kind===`table`)??!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)}var EM,$=__esmMin((()=>{kx(),Du(),gu(),kb(),dy(),Y(),SS(),uy(),EM=/* @__PURE__ */ new WeakMap})),DM=__esmMin((()=>{J(),Hx(),Y(),$()}));function parseReleaseVersion(e){let t=e.trim(),n=OM.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))}var OM,kM=__esmMin((()=>{OM=/^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/}));function walkUpFrom(e,t,n){let r=S.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=S.dirname(r);if(t===r)break;r=t}return null}function readGitMetadataFile(e,t=1048576){let n=r.openSync(e,r.constants.O_RDONLY|(r.constants.O_NONBLOCK??0));try{let e=r.fstatSync(n);if(!e.isFile()||e.size>t)throw Error(`Git metadata is not a bounded regular file`);let i=je(n,Math.min(e.size,t));if(i.length!==e.size)throw Error(`Git metadata changed during its read`);return i}finally{r.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let n=readGitMetadataFile(e),r=n.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!bt(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 S.isAbsolute(i)?i:`${S.dirname(e)}${S.sep}${i}`}function readGitDirectoryPointer(e,t=``){return r.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=S.join(e,`.git`);try{let e=r.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?S.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){let n=r.openSync(e,r.constants.O_RDONLY|(r.constants.O_NONBLOCK??0));try{if(!r.fstatSync(n).isFile())throw Error(`Git metadata is not a regular file`);let e=Buffer.alloc(t),i=Me(n,e,0);return e.subarray(0,i).toString(`utf-8`)}finally{r.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=S.dirname(e),n=S.join(t,`commondir`);try{return readGitDirectoryPointer(n)}catch(e){if(!isMissingPathError(e)||r.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(!isMissingPathError(e))throw e;r.add(i)}}if(r.size===0)return n;try{let t=readGitMetadataFile(S.join(e,`packed-refs`),2**53-1).toString(`utf8`),i=RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(escapeRegExp).join(`|`)})(?=\\s|$)`,`gm`);for(let[,e,a]of t.matchAll(i))r.delete(a)&&n.set(a,e)}catch(e){if(!isMissingPathError(e))throw e}return n}function resolveRefPath(e,t){if(!t.startsWith(`refs/`)||t.split(/[/]/).includes(`..`))return null;let n=S.resolve(e,t),r=S.relative(e,n);return!r||r.startsWith(`..`)||S.isAbsolute(r)?null:n}var AM=__esmMin((()=>{Sp(),Xy(),ap()}));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}var formatCommit,jM,resolveCommitSearchDir,cacheGitCommit,resolveGitLookupDepth,readCommitFromGit,readCommitFromPackageJson,readCommitProbe,readCommitFromBuildInfo,readLoadedCommit,resolveCommitHash,MM=__esmMin((()=>{D(),Lt(),Xy(),AM(),gp(),MO(),formatCommit=e=>{let t=e?.match(/[0-9a-fA-F]{7,40}/);return t?normalizeLowercaseStringOrEmpty(t[0].slice(0,7)):null},jM=new LruCache(256),resolveCommitSearchDir=e=>{if(e.cwd)return S.resolve(e.cwd);if(e.moduleUrl)try{return S.dirname(Ie(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(jM.set(e,t),t),resolveGitLookupDepth=(e,t)=>{if(!t)return;let n=S.relative(t,e);if(!(n.startsWith(`..`)||S.isAbsolute(n)))return(n?n.split(S.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 t=e(import.meta.url)(`../../package.json`);return formatCommit(t.gitHead??t.githead??null)}catch{return null}},readCommitProbe=(e,t,n)=>{try{for(let r of t){let t=Ie(new URL(r,e)),i;try{i=readGitMetadataPrefix(t,1024)}catch(e){if(isMissingPathError(e))continue;return null}try{let e=asNullableRecord(JSON.parse(i))?.[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=jM.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 readStringFromJsonCandidates(t,n,r,i=!1){try{let a=e(t);for(let e of n)try{let t=a(e),n=normalizeOptionalString(t[r]);if(!n||i&&t.name!==NM)continue;return n}catch{}return null}catch{return null}}function firstNonEmpty(...e){for(let t of e){let e=normalizeOptionalString(t);if(e&&e.toLowerCase()!==`undefined`&&e.toLowerCase()!==`null`)return e}}function readVersionFromPackageJsonForModuleUrl(e){return readStringFromJsonCandidates(e,PM,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,FM,`version`)}function readBuildProvenanceForModuleUrl(t){try{let n=e(t);for(let e of FM)try{let t=n(e),r=normalizeOptionalString(t.buildId);if(r&&r.length<=96){let i={buildId:r};for(let e of[`version`,`commit`,`builtAt`]){let n=normalizeOptionalString(t[e]);n&&(i[e]=n)}try{i.buildInfoPath=n.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`}function resolveRuntimeServiceCommit(){return IM}var NM,PM,FM,IM,LM,RM=__esmMin((()=>{Lt(),MM(),NM=`openclaw`,PM=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],FM=[`../build-info.json`,`../../build-info.json`,`./build-info.json`],readBuildProvenanceForModuleUrl(import.meta.url),IM=resolveLoadedCommitHash({moduleUrl:import.meta.url}),LM=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION})})),zM,BM,StartupMaintenanceRequiredError,VM=__esmMin((()=>{zM=`gateway.maintenance_required`,BM={"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`},StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n),this.kind=e,this.code=zM,this.name=`StartupMaintenanceRequiredError`}get reason(){return BM[this.kind]}}}));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 ${LM} (${e})`:`OpenClaw ${LM}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,LM)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){let s=isNewerSqliteWriterVersion(i),c=s?`; it is newer than this Gateway (${LM}).`: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!==LM)?`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 ${WS}.`)}var HM,SqliteSchemaVersionError,UM=__esmMin((()=>{kM(),Z(),RM(),Du(),MO(),VM(),HM=`SqliteSchemaVersionError`,SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e),this.name=HM}}}));function runWithSessionControllerCleanup(e){return WM.exit?WM.exit(e):e()}var WM,GM=__esmMin((()=>{B(),WM=resolveGlobalSingleton(Symbol.for(`openclaw.sessionControllerCleanupContext`),()=>({}))}));function nextMaintenanceSlot(e,t,n){return e+(Math.floor(Math.max(0,t-e)/n)+1)*n}var KM,qM,GatewayScheduler,JM=__esmMin((()=>{Ev(),GM(),SO(),It(),Qd(),_O(),ef(),KM=createSubsystemLogger(`gateway/scheduler`),qM={now:()=>Date.now(),monotonicNow:()=>performance.now(),arm:(e,t)=>{let n=setTimeout(()=>{runWithMainThreadTask(`scheduler:wake`,()=>{e()})},t);return n.unref(),()=>clearTimeout(n)}},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??qM}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(),materializeErrorStack(e.signal.reason),materializeErrorStack(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(()=>C.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(),materializeErrorStack(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 t=this.now(),n=Math.min(2147483647,Math.max(0,Math.ceil(e-t)));this.cancelTimer=runInDetachedAsyncContext(()=>this.clock.arm(()=>this.wake(t+n),n))}}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&&KM.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){KM[e.everyMs===void 0?`debug`:`trace`](`running ${e.id}`);let t=createDeferredCore(),n=new xO;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(()=>runWithMainThreadTask(e.diagnosticName,()=>n.run(e.run)))}catch(t){KM.error(`${e.id} failed: ${String(t)}`)}if(!r&&!n.hasPendingWork)finish();else return Promise.resolve(r).catch(t=>KM.error(`${e.id} failed: ${String(t)}`)).then(()=>xO.runWhenAllIdle(()=>[n],()=>n.drain())).finally(finish),t.promise}}})),YM,XM=__esmMin((()=>{Ev(),H(),YM=/* @__PURE__ */ new Set([26985,20859,4283649346,4266872130]),[...YM],createSubsystemLogger(`infra/sqlite-wal`)})),ZM=__esmMin((()=>{Nx(),kb(),NS()})),QM=__esmMin((()=>{H()}));function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=$M.get(e)?.stopCheckpointTick;$M.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return $M.get(e)?.execute!==void 0}var $M,eN=__esmMin((()=>{B(),NS(),$M=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap)}));function detachEmptySqliteExitGroup(e){e.pending.size>0||(tN===e&&(tN=void 0),process.removeListener(`exit`,e.dispatch))}function registerSqliteCacheExitClose(e){let t={close:e},n=tN;if(!n||process.listeners(`exit`).at(-1)!==n.dispatch){let e=/* @__PURE__ */ new Set([t]),r={pending:e,dispatch:()=>{let t=[...e];e.clear(),detachEmptySqliteExitGroup(r);for(let e of t)try{e.close()}catch{}}};process.on(`exit`,r.dispatch),tN=n=r}else n.pending.add(t);let r=n;return()=>{r.pending.delete(t),detachEmptySqliteExitGroup(r)}}var tN,nN=__esmMin((()=>{Uu(),Ev(),Qd(),JM(),Du(),Nx(),J(),kb(),W(),Hx(),bM(),XM(),ZM(),QM(),eN(),new Int32Array(new SharedArrayBuffer(4)),createSubsystemLogger(`infra/sqlite-wal`),new GatewayScheduler})),rN=__esmMin((()=>{DM(),Z(),LA(),Nx(),W(),ZA(),NS(),UM(),nN()}));function sqliteSnapshotSourceFileSize(e){try{let t=r.statSync(e);return t.isFile()?t.size:0}catch(e){if(w(e,`ENOENT`))return 0;throw e}}function waitForSnapshotRetrySync(e){if(e+1>=10)return;let t=Math.min(aN,iN*2**e);t>0&&Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}var iN,aN,oN=__esmMin((()=>{H(),iN=10,aN=80}));function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=S.resolve(e);for(;;)try{return r.statSync(t).isDirectory()?t:S.dirname(t)}catch{let e=S.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=r.statfsSync(t),i=finiteNonNegativeNumber(n.bsize),a=finiteNonNegativeNumber(n.bavail);if(i===null||a===null)return null;let s=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:i*a,totalBytes:s===null?null:i*s}}catch{return null}}var sN=__esmMin((()=>{})),cN,lN,uN=__esmMin((()=>{B(),cN=`OpenClawQuarantineReadCleanupError`,lN=resolveGlobalSingleton(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=cN}})}));function markOpenClawStateDatabaseFailure(e,t){dN.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),dN.get(e)===t)return e;n.push(e.cause),e instanceof AggregateError&&n.push(...e.errors)}}var dN,fN=__esmMin((()=>{B(),dN=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseFailurePaths`),()=>/* @__PURE__ */ new WeakMap)})),DuplicateAgentError,pN=__esmMin((()=>{DuplicateAgentError=class extends Error{}})),mN,AuthProfileStoreUnreadableError,hN=__esmMin((()=>{Op(),mN=`openclaw doctor --fix`,AuthProfileStoreUnreadableError=class extends Error{constructor(e){super(`Auth profile store ${shortenHomePath(e)} is unreadable; run ${mN}.`),this.databasePath=e,this.code=`AUTH_PROFILE_STORE_UNREADABLE`,this.action=mN,this.name=`AuthProfileStoreUnreadableError`}}})),McpOAuthStoreCorruptionError,gN=__esmMin((()=>{McpOAuthStoreCorruptionError=class extends Error{constructor(e,t,n){super(`MCP OAuth store ${e} is invalid: ${t}`,n),this.name=`McpOAuthStoreCorruptionError`}}})),_N,WorkspaceAliasRepointedError,vN=__esmMin((()=>{Op(),_N=`WORKSPACE_ALIAS_REPOINTED`,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=_N,this.name=`WorkspaceAliasRepointedError`,this.aliasPath=e.aliasPath,this.storedWorkspacePath=e.storedWorkspacePath,this.currentWorkspacePath=e.currentWorkspacePath}}})),WorktreeRemovalContentionError,WorktreeRemovalLockError,SessionWorktreeSourceChangedError,SessionWorktreeLifecycleError,yN=__esmMin((()=>{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,bN=__esmMin((()=>{SessionGoalOperationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SessionGoalOperationError`}}})),SessionCanonicalKeyMigrationRequiredError,xN=__esmMin((()=>{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,SqliteTranscriptMutationConflictError,SessionEntryLifecycleUpsertConflictError,SN=__esmMin((()=>{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,CN=__esmMin((()=>{SessionPendingInputCustodyError=class extends Error{}})),SessionTranscriptReadFenceError,wN=__esmMin((()=>{SessionTranscriptReadFenceError=class extends Error{constructor(e){super(e),this.name=`SessionTranscriptReadFenceError`}}})),SessionTranscriptWriterClaimReboundError,TN=__esmMin((()=>{SessionTranscriptWriterClaimReboundError=class extends Error{constructor(e){super(`session writer claim changed before transcript persistence`,{cause:e}),this.name=`SessionTranscriptWriterClaimReboundError`}}})),ModelAccountConnectAuthorityError,EN=__esmMin((()=>{ModelAccountConnectAuthorityError=class extends Error{constructor(){super(`This account action requires a current authorized connection; reconnect and try again.`)}}})),WorkerSessionAlreadyAttachedError,DN=__esmMin((()=>{WorkerSessionAlreadyAttachedError=class extends Error{constructor(e,t){super(`Session ${e} is already attached to worker environment ${t}`),this.sessionId=e,this.environmentId=t}}})),SqliteJsonlReadBudgetExceededError,ON=__esmMin((()=>{SqliteJsonlReadBudgetExceededError=class extends Error{}})),PluginBlobStoreError,kN=__esmMin((()=>{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 AN=__esmMin((()=>{})),PluginStateStoreError,jN=__esmMin((()=>{RM(),AN(),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:E,version:LM},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,MN=__esmMin((()=>{SecretStoreValidationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SecretStoreValidationError`}}})),NN,ModelSelectionLockedError,PN=__esmMin((()=>{NN=`Model selection is locked for this session.`,ModelSelectionLockedError=class extends Error{constructor(e=NN){super(e),this.name=`ModelSelectionLockedError`}}})),SkillUploadRequestError,FN=__esmMin((()=>{SkillUploadRequestError=class extends Error{constructor(...e){super(...e),this.name=`SkillUploadRequestError`}}})),SkillLibraryError,IN=__esmMin((()=>{SkillLibraryError=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.currentRevision=n,this.name=`SkillLibraryError`}}})),OpenClawAgentDatabaseMediaMigrationRequiredError,LN=__esmMin((()=>{VM(),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`}}}));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 OpenClawStateDatabaseSchemaMigrationRequiredError,RN=__esmMin((()=>{VM(),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`}}})),OpenClawStateLeaseError,zN=__esmMin((()=>{OpenClawStateLeaseError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`OpenClawStateLeaseError`,this.code=t.code,this.loss=t.loss}}})),SessionMetadataUnavailableError,BN=__esmMin((()=>{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`}}}));function isMessageOnlyErrorIdentity(e){return typeof e.type==`string`&&Object.hasOwn(VN,e.type)}function createError(e){if(isMessageOnlyErrorIdentity(e)){let t=VN[e.type];return new t(e.message)}switch(e.type){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 zD(e.databasePath);case`ownership-metadata`:return new OpenClawStateOwnershipMetadataError(e.databasePath,``);case`external-ownership`:return new OpenClawStateExternalOwnershipError(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)}var VN,HN=__esmMin((()=>{pN(),hN(),gN(),vN(),yN(),bN(),xN(),SN(),CN(),wN(),TN(),EN(),DN(),UD(),ON(),W(),UM(),VM(),kN(),jN(),MN(),PN(),FN(),IN(),LN(),RN(),zN(),BN(),VN={"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,coordinator:Dv,ownership:OpenClawStateOwnershipError,"newer-schema":SqliteSchemaVersionError,"jsonl-read-budget":SqliteJsonlReadBudgetExceededError,"range-error":RangeError,"syntax-error":SyntaxError,"type-error":TypeError}}));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)||isSqliteLockError(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 SqliteWorkerError(e.message,e.code);return e.type===`error`?t:retainSqliteWorkerErrorCode(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&&markSqliteNativeOpenFailure(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}}function retainOpenClawStateWorkerErrorPayload(e,t){t&&UN.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=UN.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)}var UN,WN=__esmMin((()=>{kb(),bb(),B(),uN(),fN(),HN(),UN=resolveGlobalSingleton(Symbol.for(`openclaw.sharedStateWorkerErrorPayloads`),()=>/* @__PURE__ */ new WeakMap)})),GN=__esmMin((()=>{WN(),W(),sM()})),KN=__esmMin((()=>{WN(),W()})),qN=__esmMin((()=>{xA(),SA()})),JN,YN=__esmMin((()=>{JN=/* @__PURE__ */ Error(`Native worker port validation reached the live sentinel`),JN.stack=void 0})),XN=__esmMin((()=>{ef(),fO(),YN()})),ZN,QN=__esmMin((()=>{Fy(),ZN={"catalog-page.worker.js":`catalog`,"code-mode.worker.js":`codeMode`,"disk-budget.worker.js":`diskBudget`,"document-extractor.worker.js":`document`,"manager-index.worker.js":`memoryIndex`,"manager-search.worker.js":`memorySearch`,"memory-index.worker.js":`memoryIndex`,"memory-search.worker.js":`memorySearch`,"run.worker.js":`teamReports`,"session-history.worker.js":`sessionHistory`},new Map([...Object.entries(Py).map(([e,t])=>[ce(t.distWorkerPath),e]),...Object.entries(ZN)])})),$N=__esmMin((()=>{SA(),ef(),$O(),xA(),XN(),QN()}));async function closeDefaultRetainedNativeWorkerSource(){await eP.defaultSource?.close()}var eP,tP=__esmMin((()=>{wA(),qN(),Qd(),B(),Yy(),ef(),qD(),YD(),Hy(),J(),$O(),fO(),$N(),YN(),eP=resolveGlobalSingleton(Symbol.for(`openclaw.nativeWorkerLifetimes`),()=>({nextId:0,sources:/* @__PURE__ */ new WeakMap,defaultBroker:{}}),closeDefaultRetainedNativeWorkerSource)}));function resolveWorkerComputeLimit(){return Math.max(1,Ze()-1)}function resolveWorkerPoolSize(e){return Math.min(e===`reader`||e===`file-reader`?2:e===`compute`?4:1,resolveWorkerComputeLimit())}function resolveSqliteBrokerWorkerCount(){return 2}var nP=__esmMin((()=>{resolveWorkerPoolSize(`reader`)})),rP=__esmMin((()=>{cj(),nP()}));function createLazyPromiseLoader(e,t={}){let n,createPromise=()=>{let r=Promise.resolve().then(e);return t.cacheRejections!==!0&&r.catch(()=>{n===r&&(n=void 0)}),r};return{load(){return n??=createPromise(),n},peek(){return n},clear(){n=void 0}}}var iP=__esmMin((()=>{}));function createLazyRuntimeSurface(e,t){let n=createLazyPromiseLoader(()=>e().then(t),{cacheRejections:!0});return Object.assign(n.load,{peek:n.peek,clear:n.clear})}function createLazyRuntimeModule(e){return createLazyRuntimeSurface(e,e=>e)}var aP=__esmMin((()=>{iP()}));function getDatabaseEngineSelection(){return sP.getStore()??oP.selection}function getDatabaseEngineInput(e){let t=getDatabaseEngineSelection();return t?.effectiveEngines[e]===`postgres`?t.postgres:void 0}var oP,sP,cP=__esmMin((()=>{B(),oP=resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineSelection`),()=>({})),sP=resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineMaintenanceSelection`),()=>new C)}));function recordPostgresPoolFailure(e){!uP.nextStep&&!uP.endpoints?.nextStep&&(uP.failure??=e)}var lP,uP,dP=__esmMin((()=>{B(),lP=lt,uP=resolveGlobalSingleton(Symbol.for(`openclaw.postgresIoPool`),()=>({endpoints:lP?.postgresPool,workers:void 0,nextStep:void 0,ready:[],refresh:void 0,failure:void 0}))}));function startPool(){if(!at&&recordPostgresPoolSelfRoot()){let e={threadId:E,owner:workerScriptName(process.argv[1]??``)};fP.publish(e);let t=new et(`openclaw.postgres.pool.self-root`);t.unref(),t.postMessage(e),t.close(),createSubsystemLogger(`postgres`).warn(`PostgreSQL worker ${e.owner} (thread ${E}) has no inherited pool; starting its own four I/O services.`)}let e=new SharedArrayBuffer(4),t=Array.from({length:4},()=>({channel:new tt,signal:new SharedArrayBuffer(8),peers:[]}));for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let{port1:r,port2:i}=new tt;t[e].peers.push({port:r,signal:t[n].signal}),t[n].peers.push({port:i,signal:t[e].signal})}let n={services:t.map(({channel:e,signal:t})=>({port:e.port1,signal:t})),allocation:e,nextStep:uP.nextStep},r=resolveRuntimeProcessEntrypointUrl(`postgresBridge`),i=resolveRuntimeWorkerThreadExecArgv(r),a=[];uP.endpoints=n,uP.workers=a;let launch=e=>{let n=t[e],c=new Int32Array(n.signal),l=!1,u=new rt(r,{workerData:{host:n.channel.port2,signal:n.signal,peers:n.peers},transferList:[n.channel.port2,...n.peers.map(({port:e})=>e)],execArgv:i});trackNativeWorkerForCpu(u,r),u.unref(),n.channel.port1.unref(),a[e]=u;let d=new Promise((e,t)=>{u.once(`error`,t),u.once(`exit`,()=>t(/* @__PURE__ */ Error(`PostgreSQL I/O service exited before readiness.${uP.nextStep?` Run ${uP.nextStep}.`:``}`))),u.once(`message`,()=>e())});d.catch(()=>{}),uP.ready[e]=d,u.on(`error`,()=>{}),u.once(`exit`,()=>{l=!0,Atomics.store(c,1,1),Atomics.notify(c,1),s.add(e)}),Promise.resolve(Atomics.waitAsync(c,1,0).value).then(async()=>{l||await u.terminate()})},s=/* @__PURE__ */ new Set;uP.refresh=()=>{for(let e of s){s.delete(e);let r={channel:new tt,signal:new SharedArrayBuffer(8),peers:[]};t[e]=r,n.services[e]={port:r.channel.port1,signal:r.signal};for(let n=0;n<t.length;n++){if(n===e)continue;let i=t[n],{port1:s,port2:c}=new tt;r.peers.push({port:s,signal:i.signal}),a[n].postMessage({watch:{port:c,signal:r.signal}},[c])}launch(e)}};try{for(let e=0;e<t.length;e++)launch(e)}catch(e){throw closePostgresPool(),e}return n}function getPostgresPool(){return uP.nextStep||uP.refresh?.(),uP.endpoints??startPool()}function createPostgresPoolEndpoints(e=getDatabaseEngineSelection()){if(!uP.endpoints&&(!e||!Object.values(e.effectiveEngines).includes(`postgres`)))return;let t=getPostgresPool();return{...t,services:t.services.map(({port:e,signal:t})=>{let n=new tt;return e.postMessage({host:n.port2},[n.port2]),{port:n.port1,signal:t}})}}function postgresPoolTransferList(e){return e?.services.map(({port:e})=>e)??[]}function selectPostgresPoolService(){let e=getPostgresPool(),t=(Atomics.add(new Uint32Array(e.allocation),0,1)>>>0)%4;return{...e.services[t],nextStep:e.nextStep}}async function closePostgresPool(){let e=uP.workers;uP.workers=void 0;for(let{port:e}of uP.endpoints?.services??[])e.close();uP.endpoints=void 0,uP.ready=[],uP.refresh=void 0,uP.failure=void 0,await Promise.all(e?.map(e=>e.terminate())??[])}var fP,pP=__esmMin((()=>{Ev(),cP(),qD(),Hy(),$O(),hf(),dP(),fP=$e(`openclaw.postgres.pool.self-root`)}));function claimStoreWriterTurn(e){let t=we.now();if(_P.reset||(_P.started=0,_P.startedAt=t,_P.reset=dt().then(()=>{_P.reset=void 0})),!e&&(_P.wait||_P.started>=mP||t-_P.startedAt>=hP))return _P.wait??=dt().then(()=>{_P.wait=void 0});_P.started++}function isActiveStoreWriter(e,t,n){if(!e.has(t))return!1;let r=gP.getStore();for(;r;){if(r.active&&r.queues===e&&r.storePath===t){let e=r.keys;if(e&&(!n||[...n].some(t=>!e.has(t))))throw Error(`Cannot expand an active store writer's keys`);return!0}r=r.parent}return!1}async function runActiveStoreWriter(e,t,n,r,i){let a={active:!0,parent:gP.getStore(),queues:e,storePath:t,keys:i};r&&(r.reentrant=!1,r.startedAt=we.now());try{return await runWithAsyncStore(gP,a,n)}finally{r&&(r.finishedAt=we.now()),a.active=!1}}async function drainStoreWriterQueue(e,t){let n=e.get(t);if(!n||n.drainPromise)return;let r=createDeferredCore();n.drainPromise=r.promise;let i=/* @__PURE__ */ new Set,a=0,s=createDeferredCore();n.wake=()=>s.resolve();let c=!0;try{for(;n.pending.length>0||a>0;){let e=/* @__PURE__ */ new Set,t;for(let r of n.pending){let n=r.keys;if(!n){a===0&&e.size===0&&(t=r);break}if(![...n].some(t=>i.has(t)||e.has(t))){t=r;break}for(let t of n)e.add(t)}if(!t){await s.promise,s=createDeferredCore();continue}let r;for(;r=claimStoreWriterTurn(c);)await r;c=!1;let l=n.pending.indexOf(t);if(l<0)continue;if(n.pending.splice(l,1),!t.keys){await t.fn().then(t.resolve,t.reject);continue}let u=t.keys;for(let e of u)i.add(e);a++;let finish=()=>{for(let e of u)i.delete(e);a--,n.wake?.()};t.fn().then(e=>{finish(),t.resolve(e)},e=>{finish(),t.reject(e)})}}finally{n.drainPromise=null,n.wake=void 0,e.delete(t),r.resolve()}}async function runQueuedStoreWrite(e){if(!e.storePath||typeof e.storePath!=`string`)throw Error(`${e.label}: storePath must be a non-empty string, got ${JSON.stringify(e.storePath)}`);e.signal?.throwIfAborted();let t=e.keys?.length?new Set(e.keys):void 0;if(e.reentrant===!0&&isActiveStoreWriter(e.queues,e.storePath,t)){e.timing&&(e.timing.reentrant=!0,e.timing.startedAt=we.now());try{return await e.fn()}finally{e.timing&&(e.timing.finishedAt=we.now())}}let n=C.snapshot(),r=e.queues.get(e.storePath);r||(r={pending:[],drainPromise:null},e.queues.set(e.storePath,r));let i=r,detach=()=>{},a=new Promise((r,a)=>{detach=()=>e.signal?.removeEventListener(`abort`,abort);let abort=()=>{let t=i.pending.indexOf(s);t!==-1&&(i.pending.splice(t,1),s.reject(e.signal?.reason),i.wake?.())},s={keys:t,fn:async()=>(detach(),await n(runActiveStoreWriter,e.queues,e.storePath,e.fn,e.timing,t)),resolve:e=>r(e),reject:a};i.pending.push(s),i.wake?.(),e.signal?.addEventListener(`abort`,abort,{once:!0}),runInDetachedAsyncContext(()=>void drainStoreWriterQueue(e.queues,e.storePath))});return e.signal&&a.then(detach,detach),await a}var mP,hP,gP,_P,vP=__esmMin((()=>{nd(),It(),Qd(),B(),mP=4,hP=4,gP=resolveGlobalSingleton(Symbol.for(`openclaw.activeStoreWriters`),()=>new C),_P=resolveGlobalSingleton(Symbol.for(`openclaw.storeWriterTurn`),()=>({started:0,startedAt:0,reset:void 0,wait:void 0}))})),yP,bP=__esmMin((()=>{B(),vP(),yP=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseWriteAdmission`),()=>({queues:/* @__PURE__ */ new Map})),yP.queues})),xP=__esmMin((()=>{cj(),B(),bP(),resolveGlobalSingleton(Symbol.for(`openclaw.workerTaskPools`),()=>/* @__PURE__ */ new Set)}));async function runBestEffortCleanup(e){try{return await e.cleanup()}catch(t){try{e.onError?.(t)}catch{}return}}var SP=__esmMin((()=>{}));function readDarwinImagePath(e){let t={encoding:`utf8`,timeout:2e3},n=re(`/usr/sbin/lsof`,[`-a`,`-p`,String(e),`-d`,`txt`,`-Fn`],t),r=n.status===0?/^n(\/.+)$/mu.exec(n.stdout)?.[1]:void 0,i=r&&re(`/bin/ps`,[`-o`,`ucomm=`,`-p`,String(e)],t);return i&&i.status===0&&i.stdout.trim()===S.basename(r).slice(0,16)?r:void 0}function isRedactedSystemImage(e){if(!e.startsWith(`/System/`))return!1;let t=re(`/usr/bin/codesign`,[`-d`,`--entitlements`,`-`,e],{encoding:`utf8`,timeout:2e3});return t.status===0&&wP.test(t.stdout)}function readCommandWithServiceMarker(e){try{return pe(e,{environmentKeys:[`OPENCLAW_SERVICE_MARKER`]})}catch(t){if(!(t instanceof ae)||t.code!==`incomplete`)throw t;let n=pe(e);return n&&[n.executable,n.argv[0]??``].some(e=>isNodeRuntime(e)||isBunRuntime(e)||S.basename(e)===`tsx`)?{...n,serviceMarkerUnavailable:!0}:n}}function readDarwinProcessCommand(e,t,n={}){try{let t=n.serviceMarker===!1?pe(e):readCommandWithServiceMarker(e);if(!t)return;let r=t.environment.OPENCLAW_SERVICE_MARKER;return{argv:[...t.argv],executable:t.executable,...r===void 0?{}:{serviceMarker:r},...`serviceMarkerUnavailable`in t?{serviceMarkerUnavailable:!0}:{}}}catch(n){if(!(n instanceof ae))throw n;if(n.code===`layout-mismatch`||n.code===`incomplete`){let r=readDarwinImagePath(e);if(r&&isRedactedSystemImage(r))return{argvUnavailable:!0,executable:r,...t?{owner:t}:{}};throw n}if(n.code===`unsupported-platform`&&process.platform===`darwin`)throw Error(`Cannot inspect Darwin process arguments under Rosetta; run OpenClaw with native arm64 Node.js.`,{cause:n});if(n.code!==`access-denied`&&n.code!==`operation-failed`)throw n;if(isPidDefinitelyDead(e))return;if(t===`different`)return CP||(CP=!0,createSubsystemLogger(`process/census`).debug(`Unreadable Darwin arguments for another UID do not establish capture custody.`,{pid:e,code:n.code})),{argvUnavailable:!0,owner:t};throw Error(`Could not classify PID ${e}: cannot inspect Darwin arguments (${n.code}).`,{cause:n})}}var CP,wP,TP=__esmMin((()=>{Vy(),Ev(),on(),CP=!1,wP=/\[Key\] com\.apple\.private\.no-read-procargs\s*\[Value\]\s*\[Bool\] true|<key>com\.apple\.private\.no-read-procargs<\/key>\s*<true\/>/u}));function parseWindowsNativeArguments(e){let t=[],n=0;for(;n<e.length;){for(;/[ \t]/.test(e.charAt(n));)n++;if(n===e.length)break;let r=``,i=!1;for(;n<e.length;){let t=0;for(;e[n]===`\\`;)t++,n++;if(e[n]===`"`)r+=`\\`.repeat(Math.floor(t/2)),t%2==1?(r+=`"`,n++):i&&e[n+1]===`"`?(r+=`"`,n+=2):(i=!i,n++);else{if(r+=`\\`.repeat(t),n===e.length||!i&&/[ \t]/.test(e.charAt(n)))break;r+=e.charAt(n++)}}t.push(r)}return t}function parseWindowsNativeCommandLine(e){if(e.includes(`\0`))return null;let t=0;for(;/[ \t]/.test(e.charAt(t));)t++;if(t===e.length)return[];let n=``,r=!1;for(;t<e.length&&(r||!/[ \t]/.test(e.charAt(t)));){let i=e.charAt(t++);i===`"`?r=!r:n+=i}return r||!n?null:[n,...parseWindowsNativeArguments(e.slice(t))]}var EP=__esmMin((()=>{}));function isRosettaTranslatedProcess(){return process.platform!==`darwin`||process.arch!==`x64`?!1:(DP??=Xe.cpus()[0]?.model.includes(`Apple`)===!0,DP)}var DP,OP=__esmMin((()=>{}));function isContainerEnvironment(){return kP??=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 r.accessSync(e,r.constants.F_OK),!0}catch{}try{let e=r.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}var kP,AP=__esmMin((()=>{}));function readWindowsProcessCensus(e){return fe({timeoutMs:e,includeCommand:!0}).flatMap(({pid:e,owner:t,identity:n,command:r})=>{if(e===0||e===4||n?.exited)return[];let i=r?.executable;if(!r&&n)try{try{var a=_usingCtx();i=a.u(jt.open(e,{access:`observe`,expect:{startTimeMicros:n.startTimeMicros}}))?.imagePath}catch(e){a.e=e}finally{a.d()}}catch{}let s;if(t===`unknown`&&!n&&!r)try{se(e)}catch(e){e instanceof ae&&e.code===`access-denied`&&(s=!0)}return[{pid:e,...n?{parentPid:n.parentPid,startIdentity:String(Math.floor(n.startTimeMicros/1e3))}:{},...r?.commandLine===void 0?{}:{commandLine:r.commandLine},...i?{executable:i}:{},...r?.cwd===void 0?{}:{cwd:r.cwd},...t===`different`?{foreignOwner:!0}:{},...s?{accessDenied:s}:{}}]})}var jP=__esmMin((()=>{tf()}));function assertAppContainerSpawnSupported(t){if(process.platform===`win32`&&!(t===`ignore`||t===`inherit`||Array.isArray(t)&&t.length>=3&&t.every(e=>e!=null&&e!==`pipe`&&e!==`overlapped`&&e!==`ipc`&&!(typeof e==`number`&&e<0)))){if(!MP){MP=!0;try{let{readCurrentAppContainerSid:t}=e(import.meta.url)(`@openclaw/proc-safe/windows-token`),n=t(),r=process.versions.uv,i=Number(r.split(`.`)[0]),a=Number(r.split(`.`)[1]);n!==null&&(i<1||i===1&&a<53)&&(NP=new AppContainerSpawnUnsupportedError(r))}catch(e){Promise.resolve().then(()=>(Ev(),vv)).then(({createSubsystemLogger:t})=>{t(`process`).debug(`AppContainer token probe failed; allowing spawn`,{error:String(e)})}).catch(()=>{})}}if(NP)throw NP}}var AppContainerSpawnUnsupportedError,MP,NP,PP=__esmMin((()=>{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`}},MP=!1}));function locateWindowsRegExe(){let e=S.win32.join(FP,`System32`,`reg.exe`);return canAccessSync(e,r.constants.R_OK)?e:null}function trimTrailingSeparators(e){let t=S.win32.parse(e),n=e;for(;n.length>t.root.length&&/[\\/]/.test(n.at(-1)??``);)n=n.slice(0,-1);return n}function normalizeWindowsInstallRoot(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.includes(`\0`)||t.includes(`\r`)||t.includes(`
`)||t.includes(`;`))return null;let n=trimTrailingSeparators(S.win32.normalize(t));if(!S.win32.isAbsolute(n)||n.startsWith(`\\\\`))return null;let r=S.win32.parse(n);return!/^[A-Za-z]:\\$/.test(r.root)||n.length<=r.root.length?null:n}function getEnvValueCaseInsensitive(e,t){let n=e[t];if(n!==void 0)return n;let r=t.toUpperCase(),i=Object.keys(e).find(e=>e.toUpperCase()===r);return i?e[i]:void 0}function queryWindowsRegistryValue(e,t,n){let r=locateWindowsRegExe();if(!r)return null;for(let i of[[`/reg:64`],[]]){let a=n===void 0?LP:Math.min(LP,Math.ceil(n-performance.now()));if(a<=0)return null;assertAppContainerSpawnSupported();try{let n=te(r,[`query`,e,`/v`,t,...i],{env:resolveDiagnosticProcessEnv(),encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:a,windowsHide:!0}),s=RegExp(`^\\s*${escapeRegExp(t)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`,`im`),c=n.match(s)?.[1]?.trim();if(c)return c}catch{}}return null}function resolveSystemRootFromEnv(e){return normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`SystemRoot`))??normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`WINDIR`))??FP}function getProcessRoots(e){if(!RP){let t={};for(let e of[`SystemRoot`,`WINDIR`,`ProgramFiles`,`ProgramFiles(x86)`,`ProgramW6432`])t[e]=getEnvValueCaseInsensitive(process.env,e);let n={env:t,systemRoot:normalizeWindowsInstallRoot(queryWindowsRegistryValue(IP,`SystemRoot`,e)??void 0)??resolveSystemRootFromEnv(t)};if(e!==void 0&&performance.now()>=e)return n;RP=n}return RP}function getWindowsSystemRoot(e,t){if(e!==process.env)return resolveSystemRootFromEnv(e);let n=getProcessRoots(t);return n.installRoots?.systemRoot??n.systemRoot}function getWindowsPowerShellExePath(e=process.env,t){return S.win32.join(getWindowsSystemRoot(e,t),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}var FP,IP,LP,RP,zP=__esmMin((()=>{Sp(),ap(),Yt(),PP(),FP=`C:\\Windows`,IP=`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`,LP=5e3,RP=null}));function readWindowsUserSid(){if(process.platform===`win32`)try{let e=re(getWindowsPowerShellExePath(),[`-NoProfile`,`-NonInteractive`,`-Command`,`[Security.Principal.WindowsIdentity]::GetCurrent().User.Value`],{encoding:`utf8`,windowsHide:!0,timeout:5e3}),t=e.stdout?.trim();return!e.error&&e.status===0&&/^S-1-\d+(?:-\d+)+$/.test(t)?t:void 0}catch{return}}var BP=__esmMin((()=>{zP()})),VP=/* @__PURE__ */ __exportAll({inspectOtherOpenClawProcesses:()=>inspectOtherOpenClawProcesses});function isStandardSystemdUserManager(e){let t=e&&`argv`in e?e.argv:[];return t.length<=3&&t[1]===`--user`&&t.slice(2).every(e=>/^--deserialize=\d+$/u.test(e))&&(t[0]===`/usr/lib/systemd/systemd`||t[0]===`/lib/systemd/systemd`)}function isStandardSystemdLoginProcess(e,t,n){return process.platform!==`linux`||n===void 0||e?.uid!==n||!(`argv`in e)?!1:isStandardSystemdUserManager(e)||e.argv.length===1&&e.argv[0]===`(sd-pam)`&&t?.uid===e.uid&&isStandardSystemdUserManager(t)}function isGatewayProcess(e,t){if(S.basename((e[0]??``).replaceAll(`\\`,`/`)).replace(/\.(exe|cmd|bat)$/iu,``)===`openclaw-gateway`)return!0;if(t.kind!==`openclaw`||t.entryIndex===void 0)return!1;let n=(e[t.entryIndex]??``).replaceAll(`\\`,`/`);return UP.some(e=>n.endsWith(`/${e}`))||getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(t.entryIndex)]),1)[0]===`gateway`}function classifyProcessArtifactCustody(e,t,n){if(!e)return{kind:`unknown`,reason:`process command is unavailable`};let r=`argv`in e?e.argv:[],i=[...r.map(e=>e.replace(/^--[^=]+=/u,``).replace(/^-r(?=.)/u,``)),n??``,`executable`in e?e.executable??``:``].filter(referencesRetainedArtifact);if(`argvUnavailable`in e||r.length===0)return i.length?{kind:`holder`}:{kind:`not-holder`};let{position:a,operands:s}=resolveRuntimeScriptPosition(r),c={pid:t,cwd:n??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:HP,inspectPackage:!0},l,u=i.flatMap(e=>{let t=classifyOpenClawEntrypointPath(e,c);return t.kind===`openclaw`&&t.artifactPath?[t.artifactPath]:(l??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`,[])});if(i.length&&s.length===0)return l?{kind:`unknown`,reason:l}:{kind:`holder`,paths:u};let d=classifyOpenClawArgv(r,c),f=isGatewayProcess(r,d),p=i.length>0||u.length>0,unscoped=()=>p||!f?{kind:`holder`}:{kind:`holder`,gateway:!0};if(d.kind===`openclaw`){if(!d.artifactPath)return s.some(({module:e})=>e)?{kind:`holder`}:unscoped();u.push(d.artifactPath),p=!0}let m=u.length?{kind:`holder`,paths:u}:void 0;if(l??=d.kind===`unclassified`&&d.cause!==`runtime-syntax`?d.reason:void 0,!n||!S.isAbsolute(n))return d.kind===`other`&&typeof a!=`number`&&a.kind===`not-runtime`&&i.length===0?{kind:`not-holder`}:{kind:`unknown`,reason:l??`working directory is unavailable`};let h=typeof a!=`number`&&a.kind!==`not-runtime`?readProcessPackageIdentity(n,!0):void 0;h?.kind===`package`&&h.name===`openclaw`&&(m=unscoped());let g=h?.kind===`package`?h.scripts:{};h?.kind===`unknown`&&(l??=h.reason);for(let{value:e,module:t}of s){let n=e;if(t){if(e.startsWith(`file:`))try{n=Ie(e)}catch(e){l??=String(e);continue}else if(!S.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){l??=`runtime module package identity is unavailable`;continue}}else if(isBunRuntime(r[0]??``)&&!/[\\/]/u.test(e)&&!S.extname(e)&&typeof g[e]==`string`&&g[e].trim())continue;let i=classifyOpenClawEntrypointPath(n,c);i.kind===`unclassified`?l??=i.reason:i.kind===`openclaw`&&(p||=i.artifactPath!==void 0,m=i.artifactPath&&(!m||m.paths)?{kind:`holder`,paths:[...m?.paths??[],i.artifactPath]}:unscoped())}return l?{kind:`unknown`,reason:l}:m??{kind:`not-holder`}}function classifyWindowsHandoffAncestry(e,t,n){let r=e.startIdentity;if(r&&n.length&&n.every(({startIdentity:e})=>/^\d+$/.test(e)&&BigInt(e)>BigInt(r)))return`unrelated`;let i=/* @__PURE__ */ new Set,a=e;for(;a.startIdentity&&!i.has(a.pid);){let e=a.startIdentity;if(i.add(a.pid),n.some(({pid:t,startIdentity:n})=>t===a.pid&&n===e||t===a.parentPid&&/^\d+$/.test(n)&&BigInt(n)<=BigInt(e)))return`descendant`;if(a.parentPid===0||a.parentPid===4)return`unrelated`;let r=t.get(a.parentPid??0);if(!r?.startIdentity||BigInt(r.startIdentity)>BigInt(e))break;a=r}return`unknown`}function inspectOtherOpenClawProcesses(e){let t=typeof e==`object`?e:void 0,n=typeof e==`string`?e:void 0,r=[],i={matchingPids:[],unverifiedPids:[]};try{if(process.platform===`linux`&&isContainerEnvironment())throw Error(`Host process visibility cannot be established from this container. Run Doctor on the host after stopping OpenClaw containers that share its temporary directory.`);let e=process.platform===`win32`,a=Date.now()+(t?15e3:1e3),s=e&&t?[...readWindowsProcessCensus(15e3)]:void 0,c=new Map(s?.map(e=>[e.pid,e])),l=e&&t?.windowsUserSid!==void 0&&readWindowsUserSid()===t.windowsUserSid,u=s?.map(({pid:e,parentPid:t,commandLine:n})=>{let r=n?parseWindowsNativeCommandLine(n):null;return{pid:e,state:``,command:r?.length&&t!==void 0?{ppid:t,argv:r}:void 0}})??[...readProcessGroupMembers(t?15e3:1e3,{readDarwinCommand:t?(e,t)=>readDarwinProcessCommand(e,t,{serviceMarker:!1}):readDarwinProcessCommand})],d=new Map(u.map(e=>[e.pid,e])),f=d.get(process.pid);if(!f||!t&&(!f.command&&process.platform!==`darwin`||process.platform===`linux`&&u.some(e=>e.command&&!(`argv`in e.command))))throw Error(`OpenClaw process census is incomplete.`);let p=s?new Map(s.map(({pid:e,cwd:t})=>[e,t])):readProcessWorkingDirectories(u.map(({pid:e})=>e)),m=/* @__PURE__ */ new Set,h=!t&&isUpdateCommandArgv(process.argv),g=/* @__PURE__ */ new Set([process.pid]),v=f,y=f.command?.ppid??f.ppid??0;for(;y>0;){let n=d.get(y);if(!n?.command||g.has(y)){if(t||n&&!n.command)break;throw Error(`OpenClaw process ancestry is incomplete.`)}let r=c.get(y)?.startIdentity,i=c.get(v.pid)?.startIdentity;if(e&&(!r||!i||BigInt(r)>=BigInt(i)))break;if(g.add(y),`argv`in n.command){let{argv:e,serviceMarker:r,serviceMarkerUnavailable:i}=n.command,a=classifyOpenClawArgv(e,{pid:y,serviceMarker:r,serviceMarkerUnavailable:i,cwd:p.get(y)??``,additionalEntrypoints:HP}),s=a.kind===`openclaw`&&a.entryIndex!==void 0?getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(a.entryIndex)]),1)[0]:void 0;(s===(t?`update`:`doctor`)||h&&s===`update`&&y===(f.command?.ppid??f.ppid))&&m.add(y)}v=n,y=n.command.ppid}let normalize=t=>e?t.replaceAll(`\\`,`/`).replace(/\/{2,}\?\/UNC\//gi,`//`).replace(/\/{2,}\?\//g,``).replace(/\/{2,}/g,`/`).toLowerCase():t,literal=e=>escapeRegExp(normalize(e)),referencePattern=n=>{let r=n.flatMap(t=>[t.replace(/[\\/]+$/,``),Le(t,{windows:e}).href]);return RegExp(`(?:^|[^\\w-])(?:${t?literal(t.runId):`(?!)`}(?=$|[^\\w-])|(?:${r.map(literal).join(`|`)||`(?!)`})(?=$|[/\\s"'\x60);,\\]]))`)},b=t?.artifactPaths??(n?[n]:[]),x=referencePattern(b),rootKey=e=>normalize(e.replace(/[\\/]+$/,``)),ee=new Set(t?.sharedRoots?.map(rootKey)),te=referencePattern(b.filter(e=>!ee.has(rootKey(e)))),ne=process.getuid?.(),outsideHandoffFamily=(e,t)=>{let n;try{n=oe(e,{throughPid:process.pid})}catch{return!1}return n?.stoppedBy===`through-pid`||t!==void 0&&n?.stoppedBy===`root`&&n.chain.every(e=>{let n=d.get(e.pid)?.command;return e.startTimeMicros>t*1e3||process.platform===`linux`&&n?.uid===ne&&isStandardSystemdUserManager(n)})},predatesHandoffDrivers=e=>{if(process.platform!==`linux`||!t?.drivers?.length)return!1;let n=readLinuxProcessStat(e)?.startedAt;return n!==void 0&&t.drivers.every(({startIdentity:e})=>BigInt(e)>BigInt(n))};for(let{pid:s,state:f,command:h}of u){if(t&&Date.now()>=a)throw Error(`Process census deadline exceeded`);if(s===process.pid||m.has(s)||(f?.startsWith(`Z`)||t)&&isPidDefinitelyDead(s))continue;let u=h&&`argv`in h?h.argv:void 0;if(t){if(!e&&u?.length===0)continue;let n=c.get(s),a=p.get(s),f=[...u??[],n?.commandLine??``,n?.executable??``,a??``],m=classifyOpenClawArgv(u??[n?.executable??``],{pid:s,cwd:a??``,serviceMarker:h&&`argv`in h?h.serviceMarker:void 0,additionalEntrypoints:HP});if(f.some(e=>x.test(normalize(e)))||!t.artifactPathsOnly&&m.kind===`openclaw`){outsideHandoffFamily(s,f.some(e=>te.test(normalize(e)))?void 0:t.familyDeadline)||i.matchingPids.push(s);continue}let g=t.familyExited?`unrelated`:n&&classifyWindowsHandoffAncestry(n,c,t.drivers??[]);if(g===`descendant`){i.matchingPids.push(s);continue}if(g===`unrelated`||l&&n?.accessDenied)continue;let v=n?.foreignOwner||h?.owner===`different`||h?.uid!==void 0&&ne!==void 0&&h.uid!==ne;if((!u||a===void 0)&&!v&&!isStandardSystemdLoginProcess(h,d.get(h?.ppid??0)?.command,ne)&&!outsideHandoffFamily(s)&&!predatesHandoffDrivers(s)){i.unverifiedPids.push(s);let t=n?.executable??u?.[0];r.push(`Could not verify handoff ancestry for PID ${s} (${t?(e?S.win32:S).basename(t):`image unavailable`}).`)}continue}let g=classifyProcessArtifactCustody(h,s,p.get(s));g.kind!==`not-holder`&&(g.kind===`holder`&&n&&(g.paths?!g.paths.some(e=>x.test(normalize(e))):g.gateway)||(i.matchingPids.push(s),g.kind===`unknown`&&r.push(`Could not verify runtime custody for PID ${s}: ${g.reason}`)))}}catch(e){let n=/Could not classify PID (\d+):/.exec(e instanceof Error?e.message:``);t&&n&&i.unverifiedPids.push(Number(n[1])),i.error=t?isRosettaTranslatedProcess()?`Host process census is unavailable under Rosetta; run openclaw update repair with native arm64 Node.js.`:`Host process census is incomplete; verify process-inspection permissions and retry update repair.`:`Could not inspect OpenClaw processes: ${String(e)}`}return t?{...i,...r.length?{warnings:r}:{}}:i.error?{error:i.error}:{pids:i.matchingPids,...r.length?{warnings:r}:{}}}var HP,UP,WP=__esmMin((()=>{Vy(),TP(),ln(),EP(),on(),Sp(),OP(),hk(),AP(),_k(),Fy(),jP(),BP(),HP=Object.values(Py).flatMap(e=>[S.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`]),UP=[S.posix.normalize(`src/infra/${Py.spawnBroker.sourceWorkerName}.ts`),`dist/${Py.spawnBroker.distWorkerPath}`,S.posix.normalize(`src/infra/${Py.directoryWatchHost.sourceWorkerName}.ts`),`dist/${Py.directoryWatchHost.distWorkerPath}`]})),GP=/* @__PURE__ */ __exportAll({maintainRetainedUpdateRuntimes:()=>maintainRetainedUpdateRuntimes,registerRetainedUpdateRuntime:()=>registerRetainedUpdateRuntime,removeTemporaryArtifacts:()=>removeTemporaryArtifacts,reportRetainedUpdateRuntime:()=>reportRetainedUpdateRuntime,resolveRetainedUpdateRuntimeParents:()=>resolveRetainedUpdateRuntimeParents});function registerRetainedUpdateRuntime(e){return qP.add(e),()=>void qP.delete(e)}function reportRetainedUpdateRuntime(e,t){let n=`Runtime retained at ${e}: ${t}`;try{KP.warn(n)}catch{}return n}function resolveRetainedUpdateRuntimeParents(e,t=[]){let n=e.split(S.sep),r=n.indexOf(`node_modules`),i=[n.slice(0,r>=0?r+1:n.length).join(S.sep),...t],a=S.dirname(e),s=[a];for(;i.some(e=>Ve(e,a));){let e=S.dirname(a);if(e===a)break;a=e,s.push(a)}return s}async function isRetainedRuntimeMarker(e){if(await T.realpath(e).catch(()=>void 0)!==e)return!1;let t=JSON.parse(await T.readFile(e,`utf8`));return isRecord(t)&&t.name===`openclaw`}async function recognizesRetainedRuntime(e,t){let n=S.parse(t).root,r=S.join(e,`tree`,Buffer.from(n).toString(`hex`)),i=S.join(r,S.relative(n,t));if(await isRetainedRuntimeMarker(S.join(i,`package.json`)))return!0;let a=S.dirname(i),s=S.dirname(a),c=S.dirname(s);if(S.basename(i)!==`openclaw`||S.basename(a)!==`node_modules`||!S.basename(s).startsWith(`openclaw@`)||S.basename(c)!==`.pnpm`||await T.realpath(c).catch(()=>void 0)!==c)return!1;let l=0;for await(let e of await T.opendir(c)){if(++l>4096)throw Error(`retained pnpm version inventory exceeds the bounded lookup; inspect it before manual cleanup`);if(e.isDirectory()&&e.name.startsWith(`openclaw@`)&&await isRetainedRuntimeMarker(S.join(c,e.name,`node_modules/openclaw/package.json`)))return!0}return!1}async function maintainRetainedUpdateRuntimes(e){let t=[],n=e.packageRoots.map(resolveIdentityPathViaExistingAncestorSync),r=new Set([Xe.tmpdir(),...e.temporaryDirectories??[],...n.flatMap(e=>resolveRetainedUpdateRuntimeParents(e))].map(resolveIdentityPathViaExistingAncestorSync));for(let i of r)try{for(let r of await T.readdir(i,{withFileTypes:!0})){if(!/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(r.name))continue;let a=S.join(i,r.name);try{let r=await T.lstat(a);if(!r.isDirectory()||process.getuid&&r.uid!==process.getuid())throw Error(`directory ownership is unknown; inspect it before manual cleanup`);if(qP.has(a))throw Error(`the creating update still owns this runtime`);let i=!1;for(let e of n)if(await recognizesRetainedRuntime(a,e)){i=!0;break}if(!i)throw Error(`no recognized runtime marker; inspect it before manual cleanup`);if(!e.repair){t.push(`Runtime retained at ${a}: run \`openclaw doctor --fix\` after its workers stop`);continue}let{inspectOtherOpenClawProcesses:s}=await Promise.resolve().then(()=>(WP(),VP)),c=await T.lstat(a);if(c.dev!==r.dev||c.ino!==r.ino||c.ctimeMs!==r.ctimeMs||qP.has(a))throw Error(`directory identity or custody changed`);e.assertCurrent();let l=s(a);if(`error`in l)throw Error(l.error);for(let e of l.warnings??[])t.includes(e)||t.push(e);if(l.pids.length)throw Error(`other OpenClaw processes are still running (PIDs: ${l.pids.join(`, `)}); let these holders finish, then rerun openclaw doctor --fix`);e.assertResourcesSettled?.(a),e.assertCurrent();let u;await removeTemporaryArtifacts(a,`Updater runtime`,e=>{u=`cleanup failed: ${formatErrorMessage(e)}`}),t.push(u?reportRetainedUpdateRuntime(a,u):`Removed abandoned updater runtime: ${a}`)}catch(e){w(e,`ENOENT`)||t.push(reportRetainedUpdateRuntime(a,formatErrorMessage(e)))}}}catch(e){w(e,`ENOENT`)||t.push(`Cannot inspect updater runtimes in ${i}: ${formatErrorMessage(e)}`)}return t}function removeTemporaryArtifacts(e,t,n=n=>KP.warn(truncateUtf16Safe(formatErrorMessage(`${t} cleanup failed; files may remain in ${e}. After the worker or session stops, check permissions and remove the retained directory: ${formatErrorMessage(n)}`),1024))){return runBestEffortCleanup({cleanup:()=>T.rm(e,{recursive:!0,force:!0}),onError:n})}var KP,qP,JP=__esmMin((()=>{D(),Ju(),Ev(),B(),sp(),H(),Xy(),SP(),bp(),KP=createSubsystemLogger(`infra:temp-artifacts`),qP=resolveGlobalSingleton(Symbol.for(`openclaw.retainedUpdateRuntimes`),()=>/* @__PURE__ */ new Set)})),YP=__esmMin((()=>{Qd(),B(),aP(),Ij(),cP(),FA(),pP(),Hy(),J(),Mk(),tA(),uO(),$O(),fO(),tP(),nP(),fM(),QN(),rP(),xP(),createLazyRuntimeModule(()=>Promise.resolve().then(()=>(JP(),GP))),resolveGlobalSingleton(Symbol.for(`openclaw.workerTaskDatabaseAdmissionChannels`),()=>/* @__PURE__ */ new Map)})),XP=__esmMin((()=>{cj(),YP()})),ZP=__esmMin((()=>{Qd(),qD(),YD(),W(),ZA(),GN(),KN(),fO(),tP(),rP(),XP()}));function sqliteSnapshotStagingError(e,t,n=!1,i){markSqliteInspectionOperation(t,`snapshot`);let a=n,s=!1,c=!1,l;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){c||=r instanceof AggregateError||r instanceof SqliteSnapshotCleanupError;let{errcode:t,path:n}=r;s||=hasSqliteSnapshotCapacityCode(r),(s||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${S.sep}`.startsWith(`${e}${S.sep}`))&&(a=!0,typeof t==`number`&&(l=t)),r=r.cause}if(!a)return t;let u=s?`free disk space/quota`:`check filesystem health and write permissions`,d=``;if(s&&i)try{let t=sqliteSnapshotSourceFileSize(i)+sqliteSnapshotSourceFileSize(`${i}-wal`)+sqliteSnapshotSourceFileSize(`${i}-journal`),n=tryReadDiskSpace(e)?.availableBytes,a=r.existsSync(`${i}-wal`)&&r.existsSync(`${i}-shm`);d=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${a?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let f=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,p=`${t instanceof Error?t.message:String(t)}${l===void 0?``:` (SQLite errcode=${l})`}; snapshot staging root ${n?e:S.dirname(e)}${d}: ${u} or set ${f} to a writable filesystem`,m=s&&!c&&readSqliteInspectionOperation(t)!==`source`?new SqliteSnapshotCapacityError(p,{cause:t}):Error(p,{cause:t});return isPrivateDirectoryCreationRefused(t)?markPrivateDirectoryCreationRefused(m):m}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}-`:BA)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:acquireSqliteSnapshotToken(n,`create`)}}catch(e){throw n&&removeTempDirectory(n),e}}var QP=__esmMin((()=>{gv(),sN(),Xy(),tM(),kb(),W(),TM(),ZA(),rM(),oN(),KA()}));function readUint32(e,t,n){return n===`LE`?e.readUInt32LE(t):e.readUInt32BE(t)}function sqliteWalChecksum(e,t,n=[0,0]){let[r,i]=n;for(let n=0;n<e.length;n+=8)r=r+readUint32(e,n,t)+i>>>0,i=i+readUint32(e,n+4,t)+r>>>0;return[r,i]}var $P=__esmMin((()=>{}));function readWalGeneration(e){let t=Buffer.alloc(eF);if(Me(e,t,0)!==t.length)return;let n=t.readUInt32BE(0);if(n!==931071618&&n!==931071619)return;let r=n===931071618?`LE`:`BE`,i=t.readUInt32BE(8),[a,s]=sqliteWalChecksum(t.subarray(0,24),r);if(!(i<512||i>65536||i&i-1||t.readUInt32BE(24)!==a||t.readUInt32BE(28)!==s))return{header:t,byteOrder:r,frameBytes:tF+i}}function copyCommittedWalFrames(e,t,n,i){let{header:a,byteOrder:s,frameBytes:c}=n;if(readWalGeneration(e)?.header.equals(a)!==!0)return!1;let l=a.subarray(16,24),u=[a.readUInt32BE(24),a.readUInt32BE(28)];writeFully(t,a,0);let d=eF,f=Math.max(1,Math.floor(nF/c)),p=Buffer.allocUnsafe(f*c);for(let n=eF;n<i;){let r=p.subarray(0,Math.min(p.length,i-n)),a=Me(e,r,n),f=0,m=!0;for(let e=0;e+c<=a;e+=c){let t=r.subarray(e,e+c);if(t.readUInt32BE(0)===0||!t.subarray(8,16).equals(l)){m=!1;break}let i=sqliteWalChecksum(t.subarray(tF),s,sqliteWalChecksum(t.subarray(0,8),s,u));if(t.readUInt32BE(16)!==i[0]||t.readUInt32BE(20)!==i[1]){m=!1;break}u=i,f=e+c,t.readUInt32BE(4)!==0&&(d=n+f)}if(f>0&&writeFully(t,r.subarray(0,f),n),!m||f<r.length)break;n+=f}return r.ftruncateSync(t,d),r.fsyncSync(t),d}function writeFully(e,t,n){for(let i=0;i<t.length;){let a=r.writeSync(e,t,i,t.length-i,n+i);if(a<=0)throw Error(`SQLite WAL snapshot write made no progress`);i+=a}}function matchesCapturedWalPrefix(e,t,n){let i=r.openSync(t,`r`);try{let t=r.fstatSync(i);if(!t.isFile()||t.size!==n)return!1;let a=Buffer.allocUnsafe(Math.min(nF,n)),s=Buffer.allocUnsafe(a.length);for(let t=0;t<n;t+=a.length){let r=Math.min(a.length,n-t),c=a.subarray(0,r),l=s.subarray(0,r);if(Me(e,c,t)!==r||Me(i,l,t)!==r||!c.equals(l))return!1}return!0}finally{r.closeSync(i)}}function prepareSqliteWalPrefixCopy(e,t,n){let i=readWalGeneration(e);if(i)return()=>{let a=r.fstatSync(e).size;if(!Number.isSafeInteger(a)||a<eF)return!1;let s=r.openSync(t,`wx`,384),c;try{c=copyCommittedWalFrames(e,s,i,a)}finally{r.closeSync(s)}return c!==!1&&n()&&matchesCapturedWalPrefix(e,t,c)&&readWalGeneration(e)?.header.equals(i.header)===!0}}var eF,tF,nF,rF=__esmMin((()=>{$P(),eF=32,tF=24,nF=1048576})),iF=__esmMin((()=>{xk(),LA(),kb()}));function statIfPresent(e){try{return r.statSync(e,{bigint:!0})}catch(e){if(e.code===`ENOENT`)return;throw e}}function readSourceSidecars(e){return{journal:!!statIfPresent(`${e}-journal`),shm:!!statIfPresent(`${e}-shm`),wal:!!statIfPresent(`${e}-wal`)}}function openPinnedFile(e,t){let n;try{n=r.openSync(e,`r`)}catch(e){throw e.code===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`):e}try{let i=r.fstatSync(n,{bigint:!0});t&&assertDatabaseFileIdentity(i,t);let a=statIfPresent(e);if(!i.isFile()||!a?.isFile()||!Fe(i,a))throw new SqliteSourceChangedError(`source-identity-changed`);return{descriptor:n,identity:i,pathname:e}}catch(e){throw r.closeSync(n),e}}function readSourceJournalMode(e,t){let n=openPinnedFile(e,t);try{let e=Buffer.alloc(aF),t=r.readSync(n.descriptor,e,0,e.length,0);return assertPinnedIdentityUnchanged(n),t===0?`empty`:t!==e.length||e.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`?`unknown`:e[18]===2||e[19]===2?`wal`:`rollback`}finally{r.closeSync(n.descriptor)}}function assertPinnedIdentityUnchanged(e){let t=r.fstatSync(e.descriptor,{bigint:!0}),n=statIfPresent(e.pathname);if(!t.isFile()||!n?.isFile()||!Fe(e.identity,t)||!Fe(e.identity,n))throw new SqliteSourceChangedError(`source-identity-changed`)}function copySourceFile(e,t,n){let i=openPinnedFile(e,n);try{let n;try{n=r.realpathSync.native(e)}catch(e){throw extractErrorCode(e)===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`,{cause:e}):e}let a=Oe({source:{rootPath:S.dirname(n),absolutePath:n},destination:{rootPath:S.dirname(t),absolutePath:t},expectedSourceIdentity:i.identity,sourceHardlinks:`allow`,clone:`auto`,mode:384});try{r.fsyncSync(a.fd),assertPinnedIdentityUnchanged(i)}finally{a.close()}}finally{r.closeSync(i.descriptor)}}function sourceMatchesCopy(e,t,n){let i=openPinnedFile(e,n);try{let e=r.openSync(t,`r`);try{if(!r.fstatSync(e).isFile())return!1;let t=Pe(i.descriptor,e);return assertPinnedIdentityUnchanged(i),t}finally{r.closeSync(e)}}finally{r.closeSync(i.descriptor)}}function assertExpectedSidecars(e,t){let n=readSourceSidecars(e);if(n.journal!==t.journal||n.wal!==t.wal)throw new SqliteSourceChangedError(`journal-state-changed`)}function rollbackJournalReferencesSuperJournal(e){let t=r.openSync(e,`r`);try{let e=r.fstatSync(t).size;if(e<16)return!1;let n=Buffer.allocUnsafe(16);if(r.readSync(t,n,0,n.length,e-n.length)!==n.length)return!1;let i=n.readUInt32BE(0);return i>0&&i<=e-20&&n.subarray(8).equals(oF)}finally{r.closeSync(t)}}function syncPrivateSnapshot(e){let t=r.openSync(e,`r+`);try{r.fsyncSync(t)}finally{r.closeSync(t)}}function recoverPrivateJournalCopy(e){if(rollbackJournalReferencesSuperJournal(`${e}-journal`))throw Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);let t=openNodeSqliteDatabase(e);try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`),t.prepare(`PRAGMA schema_version;`).get()}finally{t.close()}r.rmSync(`${e}-journal`,{force:!0}),syncPrivateSnapshot(e)}function*createStableReadOnlyCopyInTempDirectory(e,t,n,i=n?S.dirname(n):resolvePrivateSqliteSnapshotStagingRoot(),a,s){let c=n;try{c??=createSqliteSnapshotStagingDirectorySync(i);let n=S.join(c,`database.sqlite.partial`),l=S.join(c,`first`);if(process.platform!==`win32`&&r.chmodSync(c,448),readSourceJournalMode(e,a)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);let u=readSourceSidecars(e),d=!1;if(t===`wal`&&u.wal&&!u.journal){let t=openPinnedFile(`${e}-wal`);try{let r=prepareSqliteWalPrefixCopy(t.descriptor,`${n}-wal`,()=>sourceMatchesCopy(e,n,a));r&&(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:a});let i=r?.();if(assertPinnedIdentityUnchanged(t),i===!1)throw new SqliteSourceChangedError(`wal-copy-unstable`);d=i===!0}finally{r.closeSync(t.descriptor)}}let f=[...u.journal?[`-journal`]:[],...u.wal?[`-wal`]:[]];if(d)assertExpectedSidecars(e,u);else if(f.length>0){for(let t of f)yield{sourcePath:`${e}${t}`,targetPath:`${n}${t}`};if(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:a},!sourceMatchesCopy(e,n,a))throw new SqliteSourceChangedError(`main-changed-during-copy`);for(let t of f)if(!sourceMatchesCopy(`${e}${t}`,`${n}${t}`))throw new SqliteSourceChangedError(t===`-wal`?`wal-changed-during-copy`:`rollback-journal-changed-during-copy`);assertExpectedSidecars(e,u)}else{yield{sourcePath:e,targetPath:l,expectedSourceIdentity:a},assertExpectedSidecars(e,u);let t=s!==void 0||sourceMatchesCopy(e,l,a);if(assertExpectedSidecars(e,u),!t)throw new SqliteSourceChangedError(`main-changed-during-copy`);r.rmSync(n,{force:!0}),r.renameSync(l,n)}if(readSourceJournalMode(e,a)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);if(s&&(u.journal||u.wal&&r.statSync(`${n}-wal`).size!==0))throw new SqliteSourceChangedError(`recovery-data-appeared`);return u.journal&&recoverPrivateJournalCopy(n),publishPreparedCopy(c,s)}catch(t){let r=c?sqliteSnapshotStagingError(c,t,!1,e):t;if(c&&n===void 0){let e=[r];if(!removeTempDirectory(c,t=>e.push(t)))throw preparationCleanupError(e,`SQLite snapshot preparation`)}throw r}}function copyPreparedLocationSync(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value;copySourceFile(e,n,r)}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}function*prepareArtifactPreservingCopy(e,t,n,i){let a=r.realpathSync.native(e);for(let e=0;;e+=1)try{return yield*createStableReadOnlyCopyInTempDirectory(a,readSourceJournalMode(a,n),typeof t==`object`?t.directory:void 0,typeof t==`string`?t:void 0,n,i)}catch(n){if(typeof t==`object`&&discardPreparedCopyPayload(t.directory,n),!(n instanceof SqliteSourceChangedError))throw n;if(e+1>=10)throw new SqliteSourceChangedError(n.reason,{cause:n,attempts:10});waitForSnapshotRetrySync(e)}}function prepareSqliteReadOnlyLocationSyncInProcess(e,t,n,r){return copyPreparedLocationSync(prepareArtifactPreservingCopy(e,t,n,r))}var aF,oF,SqliteSourceChangedError,sF=__esmMin((()=>{O(),LA(),xM(),Nx(),kb(),CM(),TM(),ZA(),rN(),oN(),QP(),rF(),iF(),qv(),aF=20,oF=Buffer.from([217,213,5,249,32,161,99,215]),SqliteSourceChangedError=class extends Error{constructor(e,t){super(t?.attempts?`SQLite source did not stabilize (reason=${e}, attempts=${t.attempts}) after ${t.attempts} read-only inspection attempts. Wait a moment for write activity to settle, then retry the inspection`:`SQLite source changed during read-only inspection (reason=${e})`,t),this.reason=e}}}));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(e){let t=r.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(r.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile(e),i=readFile(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:i&&i.size>32n?walFingerprint(i):null}:void 0}var cF=__esmMin((()=>{W(),ZA(),sF(),QP()}));function readCommittedContent(e,t,n,i){let a=openNodeSqliteDatabase(t.location);runWithSqliteCleanup({release:()=>a.close()},`Database generation checkpoint`,()=>truncateSqliteWal(a,t.location)),n?.(t.location,e);let s=i?.(),c=s?captureSqlitePrivateSnapshotFamily(t.location,t.cleanupRoot??S.dirname(t.location)):void 0;if(s&&!c)throw Error(`Database generation private image cannot be retained`);let l=t.journalFreeContent;if(l)return assertPublishedFileIdentitySync(t.location,l.identity,l),{sha256:l.sha256,family:c};let u=r.openSync(t.location,`r`);return{sha256:runWithSqliteCleanup({release:()=>r.closeSync(u)},`Database generation digest`,()=>hashFileDescriptorSync(u).sha256),family:c}}function inspectDrainedSource(e,t){let n=resolveImmutableSqliteFileUri(e);if(t){t(n,e);return}let r=openNodeSqliteDatabase(n,{readOnly:!0});runWithSqliteCleanup({release:()=>r.close()},`Database generation admission`,()=>readSqliteSchemaObjects(r))}function readWalIndexHeader(e){let t=`${e}-shm`,n;try{n=r.openSync(t,`r`)}catch(e){return ignoreMissingPath(e)??null}try{let i=r.fstatSync(n,{bigint:!0}),a=Buffer.alloc(96),s=r.readSync(n,a,0,48,0),c=r.readSync(n,a,48,48,48),l=r.fstatSync(n,{bigint:!0}),u=r.lstatSync(t,{bigint:!0});if(!i.isFile()||!u.isFile()||[l,u].some(e=>i.dev!==e.dev||i.ino!==e.ino)||s!==48||c!==48||!a.subarray(0,48).equals(a.subarray(48,96)))throw Error(`SQLite WAL commit header is unavailable or changing: ${e}`);return a}finally{r.closeSync(n)}}function isRebuiltWalIndex(e,t){return t.readUInt32LE(8)===0&&t.subarray(0,8).equals(e.subarray(0,8))&&t.subarray(12,40).equals(e.subarray(12,40))}function sameWalCommitPublication(e,t,n){return(e===null?t===null:t!==null&&(t.equals(e)||isRebuiltWalIndex(e,t)))?!0:n.journal||(n.wal?.size??0n)!==0n?!1:t===null||e===null&&t.readUInt32LE(8)===0&&t.readBigUInt64LE(24)===0n}function readGenerationFamily(e){let t=[``,`-journal`,`-wal`].map(t=>r.lstatSync(`${e}${t}`,{bigint:!0,throwIfNoEntry:!1}));if(!t[0]&&t.slice(1).some(Boolean))throw Error(`Database is absent but retained journal data exists: ${e}`);if(t.some(e=>e&&!e.isFile()))throw Error(`Database generation requires a regular file: ${e}`);return t.map((e,t)=>t===2&&e?.size===0n?void 0:e)}function verifyGenerationFamily(e,t,n){let r=readGenerationFamily(e);if([n.database,n.journal,n.wal?.size===0n?void 0:n.wal].some((e,n)=>[t[n],r[n]].some(t=>e===void 0?t!==void 0:!t||!sameFileStatFingerprint(t,e))))throw Error(`SQLite file generation changed while reading: ${e}`)}function serializePhysicalGeneration(e,t){return sha256Hex(JSON.stringify([serializeSqliteFileGeneration(e.wal?.size===0n?{...e,wal:void 0}:e),t?.toString(`hex`)??null]))}function readUpdateDatabaseGeneration(e,t,n){let r=readGenerationFamily(e),i=r[0];if(!i)return{generation:null,physical:null};let a=readWalIndexHeader(e),s=createSqliteFileGenerationReader(),c=s(e),observe=(t,n)=>{let l=readStableSqliteFileGeneration(e,n?s:void 0),u=readWalIndexHeader(e);if(verifyGenerationFamily(e,r,l),!sameSqliteFileGeneration(c,l)||!sameWalCommitPublication(a,u,l)||c.wal&&c.wal.size>0n&&u?.[12]!==1)throw Error(`SQLite WAL commit publication could not be verified: ${e}`);let d=[c.database.dev.toString(),c.database.ino.toString(),readDatabaseIdentityBirthtime(i),t.sha256],f=u?.subarray(8,12).toString(`hex`)??null,p=u?.subarray(24,32).toString(`hex`)??null,fingerprint=(e,t)=>sha256Hex(JSON.stringify([...d,e,t])),m=!c.journal&&(c.wal?.size??0n)===0n&&(u===null||f===`00000000`&&p===`0000000000000000`),h;if(t.family&&n){let r=captureSqlitePrivateSnapshotFamily(n.location,n.cleanupRoot??S.dirname(n.location));if(r?.main!==t.family.main||r?.wal!==t.family.wal)throw Error(`Database generation private image changed before retention`);h={sourcePath:e,prepared:n,family:t.family}}return{retained:h!==void 0,observation:{generation:fingerprint(f,p),physical:serializePhysicalGeneration(l,u),...u!==null&&(c.wal?.size??0n)!==0n&&f!==`00000000`?{rebuiltIndexAlternate:fingerprint(`00000000`,p)}:{},...m?{emptyReaderAlternate:u===null?fingerprint(`00000000`,`0000000000000000`):fingerprint(null,null)}:{},...h?{preparedSource:h}:{}}}},l=!c.journal&&(c.wal?.size??0n)===0n;if(l&&!n)try{return inspectDrainedSource(e,t),observe({sha256:c.database.sha256}).observation}catch{}let u=prepareSqliteReadOnlyLocationSyncInProcess(e,n?.stagingRoot,{key:`file:${databaseFileIdentityKey(c.database)}`},l?{sha256:c.database.sha256,sizeBytes:Number(c.database.size)}:void 0),d=!1;return runWithSqliteCleanup({release:()=>{if(!d){if(!n)u.cleanup();else try{if(!u.cleanup())throw Error(`Database generation snapshot cleanup did not settle`)}catch(e){throw new SqliteSnapshotCleanupError(`Database generation snapshot cleanup failed`,{cause:e})}}}},`Database generation snapshot`,()=>{let r=readCommittedContent(e,u,t,n?.accept),i=observe(r,u);return d=i.retained,i.observation})}function readMatchingUpdateDatabaseGeneration(e,t){let{generation:n,emptyReaderAlternate:r}=readUpdateDatabaseGeneration(e);return n!==null&&t.includes(n)||r!==void 0&&t.includes(r)?n??void 0:void 0}var lF=__esmMin((()=>{ND(),H(),Lx(),LA(),cA(),W(),cF(),sF(),Hx(),sA(),bM(),qv()}));function resolveUpdateSqlitePath(e){try{return m.native(e)}catch(t){return ignoreMissingPath(t),resolvePathViaExistingAncestorSync$1(e)}}var uF=__esmMin((()=>{sp(),H()}));function migrationAuthority(e,t,n){let r=getOpenClawDatabaseMaintenanceScope();if(!r?.ownsSchemaMaintenance)throw e.refuse(`Migration did not retain schema maintenance custody.`),Error(`Database migration requires schema maintenance custody.`);return()=>{r.assertAdmission(),n?n():assertStateDatabaseAccessAllowed(t),e.assertCurrent()}}function readSqliteGeneration(e){let t=JSON.parse(runSqliteReadOnlyWorkerSync(e,void 0,`update-generation`));if(t!==null&&(typeof t!=`string`||!/^[a-f0-9]{64}$/u.test(t)))throw Error(`Database generation child returned an invalid generation.`);return t}function readSqliteFiles(e){return parseSqliteFileGeneration(runSqliteReadOnlyWorkerSync(e,void 0,`file-generation`))}function runUpdateSqliteMigration(e,t,n,r){let i=dF.getStore();if(!i?.capture)return n();let a=resolveUpdateSqlitePath(t);if(i.source?.path===a)return i.source.assertCurrent(),n();let{capture:s}=i,c=s.expected(a),l=s.openedSqlitePaths?.has(a);if(typeof c!=`string`&&!(c===null&&r?.created))return n();let u=migrationAuthority(s,t);if(u(),e.isTransaction)throw Error(`Update migration exclusion must precede the source transaction.`);let d=e.prepare(`PRAGMA locking_mode`).get()?.locking_mode;return runWithSqliteCleanup({release(){r?.close&&s.openedSqlitePaths?.delete(a);try{if(e.isOpen&&d!==`exclusive`&&!r?.retainExclusive){if(e.isTransaction)throw Error(`Update migration left its source transaction open.`);e.exec(`PRAGMA locking_mode=NORMAL; PRAGMA page_count;`)}}catch(e){throw s.refuse(`SQLite migration native custody could not be released.`),e}}},`Update migration exclusion`,()=>{try{if(c===null){let e=readSqliteFiles(t);if(e.database.size!==0n||e.journal||e.wal)throw Error(`Created SQLite migration family is no longer empty.`)}let i=s.rebuiltIndex(a),f=c===null?null:l||d===`exclusive`?readSqliteGeneration(t):readMatchingUpdateDatabaseGeneration(t,i===void 0?[c]:[c,i]);if(u(),f===void 0||!l&&d===`exclusive`&&f!==c&&f!==i)throw Error(`SQLite migration source changed after update capture: ${t}`);s.openedSqlitePaths?.add(a),f!==c&&s.accept(a,c,f),d!==`exclusive`&&e.prepare(`PRAGMA schema_version`).get(),e.exec(`PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;`),u();let p=f===null?void 0:{path:a,generation:f,assertCurrent:u};return dF.run({capture:s,source:p,assertMigrationCurrent:u},()=>{let i=n();if(isPromiseLike(i))throw Error(`Update migration callbacks must remain synchronous.`);if(e.isTransaction)throw Error(`Update migration publication requires its committed native owner.`);u(),truncateSqliteWal(e,t),r?.close?.();let c=readSqliteGeneration(t);return u(),s.accept(a,f,c),i})}catch(e){throw s.refuse(`SQLite migration publication could not be verified: ${formatErrorMessage(e)}`),e}})}function beginUpdatePostgresMigration(e,t){let n=dF.getStore()?.capture,r=e.anchor.location(),i=r&&n?.expected(r);if(!n||!r||typeof i!=`string`)return;if(!getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance){n.refuse(`PostgreSQL migration did not retain schema maintenance custody.`);return}let a=migrationAuthority(n,r,t);a();let s=e.readRecoveryGeneration(!0);if(s!==i)throw n.refuse(`PostgreSQL changed before migration acquired native custody.`),Error(`PostgreSQL migration source changed after update capture.`);let c={path:r,generation:s,assertCurrent:a},publish;return{run(e){return dF.run({capture:n,source:c,assertMigrationCurrent:a},e)},beforeCommit(){a();let t=e.readRecoveryGeneration(!1);publish=()=>n.accept(r,s,t),a()},committed(){a(),publish?.()}}}var dF,fF=__esmMin((()=>{mu(),aA(),Ix(),Xy(),xk(),cA(),W(),vM(),bM(),lF(),uF(),dF=new C}));function getStateSchemaFacts(e){return isPostgresSqlConnection(e)?getPostgresPhysicalFacts(e):getAdmittedSqliteSchemaFacts(e)}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(hasPendingSqliteDatabaseSchemaMutation(e))return;let t=Jb(e,r);if(!t)return;let n=getStateSchemaFacts(e);return t.admissionId===n?.admissionId?t.value:void 0},publish(e,t){!isPostgresSqlConnection(e)&&isSqliteSchemaAdmissionCold(e)&&admitSqliteSchema(e);let n=getStateSchemaFacts(e);if(!n||!isPostgresSqlConnection(e)&&Jb(e,Bx)?.admissionId!==n.admissionId)return;getStateSchemaVersionAdmission(e);let i={value:t,admissionId:n.admissionId};publishSqliteDatabaseAdmission(e,r,i)}}}function rememberConnectionVersion(e,t){let n=hF.get(e),install=t=>{t?hF.set(e,t):hF.delete(e)};stageSqliteTransactionState(e,{stage:()=>install(t),commit:()=>{},rollback:()=>install(n)})||install(t)}function schemaVersionKey(e){return{name:`state.schema-version:${e}`,read:pF.read}}function getStateSchemaVersionAdmission(e){let t=getStateSchemaFacts(e);if(!t)return;let n=hF.get(e);if(n?.schema===t)return n.facts;let r=Jb(e,schemaVersionKey(t.admissionId)),i=r?void 0:Jb(e,Bx);if(!r&&!isPostgresSqlConnection(e)&&i?.admissionId!==t.admissionId)return;let a=r??Jb(e,pF);return a&&(rememberConnectionVersion(e,{schema:t,facts:a}),r||publishSqliteDatabaseAdmission(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=Jb(e,Bx);(isPostgresSqlConnection(e)||r?.admissionId===n.admissionId)&&(publishSqliteDatabaseAdmission(e,schemaVersionKey(n.admissionId),t),publishSqliteDatabaseAdmission(e,pF,t))}function publishStateSchemaVersionAdmission(e,t){publishSqliteDatabaseAdmission(e,pF,t);let n=getStateSchemaFacts(e);n?(rememberConnectionVersion(e,{schema:n,facts:t}),publishSqliteDatabaseAdmission(e,schemaVersionKey(n.admissionId),t)):rememberConnectionVersion(e)}function adoptPeerPublishedStateSchemaVersion(e,t){return t?.schema_version!==36||readSqliteUserVersion(e)!==36?!1:(publishStateSchemaVersionAdmission(e,{userVersion:36,contentVersion:36}),!0)}function getStateRuntimeSchemaAdmission(e){return mF.get(e)}function publishStateRuntimeSchemaAdmission(e,t){mF.publish(e,{startupReady:t})}var pF,mF,hF,gF=__esmMin((()=>{kx(),gu(),J(),jv(),Hx(),Y(),UM(),sb(),pF={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}}},mF=createStateSchemaAdmission(`state.runtime-schema`,e=>typeof e==`object`&&e&&`startupReady`in e&&typeof e.startupReady==`boolean`?{startupReady:e.startupReady}:void 0,`process`),hF=/* @__PURE__ */ new WeakMap}));function createSqliteTerminalOpenLatch(e){let t=/* @__PURE__ */ new Map;return{peek:e=>t.get(S.resolve(e)),get:e=>t.get(S.resolve(e)),record:(n,r)=>{let i=S.resolve(n);materializeErrorStack(r),t.set(i,r),e.closeByPath(i,r)},clear:e=>{t.delete(S.resolve(e))},clearAll:e=>{for(let n of t.keys())(e===void 0||Ve(e,n))&&t.delete(n)}}}var _F=__esmMin((()=>{_O(),bp()}));function readSqliteFileGenerationSync(e){return parseSqliteFileGeneration(runSqliteReadOnlyWorkerSync(e,void 0,`file-generation`))}var vF=__esmMin((()=>{cA(),vM()})),yF=__esmMin((()=>{B(),W(),ZA(),qv(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotFlights`),()=>({unscoped:/* @__PURE__ */ new Map,scoped:/* @__PURE__ */ new WeakMap}))}));function registerLiveSqliteSnapshotOwner(e){let t=readDatabasePathIdentitySync(e.databasePath),n={assertCurrent:e.assertCurrent,database:e.database};return bF.set(t.key,n),()=>{bF.get(t.key)===n&&bF.delete(t.key)}}var bF,xF=__esmMin((()=>{B(),sF(),yF(),qv(),bF=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteLiveSnapshotOwners`),()=>/* @__PURE__ */ new Map)}));function resolveSqliteDatabaseFilePaths(e){return SF.map(t=>`${e}${t}`)}var SF,CF=__esmMin((()=>{Ev(),ip(),ND(),SF=[``,`-wal`,`-shm`,`-journal`],SF.slice(1),Buffer.from([0,5,22,7]),createSubsystemLogger(`state/sqlite`)}));function buildUpdateRehearsalPathEnv(e){return{HOME:e,USERPROFILE:e,TMPDIR:e,TMP:e,TEMP:e,XDG_CONFIG_HOME:S.join(e,`config`),XDG_CACHE_HOME:S.join(e,`cache`),XDG_DATA_HOME:S.join(e,`data`),XDG_STATE_HOME:S.join(e,`state`),OPENCLAW_HOME:e,OPENCLAW_STATE_DIR:e,OPENCLAW_CONFIG_PATH:S.join(e,`openclaw.json`),OPENCLAW_WORKSPACE_DIR:S.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&&S.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 S.resolve(t)}function isUpdateRehearsalReadOnlyPath(e,t){let n=resolveUpdateRehearsalRoot(t);if(!n)return!1;let r=S.resolve(e);return!Ve(n,r)||!Ve(resolveIdentityPathViaExistingAncestorSync(n),resolveIdentityPathViaExistingAncestorSync(r))}function isUpdateRehearsalPrivateDatabase(e,t){return resolveUpdateRehearsalRoot(t)!==void 0&&resolveSqliteDatabaseFilePaths(e).every(e=>!isUpdateRehearsalReadOnlyPath(e,t))}var wF=__esmMin((()=>{sp(),bp(),CF()}));function readCustodiedDrainedSqliteSource(e){if(maintenanceOwnerHasSourceCustody(getOpenClawDatabaseMaintenanceScope(),e)&&!(r.existsSync(`${e}-journal`)||(r.statSync(`${e}-wal`,{throwIfNoEntry:!1})?.size??0)>0))return r.statSync(e,{bigint:!0})}function assertCustodiedSourceUnchanged(e,t){let n=r.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=iA.getStore();if(!n||!isArtifactPreservingStateRead(`agent`,e))return openNodeSqliteDatabase(e,{...t,readOnly:!0});let r=readCustodiedDrainedSqliteSource(e),i=r||isUpdateRehearsalPrivateDatabase(e,process.env)?void 0:prepareSqliteReadOnlyLocationSync(e),a=i?retainSnapshotTempDirectory(i.cleanupRoot??S.dirname(i.location)):void 0,s={},close=()=>{if(s.close?.(),a?.(),i&&!i.cleanup())throw new SqliteSnapshotCleanupError(`SQLite inspection snapshot cleanup failed.`);n.readers.delete(close)};n.readers.add(close);let c=openNodeSqliteDatabase(i?.location??(r?resolveImmutableSqliteFileUri(e):e),{...t,readOnly:!0}),l=c.close.bind(c);return s.close=()=>{c.isOpen&&(l(),r&&assertCustodiedSourceUnchanged(e,r))},c.close=close,c}function prepareSqliteReadOnlyLocationSync(e,t){let n=createSqliteSnapshotStagingDirectorySync();try{return adoptPreparedLocation(runSqliteReadOnlyWorkerSync(e,n,`sync`,t),n)}catch(e){throw removeTempDirectory(n)?e:new SqliteSnapshotCleanupError(`${coerceErrorMessage(e)}; SQLite snapshot cleanup failed: ${n}`,{cause:e})}}var TF=__esmMin((()=>{O(),aA(),Ix(),LA(),W(),xF(),TM(),cF(),ZA(),vM(),yF(),ZP(),QP(),qv(),wF()}));function quarantineDecisionAdmission(e){return{name:`openclaw.quarantine.decision:${S.resolve(e)}`,lifetime:`process`,read:e=>e===null||isQuarantineDecision(e)?e:void 0}}function isQuarantineDecision(e){return isRecord(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:Jb(e,DF);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&&publishSqliteDatabaseAdmission(e,DF,{version:i}),i}function readOpenClawDatabaseQuarantine(e,t={}){let n=resolveQuarantineStorePath(t.env??process.env),load=()=>readPersistedQuarantineDecision(e,n,t.fresh)??null,r=t.fresh?load():Xb(n,quarantineDecisionAdmission(e),load);return r?resolveQuarantineDecision(r,e,n):void 0}function readPersistedQuarantineDecision(e,t,n=!1){if(!l(t))return;let r=openSqliteReadOnlyDatabase(t,{timeout:EF}),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 lN(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(S.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(S.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 lN))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 ${WS}.`);return a.name=`SqliteIntegrityError`,i&&(a.cause=i),a}var EF,DF,OF=__esmMin((()=>{D(),LA(),ID(),J(),vF(),cA(),TF(),NS(),uN(),Z(),X(),EF=5e3,DF={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 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),r?.isCurrent()?r.retire():a.retiring=!1,a.retirement=void 0,a.asyncRetirement=void 0,i?.(),i=void 0,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),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.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||((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)}}}}}function assertStateDatabaseBorrowersReleased(e,t){if(e?.references.size)throw Error(`OpenClaw state database still has active native borrowers: ${t}`)}var kF=__esmMin((()=>{LS(),X()}));function createStateDatabaseCacheAdmission(e){return{closeTerminalFailure(t,n){markOpenClawStateDatabaseFailure(n,t),revokeSqliteDatabaseAdmissionsForPath(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)}throwSqliteLifecycleErrors(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(isSqliteCorruptionError(i)){e.evict(t);return}throw i}}}}var AF=__esmMin((()=>{J(),kb(),W(),Y(),fN()})),jF,MF=__esmMin((()=>{Hv(),jF=18e5}));function createStateDatabaseIdleRetirement({cachedDatabases:e,retainedDatabaseHandles:t,idleTimers:n,idleReferences:r,borrowers:i},a){let touch=s=>{if(!(e.get(s.path)===s&&s.db.isOpen)&&t.get(s.db)!==s)return;let c=n.get(s.db);if(c){c.refresh();return}let l=runInDetachedAsyncContext(()=>setTimeout(()=>{n.delete(s.db);try{s.db.isOpen&&s.db.isTransaction?touch(s):!i.get(s.db)?.references.size&&!r.get(s.db)?.size&&a(s,!1,{busyTimeoutMs:0,checkpointMode:`PASSIVE`})}catch(e){NF.warn(`Idle shared-state database cleanup failed`,{path:s.path,error:e}),touch(s)}},jF));l.unref(),n.set(s.db,l)};return{touch,retain(t){if(e.get(t.path)!==t||!t.db.isOpen||i.get(t.db)?.retiring)throw Error(`OpenClaw state database idle retention requires its current canonical handle`);let n=r.get(t.db)??/* @__PURE__ */ new Set,a={};return n.add(a),r.set(t.db,n),()=>{n.delete(a)&&e.get(t.path)===t&&t.db.isOpen&&touch(t)}}}}var NF,PF=__esmMin((()=>{MF(),Ev(),Qd(),NF=createSubsystemLogger(`state/db`)})),FF={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=FF){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})}var IF,LF=__esmMin((()=>{IF=loadHostEnvSecurityPolicy()})),RF,zF=__esmMin((()=>{Bp(),LF(),new Set(IF.blockedKeys),new Set(IF.blockedInheritedKeys),new Set(IF.blockedOverrideKeys),RF=/* @__PURE__ */ new Set([...Object.keys(resolveNodeServiceIdentityEnvironment()),`OPENCLAW_GATEWAY_SERVICE_PID`]),RF.delete(`OPENCLAW_PROFILE`),new C})),BF=__esmMin((()=>{Zy()})),VF=__esmMin((()=>{RM(),BF()}));function findCaseInsensitiveEnvKey(e,t){if(Object.hasOwn(e,t))return t;let n=t.toUpperCase();return Object.keys(e).find(e=>e.toUpperCase()===n)}var HF=__esmMin((()=>{Yd(),Jd(),zF(),rp(),VF()}));function resolveAppliedConfigEnvOwnership(e){return{...UF.get(e),...e===process.env?WF.ownedEnv:{}}}function cloneEnvWithPlatformSemantics(e){let t={...fsSafeEnvInput(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)}})),UF.set(t,resolveAppliedConfigEnvOwnership(e)),normalizeFsSafeNativeEnv(t),t}var UF,WF,GF=__esmMin((()=>{Yd(),Jd(),HF(),UF=/* @__PURE__ */ new WeakMap,new C,WF={ownedEnv:{},sourceConfig:null}}));function getGatewayServiceInstallation(){return KF.getStore()?.installation}var KF,qF=__esmMin((()=>{B(),KF=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayServiceInstallation`),()=>new C)}));function isGatewayExternallySupervised(e=process.env){return e[JF]?.trim().toLowerCase()===`external`}var JF,YF=__esmMin((()=>{Up(),JF=`OPENCLAW_SUPERVISOR_MODE`})),XF=__esmMin((()=>{ou(),G(),gu()}));function canonicalPath(e){let t=resolveDatabasePath({path:e});try{return normalizeDatabasePath(m.native(t))}catch(e){if(w(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=ZF.scopes.getStore();return assertSchemaScopeActive(e),e?.path}function captureOpenClawStateSchemaReadAdmission(e){let t=ZF.scopes.getStore();if(t)return isExistingOpenClawStateSchema(e),{path:t.path,assertCurrent:()=>assertSchemaScopeActive(t)}}function isExistingOpenClawStateSchema(e,t){let n=getExistingOpenClawStateSchemaPath(),r=ZF.scopes.getStore(),i=t&&ZF.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(),r=ZF.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=ZF.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}; update that installation before retrying the managed node.`)}var ZF,QF=__esmMin((()=>{H(),qv(),B(),X(),ZF=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseSchemaPolicies`),()=>({scopes:new C,existingDatabases:/* @__PURE__ */ new WeakMap}))}));function captureSqliteWorkerStateContext(e){return{databaseEngineSelection:e.databaseEngineSelection??getDatabaseEngineSelection(),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,...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))}var $F=__esmMin((()=>{B(),aA(),QF(),cP(),qF(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerStateContext`),()=>new C)}));function resolveLegacyCronDefaultStoreKey(e){return S.resolve(resolveConfigDir(e),`cron`,`jobs.json`)}var eI=__esmMin((()=>{D(),ou(),yp(),XF(),G(),$F(),$()}));function captureOpenClawStateReadContextWithAdmission(e,t,n){let r=captureOpenClawStateSchemaReadAdmission(e),i=t(e),a=getGatewayServiceInstallation(),s=i.captureIntegrity?.(),c=i.assertCurrent,l=i,runInCapturedSchemaScope;if(r){let e=C.snapshot();l={databasePath:i.databasePath,coordinationKey:i.coordinationKey,get identity(){return i.identity},captureIntegrity:i.captureIntegrity,assertCurrent(){i.assertCurrent(),r.assertCurrent()}},runInCapturedSchemaScope=t=>e(()=>(l.assertCurrent(),t()))}return{databaseEngineSelection:getDatabaseEngineSelection(),maintenanceScope:getOpenClawDatabaseMaintenanceScope(),admission:l,assertPublicationCurrent:c,existingSchemaPath:r?.path,gatewayServiceInstallation:a&&n(a.databasePath)?.key===i.identity.key?a:void 0,stateIntegrity:s,runInCapturedSchemaScope,artifactPreservingReads:isArtifactPreservingStateRead(`agent`,e)||void 0}}function captureOpenClawStateReadWorkerContextWithAdmission(e,t,n){let r=e.env??process.env,i=process.platform===`win32`?cloneEnvWithPlatformSemantics(r):r,a={OPENCLAW_STATE_DIR:resolveStateDir(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:mergeProcessEnv([e.env??process.env,{OPENCLAW_STATE_DIR:void 0,OPENCLAW_SUPERVISOR_MODE:void 0},r.environment]),...e.initializationAgentPaths?{initializationAgentPaths:e.initializationAgentPaths.map(e=>S.resolve(e))}:{}}}var tI=__esmMin((()=>{GF(),vp(),cP(),qF(),YF(),Yt(),aA(),LS(),eI(),QF(),X()}));function getPluginSharedStateResourceHost(){return nI.resolveHost?.()}function runPluginSharedStateWork(e){let t=getPluginSharedStateResourceHost();return t?t.trackSharedStateWork(e):e()}var nI,rI=__esmMin((()=>{B(),nI=resolveGlobalSingleton(Symbol.for(`openclaw.pluginSharedStateAdmission`),()=>({}))}));function createSqliteWorkerAdmissionWarning(){let e=0;return(t,n)=>{let r=Date.now();r>=e&&(e=r+iI,getChildLogger({subsystem:`infra/sqlite-worker`}).warn(`SQLite worker admission delayed`,{queueDepth:t,waitMs:n}))}}function validateSqliteWorkerDatabaseLocator(e){let t=S.basename(e);if(!e||e.startsWith(`file:`)||t===`:memory:`||t===`incognito-openclaw-agent.sqlite`)throw Error(`SQLite worker stores require a file-backed filesystem path; in-memory and incognito databases are not supported`)}function reserveSqliteWorkerClient(e,t,n,r){let i=e.size<n;if(!i&&![...t].some(e=>e.retireIdle))throw new SqliteWorkerError(`SQLite worker store capacity reached`,`overloaded`);return i&&e.add(r),i}function findReusableSqliteWorkerClient(e,t){for(let n of e)if(!n.sealed&&n.isAvailable()&&n.actor.pathReferences.has(t))return n}async function reclaimSqliteWorkerClient(e,t,n,r){let assertCurrent=()=>{if(e.signal?.throwIfAborted(),e.assertCurrent?.(),r())throw new SqliteWorkerError(`SQLite worker host is closing`,`closed`)};assertCurrent();for(let r of t){if(n())return;r.actor.runtimeGeneration===e.runtimeGeneration&&await r.retireIdle?.(),assertCurrent()}if(!n())throw new SqliteWorkerError(`SQLite worker store capacity reached`,`overloaded`)}function captureSqliteWorkerOpen(e,t,n,r={}){let{createAdmission:i,preparation:a,retireIdle:s,...c}=r,l=C.snapshot(),u=e.admission,d=u?()=>{n?.(),u.assertCurrent()}:n,f=d?()=>l(d):void 0,p=S.resolve(e.databasePath);if(e.admission&&(!e.existingOnly||!e.admission.identity.startsWith(`file:`)))throw Error(`Owned SQLite Worker admission requires an existing physical identity`);f?.();let m=resolveRuntimeWorkerGenerationUrl(resolveRuntimeProcessEntrypointUrl(`sqliteStore`),e.runtimeGeneration);return{...c,carrierClass:r.carrierClass??e.isolation,retireIdle:s?()=>l(s):void 0,maintenanceScope:r.cleanupAccess?void 0:r.maintenanceScope??getOpenClawDatabaseMaintenanceScope(),...a===void 0?{}:{preparation:Ct(a)},runtimeGeneration:e.runtimeGeneration,carrierUrl:m,createAdmission:i?e=>l(i,e):void 0,assertCurrent:f,...e.admission?{expectedIdentity:e.admission.identity,expectedBirthtime:e.admission.birthtime,createOpenAdmission:()=>{let e=!1;return{nativeLocations:[p],admission:createSqliteWorkerOperationAdmission((t,n)=>{if(e||t.stage!==`open`)throw Error(`SQLite Worker open admission requested out of order`);if(f(),!n())throw Error(`SQLite Worker open admission expired`);e=!0})}}}:{},moduleUrl:new URL(e.moduleUrl),databasePath:p,input:Ct(e.input),existingOnly:e.existingOnly===!0,...t?{stateContext:captureSqliteWorkerStateContext(t)}:{}}}function validateSqliteWorkerModuleUrl(e){if(e.protocol!==`file:`||e.search||e.hash)throw Error(`SQLite worker backend must be a static local module URL`)}async function prepareSqliteWorkerDatabaseAdmission(e){validateSqliteWorkerModuleUrl(e.moduleUrl);let t=S.resolve(e.databasePath),n=ye(`sha256`).update(e.input).digest(`hex`),r=await readDatabasePathIdentity(t);if(e.assertCurrent?.(),e.expectedIdentity&&(r.key!==e.expectedIdentity||e.expectedBirthtime!==void 0&&r.birthtime!==e.expectedBirthtime))throw Error(`SQLite Worker path no longer matches its borrowed native owner`);return{databasePath:t,inputHash:n,identity:r,key:r.key}}function captureSqliteWorkerAdmissionPaths(e,t,n){let r=/* @__PURE__ */ new Set([e,t.canonicalPath]);if([...n].some(e=>e.key!==t.key&&[...r].some(t=>e.pathReferences.has(t))))throw Error(`SQLite database pathname changed while its worker owner is active; close the existing store first`);return r}function retainSqliteWorkerAdmissionCleanup(e,t,n){t?.({get pending(){return e.references===0&&e.cleanupState===`pending`},close:()=>e.references===0?n():Promise.resolve()})}function retainSqliteWorkerAdmissionPathReferences(e,t){for(let n of t)e.pathReferences.set(n,(e.pathReferences.get(n)??0)+1);return()=>{for(let n of t){let t=e.pathReferences.get(n)??0;t>1?e.pathReferences.set(n,t-1):e.pathReferences.delete(n)}}}function suspendSqliteWorkerScheduledMaintenance(e,t){if(!e.stateContext)return;let n=e.stateContext.scheduledMaintenanceSuspension??=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);if(!t)return;let r=new Int32Array(n);return Atomics.add(r,0,1),()=>{Atomics.sub(r,0,1)}}async function resolveOpenedSqliteWorkerIdentity(e,t,n){let r=await readDatabasePathIdentity(e),i=r.key;if(r.canonicalPath!==t.canonicalPath)throw Error(`SQLite database canonical pathname changed during open`);if(!i.startsWith(`file:`))throw Error(`SQLite worker backend did not establish its database file`);if(n(i))throw Error(`SQLite database identity collided with an existing worker owner during open`);if(t.key.startsWith(`file:`)&&i!==t.key)throw Error(`SQLite database file identity changed during open`);return r}function findUnclaimedSharedStateActors(e,t){let n=S.resolve(t);return[...e].filter(e=>e.stateContext!==void 0&&e.references===0&&e.cleanupState===`pending`&&e.databasePath===n)}async function closeUnclaimedSharedStateActors(e,t,n){let r=(await Promise.allSettled(findUnclaimedSharedStateActors(e,t).map(n))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(r.length)throw AggregateError(r,`SQLite worker unclaimed cleanup failed`,{cause:r[0]})}async function resolveSqliteWorkerModuleUrl(e){let t=await Ke(Ie(e)),n=Le(t).href;if(!/\.[cm]?[jt]s$/.test(t)||!(await Je(t)).isFile())throw Error(`SQLite worker backend must identify a JavaScript or TypeScript file`);return{modulePath:t,moduleUrl:n}}function assertSqliteWorkerActorStateContext(e,t){let n=t?.gatewayServiceInstallation;if(e.stateContext?.existingSchemaPath!==t?.existingSchemaPath||n!==void 0&&!he(e.stateContext?.gatewayServiceInstallation,n))throw Error(`Shared-state worker schema policy changed; close its actor first`)}function assertSqliteWorkerActorReusable(e,t,n,r){if(e.moduleUrl!==t||e.inputHash!==n)throw Error(`SQLite database already belongs to another worker backend`);assertSqliteWorkerActorStateContext(e,r)}function prepareSqliteWorkerActorContext(e,t){let{request:n}=t,r=n.stateContext??e?.stateContext;if(e&&r){assertSqliteWorkerActorStateContext(e,r),n.stateDatabasePath=e.stateDatabasePath??e.databasePath;let t={...r,gatewayServiceInstallation:e.stateContext?.gatewayServiceInstallation,...e.stateContext?.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.stateContext.scheduledMaintenanceSuspension}:{}};if(n.type!==`open`){let r=e.deliveredStateContext;n.stateContext={...t,...t.scheduledMaintenanceSuspension&&t.scheduledMaintenanceSuspension===r?.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:void 0}:{},...Object.hasOwn(t,`stateIntegrity`)&&t.stateIntegrity===r?.stateIntegrity?{stateIntegrity:void 0}:{}}}else n.stateContext=t;return t}}var iI,aI=__esmMin((()=>{gv(),Rj(),LS(),qD(),YD(),Tk(),qv(),tA(),$F(),iI=1e4}));async function acquireWithWait(e){let t=e.now??performance.now.bind(performance),n=e.pollIntervalMs;for(;;)try{return await e.acquire()}catch(r){let i=e.shouldRetry(r);if(!i)throw r;let a=e.deadlineMs-t();if(a<=0)throw r;await(e.sleep??ft)(Math.min(i===!0?n:i.delayMs,a)),n=Math.min(n*2,e.maxPollIntervalMs??e.pollIntervalMs)}}var oI=__esmMin((()=>{}));function ownedWorkerBytes(e){if(e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&!ot(e.buffer))return new Uint8Array(e.buffer);let t=new Uint8Array(e.byteLength);return t.set(e),t}var sI=__esmMin((()=>{}));async function dispatchSqliteWorkerJob(e,t,n){let r=[...e.actors].find(e=>e.id===t.request.actor),assertCurrentJob=()=>{if(!readSqliteWorkerRequestCustody(t.custody.descriptor))throw e.failed??new SqliteWorkerError(`SQLite worker job is no longer current`,`closed`)},assertDispatchable=()=>{t.custody.dispatched||t.signal?.throwIfAborted(),t.assertCurrent?.(),assertCurrentJob()};try{t.signal?.throwIfAborted(),assertCurrentJob();let n=prepareSqliteWorkerActorContext(r,t),i=r?.stateAccess,a=i?.canonicalPath,s;if(i&&t.request.type!==`close`){let prepareAccess=async()=>{t.signal?.throwIfAborted(),assertCurrentJob();let e=await i.prepareAccess({maintenanceScope:t.maintenanceScope,schemaLease:t.cleanupAccess});return t.signal?.throwIfAborted(),assertCurrentJob(),e(),e},isPending=e=>e instanceof VD&&e.databasePath===a;try{s=await prepareAccess()}catch(e){if(!isPending(e))throw e;s=await acquireWithWait({acquire:prepareAccess,shouldRetry:isPending,deadlineMs:performance.now()+US,pollIntervalMs:10,sleep:e=>sleepWithAbort(e,t.signal)})}}if(t.createAdmission||a){let n=createDeferredCore();t.settleNative=n.resolve;let i=t.createAdmission?t.createAdmission({settled:n.promise,nativeStopped:r?.nativeStopped??e.exit}):{admission:createSqliteWorkerOperationAdmission(()=>{throw new SqliteWorkerError(`SQLite domain operation requires its own admission`,`closed`)}),nativeLocations:a?[a]:[]};try{if(i.admission.requestClass=t.observation.requestClass,i.databaseIdentity){let e=t.request.databaseIdentity;if(e&&(e.databasePath!==i.databaseIdentity.databasePath||e.key!==i.databaseIdentity.key||e.birthtime!==i.databaseIdentity.birthtime))throw new SqliteWorkerError(`SQLite request physical identities differ`,`closed`);t.request.databaseIdentity=i.databaseIdentity}if(bindSqliteWorkerDatabaseAdmissionCursor(i.admission,e.databaseAdmissionCursor,()=>e.databaseAdmissionCursor=createSqliteDatabaseAdmissionCursor()),a){let assertCreate=e=>{let n=/* @__PURE__ */ new Set;if(t.request.type===`open`&&!t.request.existingIdentity&&(n.add(resolveIdentityPathViaExistingAncestorSync(t.request.databasePath)),n.add(resolveIdentityPathViaExistingAncestorSync(a))),r?.stateContext){let e=resolveIdentityPathViaExistingAncestorSync(r.databasePath);for(let t of[r.stateDatabasePath,resolveQuarantineStorePath(r.stateContext.environment)])if(t){let r=resolveIdentityPathViaExistingAncestorSync(t);r!==e&&n.add(r)}}if(!n.has(resolveIdentityPathViaExistingAncestorSync(e)))throw new SqliteWorkerError(`SQLite creation target differs from its captured database`,`closed`)},e,assertAccess=()=>{assertCurrentJob(),t.maintenanceScope?.assertAdmission();let n={maintenanceScope:t.maintenanceScope,schemaLease:e??t.cleanupAccess};s?s(n):r?.stateAccess.assertReadAllowed(n)};i.admission.bindDatabaseAuthority({databasePath:a,databaseIdentity:t.request.databaseIdentity,...t.request.type===`open`&&!t.request.existingIdentity&&resolveIdentityPathViaExistingAncestorSync(t.request.databasePath)===resolveIdentityPathViaExistingAncestorSync(a)?{coldOpenPath:a}:{},assertRequest:assertDispatchable,assertAccess,...t.request.type===`close`?{}:{assertCreate},acquireSchema(){assertAccess();let acquire=()=>acquireStateDatabaseSchemaLease(a),n=t.maintenanceScope?t.maintenanceScope.run(acquire):acquire();return e=n,t.maintenanceScope?.own(n,`shared-resources`,()=>n.release()),n}})}}catch(e){throw i.admission.finish(`not-entered`),e}t.operationAdmission={admission:i.admission,releaseService:retainSqliteWriteAdmissionService([...i.nativeLocations,...a?[a]:[],...r?.pathReferences.keys()??[]],()=>i.admission.service())},t.request.executionAuthority=readSqliteWorkerExecutionAuthority(i.admission),t.request.operationAttachment=i.admission.attachment,t.request.operationAdmission=i.admission.port}else t.request.operationAdmission=void 0;let c=captureSqliteDatabaseAdmissions(e.databaseAdmissionCursor);c.length>0&&(t.request.databaseAdmissions=c),t.request.timing=t.observation.timing,t.request.requestCustody=t.custody.descriptor;let l=prepareSqliteWorkerRequest(t);assertDispatchable();let u=l.stateContext?.databaseEngineSelection;!e.postgresPoolSent&&u&&(l.postgresPool=createPostgresPoolEndpoints(u)),s?.(),t.custody.accept(),t.detach(),r&&l.type!==`close`&&(r.openDispatch.openRefused=!1),t.custody.post(),l.timing&&(l.timing.posted=performance.now()),e.worker.postMessage(l,[...postgresPoolTransferList(l.postgresPool),...new Set(Object.values(l.transferredInput??{}).map(e=>e.buffer)),...l.operationAdmission?[l.operationAdmission]:[],...`input`in l?[l.input.buffer]:[],...l.type===`open`&&l.preparation?[l.preparation.buffer]:[]]),l.postgresPool&&(e.postgresPoolSent=!0),r&&n&&(r.deliveredStateContext=n),l.timing&&(l.timing.postFinished=performance.now())}catch(r){e.databaseAdmissionCursor=createSqliteDatabaseAdmissionCursor(),n(r,t.custody.postAttempted)}}function prepareSqliteWorkerRequest(e){if(e.request.type!==`execute`||e.request.input.byteLength<=33554432)return`input`in e.request&&(e.request.input=ownedWorkerBytes(e.request.input)),e.request.type===`open`&&e.request.preparation&&(e.request.preparation=ownedWorkerBytes(e.request.preparation)),e.request;let{input:t,...n}=e.request,r=createSqliteWorkerTransferOwner(),i=r.start([{kind:`command`,serialized:t}].values(),{kinds:[`command`]});return e.inputTransfer={id:i.id,producer:r},e.request.input=/* @__PURE__ */ new Uint8Array,{...n,type:`execute-start`,transfer:i}}function decodeSqliteWorkerReplyError(e){if(e.name===`SqliteWorkerAdmissionTimeoutError`&&e.code===`admission-timeout`)return new wk;if(e.name===`SqliteWorkerError`&&e.code===`outcome-unknown`)return new SqliteWorkerError(e.message,`outcome-unknown`);let t=Object.assign(Error(e.message),{name:e.name,...e.code===void 0?{}:{code:e.code}});return e.sharedState?(retainOpenClawStateWorkerErrorPayload(t,e.sharedState),hydrateOpenClawStateWorkerError(t,{includeOrdinary:!0})):t}function decodeSqliteWorkerCleanupError(e){let t=/* @__PURE__ */ Error(`SQLite worker native cleanup failed`);return retainOpenClawStateWorkerErrorPayload(t,e),hydrateOpenClawStateWorkerError(t,{includeOrdinary:!0})}function receiveSqliteWorkerReply(e,t,n){let r=e.current;if(!r||t.id!==r.request.id){n.fail(/* @__PURE__ */ Error(`SQLite worker returned an unexpected response`));return}if(t.transactionCount!==void 0&&r.observation.recordTransactions?.(t.transactionCount),r.observation.timing&&t.timing&&Object.assign(r.observation.timing,t.timing,{replyReceived:performance.now()}),!t.ok){let i=r.operationAdmission?.admission;if(t.cleanupFailure&&r.custody.dispatched&&!t.retire){let e=(i?.failureSource===`domain`&&!t.admissionRefused?void 0:i?.failure)??decodeSqliteWorkerReplyError(t.error);n.fail(decodeSqliteWorkerCleanupError(t.cleanupFailure),void 0,void 0,{error:e});return}t.openNotEntered&&r.request.type===`open`&&r.dispatchState&&(r.dispatchState.openNotEntered=!0);let a=decodeSqliteWorkerReplyError(t.error),s=t.openOutcome===`refused-before-agent-open`;if(!t.retire&&(s||r.request.type===`open`&&t.openNotEntered)){r.custody.retire(),e.current=void 0;let c=i?.failure??a;if(n.finish(r,c,void 0,t.openNotEntered?{kind:`not-entered`,error:c}:{kind:`completed`}),s){let t=[...e.actors].find(e=>e.id===r.request.actor);t&&(t.openDispatch.openRefused=!i?.cleanupFailures.length)}n.dispatch();return}if(r.request.type!==`execute`||t.retire){let e=r.request.type===`open`&&s,c=e||t.admissionRefused?toErrorObject(i?.failure??a,a.message):a;n.fail(c,r.request.type!==`execute`||t.admissionRefused?c:void 0,e?`refused-before-agent-open`:void 0);return}r.custody.retire(),e.current=void 0,n.finish(r,i?.failure??a),n.dispatch();return}let i;try{let n=runWithMainThreadTask(`worker:sqlite`,()=>{if(t.input===`next`){let e=r.inputTransfer;if(!e||t.transfer)throw Error(`SQLite worker requested unexpected command input`);let n=e.producer.next(e.id),i=ownedWorkerBytes(Ct(n));if(i.byteLength>33554432)throw Error(`SQLite worker input frame exceeds the transport byte limit`);return n.done&&(e.producer.end(e.id),r.inputTransfer=void 0),{type:`execute-frame`,id:r.request.id,actor:r.request.actor,input:i}}if(r.inputTransfer)throw Error(`SQLite worker completed before receiving its command input`);if(t.transfer===`start`){let e=St(t.value);if(r.request.type!==`execute`||r.transfer||e.kinds.length!==1||e.kinds[0]!==`result`)throw Error(`SQLite worker returned an unexpected result transfer`);let n={id:e.id,value:void 0,receiver:createSqliteWorkerTransferReceiver(e,e=>{n.value=e.value})};r.transfer=n}else if(t.transfer===`frame`){let e=r.transfer;if(!e)throw Error(`SQLite worker returned an unexpected result frame`);let n=St(t.value),a=e.receiver.accept(n);if(a){if(a.length!==1||a[0]?.[1]!==1)throw Error(`SQLite worker returned an incomplete result transfer`);i=e.value,r.transfer=void 0}}else{if(r.transfer)throw Error(`SQLite worker ended its result transfer without completion`);i=St(t.value)}if(r.transfer)return{type:`result-next`,id:r.request.id,actor:r.request.actor,transferId:r.transfer.id}},`reply-decode`);if(n){e.worker.postMessage(n,n.type===`execute-frame`?[n.input.buffer]:[]);return}}catch(e){n.fail(e);return}if(t.cleanupFailure){let e=r.operationAdmission?.admission,a=e?.failureSource===`domain`?void 0:e?.failure;n.fail(decodeSqliteWorkerCleanupError(t.cleanupFailure),void 0,void 0,a===void 0?{value:i}:{error:a})}else{if(t.nativeRuntimeAdmission!==void 0&&installSqliteNativeRuntimeAdmission(t.nativeRuntimeAdmission),r.custody.retire(),e.current=void 0,r.request.type===`close`){if(t.closeReceipt){let n=[...e.actors].find(e=>e.id===r.request.actor);n&&(n.closeReceipt=t.closeReceipt)}n.finish(r,void 0,i)}else{let e=r.operationAdmission?.admission;n.finish(r,e?.failureSource===`domain`?void 0:e?.failure,i)}n.dispatch()}}function withSqliteWorkerCleanupFailure(e,t){return t===void 0?e:retainSqliteWorkerErrorCode(AggregateError([e,t],`SQLite worker failure and cleanup failed`,{cause:e}),e)}function failSqliteWorkerSlot(e,t,n){if(e.failed)return;let r=toErrorObject(t,`SQLite worker failed`);e.custody.retire(),e.failed=new SqliteWorkerError(r.message,`unavailable`),e.failed.cause=r;for(let t of e.actors)t.backendClosed||notifyListeners(t.nativeLostObservers??[],e.failed);for(let t of n.waiters??[])t(e.failed);let i=e.current;i?.custody.retire(),e.current=void 0,i&&(i.inputTransfer?.producer.cancel(),i.inputTransfer=void 0,i.transfer=void 0);let{currentError:a,completed:s,openOutcome:c,retire:l,finish:u}=n,d=e.failed,f=e.queue.splice(0),p=l(),finishFailed=(e,t)=>{if(i&&s)process.emitWarning(Error(`SQLite worker operation completed before native cleanup failed`,{cause:withSqliteWorkerCleanupFailure(r,t)})),u(i,`error`in s?s.error:void 0,`value`in s?s.value:void 0,e?{kind:`completed`}:{kind:`unknown`,error:t??r});else if(i){let n=a??new SqliteWorkerError(`SQLite worker stopped before its result was received: ${r.message}`,i.request.type===`execute`&&i.custody.dispatched?`outcome-unknown`:`unavailable`);a||(n.cause=r),u(i,withSqliteWorkerCleanupFailure(n,t),void 0,i.custody.dispatched?e&&c===`refused-before-agent-open`?{kind:`completed`}:{kind:`unknown`,error:a??r,...e?{nativeStopped:!0}:{}}:{kind:`not-entered`,error:r})}for(let e of f)u(e,withSqliteWorkerCleanupFailure(d,t))};p.then(()=>finishFailed(!i?.operationAdmission?.admission.cleanupFailures.length),e=>finishFailed(!1,e))}function settleSqliteWorkerJob(e,t,n,r){e.custody.retire();let i=r??(e.custody.dispatched?{kind:`completed`}:{kind:`not-entered`,error:t});e.settleNative?.(i),e.operationAdmission?.admission.finish(i.kind===`not-entered`?`not-entered`:void 0),e.operationAdmission?.releaseService();let a=e.operationAdmission?.admission,s=t??(a?.failureSource===`domain`?void 0:a?.failure),c=e.operationAdmission?.admission.cleanupFailures??[];if(c.length>0){e.dispatchState&&(e.dispatchState.openRefused=!1);let t=AggregateError(c,`SQLite worker admission cleanup failed`);s===void 0&&e.request.type===`execute`?process.emitWarning(t):s=s===void 0?t:withSqliteWorkerCleanupFailure(toErrorObject(s,`SQLite worker failed`),t)}e.inputTransfer?.producer.cancel(),e.inputTransfer=void 0,e.transfer=void 0,e.detach(),s===void 0?e.resolve(n):e.reject(s)}var cI=__esmMin((()=>{O(),Tp(),It(),pu(),Z(),X(),WN(),oI(),sp(),UD(),xk(),ef(),LA(),pP(),J(),NS(),aI(),Tk(),tA(),Hk(),Qj(),sI()}));function cleanupFailures(e){return e.flatMap(e=>e.status===`rejected`?[e.reason]:[])}function createSqliteWorkerLifecycle({explicitSqliteCloseReleasesNativeResources:e,actors:t,slots:n,stores:r,enqueueClose:i,fail:a}){function sealClients(e,t=!1){for(let t of e)for(let e of t)e(new SqliteWorkerError(`SQLite worker host is closing`,`overloaded`));for(let e of r.values())(!t||!e.actor.stateContext)&&(e.sealed=!0)}async function closeHost({inputAdmission:e,operations:i,waiters:a}){sealClients(a);let s=[];try{await e.joinOpens(),await Promise.allSettled(i);let n=await Promise.allSettled([...t.values()].map(e=>closeActor(e)));s.push(...cleanupFailures(n)),await e.joinPreparations()}catch(e){s.push(e)}if(s.push(...cleanupFailures(await Promise.allSettled([...n].map(retireEmpty)))),s.length)throw AggregateError(s,`SQLite worker host cleanup failed`);r.clear()}async function acquireSlot(t,r,i){t.signal?.throwIfAborted(),t.assertCurrent?.(),t.signal?.throwIfAborted();let a=e,s=[...n].filter(e=>e.carrierClass===t.carrierClass),c=t.carrierClass&&t.carrierClass!==`agent`?1:r.maxWorkers,l=s.filter(e=>!e.failed&&!e.retiring&&e.runtimeGeneration===t.runtimeGeneration),u=a&&t.runtimeGeneration!==void 0&&l.length===0&&s.length>=c&&!s.some(e=>e.borrowedGenerationSlot);if(!u&&(a?s.length>=c:n.size>=r.maxStores)){if(!l.length||!a){let e=(a?s:[...n]).filter(e=>!!(e.failed||e.retiring));if(e.length>0)return await racePromiseWithAbortSignal(Promise.race(e.map(({exit:e})=>e)),t.signal,e=>e.reason),acquireSlot(t,r,i);throw new SqliteWorkerError(`SQLite worker ${a?`runtime`:`store`} capacity reached`,`overloaded`)}let e=l.filter(e=>!e.current),c;if(e.length===0){if(c=await raceWithTimeout(Promise.race(l.map(e=>e.current.result.then(()=>e,()=>e))),iI,()=>{throw new SqliteWorkerError(`SQLite worker queue capacity reached`,`overloaded`)},{signal:t.signal,onAbort:e=>{throw e.reason}}),t.signal?.throwIfAborted(),t.assertCurrent?.(),t.signal?.throwIfAborted(),c.failed||c.retiring||c.exited)return acquireSlot(t,r,i)}else c=e.reduce((e,t)=>e.actors.size<=t.actors.size?e:t);return c.pendingOpens+=1,c}return createSlot(t,u,i)}function createSlot(e,t,r){e.signal?.throwIfAborted(),ensureSqliteLibrarySelected(),e.assertCurrent?.(),e.signal?.throwIfAborted();let{carrierUrl:i}=e,s=createSqliteDatabaseAdmissionCursor();captureSqliteDatabaseAdmissions(s);let c=createPostgresPoolEndpoints(),{worker:l,exited:u}=runInDetachedAsyncContext(()=>({worker:createCpuTrackedWorker(i,{resourceLimits:{maxOldGenerationSizeMb:512,maxYoungGenerationSizeMb:32},env:resolveNodeCompileCacheEnv(),execArgv:resolveRuntimeWorkerThreadExecArgv(i),workerData:{postgresPool:c},transferList:postgresPoolTransferList(c)},()=>d.current?.observation.requestClass),exited:createDeferredCore()}));trackSqliteDatabaseAdmissionWorker(l);let d={carrierClass:e.carrierClass,postgresPoolSent:c!==void 0,custody:new SqliteWorkerSlotCustody,databaseAdmissionCursor:s,runtimeGeneration:e.runtimeGeneration,...t?{borrowedGenerationSlot:!0}:{},worker:l,receiveReply:e=>receiveSqliteWorkerReply(d,e,f),actors:/* @__PURE__ */ new Set,queue:[],exit:u.promise,exited:!1,pendingOpens:1},f=r(d);return n.add(d),l.on(`message`,e=>{receiveWorkerMemoryPort(l,e)||d.receiveReply(e)}),l.on(`error`,e=>a(d,e)),l.on(`messageerror`,e=>a(d,e)),l.once(`exit`,e=>{d.exited=!0,a(d,/* @__PURE__ */ Error(`SQLite worker exited with code ${e}`));for(let e of d.actors)e.backendClosed=!0,e.markNativeStopped();n.delete(d),u.resolve()}),l.unref(),d}async function settleGeneration(e){let r=[...t.values()].filter(t=>t.runtimeGeneration===e),i=Promise.allSettled(r.map(e=>retireActor(e)));return await Promise.all(r.map(async e=>await e.settlement)),async()=>{throwSqliteLifecycleErrors(cleanupFailures(await i),`Retained SQLite worker cleanup failed`),await Promise.all([...n].filter(t=>t.runtimeGeneration===e).map(e=>retireEmpty(e)))}}function releaseActorReference(e){--e.references,e.references||e.onReferencesDrained?.()}async function rejectSlotAdmission(e,t){--e.pendingOpens;try{await retireEmpty(e)}catch(e){throw createSqliteLifecycleAggregateError([t,e],`SQLite slot admission and cleanup failed`,t)}throw t}async function rejectActorAdmission(e,t,n){if(releaseActorReference(e),!e.references){let r=[t];try{if(e.initialized)await closeActor(e,n);else{let n=e.openDispatch.custody.postAttempted&&!e.openDispatch.openNotEntered&&!e.openDispatch.openRefused;!n&&!e.slot.failed&&(e.backendClosed=!0,e.markNativeStopped(),e.cleanupState=`pending`),n&&(a(e.slot,t),await e.slot.exit),forget(e),await retireEmpty(e.slot)}}catch(e){r.push(e)}if(r.length>1)throw AggregateError(r,`SQLite worker admission and cleanup failed`,{cause:t})}throw t}function retireActor(e){let n=[...t.values()].find(t=>t===e);if(!n)return Promise.resolve();if(n.retirement)return n.retirement;n.retirementRequested=!0;let i=createDeferredCore();n.onReferencesDrained=i.resolve,n.references||i.resolve(),n.settlement=i.promise;let a=[...r.values()].filter(e=>e.actor===n);return n.retirement=(async()=>{let e=await Promise.allSettled(a.map(e=>e.close()));await n.settlement;let t=cleanupFailures(e);if(!t.length)try{await closeActor(n)}catch(e){t.push(e)}if(t.length)throw AggregateError(t,`SQLite actor retirement failed`,{cause:t[0]})})().finally(()=>{n.retirement=void 0,n.onReferencesDrained=void 0}),n.retirement}function closeActor(t,n){return t.cleanupState===`complete`?Promise.resolve():(t.closing||=(t.cleanupState=`pending`,(async()=>{let r=[];if(!t.backendClosed)try{await i(t,n),t.backendClosed=!0,e&&t.markNativeStopped()}catch(e){e!==t.slot.failed&&r.push(e),a(t.slot,e instanceof Error?e:Error(String(e))),await t.slot.exit}try{(!e||t.slot.failed||!t.slot.pendingOpens&&[...t.slot.actors].every(e=>e.backendClosed))&&await retire(t.slot)}catch(e){r.push(e)}finally{forget(t)}throwSqliteLifecycleErrors(r,`SQLite worker actor cleanup failed`)})().finally(()=>{t.closing=void 0})),t.closing)}function forget(e){t.get(e.key)===e&&t.delete(e.key),e.slot.actors.delete(e),e.cleanupState=`complete`}async function retireEmpty(e){!e.actors.size&&!e.pendingOpens&&await retire(e)}function retire(e){return e.custody.retire(),e.retiring??=(async()=>{let t=[];if(!e.exited)try{await e.worker.terminate()}catch(e){t.push(e)}await e.exit,throwSqliteLifecycleErrors(t,`SQLite worker retirement cleanup failed`)})().finally(()=>{e.retiring=void 0}),e.retiring}return{sealClients,closeHost,acquireSlot,createSlot,settleGeneration,releaseActorReference,rejectSlotAdmission,rejectActorAdmission,retireActor,closeActor,retire}}var lI=__esmMin((()=>{Tp(),It(),Qd(),Ep(),Yy(),FA(),pP(),Hy(),J(),W(),aI(),cI(),Tk(),Hk(),$O()}));function runSqliteWorkerClientOperation(e,t,n,r,i,a){if(!e||e.sealed)return Promise.reject(new SqliteWorkerError(`SQLite worker store is closed`,`closed`));let s={maintenanceScope:getOpenClawDatabaseMaintenanceScope(),createAdmission:a,assertCurrent:i,active:!0,pending:/* @__PURE__ */ new Set,...n?{stateContext:captureSqliteWorkerStateContext(n)}:{}},c=createDeferredCore();e.scopes.add(c.promise);let l=r(c.promise);return(async()=>{try{let n=t({execute:(t,n={})=>e.execute(t,n,s)});return gt(n)?await n:n}finally{s.active=!1,await Promise.allSettled(s.pending),e.scopes.delete(c.promise),l(),c.resolve()}})()}function sqliteWorkerTransferredInputBytes(e){return[...new Set(Object.values(e??{}).map(e=>e.buffer))].reduce((e,t)=>e+t.byteLength,0)}function createSqliteWorkerClient(e){let t,n=!1,r=/* @__PURE__ */ new Set,i={actor:e.actor,close:()=>a.close(),retireIdle:e.retireIdle?()=>{if(!(i.sealed||i.scopes.size||r.size)){n=!0;try{return e.retireIdle?.()}finally{n=!1}}}:void 0,sealed:e.isDraining(),isAvailable:e.isAvailable,scopes:/* @__PURE__ */ new Set,execute:(t,n,a)=>{if(a?!a.active:i.sealed||e.isDraining())return Promise.reject(new SqliteWorkerError(`SQLite worker store is closed`,`closed`));if(n.signal?.aborted)return Promise.reject(toErrorObject(n.signal.reason,`SQLite worker operation canceled`));let s,c,l,u,d=a?.assertCurrent,f=a?.createAdmission,p=d||f?C.snapshot():void 0;try{let e=t.type;if(l=classifyWorkerRequest(e,t.input),u=d&&p?()=>p(d,e):void 0,u?.(),s=Ct({type:e,input:t.input}),n.transferredInput){let e=[...new Set(Object.values(n.transferredInput).map(e=>e.buffer))];c=structuredClone(n.transferredInput,{transfer:e})}}catch(e){return Promise.reject(toErrorObject(e,`SQLite worker command could not be serialized`))}let m=e.dispatch({payload:s,transferredInput:c},n.signal,a,u,f&&p?e=>p(f,e):void 0,l);r.add(m),a?.pending.add(m);let settled=()=>{r.delete(m),a?.pending.delete(m)};return m.then(settled,settled),m}},a={execute:(e,t={})=>i.execute(e,t),close:()=>{if(!t){i.sealed=!0;let a=n;t=(async()=>{await Promise.allSettled(i.scopes),await Promise.allSettled(r),await e.release(a)})().catch(e=>{throw t=void 0,e})}return t}};return{store:a,client:i}}var uI=__esmMin((()=>{O(),It(),LS(),Tk(),uO(),$F()}));function hasPublishedSchema(e){let t=ex(e);return t!==void 0&&tx(t)}function reserveAdmissionTurn(e){if(e.size===0)return;let t=new Set([...e].flatMap(e=>dI.pending.get(e)??[])),{promise:n,resolve:r}=createDeferredCore();for(let t of e)dI.pending.set(t,n);return{ready:Promise.all(t),release:()=>{for(let t of e)dI.pending.get(t)===n&&dI.pending.delete(t);r()}}}function prepareAdmissionTurn(e,t,n,r=()=>{}){dI.discovering++;let i=dI.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 resolveIdentityPathViaExistingAncestor(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 Ub({location:t,identity:i?.readIdentities?.get(t),assertCurrent:r})}catch(e){if(!isMissingPathError(e))throw e}let c=e?.canonicalPath??await resolveIdentityPathViaExistingAncestor(t);r(),a.add(`path:${c}`),e&&(s.set(t,e),a.add(`${e.key}:${e.birthtime??``}`)),(!e||!tx(e))&&a.add(`family:${S.dirname(c)}`)}return{turn:reserveAdmissionTurn(a),prepared:{readIdentities:s}}}finally{dI.discovering--}});return dI.discovery=i.then(()=>{},()=>{}),i}function runWithSqliteDatabaseAdmissionTurn(e,t,n=[],r,i,a){if(fI.getStore()?.active||!canShareSqliteDatabaseAdmissions())return typeof i==`function`?i().then(t):t(i);let run=(e,n)=>{let r={active:!0};return fI.run(r,async()=>{try{return await t(n)}finally{r.active=!1,e?.release()}})};return!dI.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?racePromiseWithAbortSignal(e.ready,r,e=>e.reason).then(()=>run(e,t),t=>{throw e.ready.then(e.release),t}):run(void 0,t))}var dI,fI,pI=__esmMin((()=>{Tp(),fd(),It(),B(),sp(),H(),J(),dI=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionTurns`),()=>({pending:/* @__PURE__ */ new Map,discovery:Promise.resolve(),discovering:0})),fI=new AsyncContext(Symbol.for(`openclaw.sqliteDatabaseAdmissionTurnContext`))})),SqliteWorkerInputAdmission,mI=__esmMin((()=>{It(),vP(),pI(),Tk(),SqliteWorkerInputAdmission=class{constructor(e){this.owner=e,this.bytes=0,this.opens=/* @__PURE__ */ new Set,this.inputPreparations=/* @__PURE__ */ new Set,this.openQueue=/* @__PURE__ */ new Map}get retainedBytes(){return this.bytes}retain(e){this.bytes+=e;let t=!1;return()=>{t||(t=!0,this.bytes-=e)}}async open(e,t,n,r,i,a){if(this.opens.size>=this.owner.maxPendingOpens||e>this.owner.maxMessageBytes||this.owner.queuedBytes()+this.bytes+e>this.owner.maxQueuedBytes)throw new SqliteWorkerError(`SQLite worker open input capacity reached`,`overloaded`);let s=createDeferredCore();this.opens.add(s.promise);let c=this.retain(e),enqueue=()=>runWithSqliteDatabaseAdmissionTurn([t],()=>runQueuedStoreWrite({queues:this.openQueue,storePath:a??`generic`,label:`SQLite worker open`,fn:n,signal:r}),[],r);try{return await(i?Promise.resolve().then(i).then(e=>e===void 0?enqueue():e):enqueue())}finally{this.opens.delete(s.promise),c(),s.resolve()}}async joinOpens(){for(;this.opens.size>0;)await Promise.allSettled(this.opens)}async joinPreparations(){await Promise.allSettled(this.inputPreparations)}reserveInputPreparation(e,t=`stream`){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`SQLite worker input bytes must be a non-negative safe integer`);if(this.owner.isClosing())throw new SqliteWorkerError(`SQLite worker host is closing`,`closed`);let n=t===`stream`&&e>this.owner.maxQueuedInputBytes?this.owner.maxMessageBytes:e;if(this.owner.queuedBytes()+this.bytes+n>this.owner.maxQueuedBytes)throw new SqliteWorkerError(`SQLite worker input preparation capacity reached`,`overloaded`);this.bytes+=n;let r=createDeferredCore();this.inputPreparations.add(r.promise);let i=!1,release=()=>{this.inputPreparations.delete(r.promise)&&(this.bytes-=n,r.resolve())};return{assertCurrent:()=>{if(!i&&(!this.inputPreparations.has(r.promise)||this.owner.isClosing()))throw new SqliteWorkerError(`SQLite worker input preparation is closed`,`closed`)},handoff:e=>{if(!this.inputPreparations.has(r.promise)||this.owner.isClosing())throw release(),new SqliteWorkerError(`SQLite worker input preparation is closed`,`closed`);return i=!0,release(),e()},release}}}}));function waitForSqliteOpen(e,t){return racePromiseWithAbortSignal(e,t,e=>e.reason)}var hI,gI,_I,SqliteWorkerBroker,vI=__esmMin((()=>{O(),It(),LS(),Ep(),Yy(),xk(),Hy(),aI(),lI(),cI(),uI(),Tk(),Mk(),mI(),$F(),nP(),fM(),hI=64,gI=67108864,_I=268435456,SqliteWorkerBroker=class{constructor(){this.explicitSqliteCloseReleasesNativeResources=captureSqliteWorkerClosePolicy(),this.maxWorkers=resolveSqliteBrokerWorkerCount(),this.waiters=/* @__PURE__ */ new Map,this.resuming=/* @__PURE__ */ new Set,this.warnAdmission=createSqliteWorkerAdmissionWarning(),this.actors=/* @__PURE__ */ new Map,this.slots=/* @__PURE__ */ new Set,this.clients=/* @__PURE__ */ new Set,this.stores=/* @__PURE__ */ new Map,this.operations=/* @__PURE__ */ new Set,this.lifecycle=createSqliteWorkerLifecycle({explicitSqliteCloseReleasesNativeResources:this.explicitSqliteCloseReleasesNativeResources,actors:this.actors,slots:this.slots,stores:this.stores,enqueueClose:(e,t)=>this.enqueue(e.slot,{type:`close`,actor:e.id},0,{maintenanceScope:t}),fail:(e,t)=>this.fail(e,t)}),this.nextActor=0,this.nextRequest=0,this.requests=/* @__PURE__ */ new WeakMap,this.bytes=0,this.inputAdmission=new SqliteWorkerInputAdmission({queuedBytes:()=>this.bytes,isClosing:()=>this.draining!==void 0,maxQueuedBytes:_I,maxQueuedInputBytes:gI,maxMessageBytes:Ck,maxPendingOpens:hI})}reserveInputPreparation(e,t=`stream`){return this.inputAdmission.reserveInputPreparation(e,t)}open(e,t,n,r={}){try{validateSqliteWorkerDatabaseLocator(e.databasePath)}catch(e){return Promise.reject(toErrorObject(e,`SQLite worker database locator is invalid`))}if(this.draining)return Promise.reject(new SqliteWorkerError(`SQLite worker host is closing`,`closed`));let i={},a,s;try{a=reserveSqliteWorkerClient(this.clients,this.stores.values(),hI,i),s=captureSqliteWorkerOpen(e,t,n,r);let c=e.runtimeGeneration;c?.retain(this,async()=>(await this.inputAdmission.joinOpens(),await this.lifecycle.settleGeneration(c)))}catch(e){return this.clients.delete(i),Promise.reject(toErrorObject(e,`SQLite worker input could not be serialized`))}let c=a?findReusableSqliteWorkerClient(this.stores.values(),s.databasePath):void 0;return this.inputAdmission.open(sqliteWorkerRequestBytes(s.input,s.stateContext,s.preparation),s.databasePath,async()=>(a||await reclaimSqliteWorkerClient(s,this.stores.values(),()=>reserveSqliteWorkerClient(this.clients,this.stores.values(),hI,i),()=>this.draining!==void 0),this.openAdmitted(s,i)),s.signal,c?()=>this.openAdmitted(s,i,c):void 0,s.carrierClass).catch(e=>{throw this.clients.delete(i),e})}async openAdmitted(e,t,n){let{maintenanceScope:r,cleanupAccess:i}=e,a=e.expectedIdentity?{databasePath:e.databasePath,key:e.expectedIdentity,birthtime:e.expectedBirthtime}:void 0;e.signal?.throwIfAborted(),e.assertCurrent?.();let{databasePath:s,inputHash:c,identity:l,key:u}=await prepareSqliteWorkerDatabaseAdmission(e);if(e.assertCurrent?.(),n&&this.actors.get(u)!==n.actor)return;let d=await captureStateDatabaseAccess(e.stateDatabasePath??l.canonicalPath),f=await d.prepareAccess({maintenanceScope:e.maintenanceScope,schemaLease:e.cleanupAccess});e.signal?.throwIfAborted(),e.assertCurrent?.(),f();let p=e.input,m=captureSqliteWorkerAdmissionPaths(s,l,this.actors.values());if(e.existingOnly&&!u.startsWith(`file:`)){this.clients.delete(t);return}let{modulePath:h,moduleUrl:g}=await resolveSqliteWorkerModuleUrl(e.moduleUrl);e.signal?.throwIfAborted(),e.assertCurrent?.();let v=this.actors.get(u);if(n&&(v!==n.actor||n.sealed||!n.isAvailable()))return;if(v?.slot.failed)return await waitForSqliteOpen(this.lifecycle.retireActor(v),e.signal),this.openAdmitted(e,t);let y;if(v?.retirementRequested||v?.cleanupState===`pending`){let n=v.retirementRequested?v.retirement:v.closing;if(n)return await waitForSqliteOpen(n,e.signal),this.openAdmitted(e,t);throw new SqliteWorkerError(v.retirementRequested?`SQLite actor retirement must finish before reopening`:`SQLite worker cleanup is pending; retry close before reopening`,`closed`)}if(v)assertSqliteWorkerActorReusable(v,g,c,e.stateContext),e.onNativeLost&&(v.nativeLostObservers??=/* @__PURE__ */ new Set).add(e.onNativeLost),v.references+=1,y=suspendSqliteWorkerScheduledMaintenance(v,r);else{let t=await this.lifecycle.acquireSlot(e,{maxWorkers:this.maxWorkers,maxStores:hI},e=>this.createReplyOwner(e));try{if(e.assertCurrent?.(),e.signal?.throwIfAborted(),this.actors.has(u))throw new SqliteWorkerError(`SQLite database owner was admitted while acquiring a worker; retry open`,`overloaded`)}catch(e){return this.lifecycle.rejectSlotAdmission(t,e)}let n=createDeferredCore();v={...e.onNativeLost?{nativeLostObservers:/* @__PURE__ */ new Set([e.onNativeLost])}:{},runtimeGeneration:e.runtimeGeneration,nativeStopped:n.promise,markNativeStopped:n.resolve,id:++this.nextActor,key:u,identity:l,pathReferences:new Map([...m].map(e=>[e,1])),moduleUrl:g,inputHash:c,slot:t,references:1,opened:Promise.resolve(),openDispatch:{custody:t.custody.createRequest()},initialized:!1,backendClosed:!1,databasePath:s,stateAccess:d,stateContext:e.stateContext,stateDatabasePath:e.stateDatabasePath},this.actors.set(u,v),y=suspendSqliteWorkerScheduledMaintenance(v,r),t.actors.add(v),--t.pendingOpens;let i=v;i.opened=this.enqueue(t,{type:`open`,actor:v.id,databaseIdentity:a,moduleUrl:g,databasePath:s,...e.createAdmission?{openAdmission:`input`}:e.createOpenAdmission?{openAdmission:`identity`}:{},...e.existingOnly?{existingIdentity:u}:{},input:p,...e.preparation?{preparation:e.preparation}:{},...runtimeNeedsTypeScriptLoader(h)?{sourceLoaderUrl:import.meta.resolve(`tsx/esm/api`)}:{}},sqliteWorkerRequestBytes(p,e.stateContext,e.preparation),{dispatchState:i.openDispatch,signal:e.signal,assertCurrent:e.assertCurrent,maintenanceScope:e.maintenanceScope,cleanupAccess:e.cleanupAccess,createAdmission:e.createAdmission??e.createOpenAdmission}).then(async()=>{i.initialized=!0;let e=await resolveOpenedSqliteWorkerIdentity(s,l,e=>{let t=this.actors.get(e);return t!==void 0&&t!==i});i.identity=e,e.key!==u&&(this.actors.delete(u),i.key=e.key,this.actors.set(e.key,i))})}let b=v;try{if(retainSqliteWorkerAdmissionCleanup(b,e.retainCleanup,this.lifecycle.closeActor.bind(this.lifecycle,b,r)),e.onNativeStopped?.(b.nativeStopped,()=>b.closeReceipt,()=>b.openDispatch.openRefused===!0),await v.opened,e.assertCurrent?.(),v.retirementRequested)throw new SqliteWorkerError(`SQLite actor retired during client admission`,`closed`);if(v.slot.failed)throw v.slot.failed}catch(t){return y?.(),this.lifecycle.rejectActorAdmission(v,t,e.maintenanceScope)}let x=retainSqliteWorkerAdmissionPathReferences(b,m),ee=!1,{store:te,client:ne}=createSqliteWorkerClient({actor:b,isDraining:()=>this.draining!==void 0,isAvailable:()=>!b.slot.failed&&!b.cleanupState&&!b.retirementRequested,retireIdle:e.retireIdle,dispatch:(e,t,n,r,s,c)=>this.enqueue(b.slot,{type:`execute`,actor:b.id,databaseIdentity:a,input:e.payload,transferredInput:e.transferredInput,...n?.stateContext?{stateContext:n.stateContext}:{}},sqliteWorkerRequestBytes(e.payload,n?.stateContext),{signal:t,requestClass:c,scope:n,assertCurrent:r,createAdmission:s,cleanupAccess:i,maintenanceScope:i?void 0:n?n.maintenanceScope:getOpenClawDatabaseMaintenanceScope()}),release:async e=>{ee||(ee=!0,y?.(),this.lifecycle.releaseActorReference(b),this.stores.delete(te),this.clients.delete(t),x()),this.draining&&!e&&!b.stateContext?await this.draining:b.slot.failed&&await b.slot.exit,b.references||await this.lifecycle.closeActor(b,r)}});return this.stores.set(te,ne),te}runOperation(e,t,n,r,i){return runSqliteWorkerClientOperation(this.draining?void 0:this.stores.get(e),t,n,e=>(this.operations.add(e),()=>this.operations.delete(e)),r,i)}isAvailable(e){return this.stores.get(e)?.isAvailable()??!1}retireActor(e){return this.lifecycle.retireActor(e)}getActorIdentity(e){let t=this.stores.get(e);if(!t||t.sealed||!t.actor.stateContext)throw new SqliteWorkerError(`SQLite shared actor binding is unavailable`,`closed`);return t.actor}hasUnclaimedSharedStateCleanup(e){return findUnclaimedSharedStateActors(this.actors.values(),e).length>0}async closeUnclaimedSharedState(e){await this.inputAdmission.joinOpens(),await closeUnclaimedSharedStateActors(this.actors.values(),e,e=>this.lifecycle.closeActor(e))}createReplyOwner(e){return{fail:(t,n,r,i)=>this.fail(e,t,n,r,i),finish:(t,n,r,i)=>this.finish(e,t,n,r,i),dispatch:()=>this.dispatch(e)}}enqueue(e,t,n,r,i=!1,a=trackWorkerRequest(`sqlite_writer`,r.requestClass??t.type)){let{signal:s,dispatchState:c,scope:l,assertCurrent:u,createAdmission:d,maintenanceScope:f,cleanupAccess:p}=r,reject=e=>(a.completed(),Promise.reject(e));if(this.draining&&t.type!==`close`&&!l?.active)return reject(new SqliteWorkerError(`SQLite worker host is closing`,`closed`));if(e.failed)return reject(e.failed);let m=t.type===`execute`&&n>gI,h=sqliteWorkerTransferredInputBytes(t.transferredInput),g=(m?Ck:n)+h;if(t.type!==`close`&&(t.type!==`execute`&&n>33554432||m&&(e.current||e.queue.length>0||e.pendingOpens>0)||this.bytes+this.inputAdmission.retainedBytes+g>_I))return reject(new SqliteWorkerError(`SQLite worker queue capacity reached`,`overloaded`));if(t.type!==`close`&&((this.requests.get(e)??0)>=128||!i&&this.waiters.has(e)))return m||this.draining?reject(new SqliteWorkerError(`SQLite worker queue capacity reached`,`overloaded`)):this.waitForCapacity(e,t,n,r,a);let v=createDeferredCore(),y={custody:c?.custody??e.custody.createRequest(),observation:a,signal:s,maintenanceScope:f,cleanupAccess:p,createAdmission:d,assertCurrent:u,dispatchState:c,request:{...t,id:++this.nextRequest,databaseAdmissionDeadlineAtMs:readSqliteDatabaseAdmissionDeadline()},bytes:g,result:v.promise,resolve:v.resolve,reject:v.reject,detach:()=>s?.removeEventListener(`abort`,abort)},abort=()=>{y.custody.cancel();let t=e.queue.indexOf(y);t>=0&&(e.queue.splice(t,1),this.finish(e,y,s?.reason??/* @__PURE__ */ Error(`SQLite worker operation canceled`)))};return this.requests.set(e,(this.requests.get(e)??0)+1),this.bytes+=g,m?(s?.addEventListener(`abort`,abort,{once:!0}),s?.aborted?this.finish(e,y,s.reason??/* @__PURE__ */ Error(`SQLite worker operation canceled`)):this.dispatchJob(e,y),v.promise):(e.queue.push(y),s?.addEventListener(`abort`,abort,{once:!0}),s?.aborted&&abort(),this.dispatch(e),v.promise)}waitForCapacity(e,t,n,r,i){return new Promise((a,s)=>{let c=Date.now(),l=r.signal,u=this.waiters.get(e)??/* @__PURE__ */ new Set,resume=p=>{if(!u.delete(resume))return;u.size||this.waiters.delete(e),clearTimeout(d),l?.removeEventListener(`abort`,abort),f();let m=p;m===void 0&&Date.now()-c>=1e4&&(this.warnAdmission(this.waiters.get(e)?.size??0,Date.now()-c),m=new SqliteWorkerError(`SQLite worker queue capacity reached`,`overloaded`)),m===void 0?a(this.enqueue(e,t,n,r,!0,i)):(i.completed(),s(toErrorObject(m,`SQLite worker admission failed`)))},abort=()=>resume(l?.reason??/* @__PURE__ */ Error(`SQLite worker operation canceled`)),d=setTimeout(()=>{this.warnAdmission(this.waiters.get(e)?.size??0,Date.now()-c),resume(new SqliteWorkerError(`SQLite worker queue capacity reached`,`overloaded`))},iI),f=this.inputAdmission.retain(n+sqliteWorkerTransferredInputBytes(t.transferredInput));u.add(resume),this.waiters.set(e,u),l?.addEventListener(`abort`,abort,{once:!0}),l?.aborted?abort():u.size>=128&&this.warnAdmission(u.size,0)})}dispatch(e){if(e.current||e.failed)return;let t=e.queue.shift();t?this.dispatchJob(e,t):e.worker.unref()}dispatchJob(e,t){t.custody.activate(),e.current=t,e.worker.ref(),t.observation.started(),dispatchSqliteWorkerJob(e,t,(n,r)=>{e.current===t&&(r?this.fail(e,n,toErrorObject(n,`SQLite worker transfer failed`)):(t.custody.retire(),e.current=void 0,this.finish(e,t,n),this.dispatch(e)))})}finish(e,t,n,r,i){if(t.observation.completed(),this.requests.set(e,(this.requests.get(e)??0)-1),this.bytes-=t.bytes,settleSqliteWorkerJob(t,n,r,i),!this.resuming.has(e)){for(this.resuming.add(e);(this.requests.get(e)??0)<128;){let t=this.waiters.get(e)?.values().next().value;if(!t)break;t()}this.resuming.delete(e)}}fail(e,t,n,r,i){failSqliteWorkerSlot(e,t,{currentError:n,openOutcome:r,completed:i,waiters:this.waiters.get(e),retire:()=>this.lifecycle.retire(e),finish:(t,n,r,i)=>this.finish(e,t,n,r,i)})}close(e){return e?(this.lifecycle.sealClients(this.waiters.values(),!0),e().then(()=>this.close())):(this.draining??=this.lifecycle.closeHost({inputAdmission:this.inputAdmission,operations:this.operations,waiters:this.waiters.values()}).then(()=>this.clients.clear()).finally(()=>{this.draining=void 0}),this.draining)}}}));function withCallerErrors(e){return e.catch(e=>{throw e instanceof Error?hydrateOpenClawStateWorkerError(e):e})}function bindCallerExecute(e){return{execute:(t,n)=>{let r=withCallerErrors(e.execute(t,n));return r.catch(()=>void 0),r}}}function runSqliteWorkerStoreOperation(e,t,n,r,i){return withCallerErrors(resolveSqliteWorkerBroker().runOperation(e,e=>t(bindCallerExecute(e)),n,r,i))}function resolveSqliteWorkerBroker(){return resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerBroker`),()=>new SqliteWorkerBroker,e=>withCallerErrors(e.close(async()=>{let{closeOpenClawStateDatabaseAsync:e}=await Promise.resolve().then(()=>(sL(),FI));await e()})),`shared-state`)}function isSqliteWorkerStoreAvailable(e){return resolveSqliteWorkerBroker().isAvailable(e)}function getSqliteWorkerActorIdentity(e){return resolveSqliteWorkerBroker().getActorIdentity(e)}function retireSqliteWorkerActor(e){return withCallerErrors(resolveSqliteWorkerBroker().retireActor(e))}function hasUnclaimedSharedStateSqliteCleanup(e){return resolveSqliteWorkerBroker().hasUnclaimedSharedStateCleanup(e)}function closeUnclaimedSharedStateSqliteWorkers(e){return withCallerErrors(resolveSqliteWorkerBroker().closeUnclaimedSharedState(e))}function openSharedStateSqliteWorkerStore(e,t,n,r){return at?withCallerErrors(resolveSqliteWorkerBroker().open({...e,input:void 0},t,n,{...r,carrierClass:`shared-state`})).then(e=>{if(e){let t=e.execute.bind(e),n=e.close.bind(e);e.execute=bindCallerExecute({execute:t}).execute,e.close=()=>withCallerErrors(n())}return e}):Promise.reject(new SqliteWorkerError(`Shared-state admission requires the host broker`,`unavailable`))}var yI=__esmMin((()=>{B(),WN(),vI(),Tk(),tA()}));function assertOpenClawStateWorkerActorPath(e){if(oL.getKnownOpenClawStateDatabaseIdentity(e.databasePath)?.key!==e.key)throw new StateDatabaseReadAdmissionInvalidatedError(`Shared-state worker opening path changed`)}function runWithCapturedWorkerContext(e,t){let n=e.maintenanceScope,run=()=>n?n.run(()=>n.track(t())):t();return e.runInCapturedSchemaScope?e.runInCapturedSchemaScope(run):run()}function runWithOpenClawStateWorkerStore(e,t,n,r,i,a){let{admission:s}=t,c=getSqliteWorkerActorIdentity(e);return runSqliteWorkerStoreOperation(e,e=>n(a?{execute:(t,n)=>e.execute(t,{...n,signal:n?.signal?AbortSignal.any([a,n.signal]):a})}:e),t,e=>{s.assertCurrent(),assertOpenClawStateWorkerActorPath(c),r?.(e)},i)}function assertOpenClawStateWorkerSchemaContext(e){if(isExistingOpenClawStateSchema(e.admission.databasePath),getExistingOpenClawStateSchemaPath()!==e.existingSchemaPath)throw Error(`Shared-state worker schema context does not match its caller`)}function captureOpenClawStateWorkerOpeningGuard(e){let t=e.admission,n=t.identity,r=C.bind(()=>t.assertCurrent()),assertCurrent=()=>{if(!r)throw Error(`Shared-state worker opening admission is closed`);r()};return{assertCurrent,createAdmission:()=>{let e=!1;return{nativeLocations:[t.databasePath],databaseIdentity:{databasePath:t.databasePath,key:n.key,birthtime:n.birthtime},admission:createSqliteWorkerOperationAdmission((t,n)=>{if(e||t.stage!==`open`)throw Error(`Shared-state worker open admission requested out of order`);if(assertCurrent(),!n())throw Error(`Shared-state worker open admission expired`);e=!0})}},async run(e){try{return await e()}finally{r=void 0}}}}var bI=__esmMin((()=>{tA(),yI(),LS(),sL(),QF()}));function retainOpenClawStateWorkerLease(e,t,n,r){let i=getPluginSharedStateResourceHost();i?.assertSharedStateAdmission();let a=e.maintenanceScope;e.admission.assertCurrent(),a?.assertAdmission();let s=createDeferredCore(),c=createDeferredCore(),l=createDeferredCore(),u=/* @__PURE__ */ new Set,d=/* @__PURE__ */ new Set,f,p,m,h,g=!1,v=!1,y,b,x=!1;s.promise.catch(()=>void 0);let assertResourceCurrent=()=>te?.assertCurrent(),assertInvocation=t=>{if(t.phase===`closed`||v)throw new SqliteWorkerError(`Shared-state worker operation is closed`,`closed`);e.admission.assertCurrent(),assertResourceCurrent()},assertCommandAdmission=e=>{if(assertInvocation(e),e.phase!==`accepting`)throw new SqliteWorkerError(`Shared-state worker operation is closed`,`closed`)},assertNewOperation=()=>{if(g)throw new SqliteWorkerError(`Shared-state worker lease is closed`,`closed`);e.admission.assertCurrent(),a?.assertAdmission()},retireNative=()=>(m??=(async()=>{await c.promise.catch(()=>void 0),l.resolve();let e=[];try{await f}catch(t){e.push(t)}try{await p?.()}catch(t){e.push(t)}throwSqliteLifecycleErrors(e,`Shared-state worker lease retirement failed`)})(),m.catch(()=>void 0),m),retire=()=>{g=!0,v=!0;for(let e of u)e.phase=`closed`;return retireNative()},createOperationScope=e=>({execute:(t,n)=>{try{assertCommandAdmission(e)}catch(e){let t=createDeferredCore();return t.reject(e),t.promise.catch(()=>void 0),t.promise}let run=async()=>{if(x||await racePromiseWithAbortSignal(s.promise,n?.signal),assertInvocation(e),!b)throw new SqliteWorkerError(`Shared-state worker lease is not ready`,`closed`);return b.execute(t,n)},r=(te?te.run(run):run()).catch(async e=>{if(y&&!g&&!isSqliteWorkerStoreAvailable(y))try{await retire()}catch(t){throw AggregateError([e,t],`Shared-state operation and retirement failed`,{cause:t})}throw e});e.pending.add(r);let settled=()=>e.pending.delete(r);return r.then(settled,settled),a?a.track(r):r}}),runOperation=e=>{try{assertNewOperation()}catch(e){let t=createDeferredCore();return t.reject(e),t.promise.catch(()=>void 0),t.promise}let t={phase:`accepting`,pending:/* @__PURE__ */ new Set};u.add(t);let n=createDeferredCore();return d.add(n.promise),n.promise.catch(()=>void 0),(async()=>{try{return await e(createOperationScope(t))}finally{t.phase===`accepting`&&(t.phase=`draining`),await Promise.allSettled(t.pending),t.phase=`closed`,u.delete(t)}})().then(e=>{d.delete(n.promise),n.resolve(e)},e=>{d.delete(n.promise),n.reject(e)}),n.promise},runWithAdmission=async e=>i?i.trackSharedStateWork(()=>runOperation(e)):runOperation(e),release=()=>v?retireNative():h||(g=!0,h=(async()=>{let e=[],t={phase:`accepting`,pending:/* @__PURE__ */ new Set};u.add(t);try{await s.promise,await n?.(createOperationScope(t))}catch(t){e.push(t)}finally{t.phase===`accepting`&&(t.phase=`draining`),await Promise.allSettled(t.pending),t.phase=`closed`,u.delete(t)}let r=await Promise.allSettled(d);e.push(...r.flatMap(e=>e.status===`rejected`?[e.reason]:[]));try{await retireNative()}catch(t){e.push(t)}throwSqliteLifecycleErrors(e,`Shared-state worker lease cleanup failed`)})(),h.catch(()=>void 0),h),ee={ready:s.promise,execute:(e,t)=>runWithAdmission(n=>n.execute(e,t)),runOperation:runWithAdmission,release,retire};a?.own(ee,`shared-resources`,release);let te=a?captureOpenClawDatabaseMaintenanceResource(ee,a):void 0,acquire=async()=>{try{let n=await getOpenClawStateDatabaseTerminalFailureAsync(e);if(n)throw n;if(e.admission.assertCurrent(),y=await t.open(e),e.admission.assertCurrent(),!y)throw Error(`Canonical shared-state worker did not open its database`);if(p=t.retainOperation(y,()=>{retire(),r?.()}),f=runWithOpenClawStateWorkerStore(y,e,async e=>{b=e,c.resolve(),await l.promise},assertResourceCurrent),f.catch(c.reject),await c.promise,e.admission.assertCurrent(),v)throw new SqliteWorkerError(`Shared-state worker lease is closed`,`closed`)}catch(e){let t=e instanceof Error?hydrateOpenClawStateWorkerError(e):e;c.reject(t);try{await retire()}catch(e){if(e!==t)throw AggregateError([t,e],`Shared-state lease acquisition failed`,{cause:e})}throw t}},acquireInContext=()=>runWithCapturedWorkerContext(e,acquire);return(i?i.trackSharedStateWork(acquireInContext):acquireInContext()).then(()=>{x=!0,s.resolve()},s.reject),ee}var xI=__esmMin((()=>{Ep(),W(),yI(),rI(),It(),LS(),sL(),WN(),bI()}));function createSharedStateWorkerOwner(){let e=resolveRuntimeProcessEntrypointUrl(`sharedStateStore`),t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=createStateWorkerMemoryPressureSubscription(()=>t.size>0||r.size>0||n.size>0,retireIdleWorkers),matches=(e,t)=>t===void 0||e.context.admission.identity.key===t.key,hasActiveActorOperations=e=>[...n].some(t=>e.actor?t.actor===e.actor:t===e),clearIdleRetirement=e=>{e.idleSince=void 0,clearTimeout(e.idleTimer),e.idleTimer=void 0},hasPendingCleanup=e=>e.cleanup?.pending??(!e.context.maintenanceScope&&hasUnclaimedSharedStateSqliteCleanup(e.context.admission.databasePath)),retire=e=>{clearIdleRetirement(e),t.delete(e);let n=r.get(e);if(n||(n={},r.set(e,n)),i(),n.pending)return n.pending;let a=e.store?e.store.close():e.opening.then(e=>e?.close(),()=>e.cleanup?e.cleanup.close():e.context.maintenanceScope?void 0:closeUnclaimedSharedStateSqliteWorkers(e.context.admission.databasePath));n.pending=a;let settled=()=>{n.pending=void 0,hasPendingCleanup(e)||r.delete(e),i()};return a.then(settled,settled),a},scheduleIdleRetirement=e=>{if(e.activeOperations!==0||e.idleTimer||e.context.maintenanceScope||!e.store||!t.has(e))return;e.idleSince=performance.now();let n=runInDetachedAsyncContext(()=>setTimeout(()=>{e.idleTimer===n&&e.activeOperations===0&&t.has(e)&&(e.idleTimer=void 0,retire(e).catch(t=>{SI.warn(`Idle shared-state worker retirement failed`,{path:e.context.admission.databasePath,error:t})}))},jF));e.idleTimer=n,n.unref?.()},retireAfterFailure=async(e,t,n)=>{try{await retire(e)}catch(e){throw AggregateError([t,e],`Shared-state worker ${n} and cleanup failed`,{cause:e})}throw t},retainOperation=(e,r)=>{let a=[...t].find(t=>t.store===e);if(!a)throw Error(`Shared-state worker operation lost its actor owner`);clearIdleRetirement(a),a.activeOperations+=1,n.add(a),r&&(a.nativeLostListeners.add(r),isSqliteWorkerStoreAvailable(e)||r());let s=!1;return()=>{if(!s){if(s=!0,r&&a.nativeLostListeners.delete(r),--a.activeOperations,a.activeOperations===0&&n.delete(a),i(),t.has(a)&&!isSqliteWorkerStoreAvailable(e)&&!hasActiveActorOperations(a)){let e=a.actor?retireActor(a.actor):retire(a);return e.catch(e=>{SI.warn(`Shared-state worker retirement failed`,{path:a.context.admission.databasePath,error:e})}),e}scheduleIdleRetirement(a)}}},retireActor=e=>{let n=retireSqliteWorkerActor(e);for(let n of/* @__PURE__ */ new Set([...t,...r.keys()]))n.actor===e&&retire(n);return n};async function close(e){for(let n of t.values())matches(n,e)&&retire(n);let n=(await Promise.allSettled([...r.keys()].filter(t=>matches(t,e)).map(retire))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(i(),n.length)throw AggregateError(n,`Failed to close shared-state SQLite workers`)}rL({phase:`after-resources`,close}),registerOpenClawStateDatabaseLifecycleListener(e=>{if(e.kind!==`opened`){if(!e.identity)return;close(e.identity).catch(t=>{SI.warn(`Shared-state worker retirement failed`,{path:e.path,error:t})})}});function retireIdleWorkers(e){for(let n of t)isWorkerIdleForPressure(n.idleSince,e)&&runInDetachedAsyncContext(()=>retireIdle(n))?.catch(e=>{SI.warn(`Idle shared-state worker retirement failed`,{path:n.context.admission.databasePath,error:e})})}let retireIdle=e=>e.idleTimer&&e.store&&t.has(e)&&!e.context.maintenanceScope&&!hasActiveActorOperations(e)?retire(e):void 0;return{close,retainOperation,async openCleanup(i,a,s,c,l){let u={...c};if(s(),!u.key.startsWith(`file:`))return;let assertCurrent=()=>{s();for(let e of n)if(matches(e,u)&&e.store&&!isSqliteWorkerStoreAvailable(e.store))throw new SqliteWorkerError(`Shared-state cleanup is waiting for accepted operations to settle`,`unavailable`)};assertCurrent();for(let e of/* @__PURE__ */ new Set([...t,...r.keys()]))(t.has(e)||r.has(e))&&matches(e,u)&&e.store&&!isSqliteWorkerStoreAvailable(e.store)&&(assertCurrent(),await(e.actor?retireActor(e.actor):retire(e)),assertCurrent());return openSharedStateSqliteWorkerStore({...captureRuntimeWorkerSource(e),databasePath:i,existingOnly:!0,admission:{identity:u.key,birthtime:u.birthtime,assertCurrent}},a,assertCurrent,{cleanupAccess:l&&{assertDatabaseAccess:l.assertCleanupDatabaseAccess}})},async open(n,a={}){let{existingOnly:s=!1,assertCurrent:c,signal:l}=a,{admission:u}=n,wait=e=>racePromiseWithAbortSignal(e,l),d=captureRuntimeWorkerSource(e),assertAdmission=()=>{l?.throwIfAborted(),u.assertCurrent(),c?.()};assertAdmission(),assertOpenClawStateWorkerSchemaContext(n);for(let e of/* @__PURE__ */ new Set([...t,...r.keys()]))if(matches(e,u.identity)&&t.has(e)&&(e.context.existingSchemaPath!==n.existingSchemaPath||!he(e.context.gatewayServiceInstallation,n.gatewayServiceInstallation)||e.source.moduleUrl.href!==d.moduleUrl.href)){if(hasActiveActorOperations(e))throw Error(`Shared-state worker policy changed while its actor is in use; close its leases first`);await wait(e.actor?retireActor(e.actor):retire(e)),assertAdmission()}for(let[e,t]of r)if(matches(e,u.identity)&&e.context.maintenanceScope===n.maintenanceScope){if(hasActiveActorOperations(e))throw Error(`Shared-state worker is retiring while its actor is in use; close its leases first`);if(!t.pending){if(!hasPendingCleanup(e)){r.delete(e),i();continue}throw Error(`Shared-state SQLite cleanup is pending; close the database before reopening`)}try{await wait(t.pending)}catch(n){if(r.get(e)===t)throw n}assertAdmission()}assertAdmission();let f=[...t].find(e=>matches(e,u.identity)&&e.context.maintenanceScope===n.maintenanceScope&&e.context.existingSchemaPath===n.existingSchemaPath&&he(e.context.gatewayServiceInstallation,n.gatewayServiceInstallation)),p=!f;if(!f){let e=captureOpenClawStateWorkerOpeningGuard(n),a=/* @__PURE__ */ new Set,open=()=>e.run(()=>openSharedStateSqliteWorkerStore({...d,databasePath:u.databasePath,existingOnly:s},n,e.assertCurrent,{maintenanceScope:n.maintenanceScope,...s&&u.identity.key.startsWith(`file:`)?{createAdmission:e.createAdmission}:{},retireIdle:retireIdle.bind(void 0,c),retainCleanup:e=>{c.cleanup=e},onNativeLost:notifyListeners.bind(void 0,a,void 0,void 0)})),c={source:d,context:n,existingOnly:s,nativeLostListeners:a,activeOperations:0,opening:Promise.resolve(void 0)};c.opening=n.maintenanceScope?open():runInDetachedAsyncContext(open),f=c,c.opening=c.opening.then(e=>(e?(c.store=e,c.actor=getSqliteWorkerActorIdentity(e),scheduleIdleRetirement(c)):(t.delete(c),i()),e)),t.add(f),i(),n.maintenanceScope?.own(f,`shared-resources`,()=>retire(c)),f.opening.catch(()=>{t.delete(c),hasPendingCleanup(c)&&!r.has(c)&&r.set(c,{}),i()})}let m=await(p?f.opening:wait(f.opening));try{u.assertCurrent()}catch(e){return retireAfterFailure(f,e,`admission`)}if(l?.throwIfAborted(),c?.(),!m)return!s&&f.existingOnly?this.open(n,{...a,existingOnly:!1}):void 0;if(!t.has(f))return this.open(n,a);if(clearIdleRetirement(f),!isSqliteWorkerStoreAvailable(m)&&!hasActiveActorOperations(f))return await wait(f.actor?retireActor(f.actor):retire(f)),this.open(n,a);try{f.bound||(publishOpenClawStateDatabaseWorkerAdmission(f.context.admission,getSqliteWorkerActorIdentity(m).identity),f.bound=!0)}catch(e){return retireAfterFailure(f,e,`binding`)}return f.actor&&assertOpenClawStateWorkerActorPath(f.actor),t.delete(f),t.add(f),m}}}function getOpenClawStateWorkerOwner(){return assertPublishedOpenClawStateDatabaseLifecycle(),resolveGlobalSingleton(Symbol.for(`openclaw.sharedStateWorkerOwner`),createSharedStateWorkerOwner)}var SI,CI=__esmMin((()=>{cj(),Ep(),qD(),YD(),MF(),yI(),Ev(),Qd(),B(),pu(),sL(),uj(),bI(),SI=createSubsystemLogger(`state/worker`)})),wI=/* @__PURE__ */ __exportAll({createOpenClawStateWorkerLease:()=>createOpenClawStateWorkerLease,executeOpenClawStateWorker:()=>executeOpenClawStateWorker,openOpenClawStateWorkerCleanupStore:()=>openOpenClawStateWorkerCleanupStore,runOpenClawStateWorkerOperation:()=>runOpenClawStateWorkerOperation});function openOpenClawStateWorkerCleanupStore(e,t,n,r,i){return getOpenClawStateWorkerOwner().openCleanup(e,t,n,r,i)}async function executeOpenClawStateWorker(e,t){let n=await runOpenClawStateWorkerOperation(e,e=>e.execute(t));return e.admission.assertCurrent(),n}function createOpenClawStateWorkerLease(e,t,n){return retainOpenClawStateWorkerLease(e,{open:e=>getOpenClawStateWorkerOwner().open(e),retainOperation:(e,t)=>getOpenClawStateWorkerOwner().retainOperation(e,t)},t,n)}async function runOpenClawStateWorkerOperation(e,t,n){return runPluginSharedStateWork(()=>runWithCapturedWorkerContext(e,async()=>{try{n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.assertCurrent?.();let r=await getOpenClawStateDatabaseTerminalFailureAsync(e,n?.signal);if(r)throw r;e.admission.assertCurrent(),n?.assertCurrent?.();let i=await getOpenClawStateWorkerOwner().open(e,n);if(!i){if(n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.existingOnly)return;throw Error(`Canonical shared-state worker did not open its database`)}let a=getOpenClawStateWorkerOwner().retainOperation(i);try{return n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.assertCurrent?.(),await runWithOpenClawStateWorkerStore(i,e,t,n?.assertCurrent,n?.createAdmission,n?.signal)}finally{a()}}catch(t){let n=hydrateOpenClawStateWorkerError(t),r=findOpenClawStateDatabaseFailure(n,e.admission.databasePath);if(r&&!oL.getOpenClawStateDatabaseRecordedFailure(e.admission.databasePath)){try{e.admission.assertCurrent()}catch{throw n}recordOpenClawStateDatabaseOpenFailure(e.admission.databasePath,r)}throw n}}))}var TI=__esmMin((()=>{rI(),sL(),fN(),WN(),xI(),bI(),CI()}));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(!at||isPostgresSqlConnection(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 Promise.resolve().then(()=>(TI(),wI));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:createSqliteWorkerOperationAdmission((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&&isAbortError(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(S.resolve(resolveOpenClawStateSqlitePath()));return t?.db.isOpen?t.walMaintenance.health:void 0}}}var EI=__esmMin((()=>{Ep(),gu(),eN(),tA(),LS(),X(),tI()}));function readTrackedStateDatabaseIdentity(e){return DI.get(sqlPublicationAnchor(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&&assertExistingDatabaseIdentity(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=readDatabasePathIdentitySync(e),a=withSqliteNativeOpen(()=>openNodeSqliteDatabase(n,r));try{assertStateDatabaseAccessAllowed(e),i.key.startsWith(`file:`)&&assertExistingDatabaseIdentity(e,i.key,i.birthtime);let t=i.key.startsWith(`file:`)?i:readDatabasePathIdentitySync(e);if(t.key.startsWith(`file:`)){DI.set(a,t);let e=registerNodeSqliteDisposeCallback(a,()=>{DI.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(isPostgresSqlConnection(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(prepareSqliteDatabaseCleanClose(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()}}var DI,OI=__esmMin((()=>{xk(),Du(),LA(),gu(),Nx(),J(),kb(),eN(),qv(),B(),tf(),DI=resolveGlobalSingleton(Symbol.for(`openclaw.stateNativeIdentities`),()=>/* @__PURE__ */ new WeakMap)}));function hasStateDatabaseIntegrityAdmission(e){return!!(getStateRuntimeSchemaAdmission(e)||Jb(e,AI))}function assertStateDatabaseIntegrityOnce(e,t){hasStateDatabaseIntegrityAdmission(e)||(assertSqliteIntegrity(e,t),publishSqliteDatabaseAdmission(e,AI,!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){revokeSqliteDatabaseAdmissions(e);let t=kI.get(e);t&&(invalidate(new BigInt64Array(t.revision)),invalidate(new BigInt64Array(t.lifetimeRevision)))}function bind(e,t){if(kI.get(e)?.revision===t.revision)return;kI.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()});kI.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?stageSqliteTransactionState(e,{commit:publish}):publish()}}var kI,AI,jI=__esmMin((()=>{Du(),J(),Xx(),jv(),Y(),B(),gF(),OI(),kI=resolveGlobalSingleton(Symbol.for(`openclaw.stateIntegrityBindings`),()=>/* @__PURE__ */ new WeakMap),AI={name:`state.integrity`,lifetime:`process`,read:e=>e===!0||void 0}}));function retainSqliteDatabaseRemovalExclusion(e,t){if(!l(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)}throwSqliteLifecycleErrors(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 createSqliteLifecycleAggregateError([e,t],`SQLite state removal admission and cleanup both failed.`,e)}if(isSqliteLockError(e))throw Error(`Cannot remove OpenClaw state directory while another SQLite connection is active`,{cause:e});let t=sqlitePrimaryResultCode(e);if(t!==11&&t!==26)throw e;return}process.platform===`win32`&&close()}var MI=__esmMin((()=>{LA(),kb(),W()}));function createOpenClawStateSnapshotOwnerRegistry(){let e=/* @__PURE__ */ new WeakMap;return{register(t,n){isPostgresSqlConnection(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){isPostgresSqlConnection(t)||(e.get(t)?.(),e.delete(t))}}}var NI,PI=__esmMin((()=>{gu(),xF(),B(),NI=resolveGlobalSingleton(Symbol.for(`openclaw.stateSnapshotOwners`),createOpenClawStateSnapshotOwnerRegistry)})),FI=/* @__PURE__ */ __exportAll({assertPublishedOpenClawStateDatabaseLifecycle:()=>assertPublishedOpenClawStateDatabaseLifecycle,borrowOpenClawStateDatabaseForAsyncRead:()=>tL,captureOpenClawStateDatabaseReadAdmission:()=>iL,captureOpenClawStateIntegrityAdmission:()=>aL,clearOpenClawStateDatabaseOpenFailure:()=>clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase:()=>closeOpenClawStateDatabase,closeOpenClawStateDatabaseAsync:()=>closeOpenClawStateDatabaseAsync,closeOpenClawStateDatabaseByPath:()=>closeOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseByPathAsync:()=>closeOpenClawStateDatabaseByPathAsync,closeOpenClawStateDatabaseForTest:()=>closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseWorkersByPathAsync:()=>closeOpenClawStateDatabaseWorkersByPathAsync,getOpenClawStateDatabaseTerminalFailureAsync:()=>getOpenClawStateDatabaseTerminalFailureAsync,isOpenClawStateDatabaseOpen:()=>isOpenClawStateDatabaseOpen,openClawStateDatabaseCache:()=>oL,prepareOpenClawStateCachedRead:()=>prepareOpenClawStateCachedRead,prepareOpenClawStateDatabaseRemoval:()=>prepareOpenClawStateDatabaseRemoval,publishOpenClawStateDatabaseWorkerAdmission:()=>publishOpenClawStateDatabaseWorkerAdmission,readOpenClawStateWalHealth:()=>XI,recordOpenClawStateDatabaseOpenFailure:()=>recordOpenClawStateDatabaseOpenFailure,registerOpenClawStateDatabaseAsyncResource:()=>rL,registerOpenClawStateDatabaseLifecycleListener:()=>registerOpenClawStateDatabaseLifecycleListener,registerOpenClawStatePathAsyncResource:()=>registerOpenClawStatePathAsyncResource,registerOpenClawStatePathCacheInvalidation:()=>registerOpenClawStatePathCacheInvalidation,requireOpenClawStateDatabaseIdentity:()=>requireOpenClawStateDatabaseIdentity,retainOpenClawStateDatabase:()=>eL,retainOpenClawStateDatabaseForIdle:()=>JI,retainOpenClawStateDatabaseForIndependentRead:()=>nL});function notifyOpenClawStateDatabaseLifecycle(e){let t=e.kind===`open-error`?{...e,identity:e.identity??KI.knownIdentity(e.path)}:e;for(let e of WI)e(t)}function notifyOpenClawStateDatabaseClosed(e){notifyOpenClawStateDatabaseLifecycle({kind:`closed`,path:e.path,identity:requireOpenClawStateDatabaseIdentity(e)})}function requireOpenClawStateDatabaseIdentity(e){let t=HI.get(e.db);if(!t)throw Error(`Published shared-state owner has no recorded database identity`);return t}function registerOpenClawStateDatabaseLifecycleListener(e){WI.add(e);for(let t of RI.values())t.db.isOpen&&e({kind:`opened`,database:t,identity:requireOpenClawStateDatabaseIdentity(t)});return()=>WI.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){zI.set(e.db,e),LI.unregisterRetainedExitClose??=registerSqliteCacheExitClose(closeOpenClawStateDatabase)}function ownMaintenanceStateDatabaseHandle(e){getOpenClawDatabaseMaintenanceScope()?.own(e.db,`shared-handles`,async()=>{let t=getOpenClawDatabaseMaintenanceScope();t&&isOpenClawDatabaseMaintenanceResourceOwned(e.db,t)&&(RI.get(e.path)===e||zI.get(e.db)===e)&&(await e.walMaintenance?.stop(),isOpenClawDatabaseMaintenanceResourceOwned(e.db,t)&&(RI.get(e.path)===e||zI.get(e.db)===e)&&retireOpenClawStateDatabaseHandle(e,!1))})}function closeUnpublishedOpenClawStateDatabaseHandle(e){let t=closeOpenClawStateDatabaseHandle(e);return zI.get(e.db)===e&&ownMaintenanceStateDatabaseHandle(e),t}function closeOpenClawStateDatabaseHandle(e,t){clearTimeout(BI.get(e.db)),BI.delete(e.db);try{assertStateDatabaseBorrowersReleased(UI.get(e.db),e.path)}catch(n){let r=UI.get(e.db);return r&&(r.retiring=!0,r.retirement={ordinary:!0,isCurrent:()=>!0,retire:()=>{throwSqliteLifecycleErrors(closeOpenClawStateDatabaseHandle(e,t),`OpenClaw state database cleanup failed for ${e.path}.`),r.cleanupComplete=!0,UI.delete(e.db)}}),retainStateDatabaseClose(e),[n]}VI.delete(e.db),NI.release(e.db);let{errors:n,cleanupPending:r}=closeStateDatabaseHandle(e,t);return e.db.isOpen||r?retainStateDatabaseClose(e):zI.delete(e.db),RI.get(e.path)?.db===e.db&&RI.delete(e.path),zI.size===0&&(LI.unregisterRetainedExitClose?.(),LI.unregisterRetainedExitClose=void 0),n}function evictCachedOpenClawStateDatabase(e){return isPostgresSqlConnection(e.db)||invalidateOpenClawStateRuntimeIntegrity(e.db),RI.get(e.path)===e&&(KI.invalidate(e.path),RI.delete(e.path),notifyOpenClawStateDatabaseClosed(e),closeOpenClawStateDatabaseHandle(e,{checkpointMode:`PASSIVE`}),!0)}function evictOpenClawStateDatabaseAfterCorruption(e,t){return isSqliteCorruptionError(t)&&evictCachedOpenClawStateDatabase(e)}function publishOpenClawStateDatabase(e,t){let{db:n,path:r}=e,{identity:i,admission:a}=KI.publish(r);return HI.set(n,readTrackedStateDatabaseIdentity(n)??i),RI.set(r,e),YI(e,i,a,t),qI(e),NI.register(e,()=>RI.get(r)),ownMaintenanceStateDatabaseHandle(e),notifyOpenClawStateDatabaseLifecycle({kind:`opened`,database:e,identity:i}),isPostgresSqlConnection(n)||registerNodeSqliteKyselyQueryErrorHandler(n,t=>{!n.isTransaction&&isSqliteCorruptionError(t)&&evictCachedOpenClawStateDatabase(e)}),GI.clear(r),e}function getCachedOpenClawStateDatabase(e,t){let n=resolveDatabasePath({path:e}),r=GI.get(n);if(r)throw r;return readCachedOpenClawStateDatabase(n,t)}function readCachedOpenClawStateDatabase(e,t){let n=getOpenClawDatabaseMaintenanceScope();t?.readOnly?n?.assertReadAdmission():n?.assertAdmission(),assertExistingOpenClawStateSchemaCacheAdmission(e,LI);let r=RI.get(e);if(r){if(UI.get(r.db)?.retiring)throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);qI(r)}return r}function prepareOpenClawStateCachedRead(e){let t=resolveDatabasePath({path:e}),n={readOnly:!0};getCachedOpenClawStateDatabase(t,n);let r=KI.capture(t);return()=>(r.assertCurrent(),readCachedOpenClawStateDatabase(t,n))}function withCachedOpenClawStateDatabase(e,t,n){let r=getCachedOpenClawStateDatabase(e,t);return r&&$I.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(RI.get(e.path)!==e)return;KI.invalidate(e.path);let t=closeOpenClawStateDatabaseHandle(e);notifyOpenClawStateDatabaseClosed(e),throwSqliteLifecycleErrors(t,`Stale OpenClaw state database cleanup failed for ${e.path}.`)}function recordOpenClawStateDatabaseOpenFailure(e,t){GI.record(resolveDatabasePath({path:e}),t)}function clearOpenClawStateDatabaseOpenFailure(e){let t=resolveDatabasePath({path:e});GI.clear(t),KI.invalidate(t),notifyOpenClawStateDatabaseLifecycle({kind:`failure-cleared`,path:t,identity:KI.knownIdentity(t)})}async function getOpenClawStateDatabaseTerminalFailureAsync(e,t){return e.admission.assertCurrent(),t?.throwIfAborted(),GI.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}=KI.capture(r),a=GI.get(r);if(a)throw a;for(let t of zI.values())if(UI.get(t.db)?.retiring&&(t.path===r||HI.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){assertOpenClawStateDatabaseOpenAllowed(e);let r;try{r=readOpenClawDatabaseQuarantineFailure(`state`,e,{env:t})}catch(e){if(!(e instanceof lN))throw e;n?.(e);return}if(r?.cause instanceof lN&&n?.(r.cause),r)throw $I.closeTerminalFailure(e,r),r}function retireOpenClawStateDatabaseHandle(e,t=!0,n){assertStateDatabaseBorrowersReleased(UI.get(e.db),e.path);let r=UI.get(e.db);try{let r=RI.get(e.path)?.db===e.db;t&&KI.invalidate(e.path);let i=closeOpenClawStateDatabaseHandle(e,n);if(r&&t)try{notifyOpenClawStateDatabaseClosed(e)}catch(e){i.push(e)}throwSqliteLifecycleErrors(i,`OpenClaw state database cleanup failed for ${e.path}.`)}catch(t){throw r&&retainStateDatabaseClose(e),t}r&&(r.cleanupComplete=!0,UI.delete(e.db))}function retireOpenClawStateDatabaseHandles(e,t,n){let r=/* @__PURE__ */ new Set([...zI.values(),...RI.values()]),i=[],a=!1;for(let s of r)if(e===void 0||s.path===e||n!==void 0&&HI.get(s.db)?.key===n.key){a=!0;try{retireOpenClawStateDatabaseHandle(s,!0,t)}catch(e){i.push(e)}}return throwSqliteLifecycleErrors(i,`OpenClaw state database cleanup failed.`),a}function closeOpenClawStateDatabaseByPath(e,t){return retireOpenClawStateDatabaseHandles(resolveDatabasePath({path:e}),t,KI.identity(e))}function closeOpenClawStateDatabase(e){retireOpenClawStateDatabaseHandles(void 0,e)}function registerOpenClawStatePathAsyncResource(e,t){return rL({close(n){return!n||n.key===e.identity.key||n.canonicalPath===e.identity.canonicalPath?t():Promise.resolve()}})}function publishOpenClawStateDatabaseWorkerAdmission(e,t){t&&e.assertCurrent(),KI.publish(e.databasePath,t),e.assertCurrent()}function closeOpenClawStateDatabaseWorkersByPathAsync(e){return KI.close(resolveDatabasePath({path:e}),()=>!1)}function closeOpenClawStateDatabaseByPathAsync(e,t){let n=resolveDatabasePath({path:e});return KI.close(n,async e=>(await QI(n,e),retireOpenClawStateDatabaseHandles(n,t,e)))}async function closeOpenClawStateDatabaseAsync(e){await KI.close(void 0,async()=>(await QI(),retireOpenClawStateDatabaseHandles(void 0,e)))}function isOpenClawStateDatabaseOpen(e){return e===void 0?Array.from(RI.values()).some(e=>e.db.isOpen):RI.get(resolveDatabasePath({path:e}))?.db.isOpen===!0}function closeOpenClawStateDatabaseForTest(){closeOpenClawStateDatabase(),GI.clearAll()}function assertPublishedOpenClawStateDatabaseLifecycle(){if(readGlobalSingleton(II)!==LI)throw Error(`OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle`)}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=KI.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())}}}var II,LI,RI,zI,BI,VI,HI,UI,WI,GI,KI,qI,JI,YI,XI,ZI,QI,$I,eL,tL,nL,rL,iL,aL,oL,sL=__esmMin((()=>{xk(),Du(),gu(),kb(),W(),_F(),nN(),B(),uN(),OF(),LS(),kF(),AF(),PF(),EI(),OI(),jI(),MI(),QF(),PI(),X(),II=Symbol.for(`openclaw.stateDatabaseLifecycle`),LI=resolveGlobalSingleton(II,()=>({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)=>$I.closeTerminalFailure(e,t)}),asyncResources:createOpenClawStateDatabaseAsyncLifecycle()}),()=>closeOpenClawStateDatabaseAsync(),`shared-state`),{cachedDatabases:RI,retainedDatabaseHandles:zI,idleTimers:BI,idleReferences:VI,databaseIdentities:HI,borrowers:UI,databaseLifecycleListeners:WI,terminalOpenLatch:GI,asyncResources:KI}=LI,{touch:qI,retain:JI}=createStateDatabaseIdleRetirement(LI,retireOpenClawStateDatabaseHandle),{register:YI,readHealth:XI,ownRetirement:ZI,stop:QI}=createStateDatabaseWalOwner(LI,JI,requireOpenClawStateDatabaseIdentity),$I=createStateDatabaseCacheAdmission({cachedDatabases:RI,evict:evictCachedOpenClawStateDatabase,invalidate:e=>KI.invalidate(e),notifyTerminalFailure:(e,t)=>notifyOpenClawStateDatabaseLifecycle({kind:`terminal-failure`,path:e,error:t,identity:KI.knownIdentity(e)})}),{retain:eL,borrowForRead:tL,retainForIndependentRead:nL}=createStateDatabaseRetainer(LI,{assertOpen(e,t,n){assertOpenClawStateDatabaseOpenAllowed(e,t,n),assertExistingOpenClawStateSchemaCacheAdmission(e,LI)},capture:e=>KI.capture(e),retire:retireOpenClawStateDatabaseHandle,retainFailed:retainStateDatabaseClose,ownRetirement:ZI,touch:qI}),rL=KI.register,iL=KI.capture,aL=KI.integrity,oL={assertOpenClawStateDatabaseFreshOpenAllowedAtPath,assertOpenClawStateDatabaseOpenAllowed,clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase,closeOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseHandle,closeUnpublishedOpenClawStateDatabaseHandle,closeStaleCachedOpenClawStateDatabase,evictCachedOpenClawStateDatabase,evictOpenClawStateDatabaseAfterCorruption,getCachedOpenClawStateDatabase,peekOpenClawStateDatabaseConnection:e=>RI.get(resolveDatabasePath({path:e}))?.db,withCachedOpenClawStateDatabase,getOpenClawStateDatabaseRecordedFailure:GI.peek,getOpenClawStateDatabaseIfOpenAtPath,getKnownOpenClawStateDatabaseIdentity:KI.knownIdentity,isOpenClawStateDatabaseOpen,isOpenClawStateDatabaseSchemaReady:e=>RI.get(e.path)===e&&e.db.isOpen,publishOpenClawStateDatabase,recordOpenClawStateDatabaseOpenFailure,recordOpenClawStateDatabaseLifecycleOpenError,touchStateDatabase:qI}}));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){let i=cL[t];if(!i.hasSubscribers)return r();let a=performance.now(),s=`error`;try{let e=r();return s=`ok`,e}finally{let t=performance.now()-a;i.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId:E,outcome:s,durationMs:t})}}function observeConnection(e){if(lL.has(e))return e;lL.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))})}let r=t.iterate.bind(t);return t.iterate=(...t)=>{let n=r(...t);if(!cL.statement.hasSubscribers)return n;let i=0,a=!1,s=!1,finish=t=>{s||(s=!0,a&&cL.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:E,outcome:t,durationMs:i}))},step=e=>{if(s)return e();let t=performance.now();try{let n=e();return i+=performance.now()-t,n.done&&finish(`ok`),n}catch(e){throw i+=performance.now()-t,finish(`error`),e}},c={next:(...e)=>(a=!0,step(()=>n.next(...e))),return:e=>step(()=>n.return?.(e)??{done:!0,value:e}),[Symbol.iterator](){return this}};return Object.setPrototypeOf(c,Object.getPrototypeOf(n)),c},t},e}var cL,lL,uL=__esmMin((()=>{cL={statement:$e(`openclaw.database.statement`),request:$e(`openclaw.database.request`)},lL=/* @__PURE__ */ new WeakSet})),dL,fL,pL,mL=__esmMin((()=>{dL=6e4,fL=6e4,pL=9e4}));function closeBridge(e){e.port.close()}function closeIdleBridges(){let e=[...hL.values()];hL.clear(),unwatch();for(let{bridge:t,timeout:n}of e)clearTimeout(n),closeBridge(t)}function unwatch(){hL.size||(process.off(`beforeExit`,closeIdleBridges),process.off(`exit`,closeIdleBridges))}function removeIdleBridge(e){let t=hL.get(e);return hL.delete(e),t&&clearTimeout(t.timeout),unwatch(),t?.bridge}function takeIdlePostgresBridge(e){let t=removeIdleBridge(e);if(t&&Atomics.load(t.service,1))closeBridge(t);else return t}function retainIdlePostgresBridge(e,t){let n=removeIdleBridge(e);if(n&&closeBridge(n),hL.size===gL){let e=hL.keys().next().value;closeBridge(removeIdleBridge(e))}hL.size||(process.once(`beforeExit`,closeIdleBridges),process.once(`exit`,closeIdleBridges));let r=setTimeout(()=>{let t=removeIdleBridge(e);t&&closeBridge(t)},_L);r.unref(),hL.set(e,{bridge:t,timeout:r})}var hL,gL,_L,vL=__esmMin((()=>{hL=/* @__PURE__ */ new Map,gL=2,_L=18e4}));function postgresBridgeReuseKey(e){return sha256Hex(JSON.stringify([e.url,e.lockTimeoutMs??6e4,e.statementTimeoutMs??9e4]))}function preparedBridgeKey(e){return JSON.stringify([postgresBridgeReuseKey(e),e.schema,e.storeId])}function createPostgresBridge(e){let{port1:t,port2:n}=new tt,r=new SharedArrayBuffer(8),i=new Int32Array(r),{port:a,signal:s,nextStep:c}=selectPostgresPoolService(),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 recordPostgresPoolFailure(e),e}try{a.postMessage({connection:{port:n,signal:r,url:e.url,schema:e.schema,connectTimeoutMs:dL,lockTimeoutMs:e.lockTimeoutMs??6e4,statementTimeoutMs:e.statementTimeoutMs??9e4}},[n])}catch(e){throw t.close(),n.close(),e}return t.unref(),{port:t,control:i,service:l,nextStep:c,requestId:0}}function findPreparedBridge(e){let t=yL.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}var yL,bL=__esmMin((()=>{yS(),mL(),dP(),pP(),yL=new C}));function assertPostgresOperationCurrent(){let e=Nk.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){return assertPostgresOperationCurrent(),withSqlitePostCommitPublications(sqlPublicationAnchor(e),()=>{let a=e.isTransaction&&!i,s=!1,c;try{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})`),r&&!a&&(c=beginPostgresReadSnapshotScope(e));let i=t();if(assertSyncTransactionResult$1(i),a)e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||prepareSqliteTransactionCommit(e),e.exec(r?`ROLLBACK`:`COMMIT`),s=!r};n?.withCommit?assertSyncTransactionResult$1(n.withCommit(commit)):commit()}return i}catch(t){let n=hasSqliteWorkerOutcomeUnknown(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{discardSqliteTransactionState(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{c?.()}})}var xL=__esmMin((()=>{gu(),jv(),Y(),Tk(),Pk()})),PostgresSyncConnection,SL=__esmMin((()=>{Hv(),uL(),gu(),J(),jv(),Tk(),fO(),bL(),vL(),dP(),vb(),xL(),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.idleCheckout=!1,this.lastResponseAt=Date.now(),this.outcomeUnknown=!0,this.readOnlyTransaction=!1,this.pendingWrite=!1,this.mainThread=E===0,assertEngineStoreExecutionAllowed(),Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=ye(`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??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(this.bridgeParameters);if(this.bridge=t,this.idleCheckout=e!==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){return runPostgresTransactionSync(this,e,t,...n)}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,beginSqliteDatabaseWrite(sqlPublicationAnchor(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new SqliteWorkerError(`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)&&recordPostgresPoolFailure(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,finishSqliteDatabaseWrite(sqlPublicationAnchor(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=performance.now()+12e4,a=n.inTransaction===!1,s=(this.idleCheckout||a)&&(e.operation===`query`||e.operation===`recovery-generation`),c=s&&(this.idleCheckout||a&&Date.now()-this.lastResponseAt>=1e3);n.inTransaction=void 0,this.idleCheckout=!1,n.port.postMessage({...e,...s?{reconnectIfIdle:s}:{},...c?{validateIfIdle:c}:{},id:r},[]),recordWorkerMessage(`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=i-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 l=st(n.port)?.message;if(l&&recordWorkerMessage(`sqlite_reply`,`from_worker`),!l||l.id!==r)throw this.loseConnection();if(`error`in l)throw e.operation===`connect`?decodePostgresError(l.error):isPostgresConnectionError(l.error.code)?this.loseConnection():(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)&&(this.isTransaction=!1,this.finishWrite()),decodePostgresError(l.error));return this.lastResponseAt=Date.now(),`reusable`in l?(n.inTransaction=!l.reusable,l.reusable):(n.inTransaction=`generation`in l?l.inTransaction:l.result.inTransaction,`generation`in l?l.generation:l.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,beginSqliteDatabaseWrite(sqlPublicationAnchor(this),c===`unscoped`)}return!this.isTransaction&&(l||i)&&withSqlitePostCommitPublications(sqlPublicationAnchor(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}}}})),CL=__esmMin((()=>{G(),Dx(),xx()})),wL=__esmMin((()=>{kx(),Dx(),xx(),CL()})),TL=__esmMin((()=>{J()})),EL=__esmMin((()=>{Uu()})),DL=__esmMin((()=>{EL()})),OL=__esmMin((()=>{DL(),Yy(),pA(),Fy(),Hy(),MF()})),kL=__esmMin((()=>{ou(),G(),TL(),OL(),new SqliteQueryCompiler})),AL=__esmMin((()=>{wL(),kL()}));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)]}var jL,ML,NL,PL,FL=__esmMin((()=>{jL=`memory_index_sources`,ML=`memory_index_chunks`,NL=`memory_index_chunks_fts`,PL=`memory_index_paths_fts`,buildMemoryFtsTriggers(PL,jL,`id, path, source`,`        INSERT INTO ${PL} (rowid, path, source)
        VALUES (NEW.id, NEW.path, NEW.source);`,`        DELETE FROM ${PL}
        WHERE rowid = OLD.id;`),buildMemoryFtsTriggers(NL,ML,`chunk_rowid, text, id, path, source, model, start_line, end_line`,`        INSERT INTO ${NL} (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 ${NL} WHERE rowid = OLD.chunk_rowid;`)})),IL=__esmMin((()=>{J(),jv(),kx(),Dx(),xx(),AL(),TL(),FL()})),LL=__esmMin((()=>{IL(),AL()})),RL,zL=__esmMin((()=>{v_(),G(),SL(),NS(),uL(),mL(),Dx(),xx(),LL(),RL={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,lockTimeoutMs:fL,statementTimeoutMs:pL})}catch(t){let n=redactSensitiveText(`${t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${n}; 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,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,postgresVectorDecoderVersion:t.schema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.schema.postgresVectorSearchVersion,postgresTextSearchVersion:t.schema.postgresTextSearchVersion})}}}}}}));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=Jb(t,BL);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(),RL.sqlite.schema.bootstrap({...e,input:e.input},t),publishSqliteDatabaseAdmission(t,BL,{engine:`sqlite`}),RL.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)}.`);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)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 a=i[0];if(a){if(typeof a.store_id!=`string`||a.engine!==`postgres`||typeof a.schema!=`string`)throw Error(`Invalid PostgreSQL anchor identity. Restore a matching backup.`);return{storeId:a.store_id,namespace:a.schema}}let s=Se(),c=postgresStoreNamespace(e.input.schemaPrefix,n.id,s);return t.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(s,c),e.onFreshAnchor?.(t),{storeId:s,namespace:c}},a=i?.engine===`postgres`?i:e.existingOnly?readOrCreateAnchor():runSqliteImmediateTransactionSync(t,readOrCreateAnchor),s={...e,input:e.input,...a},c=RL.postgres,l=c.openConnection(s),admit=t=>{admitPostgresPhysicalFacts({db:l,namespace:a.namespace,storeId:a.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion}),e.admitPostgres?.(l,t)};try{let r=n.search?admitPostgresSearch(l,n.search,a.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(!i||i.engine===`postgres`&&i.version!==n.version){admitPostgresCapabilities(l);let t,r;l.runTransaction(()=>{let i=!l.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(a.namespace);i&&!e.existingOnly&&(l.exec(`CREATE SCHEMA IF NOT EXISTS "${a.namespace.replaceAll(`"`,`""`)}"`),l.exec(Sx));let u;try{u=l.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(u){if(u.store_id!==a.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${a.storeId}, found ${String(u.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(u.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(u.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(u.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(l,r),invalidateLocalSqliteSchemaAdmissions(l),stageSqliteTransactionState(l,{stage:()=>{},rollback:()=>{},commit:()=>publishSqliteDatabaseSchemaChange(l),invalidate:()=>publishSqliteDatabaseSchemaChange(l)});let migrate=()=>c.schema.migrate(s,Number(u.version),l);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!i)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);c.schema.bootstrap(s,l)}admit(!u)},{withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!i||i.engine===`postgres`&&i.version!==n.version)&&publishSqliteDatabaseAdmission(t,BL,{engine:`postgres`,...a,version:n.version}),r?.();for(let e of Object.values(getAdmittedPostgresSchema(l)?.searchExtensions??{}))admitPostgresSearch(l,e,a.namespace,n.postgresVectorSearchVersion)?.();return l}catch(t){if(e.closeOnFailure)return e.closeOnFailure(l,t);throw l.close(),t}}var BL,VL=__esmMin((()=>{J(),jv(),NS(),fF(),zL(),uL(),kx(),Dx(),xx(),BL={name:`database.engine`}}));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(HL,(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(UL,(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(HL)].map(([e,t])=>[t,e]));return[...e.matchAll(HL)].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(`
`)}var HL,UL,WL=__esmMin((()=>{HL=/CREATE (?:UNIQUE )?INDEX ("(?:[^"]|"")+") ON ("(?:[^"]|"")+") (?:'(?:[^']|'')*'|"(?:[^"]|"")*"|[^;'"])*;/g,UL=/'(?:[^']|'')*'|"(?:[^"]|"")*"|\) (ASC|DESC)(?=,|\))/g}));function stateEngineInput(){if(getDatabaseEngineSelection())return getDatabaseEngineInput(`state`)}var GL=__esmMin((()=>{cP()}));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`)}var KL,qL=__esmMin((()=>{$(),KL=[`github_publication_requests`,`github_personal_publication_requests`,`github_repository_publication_requests`],KL.map(e=>`${e}.draft`)}));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,``)}var JL,YL,XL=__esmMin((()=>{uy(),$(),lb(),JL=[`local_workspace_tree_packs`,`local_workspace_source_path_sets`],YL=[`tree_root_digest`,`source_paths_digest`,`canonical_fingerprints`,`projection_fingerprints`],[...JL],YL.map(e=>`local_workspace_projections.${e}`)}));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))),`:`  ${QL},`).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,``)}var ZL,QL,$L=__esmMin((()=>{Hx(),Y(),uy(),$(),XL(),lb(),ZL=`local_workspace_projections`,QL=`CHECK ((baseline_json IS NULL) = (baseline_ref IS NULL))`,`${ZL}`}));function lazyColumnDefinitions(e){return eR.filter(t=>e===void 0||!!t[3]===e).map(([e,t,n])=>({columnName:t,dataType:n,tableName:e}))}var eR,tR,nR,rR,iR,aR=__esmMin((()=>{eR=[[`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`]],tR=lazyColumnDefinitions(),nR=lazyColumnDefinitions(!1),rR=lazyColumnDefinitions(!0),iR={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'))`]]}}));function legacyTemplateStateIdentifier(e){for(let[t,n]of[...oR,...sR.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 ${quoteSqliteIdentifier(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(`, `)});`}var oR,sR,cR,lR,uR,dR,literal,fR,pR=__esmMin((()=>{G(),Hx(),dy(),uy(),aR(),oR=[[`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`]],sR=[[`template_installs`,`claw_name`,`template_name`],[`template_installs`,`claw_version`,`template_version`],[`template_package_refs`,`claw_name`,`template_name`]],cR=new Set(oR.map(([,e])=>e)),lR=nR.filter(({tableName:e})=>cR.has(e)),uR=[...iR.packageUpdatedAt,...iR.packageIntegrity],dR=[[`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(`'`,`''`)}'`,[...oR.flat()],[...lR.map(({tableName:e,columnName:t})=>`${e}.${t}`),...uR.map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)],fR=`DO $template_names_v36$
DECLARE item record; column_item record; constraint_name text; next_constraint_name text;
BEGIN
  FOR item IN SELECT * FROM (VALUES
    ${oR.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
      ${sR.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 ${quoteSqliteIdentifier(e)} DROP CONSTRAINT ${quoteSqliteIdentifier(`${e}_origin_check`)};
    UPDATE ${quoteSqliteIdentifier(e)} SET origin = 'template-introduced' WHERE origin = 'claw-introduced';
    ALTER TABLE ${quoteSqliteIdentifier(e)} ADD CONSTRAINT ${quoteSqliteIdentifier(`${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;
  ${dR.map(([e,t])=>versionUpdates(e,t)).join(`
`)}
END $template_names_v36$;`}));function readStateSchemaContentVersion(e,t,n=readStateSchemaContentVersionRow,r){if(isPostgresSqlConnection(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 hR(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 ${mR}.`,{cause:e})}if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${mR}.`);return t}function admitStateSchemaFacts(e,t,n=`runtime`){if(isPostgresSqlConnection(e)){if(!getPostgresPhysicalFacts(e))throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL physical schema admission`)}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>36?createNewerSqliteSchemaVersionError(`OpenClaw state database`,t,i,36,readSqliteWriterAppVersion(e),n):normalizeOpenClawStateSchemaReadError(r,t)}}function assertSupportedStateSchemaVersion(e,t,n,r,i=`runtime`){if(isPostgresSqlConnection(e))return readStateSchemaContentVersion(e);try{let a=n?.userVersion??getStateSchemaVersionAdmission(e)?.userVersion??getAdmittedSqliteSchemaFacts(e)?.userVersion??readSqliteUserVersion(e),s=n?.contentVersion??(a>36?a:readStateSchemaContentVersion(e,a,r,a));if(s>36)throw createNewerSqliteSchemaVersionError(`OpenClaw state database`,t,s,36,readSqliteWriterAppVersion(e),i);return a}catch(e){throw normalizeOpenClawStateSchemaReadError(e,t)}}var mR,PostgresSchemaAdmissionUnavailableError,hR,gR=__esmMin((()=>{kx(),G(),gu(),Y(),SS(),UM(),gF(),Z(),$(),RN(),mR=`state.schema.contentVersion`,PostgresSchemaAdmissionUnavailableError=class extends Error{},hR=createSqliteQueryCache(e=>prepareSqliteQuerySync(e,()=>getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,mR)))}));function withPostgresSchemaAdmissionRetry(e,t,n){try{return t()}catch(r){if(!(r instanceof PostgresSchemaAdmissionUnavailableError)||!isPostgresSqlConnection(e)||n?.()===!1||!e.isOpen||e.isTransaction)throw r;let i=Math.min(Date.now()+1e3,readSqliteDatabaseAdmissionDeadline()??1/0),a=performance.now()+Math.max(0,i-Date.now()),s=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));return withSqliteDatabaseAdmissionWait({deadlineAtMs:i},()=>{for(let c=10;;c=Math.min(c*2,100)){assertSqliteDatabaseAdmissionWaitActive();let l=Math.min(a-performance.now(),i-Date.now());if(l<=0||(Atomics.wait(s,0,0,Math.min(c,l)),assertSqliteDatabaseAdmissionWaitActive(),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 SqliteDatabaseAdmissionTimeoutError&&(performance.now()>=a||Date.now()>=i))throw r;if(!(t instanceof PostgresSchemaAdmissionUnavailableError)||n?.()===!1||!e.isOpen||e.isTransaction)throw t}}})}}var _R=__esmMin((()=>{kx(),gu(),Mk(),gR()}));function writeStateSchemaContentVersion(e){executeSqliteQuerySync(e,getNodeSqliteKysely(e).insertInto(`config_machine_state`).values({state_key:mR,value_json:`36`,updated_at_ms:Date.now()}).onConflict(e=>e.column(`state_key`).doUpdateSet({value_json:`36`,updated_at_ms:Date.now()}).where(`config_machine_state.value_json`,`!=`,`36`)))}var vR=__esmMin((()=>{G(),Y(),UM(),Z(),$(),gR()})),yR,bR=__esmMin((()=>{yR={eagerSql:`-- 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,
  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,
  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,
  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;
`,operatorRecoveryV25Sql:`-- 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';
`,preWriteIndexesV27Sql:{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);`},writeIndexesV27Sql:`
  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);`,clientCredentialV29Sql:`-- 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;
`,workspaceCasV35Sql:`-- 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$;
`,clientCredentialSource:{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}]},fragments:[{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:`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,
  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:`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")
);
`}],expectedCatalog:[{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_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:`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:`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:`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:`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:`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}]}}));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. ${xR}`);return t}),r=new Set(n.catalog.filter(e=>e.kind===`table`).map(e=>e.table)),i=new Set(yR.fragments.flatMap(e=>e.tables.some(e=>r.has(e))?[]:e.tables));if(n.version===36&&assertPostgresCatalog(n.catalog.filter(e=>!e.kind.endsWith(`Definition`)&&e.table!==`openclaw_schema_meta`),yR.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(36,LM,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. `+xR)}if(a?.schema_version!==n.version||a.role!==`global`||a.agent_id!==null||c>n.version)throw Error(`PostgreSQL state metadata mismatch. ${xR}`);publishStateSchemaVersionAdmission(e,{userVersion:n.version,contentVersion:n.version}),publishStateRuntimeSchemaAdmission(e,!0)}function statePostgresVersionSql(e){return`UPDATE schema_meta
        SET schema_version = ${e},
          app_version = '${LM.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:withLegacyTemplateStateSchema(SR.postgres),postgresFragments:SR.postgresFragments.map(e=>({...e,tables:e.tables.map(legacyTemplateStateIdentifier),sql:withLegacyTemplateStateSchema(e.sql)}))},t={postgres:withLegacyLocalWorkspaceCas(e.postgres),postgresFragments:e.postgresFragments.map(e=>({...e,tables:e.tables.filter(e=>!JL.some(t=>t===e)),sql:withLegacyLocalWorkspaceCas(e.sql)}))},n={postgres:withLegacyPostgresIndexOrdering(t.postgres,`schema-nullability`),postgresFragments:t.postgresFragments.map(e=>({...e,sql:withLegacyPostgresIndexOrdering(e.sql,`schema-nullability`)}))},r={postgres:withLegacyPostgresIndexOrdering(n.postgres),postgresFragments:n.postgresFragments.map(e=>({...e,sql:withLegacyPostgresIndexOrdering(e.sql)}))},i={postgres:withLegacyLocalWorkspaceManifests(r.postgres),postgresFragments:r.postgresFragments.map(e=>({...e,tables:e.tables.filter(e=>e!==`local_workspace_manifest_nodes`),sql:withLegacyLocalWorkspaceManifests(e.sql)}))},a={...i,postgres:`${i.postgres}\n${yR.clientCredentialSource.sql}`},s={postgres:withLegacyPublicationDraft(a.postgres),postgresFragments:a.postgresFragments.map(e=>({...e,sql:withLegacyPublicationDraft(e.sql)}))},c={...s,postgres:s.postgres.replace(/CREATE INDEX "idx_state_leases_owner"[^;]*;/u,yR.preWriteIndexesV27Sql.state_leases)+yR.preWriteIndexesV27Sql.skill_usage+yR.preWriteIndexesV27Sql.acp_replay_events,postgresFragments:s.postgresFragments};return[{version:25,sql:yR.operatorRecoveryV25Sql,fromSchema:c,schema:c},{version:26,fromSchema:c,schema:c,sql:statePostgresVersionSql(26)},{version:27,fromSchema:c,schema:s,sql:`${yR.writeIndexesV27Sql}
        ${statePostgresVersionSql(27)}`},{version:28,fromSchema:s,schema:a,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:a,schema:i,sql:yR.clientCredentialV29Sql},{version:30,fromSchema:i,schema:i,sql:statePostgresVersionSql(30)},{version:31,fromSchema:i,schema:r,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:r,schema:n,sql:`${postgresIndexOrderingMigration([n.postgres,...n.postgresFragments.map(e=>e.sql)].join(`
`))}
        ${statePostgresVersionSql(32)}`},{version:33,fromSchema:n,schema:t,sql:`${postgresIndexOrderingMigration([t.postgres,...t.postgresFragments.map(e=>e.sql)].join(`
`),`schema-nullability`)}
        ${statePostgresVersionSql(33)}`},{version:34,fromSchema:t,schema:t,sql:statePostgresVersionSql(34)},{version:35,fromSchema:t,schema:e,sql:`${yR.workspaceCasV35Sql}\n${statePostgresVersionSql(35)}`},{version:36,fromSchema:e,schema:SR,sql:`${fR}\n${statePostgresVersionSql(36)}`}]}function ensureStatePostgresFragment(e,t){let n=getPostgresPhysicalFacts(e);if(!n)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${xR}`);let r=yR.fragments.find(e=>e.tables.includes(t));if(!r){if(yR.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}`)}if(r.tables.filter(e=>n.version>=35||!JL.some(t=>t===e)).every(e=>n.catalog.some(t=>t.kind===`table`&&t.table===e)))return;for(let t of r.dependencies){let n=yR.fragments.find(e=>e.id===t);if(!n)throw Error(`Unknown state fragment dependency ${t}`);ensureStatePostgresFragment(e,n.tables[0])}if(!stageSqliteTransactionState(e,{commit:()=>publishSqliteDatabaseSchemaChange(e),invalidate:()=>publishSqliteDatabaseSchemaChange(e)}))throw Error(`PostgreSQL state fragments require the owner's transaction`);invalidateLocalSqliteSchemaAdmissions(e);let i=n.version<36?withLegacyTemplateStateSchema(r.sql):r.sql,a=n.version<35?withLegacyLocalWorkspaceCas(i):i;e.exec(n.version<33?withLegacyPostgresIndexOrdering(a,n.version<32?`sqlite`:`schema-nullability`):a),admitPostgresPhysicalFacts({db:e,namespace:n.namespace,storeId:n.storeId,store:n.store,version:n.version,schema:CR,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:CR,input:r,inspectSqlite:()=>inspectStateSqlite(e),prepareAnchor:()=>{},openSqlite:()=>{},existingOnly:!0,reusePostgresConnection:!0,existingVersion:!0,admitPostgres:admitStatePostgres,closeOnFailure:(e,t)=>{throw n=e,t}});if(!isPostgresSqlConnection(i))throw Error(`Expected PostgreSQL state connection`);return n=i,{database:{db:n,path:t},close(){return throwSqliteLifecycleErrors(oL.closeUnpublishedOpenClawStateDatabaseHandle({db:i,path:t}),`PostgreSQL state connection cleanup failed.`),!i.isOpen&&!e.isOpen}}}catch(r){let i=oL.closeUnpublishedOpenClawStateDatabaseHandle({db:n??e,path:t});throw i.length?createSqliteLifecycleAggregateError([r,...i],`PostgreSQL state connection acquisition and cleanup failed.`,r):r}}var xR,SR,CR,wR=__esmMin((()=>{VL(),kx(),gx(),WL(),gu(),J(),W(),jv(),Hx(),Y(),RM(),gF(),sL(),Z(),GL(),OI(),qL(),$L(),XL(),pR(),gR(),_R(),vR(),bR(),xR=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`,SR={postgres:yR.eagerSql,postgresFragments:yR.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}})},CR={id:`state`,version:36,sqlite:``,...SR,get postgresMigrations(){let e=createStatePostgresMigrations();return Object.defineProperty(this,"postgresMigrations",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}}})),TR=__esmMin((()=>{on(),MD(),SD(),xD()})),ER,DR=__esmMin((()=>{tD(),ER=number().int().min(0).max(2**53-1),discriminatedUnion(`reason`,[object({reason:literal$1(`expired`),expiresAt:ER,expiredByMs:ER,heartbeatAgeMs:ER,renewalTimerLateByMs:ER.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`)})])})),OR=__esmMin((()=>{G(),TR(),DR()})),kR=__esmMin((()=>{$(),OR(),TR()}));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()}var AR=__esmMin((()=>{Y()})),jR=__esmMin((()=>{SD(),on(),RM()})),MR,NR,PR,FR,IR,LR,RR,zR,BR=__esmMin((()=>{tD(),MR=string().refine(e=>!e.includes(`\0`),`Must not contain NUL`),NR=union([MR,array(MR).min(1).refine(e=>!!e[0]?.length,`Executable must not be empty`)]),PR=union([NR,record(string(),NR)]),FR=string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u),IR=string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),LR=record(IR,object({description:string().optional(),documentationUrl:string().optional()}).passthrough()).refine(e=>Object.keys(e).length<=16,`At most 16 setup secrets may be requested`),RR=record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),MR),zR=object({source:_enum([`devcontainer`,`script`,`detected`,`none`]),identity:FR.optional(),inputs:record(string(),FR),env:record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),MR.nullable()),secretNames:array(IR).max(16).optional(),ignoredPropertiesNote:string().optional(),onCreate:PR.optional(),updateContent:PR.optional(),postCreate:PR.optional(),postStart:PR.optional(),detectedInstall:PR.optional()}).strict(),object({onCreateCommand:PR.optional(),updateContentCommand:PR.optional(),postCreateCommand:PR.optional(),postStartCommand:PR.optional(),secrets:LR.optional(),containerEnv:RR.optional(),remoteEnv:record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),MR.nullable()).optional()}).passthrough()})),VR,HR,UR,WR,GR=__esmMin((()=>{tD(),BR(),VR=string().regex(/^[a-f0-9]{64}$/u),HR=object({nodeBootstrapSha256:VR,enabledPluginIds:array(string().min(1).max(256)).max(256),workerBundleHash:VR,workerArchiveSha256:VR,openclawVersion:string().min(1).max(128),protocolFeatures:array(string().min(1).max(128)).max(64)}).strict(),UR=object({machineClass:string().min(1).max(256),platform:string().min(1).max(64),arch:string().min(1).max(64).optional(),profileKey:VR.optional()}).strict(),WR=object({key:VR,cacheKey:VR,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:zR.optional(),target:UR,artifacts:HR}).strict(),WR.omit({setupRecipe:!0,runSetupScript:!0,recipe:!0}).extend({source:literal$1(`empty`)})})),KR=__esmMin((()=>{GR(),XF(),G(),$()})),qR,JR=__esmMin((()=>{qR=[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`exec_approvals_config`]})),YR=__esmMin((()=>{$()})),XR=__esmMin((()=>{Y()}));function migratePredicateColumnsV21(e,t){let n=t===21&&ZR.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}var ZR,QR=__esmMin((()=>{$(),ZR={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)`}})),$R=__esmMin((()=>{Hx(),ES(),KR(),$(),QR()})),ez=__esmMin((()=>{Uu(),G(),Z(),$()})),tz=__esmMin((()=>{G(),yM()})),nz=__esmMin((()=>{ND()})),rz=__esmMin((()=>{B(),resolveGlobalSingleton(Symbol.for(`openclaw.outboundDeliveryEnqueued`),()=>({onEnqueued:e=>{}}))})),iz=__esmMin((()=>{rz(),G(),J(),yM(),NS()})),az=__esmMin((()=>{Uu()})),oz=__esmMin((()=>{Yu(),iz(),az()}));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.`)}var sz=__esmMin((()=>{Y(),SS(),NS(),$()})),cz=__esmMin((()=>{Yu(),Uu(),D(),nz(),G(),yM(),NS(),oz(),sz(),$()})),lz=__esmMin((()=>{Yu(),D(),tz(),jv(),uy(),Ev(),aR(),cz(),$(),lb()})),uz,dz=__esmMin((()=>{Hx(),Y(),uy(),$(),uz=[`operator_approvals`,`cron_run_receipts`,`execution_decision_facts`,`skill_workshop_changes`]})),fz=__esmMin((()=>{})),pz=__esmMin((()=>{Hx(),Y(),uy(),$()})),mz=__esmMin((()=>{pz()})),hz=__esmMin((()=>{}));function parseExternalOwnership(e,t){let n;try{n=JSON.parse(e)}catch{throw new OpenClawStateOwnershipMetadataError(t,`reserved value is not valid JSON`)}let r=isRecord(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`||!vz.test(a)||typeof s!=`number`||!Number.isSafeInteger(s)||s<0||s>_z)throw new OpenClawStateOwnershipMetadataError(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||isPostgresSqlConnection(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(gz);if(!i)return null;if(typeof i.value_json!=`string`)throw new OpenClawStateOwnershipMetadataError(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 OpenClawStateExternalOwnershipError(t,e.managerId)}function assertOpenClawStateWriteAllowed(e){let t=S.resolve(e.databasePath);assertStateDatabaseAccessAllowed(t);let n=e.inspectOwnership?void 0:Jb(e.database,yz);if(n===void 0){let r=inspectOpenClawStateOwnershipFromDatabase(e.database,t,e.schemaReady);n=e.inspectOwnership?void 0:Jb(e.database,yz),n===void 0&&(n=r,publishSqliteDatabaseAdmission(e.database,yz,n))}assertOwnershipAllowsWrite(n,t,e.env??process.env)}var gz,_z,vz,yz,bz=__esmMin((()=>{D(),xk(),YF(),LA(),gu(),J(),kb(),W(),sF(),TF(),iF(),NS(),rA(),Z(),$(),RN(),gz=`gateway.supervision`,_z=864e13,vz=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,yz={name:`state.external-ownership`,read(e){if(e===null)return null;if(isRecord(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}}}})),xz=__esmMin((()=>{Z()}));function findMissingLazyStateStartupColumn(e){for(let{tableName:t,columnName:n}of nR){if(!Az.excludedTables?.includes(t))continue;let r=e(t);if(r&&!r.columns.some(e=>e.name===n))return{tableName:t,columnName:n}}}var Sz,Cz,wz,Tz,Ez,Dz,Oz,kz,Az,jz,Mz=__esmMin((()=>{ES(),aR(),Z(),xz(),Sz=[...VS,`worker_session_tool_operations`,`worker_turn_tool_authorities`],Cz=[`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`,...Sz],wz=tR.map(({columnName:e,tableName:t})=>`${t}.${e}`),Tz=rR.map(({columnName:e,tableName:t})=>`${t}.${e}`),new Set(Tz),[...nR.map(({columnName:e,tableName:t})=>`${t}.${e}`),...Object.values(iR).flat().map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)],Ez=[`worker_session_tool_operations`,`worker_turn_tool_authorities`],new Set(Ez),Dz=[`idx_meeting_transcript_utterances_id`,`idx_operator_approvals_source_run_resolved`,`idx_worker_session_placements_environment`],Oz=[`fleet_cells`],kz={excludedTables:Oz,allowCompatibleAdditiveColumns:!0,allowedMissingTables:RS,allowedMissingColumns:Tz,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`]}},Az={...kz,excludedTables:[...Oz,...VS],excludedIndexes:HS},jz={...kz,allowedMissingTables:[...VS,...Ez,...RS],allowedMissingIndexes:Dz,allowedMissingColumns:wz}})),Nz=__esmMin((()=>{Xy()})),Pz=__esmMin((()=>{sb(),nP()})),Fz,Iz=__esmMin((()=>{JR(),Pz(),Z(),Fz={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:[]},state:{29:[...qR,`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`]}}})),Lz,Rz=__esmMin((()=>{my(),aR(),Iz(),Lz=[`sqlite_stat1`,`sqlite_stat4`],[...Lz],[...nR.map(({tableName:e})=>e),...Object.values(iR).flatMap(e=>e.map(([e])=>e)),...Lz],{...Fz.agent},{...Fz.state},[...Lz],[...Lz],[...Lz]}));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){let{pathname:r,schemaVersions:i}=t;isPostgresSqlConnection(e)&&requireNativeDatabaseFile(`postgres`,`repair`);let a=assertSupportedStateSchemaVersion(e,r,i);if((i?.contentVersion??readStateSchemaContentVersion(e))!==36)throw new SqliteSchemaMismatchError(`OpenClaw state database ${r} uses schema version ${a}; run openclaw doctor --fix before compacting it.`);let s=assertOpenClawStateDatabaseOwner(e,t);if(s?.schema_version!==a&&!adoptPeerPublishedStateSchemaVersion(e,s)){let e=typeof s?.schema_version==`number`?s.schema_version:`invalid`;throw new SqliteSchemaMismatchError(`OpenClaw state database ${r} metadata schema version ${e} does not match ${a}; run openclaw doctor --fix before compacting it.`)}assertSqliteSchemaContains(e,r,cb,jz,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,withLegacyTemplateStateSchema(cb),{allowedMissingTables:[...t.version===5?Cz:t.version<13?Sz:VS,...RS]})}var zz,Bz=__esmMin((()=>{kx(),G(),gu(),Xx(),W(),ES(),SS(),uy(),NS(),UM(),fF(),RM(),gF(),Z(),YR(),eI(),XR(),$R(),ez(),$(),lz(),QR(),dz(),fz(),mz(),hz(),qL(),$L(),XL(),pR(),gR(),bz(),Mz(),vR(),lb(),Nz(),Rz(),zz=[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28],new Map(zz.map(e=>[e,(t,n)=>assertOpenClawStateDatabaseVersionForMigration(t,{...n,version:e})])),[...uz],[...uz.map(e=>`${e}.cursor_id`)]}));function tableColumnInfo(e,t){return e.prepare(`PRAGMA table_info(${t})`).all()}function tableHasExactColumns(e,t,n){let r=tableColumnInfo(e,t).map(e=>e.name);return r.length===n.length&&r.every((e,t)=>e===n[t])}function tableHasRequiredColumns(e,t,n){let r=new Map(tableColumnInfo(e,t).map(e=>[e.name,e]));return n.every(e=>Number(r.get(e)?.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 tableHasUniqueColumn(e,t,n){return e.prepare(`PRAGMA index_list(${t})`).all().some(t=>{if(Number(t.unique??0)!==1||typeof t.name!=`string`)return!1;let r=t.name.replaceAll(`'`,`''`),i=e.prepare(`PRAGMA index_info('${r}')`).all();return i.length===1&&i[0]?.name===n})}function hasCanonicalAuditEventTable(e,t,n){let r=tableSql(e,`audit_events`)?.toLowerCase();return tableHasExactColumns(e,`audit_events`,t)&&tablePrimaryKeyColumns(e,`audit_events`).join(`,`)===`sequence`&&tableHasRequiredColumns(e,`audit_events`,n)&&typeof r==`string`&&/\bsequence\s+integer\s+primary\s+key\s+autoincrement\b/.test(r)&&tableHasUniqueColumn(e,`audit_events`,`event_id`)&&tableHasUniqueColumn(e,`audit_events`,`source_id`)}function hasCanonicalAuditIdentityKeyTable(e){if(!tableExists(e,`audit_identity_keys`))return!1;let t=tableSql(e,`audit_identity_keys`)?.toLowerCase();return tableHasExactColumns(e,`audit_identity_keys`,[`id`,`key_id`,`key`,`created_at`])&&tablePrimaryKeyColumns(e,`audit_identity_keys`).join(`,`)===`id`&&tableHasRequiredColumns(e,`audit_identity_keys`,[`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&&Hz.every(({name:e,sql:n})=>normalizeSchemaSql(t.tableSql.get(e)??null)===n)?!0:tableExists(e,`audit_events`)?hasCanonicalAuditEventTable(e,Gz,[`event_id`,`source_id`,`schema_version`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`actor_type`,`actor_id`])&&hasCanonicalAuditIdentityKeyTable(e):readSqliteUserVersion(e)<Vz&&!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,Uz,[`event_id`,`source_id`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`actor_type`,`actor_id`,`agent_id`,`run_id`])}var Vz,Hz,Uz,Wz,Gz,Kz=__esmMin((()=>{Y(),uy(),UM(),$(),lb(),Vz=2,Hz=[`audit_events`,`audit_identity_keys`].map(e=>({name:e,sql:normalizeSchemaSql(extractSqliteTableSchema(cb,e))})),Uz=[`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`],Wz=Uz.flatMap(e=>e===`source_id`?[e,`schema_version`]:[e]),Gz=[...Wz,`direction`,`channel`,`conversation_kind`,`message_outcome`,`reason_code`,`delivery_kind`,`failure_stage`,`duration_ms`,`result_count`,`account_ref`,`conversation_ref`,`message_ref`,`target_ref`]})),qz,Jz=__esmMin((()=>{$(),qz=[`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`]})),Yz=__esmMin((()=>{G(),$()})),Xz,Zz,Qz=__esmMin((()=>{Xz=`
  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
`,Zz=`CREATE INDEX idx_commitments_scope_due
  ON commitments(agent_id, session_key, status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_status_due
  ON commitments(status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_scope_dedupe
  ON commitments(agent_id, session_key, channel, dedupe_key, status);`,`${Xz.slice(1,-1)}${Zz}`,`${Xz.slice(1,-1)}${Zz}`})),$z=__esmMin((()=>{ES(),Ev(),$(),Qz(),createSubsystemLogger(`state/db`)}));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.`)}var eB=__esmMin((()=>{LA(),SS(),Kz(),Z(),sz(),$(),RN(),Jz(),dz(),qL(),pR(),gR(),Yz(),$z(),X(),lb(),[...qz],[...uz],[...oR.flat()],cb.split(`
`).flatMap(e=>{let t=/^CREATE TABLE IF NOT EXISTS (\w+) \(/u.exec(e)?.[1];return t?[t]:[]})}));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,cb,Az,n)}function assertNoLegacyStateRuntimeRepair(e,t){if(hasLegacyCronRunLogs(e))throw new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-cron-run-logs`,t)}var tB=__esmMin((()=>{kR(),LA(),Xx(),W(),jv(),ES(),SS(),TF(),NS(),AR(),fF(),jR(),gF(),Z(),KR(),jI(),Bz(),RN(),eB(),gR(),Mz(),lb()}));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)!==36)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)}var nB=__esmMin((()=>{G(),ES(),Y(),NS(),gF(),Z(),tB(),jI(),$(),gR()}));function orphanRows(e){let t=e.prepare(`SELECT rowid, * FROM task_delivery_state
    WHERE ${rB} 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 assertRecoveryShape(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 assertKnownOrphanIntegrity(e){try{return assertSqliteIntegrity(e,`task delivery recovery database`),0}catch(e){if(e instanceof SqliteRepairableForeignKeyError)return e.repair.orphanCount;throw e}}function recoverOrphanTaskDeliveryRows(e,t){if(!tableExists(e,`task_delivery_state`)||!tableExists(e,`task_runs`)||!e.prepare(`SELECT 1 FROM task_delivery_state WHERE ${rB} LIMIT 1`).get())return[];assertOpenClawStateDatabaseOwner(e,{pathname:t}),assertRecoveryShape(e);let n=assertKnownOrphanIntegrity(e);if(!e.isTransaction)throw Error(`Orphan task delivery recovery requires the Doctor write transaction.`);let i=prepareSqliteReadOnlyLocationSync(t),a;try{let s=openNodeSqliteDatabase(i.location);try{if(s.exec(`PRAGMA journal_mode = DELETE;`),assertRecoveryShape(s),assertKnownOrphanIntegrity(s)!==n)throw Error(`Orphan task delivery snapshot changed before preservation.`);let t=ye(`sha256`),r=ye(`sha256`);for(let n of orphanRows(e))t.update(encodeOrphanRow(n));for(let e of orphanRows(s))r.update(encodeOrphanRow(e));if(t.digest(`hex`)!==r.digest(`hex`))throw Error(`Orphan task delivery snapshot does not preserve the current payload.`)}finally{s.close()}a=createPrivateSqliteTempDirectorySync(S.dirname(t),`openclaw-task-delivery-recovery-`);let c=S.join(a,`database.sqlite`),l=flushAndHashFileSync(i.location);if(r.copyFileSync(i.location,c,r.constants.COPYFILE_EXCL),r.chmodSync(c,384),JSON.stringify(flushAndHashFileSync(c))!==JSON.stringify(l))throw Error(`Orphan task delivery backup verification failed.`);let u=S.join(a,`orphan-rows.jsonl`),d=r.openSync(u,`wx+`,384),f=ye(`sha256`),p=0;try{for(let t of orphanRows(e)){let e=encodeOrphanRow(t);r.writeFileSync(d,e),f.update(e),p+=1}if(r.fsyncSync(d),hashFileDescriptorSync(d).sha256!==f.digest(`hex`))throw Error(`Orphan task delivery export verification failed.`)}finally{r.closeSync(d)}if(p!==n)throw Error(`Orphan task delivery export did not account for every foreign-key violation.`);r.writeFileSync(S.join(a,`manifest.json`),JSON.stringify({format:`openclaw.task-delivery-recovery.v1`,state:`preserved-before-repair`,sourcePath:t,backup:{file:`database.sqlite`,...l,integrity:`structural-ok-known-orphans`},export:{file:`orphan-rows.jsonl`,...flushAndHashFileSync(u),count:n,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(yt(a),`Task delivery recovery directory`),requireDirectorySync(yt(S.dirname(a)),`Task delivery recovery parent`);let m=e.prepare(`DELETE FROM task_delivery_state WHERE ${rB}`).run();if(Number(m.changes)!==n)throw Error(`Orphan task delivery recovery removed an unexpected number of rows.`);return assertSqliteIntegrity(e,t),[`Preserved and recovered ${n} orphan task delivery rows; backup and row export: ${a}`]}catch(e){throw Error(`Task delivery recovery failed without committing row removal${a?`; retained artifacts: ${a}`:``}: ${String(e)}`,{cause:e})}finally{i.cleanup()}}var rB,iB=__esmMin((()=>{oA(),Lx(),LA(),Xx(),TM(),TF(),Bz(),$(),rB=`NOT EXISTS (SELECT 1 FROM task_runs WHERE task_runs.task_id = task_delivery_state.task_id)`}));function runManagedStateTransaction(e,t,n){if(e.isTransaction&&!aB.has(e))throw Error(`Cannot join an unmanaged shared-state transaction; enter through runOpenClawStateWriteTransaction before BEGIN.`);let transaction=()=>withSqlitePostCommitPublications(e,()=>{let r=!e.isTransaction;r&&aB.add(e);try{return n.singleStatement?runSqliteSingleStatementSync(e,t):runSqliteImmediateTransactionSync(e,t,n)}finally{r&&aB.delete(e)}});return n.busyTimeoutMs===void 0||isPostgresSqlConnection(e)?transaction():runWithSqliteBusyTimeout(e,n.busyTimeoutMs,transaction)}var aB,oB=__esmMin((()=>{gu(),Nx(),jv(),NS(),B(),aB=resolveGlobalSingleton(Symbol.for(`openclaw.managedStateTransactions`),()=>/* @__PURE__ */ new WeakSet)}));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 36;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,i=resolveDatabasePath({path:e.path,env:n});isExistingOpenClawStateSchema(i),t.recoverTaskDeliveryOrphans&&assertOpenClawStateSchemaRepairAllowed(i);let a=r.lstatSync(i);if(!a.isFile())throw Error(`Existing-state write requires a regular database file.`);return{env:n,pathname:i,original:a}}function createExistingOpenClawStateWriter({env:e,pathname:t,original:n},i){let assertSameFile=()=>{let e=r.lstatSync(t);if(!e.isFile()||e.dev!==n.dev||e.ino!==n.ino)throw Error(`Existing-state database generation changed.`)};if(assertSameFile(),oL.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t,e),isStatePostgres())return createExistingPostgresStateWriter(t,i,assertSameFile);let a=openTrackedStateDatabase(t,{existingOnly:!0,...i.recoverTaskDeliveryOrphans?{enableForeignKeyConstraints:!1}:{}}),s=createStateSchemaAdmission(`state.subset:${ye(`sha256`).update(JSON.stringify([i.schemaSql,i.schemaCompatibility,i.integrityCheck])).digest(`hex`)}`,e=>typeof e==`number`?e:void 0,i.integrityCheck===void 0?`process`:void 0),c=i.initializeAdditiveSchema?createSqliteSchemaEnsurer(()=>i.schemaSql,{tables:getCanonicalSqliteTableNames(i.schemaSql),indexes:getCanonicalSqliteNamedIndexNames(i.schemaSql)}):void 0,l=!1,close=()=>{l=!0,clearNodeSqliteKyselyCacheForDatabase(a),closeTrackedStateDatabase(a)};return{run(e,n){if(l||!a.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 r=n.env??process.env;if(resolveDatabasePath({path:n.path,env:r})!==t)throw Error(`Existing-state writer cannot change its database path.`);assertSameFile();let u=isExistingOpenClawStateSchema(t),d=n.busyTimeoutMs??i.busyTimeoutMs??5e3;setSqliteBusyTimeout(a,d),admitStateSchemaFacts(a,t);let write=()=>runManagedStateTransaction(a,()=>{assertSameFile(),assertOpenClawStateWriteAllowed({database:a,databasePath:t,env:r});let n=s.get(a),l=n===void 0;u&&assertExistingOpenClawStateRuntimeSchema(a,t);let validate=()=>assertExistingOpenClawStateSchema(a,t,l&&i.initializeAdditiveSchema?void 0:i.schemaSql,i.schemaCompatibility,i.integrityCheck),d,f=[];if(i.recoverTaskDeliveryOrphans){try{validate()}catch(e){if(!(e instanceof SqliteRepairableForeignKeyError))throw e}f=recoverOrphanTaskDeliveryRows(a,t),d=validate()}else d=n??validate();l&&i.initializeAdditiveSchema&&(assertSqliteSchemaContains(a,t,i.schemaSql,{...i.schemaCompatibility,allowedMissingTables:getCanonicalSqliteTableNames(i.schemaSql)}),admitSqliteSchema(a),c?.(a),assertSqliteSchemaContains(a,t,i.schemaSql,i.schemaCompatibility)),l&&(admitSqliteSchema(a),s.publish(a,d));let p=e({db:a,path:t,recoveryChanges:f});return assertSameFile(),i.recoverTaskDeliveryOrphans&&assertSqliteIntegrity(a,t),p},{beginLockFailureReporting:i.beginLockFailureReporting,busyTimeoutMs:d,databaseLabel:t,operationLabel:i.operationLabel});return i.attributeUpdateWrite?runUpdateSqliteMigration(a,t,write,{close}):write()},assertSettled(){if(assertSameFile(),assertTransactionUsable(a),a.isOpen&&a.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`);a.isOpen&&assertNoActiveSqliteReaders(a,`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.`);return withEngineStoreAdmission(()=>runManagedStateTransaction(i,()=>{n(),assertOpenClawStateWriteAllowed({database:i,databasePath:e,env:c});let s=getPostgresPhysicalFacts(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}`);let l=r({db:i,path:e,recoveryChanges:[]});return n(),l},{databaseLabel:e,operationLabel:t.operationLabel,beginLockFailureReporting:t.beginLockFailureReporting}))},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()}}}var sB=__esmMin((()=>{Hv(),kx(),Du(),Nx(),Xx(),Pv(),ES(),PS(),Y(),NS(),rA(),fF(),gF(),sL(),Z(),wR(),nB(),OI(),jI(),Bz(),QF(),gR(),iB(),oB(),X(),bz()}));function getOpenClawStateFeatureSchemaSql(e,t){return t===void 0&&cB[e]?cB[e]:e===`skill_library_entries`&&t===void 0?extractSqliteTableSchema(cb,e,{endMarker:`-- End profile-owned skill library.`,includeEndMarker:!1,errorMessage:`Canonical skill library schema missing.`}):extractSqliteTableSchema(e===`user_profile_emails`?cB.user_profiles:cb,e,t)}var cB,lB=__esmMin((()=>{uy(),Z(),lb(),cB={local_workspace_projections:[extractSqliteTableSchema(cb,`local_workspace_projections`),extractSqliteTableSchema(cb,`local_workspace_manifest_nodes`),extractSqliteTableSchema(cb,`local_workspace_tree_packs`),extractSqliteTableSchema(cb,`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);

${extractSqliteTableSchema(cb,`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);
`}})),uB=__esmMin((()=>{Buffer.from(`302a300506032b6570032100`,`hex`),Buffer.from(`302e020100300506032b657004220420`,`hex`)})),dB=__esmMin((()=>{Uu(),uB()})),fB=__esmMin((()=>{})),pB=__esmMin((()=>{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(`.`))})),mB=__esmMin((()=>{Pj(),fB(),pB()})),hB=__esmMin((()=>{Pj(),mB(),bd()}));function normalizePersistedAllowlistSource(e){return e===`allow-always`?e:void 0}function createExecApprovalsSchema(e,t){let n=vB.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=>!isRecord(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:vB.optional(),agents:r.optional()})}var gB,_B,vB,yB,bB,xB=__esmMin((()=>{D(),tD(),hB(),gB=_enum([`allowlist`,`full`,`deny`]),_B=_enum([`always`,`off`,`on-miss`]),vB=looseObject({security:gB.optional(),ask:_B.optional(),askFallback:gB.optional(),autoAllowSkills:boolean().optional()}),yB=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()}),bB=union([string().trim().min(1),yB.extend({id:string().optional(),source:string().transform(normalizePersistedAllowlistSource).optional(),commandText:string().optional()})]).transform(e=>typeof e==`string`?{pattern:e}:e),createExecApprovalsSchema(yB,!1),createExecApprovalsSchema(bB,!0)})),SB=__esmMin((()=>{$(),dB(),xB(),G()})),CB=__esmMin((()=>{vp(),X()})),wB=__esmMin((()=>{sp(),CF()})),TB=__esmMin((()=>{SB(),wB(),LA(),ES(),Y()})),EB=__esmMin((()=>{Up(),X(),TB(),wB(),G(),UM()})),DB=__esmMin((()=>{dB(),G()})),OB=__esmMin((()=>{ID()})),kB=__esmMin((()=>{Up(),B(),ip(),DB(),CB(),EB(),H(),LA(),OB(),J(),kb(),Xx(),ES(),NS(),UM(),qv(),fF(),resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialCustody`),()=>/* @__PURE__ */ new Set),resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialAdmittedFiles`),()=>/* @__PURE__ */ new Map,e=>e.clear())})),AB=__esmMin((()=>{Z(),$(),gR(),Ix(),SB(),CB(),EB(),wB(),kB(),VL(),xk(),G(),jv(),NS(),fF()})),jB=__esmMin((()=>{Op()})),MB,NB,PB=__esmMin((()=>{hB(),MB=`openclaw`,NB=[{id:MB,kind:`system`},{id:`crestodian`,kind:`system`}],new Set(NB.map(e=>normalizeAgentId(e.id)))})),FB=__esmMin((()=>{hB(),PB()})),IB=__esmMin((()=>{})),LB=__esmMin((()=>{Uu()})),RB=__esmMin((()=>{H()})),zB=__esmMin((()=>{sp(),hB(),Rj(),vp(),LB(),RB()})),BB=__esmMin((()=>{IB(),zB()})),VB=__esmMin((()=>{FB(),hB(),BB()})),HB=__esmMin((()=>{qD(),Hy()})),UB=__esmMin((()=>{Qd(),HB(),bp()})),WB=__esmMin((()=>{sp(),UB(),bp(),hB(),B(),Ix(),Op(),resolveGlobalMap(Symbol.for(`openclaw.agentDirPreparedPaths`),e=>{for(let t of e.values())t.close();e.clear()},`shared-state`)}));function resolveDefaultAgentWorkspaceDir(e=process.env,t=Xe.homedir){let n=e.OPENCLAW_WORKSPACE_DIR?.trim();if(n)return S.resolve(n);if(e.OPENCLAW_STATE_DIR?.trim())return S.join(resolveStateDir(e,t),`workspace`);let r=resolveRequiredHomeDir(e,t),i=e.OPENCLAW_PROFILE?.trim();return i&&normalizeOptionalLowercaseString(i)!=="default"?S.join(resolveProfileStateDir(i,e,t),`workspace`):S.join(r,`.openclaw`,`workspace`)}var GB=__esmMin((()=>{Lt(),hp(),vp(),pp()})),KB=__esmMin((()=>{GB(),resolveDefaultAgentWorkspaceDir()})),qB=__esmMin((()=>{jB(),Up(),VB(),hB(),Op(),WB(),FB(),KB()})),JB=__esmMin((()=>{aA(),vM()})),YB=__esmMin((()=>{Op()})),XB=__esmMin((()=>{JB(),vM(),Ev(),rp(),YB(),vp(),createSubsystemLogger(`config`)})),ZB=__esmMin((()=>{ep()})),QB=__esmMin((()=>{ND(),Yd(),H(),Xy(),wF(),GF(),rp(),Np(),XB(),Up(),ZB()})),$B=__esmMin((()=>{FB(),qB(),hB()})),eV=__esmMin((()=>{qB(),H(),Op(),GF(),QB(),Up(),zB(),RB(),$B()})),tV=__esmMin((()=>{Rj()})),nV=__esmMin((()=>{eV(),H(),CF(),tV(),X()}));function createDedupeCache(e){let t=resolveNonNegativeIntegerOption(e.ttlMs,0),n=resolveNonNegativeIntegerOption(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):pruneMapToMaxSize(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}}var rV=__esmMin((()=>{Uu(),lm()})),iV=__esmMin((()=>{vp(),rV(),H(),ID(),CF(),Ev(),X(),createSubsystemLogger(`state/db`),createDedupeCache({ttlMs:0,maxSize:4096}),Object.freeze([[`client`,`credentials.sqlite`],[`control`,`services.sqlite`]])})),aV=__esmMin((()=>{AB(),TB(),VL(),Xy(),yk(),xk(),G(),Nx(),CF(),Xx(),W(),UM(),XM(),ZM(),nN(),qv(),$F(),rA(),fF(),Ev(),gF(),sL(),Z(),eI(),GL(),wR(),OI(),nV(),jI(),iV(),gR(),bz(),vR(),createSubsystemLogger(`state/db`)})),oV=__esmMin((()=>{kx(),$F(),nB(),gR()})),sV=__esmMin((()=>{B(),resolveGlobalSingleton(Symbol.for(`openclaw.postgresStateReadSnapshot`),()=>new C)})),cV=__esmMin((()=>{Yy(),Du(),LA(),J(),kb(),MF(),W(),ZA(),Y(),QP(),NS(),nN(),qv(),Qd(),LS(),sL(),Z(),wR(),OI(),jI(),oV(),QF(),gR(),_R(),sV()})),lV=__esmMin((()=>{TF(),LS(),sL(),QF(),X()})),uV=__esmMin((()=>{W(),Y(),qv(),LS(),sL(),cV(),oB(),Ix()})),dV=__esmMin((()=>{MD(),xk(),TR()})),fV=__esmMin((()=>{Yy(),MF(),nP(),rP(),XP(),bP()})),pV=__esmMin((()=>{Hv(),pP(),qD(),YD(),pI(),J(),W(),qv(),tP(),XP(),sL(),fV(),WN()})),mV=__esmMin((()=>{Tp(),kx(),UD(),xk(),LA(),J(),W(),dV(),ZA(),sF(),vM(),TF(),sL(),Z(),uV(),X(),pV(),WN()})),hV=__esmMin((()=>{W(),SO(),LS(),sL()})),gV=__esmMin((()=>{GF(),vp(),LS(),sL(),X(),tI()})),_V=__esmMin((()=>{Tp(),yk(),J(),W(),cF(),ZA(),sF(),vM(),TF(),Ev(),aA(),sL(),wR(),X(),Ix(),gV(),createSubsystemLogger(`state/db`)})),vV=__esmMin((()=>{H(),LA(),W(),ZA(),TF(),wF(),rI(),SO(),B(),aA(),sL(),lV(),wR(),cV(),uV(),QF(),X(),Ix(),sV(),mV(),hV(),_V(),gV(),resolveGlobalSingleton(Symbol.for(`openclaw.disposableStateReads`),()=>new C),resolveGlobalSingleton(Symbol.for(`openclaw.stateSnapshotReads`),()=>new C),resolveGlobalSingleton(Symbol.for(`openclaw.synchronousStateReadSnapshots`),()=>({current:void 0}))})),yV=__esmMin((()=>{kb()})),bV=__esmMin((()=>{Xx(),zx(),ES(),NS()})),xV=__esmMin((()=>{oA(),Lx(),LA(),bV(),TM(),TF()})),SV=__esmMin((()=>{LA(),Xx(),NS()})),CV,wV=__esmMin((()=>{CV=[`auth`,`auth_permanent`,`format`,`rate_limit`,`overloaded`,`billing`,`server_error`,`timeout`,`tls_certificate`,`context_overflow`,`model_not_found`,`session_expired`,`empty_response`,`no_error_details`,`unclassified`,`unknown`]}));function closedObject(e){let t=Nt.Object(e,{additionalProperties:!1});return Object.defineProperty(t,TV,{value:Symbol(`closedObject`)}),t}var TV,EV=__esmMin((()=>{TV=`~openclawClosedObjectIdentity`})),DV,OV,kV=__esmMin((()=>{DV=864e13,OV=Nt.Integer({minimum:0,maximum:DV})}));function stringLiteralUnion(e){let t=e.map(e=>Nt.Literal(e));return Nt.Union(t)}var AV=__esmMin((()=>{})),jV,MV,NV,PV,FV=__esmMin((()=>{EV(),kV(),AV(),jV=stringLiteralUnion([`progress`,`done`,`blocked`,`needs_attention`]),Nt.Union([Nt.Literal(`no_change`),jV]),MV=Nt.String({minLength:1,maxLength:2e3,pattern:`\\S`}),NV=closedObject({outcome:jV,summary:MV}),PV=Nt.Union([closedObject({outcome:Nt.Literal(`no_change`),summary:Nt.Optional(MV)}),NV]),closedObject({...NV.properties,atMs:OV})}));function parseAutomationResult(e){if(!isRecord(e))return;let t=typeof e.summary==`string`?{...e,summary:e.summary.trim()}:{...e};return Mt.Check(PV,t)?t:void 0}var IV=__esmMin((()=>{D(),FV()})),LV=__esmMin((()=>{Uu()}));function isJsonObject(e){return isRecord(e)}function normalizeTimestamp(e){return asSafeIntegerInRange(e,{min:0,max:Hu})}var RV,zV,BV,VV,HV,UV,WV,GV,KV,qV=__esmMin((()=>{Uu(),D(),tD(),wV(),IV(),LV(),RV=_enum([`ok`,`error`,`skipped`]),zV=_enum([`succeeded`,`failed`,`unknown`]),BV=_enum([`delivered`,`not-delivered`,`unknown`,`not-requested`]),VV=string().optional().catch(void 0),HV=string().refine(e=>e.trim().length>0).optional().catch(void 0),UV=unknown().optional().transform(e=>normalizeTimestamp(e)),WV=unknown().optional().transform(e=>asSafeIntegerInRange(e,{min:0})),GV=object({input_tokens:WV,output_tokens:WV,total_tokens:WV,cache_read_tokens:WV,cache_write_tokens:WV}).transform(e=>Object.values(e).some(e=>e!==void 0)?e:void 0).optional().catch(void 0),KV=looseObject({status:BV,delivered:boolean().optional().catch(void 0),error:VV}).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:RV.optional().catch(void 0),completionStatus:zV.optional().catch(void 0),error:VV,errorReason:_enum(CV).optional().catch(void 0),summary:VV,result:unknown().optional().transform(parseAutomationResult),runId:HV,diagnostics:unknown().optional(),runAtMs:UV,durationMs:WV,nextRunAtMs:UV,triggerFired:unknown().optional().transform(e=>e===!0||void 0),model:HV,provider:HV,usage:GV,delivered:boolean().optional().catch(void 0),deliveryStatus:BV.optional().catch(void 0),deliveryError:VV,deliverySuppressionReason:_enum([`empty`,`silent`,`heartbeat`,`channel_transform`]).optional().catch(void 0),failureNotificationDelivery:KV,delivery:custom(isJsonObject).optional().catch(void 0),sessionId:HV,sessionKey:HV})})),JV=__esmMin((()=>{Yu(),qV(),yM(),AR()})),YV=__esmMin((()=>{G(),$(),gR()})),XV=__esmMin((()=>{ES(),PS(),aR(),wR(),cz(),$(),lB()})),ZV=__esmMin((()=>{kx(),xk(),Du(),LA(),J(),CF(),Xx(),jv(),ES(),Y(),NS(),UM(),bM(),nN(),rA(),gF(),sL(),Z(),nV(),jI(),iV(),vV(),$(),QF(),gR(),X(),bz()})),QV=__esmMin((()=>{sp(),qF()})),$V=__esmMin((()=>{Iz(),Rz()})),eH=__esmMin((()=>{AB(),bV(),Xx(),Y(),SV(),$F(),rA(),JV(),Ev(),YV(),gF(),sL(),Z(),eI(),nB(),tB(),$R(),jI(),Bz(),XV(),$(),QF(),eB(),Jz(),QR(),gR(),Yz(),ZV(),$z(),X(),Ix(),bz(),Mz(),QV(),$V(),createSubsystemLogger(`state/db`)})),tH=__esmMin((()=>{AB(),G(),LA(),yV(),Nx(),J(),xV(),bV(),Xx(),W(),ES(),SV(),NS(),JV(),fF(),YV(),OF(),gF(),Kz(),sL(),Z(),XR(),tB(),$R(),Bz(),sz(),iV(),XV(),$(),QF(),eB(),eH(),Jz(),QR(),gR(),Yz(),ZV(),$z(),iB(),X(),bz(),Mz(),Nz(),$V()})),nH=__esmMin((()=>{qD(),YD(),Hy(),oM(),vM(),WN()})),rH=__esmMin((()=>{cP(),yk(),xk(),CF(),ZA(),TF(),rA(),LS(),vV(),nH(),bz()})),iH=__esmMin((()=>{TF(),fF(),wR(),vV(),eB(),X()})),aH=__esmMin((()=>{Hv(),kx(),xk(),Nx(),Xx(),W(),Pv(),Y(),TF(),NS(),UM(),ZM(),rA(),aA(),gF(),LS(),sL(),Z(),XR(),wR(),nB(),tB(),OI(),Bz(),aV(),iV(),cV(),vV(),tH(),QF(),eH(),gR(),ZV(),oB(),X(),rH(),bz(),vR(),iH()}));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(!isRecord(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}}var oH=__esmMin((()=>{D()})),sH,cH=__esmMin((()=>{PS(),wR(),lB(),sH=`
  WHERE completed_at_ms IS NOT NULL;`,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`?sH:void 0}),{tables:[e],indexes:e===`node_worker_launches`?[`idx_node_worker_launches_terminal_completed`]:[]})]))})),lH=__esmMin((()=>{G(),Y(),$()}));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}var uH=__esmMin((()=>{YF(),G(),Y(),tA(),$(),aH(),oH(),cH(),lH()}));function requireNodeWorkerProcessIdentity(e){let t=getFileLockProcessStartTime(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=getFileLockProcessStartTime(e.pid);return t===null?isPidDefinitelyDead(e.pid)?`dead`:`unknown`:t===e.startTime?isPidDefinitelyDead(e.pid)?`dead`:`live`:`reused`}var dH=__esmMin((()=>{SD(),on()})),fH=/* @__PURE__ */ __exportAll({recordNodeWorkerDescendantsReaped:()=>recordNodeWorkerDescendantsReaped,recordNodeWorkerLineageSettled:()=>recordNodeWorkerLineageSettled});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:pH+(t===`descendants`?`
`+getOpenClawStateFeatureSchemaSql(`node_worker_launch_process_scopes`):``),operationLabel:`node-worker-launch.`+t+`-settled`})}var pH,mH=__esmMin((()=>{G(),sB(),lB(),uH(),dH(),pH=[`node_worker_launches`,`node_worker_launch_cleanup`].map(e=>getOpenClawStateFeatureSchemaSql(e)).join(`
`)})),hH=/* @__PURE__ */ __exportAll({acquireLinuxChildSubreaper:()=>acquireLinuxChildSubreaper});function childPids(){let e=/* @__PURE__ */ new Set;for(let t of p(`/proc/self/task`)){let n;try{n=f(`/proc/self/task/`+t+`/children`,`utf8`)}catch(e){ignoreMissingPath(e);continue}for(let t of n.trim().split(/\s+/u).filter(Boolean)){if(!/^\d+$/u.test(t)||!Number.isSafeInteger(Number(t))||Number(t)<=0)throw Error(`Linux process owner could not enumerate its children`);e.add(Number(t))}}return[...e]}function acquireLinuxChildSubreaper(){if(process.platform!==`linux`)throw Error(`Linux child ownership requires Linux`);if(runtimeHasSourceLoader())throw Error(`Linux child ownership requires a process owner without source-loader hooks`);if(Dt(),!kt())throw Error(`Linux child ownership admission verification failed`);let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Map,n=!1,retainSpawnedChild=(r,i)=>{if(i.pid!==r||!Number.isSafeInteger(r)||r<=0)throw Error(`Linux child ownership requires a spawned root`);e.add(r),n||=(process.on(`SIGCHLD`,reapExitedChildren),!0),i.once(`exit`,()=>{e.delete(r),t.delete(r)})};if(childPids().length>0)throw Error(`Linux child ownership requires a dedicated owner without existing children`);let r=!1,i={retainSpawnedChild,drain(n){if(r)return!0;for(let r of childPids()){let i=Ot(r);if(i.kind===`none`)continue;let a=t.get(r);if(i.kind===`running`&&n&&a!==n&&a!==`SIGKILL`){try{process.kill(r,n)}catch(e){if(!w(e,`ESRCH`))throw e}t.set(r,n)}i.kind===`exited`&&!e.has(r)&&At(r)&&t.delete(r)}return Ot().kind===`none`&&(r=!0,process.off(`SIGCHLD`,reapExitedChildren),!0)}},reapExitedChildren=()=>{try{i.drain()}catch{}};return i}var gH=__esmMin((()=>{wy(),H()}));D(),It(),Ut(),Wt(),Kt(),ln();function commandStdio(e){let t=[e.stdinMode===`inherit`?`inherit`:`pipe`,`pipe`,`pipe`];e.secretFd!==void 0&&setStdioEntry(t,e.secretFd,e.secretFd);let n=reserveStdioEntry(t,e.lineageFd??`pipe`),r=[n,...(e.parentLineageFds??[]).map(e=>reserveStdioEntry(t,e))];return e.ownedWorker&&t.push(`ipc`),{stdio:t,lineageFd:n,inheritedLineageFds:r}}function delay(e,t=!1){return new Promise(n=>{let r=setTimeout(n,e);t||r.unref?.()})}function runServiceChildGroupAnchor(){let t=createDeferredCore(),r,i,a=!1,c=`starting`,l=0,u=0,d,f,p=!1,m=!1,h=[],g,v=!1,y,ee,te=/* @__PURE__ */ new Set([`stdout`,`stderr`]),ne=!1,re=!1,ie,ae=!1,oe=!1,se=createDeferredCore(),S=createDeferredCore(),ce=createDeferredCore(),le=createDeferredCore(),ue=createDeferredCore(),de=createDeferredCore(),fe,pe=!1,finishInput,send=async e=>{r&&g&&!g.destroyed&&(l+=1,await new Promise(t=>{g.write(encodeServiceChildMessage({...e,generation:r.generation,sequence:l}),()=>t())}))},finish=e=>{process.exitCode=e,releaseProcessStdin();let disconnect=()=>{g?.off(`close`,disconnect),g?.destroy(),process.connected&&process.disconnect?.()};g&&!g.destroyed?(g.once(`close`,disconnect),g.end(disconnect)):disconnect()},closeAuthority=async(e,t,n=monotonicNow()+Gt)=>{if(!r||c===`closed`)return;if(r.treeOwnership===`linux-subreaper`){if(d&&!a)throw Error(`native owner cannot close before descendant extinction`);c=`closed`;for(let e of new Set(r.parentLineageFds??[]))s(e);fe=l+1,await send({type:`closing`,reason:e,...a?{descendantsReaped:!0}:{}});let t=await Promise.race([de.promise,delay(Math.max(0,n-monotonicNow())).then(()=>!1)]);finish(+!t);return}if(c=`closed`,t&&r.lineageFd===void 0&&!ne){process.kill(0,`SIGKILL`);return}let i=r.acknowledgeClosing===!0;fe=i?l+1:void 0;let u=n-monotonicNow();u>0&&send({type:`closing`,reason:e}).then(()=>{i||de.resolve(!0)},()=>de.resolve(!1)),u<=0||!await Promise.race([de.promise,delay(u).then(()=>!1)])||monotonicNow()>=n||t?process.kill(0,`SIGKILL`):finish(0)},closeInheritedLineage=()=>{r?.lineageFd!==void 0&&!p&&(p=!0,s(r.lineageFd))},reportStartupFailure=async(e,t=!1)=>{if(closeInheritedLineage(),await send({type:`startup-error`,anchorPid:process.pid,error:e instanceof Error?e.message:e,...e instanceof Error?{errorDetails:serializeBrokerError(e)}:{}}),await Promise.race([ue.promise,de.promise]),i)for(;!(a=i.drain(`SIGKILL`));)await delay(10,!0);await closeAuthority(`lineage-lost`,t)},requestCleanup=async(e,t=`SIGTERM`)=>{if(!r||c===`closed`)return;oe||=e===`parent-lost`;let n=t===`SIGKILL`||oe&&r.terminateOnHostLoss===!0;if(oe&&r.terminateOnHostLoss&&a&&(ne=!0,S.resolve()),c===`closing`){ae||=n,ae&&se.resolve();return}if(c=`closing`,ae=n,!d){await reportStartupFailure(`command startup cancelled before spawn`,!0);return}let s=monotonicNow()+Gt,l=delay(Gt);if(!r.ownedWorker&&!ae&&ee&&te.size>0&&await Promise.race([le.promise,l,se.promise]),i)try{for(;!i.drain(ae||remainingMonotonicMs(s)<=0?`SIGKILL`:`SIGTERM`);)await delay(10,!0);if(a=!0,await ce.promise,await y,await le.promise,oe&&r.terminateOnHostLoss&&(ne=!0,S.resolve()),await S.promise,!ne)throw Error(`native owner lost lineage observation before EOF`);if(r.ownedWorker&&f){let e=!1;try{e=f.recordNodeWorkerDescendantsReaped(r.cleanupBinding)}catch{}e||await send({type:`output`,stream:`stderr`,chunk:`node worker descendant extinction was not recorded; restart recovery retains capacity
`})}await closeAuthority(e,!1)}catch(e){await send({type:`result-error`,error:e instanceof Error?e.message:String(e)})}else if(r.ownedWorker){ae||process.kill(0,`SIGTERM`);let t=Promise.all([ce.promise,S.promise]);ae||await Promise.race([t,l,se.promise]),ee||d?.kill(`SIGKILL`),ne||killOwnedProcessGroupMembers(),await t,await y;let n=!1;if(ee&&ne&&f)try{n=f.recordNodeWorkerLineageSettled(r.cleanupBinding)}catch{}n||await send({type:`output`,stream:`stderr`,chunk:`node worker lineage completion was not recorded; restart recovery will retain capacity until cleanup can be verified
`}),ae||await Promise.race([le.promise,l,se.promise]),await closeAuthority(e,!0)}else if(ae||(process.kill(0,`SIGTERM`),await Promise.race([S.promise,l,se.promise])),c===`closing`&&r&&(ne&&!ee&&!ae&&await Promise.race([ce.promise,l,se.promise]),c===`closing`&&r&&!(ee&&!ae&&(await Promise.race([le.promise,l,se.promise]),c!==`closing`||!r)))){for(;!(ae||!ee||te.size>0||!ne);){let t=Math.max(0,remainingMonotonicMs(s));if(t<=0)break;if(hasLiveOwnedProcessGroupMembers(t)===!1){await closeAuthority(e,!1,s);return}let n=Math.min(100,Math.max(0,remainingMonotonicMs(s)));if(n<=0)break;await Promise.race([delay(n),se.promise])}await closeAuthority(e,!0)}},onControlMessage=e=>{if(!(!r||e.generation!==r.generation||!Number.isSafeInteger(e.sequence)||e.sequence<=u)){if(e.type===`closing-ack`)c===`closed`&&fe!==void 0&&e.closingSequence===fe&&(u=e.sequence,de.resolve(!0));else if(c!==`closed`){if(u=e.sequence,e.type===`launch`)t.resolve();else if(e.type===`startup-error-ack`)ue.resolve();else if(e.type===`lineage-closed`)ie?.();else if(e.type===`stdin-end`)pe=!0,finishInput?.();else if(e.type===`worker-close`)r.ownedWorker&&!d?requestCleanup(`cancel`):r.ownedWorker&&d?.connected&&d.disconnect();else if(e.type===`worker-start`){if(!r.ownedWorker||m||c!==`active`)return;if(!d?.connected){requestCleanup(`parent-lost`);return}m=!0,d.send({type:`openclaw-worker-start-v1`,lineageFds:h,...r.nativeProcessOwner?{nativeProcessOwner:r.nativeProcessOwner}:{}},e=>{e&&requestCleanup(`parent-lost`)})}else requestCleanup(`cancel`,e.signal)}}},startCommand=async a=>{let s=a.controlFd;if(s===void 0){c=`closed`,finish(1);return}r=a;let l=process.versions.bun?new b({readable:!0,writable:!0}):new b({fd:s,readable:!0,writable:!0});g=l,l.setEncoding(`utf8`);let u=``;l.on(`data`,e=>{for(u+=e;;){let e=u.indexOf(`
`);if(e<0)break;let t=u.slice(0,e);u=u.slice(e+1);try{onControlMessage(JSON.parse(t))}catch{requestCleanup(`parent-lost`)}}});let onControlLoss=()=>{de.resolve(!1),c!==`closed`&&requestCleanup(`parent-lost`)};if(l.once(`end`,onControlLoss),l.once(`close`,onControlLoss),l.once(`error`,onControlLoss),process.versions.bun&&l.connect({fd:s}),f=a.ownedWorker?await Promise.resolve().then(()=>(mH(),fH)).catch(()=>void 0):void 0,a.treeOwnership===`linux-subreaper`)try{let e=await Promise.resolve().then(()=>(gH(),hH));if(!e)throw Error(`portable workers require their admitted host-native process owner`);i=e.acquireLinuxChildSubreaper()}catch(e){await reportStartupFailure(e instanceof Error?e:String(e));return}if(a.type===`prepare`&&(await send({type:`prepared`}),await Promise.race([t.promise,de.promise])),r!==a||g!==l||c!==`starting`||l.destroyed||l.readableEnded||l.writableEnded||!process.connected){await requestCleanup(`parent-lost`);return}let{stdio:p,lineageFd:m,inheritedLineageFds:ae}=commandStdio(r);h=ae;let oe;try{if(process.versions.bun&&(process.platform===`darwin`||process.platform===`linux`)){let t=e(import.meta.url)(`bun:ffi`),n=process.platform===`darwin`?`/usr/lib/libSystem.B.dylib`:`libc.so.6`;oe=t.dlopen(n,{shutdown:{args:[`i32`,`i32`],returns:`i32`}}).symbols.shutdown}d=spawnWithInheritedOomScore(r.command,r.args,{cwd:r.cwd,env:r.env,argv0:r.argv0,stdio:p,detached:!1,windowsHide:!0}),d.pid&&i?.retainSpawnedChild(d.pid,d),await n(d,`spawn`)}catch(e){await reportStartupFailure(e instanceof Error?e:String(e));return}let markLineageClosed=()=>{ne||re||(ne=!0,S.resolve(),c===`active`&&(async()=>{await ce.promise,c===`active`&&(v&&await le.promise,c===`active`&&requestCleanup(`lineage-lost`))})())};if(r.lineageFd!==void 0)ie=markLineageClosed,closeInheritedLineage();else{let e=d.stdio[m];if(!e){await send({type:`startup-error`,error:`command lineage pipe was not created`}),await requestCleanup(`lineage-lost`,`SIGKILL`);return}e.once(`end`,markLineageClosed);let markLineageFailed=()=>{ne||re||(re=!0,S.resolve(),requestCleanup(`lineage-lost`))};e.once(`close`,()=>{e.readableEnded||markLineageFailed()}),e.once(`error`,markLineageFailed),e.resume()}let settleRoot=async()=>{v||!y||te.size>0||(v=!0,await y,le.resolve(),ne&&c===`active`&&await requestCleanup(`lineage-lost`))};for(let e of[`stdout`,`stderr`])x(d[e],process[e],()=>{oe?.(e===`stdout`?1:2,1),te.delete(e),settleRoot()});if(r.stdinMode!==`inherit`&&d.stdin){let e=process.stdin,t=d.stdin,endInput=()=>{(!r?.terminateOnHostLoss||pe)&&t.end()};finishInput=()=>{e.readableEnded&&endInput()};let n=!1,stopInput=()=>{e.unpipe(t),e.off(`end`,endInput),releaseProcessStdin(),n||(n=!0,send({type:`stdin-closed`}))};t.once(`error`,stopInput),t.once(`close`,stopInput),e.pipe(t,{end:!1}),e.readableEnded?endInput():e.once(`end`,endInput)}d.once(`error`,e=>{c===`starting`&&reportStartupFailure(e.message)}),r.ownedWorker&&d.on(`message`,e=>{c===`active`&&send({type:`worker-message`,message:e})}),d.pid&&c===`starting`&&(c=`active`,send({type:`ready`,commandPid:d.pid,anchorPid:process.pid,...i?{treeOwnership:`linux-subreaper`}:{}})),d.once(`exit`,(e,t)=>{ee={code:e,signal:t},y=send({type:`root-result`,code:e,signal:t}),ce.resolve(),settleRoot(),i&&r?.ownedWorker&&c===`active`&&requestCleanup(`lineage-lost`)})},onParentSignal=()=>{(c===`active`||r&&c===`starting`)&&requestCleanup(`parent-lost`)};process.on(`SIGTERM`,onParentSignal),process.on(`SIGINT`,onParentSignal),process.once(`disconnect`,()=>{de.resolve(!1),c!==`closed`&&requestCleanup(`parent-lost`)}),process.on(`message`,e=>{let t=e;if((t.type===`start`||t.type===`prepare`)&&!r&&c===`starting`){if(isRecord(e)&&e.acknowledgeClosing!==void 0&&e.acknowledgeClosing!==!0){c=`closed`,finish(1);return}startCommand(t)}else t.type===`parent-loss`&&t.generation===r?.generation&&(de.resolve(!1),requestCleanup(`parent-lost`))})}runServiceChildGroupAnchor();export{runServiceChildGroupAnchor};