openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3,825 lines • 910 kB
JavaScript
import*as e from"node:module";import{createRequire as t}from"node:module";import n,{basename as r,dirname as i,join as a,posix as s}from"node:path";import{fileURLToPath as c,pathToFileURL as l}from"node:url";import u,{existsSync as d,fstatSync as f,mkdirSync as p,opendirSync as m,readFileSync as h,readdirSync as g,readlinkSync as _,statSync as v,default as y}from"node:fs";import{createHash as b,randomBytes as x,randomUUID as S}from"node:crypto";import{appendRegularFileSync as ee,canUseRootFileOpen as te,openRootFileSync as ne,readFileDescriptorBoundedSync as re,readFileWindowFullySync as ie}from"@openclaw/fs-safe/advanced";import"@openclaw/fs-safe/errors";import{hasNodeErrorCode as C,isNodeError as ae,isPathInside as oe,isPathInside as se,normalizeWindowsPathForComparison as ce}from"@openclaw/fs-safe/path";import w,{mkdtemp as le,realpath as ue,rm as de,stat as fe,default as pe}from"node:fs/promises";import me,{availableParallelism as he,tmpdir as ge}from"node:os";import"@openclaw/fs-safe/output";import"@openclaw/fs-safe/root";import"@openclaw/fs-safe/secure-file";import"@openclaw/fs-safe/walk";import{channel as _e}from"node:diagnostics_channel";import{performance as ve}from"node:perf_hooks";import{BroadcastChannel as ye,MessageChannel as be,MessagePort as xe,SHARE_ENV as Se,Worker as Ce,getEnvironmentData as we,isMainThread as T,parentPort as Te,receiveMessageOnPort as Ee,setEnvironmentData as De,threadId as E,workerData as Oe}from"node:worker_threads";import{Buffer as ke,isUtf8 as Ae}from"node:buffer";import{AsyncLocalStorage as D,AsyncResource as je}from"node:async_hooks";import Me,{execFile as Ne,execFileSync as Pe,spawn as Fe,spawnSync as Ie}from"node:child_process";import{isPromise as Le}from"node:util/types";import{isDeepStrictEqual as Re,stripVTControlCharacters as ze,toUSVString as Be,types as Ve}from"node:util";import*as He from"node:v8";import{GCProfiler as Ue,deserialize as We,getHeapSpaceStatistics as Ge,getHeapStatistics as Ke,serialize as qe,setFlagsFromString as Je}from"node:v8";import{Session as Ye}from"node:inspector/promises";import{Chalk as Xe}from"chalk";import{Logger as Ze}from"tslog";import{readRootJsonObjectSync as Qe}from"@openclaw/fs-safe/json";import{replaceFileAtomic as $e}from"@openclaw/fs-safe/atomic";import{setImmediate as et,setTimeout as tt}from"node:timers/promises";import{parse as nt}from"semver";import{Socket as rt,connect as it}from"node:net";import{ProcSafeError as at}from"@openclaw/proc-safe/errors";import{readProcessAncestry as ot,readProcessIdentity as st}from"@openclaw/proc-safe/identity";import"@openclaw/proc-safe/reaper";import{listProcesses as ct,readProcessCommand as lt}from"@openclaw/proc-safe/inspect";import{EventEmitter as ut}from"node:events";import"@openclaw/fs-safe/durability";import{PinnedProcess as dt}from"@openclaw/proc-safe/windows-job";var ft=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)ft(n,r,{get:e[r],enumerable:!0});return t||ft(n,Symbol.toStringTag,{value:`Module`}),n};function toStringifiedError(e){return e instanceof Error?e:Error(String(e))}var pt=__esmMin((()=>{}));function isProviderAuthPersistenceError(e){try{return mt in e&&e[mt]===!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 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 mt,O=__esmMin((()=>{pt(),mt=Symbol.for(`openclaw.provider-auth-persistence-error`)}));O();function nativeErrorDetails(e){let t=e;return{message:e.message,code:t.code,errcode:t.errcode}}function serializeNativeErrorResponse(e){let t=toStringifiedError(e);return{name:t.name,...nativeErrorDetails(t),...t.cause instanceof Error?{cause:nativeErrorDetails(t.cause)}:{}}}const ht=/^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/;function parseReleaseVersion(e){let t=e.trim(),n=ht.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))}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 k=__esmMin((()=>{})),gt=__esmMin((()=>{}));gt();const _t=/* @__PURE__ */ `durable_background_processes.sandbox_persistent_execs.user_profile_identities.user_background_images.local_workspace_projections.local_workspace_manifest_nodes.local_workspace_tree_packs.local_workspace_source_path_sets.update_runs.session_repository_workspaces.github_repository_publication_requests.github_publication_session_lifecycles.skill_library_entries.skill_library_revisions.skill_library_events.skill_library_uploads.github_personal_publication_requests.cron_job_runtime_authorities.cron_run_trigger_state_retirements.execution_identity_contexts.mcp_oauth_pending_authorizations.node_worker_launch_containers.node_worker_launch_boots.node_worker_launch_cleanup.node_worker_launch_process_scopes.node_worker_launches.node_worker_prepared_workspaces.node_worker_turns.operator_approval_execution_identities.operator_approval_standing_grants.operator_approval_standing_grant_generations.web_push_approval_deliveries.execution_decision_facts.execution_owner_lifecycle_bindings.outbound_message_execution_bindings.outbound_message_progress`.split(`.`),vt=[`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`];[..._t],[...vt];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 yt=__esmMin((()=>{}));function normalizeUrlQueryParamName(e){let t=e.replace(xt,``);for(let e=0;e<=Ct;e+=1){let e;try{e=decodeURIComponent(t).replace(xt,``)}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||bt.has(t.value)||St.test(t.value)}var bt,xt,St,Ct,wt=__esmMin((()=>{yt(),bt=/* @__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(`.`)),xt=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,St=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u,Ct=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=Pt.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?Ft:Pt).exec(e.slice(t));return s?t+s[0].length:null}function findStructuredAuthParamRanges(e){let t=[];for(let n of e.matchAll(Nt)){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 Tt,Et,Dt,Ot,kt,At,jt,Mt,A,Nt,Pt,Ft,It=__esmMin((()=>{Tt="[A-Za-z0-9!#$%&'*+.^_`|~-]+",Et=String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`,Dt=String.raw`\\{1,64}t`,Ot=String.raw`(?:[ \t]+|${Dt})`,kt=String.raw`(?:[ \t]*\r?\n${Ot}|[ \t]*\\{1,64}r\\{1,64}n${Ot}|[ \t]*\\{1,64}n${Ot}|[ \t]*${Dt}[ \t]*|[ \t]*)`,At=String.raw`(?:[ \t]*\r?\n${Ot}|[ \t]*\\{1,64}r\\{1,64}n${Ot}|[ \t]*\\{1,64}n${Ot}|[ \t]*${Dt}[ \t]*|[ \t]+)`,jt=String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${Dt})|[ \t]*\\{1,64}n(?:[ \t]*|${Dt})|[ \t]*${Dt}[ \t]*)`,Mt=String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`,A=String.raw`(?:\\{1,64}["']|["']|)`,`${Mt}${A}${kt}${A}`,Nt=/* @__PURE__ */ RegExp(`${Mt}(?:Proxy-)?Authorization${A}[ \\t]*[:=]${kt}${A}(${Tt})${At}`,`giu`),Pt=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u,Ft=/^[A-Za-z0-9!#$%&'*+.^_`|~:/-]+/u})),Lt=__esmMin((()=>{})),Rt=__esmMin((()=>{})),zt=__esmMin((()=>{})),Bt=__esmMin((()=>{}));function expectDefined(e,t){if(e==null)throw Error(`expected `+t+` to be defined`);return e}var Vt=__esmMin((()=>{})),Ht=__esmMin((()=>{})),Ut=__esmMin((()=>{}));function asFiniteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}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),Wt)}var Wt,Gt=__esmMin((()=>{Wt=2147e6,Math.floor(Wt/1e3)})),Kt=__esmMin((()=>{})),qt=__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 Jt=__esmMin((()=>{})),Yt=__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 Xt=__esmMin((()=>{})),Zt=__esmMin((()=>{Lt(),Rt(),zt(),Bt(),O(),Vt(),Ht(),Ut(),Gt(),k(),Kt(),qt(),yt(),Jt(),Yt(),Xt()}));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 Qt=__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=en.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 en.set(r,a),pruneMapToMaxSize(en,$t),a}var $t,en,tn=__esmMin((()=>{Zt(),Qt(),$t=256,en=/* @__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 nn=__esmMin((()=>{tn()}));function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.prototype.toString.call(e)===`[object Object]`}var rn=__esmMin((()=>{}));function isBlockedObjectKey(e){return an.has(e)}var an,on=__esmMin((()=>{an=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`])}));function getSealedRuntimeJson5(){return sn?.json5}function getSealedRuntimeSecureTempRoot(){return sn?.resolveSecureTempRoot}var sn,cn=__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 ln=t,t}function loadJson5Parser(){if(ln)return ln;let e=getSealedRuntimeJson5();if(e!==void 0)return setJson5Runtime(e);if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`sealed JSON5 runtime was not registered before use`);return setJson5Runtime(t(import.meta.url)(`json5`))}function parseJsonWithJson5Fallback(e,t){try{return JSON.parse(e)}catch{return(t??loadJson5Parser()).parse(e)}}var ln,un=__esmMin((()=>{cn()}));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 dn=__esmMin((()=>{})),pn,mn=__esmMin((()=>{pn=`default`}));function parseEnvTemplateSecretRef(e,t=pn){if(typeof e!=`string`)return null;let n=e.trim(),r=hn.exec(n)??gn.exec(n);return r?{source:`env`,provider:t.trim()||`default`,id:expectDefined(r[1],`types.secrets regex capture 1`)}:null}var hn,gn,_n=__esmMin((()=>{Zt(),mn(),hn=/^\$\{([A-Z][A-Z0-9_]{0,127})\}$/,gn=/^\$([A-Z][A-Z0-9_]{0,127})$/}));function renderEnvTemplateToken(e){return e.defaultValue===void 0?`\${${e.name}}`:`\${${e.name}${yn}${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(yn),c=s===-1?a:a.slice(0,s),l=s===-1?void 0:a.slice(s+2);!vn.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(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 vn,yn,MissingEnvVarError,bn=__esmMin((()=>{rn(),dn(),_n(),vn=/^[A-Z_][A-Z0-9_]*$/,yn=`:-`,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`}}})),xn=__esmMin((()=>{}));function sanitizePlainObject(e){let t={};for(let[n,r]of Object.entries(e))isBlockedObjectKey(n)||(t[n]=isPlainObject(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(e)||!isPlainObject(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(s)?isPlainObject(t)?mergeDeep(t,s,n):sanitizePlainObject(s):r===`concat`&&Array.isArray(t)&&Array.isArray(s)?[...t,...s]:s}return a}var Sn=__esmMin((()=>{rn(),on()}));function isMissingPathError(e){return C(e,`ENOENT`)||C(e,`ENOTDIR`)||C(e,`not-found`)}var Cn=__esmMin((()=>{}));function normalizeWindowsPathPreservingCase(e){let t=n.win32.normalize(e);if(!t.startsWith(`\\\\?\\`))return t;let r=t.slice(4);return r.toUpperCase().startsWith(`UNC\\`)?`\\\\${r.slice(4)}`:r}var wn=__esmMin((()=>{}));function*walkForContainment(e,t){let r=n.isAbsolute(e)?e:`${process.cwd()}${n.sep}${e}`,i=n.parse(r).root,a=r.slice(i.length).split(n.sep===`\\`?/[\\/]/:`/`).filter(e=>e!==``&&e!==`.`);for(let e=a.length;e>=0;--e){let r=a.slice(e),s=i+a.slice(0,e).join(n.sep);if(r.includes(`..`))return{kind:`unresolved`,reason:`parent-after-missing`,prefix:s};let c=yield{op:`realpath`,path:s};if(c.ok)return{kind:`resolved`,path:n.join(c.value,...r)};if(!isMissingPathError(c.error))return{kind:`unresolved`,reason:C(c.error,`ELOOP`)?`link-loop`:`unreadable`,prefix:s};let l=yield{op:`readlink`,path:s};if(l.ok){if(t<=0)return{kind:`unresolved`,reason:`link-loop`,prefix:s};let e=yield*walkForContainment([n.isAbsolute(l.value)?l.value:`${n.dirname(s)}${n.sep}${l.value}`,...r].join(n.sep),t-1);return e.kind===`resolved`?{...e,danglingLink:e.danglingLink??s}:e}if((yield{op:`lstat`,path:s}).ok)return{kind:`unresolved`,reason:`unreadable`,prefix:s}}return{kind:`unresolved`,reason:`unreadable`,prefix:i}}function answerSync(e){try{return e.op===`lstat`?(u.lstatSync(e.path),{ok:!0,value:e.path}):{ok:!0,value:e.op===`realpath`?u.realpathSync.native(e.path):u.readlinkSync(e.path)}}catch(e){return{ok:!1,error:e}}}function canonicalizeForContainmentSync(e){let t=walkForContainment(e,Tn),n=t.next();for(;!n.done;)n=t.next(answerSync(n.value));return n.value}function realpathViaExistingPrefixSync(e){let t=canonicalizeForContainmentSync(e);return t.kind===`resolved`?t.path:void 0}function canonicalizeContainmentRootSync(e){let t=n.resolve(e);return realpathViaExistingPrefixSync(t)??t}var Tn,En=__esmMin((()=>{Cn(),wn(),Tn=32})),Dn=__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 n.resolve(t,`..`,`home`)}function resolveRawOsHomeDir(e,t){return normalizeHomeDirValue(e.HOME)??normalizeHomeDirValue(e.USERPROFILE)??resolveTermuxHome(e)??normalizeSafe(t)}function resolveOsHomeDir(e=process.env,t=me.homedir){let r=resolveRawOsHomeDir(e,t);return r?n.resolve(r):void 0}function resolveEffectiveHomeDir(e=process.env,t=me.homedir,r){let i=normalizeHomeDirValue(e.OPENCLAW_HOME);if(!i)return resolveOsHomeDir(e,t);if(i===`~`||i.startsWith(`~/`)||i.startsWith(`~\\`)){let a=resolveRawOsHomeDir(e,t);return a?n.resolve(i.replace(/^~(?=$|[\\/])/,()=>a)):r?.preserveUnresolvedTilde?n.resolve(i):void 0}return n.resolve(i)}var On=__esmMin((()=>{}));function matchAnsiOscAt(e,t){return Nn.lastIndex=t,Nn.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 kn,An,jn,Mn,Nn,Pn=__esmMin((()=>{kn=`(?:\\x1b\\]|\\x9d)`,An=`(?:\\x1b\\\\|\\x07|\\x9c)`,jn=`${kn}[^\\x07\\x1b\\x9c]*${An}`,Mn=`[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,Nn=new RegExp(jn,`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);In.lastIndex=i;let l=!s&&t.compatibilityGrammar?In.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 Fn,In,Ln=__esmMin((()=>{Pn(),Fn=`${kn}[\\s\\S]*?${An}`,In=RegExp(`${Fn}|${Mn}`,`y`),new Intl.Segmenter(void 0,{granularity:`grapheme`})}));function sanitizeTerminalText(e){return stripAnsi(e).replace(/[\p{Cc}\p{Bidi_Control}]/gu,e=>e===`\r`?`\\r`:e===`
`?`\\n`:e===` `?`\\t`:``)}var Rn=__esmMin((()=>{Ln()}));function resolveGlobalSingletonResetRegistry(){let e=globalThis,t=e[zn];if(t instanceof Map)return t;let n=/* @__PURE__ */ new Map;return e[zn]=n,n}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 resolveGlobalSet(e,t){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Set,e=>e.clear(),t)}var zn,j=__esmMin((()=>{zn=Symbol.for(`openclaw.globalSingletonLifecycleResets`)}));function tryProcessCwd(){try{return process.cwd()}catch{return}}var Bn=__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=me.homedir){let r=resolveEffectiveHomeDir(e,t)??tryProcessCwd();if(r)return n.resolve(r);throw Error(`Unable to resolve an OpenClaw home: set OPENCLAW_HOME, 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??me.homedir);return n?e.replace(/^~(?=$|[\\/])/,()=>n):e}function resolveAgainstUserBase(e){let t=getUserPathBaseDirectory().getStore();return t?n.resolve(t,e):n.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??me.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=me.homedir){return e?resolveHomeRelativePath(e,{env:t,homedir:n}):``}var Vn=__esmMin((()=>{On(),j(),Bn()}));function isValidProfileName(e){return Hn.test(e)}function normalizeProfileName(e){let t=e?.trim();return!t||normalizeLowercaseStringOrEmpty(t)==="default"||!isValidProfileName(t)?null:t}function resolveProfileStateDir(e,t,r){let i=e.trim();if(!isValidProfileName(i))throw Error(`Invalid profile name: ${JSON.stringify(e)}`);let a=normalizeLowercaseStringOrEmpty(i)==="default"?``:`-${i}`;return n.join(resolveRequiredHomeDir(t,r),`.openclaw${a}`)}var Hn,Un=__esmMin((()=>{yt(),Vn(),Hn=/^[a-z0-9][a-z0-9_-]{0,63}$/i})),LruCache,Wn=__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 n.join(e(),`.openclaw`)}function resolveStateDir(e=process.env,t=me.homedir){let r=e.OPENCLAW_STATE_DIR?.trim();if(r&&process.platform!==`win32`&&n.isAbsolute(r)){let e=Gn.peek(r);if(e!==void 0)return e;let t=n.resolve(r);return Gn.set(r,t),t}return r?resolveHomeRelativePath(r,{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 Gn,Kn=__esmMin((()=>{Un(),Vn(),Wn(),Gn=new LruCache(64)}));function resolveConfigDir(e=process.env,t=me.homedir){let r=e.OPENCLAW_STATE_DIR?.trim();if(r)return resolveUserPath(r,e,t);let i=e.OPENCLAW_CONFIG_PATH?.trim();return i?n.dirname(resolveUserPath(i,e,t)):resolveStateDir(e,t)}var qn=__esmMin((()=>{Kn(),Vn()})),Jn=__esmMin((()=>{wn()}));function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var Yn=__esmMin((()=>{}));function createAbortError(e,t){let n=Error(e,t);return n.name=`AbortError`,n}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 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?Xn:Number.isFinite(e)?e:0),0),Xn)}function resolveRetryConfig(e=Zn,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.random??Math.random,n=e.createFailure??(e=>toRetryError(e.at(-1)??/* @__PURE__ */ Error(`Retry failed`)));return async function(r,i=3,a=300){let s=[],c=typeof i==`number`,l=typeof i==`number`?{attempts:i}:i,u=resolveRetryConfig(Zn,l),d=u.attempts,f=u.minDelayMs,p=u.maxDelayMs>0?u.maxDelayMs:1/0,m=l.retryAfterMaxDelayMs===void 0?p:Math.max(f,resolveRetryDelayMs(clampNumber(l.retryAfterMaxDelayMs,p,0))),h=l.random??t,g=l.sleep??defaultSleep,_=l.shouldRetry??(()=>!0);for(let t=1;t<=d;t+=1)try{return await r()}catch(n){if(s.push(n),t>=d||e.shouldRetry?.(n)===!1||!_(n,t))break;if(c){await defaultSleep(resolveRetryDelayMs(a*2**(t-1)));continue}let r={attempt:t,maxAttempts:d,err:n,label:l.label},i=l.retryAfterMs?.(n),v=typeof i==`number`&&Number.isFinite(i),y=typeof l.delayMs==`function`?l.delayMs(r):l.delayMs,b=y===void 0?void 0:resolveRetryDelayMs(y),x=v?Math.max(i,f):b===void 0?f*2**(t-1):Math.max(b,f),S=v?m:p,ee=Math.min(x,S),te=v&&(i??0)<=S,ne=u.jitter===`full`&&!v||te;ee=applyJitter(ee,u.jitter,ne?`positive`:`symmetric`,h),ee=Math.min(Math.max(ee,f),S),await l.onRetry?.({...r,delayMs:ee}),ee>0&&await g(ee)}throw n(s)}}var Xn,Zn,defaultSleep,Qn=__esmMin((()=>{Xn=2147e6,Zn={attempts:3,minDelayMs:300,maxDelayMs:3e4,jitter:0},defaultSleep=async e=>{let t=e;do{let e=Math.min(t,Xn);await new Promise(t=>{setTimeout(t,e)}),t-=e}while(t>0)},createRetryRunner()})),$n=__esmMin((()=>{Qn()})),er=__esmMin((()=>{Gt(),Qn(),$n()})),tr=__esmMin((()=>{})),nr=__esmMin((()=>{Rn(),qn(),Jn(),rn(),er(),tr(),String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`,String.raw`[\s"'\x60)\]}>]`,String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`,resolveConfigDir()}));function isConfigContainer(e){return Array.isArray(e)||isPlainObject(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){return canonicalizeContainmentRootSync(e)}function createConfigIncludeBoundary(e,t=[]){let r=n.normalize(n.dirname(e));return{configRoot:{rootDir:r,rootRealDir:n.normalize(safeRealpath(r))},allowedRoots:t.filter(e=>typeof e==`string`&&e.length>0&&n.isAbsolute(e)).map(e=>{let t=n.normalize(e);return{rootDir:t,rootRealDir:n.normalize(safeRealpath(t))}})}}function readConfigIncludeFileWithGuards(e){let t=e.ioFs??u,r=e.maxBytes??ir;if(!te(t)){let r=t.readFileSync(e.resolvedPath,`utf-8`);try{e.onResolvedPath?.(n.normalize(t.realpathSync(e.resolvedPath)))}catch{}return r}let i=ne({absolutePath:e.resolvedPath,rootPath:e.rootRealDir,rootRealPath:e.rootRealDir,boundaryLabel:`config directory`,skipLexicalRootCheck:!0,rejectSymlinks:!1,maxBytes:r,ioFs:t});if(!i.ok)throw i.reason===`validation`?new ConfigIncludeError(`Include file failed security checks (regular file, max ${r} 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 r=t.readFileSync(i.fd,`utf-8`);return e.onResolvedPath?.(n.normalize(i.path)),r}finally{t.closeSync(i.fd)}}function resolveConfigIncludes(e,t,n=or,r={}){let i=createConfigIncludeBoundary(t,r.allowedRoots??[]);return new IncludeProcessor(t,n,i).process(e)}function resolveConfigIncludesForTopLevelKey(e,t,n,r=or,i={}){let a=createConfigIncludeBoundary(t,i.allowedRoots??[]);return new IncludeProcessor(t,r,a,/* @__PURE__ */ new Set([n])).process(e)}var rr,ir,ar,ConfigIncludeError,ConfigIncludeReadError,CircularIncludeError,IncludeProcessor,or,sr=__esmMin((()=>{Zt(),xn(),Sn(),Cn(),En(),Dn(),nr(),un(),rr=`$include`,ir=2097152,ar=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=[],r=this.traverseValue(e,null,!1,{basePath:this.basePath,visited:/* @__PURE__ */ new Set([n.normalize(this.basePath)]),depth:0}),i;for(;;){let e=r.next(i);if(e.done){let n=t.pop();if(!n)return e.value;i=e.value,r=n}else t.push(r),r=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(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[rr],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(u))throw new ConfigIncludeError(`Sibling keys require included content to be an object`,typeof i==`string`?i:rr);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>=ar)throw new ConfigIncludeError(`Include path exceeds maximum length (${ar} characters)`,e);let r=n.dirname(t.basePath),i=n.isAbsolute(e)?e:n.resolve(r,e),a=n.normalize(this.resolver.mapPath?.(i)??i);if(a.length>=ar)throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${ar} characters)`,e);let s=realpathViaExistingPrefixSync(a),c=this.findContainingRoot(a,`rootDir`)??(s?this.findContainingRoot(n.normalize(s),`rootRealDir`):null);if(!c)throw new ConfigIncludeError(`Include path escapes config directory: ${e} (root: ${this.rootDir})`,e);this.resolver.onLexicalPath?.(a);try{let t=u.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:c};throw new ConfigIncludeReadError(`Failed to resolve include file realpath: ${e} (resolved: ${a})`,e,t instanceof Error?t:void 0)}}findContainingRoot(e,t){if(oe(this.boundary.configRoot[t],e))return this.boundary.configRoot;for(let n of this.boundary.allowedRoots)if(oe(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)}}},or={readFile:e=>u.readFileSync(e,`utf-8`),readFileWithGuards:readConfigIncludeFileWithGuards,parseJson:parseJsonWithJson5Fallback}})),cr=__esmMin((()=>{Gt()}));function resolveIsNixMode(e=process.env){return e.OPENCLAW_NIX_MODE===`1`}function envHomedir(e){return()=>resolveRequiredHomeDir(e,me.homedir)}function resolveIncludeRoots(e=process.env,t=envHomedir(e)){let r=e.OPENCLAW_INCLUDE_ROOTS?.trim();if(!r)return[];let effectiveHomedir=()=>resolveRequiredHomeDir(e,t),i=/* @__PURE__ */ new Set,a=[];for(let t of r.split(n.delimiter)){let r=t.trim();if(!r)continue;let s=n.resolve(resolveHomeRelativePath(r,{env:e,homedir:effectiveHomedir}));i.has(s)||(i.add(s),a.push(s))}return a}function resolveConfigPathCandidate(e=process.env,t=envHomedir(e)){return resolveConfigPath(e,void 0,t)}function resolveConfigPath(e=process.env,t,r=envHomedir(e)){let i=e.OPENCLAW_CONFIG_PATH?.trim();return i?resolveUserPath(i,e,r):n.join(t??resolveStateDir(e,r),lr)}var lr,ur=__esmMin((()=>{Vn(),cr(),Kn(),resolveIsNixMode(),lr=`openclaw.json`,resolveStateDir(),resolveConfigPathCandidate()}));function createUnownedAppliedLoggingConfig(){return fr}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 dr,fr,pr,M,mr=__esmMin((()=>{dr=Symbol.for(`openclaw.loggingState`),fr=`unowned`,pr=globalThis,M=pr[dr]??createLoggingState(),pr[dr]=M}));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(M.appliedConfig!==`unowned`)return M.appliedConfig;let e=resolveLoggingConfigSelector();if(hr?.selector===e)return hr.logging;let t=resolveConfigPath();if(!u.existsSync(t)){hr={selector:e,logging:void 0};return}let n=parseJsonWithJson5Fallback(u.readFileSync(t,`utf8`)),r=resolveIncludeRoots(),i;try{i=resolveConfigIncludesForTopLevelKey(n,t,`logging`,void 0,{allowedRoots:r})}catch{let e=isRecord(n)?n.logging:void 0;if(e===void 0)return;try{i=resolveConfigIncludes({logging:e},t,void 0,{allowedRoots:r})}catch{return resolvePartialDiagnosticLoggingConfig(e)}}let a;try{a=resolveConfigEnvVars(i)}catch{return resolvePartialDiagnosticLoggingConfig(isRecord(i)?i.logging:void 0)}let s=isRecord(a)?a.logging:void 0,c=isRecord(s)?s:void 0;return hr={selector:e,logging:c},c}catch{return}}var hr,gr=__esmMin((()=>{k(),bn(),sr(),ur(),Bn(),un(),mr()}));function clampMessage(e){return e.length>_r?`${truncateUtf16Safe(e,_r)}...(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 _r,vr=__esmMin((()=>{k(),Xt(),_r=4096}));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(Sr.has(n))return t+2;if(n===`x`)return xr.test(e[t+2]??``)&&xr.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&&xr.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=!Sr.has(e[a+1]);else if(s===`[`){if(c=classAtomEnd(e,a),c<0)return e}else if(s===`{`){let t=yr.exec(e.slice(a)),s=t&&r>=0?t:br.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(Cr.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;Cr.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=wr.get(e);s||(s=new RegExp(e.source,`${e.flags.replace(`d`,``).replace(`g`,``)}dg`),wr.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(Cr.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:Tr.get(t);r||(r=new RegExp(t.source,`${t.flags}g`),Tr.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 Cr.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 yr,br,xr,Sr,escapeHexValue,isHighSurrogateEscape,isLowSurrogateEscape,Cr,wr,Tr,Er=__esmMin((()=>{yr=/^\{(\d+),\}/,br=/^\{(?:\d+(?:,\d*)?|,\d+)\}/,xr=/[0-9A-Fa-f]/,Sr=/* @__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||!xr.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},Cr=/* @__PURE__ */ new WeakMap,wr=/* @__PURE__ */ new WeakMap,Tr=/* @__PURE__ */ new WeakMap}));function replacePatternBounded(e,t,n){if(e.length<=Dr)return e.replace(t,n);let r;for(let i=0;i<e.length;i+=Or){let a=e.slice(i,i+Or),s=a.replace(t,n);r===void 0?s!==a&&(r=e.slice(0,i)+s):r+=s}return r??e}var Dr,Or,kr=__esmMin((()=>{Dr=32768,Or=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 Ar=__esmMin((()=>{Zt()}));function isPlainRedactableObject(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function serializeRedactionRecord(e,t){let n={value:{structured:!0,primitiveMask:!1},children:/* @__PURE__ */ new Map},r=[];return{json:JSON.stringify(e,function(e,i){for(;r.length>0&&r.at(-1)?.value!==this;)r.pop();let a=r.at(-1),s=Array.isArray(this),c=s&&a?a.key:e,l=s&&a?a.path:a?[...a.path,e]:[],u=i,d=(a?.structured??!0)&&(typeof u!=`object`||!u||Array.isArray(u)||isPlainRedactableObject(u)),f=d&&[`number`,`boolean`,`bigint`].includes(typeof u)&&t({key:c,path:l,objectPath:!s}),p=typeof i==`object`&&!!i&&r.some(e=>e.value===i),m=p?`[Circular]`:typeof i==`bigint`?String(i):i,h=typeof m==`object`&&!!m,g=n;return a&&a.structured&&(h||!d||f||p)?(g={value:{structured:d&&!p,primitiveMask:f},children:/* @__PURE__ */ new Map},a.origins.children.set(e,g)):a?g=a.origins:n.value={structured:d,primitiveMask:f},h&&r.push({value:m,path:l,key:c,origins:g,structured:d}),m}),origins:n}}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(jr)){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 jr,Mr=__esmMin((()=>{Zt(),jr=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\]]/g}));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,_=/* @__PURE__ */ new Set;for(let e of d)commitOriginalEdits(e,s(e))&&_.add(e);_.size>0&&(g=updateCurrentRecord(e,g,d,_));let v=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){let a=i.visitMatches??visitRedactMatches;if(!i.couldMatch||i.couldMatch(g))for(let c of i.patterns){if(s===0)for(h of v)a(h.currentValue,c,visitDecodedMatch);else a(g,c,n=>{let i=r(n,c);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),_=Math.min(i.end,n.currentEnd-a),v=r?_-n.currentStart:currentDecodedBoundary(e,n,_,p);if(h===void 0||v===void 0){for(;h===void 0;)h=currentDecodedBoundary(e,n,--m,p);for(;v===void 0;)v=currentDecodedBoundary(e,n,++_,p);let t=n===f&&l?projectedStringEnd(e,d,l,n,h,v):c.length;add(n,{start:h,end:t,replacement:`***`});continue}if(v<h||u&&v===h)continue;let{start:y,end:b}=i,x=i.redact({start:h,end:v,value:g.slice(Math.max(y,n.currentStart+a),Math.min(b,n.currentEnd-a))});if(!x)continue;let S=`***`;if(s)try{S=r?x.replacement:JSON.parse(`"${x.replacement}"`)}catch{}add(n,{...x,replacement:S})}}});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||_.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 Nr=__esmMin((()=>{Zt(),Ar(),Mr(),Er()}));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 Pr,Fr,Ir=__esmMin((()=>{Pr=String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----`,Fr={source:Pr,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:Pr,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 fi.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||pi.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);fi.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))))),mi.test(l))r===-1&&(r=c);else{if((!i||c>=i.end&&!i.queryOrFragment)&&l===`:`&&e.startsWith(`//`,c+1)&&r!==-1&&hi.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(_i)];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!==` `||!yi.test(e[i-2]??``)){r=!0;let s=i+a[0].length;if(!c){vi.lastIndex=s;let t=vi.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===`:`&&!bi.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(`^(?:${wi}|${Ti})$`,`i`),n=/* @__PURE__ */ new Set([Oi,Ai]),r=/* @__PURE__ */ new Set([Xr,Zr,Qr,$r]),i=new RegExp(String.raw`[:=](?<=(?:${Wr})\s*[:=])`),a=new RegExp(String.raw`[:=](?<=(?:${Wr})\s*[:=])\s*["'\x60]`),s=new RegExp(String.raw`[:=](?<=\.(?:${Wr})\s*[:=])`),c=new RegExp(String.raw`=(?<=(?:^|[\s,;({\["])(?:${Ur})=)`,`i`);return{bodySecretKeys:e,credentialHeaderField:t,formAware:n,shellReferencePreserving:r,prefilters:new Map([[Xr,e=>/KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD|CVC|CVV|SECURITY|PAYMENT/.test(e)],[Zr,e=>e.includes(`\\`)],[Qr,e=>/[=]["'`]/.test(e)],[$r,e=>c.test(e)],[ti,e=>/["'`]/.test(e)&&a.test(e)],[ni,e=>(e.includes(`:`)||e.includes(`=`))&&i.test(e)],[ri,e=>e.includes(`=`)],[ii,e=>/[-_](?:password|passphrase|pass|passwd)\s*[:=]/.test(e)],[ai,e=>s.test(e)],[ci,e=>/["']/.test(e)],[li,e=>/["']/.test(e)],...ji.slice(0,4).map(e=>[e,e=>/authorization/i.test(e)]),[Di,e=>/api-key|apikey|api-token|access-token/i.test(e)],[Oi,e=>/api-key|apikey|api-token|access-token/i.test(e)],[oi,e=>e.includes(`"`)],[si,e=>e.includes(`"`)],[ki,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)],[Ai,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)]]),chunkUnsafe:/* @__PURE__ */ new Set([Si,Ci,Mi,Ni,Pi,Fi,...ji,...Li.filter(e=>e.startsWith(ui))])}}var Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,base64SafeToken,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi=__esmMin((()=>{It(),Ir(),Lr=String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`,Rr=String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`,zr=String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`,Br=String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`,Vr=String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${Br}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`,Hr=String.raw`${Vr}|app[-_]?secret|credential|${Rr}`,Ur=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|${Rr}`,Wr=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|${Rr}`,Gr=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|${Rr}`,Kr=String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`,qr=String.raw`password|passphrase|pass|passwd`,Jr=String.raw`${Br}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${Rr}`,Yr=`\\p{C}\\u00A0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000\\u115F\\u1160\\u3164\\uFFA0`,Xr=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Lr})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`,Zr=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Lr})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`,Qr=String.raw`(^|[\s,;({\["])(?:${Ur})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`,$r=String.raw`(^|[\s,;({\["])(?:${Ur})=(["'\x60]?[^\s&#"'\x60<>]+)`,ei=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|${Rr}`,ti=String.raw`/(^|[\s,{])(?:(?:${ei})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${qr})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${Wr})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`,ni=String.raw`/(^|[\s,{])(?:(?:${Gr})\s*:\s*|(?:${Wr})(?:\s+=\s*|=\s+))([^\s#"'\x60<>]+)/g`,ri=String.raw`/(^|[\s,{])(?:${Kr})=([^\s#"'\x60<>]+)/g`,ii=String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${qr})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,ai=String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${Wr})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,oi=String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${Br}|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*"([^"]+)"`,si=String.raw`"(?:${zr})"\s*:\s*"([^"]+)"`,ci=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`,li=String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,ui=String.raw`(^|[^A-Za-z0-9])`,base64SafeToken=e=>String.raw`${ui}(?=${e})(?<!;base64,[A-Za-z0-9+/=]*)(${e})`,di=String.raw`(^|[^A-Za-z0-9_])`,fi=/(?=[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,pi=/\s/,mi=/[A-Za-z0-9+.-]/,hi=/[A-Za-z]/,gi=Object.freeze({source:`aws-secret-access-key`,exec:matchAwsSecretAccessKeys,couldMatch:couldMatchAwsSecretAccessKey}),_i=new RegExp(String.raw`(?<![A-Za-z0-9])(pass|${Gr})\s*:\s*`,`gi`),vi=/[^\s#"'\x60<>]+/y,yi=/[A-Za-z0-9]/,bi=/[ \t\r\n]/,xi=Object.freeze({source:`bare-pass-assignment`,exec:matchBarePassAssignments}),Si=String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`,Ci=String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`,wi=`x-goog-api-key|api-key|apikey|x-api-token|x-access-token`,Ti=`X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token`,Ei=String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`,Di=String.raw`${Ei}(?:${wi})${A}[ \t]*:${kt}${A}([^\s\\"',;]+)`,Oi=String.raw`${Ei}(?:${wi})${A}[ \t]*=${kt}${A}([^\s\\"',;]+)`,ki=String.raw`${Ei}(?:${Ti})\s*:\s*([^\s"',;]+)`,Ai=String.raw`${Ei}(?:${Ti})\s*=\s*([^\s"',;]+)`,ji=[String.raw`${Mt}Proxy-Authorization${A}[ \t]*[:=]${kt}${A}${Tt}${At}(${Et})`,String.raw`${Mt}Proxy-Authorization${A}[ \t]*[:=]${kt}${A}(${Et})[ \t]*(?=${A}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,String.raw`${Mt}Authorization${A}[ \t]*[:=]${kt}${A}(?!(?:Bearer|Basic|Bot)(?=${At}))${Tt}${At}(${Et})`,String.raw`${Mt}Authorization${A}[ \t]*[:=]${kt}${A}(?!(?:Bearer|Basic|Bot)(?=${At}))(${Et})[ \t]*(?=${A}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,Di,Oi],Mi=String.raw`Authorization${A}[ \t]*[:=]${jt}${A}Bearer${At}(${Et})`,Ni=String.raw`Authorization${A}[ \t]*[:=]${jt}${A}Basic${At}(${Et})`,Pi=String.raw`Authorization${A}[ \t]*[:=]${jt}${A}Bot${At}(${Et})`,Fi=String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`,Ii=[Xr,Zr,oi,si,ci,li,String.raw`--(?:${Jr})=([^\s"']+)`,String.raw`--(?:${Jr})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,Mi,Ni,Pi,...ji,ki,Ai,Fi,String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,String.raw`(^|[\s,;])(?:${Hr})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,Qr,$r,ti,ni,xi,ri,ii,ai,Pr,String.raw`(^|[\s,{])["']?(?:${Br})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`],Li=[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`${di}(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`${di}(fw-[A-Za-z0-9]{30,})`,String.raw`${di}(fw_[A-Za-z0-9]{30,})`,String.raw`${di}(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,})`,Si,Ci],Ri=[...Ii,...Li,gi]}));function isJsWhitespaceAt(e,t){if(t>=e.length)return!1;let n=e.charCodeAt(t);return Bi.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=Vi.get(t);n||(n=[],Vi.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=Hi(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 Bi,Vi,GAAAA_VALUE_CHAR,ATBB_VALUE_CHAR,AT_VALUE_CHAR,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,JWT_SEGMENT_CHAR,Zi,Qi,$i,ea,ta,na,ra,ia,aa,FORM_FIRST_PAIR_KEY_CHAR,FORM_FIRST_PAIR_TAIL_CHAR,oa,sa,ca,la,ua,da,fa=__esmMin((()=>{zi(),Bi=/* @__PURE__ */ new Set([9,10,11,12,13,32,160,5760,8232,8233,8239,8287,12288,65279]),Vi=/* @__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===`_`,Hi=fixedTailTokenEnd(4,32,isHexChar),Ui=makeBase64SafeTokenMatcher(`vendor-token gAAAA (linear)`,`gAAAA`,()=>(e,t)=>{let n=runEndOf(e,t+5,GAAAA_VALUE_CHAR);return n-(t+5)>=20?n:null}),Wi=makeBase64SafeTokenMatcher(`vendor-token ATBB (linear)`,`ATBB`,()=>(e,t)=>{let n=runEndOf(e,t+4,ATBB_VALUE_CHAR);return n-(t+4)>=16?n:null}),Gi=makeBase64SafeTokenMatcher(`vendor-token AKIA (linear)`,`AKIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),Ki=makeBase64SafeTokenMatcher(`vendor-token ASIA (linear)`,`ASIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),qi=makeBase64SafeTokenMatcher(`vendor-token dapi (linear)`,`dapi`,()=>dapiTokenEnd),Ji=makeAtEqualsTokenMatcher(`vendor-token ATCTT3xFfG (linear)`,`ATCTT3xFfG`),Yi=makeAtEqualsTokenMatcher(`vendor-token ATATT (linear)`,`ATATT`),Xi=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===`-`,Zi=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}}}),Qi=String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,$i=String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,ea=/* @__PURE__ */ new Set([`http`,`https`,`ws`,`wss`,`ftp`]),ta=/* @__PURE__ */ new Set([`postgres`,`postgresql`,`mysql`,`mongodb`,`mongodb+srv`,`redis`,`rediss`,`amqp`,`amqps`]),na=makeUserInfoMatcher(`url-userinfo (linear)`,ea,e=>e===`/`||e===`@`||isJsWhitespaceChar(e)),ra=makeUserInfoMatcher(`connection-string (linear)`,ta,e=>e===`@`||isJsWhitespaceChar(e)),ia=String.raw`(^|[\s,;])(?:${Hr})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,aa=RegExp(`^(?:${Hr})$`,`i`),FORM_FIRST_PAIR_KEY_CHAR=e=>isAlnumChar(e)||e===`-`||e===`_`,FORM_FIRST_PAIR_TAIL_CHAR=e=>isAlnumChar(e)||e===`_`||e===`.`||e===`-`,oa=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&&aa.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)}}}),sa=String.raw`(^|[\s,;({\["])(?:${Ur})=(["'\x60])`,ca=String.raw`(^|[\s,{])(?:(?:${ei})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${qr})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${Wr})\s*[:=]\s*)(["'\x60])`,la=makeQuotedAssignmentMatcher(`standalone-quoted-assignment (linear)`,sa,`gi`),ua=makeQuotedAssignmentMatcher(`config-quoted-assignment (linear)`,ca,`g`),da=/* @__PURE__ */ new Map([[base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),Ui],[base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Ji],[base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Yi],[base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),Wi],[base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),qi],[base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),Gi],[base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),Ki],[Xi,Zi],[Qi,na],[$i,ra],[ia,oa],[Qr,la],[ti,ua]])}));function maskToken(e){return e.length<pa?`***`:`${sliceUtf16Safe(e,0,ma)}…${sliceUtf16Safe(e,-4)}`}function splitSecretValueForMask(e){let t=e[0]??``,n=+!!_a.has(t);if(n){let n=e.lastIndexOf(t);if(n>0){let t=e.slice(n+1);if(ga.test(t))return{maskable:e.slice(1,n),suffix:t,maskStart:0,maskEnd:n+1}}}let r=e.slice(n),i=r.match(ha)?.[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 pa,ma,ha,ga,_a,va=__esmMin((()=>{Xt(),pa=18,ma=6,ha=/(["'`,;)}\]]+)$/u,ga=/^["'`,;)}\]]*$/u,_a=/* @__PURE__ */ new Set([`"`,`'`,"`"])}));function startRedactionMeasurement(e){if(!ya.hasSubscribers)return;let t=ve.now(),n=process.threadCpuUsage();return(r,i,a)=>{let s=ve.now()-t,c=process.threadCpuUsage(n);ya.publish({operation:e,outcome:r,pid:process.pid,threadId:E,isMainThread:T,elapsedMs:s,threadCpuMs:(c.user+c.system)/1e3,...i===void 0?{}:{inputChars:i},...a===void 0?{}:{patternCount:a}})}}var ya,ba=__esmMin((()=>{ya=_e(`openclaw.redaction`)}));function couldMatchDefaultRedactPatterns(e){return xa.test(e)||(e.includes(`-`)||e.includes(`_`))&&Sa.test(e)||Ca.test(e)||e.includes(`://`)&&e.includes(`@`)||e.includes(`=`)&&wa.test(e)||gi.couldMatch(e)}function couldMatchDefaultFullContextPatterns(e){return couldMatchDefaultRedactPatterns(e)||Ta.test(e)}function couldMatchVendorRedactPatterns(e){return(e.includes(`-`)||e.includes(`_`))&&Sa.test(e)||Ca.test(e)||Ta.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 xa,Sa,Ca,wa,Ta,Ea=__esmMin((()=>{zi(),xa=/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,Sa=/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,Ca=/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,wa=RegExp(`[${Yr}+%]`,`u`),Ta=/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 Da=__esmMin((()=>{}));function invalidateMatcher(){Oa.revision+=1,Oa.registeredValueRedactor=void 0}function redactRegisteredSecretValues(e,t){return!e||Oa.registeredValues.size===0?e:(Oa.registeredValueRedactor??=createSecretValueRedactor([...Oa.registeredValues.keys()]),Oa.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,6));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(){Oa.registeredValues.clear(),invalidateMatcher()}var Oa,ka=__esmMin((()=>{Da(),j(),Yn(),Oa=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 Aa.has(e)?`hostname_mismatch`:ja.has(e)?`certificate_invalid`:null}function classifyMessage(e){return Ma.some(t=>t.test(e))?`hostname_mismatch`:Na.some(t=>t.test(e))?`certificate_invalid`:null}function inspectTlsCertificateErrorInternal(e,t,n){if(n>Pa)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 Aa,ja,Ma,Na,Pa,Fa=__esmMin((()=>{Aa=/* @__PURE__ */ new Set([`ERR_TLS_CERT_ALTNAME_INVALID`,`HOSTNAME_MISMATCH`]),ja=/* @__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(`.`)),Ma=[/hostname\/ip does not match certificate(?:'s)? altnames/i,/hostname mismatch/i,/host: .+ is not in the cert(?:ificate)?(?:'s)? altnames/i],Na=[/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],Pa=8}));function isKnownTransportErrorCode(e){return Ra.some(({code:t})=>t.exec(e)?.[0]===e)||inspectTlsCertificateError({code:e})?.code===e}var Ia,La,Ra,za=__esmMin((()=>{Fa(),Ia=/(?:\s*:\s*|\s+)/,RegExp(`^(?:http\\s*)?(\\d{3})${Ia.source}(.+)$`,`i`),RegExp(`^(?:http\\s*)?(\\d{3})(?:${Ia.source}([\\s\\S]+))?$`,`i`),La="Couldn't connect to the AI service. Check your connection, then try again. For details, open Settings → Logs in the OpenClaw app or run `openclaw logs --follow`.",Ra=[{code:/\beconnrefused\b/i,phrases:/connection refused|actively refused/i,message:La},{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 OpenClaw app 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:La}]}));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 Ba=__esmMin((()=>{za()}));function parsePattern(e){if(e===Pr)return Fr;if(typeof e!=`string`&&!(e instanceof RegExp))return typeof e==`object`&&e&&typeof e.exec==`function`?e:null;let t=typeof e==`string`?da.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=Ja.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`&&Ha.shellReferencePreserving.has(e)&&Ua.add(t),t&&typeof e==`string`&&Ha.formAware.has(e)&&Ya.add(t),t&&typeof e==`string`&&(e.startsWith(di)||Ha.chunkUnsafe.has(e))&&qa.add(t),t&&typeof e==`string`){if(Ja.has(e)&&Wa.add(t),n&&Ka.has(e)&&!Ga.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;Ga.set(t,()=>t.source===e&&t.exec===n&&(!(t instanceof RegExp)||t.flags===r&&t[Symbol.replace]===i))}let r=Ha.prefilters.get(e);n&&r&&setRedactPatternPrefilter(t,r)}return t}function resolvePatterns(e){if(usesBuiltInRedactPatterns(e))return Xa??=Ri.map(parsePattern).filter(e=>!!e),Xa;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(!Za){Za=!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(gi),[...t]}function usesBuiltInRedactPatterns(e){return e===void 0||e===Ri||Array.isArray(e)&&e.length===0}function normalizeSensitiveKeyName(e){let t=e.replace($a,``);try{return decodeURIComponent(t).replace($a,``).toLowerCase().replaceAll(`-`,`_`)}catch{return t.toLowerCase().replaceAll(`-`,`_`)}}function isSensitiveBodyKey(e){return isSensitiveUrlQueryParamName(e)||Ha.bodySecretKeys.has(normalizeSensitiveKeyName(e))}function hasEncodedOrInvisibleFormKey(e){return eo.test(e)||e.replace(Qa,``)!==e}function visitSensitiveAssignments(e,t,n){if(!e||t===`url`&&!e.includes(`?`)||t===`encoded`&&!e.includes(`%`)&&e.replace(Qa,``)===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`?lo:t===`encoded`?so:co,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(ao.test(n))return redactAssignmentValues(n,`form`,t);let r=[],i=n.replace(oo,(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(uo.test(e)){let n=0;return e.split(uo).map(e=>{let r=fo.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,sourceOffset:i=0,replacement:a},s){if(e.includes(`PRIVATE KEY-----`))return{start:i+r,end:i+r+e.length,value:e,redact:e=>({start:e.start,end:e.end,value:e.value,replacement:a??redactPemBlock(e.value,`…redacted…`)})};let c=selectSecretCapture(e,t);if(c.value===`***`)return;let l=c.value===e?0:getSecretCaptureStart(s,n,e,r,c);if(l<0)return;let u=i+r+l;return{start:u,end:u+c.value.length,value:c.value,redact:t=>{let n=t.value,r=Ya.has(s)?splitFormAwareCredentialValue(n):{secret:n,suffix:``};if(splitSecretValueForMask(r.secret).maskable===`***`)return;let i=Ua.has(s);if(i&&(shouldPreserveShellReferenceMatch(e,n)||isEmptyShellParameterExpansionTail(n)))return;let c=a??(i?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 usesBoundedScan(e){return e instanceof RegExp&&!Wa.has(e)&&!qa.has(e)}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)Ga.get(a)?.()&&(s!==r&&(s=r,c=couldMatchVendorRedactPatterns(r)),!c)?a instanceof RegExp&&(a.lastIndex=0):r=!n?.fullContext&&usesBoundedScan(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=>!_o.has(e.toLowerCase()))}function redactAppSpecificPasswords(e){return e.includes(`-`)?e.replace(go,(e,t)=>looksLikeAppSpecificPassword(t)?maskToken(t):e):e}function resolveConfigRedaction(){let e=readLoggingConfig();return{mode:Va,patterns:e?.redactPatterns}}function resolveRedactOptions(e){let t=e??resolveConfigRedaction(),n=t.mode===`off`?`off`:Va;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,...Ri]:t}}function redactToolPayloadText(e){return redactToolPayloadTextWithConfig(e,readLoggingConfig())}function redactToolPayloadTextWithConfig(e,t){return redactSensitiveText(e,resolveToolPayloadRedaction(t))}function isSensitiveFieldKey(e){return po.test(e)||vo.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||ho.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 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`&&mo.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`:Ha.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||ho.test(n))for(let e of t.matchAll(go))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(),{json:a,origins:s}=serializeRedactionRecord(e,({key:e,path:t,objectPath:n})=>classifyLogFieldProtection(e,t,n,void 0)===`legacy`);i=a.length;let c=createRedactPrefilter(couldMatchDefaultFullContextPatterns),l=JSON.parse(redactJsonRecord(a,s,[[{patterns:n.patterns}],[{patterns:yo},{patterns:n.patterns,...n.patterns===Xa?{couldMatch:c}:{}}]],prepareRedactionCapture,t?getLegacyFieldRecordEdits:()=>[],e=>getFieldRecordEdits(e,n.mode),e=>getTextRecordEdits(e,n.mode,t!==void 0),(e,t)=>e.path.length===1&&bo.has(e.key)||n.patterns===Xa&&!c(t),t?.message));return r=`ok`,l}finally{n?.(r,i)}}var Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za,Qa,$a,eo,to,no,ro,io,ao,oo,so,co,lo,uo,fo,po,mo,ho,go,_o,vo,yo,bo,xo=__esmMin((()=>{wt(),It(),nn(),gr(),kr(),Ar(),Mr(),Nr(),fa(),va(),Er(),zi(),Ir(),ba(),Ea(),ka(),Ba(),Va=`tools`,Ha=createBackendRedactPatterns(),Ua=/* @__PURE__ */ new WeakSet,Wa=/* @__PURE__ */ new WeakSet,Ga=/* @__PURE__ */ new WeakMap,Ka=new Set(Li),qa=/* @__PURE__ */ new WeakSet,Ja=new Set(Ri.filter(e=>typeof e==`string`)),Ya=/* @__PURE__ */ new WeakSet,Za=!1,Qa=new RegExp(String.raw`[${Yr}+]`,`gu`),$a=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,eo=/%[0-9A-Fa-f]{2}/u,to=String.raw`[${Yr}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${Yr}+])*`,no=`[^&\\s<>]*`,ro=`[^&#\\s<>]*`,io=String.raw`${to}=${no}`,ao=new RegExp(String.raw`^${io}(?:&${io})+$`,`u`),oo=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`])(${io}(?:&${io})+)`,`gu`),so=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`&])(${to})=(${no})`,`gu`),co=new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${to})=(${no})(["'\x60]?)`,`giu`),lo=new RegExp(String.raw`([?&])(${to})=(${ro})`,`gu`),uo=/(\r\n|\r|\n)/u,fo=/^(?:\r\n|\r|\n)$/u,po=new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${Br}|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|${Rr}|${zr})$`,`i`),mo=/^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u,ho=/^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i,go=/\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g,_o=/* @__PURE__ */ new Set([`case`,`claw`,`demo`,`file`,`main`,`name`,`open`,`path`,`slug`,`test`]),vo=new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Lr})$`,`i`),yo=[{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)}}],bo=/* @__PURE__ */ new Set([`time`,`level`])}));function formatErrorMessage(e){return formatErrorMessage$1(e,{redact:redactSensitiveText})}var So=__esmMin((()=>{O(),xo(),Cn()}));function realpathExistingAncestorSync(e){let t=[],r=e;for(;;)try{return n.join(u.realpathSync.native(r),...t.toReversed())}catch{let e=n.dirname(r);if(e===r)return;t.push(n.basename(r)),r=e}}async function realpathExistingAncestor(e){let t=[],r=e;for(;;)try{return n.join(await w.realpath(r),...t.toReversed())}catch{let e=n.dirname(r);if(e===r)return;t.push(n.basename(r)),r=e}}function resolveIdentityPathViaExistingAncestorSync(e){let t=n.resolve(e);return realpathExistingAncestorSync(t)??t}async function resolveIdentityPathViaExistingAncestor(e){let t=n.resolve(e);return await realpathExistingAncestor(t)??t}function canAccessSync(e,t){try{return u.accessSync(e,t),!0}catch{return!1}}var Co=__esmMin((()=>{Cn()}));Yn(),So(),Co();function walkUpFrom(e,t,r){let i=n.resolve(e);for(let e=0;t.maxDepth===void 0||e<t.maxDepth;e+=1){let e=r(i);if(e!=null)return e;let t=n.dirname(i);if(t===i)break;i=t}return null}function readGitMetadataFile(e,t=1048576){let n=u.openSync(e,u.constants.O_RDONLY|(u.constants.O_NONBLOCK??0));try{let e=u.fstatSync(n);if(!e.isFile()||e.size>t)throw Error(`Git metadata is not a bounded regular file`);let r=re(n,Math.min(e.size,t));if(r.length!==e.size)throw Error(`Git metadata changed during its read`);return r}finally{u.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let r=readGitMetadataFile(e),i=r.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!Ae(r)||!i.startsWith(t)||i.length===t.length||i.includes(`\0`))throw Error(`Git directory pointer is incomplete or malformed`);let a=i.slice(t.length);return n.isAbsolute(a)?a:`${n.dirname(e)}${n.sep}${a}`}function readGitDirectoryPointer(e,t=``){return u.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=n.join(e,`.git`);try{let e=u.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?n.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){let n=u.openSync(e,u.constants.O_RDONLY|(u.constants.O_NONBLOCK??0));try{if(!u.fstatSync(n).isFile())throw Error(`Git metadata is not a regular file`);let e=Buffer.alloc(t),r=ie(n,e,0);return e.subarray(0,r).toString(`utf-8`)}finally{u.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=n.dirname(e),r=n.join(t,`commondir`);try{return readGitDirectoryPointer(r)}catch(e){if(!isMissingPathError(e)||u.lstatSync(r,{throwIfNoEntry:!1}))throw e}return t}function readGitRefs(e,t){let r=new Map(t.map(e=>[e,null])),i=/* @__PURE__ */ new Set;for(let n of t){let t=resolveRefPath(e,n);if(t)try{r.set(n,readGitMetadataPrefix(t).trim())}catch(e){if(!isMissingPathError(e))throw e;i.add(n)}}if(i.size===0)return r;try{let t=readGitMetadataFile(n.join(e,`packed-refs`),2**53-1).toString(`utf8`),a=RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...i].map(escapeRegExp).join(`|`)})(?=\\s|$)`,`gm`);for(let[,e,n]of t.matchAll(a))i.delete(n)&&r.set(n,e)}catch(e){if(!isMissingPathError(e))throw e}return r}function resolveRefPath(e,t){if(!t.startsWith(`refs/`)||t.split(/[/]/).includes(`..`))return null;let r=n.resolve(e,t),i=n.relative(e,r);return!i||i.startsWith(`..`)||n.isAbsolute(i)?null:r}function throwIfSettledRejected(e,t){throwCollectedErrors(e.flatMap(e=>e.status===`rejected`?[e.reason]:[]),t)}function throwCollectedErrors(e,t){if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,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 wo=__esmMin((()=>{O()}));function runInDetachedAsyncContext(e){return Eo?Eo.runInAsyncScope(e):e()}var To,Eo,Do=__esmMin((()=>{j(),To=typeof process>`u`?void 0:process.getBuiltinModule?.(`node:async_hooks`),Eo=To?resolveGlobalSingleton(Symbol.for(`openclaw.detachedAsyncContext`),()=>new To.AsyncResource(`openclaw.detached-async-context`)):void 0}));function enterAsyncStore(e,t){return this.enterWith(e),t()}function runWithAsyncStore(e,t,n){return e.getStore()===t?n():new je(`OpenClawAsyncStore`).runInAsyncScope(enterAsyncStore,e,t,n)}var Oo=__esmMin((()=>{}));function createDeferredCore(){return ko.withResolvers()}var ko,Ao=__esmMin((()=>{ko=Promise})),jo=__esmMin((()=>{Qn()}));function runOutsideAsyncWorkScope(e){return Mo.getStore()===void 0?No.getStore()===void 0?e():No.exit(e):runWithAsyncStore(Mo,void 0,()=>(No.enterWith(void 0),e()))}var Mo,No,Po,Fo,Io=__esmMin((()=>{wo(),Do(),Oo(),Ao(),j(),jo(),Mo=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScope`),()=>new D),No=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new D),Po=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}}),Fo=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=Mo.getStore();if(t===this)return e();let n=No.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return runWithAsyncStore(Mo,this,()=>(No.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new Po;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 Po);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 Lo=__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 Ro=__esmMin((()=>{})),zo,Bo=__esmMin((()=>{j(),resolveGlobalSingleton(Symbol.for(`openclaw.pluginSourceAcquisitionFailures`),()=>/* @__PURE__ */ new WeakSet),resolveGlobalSingleton(Symbol.for(`openclaw.pluginSourcePreparationOperations`),()=>/* @__PURE__ */ new WeakSet),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`}}),zo=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 createPluginExecutionFrame(e,t){return t?t.withScopes(e):new Vo(e)}var Vo,Ho,Uo,Wo=__esmMin((()=>{Oo(),j(),Bo(),Vo=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(){}get canUseInteractiveStateReadCapacity(){return!1}withScopes(e){return new InvocationFrame(e)}},Ho=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new D;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)}}}),Ho.invocation,Uo=Ho.getFrame,Ho.runFrame}));function releasePluginCacheInstance(e,t){let n=qo.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&&qo.delete(e)}function getPluginCacheRetainers(e){let t=Ko.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:createDeferredCore()},Ko.set(e,t)),t}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:!1,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},autoEnable:/* @__PURE__ */ new WeakMap,snapshots:/* @__PURE__ */ new Map,derivedIndexes:/* @__PURE__ */ new WeakMap,preparedManifests:/* @__PURE__ */ new WeakMap,snapshotManifestFacts:/* @__PURE__ */ new WeakMap,discovery:/* @__PURE__ */ new Map,sharedDiscovery:/* @__PURE__ */ new Map,projections:/* @__PURE__ */ new WeakMap,projectionSources:/* @__PURE__ */ new WeakMap,completions:/* @__PURE__ */ new WeakMap,indexFacts:/* @__PURE__ */ new WeakMap,providerPolicyOwners:/* @__PURE__ */ new WeakMap,channelAdapters:/* @__PURE__ */ new WeakMap,bundledChannelCatalogs:/* @__PURE__ */ new Map,bundledProviderPolicySurfaces:/* @__PURE__ */ new WeakMap,staticCatalogStates:/* @__PURE__ */ new WeakMap,modelSuppressionResolvers:/* @__PURE__ */ new WeakMap,mcpAuthDeclarations:/* @__PURE__ */ new WeakMap}}function createPluginCache(e={}){return{async[Symbol.asyncDispose](){await retirePluginCache(this)},kind:e.kind??`operation`,roots:/* @__PURE__ */ new Map,rootAliases:/* @__PURE__ */ new Map,sdk:createPluginCacheSdk(),setupModules:/* @__PURE__ */ new Map,instances:/* @__PURE__ */ new Set,metadata:createPluginMetadataCache(),installRecords:/* @__PURE__ */ new Map,persistedInstalledIndex:/* @__PURE__ */ new Map,preparedBundledDiscoveryModes:/* @__PURE__ */ new Map,dependencyStatus:/* @__PURE__ */ new WeakMap,moduleLoaders:/* @__PURE__ */ new Map,sources:/* @__PURE__ */ new Map,sourceAliases:/* @__PURE__ */ new Map,runtimeRecordRoots:/* @__PURE__ */ new WeakMap}}function getProcessPluginCache(){return Go.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return Uo()?.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 Fo;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 zo?[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 Go,Ko,qo,Jo=__esmMin((()=>{wo(),Io(),Ao(),j(),Lo(),Ro(),Bo(),Wo(),Go=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),Ko=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),qo=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap)})),Yo=__esmMin((()=>{}));function createRuntimeProcessEntrypoints(e){let runtimeProcessEntrypoint=(t,n=t,r=`.js`,i)=>({currentModuleUrl:e,sourceModulePath:`src/${t}${i??`.ts`}`,sourceExtension:i,sourceWorkerName:t.startsWith(`infra/`)?t.slice(6):`../${t}`,distWorkerPath:`${n}${r}`}),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`),doctorDatabaseBloat:runtimeProcessEntrypoint(`commands/doctor-db-bloat.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`),stallObserver:runtimeProcessEntrypoint(`logging/diagnostic-stall-observer.worker`),fileLog:runtimeProcessEntrypoint(`logging/logger-file.worker`),systemCaWarmup:runtimeProcessEntrypoint(`gateway/system-ca-warmup.worker`),openclawIdTunnel:runtimeProcessEntrypoint(`gateway/openclaw-id/tunnel-child/entry`),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`),execRealpath:runtimeProcessEntrypoint(`infra/exec-realpath.worker`),sharedStateStore:runtimeProcessEntrypoint(`state/openclaw-state.worker`),clientCredentials:runtimeProcessEntrypoint(`infra/client-credential.worker`),secretFileRead:runtimeProcessEntrypoint(`infra/secret-file-read.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`),updateConfigProjection:runtimeProcessEntrypoint(`infra/update-config-projection.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`),sessionTranscriptActiveFactsBackfill:runtimeProcessEntrypoint(`config/sessions/session-transcript-active-facts-backfill.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 Xo,Zo,Qo,$o=__esmMin((()=>{Xo={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:{...pluginRuntimeProcess(`file-transfer`,`src/node-host/dir-fetch-archive`,`src/node-host/dir-fetch-archive.worker`),sourceWorkerName:`dir-fetch-archive.worker`},fileTransferDirList:{...pluginRuntimeProcess(`file-transfer`,`src/node-host/dir-list-worker-command`,`src/node-host/dir-list.worker`),sourceWorkerName:`dir-list.worker`},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`)},Zo={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`],[`fileLog`,`file-log.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:[[`serviceChildRelay`,`service-child-relay`],[`serviceChildGroupAnchor`,`service-child-group-anchor`]]}},Qo={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`}}}));function parsePackageName(e){let t=JSON.parse(e);return typeof t.name==`string`?t.name:null}async function readPackageName(e,t){t?.throwIfAborted();let r=getPluginCache().sdk.packageNames,i=n.join(n.resolve(e),`package.json`);if(r.has(i))return r.get(i)??null;try{let e=parsePackageName(await pe.readFile(i,{encoding:`utf-8`,signal:t}));return t?.throwIfAborted(),r.set(i,e),e}catch{return t?.throwIfAborted(),r.set(i,null),null}}function readPackageNameSync(e){let t=getPluginCache().sdk.packageNames,r=n.join(n.resolve(e),`package.json`);if(t.has(r))return t.get(r)??null;try{let e=parsePackageName(y.readFileSync(r,`utf-8`));return t.set(r,e),e}catch{return t.set(r,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=n.resolve(e);for(let e=0;e<12&&(yield t,n.basename(t)!==`node_modules`);e+=1){let e=n.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,r=n.resolve(e),i=t.get(r);if(i)return[...i];let a=r,s=[];try{let e=y.realpathSync(a);e!==a&&s.push(n.dirname(e))}catch{}s.push(n.dirname(a));let c=a.split(n.sep),l=c.lastIndexOf(`.bin`);if(l>0&&c[l-1]===`node_modules`){let e=n.basename(a),t=c.slice(0,l).join(n.sep);s.push(n.join(t,e))}let u=dedupeCandidates(s);return t.set(r,u),[...u]}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(n.dirname(c(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=>n.resolve(e)))]}var es=__esmMin((()=>{Jo(),Yo(),$o()}));k(),yt(),So(),Wn(),es();const formatCommit=e=>{let t=e?.match(/[0-9a-fA-F]{7,40}/);return t?normalizeLowercaseStringOrEmpty(t[0].slice(0,7)):null},ts=new LruCache(256),resolveCommitSearchDir=e=>{if(e.cwd)return n.resolve(e.cwd);if(e.moduleUrl)try{return n.dirname(c(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(ts.set(e,t),t),resolveGitLookupDepth=(e,t)=>{if(!t)return;let r=n.relative(t,e);if(!(r.startsWith(`..`)||n.isAbsolute(r)))return(r?r.split(n.sep).filter(Boolean).length:0)+1},readCommitFromGit=(e,t)=>{let n=readGitHead(e,{maxDepth:resolveGitLookupDepth(e,t)});return n===void 0?void 0:formatCommit(n.value)},readCommitFromPackageJson=()=>{try{let e=t(import.meta.url)(`../../package.json`);return formatCommit(e.gitHead??e.githead??null)}catch{return null}},readCommitProbe=(e,t,n)=>{try{for(let r of t){let t=c(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=ts.get(i);if(a!==void 0)return a;let s=resolveOpenClawPackageRootSync({cwd:e.cwd,moduleUrl:e.moduleUrl});try{let e=readCommitFromGit(i,s);if(e!==void 0)return cacheGitCommit(i,e)}catch{}let c=readCommitFromBuildInfo();if(c)return cacheGitCommit(i,c);let l=readCommitFromPackageJson();return l?cacheGitCommit(i,l):cacheGitCommit(i,null)};function resolveLoadedCommitHash(e={}){let t=e.moduleUrl??import.meta.url,n=readLoadedCommit(t);return n===void 0?resolveCommitHash({moduleUrl:t,...e.env?{env:e.env}:{}}):n}yt();const ns=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],rs=[`../build-info.json`,`../../build-info.json`,`./build-info.json`];function readStringFromJsonCandidates(e,n,r,i=!1){try{let a=t(e);for(let e of n)try{let t=a(e),n=normalizeOptionalString(t[r]);if(!n||i&&t.name!==`openclaw`)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,ns,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,rs,`version`)}function readBuildProvenanceForModuleUrl(e){try{let n=t(e);for(let e of rs)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`}readBuildProvenanceForModuleUrl(import.meta.url);const is=resolveLoadedCommitHash({moduleUrl:import.meta.url});function resolveRuntimeServiceCommit(){return is}const as=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION});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 os=__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 ss=__esmMin((()=>{}));function isPostgresSqlConnection(e){return cs in e&&e[cs]===!0}function sqlPublicationAnchor(e){return isPostgresSqlConnection(e)?e.anchor:e}var cs,ls=__esmMin((()=>{cs=Symbol.for(`openclaw.postgres-sync-connection`)}));j(),os(),ls();const{kyselyByDatabase:us,queryErrorHandlerByDatabase:ds}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap})),fs=Symbol.for(`openclaw.kyselySyncStatementCache`),ps=Symbol.for(`openclaw.kyselySyncStatementInvalidation`),ms=Symbol.for(`openclaw.kyselySyncStatementCacheEnabled`),hs=Symbol.for(`openclaw.kyselySyncAuthorizerActive`),gs=Symbol.for(`openclaw.sqliteDisposeCallbacks`),_s=Symbol.for(`openclaw.sqliteDisposeGuards`),vs=65536;function disposeSqliteStatement(e){e[Symbol.dispose]?.()}function clearStatementCache(e){let t=e[fs];if(delete e[fs],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[gs]??=/* @__PURE__ */ new Set,t)}function assertNodeSqliteDisposalAllowed(e){for(let t of e[_s]??[])t()}function disposeNodeSqliteDependents(e,t=`close`){assertNodeSqliteDisposalAllowed(e);for(let n of e[gs]??[])n(t)}function clearNodeSqliteKyselyCacheForDatabase(e){clearStatementCache(e),us.delete(e),ds.delete(e)}function installStatementInvalidation(e){if(!e[ps]){if(typeof e.setAuthorizer==`function`){let t=e.setAuthorizer.bind(e);Object.defineProperty(e,"setAuthorizer",{configurable:!0,writable:!0,value(e){t(e),this[hs]=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,ps,{configurable:!0,value:!0})}}function queryFitsStatementCache(e,t){let n=Buffer.byteLength(e);if(n>vs)return!1;for(let e of t){if(typeof e==`string`){if(e.length>vs-n)return!1;n+=Buffer.byteLength(e)}else ArrayBuffer.isView(e)&&(n+=e.byteLength);if(n>vs)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[ms]||a[hs]||!queryFitsStatementCache(t,n)){let n=e.prepare(t);return executeLeased(n,()=>disposeSqliteStatement(n))}let s=a[fs];s||(s={statements:/* @__PURE__ */ new Map,candidates:/* @__PURE__ */ new Set,active:/* @__PURE__ */ new WeakSet},Object.defineProperty(a,fs,{configurable:!0,value:s}));let c=s.statements.get(t),l;if(c&&!s.active.has(c))s.statements.delete(t),s.statements.set(t,c),l=c;else if(l=e.prepare(t),!c&&s.candidates.delete(t)){if(s.statements.set(t,l),s.statements.size>64){let e=s.statements.entries().next().value;s.statements.delete(e[0]),s.active.has(e[1])||disposeSqliteStatement(e[1])}}else if(!c&&(s.candidates.add(t),s.candidates.size>64)){let e=s.candidates.values().next().value;e!==void 0&&s.candidates.delete(e)}return s.active.add(l),executeLeased(l,()=>{s.active.delete(l),(a[fs]!==s||s.statements.get(t)!==l)&&disposeSqliteStatement(l)})}const ys={"state-migrations":`state migration`,"newer-schema":`a newer OpenClaw build`,"agent-media":`offline media migration`,"audit-events-v2":`state database schema migration`,"legacy-workshop-review-index":`state database schema migration`,"legacy-cron-run-logs":`cron run history migration`,"legacy-workspace":`workspace setup state migration`,"legacy-session-store":`session store migration`};var StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n),this.kind=e,this.code=`gateway.maintenance_required`,this.name=`StartupMaintenanceRequiredError`}get reason(){return ys[this.kind]}};es();var SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e),this.name=`SqliteSchemaVersionError`}};function readSqliteUserVersion(e){let t=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get());return Number(t?.user_version??0)}function readSqliteWriterAppVersion(e){try{let t=executeWithCachedStatement(e,`SELECT app_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`,[],e=>e.get());return typeof t?.app_version==`string`&&t.app_version.length>0?t.app_version:void 0}catch{return}}function describeRunningOpenClawBuild(){let e=resolveRuntimeServiceCommit(),t=resolveOpenClawPackageRootSync({moduleUrl:import.meta.url}),n=e?`OpenClaw ${as} (${e})`:`OpenClaw ${as}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,as)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){let s=isNewerSqliteWriterVersion(i),c=s?`; it is newer than this Gateway (${as}).`: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!==as)?`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 https://docs.openclaw.ai/reference/database-schemas.`)}function assertWorkerTaskActive(e,t){if(!t()||(e&bs)!==0)throw Error(`worker task cancelled`)}function acquireWorkerNativeSection(e,t){for(;;){let n=Atomics.load(e,0);if(assertWorkerTaskActive(n,t),Atomics.compareExchange(e,0,n,n+xs)===n)break}let n=!1;return()=>{n||(n=!0,Atomics.sub(e,0,xs),Atomics.notify(e,0))}}function withWorkerTaskNativeSectionScope(e,t,n){return ws.run(()=>acquireWorkerNativeSection(e,t),n)}function createWorkerNativeSectionState(){return new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))}function cancelWorkerNativeSections(e){Atomics.or(e,0,bs),Atomics.notify(e,0)}function observeWorkerTaskCancellation(e,t,n){let r=!0,i=(async()=>{for(;;){if(!r||!t())return;let i=Atomics.load(e,0);if((i&bs)!==0){n();return}await Atomics.waitAsync(e,0,i).value}})();return()=>(r=!1,Atomics.notify(e,0),i)}function waitForWorkerNativeSections(e){if(!areWorkerNativeSectionsSettled(e))return(async()=>{for(;;){let t=Atomics.load(e,0);if(t<xs)return;await Atomics.waitAsync(e,0,t).value}})()}function areWorkerNativeSectionsSettled(e){return Atomics.load(e,0)<xs}function releaseWorkerNativeSectionsOnExit(e){Atomics.store(e,0,bs),Atomics.notify(e,0)}function createWorkerTaskControl(e,t,n=new AbortController().signal){let throwIfCancelled=()=>assertWorkerTaskActive(Atomics.load(e,0),t);return{signal:n,throwIfCancelled,runNativeSection:async n=>{let r=acquireWorkerNativeSection(e,t),i;try{i=await n()}finally{r()}return throwIfCancelled(),i}}}var bs,xs,Ss,Cs,ws,Ts=__esmMin((()=>{bs=1,xs=2,Ss=Symbol.for(`openclaw.workerTaskNativeSection`),Cs=globalThis,ws=Cs[Ss]??=new D}));Ts();function postTaskMessage(e,t,n,r=[]){e.postMessage(t,r),n&&(Atomics.add(n,0,1),Atomics.notify(n,0))}function serveOwnedWorkerTasks$1(e,t,n){if(!Te)return;let r=Te,i=r,a=!1,s=!1;n.initialize(i);let c,l=Promise.resolve(),u=Promise.resolve(),d=0,f,p=typeof e==`function`?void 0:e.synchronousStateless,m=typeof e==`function`?e:e.synchronousStateless,reply=(e,r)=>{postTaskMessage(i,{status:`ok`,value:r,taskId:e.taskId,...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},e.progressSignal,t.transferList?.(r)??[])},fail=(e,r)=>{t.retireOnError?s=!0:postTaskMessage(i,{status:`failed`,taskId:e.taskId,error:r instanceof Error?r.message:String(r),...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},e.progressSignal)},finish=()=>{s?(async()=>{try{await u}finally{try{await n.onRetire?.()}finally{process.exitCode=1;try{i.close()}finally{i!==r&&r.close()}}}})().catch(()=>{process.exitCode=1}):n.onIdle()};i.on(`message`,function receive(e){if(s){e.resourcePort?.close();return}if(!a){a=!0;let t=n.selectStartupPort?.(e);if(t){i.off(`message`,receive),i=t,n.initialize(i),i.on(`message`,receive),n.onReady?.();return}}if(n.onMessage(e.sampleMemory===!0),e.closeResource&&e.resourcePort){let r=e.resourcePort,i=t.closesBesideExecution?.(e.key)?void 0:l;d++,u=u.then(()=>i).then(async()=>{if(s)throw Error(`Worker is retiring after a terminal task failure`);await t.closeResource(e.key),r.postMessage({ok:!0},[])}).catch(e=>{r.postMessage({ok:!1,error:e instanceof Error?e.message:String(e),detail:t.encodeResourceError?.(e)},[])}).finally(()=>{r.close(),d--,!c&&!s&&n.onIdle()});return}if(e.responseId!==void 0){if(e.taskId===f?.taskId&&e.responseId===f.responseId)return;if(!c||e.taskId!==c.taskId||e.responseId!==c.responseId||!c.pending)throw Error(`stale worker task response`);try{c.assertCurrent()}catch(e){c.cancelPending(e);return}let t=c.pending;c.pending=void 0;let n=!1,r=e.taskId,a=e.responseId,s=c.progressSignal;t.resolve({input:e.input,consumed:()=>{n||(n=!0,postTaskMessage(i,{status:`consumed`,taskId:r,id:a},s))}});return}if(c)throw Error(`overlapping worker tasks`);let r=new Int32Array(e.nativeSections),h={taskId:e.taskId,responseId:0,progressSignal:e.progressSignal,assertCurrent:()=>_.throwIfCancelled(),cancelPending:e=>{let t=h.pending;t&&(h.pending=void 0,f={taskId:h.taskId,responseId:h.responseId},t.reject(e))}},g=new AbortController,_=createWorkerTaskControl(r,()=>c===h,g.signal);if(c=h,p&&!e.interactive&&d===0){try{_.throwIfCancelled(),n.installTaskContext(e.taskContext);let t=p(e.input);c=void 0,reply(h,t)}catch(e){c=void 0,fail(h,e)}finally{finish()}return}let v=observeWorkerTaskCancellation(r,()=>c===h,()=>{let e=/* @__PURE__ */ Error(`worker task cancelled`);g.abort(e),h.cancelPending(e)}),y=e.interactive?{notify:e=>{_.throwIfCancelled(),postTaskMessage(i,{status:`notification`,taskId:h.taskId,value:e},h.progressSignal)},consumeInput:()=>postTaskMessage(i,{status:`consumed`,taskId:h.taskId,id:0},h.progressSignal),request:(e,t)=>{if(_.throwIfCancelled(),c!==h||h.pending)throw Error(`closed or busy worker channel`);let n=Promise.withResolvers();h.pending=n;try{let n=t?[...t]:[];_.throwIfCancelled(),postTaskMessage(i,{status:`request`,taskId:h.taskId,id:++h.responseId,value:e},h.progressSignal,n)}catch(e){h.pending=void 0,n.reject(e)}return n.promise}}:void 0,b=u;l=Promise.resolve().then(async()=>{try{return await b,_.throwIfCancelled(),n.installTaskContext(e.taskContext),await withWorkerTaskNativeSectionScope(r,()=>c===h,()=>m(e.input,y,_))}finally{await v?.(),c=void 0}}).then(e=>reply(h,e)).catch(e=>fail(h,e)).finally(finish)}),n.onReady?.()}Ts();function scheduleOpenClawCompileCacheFlush(){if(!e.getCompileCacheDir?.())return;let t=globalThis[Symbol.for(`openclaw.nodeCompileCacheBase`)]??={};t.flush||(t.flush=setImmediate(()=>{t.flush=void 0;try{e.flushCompileCache()}catch{}}),t.flush.unref())}function resolveSafeNodeCompileCacheDirectory(e){if(process.platform===`win32`&&n.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=n.dirname(n.dirname(e)),r=n.basename(n.dirname(e));if(n.basename(t)!==`openclaw`||sanitize(r)!==r||!Ms.test(n.basename(e)))return;let i=Date.now(),a=await w.lstat(t).catch(()=>void 0);for(let r of[t,n.dirname(e),e]){let e=r===t?a:await w.lstat(r).catch(()=>void 0);if(e&&!e.isDirectory())return}if(a&&i-a.mtimeMs<Os)return;await w.mkdir(t,{recursive:!0});let s=`${t}.maintenance`,c=await w.lstat(s).catch(()=>void 0);if(c&&i-c.mtimeMs>3e5&&await w.rmdir(s).catch(()=>{}),!await w.mkdir(s).then(()=>!0,()=>!1))return;let l=[],u=0,d=0,f=!1;async function prune(){for(l.sort((e,t)=>t.mtimeMs-e.mtimeMs);l.length;){if(Date.now()-i>js)return!1;let e=l[l.length-1];if(u<=Es&&l.length<=ks&&i-e.mtimeMs<=Ds)break;await w.unlink(e.file).catch(e=>{if(e.code!==`ENOENT`)throw e}),u-=e.size,l.pop()}return!0}async function visit(e){for await(let t of await w.opendir(e)){if(++d>As||Date.now()-i>js)return!1;let r=n.join(e,t.name);if(t.isDirectory()){if(!await visit(r))return!1}else if(t.isFile()){let e=await w.lstat(r).catch(e=>{if(e.code!==`ENOENT`)throw e});if(!e)continue;if(u+=e.size,l.push({file:r,size:e.size,mtimeMs:e.mtimeMs}),l.length%256==0&&!await prune())return!1}}return!0}try{if(i-(await w.lstat(t)).mtimeMs<Os){f=!0;return}let e=await visit(t);if(await prune()&&e){let e=/* @__PURE__ */ new Date;await w.utimes(t,e,e),f=!0}}finally{f||await w.utimes(t,a?.atime??/* @__PURE__ */ new Date(0),a?.mtime??/* @__PURE__ */ new Date(0)).catch(()=>{}),await w.rmdir(s)}}var Es,Ds,Os,ks,As,js,Ms,sanitize,Ns=__esmMin((()=>{T&&process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED===`gateway`&&(delete process.env.NODE_DISABLE_COMPILE_CACHE,delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED),Es=536870912,Ds=6048e5,Os=36e5,ks=4096,As=16384,js=3e4,Ms=/^(?:[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]===c(import.meta.url)&&process.argv[3]&&maintain(process.argv[3]).catch(()=>{})}));function captureDeletedAgentDatabaseFences(){return[...Ps.deleted]}function installDeletedAgentDatabaseFences(e){Ps.deleted.clear();for(let[t,n]of e)Ps.deleted.set(t,n)}async function applyAgentDatabaseReaderRequest(e){if(e.kind===`revive`){for(let[t,n]of Ps.deleted)e.agentIds.includes(n)&&Ps.deleted.delete(t);return}if(e.deleted)for(let t of e.candidates)Ps.deleted.set(n.resolve(t.path),e.agentId);let t=e.deleted?void 0:new Set(e.retainedPaths?.map(e=>n.resolve(e)));throwIfSettledRejected(await Promise.allSettled([...Ps.closers].map(async n=>n(e.candidates,t))),`Agent database reader cleanup failed`)}function normalizeCandidates(e){if(Array.isArray(e)&&e.every(e=>isRecord(e)&&typeof e.path==`string`&&(e.scope===void 0||e.scope===`sibling-family`)))return e.map(e=>e.scope?{path:e.path,scope:e.scope}:{path:e.path})}function decodeAgentDatabaseReaderRequest(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}if(Array.isArray(t)){let e=normalizeCandidates(t);return e?{kind:`close`,candidates:e,deleted:!1}:void 0}if(isRecord(t)){if(`candidates`in t&&!(`deleted`in t)){let e=normalizeCandidates(t.candidates),n=t.retainedPaths;return e&&isStringArray(n)?{kind:`close`,candidates:e,retainedPaths:n,deleted:!1}:void 0}if(`deleted`in t){let e=normalizeCandidates(t.deleted);return e&&typeof t.agentId==`string`&&t.agentId.length>0?{kind:`close`,candidates:e,deleted:!0,agentId:t.agentId}:void 0}if(`revive`in t&&isStringArray(t.revive))return{kind:`revive`,agentIds:t.revive}}}var Ps,Fs=__esmMin((()=>{k(),j(),wo(),Ps=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseReaders`),()=>({closers:/* @__PURE__ */ new Set,deleted:/* @__PURE__ */ new Map}))}));function getDatabaseEngineSelection(){return Ls.getStore()??Is.selection}function withDatabaseEngineSelection(e,t){return Ls.run(e,t)}var Is,Ls,Rs=__esmMin((()=>{j(),Is=resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineSelection`),()=>({})),Ls=resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineMaintenanceSelection`),()=>new D)}));function postgresPoolWorkerFailure(){return N.failure}function bindPostgresPool(e){if(N.endpoints){if(N.endpoints===e)return;for(let{port:t}of e.services)t.close()}else N.endpoints=e}async function closePostgresPool(){let e=N.workers;N.workers=void 0;for(let{port:e}of N.endpoints?.services??[])e.close();N.endpoints=void 0,N.ready=[],N.refresh=void 0,N.failure=void 0,await Promise.all(e?.map(e=>e.terminate())??[])}var zs,N,Bs=__esmMin((()=>{j(),zs=Oe,N=resolveGlobalSingleton(Symbol.for(`openclaw.postgresIoPool`),()=>({endpoints:zs?.postgresPool,workers:void 0,nextStep:void 0,ready:[],refresh:void 0,failure:void 0}))})),Vs,Hs=__esmMin((()=>{Vs=`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 Us=__esmMin((()=>{}));function databaseFileIdentityKey(e){return`${e.dev}:${e.ino}`}function readDatabaseIdentityBirthtime(e){return Ws?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 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,r){if(!C(r,`ENOENT`))throw r;t.unshift(n.basename(e));let i=n.dirname(e);if(i===e)throw r;return i}async function inspectDatabasePathIdentity(e){let t=await fe(e,{bigint:!0}).catch(e=>{if(!C(e,`ENOENT`))throw e});if(t){if(!t.isFile())return;try{let n=await ue(e);return existingIdentity(t,await fe(n,{bigint:!0}),n)}catch(e){throw C(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=[],r=n.resolve(e);for(;;)try{return normalizeDatabasePath(n.join(await ue(r),...t))}catch(e){r=missingAncestorParent(r,t,e)}}function isSoleDatabaseFileDescriptor(e,t){if(process.platform!==`linux`)return!1;try{for(let n of g(`/proc/self/fd`))if(/^\d+$/u.test(n)&&Number(n)!==e)try{let e=f(Number(n),{bigint:!0});if(e.dev===t.dev&&e.ino===t.ino)return!1}catch(e){if(!C(e,`EBADF`))return!1}return!0}catch{return!1}}var Ws,Gs=__esmMin((()=>{Cn(),wn(),Ws=process.platform!==`linux`&&process.platform!==`android`}));function readSqliteDatabaseAdmissionIdentity(e){return`${e.dev}:${e.ino}:${readDatabaseIdentityBirthtime(e)}`}function readSqliteDatabaseAdmissionFact(e,t){return e[qs]??={value:t.read?t.read(e.value):e.value},e[qs].value}function admitSqliteDatabaseFactValue(e,t){let n={value:t};return readSqliteDatabaseAdmissionFact(n,e),n}function retainSqliteDatabaseWriteScope(e,t,n){let r=e.writeScopes,i=Ys.get(r);i||(i={bytes:[...r.keys()].reduce((e,t)=>e+writeScopeBytes(t),0),retired:/* @__PURE__ */ new Set},Ys.set(r,i)),r.delete(t)||(i.bytes+=writeScopeBytes(t)),r.set(t,n),pruneSqliteDatabaseWriteScopes(e)}function pruneSqliteDatabaseWriteScopes(e){let t=Ys.get(e.writeScopes);if(t.bytes<=Js)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<=Js))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),P[t])}function advanceSqliteDatabaseGeneration(e,t){return Atomics.add(new Int32Array(e.generation),P[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 snapshotWriteScopes(e,t=Xs,n){let r=t,i=Ys.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&Xs.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 P,Ks,qs,Js,Ys,writeScopeBytes,Xs,SqliteDatabaseAdmissionRegistry,Zs=__esmMin((()=>{j(),Us(),Hs(),Gs(),P={schemaRevision:0,factRevision:1,publicationRevision:2,retired:3,writeRevision:4,hostRevision:5,unscopedWriteRevision:6,writeScopeRevision:7,sealPresent:8},Ks=Object.keys(P).length,qs=Symbol.for(`openclaw.sqliteDatabaseAdmission.decodedValue`),Js=1048576,Ys=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseWriteScopeRetention`),()=>/* @__PURE__ */ new WeakMap),writeScopeBytes=e=>e.length*2+256,Xs=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),P.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.compareExchange(n.writerDiagnostic,1,e+1,0),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 r=normalizeDatabasePath(n.resolve(e));t===void 0?this.locations.delete(r):this.locations.set(r,t)}forLocation(e){return this.forPathname(normalizeDatabasePath(n.resolve(e)))}prepareLocation(e){let t=normalizeDatabasePath(n.resolve(e));return()=>this.forPathname(t)}forPathname(e){let t=this.locations.get(e),n=t===void 0?void 0:this.records.get(t);return n&&!isSqliteDatabaseAdmissionRetired(n)?n:void 0}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,n){let r=readSqliteDatabaseAdmissionIdentity(n),i=this.descriptors.get(r);if(i&&i.descriptor!==t)throw Error(`SQLite descriptor custody changed during admission`);i||this.descriptors.set(r,{location:e,descriptor:t,file:n,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:S(),generation:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*Ks),writerDiagnostic:new Int32Array(new SharedArrayBuffer(125*Int32Array.BYTES_PER_ELEMENT)),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:{location:e,descriptor:t,file:n,facts:/* @__PURE__ */ new Map};return a.location=e,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),r=this.descriptors.get(e)?.descriptor??n?.descriptor;if(r===void 0)return!1;let i=u.fstatSync(r,{bigint:!0});return i.nlink>1n||t.requireSoleDescriptor&&!isSoleDatabaseFileDescriptor(r,i)?!1:(n&&Atomics.store(new Int32Array(n.generation),P.retired,1),u.closeSync(r),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 r of this.records.values()){if(isSqliteDatabaseAdmissionRetired(r)){readSqliteDatabaseGeneration(r,`retired`)===1&&this.descriptors.delete(r.identity),this.forget(r.identity);continue}if(e&&e!==r&&!(n&&e.has(r)))continue;let i=e===r||n;for(let[e,t]of r.references)Atomics.load(new Int32Array(t),0)<0&&(r.references.delete(e),i=!0);let a=this.published.get(r.identity),s=readSqliteDatabaseGeneration(r,`writeScopeRevision`),c=a&&e?n?e.get(r):t:void 0,l=c===void 0&&this.scopeSweeps.get(r)!==s,u=snapshotWriteScopes(r.writeScopes,a?.writeScopes,c??(l?void 0:[]));if(l&&this.scopeSweeps.set(r,s),i||=u!==a?.writeScopes,!i)continue;E===0&&(r.writeScopeRevision=readSqliteDatabaseGeneration(r,`writeScopeRevision`));let{writeScopes:d,...f}=r,p={...f,facts:new Map(r.facts),references:new Map(r.references),hostRevision:E===0?readSqliteDatabaseGeneration(r,`hostRevision`):r.hostRevision},m={...p,writeScopes:u.filter(e=>e.size>0)};this.published.set(r.identity,{metadata:p,writeScopes:u,snapshot:m})}this.revision++,De(Vs,[...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 F.registry.capture(e,t)}function installSqliteDatabaseAdmissions(e){F.registry.install(e)}function exchangeSqliteDatabaseAdmission(e,t,n=!1,r){let i=F.exchange.getStore();if(i&&!F.exchanging){F.exchanging=!0;try{let a=typeof e==`string`?{location:e}:{admissions:[e]},s=F.registry.captureExchange(a,e);if(n&&s.length===0)return;installSqliteDatabaseAdmissions(i(s,typeof e==`string`?e:void 0,t,r))}catch(e){throw F.registry.resetExchangeCursor(),e}finally{F.exchanging=!1}}}function withSqliteDatabaseAdmissionExchange(e,t){return F.exchange.run(e,t)}var F,Qs,$s=__esmMin((()=>{j(),Hs(),Zs(),F=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 D,exchanging:!1,publication:0})),Qs=readSqliteDatabaseAdmissions(we(Vs)),Qs&&(installSqliteDatabaseAdmissions(Qs),F.registry.captureExchange())})),ec,tc,nc=__esmMin((()=>{j(),ec=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseAccessError`),()=>class extends Error{constructor(...e){super(...e),this.name=`StateDatabaseAccessError`}}),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`}}),resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseMaintenanceScopeError`),()=>class extends ec{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`}}),tc=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseAdmissionPendingError`),()=>class extends ec{constructor(e,t){super(t),this.databasePath=e}}),resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseOfflineMaintenanceError`),()=>class extends ec{constructor(e,t){super(t),this.databasePath=e}})}));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=>Re(t,e))===t);return Object.assign(t===void 0?Error(e):new SqliteWorkerError(e,t),{cause:r.length>1?AggregateError(r,e):r[0]})}var rc,SqliteWorkerError,ic=__esmMin((()=>{O(),rc=Symbol.for(`openclaw.sqliteWorkerErrorCode`),SqliteWorkerError=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`SqliteWorkerError`,Object.defineProperty(this,rc,{value:t})}}}));function withSqliteDatabaseAdmissionWait(e,t){let n={wait:e,parent:ac.getStore(),active:!0},close=()=>{n.active=!1},r=!1;try{let e=ac.run(n,t);return Le(e)&&(r=!0,e.then(close,close)),e}finally{r||close()}}function readSqliteDatabaseAdmissionDeadline(){let e;for(let t=ac.getStore();t;t=t.parent){if(!t.active)continue;let n=t.wait.deadlineAtMs;if(n!==void 0&&(e=Math.min(e??1/0,n)),t.wait.settlesCancellation)break}return e}function assertSqliteDatabaseAdmissionWaitActive(){try{for(let e=ac.getStore();e;e=e.parent)if(e.active){if(e.wait.settlesCancellation)return;e.wait.assertActive?.()}}catch(e){throw wrapSqliteWorkerError(`SQLite admission facts exchange cancelled by its caller`,`unavailable`,e)}}function hasSqliteDatabaseAdmissionWait(){return ac.getStore()!==void 0}var ac,oc=__esmMin((()=>{j(),ic(),ac=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionWait`),()=>new D)})),sc,AsyncContext,cc=__esmMin((()=>{j(),sc=resolveGlobalSingleton(Symbol.for(`openclaw.asyncContext`),()=>new D),AsyncContext=class{constructor(e){this.key=e}getStore(){return sc.getStore()?.[this.key]}run(e,t){let n=sc.getStore(),r=n?.[this.key];if(Object.is(r,e))return t();let i={...n,[this.key]:e};sc.enterWith(i);try{return t()}finally{let e=sc.getStore();sc.enterWith(e===i?n:{...e,[this.key]:r})}}exit(e){return this.run(void 0,e)}enterWith(e){sc.enterWith({...sc.getStore(),[this.key]:e})}}}));function observeSqliteReaderCounters(e){uc.listeners.add(e);for(let t of uc.counters.values())e(t);return()=>uc.listeners.delete(e)}function accumulateSqliteReaderCounters(e,t){for(let n of t){let t=n.operation,r=e.get(t);r||(r={operation:t,count:0,readBytes:0},e.set(t,r)),r.count+=Number(Atomics.load(n.values,0)),r.readBytes+=Number(Atomics.load(n.values,1))}}function receive(e,t){let{operation:n,values:r}=t,i=uc.operations.has(n)||uc.operations.size<lc?n:`other`;uc.operations.add(i);let a=uc.workers.get(e);a||(a=/* @__PURE__ */ new Map,uc.workers.set(e,a)),a.set(n,{operation:i,values:r})}function retire(e){let t=uc.workers.get(e);t&&(accumulateSqliteReaderCounters(uc.retired,t.values()),uc.workers.delete(e))}var lc,uc,dc=__esmMin((()=>{j(),lc=256,uc=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteReaderMetrics`),()=>({counters:/* @__PURE__ */ new Map,listeners:/* @__PURE__ */ new Set,workers:/* @__PURE__ */ new Map,operations:/* @__PURE__ */ new Set,retired:/* @__PURE__ */ new Map}))}));function sqliteReaderDatabasePathKey(e){let t=n.resolve(e);return process.platform===`win32`?ce(t):t}function boundedOperation(e){return(e.trim()||`sqlite reader`).slice(0,120)}function currentSqliteOperationTiming(){return fc.getStore()?.timing}function currentOwner(e,t){let n=t??fc.getStore();return{operation:boundedOperation(n?.operation??e),ownerKind:n?.ownerKind??(T?`main`:`worker`),...n?.actorId===void 0?{}:{actorId:n.actorId}}}function connectionFor(e){let t=pc.byDatabase.get(e);if(!t){let n=Date.now(),r=e.location();t={id:++pc.nextId,path:r?sqliteReaderDatabasePathKey(r):void 0,database:new WeakRef(e),owner:currentOwner(`sqlite connection`),openedAtMs:n,readers:/* @__PURE__ */ new Map},pc.byDatabase.set(e,t),pc.finalizer.register(e,t,t)}if(t.path){let e=pc.byPath.get(t.path)??/* @__PURE__ */ new Map;e.set(t.id,t),pc.byPath.set(t.path,e)}return t}function forgetConnection(e){if(e.path){let t=pc.byPath.get(e.path);t?.delete(e.id),t?.size===0&&pc.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)}}}var fc,pc,mc=__esmMin((()=>{cc(),j(),dc(),fc=new AsyncContext(Symbol.for(`openclaw.sqliteReaderOwners`)),pc=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteReaderConnections`),()=>({nextId:0,byDatabase:/* @__PURE__ */ new WeakMap,byPath:/* @__PURE__ */ new Map,finalizer:new FinalizationRegistry(e=>forgetConnection(e))}))}));function readSqliteWorkerMonotonicNs(){return hc.bigint()}function readSqliteWorkerAdmissionDecision(e){if(!isRecord(e)||!(e.decision instanceof SharedArrayBuffer)||e.decision.byteLength!==Int32Array.BYTES_PER_ELEMENT||e.stage!==`open`&&e.stage!==`prepare`&&e.stage!==`transaction`&&e.stage!==`commit`)return;let t=new Int32Array(e.decision),n=typeof e.deadlineMs==`number`&&Number.isFinite(e.deadlineMs)?readSqliteWorkerMonotonicNs()+BigInt(Math.max(0,Math.ceil(e.deadlineMs)))*1000000n:void 0;return{decision:t,expired:()=>{if(n!==void 0&&readSqliteWorkerMonotonicNs()>=n&&Atomics.compareExchange(t,0,0,3)===0&&Atomics.notify(t,0),Atomics.load(t,0)!==3)return!1;if(Array.isArray(e.ports))for(let t of e.ports)t instanceof xe&&t.close();return!0},request:{stage:e.stage,facts:e.facts}}}var hc,gc=__esmMin((()=>{k(),j(),ic(),hc=process.hrtime,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`}}),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 classifySqliteWorkerExecute(e){if(yc.has(e))return e;let t=e.indexOf(`.`),n=t===-1?e:e.slice(0,t);return yc.has(n)?n:`execute`}function classifyWorkerRequest(e,t){if(typeof e!=`string`)return`execute`;if(bc.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`&&Sc.some(e=>i.endsWith(e))){let e=xc.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 Cc)if(e.startsWith(t))return n;return classifySqliteWorkerExecute(e)}function normalizeWorkerRequestClass(e){return e!==void 0&&wc.has(e)?e:`other`}var _c,vc,yc,bc,xc,Sc,Cc,wc,Tc=__esmMin((()=>{k(),_c=/* @__PURE__ */ `admit,audit.events.list,audit.writer.process,audit.writer.prune,database.domain.bind,database.domain.close,database.domain.publish,database.prepareWrite,database.walMaintenance,localWorkspace.prepare,localWorkspace.pruneLegacy,localWorkspace.beginSweep,localWorkspace.finishSweep,localWorkspace.sweepBatch,localWorkspace.mutate,localWorkspace.manifest,localWorkspace.readBacking,localWorkspace.sweepCandidates,localWorkspace.reviewBase,localWorkspace.byProjectionPath,localWorkspace.exists,localWorkspace.get,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(`,`),vc=/* @__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(`.`),yc=/* @__PURE__ */ new Set([..._c,...vc]),bc=/* @__PURE__ */ new Set(/* @__PURE__ */ `abortedPartial,acceptIntent,add,append,appendChunk,assistant,batch,boards.applyOps,boards.grant,boards.putWidget,cache.clear,cache.prune,cache.read,cache.retire,cache.stage.start,cache.write,cache.write.inline,cancel,catalog.pruneRemovedProviders,catalog.removeCredentials,catalog.replace,category.apply,category.prepare,claim,complete,connection.inspect,create,delete,deleteChunk,discardIntent,discover,enqueueIntent,finalize,finish,forget.mark,forget.purge,hasPending,index.facts,index.upgradeProviderKey,index.writeEmbeddingRefusal,index.writeMetadata,involvement,list,listPendingSessions,match,owner.assign,participant,preflight,prepare,prepareRun,prune,publishClosedTurn,put,readNextPending,record,recordFailure,remove,reserve,schema.admit,source.chunks,source.delete,source.hash,source.refresh,source.replace,source.replace.group,source.replace.inline,source.state,stage.append,stage.discard,stage.start,suggestion.add,suggestion.claim,suggestion.finalize,suggestion.release,sweep,vector.ensure,vector.prepare,devicePairing.ensureToken,devicePairing.list,devicePairing.lookup,devicePairing.updateMetadata,devicePairing.updatePresence,devicePairing.verifyToken,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.actor.read,session.agentPurge.commit,session.agentPurge.prepare,session.archivePruning.deletePublished,session.archivePruning.pruneRetention,session.archivePruning.reclaimPages,session.archivePruning.removeLegacy,session.archives.preparePublication,session.archives.recordPublication,session.entries.replace,session.entry.acp,session.entry.patch.commit,session.entry.patch.prepare,session.entry.read,session.entry.readResult,session.entry.replacements.commit,session.entry.replacements.prepare,session.goal.mutate,session.lifecycle.delete,session.lifecycle.deletePlan,session.lifecycle.project,session.lifecycle.reset,session.maintenance.finalize,session.maintenance.metadata,session.maintenance.prepare,session.maintenance.size,session.messageCut.commit,session.messageCut.fork,session.messageCut.preflight,session.messageRewrite.commit,session.messageRewrite.modelPrompt,session.messageRewrite.prepare,session.metadata.append,session.metadata.initialize,session.metadata.mutation,session.nativeBindings.delete,session.parentFork.commit,session.parentFork.prepare,session.parentFork.source,session.pendingInputs.mutate,session.pendingInputs.read,session.pendingInputs.withdraw,session.providerReview.compare,session.reaction.set,session.rowTranscript.backfill,session.turn.commit,session.turn.prepare,trajectory.events.append,trajectory.retention.begin,trajectory.retention.delete,transcript.commit,transcript.prepare,usageCache.prune,usageCache.writeQuarters,usageCache.writeRollup`.split(`,`)),xc=/* @__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`]]),Sc=[`/config/sessions/session-transcript-projection-publication.worker.js`,`/config/sessions/session-transcript-projection-publication.worker.ts`],Cc=[[`pluginState.`,`plugin_state`],[`session.history.`,`transcript_read`],[`trajectory.`,`transcripts`],[`session.transcript.`,`transcripts`],[`transcripts.`,`transcripts`],[`session.`,`sessions`],[`cron.`,`cron`]],wc=/* @__PURE__ */ new Set([...bc,...xc.values(),...yc,...Cc.map(([,e])=>e),`task`,`open`,`close`,`execute`,`domain_execute`,`auth_profiles`])}));function sampleWorkerAuthorityOperation(e){return T&&normalizeWorkerRequestClass(e).startsWith(`session.actor.`)&&Math.random()<1/128}function recordWorkerAuthorityMessage(e,t,n=sampleWorkerAuthorityOperation(t)){return recordWorkerMessage(e?.kind===`sqlite-database-admissions`?`admission`:`authority`,`from_worker`,typeof e?.payloadBytes==`number`?e.payloadBytes:void 0,t,n?e:void 0),n}function withoutField(e,t){if(!isRecord(e)||!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function recordAuthorityPayload(e,t,n){let r=normalizeWorkerRequestClass(n);if(!r.startsWith(`session.actor.`))return;let i=t.kind===`native-settlement`&&isRecord(t.settlement)?t.settlement.committed:t.committed,a=isRecord(i);if(!a&&!Object.hasOwn(t,`facts`))return;let s=a?[`receipt_entry`,`receipt_events`,`receipt_value`,`receipt_other`]:[`admission_entry`,`admission_other`],c=(e.payloadComponents??={})[r]??={},l,u=a&&typeof t.payloadBytes==`number`?t.payloadBytes:void 0;try{let e=a?i.facts:t.facts;if(u??=qe(e).byteLength,a&&isRecord(e)&&isRecord(e.receipt)){let t={...e.receipt,postimage:withoutField(e.receipt.postimage,`entry`)};delete t.entryMetadata;let n={...e,receipt:t},r=Math.min(u,qe(n).byteLength),i={...n,receipt:{...n.receipt,transcript:withoutField(withoutField(e.receipt.transcript,`appendedEvents`),`authorityReceipts`)}},a=Math.min(r,qe(i).byteLength),s=Math.min(a,qe({...i,value:void 0,receipt:{...i.receipt,transcript:withoutField(i.receipt.transcript,`append`)}}).byteLength);l=[u-r,r-a,a-s,s]}else if(!a&&isRecord(e)&&isRecord(e.publication)&&e.publication.kind===`session-actor-admission`){let t=qe({...e,publication:{...e.publication,snapshot:withoutField(e.publication.snapshot,`entry`)}}).byteLength;l=[u-t,t]}else l=a?[0,0,0,u]:[0,u];l.some(e=>e<0)&&(l=void 0)}catch{}for(let[e,t]of s.entries()){let n=c[t]??={bytes:0,samples:0,unmeasured:0};l?(n.bytes+=l[e]??0,n.samples++):(n.unmeasured++,t===`receipt_other`&&u!==void 0&&(n.bytes+=u))}}function recordWorkerMessage(e,t,n,r,i){if(!T)return;let a=Ec.get(e);a||(a={},Ec.set(e,a));let s=a[t]??={kind:e,direction:t,messages:0,payloadBytes:0,unmeasuredMessages:0};if(s.messages++,n===void 0)s.unmeasuredMessages++;else if(s.payloadBytes+=n,e===`sqlite_request`||e===`sqlite_reply`||e===`authority`){let e=s.payloadBytesByRequestClass??={},t=normalizeWorkerRequestClass(r);e[t]=(e[t]??0)+n}i&&e===`authority`&&t===`from_worker`&&recordAuthorityPayload(s,i,r)}function messageData(e){return isRecord(e)&&!Ve.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(!T)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(!Ve.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){T&&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 Ec,Dc=__esmMin((()=>{k(),j(),Tc(),Ec=resolveGlobalSingleton(Symbol.for(`openclaw.workerMessageMetrics`),()=>/* @__PURE__ */ new Map)}));function bindSqliteDatabaseAdmissionUpstream(e){let t=Nc.connection;if(t){if(t.port!==e)throw new SqliteWorkerError(`SQLite admission upstream changed owner`,`closed`);return}let n={port:e,closed:!1};Nc.connection=n,e.once(`close`,()=>{n.closed=!0}),e.unref()}function getSqliteDatabaseAdmissionUpstream(){return Nc.connection}function isSqliteDatabaseAdmissionLocation(e){return isRecord(e)&&typeof e.identity==`string`&&typeof e.canonicalPath==`string`}function exchangeSqliteDatabaseAdmissions(e,t,n,r,i){return exchangeDatabaseAdmissions(e,t,n,r,i)}function exchangeDatabaseAdmissions(e,t,n,r,i){let{port1:a,port2:s}=new be,c=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),l=currentSqliteOperationTiming(),u=Date.now(),d=readSqliteDatabaseAdmissionDeadline(),f=d===void 0?Mc:Math.max(0,d-Date.now()),p=readSqliteWorkerMonotonicNs()+BigInt(Math.ceil(f))*1000000n,remaining=()=>{assertSqliteDatabaseAdmissionWaitActive();let e=Number(p-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,observedLocation:i,deadlineAtMs:d,port:s,decision:c.buffer},[s]);Atomics.load(c,0)===Oc;){let e=remaining();Atomics.wait(c,0,Oc,hasSqliteDatabaseAdmissionWait()?Math.min(100,e):e)}remaining();let l=Atomics.load(c,0);if(l===4&&n&&r===!0)throw new tc(n,`OpenClaw state at ${n} is undergoing schema admission; retry when it finishes.`);if(l!==kc)throw new SqliteWorkerError(`SQLite admission facts exchange failed`,`unavailable`);let u=readSqliteDatabaseAdmissions(Ee(a)?.message);if(!u)throw new SqliteWorkerError(`SQLite admission facts reply is unavailable`,`unavailable`);return u}finally{Atomics.compareExchange(c,0,Oc,Ac),l&&(l.databaseAdmissionWaitMs+=Date.now()-u),a.close(),s.close()}}function isSqliteDatabaseAdmissionMessage(e){return!(!(e.port instanceof xe)||!(e.decision instanceof SharedArrayBuffer)||e.decision.byteLength!==Int32Array.BYTES_PER_ELEMENT||e.location!==void 0&&typeof e.location!=`string`||e.observedLocation!==void 0&&!isSqliteDatabaseAdmissionLocation(e.observedLocation)||e.deadlineAtMs!==void 0&&(typeof e.deadlineAtMs!=`number`||!Number.isFinite(e.deadlineAtMs))||e.create!==void 0&&typeof e.create!=`boolean`&&e.create!==`admitted`)}function createSqliteDatabaseAdmissionReplies(){let e=createSqliteDatabaseAdmissionCursor();return{release(e){Pc.delete(e)},receive(t,n,r,i){if(!isSqliteDatabaseAdmissionMessage(t)){i(new SqliteWorkerError(`SQLite admission facts request is invalid`,`unavailable`));return}let a=new Int32Array(t.decision),{deadlineAtMs:s,observedLocation:c}=t,assertWaiting=()=>{if(Atomics.load(a,0)!==Oc||s!==void 0&&Date.now()>=s)throw new SqliteWorkerError(`SQLite admission requester stopped waiting`,`unavailable`)},l=t.port,u=t.location;return{message:t,decision:a,deadlineAtMs:s,observedLocation:c,assertWaiting,publishFacts:t=>{assertWaiting();let r=u===void 0&&t.length===0?void 0:{location:u,admissions:t},i=captureSqliteDatabaseAdmissions(Pc.get(n)?.cursor??e,r);l.postMessage(i,[]),recordWorkerMessage(`admission`,`to_worker`),Atomics.compareExchange(a,0,Oc,kc)},failFacts:(t,s)=>{if(Atomics.load(a,0)!==Oc)return;let c=Pc.get(n);c?c.cursor=r?r(()=>c.reset()):c.reset():e=createSqliteDatabaseAdmissionCursor(),t instanceof tc&&t.databasePath===s?Atomics.compareExchange(a,0,Oc,4):Atomics.compareExchange(a,0,Oc,jc)===Oc&&i(t)},finishFacts:()=>{l.close(),Atomics.notify(a,0)}}}}}var Oc,kc,Ac,jc,Mc,SqliteDatabaseAdmissionTimeoutError,Nc,Pc,Fc=__esmMin((()=>{k(),j(),nc(),$s(),Zs(),oc(),mc(),gc(),Dc(),Oc=0,kc=1,Ac=2,jc=2,Mc=6e5,SqliteDatabaseAdmissionTimeoutError=class extends SqliteWorkerError{constructor(){super(`SQLite admission facts exchange timed out; the host did not reply`,`unavailable`)}},Nc=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionUpstream`),()=>({})),Pc=/* @__PURE__ */ new WeakMap}));function clearActiveProgressLine(){Ic?.isTTY&&Ic.write(`\r\x1B[2K`)}var Ic,Lc=__esmMin((()=>{Ic=null}));function isVerbose(){return Rc}var Rc,zc=__esmMin((()=>{Rc=!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?Bc.trustedInterest:Bc.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}var Bc,Vc=__esmMin((()=>{j(),Bc=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}))})),I,Hc,Uc,Wc,Gc=__esmMin((()=>{I={priority:!1,publicExcluded:!1},Hc=[{...I,name:`worker.request`},{...I,name:`diagnostic.gc`,publicExcluded:!0},{...I,name:`gateway.event_loop.sample`,publicExcluded:!0},{...I,name:`gateway.main_thread.stall`,publicExcluded:!0},{...I,name:`gateway.http.cancelled`,publicExcluded:!0},{...I,name:`gateway.rpc`,publicExcluded:!0},{...I,name:`sessions.list.baseline.retired`},{...I,name:`sessions.list.retention`,publicExcluded:!0},{...I,name:`sessions.projection.retention`,publicExcluded:!0},{...I,name:`sessions.event.retention`,publicExcluded:!0},{...I,name:`sessions.event.rows.reset`,publicExcluded:!0},{...I,name:`gateway.ws.event`,publicExcluded:!0},{...I,name:`gateway.ws.connections`,publicExcluded:!0},{...I,name:`tool.execution.started`},{...I,name:`tool.execution.completed`,priority:!0},{...I,name:`tool.execution.error`,priority:!0},{...I,name:`tool.execution.blocked`,priority:!0},{...I,name:`skill.used`},{...I,name:`exec.process.completed`},{...I,name:`exec.approval.followup_suppressed`},{...I,name:`message.delivery.started`},{...I,name:`message.delivery.completed`},{...I,name:`message.delivery.error`},{...I,name:`talk.event`},{...I,name:`model.call.started`},{...I,name:`model.call.completed`,priority:!0},{...I,name:`model.call.error`,priority:!0},{...I,name:`model.response.observed`},{...I,name:`run.progress`},{...I,name:`run.execution_phase`},{...I,name:`agent.commentary`},{...I,name:`harness.run.completed`,priority:!0},{...I,name:`harness.run.error`,priority:!0},{...I,name:`context.assembled`},{...I,name:`log.record`,publicExcluded:!0}],Uc=Hc.map(e=>e.name),Wc=Hc.filter(e=>e.priority).map(e=>e.name),Hc.filter(e=>e.publicExcluded).map(e=>e.name)}));function isNonZeroHex(e){return!/^0+$/.test(e)}function isValidDiagnosticTraceId(e){return typeof e==`string`&&Kc.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&qc.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&Jc.test(e)}function normalizeDiagnosticTraceContext(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 getActiveDiagnosticTraceContext(){return Xc.getStore()}var Kc,qc,Jc,Yc,Xc,Zc=__esmMin((()=>{Zt(),cc(),Kc=/^[0-9a-f]{32}$/,qc=/^[0-9a-f]{16}$/,Jc=/^[0-9a-f]{2}$/,Yc=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`),Xc=new AsyncContext(Yc)}));function cloneDiagnosticValueForListener(e,t=!1){if(Qc.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return Qc.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&Qc.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return Qc.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(Qc.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 Qc,$c=__esmMin((()=>{Vc(),Zc(),on(),Qc=/* @__PURE__ */ new WeakSet})),el,tl=__esmMin((()=>{el=`coreModelRequestLifecycle`}));function isTrustedOtelDiagnosticListener(e){return nl.has(e)}var nl,rl=__esmMin((()=>{nl=/* @__PURE__ */ new WeakSet}));function consumeHostPluginUsageDiagnosticEvent(e){let t=il.get(e);return il.delete(e),t}var il,al=__esmMin((()=>{il=/* @__PURE__ */ new WeakMap}));function consumeCoreSemanticRunProgressDiagnosticEvent(e){let t=sl.get(e);return sl.delete(e),t}var ol,sl,cl=__esmMin((()=>{ol=`coreSemanticRunProgress`,sl=/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){let t=ul.events.get(e);return ul.events.delete(e),t}var ll,ul,dl=__esmMin((()=>{cc(),j(),ll=`toolExecutionLiveness`,ul=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new AsyncContext(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}))}));function hasDiagnosticTracePropagationConsumer(){return pl.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=pl.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=pl.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 fl,pl,ml=__esmMin((()=>{j(),Zc(),fl=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),pl=resolveGlobalSingleton(fl,()=>({marker:fl,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`||hl.some(e=>(asFiniteNumber(t?.[e])??0)!==0))}function hasObservedModelUsage(e){return e?.usageReport!==void 0||hasRecordedUsageCost(e?.cost)||hasNonzeroUsage(e)}var hl,gl=__esmMin((()=>{Gt(),k(),hl=[`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 _l=__esmMin((()=>{}));function isDiagnosticFlagEnabled(e,t,n=process.env){let r=t?.diagnostics?.flags??[],i=parseDiagnosticEnvFlags(n[vl]),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 vl,yl=__esmMin((()=>{yt(),Jt(),_l(),vl=`OPENCLAW_DIAGNOSTICS`}));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??bl).includes(r))return!0;if((t.falsy??xl).includes(r))return!1}}var bl,xl,Sl=__esmMin((()=>{yt(),bl=[`true`,`1`,`yes`,`on`],xl=[`false`,`0`,`no`,`off`]})),Cl=__esmMin((()=>{j(),resolveGlobalSingleton(Symbol.for(`openclaw.processEnvironmentKey`),()=>({key:{},aliases:new WeakSet([process.env])}))})),wl,Tl=__esmMin((()=>{Cl(),wl=[`FS_SAFE_PYTHON_MODE`,`OPENCLAW_FS_SAFE_PYTHON_MODE`],[...wl]}));function isTruthyEnvValue(e){return parseBooleanValue(e)===!0}var El=__esmMin((()=>{Sl(),Tl()}));function runWithMainThreadTask(e,t,n){let r=Dl.observer;return r?r.run(e,t,n):t()}var Dl,Ol=__esmMin((()=>{Do(),j(),Dl=resolveGlobalSingleton(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new D}))}));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 kl=__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:Al,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&&Ml.write(r,e,n)}var Al,jl,Ml,Nl=__esmMin((()=>{gl(),j(),yl(),Zc(),El(),Ol(),Al=`openclaw.diagnostics.v1`,jl=65536,new D,new D,Ml=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e,t,n,r=!1,a=!1,s=/* @__PURE__ */ new Set;function append(e,t){try{let n=i(e.path);s.has(n)||(p(n,{recursive:!0}),s.add(n)),ee({filePath:e.path,content:t})}catch(t){e.failedWrites++,a||(a=!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:S(),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>jl&&flush(),r||l>jl?append(e,c):(t?(t.content+=c,t.bytes+=l):t={capture:e,content:c,bytes:l},n??=setImmediate(flush).unref())}}})}));function normalizeDiagnosticWorkerScript(e){return typeof e==`string`&&Il.has(e)?e:`other`}function workerScriptName(e,t=!1){return t||e instanceof URL&&e.protocol!==`file:`?`other`:Fl.get(scriptBasename(e instanceof URL?c(e):e))??`other`}var scriptBasename,Pl,Fl,Il,Ll=__esmMin((()=>{$o(),scriptBasename=e=>r(e).replace(/\.[cm]?[jt]s$/u,`.js`),Pl=createRuntimeProcessEntrypoints(import.meta.url),Fl=/* @__PURE__ */ new Map;for(let e of Object.values(Pl)){let t=scriptBasename(e.distWorkerPath);Fl.set(t,t),Fl.set(scriptBasename(e.sourceModulePath),t)}for(let e of Object.values(Xo)){let t=scriptBasename(e.distWorkerPath);Fl.set(t,t),Fl.set(scriptBasename(e.package.distWorkerPath),t),Fl.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(let e of Object.values(Zo))for(let[t,n]of e.entries){let e=scriptBasename(`${n}.mjs`);Fl.has(e)||Fl.set(e,scriptBasename(Pl[t].distWorkerPath))}Il=new Set(Fl.values())}));function areDiagnosticsEnabledForProcess(){return Wl.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=Rl;if(c?.includePrivateData!==!1&&(l=s?.()??Rl,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&&Ul.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,Bl);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:zl,drainBatchSize:Bl}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=Wl,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?{[ll]:n.toolExecutionLiveness}:{},...n.coreModelRequestLifecycle?{[el]:n.coreModelRequestLifecycle}:{},...n.coreSemanticRunProgress?{[ol]:n.coreSemanticRunProgress}:{},...d?{trustedTraceContext:d}:{}}),p=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(s),m=a&&(n.queuedPhase||Hl.has(s.type));if(m){if(r.asyncQueue.length>=zl){if(!t||!Ul.has(s.type)){noteAsyncDiagnosticDrop(r,{event:s,metadata:f,privateData:u,hostPluginId:c});return}let e=makeRoomForPriorityAsyncDiagnosticEvent(r);e&¬eAsyncDiagnosticDrop(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 Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl=__esmMin((()=>{O(),Wo(),j(),Vc(),Gc(),$c(),tl(),rl(),al(),cl(),dl(),Zc(),ml(),Nl(),Ll(),Rl=Object.freeze({}),zl=1e4,Bl=100,Vl=Symbol.for(`openclaw.diagnosticEvents.state.v1`),Hl=new Set(Uc),Ul=new Set(Wc),Wl=resolveGlobalSingleton(Vl,()=>({marker:Vl,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}))})),Kl=__esmMin((()=>{Lc()}));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))}}}var ql=__esmMin((()=>{Lc(),Kl(),mr(),{...createRuntimeIo()}})),Jl=__esmMin((()=>{j(),resolveGlobalSingleton(Symbol.for(`openclaw.signalExitOwner`),()=>({})),resolveGlobalSet(Symbol.for(`openclaw.signalExitBarriers`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitGates`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitFinalizers`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitObservers`),`close-and-restart`),resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStartupSignals`),()=>({}))}));function isValidTimeZone(e){let t=Yl.get(e);if(t!==void 0)return t;let n;try{new Intl.DateTimeFormat(`en`,{timeZone:e}).format(),n=!0}catch{n=!1}return Yl.set(e,n),n}function resolveEffectiveTimeZone(e){let t=e??process.env.TZ;return t&&isValidTimeZone(t)?t:Zl??=Intl.DateTimeFormat().resolvedOptions().timeZone}function getTimestampParts(e,t){let n=resolveEffectiveTimeZone(t),r=Math.floor(e.getTime()/1e3);if(Ql?.second===r&&Ql.timeZone===n)return Ql.parts;let i=Xl.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`}),Xl.set(n,i));let a={};for(let t of i.formatToParts(e))a[t.type]=t.value;return Ql={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 Yl,Xl,Zl,Ql,$l=__esmMin((()=>{Yl=/* @__PURE__ */ new Map,Xl=/* @__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(M.overrideSettings?.consoleStyle??readLoggingConfig()?.consoleStyle)===`json`?formatJsonConsoleLine(e):e.message}function writeConsoleDiagnosticWarning(e){process.stderr.write(`${formatConsoleDiagnosticLine({level:`warn`,message:e})}\n`)}var eu=__esmMin((()=>{gr(),xo(),mr(),$l()}));function tryParseLogLevel(e){if(typeof e!=`string`)return;let t=e.trim();return tu.includes(t)?t:void 0}function normalizeLogLevel(e,t=`info`){return tryParseLogLevel(e)??t}function levelToMinLevel(e){return nu[e]}function isLogLevelEnabled(e,t){return e!==`silent`&&t!==`silent`&&levelToMinLevel(e)>=levelToMinLevel(t)}var tu,nu,ru=__esmMin((()=>{tu=[`silent`,`fatal`,`error`,`warn`,`info`,`debug`,`trace`],nu={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){M.invalidEnvLogLevelValue=null;return}let t=tryParseLogLevel(e);if(t)return M.invalidEnvLogLevelValue=null,t;M.invalidEnvLogLevelValue!==e&&(M.invalidEnvLogLevelValue=e,writeConsoleDiagnosticWarning(`[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${redactToolPayloadText(e)}" (allowed: ${tu.join(`|`)}).`))}var iu=__esmMin((()=>{yt(),eu(),ru(),xo(),mr()}));function loadResolveSecureTempRoot(){if(ou)return ou;let e=getSealedRuntimeSecureTempRoot();if(e)return ou=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 ou=process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@openclaw/fs-safe/secure-temp-root`).resolveSecureTempRoot,ou}function assertSafeTempAncestors(e,t){let r=t.platform??process.platform;if(r===`win32`||r===`android`)return;let i=process.getBuiltinModule(`fs`),a=t.lstatSync??i.lstatSync,s=t.lstatSync&&t.lstatSync!==i.lstatSync?n.resolve(e):i.realpathSync.native(e);for(let e=n.dirname(s);;e=n.dirname(e)){let t=a(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(n.dirname(e)===e)return}}function resolvePreferredOpenClawTmpDir(e={}){let t=loadResolveSecureTempRoot(),r={...e,preferredDir:e.preferredDir??`/tmp/openclaw`,fallbackPrefix:`openclaw`,warningPrefix:`[openclaw]`,unsafeFallbackLabel:`OpenClaw temp dir`,skipPreferredOnWindows:!0},i=t(r);if(e.purpose===`coordination`)return i;let a;try{return assertSafeTempAncestors(i,e),i}catch(e){a=e}let s=e.stateDir??resolveStateDir();try{let i=t({...r,preferredDir:void 0,tmpdir:()=>n.join(s,`tmp`)});return assertSafeTempAncestors(i,e),(e.warn??console.warn)(`[openclaw] ${String(a)} Using private state temp dir: ${i}`),i}catch(e){throw Error(`No safe OpenClaw temp root is available. Default root: ${String(a)} State fallback ${JSON.stringify(s)}: ${String(e)}`,{cause:e})}}var au,ou,su=__esmMin((()=>{Kn(),cn(),au=`/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 cu=__esmMin((()=>{}));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 lu,uu,du=__esmMin((()=>{lu=`openclaw`,uu=`.log`}));function detachEmptyGroup(e){e.pending.size>0||(fu.lastGroup===e&&(fu.lastGroup=void 0),process.removeListener(`exit`,e.dispatch))}function registerProcessExitCleanup(e){let t={close:e},n=fu.lastGroup;if(!n||process.listeners(`exit`).at(-1)!==n.dispatch){let e=/* @__PURE__ */ new Set([t]),r={pending:e,dispatch:()=>{let t=[...e];e.clear(),detachEmptyGroup(r);for(let e of t)try{e.close()}catch{}}};process.on(`exit`,r.dispatch),fu.lastGroup=n=r}else n.pending.add(t);let r=n;return()=>{r.pending.delete(t),detachEmptyGroup(r)}}var fu,pu=__esmMin((()=>{j(),fu=resolveGlobalSingleton(Symbol.for(`openclaw.processExitCleanup`),()=>({}))}));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 mu=__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)}function createLazyRuntimeNamedExport(e,t){return createLazyRuntimeSurface(e,e=>e[t])}var hu=__esmMin((()=>{mu()}));function rotatedLogPath(e,t){let r=n.extname(e);return`${e.slice(0,e.length-r.length)}.${t}${r}`}function ensureLogDirectorySync(e,t=!0,r=511){try{u.mkdirSync(e,{mode:r})}catch(i){let a=extractErrorCode(i);if(a===`EEXIST`&&u.statSync(e).isDirectory())return;let s=n.dirname(e);if(!t||a!==`ENOENT`||s===e)throw i;ensureLogDirectorySync(s,!0,r),ensureLogDirectorySync(e,!1,r)}}function rotateLogFile(e){try{ensureLogDirectorySync(n.dirname(e)),u.rmSync(rotatedLogPath(e,gu),{force:!0});for(let t=4;t>=1;--t){let n=rotatedLogPath(e,t);u.existsSync(n)&&u.renameSync(n,rotatedLogPath(e,t+1))}return u.existsSync(e)&&u.renameSync(e,rotatedLogPath(e,1)),!0}catch{return!1}}function pruneOldRollingLogs(e){try{let t=u.readdirSync(e,{withFileTypes:!0}),r=Date.now()-_u;for(let i of t){if(!i.isFile()||!i.name.startsWith(`openclaw-`)||!i.name.endsWith(`.log`))continue;let t=n.join(e,i.name);try{u.statSync(t).mtimeMs<r&&u.rmSync(t,{force:!0})}catch{}}}catch{}}function prepareFileLogTarget(e,t){ensureLogDirectorySync(n.dirname(e)),t&&pruneOldRollingLogs(n.dirname(e))}function resolveDefaultFileLogTarget(e,t){return ensureLogDirectorySync(t.stateDir,!0,448),n.join(resolvePreferredOpenClawTmpDir({preferredDir:n.join(t.stateDir,`logs`),tmpdir:()=>n.join(t.stateDir,`tmp`),stateDir:t.stateDir}),e)}async function executeFileLogIO(e){switch(e.type){case`resolveDefault`:return resolveDefaultFileLogTarget(e.file,e.root);case`prepare`:return prepareFileLogTarget(e.file,e.rolling);case`size`:try{return u.statSync(e.file).size}catch{return 0}case`append`:{let t=e.rotate?rotateLogFile(e.file)?`rotated`:`failed`:`none`;try{return ee({filePath:e.file,content:e.payload}),{rotation:t,appended:!0}}catch{return{rotation:t,appended:!1}}}}}var gu,_u,vu=__esmMin((()=>{O(),su(),du(),gu=5,_u=864e5})),yu,bu,xu,Su=__esmMin((()=>{yu=Symbol.for(`openclaw.cliRespawnParent`),bu=`OPENCLAW_CLI_RESPAWN_PARENT`,xu=process.env[bu],delete process.env[bu],xu===String(process.ppid)&&(globalThis[yu]={pid:process.ppid})}));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)}var Cu=__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:r=!1}){let i=e??t;if(!n.isAbsolute(i))return;let a=n.dirname(i),s=n.join(a,`manifest.json`),c;try{c=h(s,`utf8`)}catch(e){if(e?.code===`ENOENT`||e?.code===`ENOTDIR`)return;throw e}let l;try{l=JSON.parse(c)}catch(e){throw Error(`Invalid standalone runtime manifest: ${s}`,{cause:e})}let nonBlank=e=>typeof e==`string`&&e.trim().length>0;if(l?.schemaVersion!==1||![`jit`,`bytecode`,`aot`].includes(l.mode)||!nonBlank(l.executable?.path)||!nonBlank(l.runtime?.path)||!nonBlank(l.openclaw?.version)||!nonBlank(l.bun?.version))throw Error(`Invalid standalone runtime manifest: ${s}`);let u=n.relative(a,n.resolve(a,l.executable.path)),d=n.relative(a,n.resolve(a,l.runtime.path));if(n.isAbsolute(l.executable.path)||!u||u===`..`||u.startsWith(`..${n.sep}`)||e&&n.resolve(a,l.executable.path)!==n.resolve(e)||t&&n.resolve(a,l.runtime.path)!==n.resolve(t)||n.isAbsolute(l.runtime.path)||!d||d===`..`||d.startsWith(`..${n.sep}`))throw Error(`Invalid standalone runtime manifest: ${s}`);return{schemaVersion:1,mode:l.mode,executable:{path:l.executable.path,...nonBlank(l.executable.sha256)?{sha256:l.executable.sha256}:{}},runtime:{path:l.runtime.path,...nonBlank(l.runtime.sha256)?{sha256:l.runtime.sha256}:{}},openclaw:{version:l.openclaw.version,...nonBlank(l.openclaw.commit)?{commit:l.openclaw.commit}:{}},bun:{version:l.bun.version},...r?projectStandaloneBuildInfo(l):{}}}function getEmbeddedStandaloneRuntimeRoot(){let e=globalThis.__openclawStandaloneRootUrl;return typeof e==`string`?c(e):void 0}function isEmbeddedStandaloneModule(e){let t=e.startsWith(`file:`)?c(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?n.resolve(n.dirname(e),t.runtime.path):void 0}function isStandaloneRuntimeExecutable(e=process.execPath){return resolveStandaloneSidecarRoot(e)!==void 0}function resolveRuntimeScriptEnv(e){return isStandaloneRuntimeExecutable()?{...e,BUN_BE_BUN:`1`}:{...e}}var wu,Tu=__esmMin((()=>{Su(),wu=Symbol.for(`openclaw.windowsNativeRedirectStartup`),process.platform===`win32`&&!process.versions.bun&&(globalThis[wu]??=Object.freeze({execArgv:Object.freeze([...process.execArgv]),appRoot:process.env.OPENCLAW_NATIVE_APP_ROOT,stagedRoot:process.env.OPENCLAW_NATIVE_STAGED_ROOT}))})),Eu,Du=__esmMin((()=>{$o(),Eu=createRuntimeProcessEntrypoints(import.meta.url)}));function resolveRuntimeProcessDistRoot(e){let t=e.replaceAll(n.sep,`/`).lastIndexOf(`/dist/`);return t>=0?e.slice(0,t+6):void 0}var Ou=__esmMin((()=>{resolveRuntimeProcessDistRoot(c(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)||ku.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(ju.has(u)){let s=a<0?e[++n]??``:r.slice(a+1),c=!i&&u===`--test-reporter`&&/^(?:dot|spec|tap)$/.test(s);!Au.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=Mu.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 ku,Au,ju,Mu,Nu=__esmMin((()=>{ku=/^node(?:-\d+|\d+)(?:\.\d+)*(?:\.exe)?$/,Au=/* @__PURE__ */ new Set([`-r`,`--preload`,`--require`,`--import`,`--loader`,`--experimental-loader`,`--test-reporter`,`--test-global-setup`]),ju=/* @__PURE__ */ new Set([...Au,`-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`]),Mu=/* @__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 l(n.join(e.root,`dist`,e.distWorkerPath));let t=c(e.currentModuleUrl),r=resolveRuntimeProcessDistRoot(t);if(r!==void 0){let t=e.distWorkerPath;if(e.package){let i=n.resolve(r,`..`),a=Qe({rootDir:i,relativePath:`package.json`,boundaryLabel:`runtime worker package`,rejectHardlinks:!1});if(!a.ok)throw Error(`Cannot resolve runtime worker package: ${i}/package.json`);a.value.name===e.package.name&&(t=e.package.distWorkerPath)}return l(n.join(r,t))}let i=e.sourceExtension??(n.extname(t)||`.js`);return new URL(`./${e.sourceWorkerName}${i}`,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=c(e);return runtimeNeedsTypeScriptLoader(n,t)?[`--import`,import.meta.resolve(`tsx`),n]:[...resolveRuntimeArgs(t),n]}function resolveRuntimeWorkerThreadExecArgv(e,t=process.execPath){return typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD?[]:e.protocol===`file:`&&runtimeNeedsTypeScriptLoader(c(e),t)?[`--import`,import.meta.resolve(`tsx/esm`)]:[]}var Pu=__esmMin((()=>{Tu(),Ou(),Nu()}));function resolveRuntimeProcessEntrypointUrl(e){return Fu.get(e)??resolveRuntimeWorkerUrl(Eu[e])}var Fu,Iu=__esmMin((()=>{Tu(),Du(),$o(),Pu(),Fu=/* @__PURE__ */ new Map}));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=D.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 flatMapRetainedOperation(e,t){let n;return driveRetainedOperation(e,(r,i)=>{if(!n){e.service();let r=e.read();if(r.status===`pending`)return;if(r.status===`rejected`)throw r.error;n=t(r.value),n.result.then(i,i)}n.service();let a=n.read();a.status===`fulfilled`?r.resolve(a.value):a.status===`rejected`&&r.reject(a.error)})}var Lu=__esmMin((()=>{}));function createWorkerComputeCapacity(e){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`compute capacity must be a positive safe integer`);let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=0,a=0,s=!1,canAdmit=e=>i<128&&a+e<=268435456,requestCheckpoints=()=>{let e=n.size;if(e){for(let n of t)if(n.requestCheckpoint()&&--e===0)break}},drain=()=>{if(!s){s=!0;try{for(;t.size<e&&n.size;){let e=n.values().next().value;n.delete(e),e()}}finally{s=!1}requestCheckpoints()}};return{getSnapshot:()=>({limit:e,active:t.size,waitingPools:n.size,pendingTasks:i,pendingBytes:a}),canAdmit,subscribeAdmission(e){return r.add(e),()=>r.delete(e)},admit(e){return canAdmit(e)?(i++,a+=e,!0):!1},finish(e){i--,a-=e;for(let e of r)e()},acquire(r,i){if(t.size>=e||!s&&n.size){n.add(r),requestCheckpoints();return}let a={requestCheckpoint:i};return t.add(a),a},release(e){t.delete(e),drain()},remove(e){n.delete(e)},requestCheckpoints}}var Ru,zu=__esmMin((()=>{Ru=268435456}));function workerTaskUnavailableError(e,t,n,r=e.task){let i=e.ready===!1?`startup`:r?.exchange?`exchange`:`running`,a=r?.diagnosticLabel?` [task=${r.diagnosticLabel} admittedInputBytes=${r.inputBytes} exchanges=${r.exchangeSequence} stage=${i}]`:``;return new WorkerTaskError(t+a,`unavailable`,{cause:n})}function workerTaskRetirementError(e,t){return e?AggregateError([e,t],`Worker retirement failed: ${toErrorObject(t,`worker retirement failed`).message}; task failed: ${e.message}`,{cause:t}):t}function workerTaskTimeoutError(e,t){let n=e?.sent===!1?e.name:void 0;n===`unknown`&&(n=t.protocol===`file:`?t.pathname.split(`/`).at(-1)?.slice(0,96)||`worker`:`${t.protocol} worker`);let r=new WorkerTaskError(n?`worker task timed out waiting for host callback ${n}`:`worker task timed out`,`timeout`);return n&&process.emitWarning(r.message,{code:`WORKER_HOST_CALLBACK_TIMEOUT`}),r}var WorkerTaskError,Bu=__esmMin((()=>{O(),WorkerTaskError=class extends Error{constructor(e,t,n){super(e,n),this.code=t,this.name=`WorkerTaskError`,this.capacityAvailable=n?.capacityAvailable}}}));function enqueueWorkerTask(e,t){let n=t.options.pointRead?e.findIndex(e=>!e.options.pointRead):-1;e.splice(n===-1?e.length:n,0,t)}var WorkerTaskAdmission,Vu=__esmMin((()=>{zu(),Bu(),WorkerTaskAdmission=class{constructor(e,t,n){this.maxPendingTasks=e,this.maxPendingBytes=t,this.shared=n,this.taskCount=0,this.byteCount=0,this.closed=!1,this.waiters=/* @__PURE__ */ new Map,this.notify=()=>{for(let[e,t]of this.waiters)(this.closed||this.taskCount<this.maxPendingTasks&&this.byteCount+e<=this.maxPendingBytes&&(!this.shared||this.shared.canAdmit(e)))&&(this.waiters.delete(e),t.resolve());this.waiters.size||(this.stopWatchingCapacity?.(),this.stopWatchingCapacity=void 0)};for(let[n,r]of Object.entries({maxPendingTasks:e,maxPendingBytes:t}))if(!Number.isSafeInteger(r)||r<1)throw RangeError(`${n} must be a positive safe integer`)}get pendingTasks(){return this.taskCount}get pendingBytes(){return this.byteCount}admitTask(e,t){let{pointRead:n,onRequest:r,onRequestSync:i}=e.options;if(n)return r||i?/* @__PURE__ */ TypeError(`Point reads carry their facts and cannot call back into the host`):void 0;let a=this.admit(e.inputBytes,t);return e.admitted=a===void 0,a}admit(e,t){let n;if(this.taskCount>=this.maxPendingTasks)n=`pool pending tasks: pendingTasks=${this.taskCount} maxPendingTasks=${this.maxPendingTasks} inputBytes=${e}`;else if(this.byteCount+e>this.maxPendingBytes)n=`pool pending bytes: pendingBytes=${this.byteCount} maxPendingBytes=${this.maxPendingBytes} inputBytes=${e}`;else if(this.shared&&!this.shared.admit(e)){let{pendingTasks:t,pendingBytes:r}=this.shared.getSnapshot();n=t>=128?`shared compute pending tasks: pendingTasks=${t} maxPendingTasks=128 inputBytes=${e}`:`shared compute pending bytes: pendingBytes=${r} maxPendingBytes=${Ru} inputBytes=${e}`}else{this.taskCount++,this.byteCount+=e;return}let r=t();return new WorkerTaskError(`worker task capacity reached [${r?`task=${r} `:``}${n}]`,`overloaded`,{capacityAvailable:this.waitForCapacity(e)})}finish(e){this.taskCount--,this.byteCount-=e,this.shared?.finish(e),this.notify()}close(){this.closed=!0,this.notify()}waitForCapacity(e){if(e>this.maxPendingBytes||this.shared&&e>268435456)return;let t=this.waiters.get(e);if(t)return t.promise;let n=Promise.withResolvers();return this.waiters.set(e,n),this.stopWatchingCapacity??=this.shared?.subscribeAdmission(this.notify),this.notify(),n.promise}}}));function captureWorkerTaskContext(){let e=new je(`OpenClaw.WorkerTask`);return t=>e.runInAsyncScope(t)}var Hu=__esmMin((()=>{}));function serviceNativeWorkerPass(e,t){let n=[];for(let e of t)e.native&&n.push(e.native);e.serviceNativeWorkers(n)}var Uu=__esmMin((()=>{}));function createWorkerTaskPoolBootstrap(e,t,n){let r,admissionError=()=>r&&![...e].some(e=>e.ready===!0&&!e.retiring&&!e.retirementFailed)?r:void 0,rejectQueued=()=>{let e=admissionError();if(!e)return;let r=t.splice(0);for(let t of r)n(t,e)};return{error:()=>r,get admissionError(){return admissionError()},fail(e){r??=e,rejectQueued()},rejectQueued,reset:()=>{r=void 0}}}var Wu=__esmMin((()=>{}));function createWorkerHostExchange(e,t){let n=isRecord(t)?t.kind??t.type:t;return e.exchange={id:++e.exchangeSequence,name:typeof n==`string`&&/^[a-zA-Z][a-zA-Z0-9._:-]{0,95}$/.test(n)?n:`unknown`,pressure:new AbortController,sent:!1,onConsumed:void 0}}function dispatchOwnedWorkerRequest(e,t,n,r,i){let a={signal:(e.controller??=new AbortController).signal,yieldSignal:r.pressure.signal},assertCurrent=()=>{if(e.done||t.task!==e)throw new WorkerTaskError(`worker task closed before host dispatch`,`unavailable`)};if(e.options.onRequestSync)try{assertCurrent(),i.accept(e.options.onRequestSync(n,a))}catch(e){i.reject(e)}else Promise.resolve().then(()=>(assertCurrent(),e.options.onRequest(n,a))).then(i.accept).catch(i.reject)}async function joinOwnedWorkerTasks(e){let t=(await Promise.allSettled(e)).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Worker task cleanup failed`)}function joinOwnedWorkerTask(e,t,n=!1){return startJoinOwnedWorkerTask(e,t,n).result}function startJoinOwnedWorkerTask(e,t,n){let r=startCloseOwnedWorkerTask(e,t,n),observe=()=>{let n=r.read();if(n.status===`pending`)return n;if(n.status===`rejected`&&e.owner?.closing===r&&(e.owner.closing=void 0),e.owner?.closed){let n=e.slot;e.slot=void 0,t.release(e,n)}return n},i=r.result.then(()=>{observe()},e=>{throw observe(),e});return i.catch(()=>void 0),{result:i,read:observe,service(){r.service(),observe()}}}function closeOwnedWorkerTask(e,t,n=!1){return startCloseOwnedWorkerTask(e,t,n).result}function startCloseOwnedWorkerTask(e,t,n){let r=e.owner;if(!r||r.closed){if(r?.closing)return r.closing;let e=createRetainedOperation(()=>{});return e.resolve(),e.operation}if(r.retire||=n,r.closing)return r.closing;let i,a,s=!1,c=createRetainedOperation(()=>{i?.service(),advance()}),advance=()=>{if(!(s||c.operation.read().status!==`pending`)){s=!0;try{if(e.preparation){a!==e.preparation.promise&&(a=e.preparation.promise,a.then(advance,c.reject));return}let n=e.slot;if(n&&r.retire){i||(i=t.retire(n),i.result.then(advance,advance));let e=i.read();if(e.status===`pending`)return;if(e.status===`rejected`)throw e.error}t.detach(e);try{r.complete?.()}finally{r.closed=!0,r.complete=void 0,r.onCloseError=void 0,e.input=void 0,e.options={},e.abort=()=>{}}c.resolve()}catch(e){r.onCloseError?.(e),c.reject(e)}finally{s=!1}}};return r.closing=c.operation,e.done||t.cancel(e),advance(),c.operation}function retainWorkerTask(e,t,n){return{result:e.promise,read:()=>e.read(),service:n,release:r=>{let i=startJoinOwnedWorkerTask(e,t,r?.retire===!0);return{result:i.result,read:()=>i.read(),service:()=>{n(),i.service()}}}}}function prepareWorkerTaskInput(e,t,n,r){let i=e.input;e.input=void 0;let a=Promise.withResolvers();e.preparation=a;let finishPreparation=()=>{a.resolve(),e.preparation===a&&(e.preparation=void 0)},failed=e=>{finishPreparation(),n(e)},s;try{s=typeof i==`function`?i():i}catch(e){failed(e);return}r&&(s=Promise.resolve(s).then(async e=>(await r(),e)));let ready=e=>{finishPreparation(),t(e)};isPromiseLike(s)?Promise.resolve(s).then(ready,failed):ready(s)}function armWorkerTaskTimeout(e,t,n,r){if(t===void 0||r&&(e.options.timeoutFrom??`enqueue`)!==r)return;clearTimeout(e.timer);let i=performance.now();e.deadline=Math.min(e.options.hostTimeout!==`owner`&&e.options.timeoutMs!==void 0?e.deadline??(e.options.timeoutFrom===`dispatch`?i:e.enqueuedAt)+resolveTimerTimeoutMs(e.options.timeoutMs,6e4):1/0,i+resolveTimerTimeoutMs(t,6e4)),e.timer=setTimeout(n,Math.max(0,e.deadline-i),e)}function expireWorkerTasks(e,t,n){let r=performance.now(),i=[...e,...[...t].flatMap(e=>e.task?[e.task]:[])];for(let e of i)!e.done&&e.deadline!==void 0&&r>=e.deadline&&n(e)}var Gu=__esmMin((()=>{Gt(),ss(),k(),Lu(),Bu()}));function joinWorkerTaskPreparationCleanups(e,t){return joinOwnedWorkerTasks([...[...e.preparationCleanups].map(([t,n])=>n.finally(()=>{e.preparationCleanups.delete(t)&&e.releaseAdmission(t)})),t.then(()=>void 0)])}function notifyExecutionSettled(e){try{e.executionNotified||(e.executionNotified=!0,e.options.onExecutionSettled?.({retired:e.slot?.retired===!0}))}catch(e){return toErrorObject(e,`worker settlement receipt failed`)}}function createWorkerTaskCompletion(e,t,n,r){let i=e.slot,a=i?.native,s=a?.taskChannelFailure,c=i&&a&&s&&n&&(n===s||n.cause===s)?()=>{let t=a.terminalFailure;return t?workerTaskUnavailableError(i,String(t),t,e):a.executionStopped?workerTaskUnavailableError(i,`${s.message}; worker exited with code ${a.executionExitCode}`,s,e):n}:void 0;e.owner&&c&&(e.owner.onCloseError=t=>e.reject(workerTaskRetirementError(c(),t)));let l=e.owner?void 0:e.preparation,u,complete=()=>{!e.owner&&!l&&t.releaseAdmission(e);let i=c?.()??n;try{return completeWorkerTask(e,t,i,r,u)}finally{e.owner&&c&&e.reject(i)}};if(!l)return{complete,resolveFailure:c};let d=Promise.withResolvers();return t.preparationCleanups.set(e,d.promise),d.promise.catch(()=>void 0),{resolveFailure:c,complete:()=>{u=e.runInContext(()=>notifyExecutionSettled(e)),n&&e.reject(c?.()??n),l.promise.then(()=>{let n=complete();if(n)throw n;t.preparationCleanups.delete(e),t.releaseAdmission(e),d.resolve()}).catch(d.reject)}}}function completeWorkerTask(e,t,n,r,i){return e.runInContext(()=>{let a=n??i,s=i?[i]:[];try{e.inputConsumed||(e.inputConsumed=!0,e.options.onInputConsumed?.());let t=e.exchange?.onConsumed;e.exchange=void 0,t?.()}catch(e){let t=toErrorObject(e,`worker input release failed`);s.push(t),a??=t}let c=notifyExecutionSettled(e);c&&(s.push(c),a??=c);let l=e.computePermit;if(e.computePermit=void 0,l&&t.releaseCompute(l),Ku.hasSubscribers){let n=performance.now();Ku.publish({...t.diagnostics(),outcome:a?`failed`:`ok`,queueMs:(e.startedAt??n)-e.enqueuedAt,preparationMs:e.startedAt===void 0?0:(e.preparedAt??n)-e.startedAt,runMs:e.preparedAt===void 0?0:n-e.preparedAt,transferMs:e.transferMs,hostWaitMs:e.hostWaitMs})}let u=s[0],d=s.length>1?AggregateError(s,`Worker task cleanup failed`,{cause:u}):u;if(e.owner){if(d)throw d}else a?e.reject(a):e.resolve(r);return d})}var Ku,qu=__esmMin((()=>{O(),Bu(),Gu(),Ku=_e(`openclaw.worker.task`)}));function startCloseWorkerPoolResources(e,t,n,r,i,a,s){let c=[...e].map(e=>{if(e.retiring)return e.retiring;if(e.native?.executionStopped)return n(e);let c=e.worker;if(!c){let e=createRetainedOperation(()=>{});return e.resolve(),e.operation}let l=t.get(c)??{pending:0};return l.pending++,t.set(c,l),c.ref(),startCloseWorkerTaskResources(e,c,l,i,a,n,r,s)}),l=createRetainedOperation(()=>{for(let e of c)e.service();advance()}),advance=()=>{let e=c.map(e=>e.read());if(e.some(e=>e.status===`pending`))return;let t=e.flatMap(e=>e.status===`rejected`?[e.error]:[]);t.length?l.reject(AggregateError(t,`Worker resource cleanup failed`)):l.resolve()};for(let e of c)e.result.then(advance,advance);return advance(),l.operation}function observeResourceWorkerExit(e,t,n){let r=t.exit;if(!r){let n=/* @__PURE__ */ new Set;r={waiters:n,receive:()=>{for(let e of n)e()}},t.exit=r,e.once(`exit`,r.receive)}return r.waiters.add(n),()=>{r.waiters.delete(n),r.waiters.size||(e.removeListener(`exit`,r.receive),t.exit===r&&(t.exit=void 0))}}function startCloseWorkerTaskResources(e,t,n,r,i,a,s,c){let{port1:l,port2:u}=s(()=>new be),d=D.snapshot(),f=!1,p=!1,m,h=createRetainedOperation(()=>{if(f)return;for(e.native?.service(),e.native?.executionStopped&&(p=!0,m??=e.retiring??a(e));;){let e=Ee(l);if(!e||f)break;receive(e.message)}let t=m??e.retiring;if(p&&t){t.service();let e=t.read();e.status===`fulfilled`?finish():e.status===`rejected`&&finish(toErrorObject(e.error,`Worker resource cleanup retirement failed`))}}),finish=r=>d(()=>{f||(f=!0,g(),l.close(),u.close(),n.pending--,n.pending||e.task||e.retiring||t.unref(),r?h.reject(r):h.resolve(),d=s)}),receive=e=>d(()=>{c?.();try{if(isRecord(e)&&e.ok===!0){finish();return}let t=isRecord(e)&&e.detail!==void 0&&i?.decodeResourceError?i.decodeResourceError(e.detail):Error(isRecord(e)&&typeof e.error==`string`?e.error:`Invalid worker resource cleanup receipt`);finish(t)}catch(e){finish(toErrorObject(e,`Worker resource cleanup receipt could not be decoded`))}}),g=observeResourceWorkerExit(t,n,()=>finish());l.once(`message`,receive),l.once(`messageerror`,e=>finish(toErrorObject(e,`Worker resource cleanup receipt could not be decoded`))),l.once(`close`,()=>{if(f)return;let t=e.retiring;t?(p=!0,m=t,t.result.then(()=>finish(),e=>finish(toErrorObject(e,`Worker resource cleanup retirement failed`)))):finish(/* @__PURE__ */ Error(`Worker resource cleanup closed without a receipt`))});try{t.postMessage({closeResource:!0,key:r,resourcePort:u},[u])}catch(e){finish(toErrorObject(e,`Worker resource cleanup could not be sent`))}return h.operation}var Ju=__esmMin((()=>{O(),k(),Lu()}));function isWorkerIdleForPressure(e,t=!1){return e!==void 0&&(t||performance.now()-e>=1e3)}function createWorkerIdleTimers(e){let t=setTimeout,n=clearTimeout;return{clear(e){n(e.idleTimer),e.idleTimer=void 0},arm(n,r,i){n.idleTimer||(n.idleTimer=e(()=>t(()=>{n.idleTimer=void 0,i()},r)),n.idleTimer.unref())}}}function createWorkerTaskPoolRetirement({slots:e,options:t,retainOneIdleWorker:n,runInContext:r,dispatch:i,onRotationComplete:a,serviceDeadlines:s,markWorkerRetirement:c,serviceHost:l}){let u=/* @__PURE__ */ new Map,d=-1/0,f,p=-1/0,m,h,g=!1,_=createWorkerIdleTimers(r),v=performance.now.bind(performance),y=n?/* @__PURE__ */ new Set:void 0;function newestIdle(){if(!y)return;let e;for(let t of y)e=t;return e}function clearIdle(e){e.idleSince=void 0,y?.delete(e),_.clear(e)}let isBurstSlot=n=>{if(t.burstIdleTimeoutMs!==void 0){for(let t of e)if(!t.retiring&&!t.retirementFailed)return t!==n}return!1};function startRotate(){if(h)return h;let t=D.snapshot(),n,r,c=!1,u=createRetainedOperation(()=>{serviceNativeWorkerPass(l,f),s();for(let e of n??[])e.service();r?.service(),advance()});h=u.operation,g=!1;let f=[...e],m=f.flatMap(e=>e.task?[e.task]:[]),advance=()=>t(()=>{if(!(c||u.operation.read().status!==`pending`)){c=!0;try{if(m.some(e=>e.read().status===`pending`))return;if(!n){n=f.map(e=>startRetire(e,`rotation`));for(let e of n)e.result.then(advance,advance)}for(let e of n){let t=e.read();if(t.status===`rejected`)throw t.error;if(t.status===`pending`)return}r||(r=startJoinArtifacts(),r.result.then(advance,advance));let e=r.read();if(e.status===`pending`)return;if(e.status===`rejected`)throw e.error;d=-1/0,p=-1/0,h=void 0,a(),u.resolve(),i()}catch(e){h=void 0,g=!0,u.reject(e)}finally{c=!1}}});for(let e of m)e.promise.then(advance,advance);return advance(),u.operation}function startRetire(n,a=`closed`){if(a===`idle_timeout`&&(isBurstSlot(n)?p=v():d=v()),f===n&&(f=void 0),m===n&&(m=void 0),n.worker&&c(n.worker,a),clearIdle(n),cancelWorkerNativeSections(n.nativeSections),n.retiring)return n.retiring;let s=D.snapshot(),h,g,_=!1,y=!1,b=createRetainedOperation(()=>{h?.service(),advance()}),advance=()=>s(()=>{if(!(y||b.operation.read().status!==`pending`)){y=!0;try{if(n.creating)return;if(!areWorkerNativeSectionsSettled(n.nativeSections)){_||(_=!0,Promise.resolve(waitForWorkerNativeSections(n.nativeSections)).then(advance,b.reject));return}if(n.worker&&!h){c(n.worker,a);try{if(g===void 0&&(g=l.flushWorkerDiagnostics?.(n.worker,a)??null,g?.result.then(advance,advance)),g?.service(),g?.read().status===`pending`)return}catch{g=null}if(n.native)h=n.native.stop();else{let e=createRetainedOperation(()=>{});h=e.operation,Promise.resolve().then(()=>n.worker.terminate()).then(()=>e.resolve(),e.reject)}if(l.workerStopped){let e=n.worker;h=flatMapRetainedOperation(h,()=>{let t=createRetainedOperation(()=>{}),n=l.workerStopped?.(e);return n?n.then(()=>t.resolve(),t.reject):t.resolve(),t.operation})}h.result.then(advance,advance)}let t=h?.read();if(t?.status===`pending`)return;if(t?.status===`rejected`)throw t.error;n.retired=!0;let s=n.releaseResources;s&&r(()=>{let e=(async()=>{try{await s()}catch(e){try{process.emitWarning(`Worker task resource release failed: ${String(e)}`)}catch{}}})(),t=createRetainedOperation(()=>{});u.set(e,t.operation),e.then(()=>{u.delete(e),t.resolve()},t.reject)}),n.worker?.removeAllListeners(),e.delete(n);for(let e of n.completions??[])e();n.completions=void 0,i(),b.resolve()}catch(e){try{Promise.resolve(t.onRetirementFailure?.(e)).catch(()=>void 0)}catch{}n.retirementFailed=!0,n.retiring=void 0,b.reject(e)}finally{y=!1}}});return n.retiring=b.operation,Promise.resolve().then(advance),b.operation}function retire(e,t){return startRetire(e,t).result}function startJoinArtifacts(){let e=[...u.values()],t=createRetainedOperation(()=>{for(let t of e)t.service();advance()}),advance=()=>{let n=e.map(e=>e.read()),r=n.find(e=>e.status===`rejected`);r?.status===`rejected`?t.reject(r.error):n.every(e=>e.status===`fulfilled`)&&t.resolve()};for(let t of e)t.result.then(advance,advance);return advance(),t.operation}async function retryFailedRetirements(){let t=await Promise.allSettled([...e].filter(e=>e.retirementFailed).map(e=>retire(e)));t.push(...await Promise.allSettled(u.keys()));let n=t.flatMap(e=>e.status===`rejected`?[toErrorObject(e.reason,`worker retirement retry failed`)]:[]),r=n[0];if(r)throw n.length===1?r:AggregateError(n,`Worker retirement retries failed`,{cause:r})}function idle(e,n=0){let r=isBurstSlot(e),i=(r?t.burstIdleTimeoutMs:t.idleTimeoutMs)??6e4;if(e.idleSince??=v()-n,i<=0)return;if(y&&!y.has(e)){let t=newestIdle();y.add(e),t&&!t.idleTimer&&retire(t,`idle_timeout`).catch(()=>void 0)}!r&&!f&&v()-d<Yu&&(f=e),r&&(!m||!isBurstSlot(m))&&v()-p<Yu&&(m=e);let a=r?v():0,s=r?m===e?i*3:i:f===e?Math.max(i,Yu):i;_.arm(e,Math.max(0,s-n),()=>{newestIdle()!==e&&(r&&!isBurstSlot(e)?idle(e,v()-a):retire(e,`idle_timeout`).catch(()=>void 0))})}return{get preferredIdle(){return newestIdle()},get dispatchAllowed(){return h===void 0&&!g},startRotate,retire,startRetire,service(){let t=[...e];for(let e of t)e.retiring?.service();h?.service()},clearIdle,idle,retireIdle(t,n=!1){for(let r of e)!r.task&&!r.retiring&&!r.retirementFailed&&r.worker&&isWorkerIdleForPressure(r.idleSince,n)&&!t.get(r.worker)?.pending&&retire(r,`memory_pressure`).catch(()=>void 0)},retryFailedRetirements,joinArtifacts:()=>startJoinArtifacts().result}}var Yu,Xu=__esmMin((()=>{O(),Lu(),Uu(),Ts(),Yu=3e5}));function sendWorkerTaskInput(e){let{slot:t,task:n,input:r}=e;if(n.done)return;n.preparedAt=performance.now();let i=e.bootstrapError();if(i&&!t.worker)e.refuse(i);else try{let i=t.worker;if(!i){t.creating=!0;try{i=e.createWorker()}catch(t){e.fail(t,!0);return}finally{t.creating=!1}}let a=n.options.transferList?.(r);if(!n.done){let s=e.host.captureTaskContext(i),c=[...a??[],...e.host.taskContextTransferList?.(s)??[]],l=performance.now(),u=n.options.progressSignal;i.postMessage({input:r,taskId:n.id,interactive:!!(n.options.onRequest||n.options.onRequestSync||n.options.onNotification),nativeSections:t.nativeSections.buffer,...u?{progressSignal:u}:{},taskContext:s,sampleMemory:!0},c),n.transferMs+=performance.now()-l}}catch(t){e.fail(t)}}function createWorkerTaskPoolWorker(e){let{slot:t,options:n}=e,r=e.host.captureWorkerStartObserver?.(n.workerUrl),i=e.runInContext(()=>{let r=n.prepareWorker?.();t.releaseResources=r?.releaseResources;let i=r?.temporaryDirectory;if(i){let n=e.host.prepareResources(),r=t.releaseResources;t.releaseResources=async()=>{try{await n,await e.host.releaseTemporaryDirectory(i)}finally{await r?.()}}}let a=n.workerUrl,s={...n.workerOptions,...r?.options};e.host.requiresReady&&(t.ready=!1);let c=e.host.createWorker(a,s);return t.native=c.native,c.worker}),a=!1,started=()=>{a||(a=!0,e.onStarted(i),r?.(),r=void 0)};return t.native?(t.native.on(`started`,started),t.native.on(`execution-exit`,n=>{releaseWorkerNativeSectionsOnExit(t.nativeSections),t.retiring||e.onFailure(e.unavailableError(`worker exited with code ${n}`),!0)})):started(),t.worker=i,i.on(`message`,n=>{if(e.host.receiveMessage(i,n))return;if(t.ready===!1){isRecord(n)&&n.status===`ready`?t.ready=!0:e.onFailure(e.unavailableError(`worker task server did not become ready`),!0);return}let r=t.task;r?r.runInContext(()=>e.onMessage(n)):e.onMessage(n)}),i.on(`error`,t=>e.onFailure(e.unavailableError(String(t),t),!0)),i.on(`messageerror`,t=>e.onFailure(e.unavailableError(String(t),t))),i.once(`exit`,n=>{releaseWorkerNativeSectionsOnExit(t.nativeSections);let r=a;a=!1,e.onExit(n,r)}),i}var Zu=__esmMin((()=>{k(),Ts()})),Qu,$u,WorkerTaskPoolCore,ed=__esmMin((()=>{O(),k(),Lu(),Vu(),zu(),Hu(),Bu(),Uu(),Ts(),Wu(),qu(),Gu(),Ju(),Xu(),Zu(),Qu=D.snapshot(),$u=_e(`openclaw.memory.critical`),WorkerTaskPoolCore=class{constructor(e,t,n,r={}){if(this.options=e,this.host=t,this.publicDispatch=n,this.ownerOptions=r,this.slots=/* @__PURE__ */ new Set,this.ownedTasks=/* @__PURE__ */ new Set,this.resourceClosures=/* @__PURE__ */ new WeakMap,this.ownedSettlement={cancel:e=>this.cancel(e,new WorkerTaskError(`worker task closed`,`unavailable`)),detach:e=>{e.slot?.task===e&&(e.slot.task=void 0,this.activeTasks--)},retire:e=>this.retirement.startRetire(e),release:(e,t)=>{this.ownedTasks.delete(e)&&(this.releaseAdmission(e),e.runInContext=Qu,this.dispatch(),t&&!e.owner?.retire&&!t.task&&!t.retiring&&this.idle(t))}},this.completion={preparationCleanups:/* @__PURE__ */ new Map,releaseAdmission:e=>this.releaseAdmission(e),releaseCompute:e=>this.computeCapacity.release(e),diagnostics:()=>({worker:this.options.workerUrl.pathname.split(`/`).at(-1),...this.publicDispatch?.getSnapshot()??this.getSnapshot(),pendingBytes:this.admission.pendingBytes})},this.queue=[],this.bootstrap=createWorkerTaskPoolBootstrap(this.slots,this.queue,(e,t)=>this.finish(e,t)),this.workers=0,this.workersCreated=0,this.activeTasks=0,this.resumeCompute=()=>this.dispatch(),this.nextTaskId=0,this.retireIdleOnPressure=e=>this.retirement.retireIdle(this.resourceClosures,e===!0),this.expireTasks=()=>expireWorkerTasks(this.queue,this.slots,this.timeout),this.retryFailedRetirements=()=>this.retirement.retryFailedRetirements(),this.timeout=e=>{e.done||this.cancel(e,workerTaskTimeoutError(e.exchange,this.options.workerUrl))},this.observeTask=t.createTaskObserver?.(e.workerUrl),this.maxWorkers=t.maxWorkers??e.maxWorkers??he(),!Number.isSafeInteger(this.maxWorkers)||this.maxWorkers<1)throw RangeError(`maxWorkers must be a positive safe integer`);this.computeCapacity=e.sharedCompute?t.computeCapacity:void 0,this.admission=new WorkerTaskAdmission(e.maxPendingTasks??128,e.maxPendingBytes??268435456,this.computeCapacity),this.retirement=createWorkerTaskPoolRetirement({slots:this.slots,options:e,retainOneIdleWorker:r.retainOneIdleWorker,runInContext:Qu,dispatch:()=>this.dispatch(),onRotationComplete:()=>{this.bootstrap.reset(),e.onRotationComplete?.()},serviceDeadlines:this.expireTasks,markWorkerRetirement:(e,n)=>t.workerRetiring(e,n),serviceHost:t}),t.pools.register(this)}run(e,t){if(this.closedError)return Promise.reject(this.closedError);let n=t.inputBytes??0;return!Number.isSafeInteger(n)||n<0?Promise.reject(/* @__PURE__ */ RangeError(`inputBytes must be a nonnegative safe integer`)):this.enqueue(e,t,!1,n).promise}runTask(e,t){let n=this.enqueue(e,t,!0);return{result:n.promise,close:e=>joinOwnedWorkerTask(n,this.ownedSettlement,e?.retire===!0)}}startTask(e,t){if(!this.ownerOptions.retainedTransport)throw new WorkerTaskError(`Retained tasks require their native lifetime transport`,`unavailable`);return retainWorkerTask(this.enqueue(e,t,!0),this.ownedSettlement,()=>this.service())}service(){serviceNativeWorkerPass(this.host,this.slots),this.expireTasks(),this.retirement.service();for(let e of Array.from(this.ownedTasks))e.owner?.closing?.service();this.dispatch()}enqueue(e,t,n,r=t.inputBytes??0){let i=createRetainedOperation(()=>this.service(),{observeRejection:this.ownerOptions.retainedTransport===!0}),a={promise:i.operation.result,resolve:i.resolve,reject:i.reject,read:()=>i.operation.read(),id:++this.nextTaskId,runInContext:captureWorkerTaskContext(),controller:void 0,inputConsumed:!1,executionNotified:!1,exchangeSequence:0,input:e,options:{...t},abort:()=>this.cancel(a,toErrorObject(t.signal?.reason,`worker task aborted`)),done:!1,admitted:!1,...n?{owner:{closed:!1,retire:!1}}:{},inputBytes:r,enqueuedAt:performance.now(),transferMs:0,hostWaitMs:0};n&&this.ownedTasks.add(a);let s=this.closedError??this.bootstrap.admissionError;if(s||!Number.isSafeInteger(r)||r<0)return this.finish(a,s??/* @__PURE__ */ RangeError(`inputBytes must be a nonnegative safe integer`)),a;let c=this.admission.admitTask(a,()=>this.host.describeTask?.(this.options.workerUrl,void 0,t.diagnosticOperation));return c?(this.finish(a,c),a):(a.observation=this.observeTask?.(a.options.diagnosticOperation),armWorkerTaskTimeout(a,t.timeoutMs,this.timeout,`enqueue`),t.signal?.addEventListener(`abort`,a.abort,{once:!0}),enqueueWorkerTask(this.queue,a),t.signal?.aborted?a.abort():this.dispatch(),a)}get isClosed(){return this.closedError!==void 0}getSnapshot(){return{maxWorkers:this.maxWorkers,workers:this.workers,workersCreated:this.workersCreated,activeTasks:this.activeTasks,pendingTasks:this.admission.pendingTasks}}startCloseResources(e){return startCloseWorkerPoolResources(this.slots,this.resourceClosures,e=>this.ownedSettlement.retire(e),Qu,e,this.ownerOptions,this.host.observeResourceReply)}rotate(){return this.startRotate().result}startRotate(){return this.computeCapacity?.remove(this.resumeCompute),this.retirement.startRotate()}close(e=new WorkerTaskError(`worker task pool closed`,`unavailable`),t=`closed`){this.closedError??=e,this.admission.close(),$u.unsubscribe(this.retireIdleOnPressure),this.computeCapacity?.remove(this.resumeCompute);for(let e of this.queue.splice(0))this.finish(e,this.closedError);for(let e of this.slots)e.worker&&this.host.workerRetiring(e.worker,t),e.task&&!e.task.owner&&this.finish(e.task,this.closedError,void 0,!0);let n=[...this.ownedTasks],r=new Set(n.flatMap(e=>e.slot?.task===e?[e.slot]:[])),i=n.map(e=>joinOwnedWorkerTask(e,this.ownedSettlement,!0)),a=[...this.slots].filter(e=>!r.has(e)),s=[...i,...a.map(e=>this.retirement.retire(e,t))];return this.host.pools.close(this,s,()=>joinWorkerTaskPreparationCleanups(this.completion,this.retirement.joinArtifacts()))}dispatch(){for(this.slots.size||$u.unsubscribe(this.retireIdleOnPressure),this.queue.length&&!this.closedError&&this.retirement.dispatchAllowed||this.computeCapacity?.remove(this.resumeCompute);!this.closedError&&this.retirement.dispatchAllowed&&this.queue.length;){let e=this.queue[0],t=this.maxWorkers+Number(e.options.pointRead===!0),n=this.activeTasks<t?this.retirement.preferredIdle:void 0;if(n??=[...this.slots].find(e=>this.activeTasks<t&&!e.task&&!e.retiring&&!e.retirementFailed&&(!this.bootstrap.error()||e.worker)),!n){let e=this.bootstrap.error();if(e&&this.bootstrap.rejectQueued(),e||this.slots.size>=t){let e=this.queue.length;for(let t of this.slots)t.task?.exchange&&!t.task.exchange.sent&&!t.task.exchange.pressure.signal.aborted&&e-->0&&t.task.exchange.pressure.abort();return}}if(this.computeCapacity&&!e.options.pointRead){let t=this.computeCapacity.acquire(this.resumeCompute,()=>e.exchange&&!e.exchange.sent&&!e.exchange.pressure.signal.aborted?(e.runInContext(()=>e.exchange?.pressure.abort()),!0):!1);if(!t)return;e.computePermit=t}n||(n={nativeSections:createWorkerNativeSectionState()},this.slots.add(n)),this.retirement.clearIdle(n);let r=this.queue.shift();n.task=r,this.activeTasks++,r.slot=n,r.startedAt=performance.now(),armWorkerTaskTimeout(r,r.options.timeoutMs,this.timeout,`dispatch`),r.observation?.started(),r.runInContext(()=>{try{n.worker?.ref()}catch(e){this.fail(n,toErrorObject(e,`worker reference failed`));return}prepareWorkerTaskInput(r,e=>{r.diagnosticLabel=this.host.describeTask?.(this.options.workerUrl,e),sendWorkerTaskInput({slot:n,task:r,input:e,host:this.host,bootstrapError:this.bootstrap.error,createWorker:()=>this.createWorker(n),fail:(e,t)=>this.fail(n,workerTaskUnavailableError(n,String(e),e),t),refuse:e=>this.finish(r,e,void 0,!0)})},e=>this.finish(r,toErrorObject(e,`worker task preparation failed`)),!n.worker&&this.options.prepareWorker?()=>Qu(()=>this.host.prepareResources()):void 0)})}}createWorker(e){return(this.options.idleTimeoutMs??6e4)>0&&($u.unsubscribe(this.retireIdleOnPressure),$u.subscribe(this.retireIdleOnPressure)),createWorkerTaskPoolWorker({slot:e,options:this.options,host:this.host,runInContext:Qu,unavailableError:(t,n)=>workerTaskUnavailableError(e,t,n),onStarted:e=>{this.workers++,this.workersCreated++,this.host.workerStarted(e,this)},onMessage:t=>this.receive(e,t),onFailure:(t,n)=>this.fail(e,t,n),onExit:(t,n)=>{n&&this.workers--;let r=workerTaskUnavailableError(e,`worker exited with code ${t}`);this.fail(e,r,!0)}})}receive(e,t){if(e.retiring)return;let n=e.task;if(n&&isRecord(t)&&(t.status===`request`||t.status===`consumed`||t.status===`notification`)){try{this.receiveExchange(e,n,t)}catch(t){this.fail(e,toErrorObject(t,`worker consumption callback failed`))}return}if(!n||!isRecord(t)||(n.options.onRequest||n.options.onRequestSync||t.taskId!==void 0)&&t.taskId!==n.id||t.status!==`ok`&&t.status!==`failed`){this.fail(e,new WorkerTaskError(`invalid worker task response`,`unavailable`));return}let r=t,i=!!(n.exchange||n.options.onInputConsumed&&!n.inputConsumed);if(r.status===`failed`)this.finish(n,new WorkerTaskError(r.error,`failed`),void 0,i);else{try{this.options.validateResult?.(r.value)}catch(t){this.fail(e,toErrorObject(t,`worker result validation failed`));return}this.finish(n,void 0,r.value,i)}}receiveExchange(e,t,n){if(n.taskId!==t.id){this.fail(e,new WorkerTaskError(`stale worker exchange`,`unavailable`));return}if(n.status===`notification`){t.options.onNotification?.(n.value);return}if(n.status===`consumed`){if(n.id===0&&!t.inputConsumed){t.inputConsumed=!0;let e=t.options.onInputConsumed;t.options.onInputConsumed=void 0,e?.()}else if(t.exchange?.sent&&n.id===t.exchange.id){let e=t.exchange.onConsumed;t.exchange=void 0,e?.()}else this.fail(e,new WorkerTaskError(`invalid worker consumption receipt`,`unavailable`));return}if(!t.options.onRequest&&!t.options.onRequestSync||t.exchange||!Number.isSafeInteger(n.id)||n.id!==t.exchangeSequence+1){this.fail(e,new WorkerTaskError(`invalid worker exchange`,`unavailable`));return}t.options.hostTimeout===`owner`&&(clearTimeout(t.timer),t.deadline=void 0);let r=createWorkerHostExchange(t,n.value);t.hostWaitStartedAt=performance.now(),this.dispatch(),this.computeCapacity?.requestCheckpoints(),dispatchOwnedWorkerRequest(t,e,n.value,r,{accept:n=>{if(!t.done&&t.deadline!==void 0&&performance.now()>=t.deadline&&this.timeout(t),t.done||e.task!==t||e.retiring){let release=()=>{try{t.runInContext(()=>n.onConsumed?.())}catch{}};this.slots.has(e)?(e.completions??=[]).push(release):release()}else{this.finishHostWait(t),r.onConsumed=n.onConsumed,r.sent=!0,armWorkerTaskTimeout(t,n.timeoutMs,this.timeout);try{e.worker.postMessage({taskId:t.id,responseId:r.id,input:n.input},n.transferList)}catch(t){this.fail(e,toErrorObject(t,`worker response delivery failed`))}}},reject:n=>{!t.done&&e.task===t&&this.fail(e,toErrorObject(n,`worker host exchange failed`))}})}cancel(e,t){e.done||(e.slot?(e.slot.worker&&this.host.workerRetiring(e.slot.worker,`cancelled`),e.owner?this.finish(e,t,void 0,!0):this.fail(e.slot,t)):(this.queue.splice(this.queue.indexOf(e),1),this.finish(e,t)))}fail(e,t,n){e.retiring||(n&&e.ready===!1&&this.bootstrap.fail(t),e.worker&&this.host.workerRetiring(e.worker,`failure`),e.task?.owner?e.task.done?e.task.owner.retire||closeOwnedWorkerTask(e.task,this.ownedSettlement,!0).catch(()=>void 0):this.finish(e.task,t,void 0,!0):this.options.restartOnError===!1?(this.publicDispatch?.close(t)??this.close(t)).catch(()=>void 0):e.task?this.finish(e.task,t,void 0,!0):this.retirement.retire(e).catch(()=>void 0))}finishHostWait(e){let t=e.hostWaitStartedAt;t!==void 0&&(e.hostWaitStartedAt=void 0,e.hostWaitMs+=performance.now()-t)}finish(e,t,n,r=!1){if(e.done)return;this.finishHostWait(e),e.done=!0,e.observation?.completed(),e.observation=void 0,e.runInContext(()=>e.controller?.abort(t)),clearTimeout(e.timer),e.deadline=void 0,e.options.signal?.removeEventListener(`abort`,e.abort);let i=e.slot,{complete:a,resolveFailure:s}=createWorkerTaskCompletion(e,this.completion,t,n);e.owner?(e.owner.complete=a,e.owner.retire||=r||!!(t&&e.slot&&e.preparedAt!==void 0),t?(!s||e.preparation)&&e.reject(s?.()??t):e.resolve(n),(t||r)&&closeOwnedWorkerTask(e,this.ownedSettlement).catch(()=>void 0)):i&&(i.task=void 0,this.activeTasks--,r)?((i.completions??=[]).push(a),this.retirement.retire(i,`failure`).catch(n=>e.reject(workerTaskRetirementError(s?.()??t,n)))):(a(),this.dispatch(),i&&!i.task&&!i.retiring&&this.idle(i))}releaseAdmission(e){e.admitted&&(e.admitted=!1,this.admission.finish(e.inputBytes))}idle(e){e.worker&&!this.resourceClosures.get(e.worker)?.pending&&e.worker.unref(),this.retirement.idle(e)}}})),td=__esmMin((()=>{ed(),Xu(),Bu(),zu(),Gu()}));function resolveNodeCompileCacheEnv(e=process.env){if(e.NODE_DISABLE_COMPILE_CACHE!==void 0)return e;let t=e.NODE_COMPILE_CACHE??resolveGlobalSingleton(nd,()=>({})).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 nd,rd=__esmMin((()=>{Ns(),j(),nd=Symbol.for(`openclaw.nodeCompileCacheBase`)})),id,ad,od,sd=__esmMin((()=>{id=`${process.execArgv.join(` `)} ${process.env.NODE_OPTIONS??``}`,ad=/--max[-_](?:old[-_]space[-_]size(?:[-_]percentage)?|heap[-_]size)(?:=|\s)/u,od=/--(?:freeze[-_]flags[-_]after[-_]init|(?:abort|exit)[-_]on[-_]contradictory[-_]flags)(?:=(?:true|1))?(?:\s|$)/u,T&&!process.versions.bun&&ad.test(id)&&(od.test(id)?process.emitWarning(`V8 startup flags prevent enforcing per-worker heap limits.`):Je(`--max-old-space-size=0 --max-heap-size=0`))})),cd=__esmMin((()=>{Lu()}));function resolveProcessRuntimeWorkerFile(e){let t=ld.resolve;if(!t)return e;if(e instanceof URL)return e.protocol===`file:`?t(e):e;if(typeof e==`string`&&e.startsWith(`/`)){let n=t(l(e));return n.protocol===`file:`?c(n):e}return e}var ld,ud=__esmMin((()=>{j(),ld=resolveGlobalSingleton(Symbol.for(`openclaw.processRuntimeWorkerGeneration`),()=>({}))}));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)):[]}function collectPostgresBridgeCounters(e,t,n){let r=/* @__PURE__ */ new Map([[E,{threadId:E,count:e,selfRootCount:n}]]);for(let e of t)for(let t of e.postgresBridgeCounters??[])r.set(t.threadId,t);return[...r.values()]}var dd=__esmMin((()=>{k()}));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){if(e.length+2>t)return t+1;let n=Buffer.byteLength(e,`utf8`)+2;if(n>t)return t+1;for(let t of e.match(fd)??[]){let e=t.charCodeAt(0);n+=e>=55296?3:e<32&&!`\b
\f\r`.includes(t)?5:1}return n}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 fd,pd=__esmMin((()=>{fd=/["\\\u0000-\u001f\ud800-\udfff]/gu})),md=__esmMin((()=>{Tu(),j(),resolveGlobalSingleton(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=we(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return De(e,n),new Int32Array(n)})})),hd=__esmMin((()=>{Tu(),md()}));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 codePath(e){return n.sep===`/`?e:e.replaceAll(n.sep,`/`)}function codeUrl(e,t){if(/^node:[a-zA-Z0-9_./-]+$/.test(e))return e;if(e.length>2048||/[?#]/.test(e))return;let r=e;if(e.startsWith(`file:`))try{r=c(e)}catch{return}if(!n.isAbsolute(r))return;let i=t?codePath(n.relative(t,r)):``,a=(t&&!i.startsWith(`..`)?`/${i}`:codePath(n.normalize(r))).match(/.*\/node_modules\/((?:@[a-zA-Z0-9_-][a-zA-Z0-9._-]*\/)?[a-zA-Z0-9_-][a-zA-Z0-9._-]*)\//)?.[1];return a?`node_modules/${a}`:/^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?(?:src|dist)\/[a-zA-Z0-9_@./+-]+\.[cm]?js$/.test(i)||/^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?src\/[a-zA-Z0-9_@./+-]+\.ts$/.test(i)?`openclaw:${i}`: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===``&&gd.has(e.functionName),i=r||n!==void 0&&e.functionName.length<=256&&/^(?:(?:(?:get|set) )?#?[$A-Z_a-z][$\w]*(?:\.#?[$A-Z_a-z][$\w]*)*)?$/.test(e.functionName),a=n?.startsWith(`node_modules/`)&&!(n.startsWith(`node_modules/@openclaw/`)&&i)?`[dep:${n.slice(13)}]`:e.scriptId===`0`&&e.url===``&&e.lineNumber<0&&!r?`[native]`:void 0;return{redacted:!i&&!a,callFrame:{functionName:a??(i?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(_d)return unavailable(`busy`);_d=!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=!T&&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:He.getHeapSpaceStatistics()};let p=performance.now();n=!0;let m=t.start();d=performance.now()-p,await m,e.durationMs>0&&await tt(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:He.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 _d=!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{_d=!1}}var gd,_d,ProfileFailure,vd=__esmMin((()=>{Cu(),es(),gd=/* @__PURE__ */ new Set([`(root)`,`(program)`,`(idle)`,`(garbage collector)`,`(GC)`,`(PARSER)`,`(COMPILER)`,`(BYTECODE_COMPILER)`,`(V8 API)`,`(EXTERNAL)`,`(LOGGING)`,`(IDLE_EXTERNAL)`,`(IDLE)`,`(JS)`,`(deopt)`]),_d=!1,ProfileFailure=class extends Error{constructor(e){super(e),this.reason=e}}})),yd=__esmMin((()=>{Kn(),vd()}));function sanitizeNode(e,t){let{callFrame:n,redacted:r}=sanitizeDiagnosticProfileFrame(e.callFrame,t);return{redacted:r||e.deoptReason!==void 0,node:{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]`}}}}function sanitizeCpuProfileResult(e,t,{durationMs:n,startBlockedMs:r}){assertProfile(e.samples!==void 0&&e.timeDeltas!==void 0);let i=0,a=e.nodes.map(e=>{let n=sanitizeNode(e,t);return i+=Number(n.redacted),n.node});return{requestedDurationMs:bd,actualDurationMs:n,startBlockedMs:r,samplingIntervalMicros:xd,sampleLossCount:null,redactedNodeCount:i,profile:{nodes:a,startTime:e.startTime,endTime:e.endTime,samples:e.samples,timeDeltas:e.timeDeltas}}}function sanitizeDiagnosticCpuProfile(e,t,n){if(assertProfile(e.samples!==void 0&&e.timeDeltas!==void 0),e.nodes.length>Sd||e.samples.length>Cd)throw new ProfileFailure(`profile-too-large`);let r=sanitizeCpuProfileResult(e,t,n),{nodes:i}=r.profile;if(boundedJsonUtf8Bytes(r,1048576).complete)return r;let a=new Map(i.map(e=>[e.id,e])),s=/* @__PURE__ */ new Map;for(let e of i)for(let t of e.children??[])s.set(t,e.id);let c=/* @__PURE__ */ new Map;for(let t of e.samples)c.set(t,(c.get(t)??0)+1);let l=/* @__PURE__ */ new Map;for(let[e,t]of c){let n=[],r=a.get(e);for(;r&&n.length<wd;)n.push(r.callFrame),r=a.get(s.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=a.get(s.get(r.id));r&&(n.push(r.callFrame),i=e)}let c=JSON.stringify({stack:n,elidedFrameCount:i}),u=l.get(c);u?u.sampleCount+=t:l.set(c,{stack:n,elidedFrameCount:i,sampleCount:t})}let u=[],d={...r,profile:void 0,truncated:!0,originalNodeCount:i.length,sampleCount:e.samples.length,omittedSampleCount:e.samples.length,summary:u},f=Buffer.byteLength(JSON.stringify(d));for(let e of[...l.values()].toSorted((e,t)=>t.sampleCount-e.sampleCount)){let t=Buffer.byteLength(JSON.stringify(e))+Number(d.summary.length>0);if(d.summary.length===Td||f+t>1048576)break;d.summary.push(e),d.omittedSampleCount-=e.sampleCount,f+=t}return d}var bd,xd,Sd,Cd,wd,Td,Ed=__esmMin((()=>{pd(),hd(),yd(),vd(),bd=5e3,xd=1e4,Sd=16384,Cd=65536,wd=8,Td=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 et());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 et();e.push(a)}t=e}return t[0]??[]}async function sanitizeDiagnosticHeapProfile(e,t,n,r){let i=e.samples,a=/* @__PURE__ */ new Map,s=[{source:e.head}],c=0,l=0;for(let{source:e,parent:n}of s){++l%1024==0&&await et();let{callFrame:r,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);c+=Number(i);let u={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]},d={node:u,parent:n,totalBytes:u.selfSize,count:0,frameId:0};a.set(u.id,d),n?.node.children.push(u);for(let t of e.children)s.push({source:t,parent:d}),++l%1024==0&&await et()}s.length=0;let u=[],d=0,f=0;for(let e of i){++l%1024==0&&await et();let t=a.get(e.nodeId);t?(t.count++,u.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})):(d++,f+=e.size)}let p=[...a.values()];a.clear();for(let e=p.length-1;e>=0;e--){++l%1024==0&&await et();let t=p[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let m={...n,redactedNodeCount:c,unattributedSampleCount:d,unattributedSampleBytes:f},h={...m,truncated:d>0,profile:{head:p[0].node,samples:u}};if(boundedJsonUtf8Bytes(h,1048576).complete)return h;let g=await r?.(h.profile),_=/* @__PURE__ */ new Map,v=/* @__PURE__ */ new Map,y=[],b=[],x=[];for(let e of p){++l%1024==0&&await et();let t=JSON.stringify(e.node.callFrame),n=_.get(t);n===void 0&&(n=_.size,_.set(t,n)),e.frameId=n;let{totalBytes:r,count:i}=e;if(r===0)continue;let a=e.node.selfSize;e.app=e.node.callFrame.url.startsWith(`openclaw:`)?e:e.parent?.app,e.owner=e.parent?.owner??e.app;let s=e.parent;for(let t=1;s&&t<=Dd;t++,s=s.parent){if(s.frameId!==n)continue;let r=e.parent,i=s.parent,a=1;for(;a<t&&r&&i&&r.frameId===i.frameId;)r=r.parent,i=i.parent,a++;if(a===t){let n=s.cycle;e.cycle={width:t,count:n?.width===t?n.count+1:2,next:n?.width===t?n.next:i};break}}b.length=x.length=y.length=0,b.push(e),x.push(1),y.push(n);let c=e.parent;for(;c&&b.length<Dd;){let e=c.cycle,t=e&&e.width<=Dd-b.length?e.width:1,n=t===e?.width?e.count:1,r=n>1?e.next:c.parent;for(let e=0;e<t;e++){let r=c,i=e===t-1&&n>1;b.push(r),x.push(i?n:1),y.push(i?`${r.frameId}x${n}`:r.frameId),c=r.parent}c=r}if(c){let t=b[29].app,n=t?t===e.owner?[t]:[t,e.owner]:[];b.length=x.length=y.length=29,b.push(void 0,...n),x.push(1,1,1),y.push(`...`,...n.map(e=>e.frameId))}let u=y.join(`,`),d=v.get(u);if(d)d.selfBytes+=a,d.totalBytes+=r,d.count+=i;else{let t=[e.node.callFrame];for(let e=1;e<b.length;e++){let n=b[e]?.node.callFrame;t.push(n?x[e]>1?{...n,functionName:`${n.functionName} ×${x[e]}`}:n:{functionName:`[...]`,url:``,scriptId:`0`,lineNumber:-1,columnNumber:-1})}v.set(u,{stack:t,selfBytes:a,totalBytes:r,count:i})}}_.clear(),b.length=0,p.length=0;let S={...m,...g,truncated:!0,summary:[]},ee=Buffer.byteLength(JSON.stringify(S));for(let e of await sortAllocationSummaries(v.values())){++l%1024==0&&await et();let t=Buffer.byteLength(JSON.stringify(e))+Number(S.summary.length>0);if(ee+t>1048576)break;S.summary.push(e),ee+=t}return S}var Dd,Od=__esmMin((()=>{pd(),hd(),yd(),vd(),Dd=32})),kd=/* @__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:Ad,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:jd,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:Ad,effectiveDurationMs:Ad,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:jd,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=Pd.then(async()=>{let t=n.join(resolveStateDir(),`diagnostics`);await w.mkdir(t,{recursive:!0,mode:448});let r=(await w.readdir(t)).filter(e=>Nd.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-Md+2)))await w.unlink(n.join(t,e));let i=`code-mode-gc-${Date.now()}-${S()}`,a=[];for(let[r,s]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${i}.${r}profile.json`;await $e({filePath:n.join(t,e),content:s,mode:384,dirMode:448}),a.push(e)}return a});return Pd=t.catch(()=>{}),t}var Ad,jd,Md,Nd,Pd,Fd=__esmMin((()=>{Kn(),Ed(),Od(),vd(),v_(),Ad=5e3,jd=262144,Md=20,Nd=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/,Pd=Promise.resolve()}));function createCpuTrackedWorker(e,t,n){let r=runWithMainThreadTask(`worker:${workerScriptName(e,t?.eval)}`,()=>new Ce(t?.eval?e:resolveProcessRuntimeWorkerFile(e),t));return trackNativeWorkerForCpu(r,e,t?.eval),Object.assign(L.workers.get(r),{internalMessages:!0,requestClass:n}),r}function trackNativeWorkerForCpu(e,t,n=!1){trackWorker(e);let r=L.workers.get(e),i=workerScriptName(t,n);if(r.script!==i&&(r.script===`bridge.worker.js`&&Atomics.sub(L.postgresBridgeCount,0,1),i===`bridge.worker.js`&&Atomics.add(L.postgresBridgeCount,0,1),r.script=i),r.script===`sqlite-store.worker.js`&&attributeWorkerMetrics(r,`writer`),r.script===`code-mode-node.worker.js`&&r.workerSlot===void 0){let e=new Set([...L.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 getTrackedPostgresBridgeCounters(){return collectPostgresBridgeCounters(L.postgresBridgeCount,L.workers.values(),L.postgresPoolSelfRootCount)}function recordPostgresPoolSelfRoot(){return Atomics.compareExchange(L.postgresPoolSelfRootCount,0,0,1)===0}function observeTrackedPostgresBridgeCounters(e){return L.postgresBridgeObservers.add(e),()=>L.postgresBridgeObservers.delete(e)}function publishPostgresBridgeCounters(){for(let e of L.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 attributeWorkerToPool(e,t,n){let r=L.workers.get(e);if(!r)return;let i=L.poolIds.get(t);i===void 0&&(i=++L.nextPoolId,L.poolIds.set(t,i)),r.poolId=i,attributeWorkerMetrics(r,n,0)}function attributeWorkerMetrics(e,t,n){let r=t===`reader`||t===`file-reader`||t===`compute`||t===`writer`||t===`singleton`?t:`other`,i=`${r}:${e.script}`,a=L.taskMetrics.get(i);a||(a={workerClass:r,script:e.script,tasksCompleted:n,heapUsedHighWaterBytes:0,gc:[]},L.taskMetrics.set(i,a)),e.taskMetrics=a}function forgetWorker(e){let t=L.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(L.postgresBridgeCount,0,1),t.memoryFlush?.resolve(),drainWorkerMemoryPort(t),retire(t),t.memoryPort?.close(),L.workers.delete(e),L.revision++,L.cpuSources=void 0,t.postgresBridgeCounters&&publishPostgresBridgeCounters()}function countWorkerStart(e){let t=L.lifecycle.get(e.script);return t||(t={started:0,retired:/* @__PURE__ */ new Map},L.lifecycle.set(e.script,t)),e.started||(e.started=!0,t.started++),t}function markWorkerRetirement(e,t){let n=L.workers.get(e);n&&(n.retirementReason??=t)}function flushWorkerDiagnostics(e,t){let n=L.workers.get(e);if(n?.memoryFlush)return n.memoryFlush.operation;let r=n?.memoryPort;if(!n?.taskMetrics||!r||!L.gcObserver||[`failure`,`cancelled`,`crash`,`gc-thrash`,`gc-storm`,`exit`].includes(t))return;let i=performance.now()+100,a=createRetainedOperation(()=>{drainWorkerMemoryPort(n),performance.now()>=i&&a.resolve()});n.memoryFlush=a;let s=setTimeout(()=>a.resolve(),100);a.operation.result.then(()=>clearTimeout(s));try{r.postMessage({flush:!0}),recordWorkerMessage(`memory`,`to_worker`,1)}catch{a.resolve()}return a.operation}function trackWorker(e){if(L.workers.has(e))return;if(T&&e instanceof Ce&&recordWorkerMessage(`lifecycle`,`to_worker`),T&&e instanceof Ce&&canObserveWorkerMessages(e)){let t=Object.getPrototypeOf(e)===Ce.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??Ce.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??Ce.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())}}};L.workers.set(e,n),queueMicrotask(()=>countWorkerStart(n)),L.revision++,L.cpuSources=void 0,e.once(`exit`,()=>forgetWorker(e))}function recordWorkerHeap({taskMetrics:e},t){e&&(e.heapUsedHighWaterBytes=Math.max(e.heapUsedHighWaterBytes,t))}function isWorkerGcObservationEnabled(){return!!L.gcObserver}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)}L.gcObserver?.(t,e.script,e.workerSlot)}function drainWorkerMemoryPort({memoryPort:e,memoryReceive:t}){if(e&&t)for(let n=Ee(e);n;n=Ee(e))t(n.message)}function receiveWorkerMemoryPort(e,t){if(isRecord(t)&&(t.status===`ok`||t.status===`failed`)&&t.diagnostics===!0){let t=L.workers.get(e);return t?.taskMetrics?.tasksCompleted!==void 0&&t.taskMetrics.tasksCompleted++,!1}if(!isRecord(t)||t.status!==`memory`||!(t.port instanceof xe))return!1;let n=t.port,r=L.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.memoryReceive=void 0,r.memoryPending=!1,r.memoryUnavailable=!0,r.memoryFlush?.resolve(),n.close()};return r.memoryReceive=t=>{if(`sqliteReaderCounter`in t)receive(r,t.sqliteReaderCounter),recordWorkerMessage(`memory`,`from_worker`,16);else if(`postgresBridgeCounters`in t)receivePostgresBridgeCounters(r,t.postgresBridgeCounters),recordWorkerMessage(`memory`,`from_worker`);else if(`flushed`in t)recordWorkerMessage(`memory`,`from_worker`,8),recordWorkerHeap(r,t.heapUsed),r.memoryFlush?.resolve();else if(`retireWorkerId`in t)recordWorkerMessage(`memory`,`from_worker`),Id.publish(t.retireWorkerId);else if(`gcStorm`in t){recordWorkerMessage(`memory`,`from_worker`);let i=e.threadId,a=r.workerSlot;Promise.resolve().then(()=>(Fd(),kd)).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&&(recordWorkerHeap(r,t.heapUsed),delete t.gc,r.heap={value:t,sampledAt:performance.now()},r.memoryPending=!1,r.memoryUnavailable=!1)},n.on(`message`,r.memoryReceive),n.once(`close`,close),n.once(`messageerror`,close),n.unref(),L.gcObserver&&(n.postMessage({gc:!0}),recordWorkerMessage(`memory`,`to_worker`,1)),!0}var Id,L,Ld=__esmMin((()=>{sd(),k(),cd(),j(),Ol(),ud(),dc(),Ll(),Dc(),dd(),Id=_e(`openclaw.code-mode.gc-storm`),L=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 startPool(){if(!T&&recordPostgresPoolSelfRoot()){let e={threadId:E,owner:workerScriptName(process.argv[1]??``)};Rd.publish(e);let t=new ye(`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 be,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 be;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:N.nextStep},r=resolveRuntimeProcessEntrypointUrl(`postgresBridge`),i=resolveRuntimeWorkerThreadExecArgv(r),a=[];N.endpoints=n,N.workers=a;let launch=e=>{let n=t[e],c=new Int32Array(n.signal),l=!1,u=new Ce(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.${N.nextStep?` Run ${N.nextStep}.`:``}`))),u.once(`message`,()=>e())});d.catch(()=>{}),N.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;N.refresh=()=>{for(let e of s){s.delete(e);let r={channel:new be,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 be;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 N.nextStep||N.refresh?.(),N.endpoints??startPool()}function createPostgresPoolEndpoints(e=getDatabaseEngineSelection()){if(!N.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 be;return e.postMessage({host:n.port2},[n.port2]),{port:n.port1,signal:t}})}}function postgresPoolTransferList(e){return e?.services.map(({port:e})=>e)??[]}var Rd,zd=__esmMin((()=>{v_(),Rs(),Iu(),Pu(),Ld(),Ll(),Bs(),Rd=_e(`openclaw.postgres.pool.self-root`)}));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 b(`sha256`).update(e).digest(`hex`).slice(0,16)}function hasNoJournal(e){return[`-wal`,`-journal`].every(t=>{try{let n=u.statSync(`${e}${t}`,{bigint:!0});return n.isFile()&&n.size===0n}catch(e){if(C(e,`ENOENT`))return!0;throw e}})}function decodeSeal(e,t,n){let r=JSON.parse(e);if(!isRecord(r)||typeof r.payload!=`string`||r.checksum!==checksum(r.payload))return n(`malformed-proof`);let i=JSON.parse(r.payload);if(!isRecord(i)||i.version!==1||typeof i.schemaIdentity!=`string`||typeof i.verifiedAt!=`number`||!Number.isSafeInteger(i.verifiedAt)||!(`facts`in i)||!t.isFile())return n(`malformed-proof`);let a=Date.now()-i.verifiedAt;return a<0||a>Bd?n(`expired-proof`):Object.entries(fileFields(t)).every(([e,t])=>i[e]===t)?{schemaIdentity:i.schemaIdentity,verifiedAt:i.verifiedAt,facts:i.facts,...i.identity===void 0?{}:{identity:i.identity}}:n(`file-mismatch`)}function readSqliteCleanCloseSeal(e,t,n){let refuse=e=>{n?.(e)};try{let n=`${e}.seal`;if(!u.lstatSync(n).isFile())return refuse(`malformed-proof`);let r=decodeSeal(u.readFileSync(n,`utf8`),t,refuse);return r?hasNoJournal(e)?r:refuse(`journal-present`):void 0}catch(e){return refuse(C(e,`ENOENT`)?`no-proof`:`malformed-proof`)}}async function readSqliteCleanCloseSealAsync(e,t,n){let refuse=e=>{n?.(e)};try{let n=`${e}.seal`;if(!(await u.promises.lstat(n)).isFile())return refuse(`malformed-proof`);let r=decodeSeal(await u.promises.readFile(n,`utf8`),t,refuse);if(!r)return;for(let t of[`-wal`,`-journal`])try{let n=await u.promises.stat(`${e}${t}`,{bigint:!0});if(!n.isFile()||n.size!==0n)return refuse(`journal-present`)}catch(e){if(!C(e,`ENOENT`))throw e}return r}catch(e){return refuse(C(e,`ENOENT`)?`no-proof`:`malformed-proof`)}}function invalidateSqliteCleanCloseSeal(e){try{u.unlinkSync(`${e}.seal`)}catch(e){if(!C(e,`ENOENT`))throw e}}function writeSqliteCleanCloseSeal(e,t,n,r){try{let i=`${e}.seal`,a=u.lstatSync(i,{throwIfNoEntry:!1});if(!n.isFile()||a&&!a.isFile()||!hasNoJournal(e))return invalidateSqliteCleanCloseSeal(e),!1;let s=JSON.stringify({version:1,schemaIdentity:t,...fileFields(n),verifiedAt:r.verifiedAt,facts:r.facts,identity:r.identity});return u.writeFileSync(i,JSON.stringify({payload:s,checksum:checksum(s)})),!0}catch{try{invalidateSqliteCleanCloseSeal(e)}catch{}return!1}}var Bd,Vd=__esmMin((()=>{k(),Cn(),Gs(),Bd=6048e5}));function createSqliteLifecycleAggregateError(e,t,n){return AggregateError(e,t,{cause:n})}var Hd=__esmMin((()=>{j(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteCoordinatorError`),()=>class extends Error{constructor(e,t){super(e),this.cause=t,this.name=`SqliteCoordinatorError`}})}));function resolveSqliteDatabaseFilePath(e){if(!e.startsWith(`file:`))return e;let[t=``]=e.slice(5).split(/[?#]/u,1);return t.startsWith(`/`)?c(e):decodeURIComponent(t)}function createSqliteDatabaseDescriptorOwner(e){function prepareOwnedSqliteDatabaseAdmission(t){let n=F.descriptorPreparation.then(async()=>{if(E!==0)throw Error(`SQLite descriptor preparation belongs to the host`);t.assertCurrent();let n=await u.promises.stat(t.location,{bigint:!0});assertDatabaseFileIdentity(n,t.expectedIdentity);let r=await u.promises.realpath(t.location);if(t.assertCurrent(),r!==t.location)throw Error(`SQLite private staging location changed before admission`);let i=readSqliteDatabaseAdmissionIdentity(n),a=F.registry.descriptors.get(i);if(retainPreparedSqliteDatabaseAdmissionLocation(t.location,t.expectedIdentity,{identity:i,canonicalPath:r}))return;let s=a?.descriptor??await new Promise((e,n)=>{u.open(t.location,`r`,(t,r)=>t?n(t):e(r))}),c=!1,l=!1;try{let n=await new Promise((e,t)=>{u.fstat(s,{bigint:!0},(n,r)=>n?t(n):e(r))});assertDatabaseFileIdentity(n,t.expectedIdentity),c=a===void 0;let i,d=await readSqliteCleanCloseSealAsync(r,n,e=>{i=e});assertDatabaseFileIdentity(await u.promises.stat(t.location,{bigint:!0}),t.expectedIdentity),t.assertCurrent();let f=F.registry.retainDescriptor(r,s,n);l=!0,e.load(f,{seal:d,refusal:i})}catch(e){if(c&&!l)try{await new Promise((e,t)=>{u.close(s,n=>n?t(n):e())})}catch(t){throw createSqliteLifecycleAggregateError([e,t],`SQLite preparation cleanup failed`,e)}throw e}});return F.descriptorPreparation=n.then(()=>{},()=>{}),n}function prepareSqliteDatabaseAdmissionAsync(t){let n=resolveAdmissionTarget(t.location,t.create!==void 0);if(!n)return Promise.resolve(void 0);let{filename:r,create:i}=n,a=t.identity,prepare=async()=>{t.assertCurrent();let n=a??await inspectDatabasePathIdentity(r);if(a=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 s=n.key.startsWith(`file:`),c=!s&&i?t.create:void 0;if(!s&&!c)return n;let l=`${n.key.slice(5)}:${n.birthtime}`;if(t.observedLocation&&t.observedLocation.identity!==l)throw Error(`SQLite database changed while retaining its admission identity`);if(E!==0){if(c)throw Error(`SQLite descriptor creation belongs to the host`);return pathAdmission(r,l),t.assertCurrent(),n}let d=s?F.registry.descriptors.get(l):void 0;if(d&&(assertDatabaseFileIdentity(d.file,n),retainPreparedSqliteDatabaseAdmissionLocation(r,void 0,{identity:l,canonicalPath:n.canonicalPath})))return n;let f,p;if(d)f=d.descriptor,p=d.file;else{c&&await c.authorize(n.canonicalPath),t.assertCurrent();let e=c?createDeferredCore():void 0;e&&c?.retain(e.promise);let i;try{i=await new Promise((e,t)=>{u.open(r,c?`wx`:`r`,420,(n,r)=>n?t(n):e(r))}),f=i,p=await new Promise((e,t)=>{u.fstat(f,{bigint:!0},(n,r)=>n?t(n):e(r))}),s&&assertDatabaseFileIdentity(p,n),F.registry.retainDescriptorCustody(n.canonicalPath,f,p),e?.resolve()}catch(t){if(i===void 0){if(e?.resolve(),c&&C(t,`EEXIST`))return prepare()}else e?.reject(t);throw t}}let m=s?n:{key:`file:${p.dev}:${p.ino}`,canonicalPath:n.canonicalPath,birthtime:readDatabaseIdentityBirthtime(p)},h,g=s?await readSqliteCleanCloseSealAsync(n.canonicalPath,p,e=>{h=e}):void 0,_=await inspectDatabasePathIdentity(r);if(!_||_.key!==m.key||_.birthtime!==m.birthtime||_.canonicalPath!==m.canonicalPath)throw Error(`SQLite database changed identity during admission`);t.assertCurrent();let v=F.registry.records.get(readSqliteDatabaseAdmissionIdentity(p)),y=v&&!isSqliteDatabaseAdmissionRetired(v)?v:F.registry.retainDescriptor(m.canonicalPath,f,p);return F.registry.observeLocation(r,y.identity),s?e.load(y,{seal:g,refusal:h}):e.markLoaded(y),m},s=F.descriptorPreparation.then(prepare);return F.descriptorPreparation=s.then(()=>{},()=>{}),s}function retainPreparedSqliteDatabaseAdmissionLocation(t,n,r){let i=!r&&F.registry.forLocation(t),a=i&&F.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&&F.registry.descriptors.get(r.identity);if(r&&s&&e.isLoaded(s)){n&&assertDatabaseFileIdentity(s.file,n);let i=F.registry.records.get(r.identity),a=i&&!isSqliteDatabaseAdmissionRetired(i)?i:F.registry.retainDescriptor(r.canonicalPath,s.descriptor,s.file);return F.registry.observeLocation(t,a.identity),e.markLoaded(a),!0}return!1}function retainSqliteDatabaseAdmissionLocation(t,n,r){if(retainPreparedSqliteDatabaseAdmissionLocation(t,n,r))return;let i=u.statSync(t,{bigint:!0});if(!i.isFile())return;let a=readSqliteDatabaseAdmissionIdentity(i),s=F.registry.records.get(a);if(s&&!isSqliteDatabaseAdmissionRetired(s)){F.registry.observeLocation(t,a),e.load(s);return}if(E!==0)return;let c=F.registry.descriptors.get(a)?.descriptor??u.openSync(t,`r`),l=u.fstatSync(c,{bigint:!0});if(!l.isFile()||readSqliteDatabaseAdmissionIdentity(l)!==a)throw Error(`SQLite database changed while retaining its admission identity`);let d=F.registry.retainDescriptor(u.realpathSync.native(t),c,l);F.registry.observeLocation(t,d.identity),e.load(d)}function pathAdmission(t,n){try{let r=F.registry.forLocation(t);if(!r){let e=n;if(e===void 0&&E!==0){let n=u.statSync(t,{bigint:!0});if(!n.isFile())return;e=readSqliteDatabaseAdmissionIdentity(n)}exchangeSqliteDatabaseAdmission(t,void 0,!1,e!==void 0&&E!==0?{identity:e,canonicalPath:u.realpathSync.native(t)}:void 0),r=F.registry.forLocation(t)}return r?(e.load(r),r):(retainSqliteDatabaseAdmissionLocation(t),F.registry.forLocation(t))}catch(e){if(C(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 r=resolveAdmissionTarget(t,n.create);if(!r)return;let{filename:i,create:a}=r;try{let e=u.statSync(i,{bigint:!0});if(!e.isFile()){F.registry.observeLocation(i,void 0);return}let t=readSqliteDatabaseAdmissionIdentity(e);return F.registry.observeLocation(i,t),t}catch(t){if(C(t,`ENOENT`)){if(F.registry.observeLocation(i,void 0),!a)return;if(E!==0){let e=F.exchange.getStore()!==void 0;exchangeSqliteDatabaseAdmission(i,!0);let n=prepareSqliteDatabaseAdmission(i);if(e&&n===void 0)throw Error(`SQLite worker file creation requires host authority: ${i}`,{cause:t});return n}let n;try{n=u.openSync(i,`wx`,420)}catch(e){if(C(e,`EEXIST`))return prepareSqliteDatabaseAdmission(i);throw e}let r=u.fstatSync(n,{bigint:!0}),s=F.registry.retainDescriptor(u.realpathSync.native(i),n,r);if(e.markLoaded(s),prepareSqliteDatabaseAdmission(i)!==s.identity)throw Error(`SQLite database changed identity during file creation`,{cause:t});return s.identity}throw t}}return{prepareOwnedSqliteDatabaseAdmission,prepareSqliteDatabaseAdmissionAsync,retainSqliteDatabaseAdmissionLocation,retainPreparedSqliteDatabaseAdmissionLocation,prepareSqliteDatabaseAdmission,pathAdmission}}var Ud=__esmMin((()=>{Ao(),Cn(),Vd(),$s(),Zs(),Hd(),Gs()}));function getSqliteNativeAdmissionFacts(e){return Wd.operations.get(e)?.facts}function beginSqliteDatabaseAdmissionOperation(e){let t=Wd.operations.get(e)??{depth:0,facts:/* @__PURE__ */ new Map};return t.depth+=1,Wd.operations.set(e,t),()=>{--t.depth,t.depth===0&&Wd.operations.delete(e)}}var Wd,Gd=__esmMin((()=>{j(),Wd=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 readSqliteDatabaseWriteRevision(e){let r=sqlPublicationAnchor(e);if(!r.isOpen||t.suspended.has(r))return;let i=n(r);if(!i){let e=r.location();return!e||e===`:memory:`?t.localWriteRevisions.get(r)??0:void 0}return readSqliteDatabaseGeneration(i,`writeRevision`)}function readSqliteDatabaseSiblingWriteRevision(e){let n=sqlPublicationAnchor(e),r=readSqliteDatabaseWriteRevision(n);return r===void 0?void 0:r-(t.localWriteRevisions.get(n)??0)|0}function readSqliteDatabaseCleanClose(t){let n=e.prepareFileIdentity(t),i=r(t);return i!==void 0&&i.identity===n&&Atomics.load(new Int32Array(i.generation),P.sealPresent)===1}function readSqliteDatabaseIntegrityVerification(t){let n=typeof t==`string`?getOrLoadSqliteDatabaseAdmissionForPath(t,e.integrityVerificationKey,()=>void 0):getSqliteDatabaseAdmission(t,e.integrityVerificationKey);return n===void 0?void 0:{verifiedAt:n}}function readSqliteDatabaseCleanCloseRefusal(e){return n(sqlPublicationAnchor(e))?.cleanCloseRefusal}function retainSqliteDatabaseAdmissionForPath(e){let n=r(e);if(!n)return;try{a(n)}catch(e){throw s(n),e}let i=!1,c=t.registry.prepareLocation(e);return{location:e,identity:{...n.physicalIdentity,canonicalPath:n.location},isCurrent:()=>!i&&c()===n,release(){i||(i=!0,s(n))}}}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?P.schemaRevision:P.factRevision,s=n.facts.get(t.name),c=s&&new Int32Array(s.current);return()=>{if(Atomics.load(i,P.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 getSqliteDatabaseAdmissionSourceForPath(e){let n=t.registry.forLocation(e);return n&&{identity:n.physicalIdentity,canonicalPath:n.location}}function observeSqliteDatabaseAdmissionLocation(e,n){let r=t.registry.forLocation(n.canonicalPath);r?.physicalIdentity.key===n.key&&r.physicalIdentity.birthtime===n.birthtime&&t.registry.observeLocation(e,r.identity)}function hasSqliteDatabaseSchemaAdmissionForIdentity(e){if(!e.key.startsWith(`file:`)||e.birthtime===void 0)return!1;let n=`${e.key.slice(5)}:${e.birthtime}`;return hasSqliteDatabaseSchemaAdmission(t.registry.records.get(n))}return{readSqliteDatabaseWriteRevision,readSqliteDatabaseSiblingWriteRevision,readSqliteDatabaseCleanClose,readSqliteDatabaseIntegrityVerification,readSqliteDatabaseCleanCloseRefusal,getSqliteDatabaseAdmission,getSqliteDatabaseSchemaRevision,getOrLoadSqliteDatabaseAdmissionForPath,peekSqliteDatabaseAdmissionForPath,prepareSqliteDatabaseAdmissionForPath,hasSqliteDatabaseSchemaAdmissionForPath,getSqliteDatabaseAdmissionIdentityForPath,getSqliteDatabaseAdmissionSourceForPath,observeSqliteDatabaseAdmissionLocation,hasSqliteDatabaseSchemaAdmissionForIdentity,retainSqliteDatabaseAdmissionForPath}}var Kd=__esmMin((()=>{ls(),Zs(),Gd()}));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&&qd.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 qd,Jd=__esmMin((()=>{qd=/* @__PURE__ */ new Set([`CHECK`,`FOREIGN`,`PRIMARY`,`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 Yd=__esmMin((()=>{Jd()}));function hasPendingAgentStartupColumns(e){let t=/* @__PURE__ */ new Map;return Zd.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 Xd,Zd,Qd=__esmMin((()=>{Yd(),Xd=[{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`}],[...Xd],Zd=[{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`}]})),$d,ef=__esmMin((()=>{$d=`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 r=u.mkdtempSync(n.join(t.parentDirectory??me.tmpdir(),`openclaw-script-`)),i=n.join(r,e.fileName),a=!1,dispose=()=>{if(!a)try{u.rmSync(r,{recursive:!0,force:!0}),a=!0}catch(e){process.emitWarning(`Runtime script cleanup failed at ${r}: ${e instanceof Error?e.message:String(e)}`)}};try{return u.writeFileSync(i,e.source,{mode:384,flag:`wx`}),{url:l(i),dispose}}catch(e){throw dispose(),e}}var tf=__esmMin((()=>{}));function probeBunSqliteLibrary(e){let t=materializeRuntimeProcessScriptFile({fileName:Qo.bunSqliteLibraryProbe.fileName,source:$d});try{let r=c(t.url),i=n.dirname(r),a=n.join(i,`bunfig.toml`);u.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 l=Ie(process.execPath,[`--no-install`,`--no-env-file`,`--config=${a}`,r,n.resolve(e)],{cwd:i,env:resolveRuntimeScriptEnv(s),encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,killSignal:`SIGKILL`,maxBuffer:4096});if(l.error)throw l.error;let d=parseProbeFacts(l.stdout);if(l.status!==0)throw Error(d&&`error`in d&&typeof d.error==`string`?d.error.slice(0,512):`SQLite library probe failed (${l.signal??l.status})`);if(!d||!(`version`in d)||typeof d.version!=`string`||d.version.length>64||!(`extensionLoadingSupported`in d)||typeof d.extensionLoadingSupported!=`boolean`)throw Error(`SQLite library probe returned invalid output`);return{version:d.version,extensionLoadingSupported:d.extensionLoadingSupported}}finally{t.dispose()}}function parseProbeFacts(e){let t;try{t=JSON.parse(e)}catch{return}return typeof t==`object`&&t&&!Array.isArray(t)&&`protocol`in t&&t.protocol===1?t:void 0}var nf=__esmMin((()=>{Tu(),ef(),$o(),tf()})),rf,af=__esmMin((()=>{rf=`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 of=__esmMin((()=>{})),sf=__esmMin((()=>{of()})),cf=/* @__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 et(void 0,{ref:!n})),t&&await de(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 le(a(ge(),`openclaw-sqlite-close-`)),e=await ue(e),lf.publish({phase:`start`}),t=new Ce(resolveRuntimeWorkerUrl(Eu.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,s=cleanupProbe(t,e,i);if(i)return r;let c=await s;return c?{explicitSqliteCloseReleasesNativeResources:!1,reason:c}:r}var lf,uf=__esmMin((()=>{Qn(),Du(),Pu(),lf=_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),De(ff,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(!T)return decide({...i,reason:`Parent did not complete SQLite close admission`,...we(ff)})}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(()=>(uf(),cf));return decide({...await e(),decided:!0})}catch(e){return decide(conservative(`SQLite close check failed: ${String(e)}`))}})(),n}}}function selectLibrary(e){let{Database:n}=t(import.meta.url)(`bun:sqlite`);n.setCustomSQLite(e)}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?s.join(i,`lib/libsqlite3.dylib`):void 0,c=process.env.HOMEBREW_PREFIX?.trim(),l=r===void 0?[.../* @__PURE__ */ new Set([...a?[a]:[],...c?[s.join(c,`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 l){let i=r===void 0?n===a?`bundled`:`discovered`:`env`,s,c=!0;try{try{s=probeBunSqliteLibrary(n)}catch(e){throw c=d(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 readPublishedSqliteLibrarySelection(){return we(df)}function createRuntimeSelector(){let e=!!process.versions.bun&&process.platform===`darwin`,t;e&&!T&&(t=readPublishedSqliteLibrarySelection());let n=createSelector(),r=!1;return i=>{let a=t??n(i);return e&&T&&!r&&(De(df,Object.freeze({...a})),r=!0),a}}function runtimeSelector(){return resolveGlobalSingleton(Symbol.for(`openclaw.bunSqliteLibrarySelection`),createRuntimeSelector)}function capabilities(){let e=runtimeSelector();return e.capabilities??=createCapabilities(e)}function getSqliteRuntimeCapabilities(){return capabilities().get()}function captureSqliteWorkerEnvironmentData(e=we(Vs)){return[[df,ensureSqliteLibrarySelected()],[ff,getSqliteRuntimeCapabilities()],[pf,we(pf)],[Vs,e],[rf,we(rf)]]}function ensureSqliteLibrarySelected(e){return runtimeSelector()(e)}var df,ff,pf,mf=__esmMin((()=>{Tu(),j(),nf(),af(),_l(),Hs(),sf(),df=`openclaw.bunSqliteLibrarySelection`,ff=`openclaw.sqliteRuntimeCapabilities`,pf=`openclaw.sqliteNativeRuntimeAdmission`}));function compareValidSemver(e,t){let n=nt(e),r=nt(t);return n&&r?n.compare(r):null}var hf=__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(gf,()=>({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 gf,_f=__esmMin((()=>{k(),j(),gf=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(Re(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(we(pf))}function assertSafeSqliteRuntime(e){if(yf===e)return;let t=parseSqliteNativeRuntimeAdmission(we(pf));if(t){assertSqliteWalResetSafeVersion(t.version,process.versions.node),xf=(compareValidSemver(t.version,`3.45.0`)??-1)>=0,bf=t.extensionLoadingSupported,yf=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()}xf=(compareValidSemver(r,`3.45.0`)??-1)>=0,bf=a,yf=e,De(pf,{format:1,runtime:sqliteNativeRuntimeIdentity(),version:r,storageIdentity:i,extensionLoadingSupported:a})}function requireNodeSqlite(){installProcessWarningFilter();try{ensureSqliteLibrarySelected();let e=vf("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 vf,yf,bf,xf,Sf=__esmMin((()=>{k(),mf(),So(),hf(),sf(),_f(),vf=t(import.meta.url)})),Cf,wf=__esmMin((()=>{Cf=`-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;
-- session_entry_snapshots owns keyed cold values. Promoted node columns are query
-- indexes; session_windows and their children own transcript generations.
-- Legacy ACP provenance is private import evidence carried with its logical session.
CREATE TABLE IF NOT EXISTS schema_meta (
meta_key TEXT NOT NULL PRIMARY KEY,
role TEXT NOT NULL,
schema_version INTEGER NOT NULL,
agent_id TEXT,
app_version TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS session_nodes (
session_key TEXT NOT NULL PRIMARY KEY,
current_session_id TEXT NOT NULL,
entry_json TEXT NOT NULL,
session_started_at INTEGER,
has_optional_references INTEGER NOT NULL DEFAULT 0,
snapshot_revision INTEGER NOT NULL DEFAULT 0,
legacy_acp_migration_json TEXT,
entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),
updated_at INTEGER NOT NULL,
status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
created_at INTEGER,
created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),
created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),
created_actor_id TEXT,
owner_actor_type TEXT,
owner_actor_id TEXT,
owner_assigned_by_type TEXT,
owner_assigned_by_id TEXT,
owner_assigned_at INTEGER,
project_id TEXT,
parent_session_key TEXT,
spawned_by TEXT,
fork_source_session_key TEXT,
fork_source_session_id TEXT,
fork_source_entry_id TEXT,
label TEXT,
display_name TEXT,
category TEXT,
icon TEXT,
pinned_at INTEGER,
archived_at INTEGER,
last_read_at INTEGER,
last_interaction_at INTEGER,
last_activity_at INTEGER
) STRICT;
CREATE TABLE IF NOT EXISTS session_entry_snapshots (
session_key TEXT NOT NULL,
field TEXT NOT NULL CHECK (field IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')),
value_json TEXT NOT NULL,
PRIMARY KEY (session_key, field),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;
CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_insert
AFTER INSERT ON session_entry_snapshots
BEGIN
UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
WHERE session_key = NEW.session_key;
END;
CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_update
AFTER UPDATE OF session_key, field, value_json ON session_entry_snapshots
WHEN NEW.session_key IS NOT OLD.session_key
OR NEW.field IS NOT OLD.field OR NEW.value_json IS NOT OLD.value_json
BEGIN
UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
WHERE session_key IN (OLD.session_key, NEW.session_key);
END;
CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_delete
AFTER DELETE ON session_entry_snapshots
BEGIN
UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
WHERE session_key = OLD.session_key;
END;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at
ON session_nodes(updated_at DESC, session_key);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label
ON session_nodes(label, session_key)
WHERE label IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_parent_session_key
ON session_nodes(parent_session_key, session_key);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_spawned_by
ON session_nodes(spawned_by, session_key);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_status
ON session_nodes(status, session_key)
WHERE status IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_archived_at
ON session_nodes(archived_at, session_key)
WHERE archived_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_active
ON session_nodes(session_key)
WHERE archived_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_current_session_id
ON session_nodes(current_session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_valid_pending
ON session_nodes(session_key)
WHERE entry_valid = 0;
CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_not_valid
ON session_nodes(session_key)
WHERE entry_valid != 1;
CREATE TABLE IF NOT EXISTS session_participants (
session_key TEXT NOT NULL,
identity_namespace TEXT NOT NULL,
actor_id TEXT NOT NULL,
contribution_count INTEGER NOT NULL,
first_prompted_at INTEGER,
last_prompted_at INTEGER,
PRIMARY KEY (session_key, identity_namespace, actor_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS session_key_contract (
id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
main_key TEXT NOT NULL,
canonical_ready TEXT,
updated_at INTEGER NOT NULL
) STRICT;
INSERT OR IGNORE INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0);
CREATE TABLE IF NOT EXISTS session_windows (
session_id TEXT NOT NULL PRIMARY KEY,
session_key TEXT NOT NULL,
previous_session_id TEXT,
reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),
session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
transcript_updated_at INTEGER DEFAULT NULL,
row_transcript_json TEXT,
row_transcript_updated_at INTEGER,
transcript_observed_at INTEGER DEFAULT NULL,
session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),
acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),
plugin_owner_id TEXT,
hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),
started_at INTEGER,
ended_at INTEGER,
status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),
channel TEXT,
account_id TEXT,
primary_conversation_id TEXT,
model_provider TEXT,
model TEXT,
agent_harness_id TEXT,
parent_session_key TEXT,
spawned_by TEXT,
display_name TEXT,
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_updated_at
ON session_windows(updated_at DESC, session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_session_key
ON session_windows(session_key, updated_at DESC, session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_created_at
ON session_windows(created_at DESC, session_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_windows_conversation
ON session_windows(primary_conversation_id)
WHERE primary_conversation_id IS NOT NULL;
-- Offline imports and repairs queue explicit work; admission also settles keys
-- removed during repair, so the queue deliberately has no node foreign key.
CREATE TABLE IF NOT EXISTS session_canonical_validation_pending (
session_key TEXT NOT NULL PRIMARY KEY
) STRICT;
CREATE TABLE IF NOT EXISTS conversations (
conversation_id TEXT NOT NULL PRIMARY KEY,
channel TEXT NOT NULL,
account_id TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('direct', 'group', 'channel')),
peer_id TEXT NOT NULL,
delivery_target TEXT NOT NULL,
parent_conversation_id TEXT,
thread_id TEXT,
native_channel_id TEXT,
native_direct_user_id TEXT,
label TEXT,
metadata_json TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_conversations_lookup
ON conversations(channel, account_id, kind, peer_id, thread_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_conversations_identity
ON conversations(
channel,
account_id,
kind,
peer_id,
IFNULL(parent_conversation_id, ''),
IFNULL(thread_id, '')
);
CREATE INDEX IF NOT EXISTS idx_agent_conversations_updated
ON conversations(updated_at DESC, conversation_id);
CREATE TABLE IF NOT EXISTS conversation_deliveries (
operation_id TEXT NOT NULL PRIMARY KEY,
operation_kind TEXT NOT NULL CHECK (operation_kind IN ('send', 'turn')),
conversation_id TEXT NOT NULL,
source_session_key TEXT,
message_hash TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied')),
prepared_message_id TEXT,
platform_message_id TEXT,
queue_id TEXT,
rejection_error TEXT,
reply_message_id TEXT,
reply_to_id TEXT,
reply_thread_id TEXT,
reply_text TEXT,
reply_timestamp INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
CHECK (
(status = 'rejected' AND rejection_error IS NOT NULL) OR
(status != 'rejected' AND rejection_error IS NULL)
),
FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_reply
ON conversation_deliveries(conversation_id, platform_message_id, prepared_message_id)
WHERE status IN ('queued', 'sent', 'replied');
CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_updated
ON conversation_deliveries(updated_at DESC, operation_id);
CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_source_session
ON conversation_deliveries(source_session_key, operation_id);
CREATE TABLE IF NOT EXISTS session_conversations (
session_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')),
route_context_json TEXT,
first_seen_at INTEGER NOT NULL,
last_seen_at INTEGER NOT NULL,
PRIMARY KEY (session_id, conversation_id, role),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;
-- Older same-version writers preserve the envelope while updating the association.
CREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update
AFTER UPDATE OF role, last_seen_at ON session_conversations
WHEN NEW.route_context_json IS OLD.route_context_json
BEGIN
UPDATE session_conversations
SET route_context_json = NULL
WHERE session_id = NEW.session_id
AND conversation_id = NEW.conversation_id
AND role = NEW.role;
END;
CREATE INDEX IF NOT EXISTS idx_agent_session_conversations_conversation
ON session_conversations(conversation_id, last_seen_at DESC, session_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_session_conversations_primary
ON session_conversations(session_id)
WHERE role = 'primary';
CREATE TABLE IF NOT EXISTS session_members (
session_key TEXT NOT NULL,
identity_id TEXT NOT NULL,
added_by TEXT NOT NULL,
added_at INTEGER NOT NULL,
PRIMARY KEY (session_key, identity_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_members_identity
ON session_members(identity_id, session_key);
CREATE TABLE IF NOT EXISTS session_suggestions (
id TEXT PRIMARY KEY,
session_key TEXT NOT NULL,
author_id TEXT NOT NULL,
author_label TEXT,
text TEXT NOT NULL,
created_at INTEGER NOT NULL,
state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'dismissed')),
dispatch_token TEXT,
dispatch_started_at INTEGER,
dispatch_resolution TEXT CHECK (dispatch_resolution IN ('send', 'queue', 'edit', 'dismiss')),
CHECK (
(dispatch_token IS NULL AND dispatch_started_at IS NULL AND dispatch_resolution IS NULL)
OR (dispatch_token IS NOT NULL AND dispatch_started_at IS NOT NULL AND dispatch_resolution IS NOT NULL)
),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_session_state_created
ON session_suggestions(session_key, state, created_at, id);
CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_author_created
ON session_suggestions(author_id, created_at, id);
CREATE TABLE IF NOT EXISTS session_reactions (
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
message_id TEXT NOT NULL,
emoji TEXT NOT NULL,
identity_id TEXT NOT NULL,
identity_label TEXT,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_key, session_id, message_id, emoji, identity_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS board_tabs (
session_key TEXT NOT NULL,
tab_id TEXT NOT NULL,
title TEXT NOT NULL,
position INTEGER NOT NULL CHECK (position >= 0),
chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),
created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
revision INTEGER NOT NULL CHECK (revision >= 0),
PRIMARY KEY (session_key, tab_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS board_widgets (
session_key TEXT NOT NULL,
name TEXT NOT NULL,
tab_id TEXT NOT NULL,
title TEXT,
content_kind TEXT NOT NULL CHECK (content_kind IN ('html', 'mcp-app', 'plugin')),
html BLOB,
descriptor_json TEXT,
sha256 TEXT NOT NULL,
view_generation TEXT,
revision INTEGER NOT NULL CHECK (revision >= 1),
size_w INTEGER NOT NULL CHECK (size_w BETWEEN 1 AND 12),
size_h INTEGER NOT NULL CHECK (size_h BETWEEN 1 AND 20),
position INTEGER NOT NULL CHECK (position >= 0),
manifest TEXT NOT NULL DEFAULT '{}',
grant_state TEXT NOT NULL DEFAULT 'none' CHECK (grant_state IN ('none', 'pending', 'granted', 'rejected')),
granted_sha TEXT,
created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_key, name),
FOREIGN KEY (session_key, tab_id) REFERENCES board_tabs(session_key, tab_id) ON DELETE CASCADE,
CHECK (
(content_kind = 'html' AND html IS NOT NULL AND descriptor_json IS NULL AND view_generation IS NOT NULL) OR
(content_kind = 'mcp-app' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL) OR
(content_kind = 'plugin' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL)
)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position
ON board_widgets(session_key, tab_id, position);
CREATE TABLE IF NOT EXISTS session_progress_cards (
session_key TEXT NOT NULL PRIMARY KEY,
markdown TEXT,
steps_json TEXT,
revision INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS heartbeat_outcomes (
session_key TEXT NOT NULL PRIMARY KEY,
run_session_key TEXT NOT NULL,
outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),
summary TEXT NOT NULL,
response_reason TEXT,
priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),
next_check TEXT,
task_names_json TEXT,
wake_source TEXT,
wake_reason TEXT,
occurred_at INTEGER NOT NULL,
context_run_id TEXT,
context_claimed_at INTEGER,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS message_tool_run_outcomes (
id INTEGER PRIMARY KEY,
run_id TEXT NOT NULL,
session_key TEXT NOT NULL,
agent_id TEXT NOT NULL,
provider TEXT NOT NULL,
model TEXT NOT NULL,
outcome TEXT NOT NULL CHECK (outcome IN ('tool_delivered', 'mute')),
run_status TEXT NOT NULL CHECK (run_status IN ('completed', 'errored', 'aborted')),
occurred_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_message_tool_run_outcomes_occurred
ON message_tool_run_outcomes(occurred_at DESC, id DESC);
-- Receipts outlive Goal clear and session reset so a delayed retry cannot recreate a Goal.
-- They intentionally have no session FK; bounded retention belongs to the operation owner.
CREATE TABLE IF NOT EXISTS session_creation_operations (
operation_digest TEXT PRIMARY KEY,
request_fingerprint TEXT NOT NULL,
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
lifecycle_revision TEXT,
role TEXT,
scopes_json TEXT NOT NULL,
expires_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_creation_operations_expiry
ON session_creation_operations(expires_at);
-- END SESSION CREATION OPERATIONS
CREATE TABLE IF NOT EXISTS session_goal_operations (
session_key TEXT NOT NULL,
operation_id TEXT NOT NULL,
session_id TEXT NOT NULL,
request_fingerprint TEXT NOT NULL,
result_json TEXT NOT NULL,
expires_at INTEGER NOT NULL,
PRIMARY KEY (session_key, operation_id)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_goal_operations_expiry
ON session_goal_operations(expires_at);
CREATE TABLE IF NOT EXISTS transcript_events (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_json TEXT,
created_at INTEGER NOT NULL,
event_zstd BLOB,
event_utf8_bytes INTEGER CHECK (event_utf8_bytes IS NULL OR event_utf8_bytes >= 0),
navigation_json TEXT,
navigation_type TEXT,
navigation_custom_type TEXT,
navigation_display INTEGER NOT NULL DEFAULT 0,
message_role TEXT,
navigation_last_type TEXT,
navigation_last_custom_type TEXT,
navigation_valid INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
CHECK (
(event_json IS NOT NULL AND event_zstd IS NULL)
OR (
event_json IS NULL AND event_zstd IS NOT NULL
AND event_utf8_bytes IS NOT NULL
AND event_utf8_bytes BETWEEN 1 AND 4194304
AND length(event_zstd) BETWEEN 1 AND 4194304
AND navigation_json IS NOT NULL
)
OR (
event_json IS NULL AND event_zstd IS NULL
AND event_utf8_bytes IS NOT NULL
AND event_utf8_bytes BETWEEN 1 AND 4194304
AND navigation_json IS NOT NULL
)
),
CHECK (
navigation_json IS NULL OR CASE WHEN json_valid(navigation_json) THEN coalesce(
octet_length(navigation_json) <= 16384
AND json_type(navigation_json, '$.version') = 'integer'
AND json_extract(navigation_json, '$.version') = 1
AND json_type(navigation_json, '$.report') = 'object'
AND json_extract(navigation_json, '$.report.kind') IN ('canonical', 'leaf', 'link', 'ignored')
AND json_type(navigation_json, '$.navigation') = 'object'
AND json_type(navigation_json, '$.reset') = 'object'
AND json_type(navigation_json, '$.model') = 'object'
AND json_type(navigation_json, '$.modelBytes') = 'integer'
AND json_extract(navigation_json, '$.modelBytes') BETWEEN 0 AND 4194304
AND json_type(navigation_json, '$.modelWithoutCheckpointBytes') = 'integer'
AND json_extract(navigation_json, '$.modelWithoutCheckpointBytes') BETWEEN 0 AND 4194304
AND json_type(navigation_json, '$.withoutCustomDataBytes') = 'integer'
AND json_extract(navigation_json, '$.withoutCustomDataBytes') BETWEEN 0 AND 4194304,
0) ELSE 0 END
)
) STRICT;
-- Canonical cold-tier owner for reclaimed transcript generations. The derived
-- .deleted/.reset file may be recreated from this row after a crash.
CREATE TABLE IF NOT EXISTS session_transcript_archives (
session_id TEXT NOT NULL,
generation TEXT NOT NULL,
session_key TEXT NOT NULL,
reason TEXT NOT NULL CHECK (reason IN ('deleted', 'reset')),
encoding TEXT NOT NULL CHECK (encoding IN ('identity', 'zstd')),
archive_blob BLOB NOT NULL,
archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
archive_name TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
published_at INTEGER,
publish_attempts INTEGER NOT NULL DEFAULT 0 CHECK (publish_attempts >= 0),
last_publish_attempt_at INTEGER,
last_publish_error TEXT,
PRIMARY KEY (session_id, generation),
CHECK (archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_pending
ON session_transcript_archives(created_at, session_id, generation)
WHERE published_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_retention
ON session_transcript_archives(created_at, session_id, generation);
CREATE TABLE IF NOT EXISTS session_transcript_cold_archives (
session_id TEXT NOT NULL PRIMARY KEY,
generation TEXT NOT NULL,
archive_name TEXT NOT NULL UNIQUE,
archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
event_count INTEGER NOT NULL CHECK (event_count >= 1),
raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
last_seq INTEGER NOT NULL,
archived_at INTEGER NOT NULL,
storage TEXT NOT NULL CHECK (storage IN ('file', 'sqlite')),
archive_blob BLOB,
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%'),
CHECK ((storage = 'file' AND archive_blob IS NULL) OR (storage = 'sqlite' AND archive_blob IS NOT NULL))
) STRICT;
CREATE TABLE IF NOT EXISTS session_transcript_cold_archive_chunks (
session_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
archive_name TEXT NOT NULL UNIQUE,
archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
first_seq INTEGER NOT NULL,
last_seq INTEGER NOT NULL CHECK (last_seq >= first_seq),
event_count INTEGER NOT NULL CHECK (event_count >= 1),
raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
archive_blob BLOB,
PRIMARY KEY (session_id, chunk_index),
FOREIGN KEY (session_id) REFERENCES session_transcript_cold_archives(session_id) ON DELETE CASCADE,
CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT, WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (
session_id TEXT NOT NULL PRIMARY KEY,
generation TEXT NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS trajectory_runtime_events (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
run_id TEXT,
event_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
event_utf8_bytes INTEGER,
event_payload BLOB,
event_codec TEXT,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_trajectory_runtime_run
ON trajectory_runtime_events(session_id, run_id, created_at, COALESCE(event_utf8_bytes, octet_length(event_json)));
CREATE TABLE IF NOT EXISTS acp_parent_stream_events (
session_id TEXT NOT NULL,
run_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_id, run_id, seq),
FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_acp_parent_stream_run
ON acp_parent_stream_events(run_id, seq);
CREATE TABLE IF NOT EXISTS transcript_event_identities (
session_id TEXT NOT NULL,
event_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_type TEXT,
parent_id TEXT,
message_idempotency_key TEXT,
created_at INTEGER NOT NULL,
PRIMARY KEY (session_id, event_id),
FOREIGN KEY (session_id, seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_message_idempotency
ON transcript_event_identities(session_id, message_idempotency_key)
WHERE message_idempotency_key IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_identity_sequence
ON transcript_event_identities(session_id, seq);
CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence
ON transcript_event_identities(session_id, event_type, seq DESC);
CREATE TABLE IF NOT EXISTS context_engine_turn_outbox (
enqueue_sequence INTEGER PRIMARY KEY,
advancement_key TEXT NOT NULL UNIQUE,
engine_id TEXT NOT NULL,
owner_plugin_id TEXT,
session_id TEXT NOT NULL,
payload_json TEXT NOT NULL,
payload_state TEXT,
attempt_count INTEGER NOT NULL DEFAULT 0,
last_attempt_at INTEGER,
last_error TEXT,
created_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_context_engine_turn_outbox_engine
ON context_engine_turn_outbox(engine_id, created_at);
CREATE TABLE IF NOT EXISTS agent_tool_usage (
tool_id TEXT PRIMARY KEY NOT NULL,
score REAL NOT NULL CHECK (score >= 0),
updated_at INTEGER NOT NULL
) STRICT;
-- END AGENT TOOL USAGE
CREATE TABLE IF NOT EXISTS cache_entries (
scope TEXT NOT NULL,
key TEXT NOT NULL,
value_json TEXT,
blob BLOB,
expires_at INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (scope, key)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_cache_expiry
ON cache_entries(scope, expires_at, key)
WHERE expires_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_cache_updated
ON cache_entries(scope, updated_at DESC, key);
CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_scope
ON cache_entries(CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.agentId') END,
CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.sessionKey') END, CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.origin') END)
WHERE scope = 'talk-client-voice-sessions'
AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';
CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_updated
ON cache_entries(scope, updated_at)
WHERE scope = 'talk-client-voice-sessions'
AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';
CREATE TABLE IF NOT EXISTS auth_profile_store (
store_key TEXT NOT NULL PRIMARY KEY,
store_json TEXT NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS auth_profile_state (
state_key TEXT NOT NULL PRIMARY KEY,
state_json TEXT NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_sources (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'memory',
hash TEXT NOT NULL,
mtime REAL NOT NULL,
size INTEGER NOT NULL,
UNIQUE (path, source)
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_chunks (
chunk_rowid INTEGER PRIMARY KEY,
id TEXT NOT NULL UNIQUE,
path TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'memory',
start_line INTEGER NOT NULL,
end_line INTEGER NOT NULL,
hash TEXT NOT NULL,
model TEXT NOT NULL,
text TEXT NOT NULL,
embedding BLOB NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_chunk_recall_metadata (
chunk_id TEXT PRIMARY KEY,
importance INTEGER CHECK (importance IS NULL OR importance BETWEEN 1 AND 10),
triggers TEXT,
project_key TEXT,
FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_chunk_provenance (
chunk_id TEXT PRIMARY KEY,
origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),
observed_at INTEGER NOT NULL,
supersedes_key TEXT,
FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS memory_entry_origins (
entry_key TEXT NOT NULL,
agent_id TEXT NOT NULL,
session_id TEXT NOT NULL,
session_key TEXT,
origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
observed_at INTEGER NOT NULL,
PRIMARY KEY (entry_key, agent_id, session_id)
) STRICT, WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS memory_session_tombstones (
session_id TEXT NOT NULL PRIMARY KEY,
agent_id TEXT NOT NULL,
reason TEXT NOT NULL,
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS memory_embedding_cache (
provider TEXT NOT NULL,
model TEXT NOT NULL,
provider_key TEXT NOT NULL,
hash TEXT NOT NULL,
embedding BLOB NOT NULL,
dims INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (provider, model, provider_key, hash)
) STRICT;
CREATE TABLE IF NOT EXISTS memory_index_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
revision INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS standing_intents (
intent_key INTEGER PRIMARY KEY,
id TEXT NOT NULL UNIQUE,
description TEXT NOT NULL,
trigger_keywords TEXT NOT NULL,
trigger_embedding TEXT,
channel_scope TEXT,
sender_scope TEXT,
creator_sender TEXT CHECK (creator_sender IS NULL OR length(trim(creator_sender)) > 0),
status TEXT NOT NULL CHECK (status IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired')),
expires_at INTEGER NOT NULL,
max_fires INTEGER NOT NULL CHECK (max_fires > 0),
fire_count INTEGER NOT NULL DEFAULT 0 CHECK (fire_count >= 0),
cooldown_seconds INTEGER NOT NULL DEFAULT 86400 CHECK (cooldown_seconds >= 0),
last_fired_at INTEGER,
created_at INTEGER NOT NULL,
source_session_id TEXT
) STRICT;
CREATE INDEX IF NOT EXISTS idx_standing_intents_lifecycle
ON standing_intents(status, expires_at, last_fired_at);
CREATE INDEX IF NOT EXISTS idx_standing_intents_scope
ON standing_intents(status, channel_scope, sender_scope);
CREATE VIRTUAL TABLE IF NOT EXISTS standing_intents_fts USING fts5(
trigger_keywords,
content = 'standing_intents',
content_rowid = 'intent_key',
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_insert
AFTER INSERT ON standing_intents
BEGIN
INSERT INTO standing_intents_fts(rowid, trigger_keywords)
VALUES (new.intent_key, new.trigger_keywords);
END;
CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_delete
AFTER DELETE ON standing_intents
BEGIN
INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
VALUES ('delete', old.intent_key, old.trigger_keywords);
END;
CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_update
AFTER UPDATE OF trigger_keywords ON standing_intents
BEGIN
INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
VALUES ('delete', old.intent_key, old.trigger_keywords);
INSERT INTO standing_intents_fts(rowid, trigger_keywords)
VALUES (new.intent_key, new.trigger_keywords);
END;
CREATE TABLE IF NOT EXISTS session_transcript_index_state (
session_id TEXT NOT NULL PRIMARY KEY,
indexed_seq INTEGER NOT NULL,
leaf_event_id TEXT,
needs_rebuild INTEGER NOT NULL DEFAULT 0,
active_event_count INTEGER NOT NULL DEFAULT 0,
active_message_count INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;
CREATE TABLE IF NOT EXISTS session_transcript_active_events (
session_id TEXT NOT NULL,
active_position INTEGER NOT NULL CHECK (active_position >= 0),
event_seq INTEGER NOT NULL,
message_position INTEGER CHECK (message_position IS NULL OR message_position >= 0),
context_eligible INTEGER,
PRIMARY KEY (session_id, active_position),
FOREIGN KEY (session_id, event_seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_event_seq
ON session_transcript_active_events(session_id, event_seq);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_messages
ON session_transcript_active_events(session_id, message_position)
WHERE message_position IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_agent_transcript_context_pending
ON session_transcript_active_events(session_id)
WHERE context_eligible IS NULL;
CREATE TABLE IF NOT EXISTS session_transcript_active_event_facts (
session_id TEXT NOT NULL,
seq INTEGER NOT NULL,
serialized_bytes INTEGER NOT NULL CHECK (serialized_bytes >= 1),
dependency_navigation_json TEXT NOT NULL,
PRIMARY KEY (session_id, seq),
FOREIGN KEY (session_id, seq)
REFERENCES session_transcript_active_events(session_id, event_seq) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;
-- END ACTIVE EVENT FACTS
CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(
text,
session_id UNINDEXED,
message_id UNINDEXED,
role UNINDEXED,
timestamp UNINDEXED,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (
id INTEGER PRIMARY KEY,
session_id TEXT NOT NULL,
message_id TEXT
) STRICT;
CREATE INDEX IF NOT EXISTS idx_session_transcript_fts_rows_session_message
ON session_transcript_fts_rows(session_id, message_id);
CREATE TRIGGER IF NOT EXISTS session_transcript_fts_rows_after_delete
AFTER DELETE ON session_transcript_fts_rows
BEGIN
DELETE FROM session_transcript_fts WHERE rowid = OLD.id;
END;
INSERT OR IGNORE INTO memory_index_state (id, revision) VALUES (1, 0);
CREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at
ON memory_embedding_cache(updated_at);
CREATE INDEX IF NOT EXISTS idx_memory_index_sources_source
ON memory_index_sources(source);
CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path_source
ON memory_index_chunks(path, source);
CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_source
ON memory_index_chunks(source);
-- Accepted input stays outside the active transcript until its exact turn owns execution.
CREATE TABLE IF NOT EXISTS session_pending_inputs (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
input_id TEXT NOT NULL UNIQUE,
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
run_id TEXT NOT NULL,
request_hash TEXT NOT NULL,
message_json TEXT NOT NULL,
lifecycle_generation TEXT NOT NULL,
state TEXT NOT NULL CHECK (state IN ('queued', 'interrupted', 'cancelled')),
accepted_at INTEGER NOT NULL,
consumed_event_id TEXT,
UNIQUE (session_id, idempotency_key),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_pending_inputs_session
ON session_pending_inputs(session_key, session_id, seq DESC);
-- Processing completion is separate from input consumption; neither schedules replay.
CREATE TABLE IF NOT EXISTS session_input_completions (
session_key TEXT NOT NULL,
session_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
run_id TEXT NOT NULL,
request_hash TEXT NOT NULL,
outcome_json TEXT NOT NULL,
succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
completed_at INTEGER NOT NULL,
PRIMARY KEY (session_id, idempotency_key),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_input_completions_session_key
ON session_input_completions(session_key);
`})),Tf,Ef=__esmMin((()=>{Tf=`
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 device_pairing_browser_requests (
request_id TEXT NOT NULL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
device_id TEXT NOT NULL UNIQUE,
public_key TEXT NOT NULL,
remote_ip TEXT,
user_agent TEXT,
origin TEXT,
status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'rejected')),
approved_token_sha256 TEXT,
created_at_ms INTEGER NOT NULL,
expires_at_ms INTEGER NOT NULL
) 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,
bootstrap_deferred 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 durable_background_processes (
id TEXT NOT NULL PRIMARY KEY,
record_json TEXT NOT NULL
) STRICT;
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,
resource_receipt_json TEXT,
retention_json TEXT,
provision_source_json TEXT
) 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,
disk_authority_json TEXT,
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,
repository_disk_authority_json TEXT,
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=b(`sha256`).update(JSON.stringify([Df,i,e])),s=b(`sha256`).update(e);return e!==`state`&&(a.update(`42`),a.update(Cf),s.update(`42`),s.update(Cf)),e!==`agent`&&(a.update(`40`),a.update(Tf),s.update(`40`),s.update(Tf)),{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:Df}}}var Df,Of=__esmMin((()=>{Sf(),wf(),gt(),Ef(),Df=3}));function sealSchema(e){let t=e.includes(`agent.schema-metadata`),n=t===e.includes(`state.schema-version`)?`other`:t?`agent`:`state`;return kf[n]??=sqliteDatabaseSealSchemaFor(n)}function isSealedKey(e){return Mf.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 kf,Af,jf,Mf,SqliteDatabaseCleanCloseSeals,Nf=__esmMin((()=>{k(),Qd(),Of(),Vd(),Zs(),kf={},Af={name:`sqlite.full-verification`,lifetime:`process`,read:e=>typeof e==`number`&&Number.isSafeInteger(e)?e:void 0},jf={...Af,name:`sqlite.quick-verification`},Mf=/* @__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),P.sealPresent,Atomics.load(new Int32Array(n),P.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,u.fstatSync(e.descriptor,{bigint:!0}),t=>{e.cleanCloseRefusal=t});if(!n||typeof n.facts!=`string`)return;let r=JSON.parse(n.facts,decodeSealValue);if(!Array.isArray(r)||!r.every(e=>Array.isArray(e)&&e.length===3&&typeof e[0]==`string`&&isSealedKey(e[0])&&typeof e[1]==`boolean`)||!r.some(([e,,t])=>(e===Af.name||e===jf.name)&&t===n.verifiedAt)||!r.some(([e,,t])=>e===`sqlite-schema`&&isRecord(t)))return;let i=sealSchema(r.map(([e])=>e));if(!i){e.cleanCloseRefusal=`identity-mismatch`;return}let a=n.identity;if(a!==void 0&&(!isRecord(a)||typeof a.runtime!=`string`||typeof a.schema!=`string`||typeof a.policy!=`number`))return;if(isRecord(a)&&typeof a.sqlite!=`string`){if(!isRecord(a.sqlite)||typeof a.sqlite.version!=`string`||typeof a.sqlite.sourceId!=`string`||typeof a.sqlite.compileOptions!=`string`)return;let t=a.schema!==i.identity.schema,n=a.policy!==i.identity.policy,r=a.sqlite.compileOptions!==i.identity.sqlite.compileOptions;if(t||n||r){e.cleanCloseRefusal=t?`schema-mismatch`:n?`policy-mismatch`:`feature-mismatch`;return}}else if(n.schemaIdentity!==i.schemaIdentity){e.cleanCloseRefusal=`identity-mismatch`;return}let s=r.find(([e])=>e===`sqlite-schema`)?.[2];if(!(s.tableSql instanceof Map))return;if(hasPendingAgentStartupColumns(s.tableSql)){e.cleanCloseRefusal=`schema-mismatch`;return}delete e.cleanCloseRefusal;for(let[t,n,i]of r)this.publishFact(e,{name:t,schemaDependent:n,lifetime:`process`},{value:i},readSqliteDatabaseFactRevision(e,n));Atomics.store(new Int32Array(e.generation),P.sealPresent,1)}catch{}finally{this.references.publish(e)}}}invalidate(e,t){invalidateSqliteCleanCloseSeal(t?.location??e),t&&Atomics.store(new Int32Array(t.generation),P.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 r=[...t.facts].filter(([e,n])=>isSealedKey(e)&&isSqliteDatabaseAdmissionFactCurrent(t,n));if(!r.some(([e])=>e===`sqlite-schema`))return()=>!1;let i=JSON.stringify(r.map(([e,t])=>[e,t.schemaDependent,t.value]),encodeSealValue),a=sealSchema(r.map(([e])=>e));return a?()=>{if(e.isOpen||readSqliteDatabaseGeneration(t,`retired`)!==0||r.some(([,e])=>Atomics.load(new Int32Array(e.current),0)!==1||e.revision!==readSqliteDatabaseFactRevision(t,e.schemaDependent)))return!1;try{let e=u.fstatSync(t.descriptor,{bigint:!0});if(readSqliteDatabaseAdmissionIdentity(u.statSync(t.location,{bigint:!0}))!==t.identity)return!1;let r=writeSqliteCleanCloseSeal(t.location,a.schemaIdentity,e,{verifiedAt:n,facts:i,identity:a.identity});return Atomics.store(new Int32Array(t.generation),P.sealPresent,+!!r),r}catch{return!1}}:()=>!1}}}));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&Lf}function isSqliteLockError(e){let t=sqliteErrorCode(e);if(t!==void 0&&Pf.has(t))return!0;let n=sqlitePrimaryResultCode(e);return n===Ff||n===If}var Pf,Ff,If,Lf,Rf=__esmMin((()=>{k(),j(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteInspectionOperations`),()=>/* @__PURE__ */ new WeakMap),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeOpenFailures`),()=>/* @__PURE__ */ new WeakSet),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotFailureScopes`),()=>new D),Pf=/* @__PURE__ */ new Set([`SQLITE_BUSY`,`SQLITE_LOCKED`]),Ff=5,If=6,Lf=255}));function hasSqlitePostCommitScope(e){return zf.has(sqlPublicationAnchor(e))}function stageSqliteTransactionState(e,t){let n=Bf.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 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);zf.get(r)?.splice(0);let i=Bf.get(r)?.splice(0)??[];zf.delete(r),Bf.delete(r),rollbackTransactionState(i,t,n)}var zf,Bf,Vf=__esmMin((()=>{v_(),j(),ls(),Hd(),createSubsystemLogger(`sqlite/publication`),zf=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePostCommitPublications`),()=>/* @__PURE__ */ new WeakMap),Bf=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteTransactionState`),()=>/* @__PURE__ */ new WeakMap)}));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(Hf,``),s);){a+=1;let e=s.includes(`;`)?findSqlCharacter(s,`;`):-1,c=e<0?s:s.slice(0,e),l=Uf.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 Hf,Uf,Wf=__esmMin((()=>{Jd(),Hf=/^(?:\s|;|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/u,Uf=/^(BEGIN|SAVEPOINT|COMMIT|END|RELEASE|ROLLBACK)\b/i}));function isPreparingSqliteNativeMutation(e){return Kf.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=Kf.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 Gf.set(e,(Gf.get(e)??0)+1),{...a,finish(t,n,r){try{a.finish(t,n,r)}finally{let t=(Gf.get(e)??1)-1;t===0?Gf.delete(e):Gf.set(e,t)}}}},r=/* @__PURE__ */ new Set,execute=(t,n,r=`execute`)=>{let i=Kf.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,resolveMutation=()=>a??=classifySqliteMutation(i.sourceSQL,`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)),resolveMutation());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||=(qf.register(i,d),!0);let a=execute(()=>reset(()=>callStatement(u??t.StatementSync.prototype.iterate.bind(i),n)),Jf,`bind`),s=new WeakRef(a),c=createIteratorLifetime(d,r),l=a.next,p=a.return,m;return a.next=function(...t){if(m&&this===s.deref()&&e.isOpen)return{...m};if(this!==s.deref()||c.invalidated||!e.isOpen)return l.apply(this,t);c.finished&&(c.finished=!1,d.add(c)),c.observed??=begin(resolveMutation(),`iterate`),r.add(c);let n=l.apply(this,t);return n.done?(p?.call(this),m={...n},c.finish(!0)):c.observed?.stepped?.(),n},p&&(a.return=function(...t){if(m&&this===s.deref()&&e.isOpen)return{...m};if(this!==s.deref()||!e.isOpen)return p.apply(this,t);let n=execute(()=>c.finished||c.invalidated?p.apply(this,t):reset(()=>p.apply(this,t),`return`),Jf,`bind`);return n.done&&(m={...n}),c.finish(),n}),a};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 Gf,Kf,qf,Jf,Yf=__esmMin((()=>{j(),Rf(),Vf(),Wf(),ic(),Gf=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeExecution`),()=>/* @__PURE__ */ new WeakMap),Kf=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePreparedNativeMutation`),()=>/* @__PURE__ */ new WeakMap),qf=new FinalizationRegistry(e=>{for(let t of e)t.finish(!1,!0)}),Jf={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&¬ifyListeners(n,void 0)}}function withSqliteDatabaseWriteScope(t,n,r){let i=sqlPublicationAnchor(t),a=e.admission(i);if(!(a?readSqliteDatabaseGeneration(a,`writeScopeRevision`)>0:R.localScopeRevisions.has(i))){let e=r();if(isPromiseLike(e))throw Error(`SQLite write scopes cannot await work`);return e}let s=normalizedWriteScopes(n),c=R.writeScopes.get(i);R.writeScopes.set(i,s);try{let e=r();if(isPromiseLike(e))throw Error(`SQLite write scopes cannot await work`);return e}finally{c?R.writeScopes.set(i,c):R.writeScopes.delete(i)}}function withoutSqliteDatabaseWriteScope(e,t){let n=sqlPublicationAnchor(e),r=R.writeScopes.get(n);R.writeScopes.delete(n);try{return t()}finally{r&&R.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}let t,n=0;function createScopeRevision(){t&&n!==t.byteLength||(t=new SharedArrayBuffer(48*Int32Array.BYTES_PER_ELEMENT),n=0);let e=new Int32Array(t,n,3);return n+=e.byteLength,{identity:S(),state:e}}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??R.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=R.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 prepareSqliteDatabaseScopedWriteRevisionForPath(t,n){let r=retainSqliteDatabaseWriteScopesForPath(t,n);if(!r)return;let i=e.pathAdmission(t);if(!i){r();return}let a=normalizedWriteScopes(n).map(e=>i.writeScopes.get(e)),s=a.map(e=>Atomics.load(e.state,0)),c=/* @__PURE__ */ new WeakMap,l=new Int32Array(i.generation),u=!1,inspectReference=e=>{let t=c.get(e);t||(t=new Int32Array(e),c.set(e,t)),u||=Atomics.load(t,1)>0},d=Atomics.load(l,P.schemaRevision),f=Atomics.load(l,P.unscopedWriteRevision),p=0,m=!1;return{read(){if(m||Atomics.load(l,P.retired)!==0||(u=!1,i.references.forEach(inspectReference),u))return;let e=Atomics.load(l,P.schemaRevision),t=Atomics.load(l,P.unscopedWriteRevision),n=d!==e||f!==t;d=e,f=t;for(let e=0;e<a.length;e++){let t=a[e];if(Atomics.load(t.state,1)!==0)return;let r=Atomics.load(t.state,0);n||=s[e]!==r,s[e]=r}return n&&p++,p},release(){m||(m=!0,r())}}}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`,(R.localUnscopedRevisions.get(e)??0)+ +(n===null),t.map(t=>[t,R.localScopeRevisions.get(e).get(t).identity,Atomics.load(R.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`,Be(e)]:[`session-id`,Be(e.sessionId),...e.partition===void 0?[]:[Be(e.partition)]])))].toSorted()}function ensureLocalWriteScopes(e,t){let n=R.localScopeRevisions.get(e)??/* @__PURE__ */ new Map;for(let e of t)n.has(e)||n.set(e,createScopeRevision());R.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,r){let i=normalizedWriteScopes(n),a=e.pathAdmission(t,r);if(a&&!isSqliteDatabaseAdmissionRetired(a))return ensureWriteScopes(a,i),scopedWriteToken(a,i)}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,R.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){R.pendingWriteScopes.delete(e)},begin(e,t){let n=t?void 0:R.writeScopes.get(e),r=R.pendingWriteScopes.get(e);if(!n||r===null)R.pendingWriteScopes.set(e,null);else{let t=r??/* @__PURE__ */ new Set;for(let e of n)t.add(e);R.pendingWriteScopes.set(e,t)}},finish(e,t){let n=R.pendingWriteScopes.get(e);R.pendingWriteScopes.delete(e);let r=!n;if(n){let i=R.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&&(R.localUnscopedRevisions.set(e,(R.localUnscopedRevisions.get(e)??0)+1),t&&advanceSqliteDatabaseGeneration(t,`unscopedWriteRevision`))},settleWorker,onSqliteDatabaseWriteSettled,retireSqliteDatabaseWriteScopes,retainSqliteDatabaseWriteScopesForPath,prepareSqliteDatabaseScopedWriteRevisionForPath,withSqliteDatabaseWriteScope,withoutSqliteDatabaseWriteScope,readSqliteDatabaseScopedWriteToken,readSqliteDatabaseScopedWriteTokenForPath,readSqliteDatabaseScopedWriteTokensForPath,readSqliteDatabasePendingScopedWriteToken,readSqliteDatabaseWriteTokenForPath,readSqliteDatabasePendingWriteToken}}var R,Xf=__esmMin((()=>{ss(),j(),os(),ls(),Zs(),Yf(),Vf(),R=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 Zf,Qf,$f=__esmMin((()=>{j(),Zf=resolveGlobalSingleton(Symbol.for(`openclaw.postgresReadSnapshots`),()=>/* @__PURE__ */ new WeakMap),Qf=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSchemaFacts`),()=>/* @__PURE__ */ new WeakMap)}));function bindSqliteDatabaseAdmission(e,t){F.connections.delete(e),F.openedIdentities.delete(e),F.unproven.delete(e);let n=e.location();if(!n||n===`:memory:`)return;let r=op(n);if(t!==void 0&&r!==t)throw Error(`SQLite database changed identity during native open`);if(!r)return;if(F.openedIdentities.set(e,r),t===void 0){F.unproven.add(e);return}let i=F.registry.records.get(r);(i&&!isSqliteDatabaseAdmissionRetired(i)||F.registry.descriptors.get(r)?.facts.size)&&admission$1(e)}function admission$1(e,t=!0){let n=F.openedIdentities.get(e);if(!e.isOpen||n===void 0||F.unproven.has(e))return;let r=F.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?sp(i,n):F.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=F.registry.changeReferences(r,1),i=!1;try{t&&exchangeSqliteDatabaseAdmission(r);let n=readSqliteDatabaseGeneration(r,`retired`);if(n===0)return F.connections.set(e,r),i=!0,r;if(n!==2)throw Error(`SQLite database admission retired during native open`)}finally{i||F.registry.changeReferences(r,-1)}let a=e.location(),s=e.isTransaction?F.registry.records.get(n):a?sp(a,op(a)):void 0;if(!s||isSqliteDatabaseAdmissionRetired(s))throw Error(`SQLite database admission unavailable during native open`);r=s}}catch(t){throw F.openedIdentities.delete(e),t}}function releaseSqliteDatabaseAdmission(e){let t=F.connections.get(e);F.openedIdentities.delete(e)&&t&&(F.local.delete(e),releaseReference(t))}function retainReference(e){F.registry.changeReferences(e,1)&&exchangeSqliteDatabaseAdmission(e)}function releaseReference(e){F.registry.changeReferences(e,-1)&&(F.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}:${++F.publication}`)&&(F.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),P.sealPresent)===1&&ep.invalidate(n.location,n),Tp.begin(e,t),!F.dataWriters.has(e)&&(F.dataWriters.set(e,n),n&&Atomics.add(new Int32Array(n.references.get(E)),1,1))}function finishSqliteDatabaseWrite(e,t=!1){if(!F.dataWriters.has(e))return;let n=F.dataWriters.get(e);if(F.dataWriters.delete(e),t)Tp.cancel(e),n&&Atomics.sub(new Int32Array(n.references.get(E)),1,1);else if(F.localWriteRevisions.set(e,(F.localWriteRevisions.get(e)??0)+1),Tp.finish(e,n),n){advanceSqliteDatabaseGeneration(n,`writeRevision`),Atomics.sub(new Int32Array(n.references.get(E)),1,1);let e=F.writeListeners.get(n);e&¬ifyListeners(e,void 0)}}function trackSqliteDatabaseAdmissionWorker(e){let t=e.threadId;e.once(`exit`,()=>{for(let e of F.registry.records.values())Tp.settleWorker(e,t);F.registry.releaseWorker(t)})}function publishSqliteDatabaseAdmission(e,t,n,r={}){let i=sqlPublicationAnchor(e),a=admission$1(i,!e.isTransaction);if(!a||isSqliteDatabaseAdmissionRetired(a)||F.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:F.ddlRevisions.get(i)??0};if(c){c.set(t.name,u);return}let d=F.local.get(i)??/* @__PURE__ */ new Map;F.local.set(i,d);let f=d.get(t.name);stageSqliteTransactionState(i,{stage:()=>d.set(t.name,u),rollback:()=>{F.local.get(i)===d&&(f===void 0?d.delete(t.name):d.set(t.name,f))},commit:()=>{F.local.get(i)===d&&d.get(t.name)===u&&(d.delete(t.name),u.revision!==readSqliteDatabaseFactRevision(a,u.schemaDependent)||u.schemaDependent&&u.ddlRevision!==(F.ddlRevisions.get(i)??0)||publishFact(a,t,u,u.revision))}})}function invalidateLocalSqliteSchemaAdmissions(e){let t=sqlPublicationAnchor(e),n=F.ddlRevisions.get(t)??0,r=F.schemaDirty.has(t),stage=()=>{F.ddlRevisions.set(t,n+1),F.schemaDirty.add(t)};stageSqliteTransactionState(t,{stage,commit:()=>{},rollback:()=>{F.ddlRevisions.set(t,n),r||F.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),F.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()}F.local.delete(t),F.rolledBack.add(t),e.isTransaction||F.schemaDirty.delete(t)}function publishSqliteDatabaseSchemaChange(e){let t=sqlPublicationAnchor(e),n=admission$1(t,!1);if(n){let e=advanceSqliteDatabaseGeneration(n,`schemaRevision`),r=F.ddlRevisions.get(t)??0;for(let n of F.local.get(t)?.values()??[])n.schemaDependent&&n.revision===e&&n.ddlRevision===r&&(n.revision=e+1)}else{let e=F.openedIdentities.get(t);e&&F.localSchemaRevisions.set(e,(F.localSchemaRevisions.get(e)??0)+1)}e.isTransaction||F.schemaDirty.delete(t)}function suspendSqliteDatabaseAdmission(e,t){t?F.suspended.add(e):F.suspended.delete(e)}var ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp=__esmMin((()=>{j(),os(),ls(),$s(),Ud(),Kd(),Zs(),Nf(),oc(),Xf(),Gd(),Vf(),$f(),ep=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseCleanCloseSeals`),()=>new SqliteDatabaseCleanCloseSeals(publishFact,{retain:e=>F.registry.changeReferences(e,1),release:releaseReference,publish:e=>F.registry.publish(e),descriptor:e=>F.registry.descriptors.get(e.identity)})),tp=createSqliteDatabaseDescriptorOwner(ep),{prepareOwnedSqliteDatabaseAdmission:np,prepareSqliteDatabaseAdmissionAsync:rp,retainSqliteDatabaseAdmissionLocation:ip,retainPreparedSqliteDatabaseAdmissionLocation:ap,prepareSqliteDatabaseAdmission:op}=tp,{pathAdmission:sp}=tp,cp=createSqliteDatabaseAdmissionReader({state:F,admission:admission$1,pathAdmission:sp,prepareFileIdentity:op,integrityVerificationKey:Af,exchange:exchangeSqliteDatabaseAdmission,publishFact,retain:retainReference,release:releaseReference}),{readSqliteDatabaseCleanClose:lp,readSqliteDatabaseWriteRevision:up,readSqliteDatabaseSiblingWriteRevision:dp,readSqliteDatabaseIntegrityVerification:fp,readSqliteDatabaseCleanCloseRefusal:pp,getSqliteDatabaseAdmission:mp,getSqliteDatabaseSchemaRevision:hp,getOrLoadSqliteDatabaseAdmissionForPath:gp,peekSqliteDatabaseAdmissionForPath:_p,prepareSqliteDatabaseAdmissionForPath:vp,hasSqliteDatabaseSchemaAdmissionForPath:yp,getSqliteDatabaseAdmissionIdentityForPath:bp,getSqliteDatabaseAdmissionSourceForPath:xp,observeSqliteDatabaseAdmissionLocation:Sp,hasSqliteDatabaseSchemaAdmissionForIdentity:Cp,retainSqliteDatabaseAdmissionForPath:wp}=cp,Tp=createSqliteDatabaseWriteReceipts({admission:admission$1,pathAdmission:(e,t)=>t?t.key.startsWith(`file:`)?F.registry.records.get(`${t.key.slice(5)}:${t.birthtime}`):void 0:sp(e),retain:retainReference,release:releaseReference,writeListeners:F.writeListeners,readRevision:up,writer:e=>F.dataWriters.get(e),suspended:e=>F.suspended.has(e),hasPendingSchemaMutation:e=>e.isTransaction&&Qf.get(e)?.transactionalSchema===!0,publish(e,t){F.registry.publish(e,t),exchangeSqliteDatabaseAdmission(e)}}),{onSqliteDatabaseWriteSettled:Ep,retireSqliteDatabaseWriteScopes:Dp,retainSqliteDatabaseWriteScopesForPath:Op,prepareSqliteDatabaseScopedWriteRevisionForPath:kp,withSqliteDatabaseWriteScope:Ap,withoutSqliteDatabaseWriteScope:jp,readSqliteDatabaseScopedWriteToken:Mp,readSqliteDatabaseScopedWriteTokenForPath:Np,readSqliteDatabaseScopedWriteTokensForPath:Pp,readSqliteDatabasePendingScopedWriteToken:Fp,readSqliteDatabaseWriteTokenForPath:Ip,readSqliteDatabasePendingWriteToken:Lp}=Tp}));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 isNativeSettlementReceipt(e){return isRecord(e)&&(e.kind===`completed`||e.kind===`unknown`)&&(e.committed===void 0||isNativeCommitReceipt(e.committed))}function resolveSqliteWorkerFinishSettlement(e,t,n){return e??(n===`not-entered`&&!t?{kind:`completed`}:void 0)}function createSqliteWorkerNativeReceiptOwner(e,t){let n=[],r=!1,i,a=0,s,invalidProtocol=e=>t(new SqliteWorkerError(`SQLite worker ${e} is invalid`,`outcome-unknown`)),installCommitted=s=>{if(s.sequence<=a)return;a=s.sequence;let c={facts:s.facts};i=c,r=!0;try{e(()=>{for(let e of n)e(c)})}catch(e){t(Object.assign(new SqliteWorkerError(`SQLite committed facts publication failed`,`outcome-unknown`),{cause:e}))}finally{r=!1}};return{get committed(){return i},get settlement(){return s},get observingCommit(){return r},observe(e){n.push(e)},receive(e){if(isRecord(e)&&e.kind===`native-commit`){let t=e.committed;return isNativeCommitReceipt(t)?(installCommitted(t),!0):(invalidProtocol(`commit receipt`),!0)}if(isRecord(e)&&e.kind===`native-settlement`){let t=e.settlement;return isNativeSettlementReceipt(t)?(t.committed!==void 0&&installCommitted(t.committed),s={kind:t.kind,...i?{committed:i}:{}},!0):(invalidProtocol(`native settlement`),!0)}return!1},finish(e){s=resolveSqliteWorkerFinishSettlement(s,i,e),r?queueMicrotask(()=>{n.length=0}):n.length=0}}}var zp=__esmMin((()=>{k(),j(),Vf(),gc(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerNativeCommitReceipts`),()=>/* @__PURE__ */ new WeakMap),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerOperationAdmission`),()=>new D)})),Bp=__esmMin((()=>{gc()})),Vp=__esmMin((()=>{nc(),mc(),gc(),Fc(),Gs(),zp(),Bp()})),Hp=__esmMin((()=>{Rp(),gc(),Fc(),zp(),Vp()}));function createSqliteDatabaseAdmissionRelay(e){return createOperationAdmission(()=>{throw Error(`Worker format facts do not grant database authority`)},void 0,e)}function createOperationAdmission(e,t,n,r){let{port1:i,port2:a}=runInDetachedAsyncContext(()=>new be),s={admit:e,prepare:r,assertRelayCurrent:n,inOwnerContext:D.snapshot()},c=/* @__PURE__ */ new Map,l,u=createSqliteDatabaseAdmissionReplies(),d=[],f=!1,p=!1,m,h,g,_,v=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,Up,Gp)===Up?(recordFailure(t,n),Atomics.notify(e,0)):Atomics.load(e,0)===Wp&&d.push(t)},y=createSqliteWorkerNativeReceiptOwner(e=>s?.inOwnerContext(e),e=>recordFailure(e,`protocol`)),receive=e=>{let t=s,n=isRecord(e)?e:void 0;if(m=recordWorkerAuthorityMessage(n,b.requestClass,m),p=!0,n?.kind===`sqlite-database-admissions`){let e=u.receive(n,b,t?.inOwnerContext,e=>recordFailure(e,`protocol`));if(!e)return;let{message:r,decision:i,deadlineAtMs:a,observedLocation:l,assertWaiting:p,publishFacts:m,failFacts:h,finishFacts:g}=e,v,y=!1;try{if(p(),f||!t)throw new SqliteWorkerError(`SQLite worker admission is closed`,`closed`);let e=r.create===`admitted`?t.assertRelayCurrent:void 0;if(r.create===`admitted`&&!e)throw new SqliteWorkerError(`SQLite creation relay is not admitted`,`closed`);let n=readSqliteDatabaseAdmissions(r.admissions);if(!n)throw new SqliteWorkerError(`SQLite admission facts request is invalid`,`unavailable`);installSqliteDatabaseAdmissions(n);let u=_,b=u?.databaseIdentity,x=b&&(r.location===b.databasePath||r.location===u.databasePath)?b:void 0,S=getSqliteDatabaseAdmissionUpstream(),ee=!r.create&&(!r.location||ap(r.location,x,l));if(!S&&ee){m(n);return}if(!S&&r.location&&(!r.create||u||e)){let a=r.location,b=r.create,assertCurrent=()=>{if(p(),f||s!==t||_!==u)throw new SqliteWorkerError(`SQLite worker admission is closed`,`closed`);t.inOwnerContext(()=>{u?.assertRequest?.(),e?.()})};c.set(i,void 0),y=!0,t.inOwnerContext(async()=>{try{await rp({location:a,expectedIdentity:x,observedLocation:l,assertCurrent,...b?{create:{async authorize(e){if(assertCurrent(),b===`admitted`)return;let n=u?.assertCreate?.bind(u),r=u?.prepareCreate?.bind(u);if(!u||!n)throw new SqliteWorkerError(`SQLite worker file creation requires host authority`,`closed`);u.coldOpenPath&&await resolveIdentityPathViaExistingAncestor(u.coldOpenPath)===e&&(v=u.coldOpenPath),assertCurrent(),t.inOwnerContext(()=>u.assertAccess()),r?await t.inOwnerContext(r,e):t.inOwnerContext(n,e),assertCurrent(),t.inOwnerContext(()=>u.assertAccess()),v=void 0},retain(e){c.set(i,e),e.catch(e=>{d.includes(e)||d.push(e)})}}}:{}}),assertCurrent(),m(n)}catch(e){h(e,v)}finally{c.delete(i),g()}});return}let te=r.location,ne=!1;if(r.location&&r.create&&!op(r.location)){te=resolveIdentityPathViaExistingAncestorSync(r.location);let e=te,n=_,i=n?.assertCreate?.bind(n);r.create===`admitted`?ne=!0:n&&i&&(n.coldOpenPath&&resolveIdentityPathViaExistingAncestorSync(n.coldOpenPath)===e&&(v=n.coldOpenPath),t.inOwnerContext(()=>{n.assertRequest?.(),n.assertAccess(),i(e)}),v=void 0,ne=!0)}if(ne&&e&&t.inOwnerContext(e),f)throw new SqliteWorkerError(`SQLite worker admission is closed`,`closed`);if(S){if(S.closed)throw new SqliteWorkerError(`SQLite admission upstream is closed`,`closed`);installSqliteDatabaseAdmissions(withSqliteDatabaseAdmissionWait({deadlineAtMs:a,assertActive:p},()=>exchangeDatabaseAdmissions(S.port,n,te,ne?`admitted`:void 0,l)))}else if(te)try{p(),ne&&op(te,{create:!0});let e=_?.databaseIdentity;ip(te,e&&(te===e.databasePath||te===_?.databasePath)?e:void 0,l)}catch(e){if(!isRecord(e)||e.code!==`ENOENT`)throw e}m(n)}catch(e){h(e,v)}finally{y||g()}return}if(y.receive(e))return;let r=readSqliteWorkerAdmissionDecision(e);if(!r){recordFailure(new SqliteWorkerError(`SQLite worker admission request is invalid`,`unavailable`),`protocol`);return}let{decision:i,expired:a,request:l}=r;if(a())return;c.set(i,void 0);try{h&&t?.inOwnerContext(h,l)}catch(e){refuse(i,e,`domain`);return}if(f||!t){refuse(i,new SqliteWorkerError(`SQLite worker admission is closed`,`closed`),`authority`);return}let grant=e=>{if(f||a()||Atomics.load(i,0)!==Up)return!1;try{t.inOwnerContext(()=>_?.assertAccess())}catch(e){return refuse(i,e,`authority`),!1}if(f||a()||Atomics.load(i,0)!==Up||(e?.(),a()))return!1;let n=Atomics.compareExchange(i,0,Up,Wp)===Up;return n&&Atomics.notify(i,0),n},g=!1,finishDecision=()=>{c.delete(i),Atomics.load(i,0)===Up&&refuse(i,new SqliteWorkerError(`SQLite worker admission was not granted`,`closed`),`domain`)},v=`authority`;try{if(t.inOwnerContext(()=>{_?.assertRequest?.()}),l.stage===`prepare`&&isRecord(l.facts)&&l.facts.kind===`schema-maintenance`){let e=_;if(!e||typeof l.facts.databasePath!=`string`||resolveIdentityPathViaExistingAncestorSync(l.facts.databasePath)!==e.databasePath)throw new SqliteWorkerError(`SQLite schema maintenance target differs from its admitted database`,`closed`);t.inOwnerContext(()=>{e.lease??=e.acquireSchema(),e.assertAccess(),e.lease.assertCurrent(),grant()})}else{v=`domain`;let e=t.prepare;if(e){g=!0,(async()=>{try{await t.inOwnerContext(e,l),!f&&!a()&&Atomics.load(i,0)===Up&&t.inOwnerContext(t.admit,l,grant)}catch(e){refuse(i,e,`domain`)}finally{finishDecision()}})();return}t.inOwnerContext(t.admit,l,grant)}}catch(e){e instanceof tc&&_?.coldOpenPath===e.databasePath&&!_.lease&&l.stage===`prepare`&&isRecord(l.facts)&&l.facts.kind===`schema-maintenance`&&typeof l.facts.databasePath==`string`&&resolveIdentityPathViaExistingAncestorSync(l.facts.databasePath)===_.databasePath?Atomics.compareExchange(i,0,Up,4)===Up&&Atomics.notify(i,0):refuse(i,e,v)}finally{g||finishDecision()}};i.on(`message`,e=>s?s.inOwnerContext(receive,e):receive(e)).unref();let drain=e=>{for(let t=e;t;t=Ee(i))receive(t.message)},service=()=>{if(y.observingCommit)return;let e=Ee(i);if(e)return s?s.inOwnerContext(drain,e):drain(e)},b={port:a,attachment:t===void 0?void 0:{value:t},observeRequests(e){if(f||h)throw new SqliteWorkerError(`SQLite request observation is already bound or closed`,`closed`);h=e},bindDatabaseAuthority(e){if(f||_)throw new SqliteWorkerError(`SQLite database authority is already bound or closed`,`closed`);_={...e}},get failure(){return g?.error},get failureSource(){return g?.source},get cleanupFailures(){return d},get committed(){return service(),y.committed},get settlement(){return y.settlement},waitForSettlement(e){for(;;){if(service(),g!==void 0)throw toErrorObject(g.error,`SQLite worker admission failed`);if(y.settlement?.kind===`completed`)return y.settlement;let t=e-performance.now();if(y.settlement?.kind===`unknown`||f||t<=0)throw new SqliteWorkerError(`SQLite worker native settlement is unknown`,`outcome-unknown`);Atomics.wait(v,0,0,Math.min(5,t))}},service,abortConstruction(){if(p)throw new SqliteWorkerError(`SQLite admission construction has already received work`,`closed`);if(b.finish()!==void 0)throw new SqliteWorkerError(`SQLite unstarted admission cleanup did not finish synchronously`,`closed`)},finish(e){if(l)return l;f=!0,service();let t=[...c.values()].filter(e=>e!==void 0);for(let e of c.keys())Atomics.load(e,0)===Up&&refuse(e,new SqliteWorkerError(`SQLite worker admission is closed`,`closed`),`authority`);i.close(),a.close();let release=()=>{if(y.finish(e),h=void 0,_?.lease)try{_.lease.release(),_.lease=void 0}catch(e){d.push(e)}_?.lease||(_=void 0),s=void 0,u.release(b)};if(t.length===0)release();else return l=Promise.allSettled(t).then(release).finally(()=>{l=void 0}),l}};return Kp.set(b,e=>{if(f||p)throw new SqliteWorkerError(`SQLite commit observation is closed or started`,`closed`);y.observe(e)}),b}var Up,Wp,Gp,Kp,qp=__esmMin((()=>{O(),k(),Do(),j(),nc(),Co(),Rp(),gc(),Fc(),zp(),Dc(),Vp(),Hp(),Up=0,Wp=1,Gp=2,Kp=/* @__PURE__ */ new WeakMap,resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerExecutionAuthorities`),()=>/* @__PURE__ */ new WeakMap)}));function getSpawnBroker(){let e=Jp.getStore();return Yp.startupDisabled||e===null?void 0:e??Yp.host}var Jp,Yp,Xp=__esmMin((()=>{cc(),Jp=new AsyncContext(Symbol(`spawnBroker`)),Yp={startupDisabled:!1}}));function renderOutput(e){let t=typeof e==`string`?e:Zp.decode(e);return t.endsWith(`
`)&&(t=t.slice(0,t.endsWith(`\r
`)?-2:-1)),ze(t).replace(/[\p{Separator}\p{Other}]/gu,e=>{let t=Qp.get(e);if(t!==void 0)return t;let n=e.codePointAt(0),r=n.toString(16);return n<=65535?`\\u${r.padStart(4,`0`)}`:`\\U${r}`})}function decodeExecaMessage(e,t){return e.messageOutputs?[e.message,...e.messageOutputs.map(e=>renderOutput(t[e]))].join(`
`):e.message}function restoreError(e,t){let n=Error(decodeExecaMessage(e,t),{cause:e.cause?restoreError(e.cause,t):void 0});return Object.assign(n,{name:e.name,code:e.code})}function restoreExecaResult(e){let{error:t,...n}=e,r={...n,stdout:n.stdout,stderr:n.stderr,shortMessage:n.shortMessage,code:n.code};if(t){let e=restoreError(t,r);return Object.assign(e,r,{cause:e.cause})}return{...r,cause:void 0}}var Zp,Qp,$p=__esmMin((()=>{Zp=new TextDecoder,Qp=/* @__PURE__ */ new Map([[` `,` `],[`
`,`
`],[`\b`,`\\b`],[`\f`,`\\f`],[`\r`,`\\r`],[` `,`\\t`]])}));function executableIdentity(e){try{return formatExecutableIdentity(v(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(C(t,`ENOENT`)||C(t,`ENOTDIR`))&&recordUnavailableRuntime(e,t),{execPath:e,available:!(z.execPath===e&&z.failure)}}async function prepareChildRuntimeViability(e){let t=e?.execPath??process.execPath,n=!(z.execPath===t&&z.failure);if(n)try{let e=await probeChildRuntimeExecutable(t);n=!classifyRuntimeProbe(t,e,await w.stat(t).then(formatExecutableIdentity,()=>void 0),e.error)}catch(e){n=publishRuntimeViability(t,await w.stat(t).then(()=>e,e=>e)).available}return{publish:()=>({execPath:t,available:n&&publishRuntimeViability(t).available})}}function recoverUnavailableRuntime(){if(z.execPath!==process.execPath||!z.failure||!z.recover||z.recoveryStarted)return;z.recoveryStarted=!0;let e=z.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??n.parse(process.execPath).root,env:e.env??{...process.env,NODE_OPTIONS:void 0},timeout:1e3,maxBuffer:8192}}async function probeChildRuntimeExecutable(e,t={}){let n=getSpawnBroker();if(n){let r=n.spawnExeca([e,`--version`],{...runtimeProbeOptions(t),extendEnv:!1,stripFinalNewline:!1,stdin:`ignore`});r.child.once(`spawn`,()=>{r.child.stdout?.resume(),r.child.stderr?.resume()});let i=restoreExecaResult(await r.result);return await r.child.waitForClose(),{stdout:typeof i.stdout==`string`?i.stdout:``,stderr:typeof i.stderr==`string`?i.stderr:``,error:i instanceof Error?i:void 0,status:i.exitCode??null,signal:i.signal??null}}return new Promise(n=>{Ne(e,[`--version`],runtimeProbeOptions(t),(e,t,r)=>n({stdout:t,stderr:r,error:e??void 0,status:e?typeof e.code==`number`?e.code:null:0,signal:e?.signal??null}))})}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(z.execPath===process.execPath&&z.failure)throw z.failure}function recordUnavailableRuntime(e,t,n){if(z.execPath===e&&z.failure)return z.failure;z.execPath=e;let r=formatMissingChildRuntimeWarning({execPath:e,available:!1}),i=n?.trim();return z.failure=Object.assign(Error(i?`${r}\n${i}`:r,{cause:t}),{code:`NODE_RUNTIME_UNAVAILABLE`}),createSubsystemLogger(`gateway/runtime`).error(z.failure.message),recoverUnavailableRuntime(),z.failure}function needsRuntimeProbe(e){return!!(e.error||e.signal===`SIGABRT`||tm.test(e.stderr??``))}function classifyRuntimeProbe(e,t,n,r){if(z.execPath===e&&z.failure)return z.failure;let i=e!==z.initialPath||n!==z.initialIdentity;return em.test(t.stderr)||tm.test(t.stderr)||C(t.error,`ENOENT`)||C(t.error,`ENOTDIR`)||i&&(t.signal===`SIGABRT`||C(t.error,`ENOEXEC`)||C(t.error,`EACCES`)||C(t.error,`EPERM`))?recordUnavailableRuntime(e,r,t.stderr):void 0}async function prepareChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(z.execPath===t&&z.failure)return z.failure;if(em.test(e.stderr??``)||e.error&&!(await prepareChildRuntimeViability({execPath:t})).publish().available)return recordUnavailableRuntime(t,e.error,e.stderr);if(!e.error&&needsRuntimeProbe(e))return classifyRuntimeProbe(t,await probeChildRuntimeExecutable(t),t===z.initialPath?await w.stat(t).then(formatExecutableIdentity,()=>void 0):void 0,e.error)}var z,em,tm,nm=__esmMin((()=>{Rn(),v_(),Xp(),$p(),Do(),j(),Cn(),z=resolveGlobalSingleton(Symbol.for(`openclaw.childRuntimeViability`),()=>({initialPath:process.execPath,initialIdentity:executableIdentity(process.execPath)})),em=/(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i,tm=/(?:dyld[^\n]*:\s*Symbol not found:|symbol lookup error:|Error loading shared library|version [`'"][^`'"\r\n]+[`'"] not found)/i}));function getSpawnBrokerAdmission(){return rm.getStore()??`command`}var rm,im=__esmMin((()=>{rm=new D}));function waitForBrokerChildCompletion(e){return new Promise(t=>{let n=e.exitCode!=null||e.signalCode!=null,r=!e.connected,i=0,finish=()=>{n&&r&&i===0&&(e.removeListener(`exit`,onExit),e.removeListener(`error`,onError),e.removeListener(`disconnect`,onDisconnect),t())},onExit=()=>{n=!0,finish()},onError=()=>{e.pid===void 0&&(n=!0,r=!0,finish())},onDisconnect=()=>{r=!0,finish()};e.once(`exit`,onExit),e.on(`error`,onError),e.once(`disconnect`,onDisconnect);for(let t of e.stdio??[])t&&!t.closed&&(i++,t.once(`close`,()=>{i--,finish()}));finish()})}var am=__esmMin((()=>{}));function isContinuationByte(e){return e!==void 0&&(e&192)==128}function truncateUtf8Suffix(e,t){if(t<=0)return``;if(e.length<=t&&ke.byteLength(e)<=t)return e;let n=ke.from(Number.isInteger(t)?e.slice(-t-1):e),r=n.byteLength-t;for(;r<n.byteLength&&isContinuationByte(n[r]);)r+=1;return n.subarray(r).toString(`utf8`)}var om=__esmMin((()=>{}));function childCapacityError(e,t){let n=0,r=0;for(let t of e)n++,t===`mcp`&&r++;if(n>=sm)return`Spawn broker child capacity exceeded (${sm}); close running processes before retrying`;if(t===`mcp`&&r>=cm)return`Spawn broker MCP child capacity exceeded (${cm}); close unused MCP sessions before retrying`}function serializeBrokerError(e){return{message:e.message,code:e.code,errno:e.errno,syscall:e.syscall,path:e.path}}var sm,cm,SpawnBrokerError,lm=__esmMin((()=>{sm=512,cm=448,SpawnBrokerError=class extends Error{constructor(e,t){super(e,t),this.code=`ERR_SPAWN_BROKER_UNAVAILABLE`,this.name=`SpawnBrokerError`}}}));function observeBrokerChildDiagnostics(e){let t=process.execPath,n=!1;e.once(`message`,()=>{n=!0});let r=``;return e.stderr?.setEncoding(`utf8`).on(`data`,e=>{r=truncateUtf8Suffix(r+e,2048)}),async()=>{let i=redactToolPayloadText(r).trim();return await prepareChildRuntimeFailure({execPath:t,stderr:r,signal:e.signalCode,started:n})??/* @__PURE__ */ Error(`exited with code=${e.exitCode??`null`} signal=${e.signalCode??`none`}${i?`\nstderr:\n${i}`:``}`)}}async function prepareBrokerFailureCause(e,t){try{return await e??t}catch(e){return AggregateError(t?[t,e]:[e],`Spawn broker diagnosis failed`,{cause:t})}}function createBrokerFailureError(e,t){return new SpawnBrokerError(e&&C(e,`NODE_RUNTIME_UNAVAILABLE`)?e.message:t?`Spawn broker exited; command outcome is unavailable`:`Spawn broker failed before readiness: ${e?.message??`channel lost`}`,{cause:e})}var um=__esmMin((()=>{nm(),Cn(),xo(),om(),lm()}));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])=>dm.has(t===`win32`?e.toUpperCase():e)))}var dm,fm=__esmMin((()=>{dm=/* @__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=st(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 hm;let r=n.win32.normalize(t);return/^[A-Za-z]:\\/.test(r)&&!r.startsWith(`\\\\`)?r:hm}function windowsPowerShellPath(e){return n.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return n.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=mm,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;let r=performance.now()+t,i=readNativeProcessStartTime(e);if(i!==void 0)return i;let a=Math.ceil(r-performance.now());if(a<=0)return null;let s=Ie(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,pm),windowsHide:!0});if(!s.error&&s.status===0){let e=parseWindowsProcessStartTime(s.stdout);if(e!==null)return e}let c=Math.ceil(r-performance.now());if(c<=0)return null;let l=Ie(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 pm,mm,hm,gm=__esmMin((()=>{fm(),pm=5e3,mm=1e4,hm=`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 _m||=t(import.meta.url)(`@openclaw/proc-safe/identity`),_m}var _m,vm=__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 ym=__esmMin((()=>{vm()}));function readDarwinNativeIdentity(e){if(!(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=st(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=st(e);return t!==null&&!t.exited}catch(e){return e instanceof at&&(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 exitedLinuxStatus(e,t){let n=t.match(/^State:\s+(\S)/m)?.[1],r=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(r===`0`)return;let i=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return i!==void 0&&Number(i)!==e||(n===`Z`||n===`X`)&&r===`1`}function isMissingPid(e){try{process.kill(e,0)}catch(e){return C(e,`ESRCH`)}return!1}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return!1;try{let t=exitedLinuxStatus(e,u.readFileSync(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}async function isPidDefinitelyDeadAsync(e){if(!hasLinuxProcfs())return isPidDefinitelyDead(e);if(!isValidPid(e))return!0;try{process.kill(e,0)}catch(e){return C(e,`ESRCH`)}try{let t=exitedLinuxStatus(e,await u.promises.readFile(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}function isPidDefinitelyDead(e){if(!isValidPid(e))return!0;let t=!1;try{process.kill(e,0)}catch(e){let n=ae(e)?e.code:void 0;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?bm:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{let n=Me.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 parseLinuxProcessStat(e,t){let n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;let r=t.slice(n+1).trimStart().split(/\s+/),i=Number(r[19]),a=Number(r[1]);return Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(a)&&a>=0?{parentPid:a,startedAt:i}:null}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{return parseLinuxProcessStat(e,u.readFileSync(`/proc/${e}/stat`,`utf8`))}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getProcessInstanceStartTime(e){if(!isValidPid(e))return null;if(hasLinuxProcfs()){let t=getProcessStartTime(e);return Number.isSafeInteger(t)?t:null}let t=readDarwinNativeIdentity(e);if(!t)return null;let n=t.startTimeMicros;return Number.isSafeInteger(n)?n:null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&xm!==null)return xm;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&&(xm=i),i}var bm,xm,Sm=__esmMin((()=>{Cn(),fm(),gm(),ym(),bm=1e3,xm=null}));function killProcessTree(e,t){if(!Number.isFinite(e)||e<=0)return;if(process.platform===`win32`){if(t?.force===!0){signalProcessTreeWindowsAndWait(e,`SIGKILL`);return}killProcessTreeWindows(e,normalizeGraceMs(t?.graceMs));return}let n=t?.detached===!0||t?.detached!==!1&&isProcessGroupLeader(e),r=t?.detached===!1&&!n&&process.platform===`linux`,i=r?collectUnixProcessTree(e):void 0;if(r&&!i){signalProcessTreeUnix(e,t?.force===!0?`SIGKILL`:`SIGTERM`,!1);return}let a=!1,force=()=>{if(a)return;a=!0;let t=i?.filter(verifiedProcessInstanceAlive)??[];(n?isProcessAlive(-e):r?t.length>0:isProcessAlive(e))&&signalProcessTreeUnix(e,`SIGKILL`,n,i?t:void 0)};if(t?.force===!0){i?force():signalProcessTreeUnix(e,`SIGKILL`,n);return}signalProcessTreeUnix(e,`SIGTERM`,n,i);let s=normalizeGraceMs(t?.graceMs),c=setTimeout(force,s);r||c.unref();let l=!1;return{force:()=>{clearTimeout(c),force()},exited:()=>(l||=n?!isProcessAlive(-e):i?!i.some(capturedProcessInstanceMayBeAlive):!isProcessAlive(e),l&&(a=!0,clearTimeout(c)),l)}}function normalizeGraceMs(e){return typeof e!=`number`||!Number.isFinite(e)?Cm:Math.max(0,Math.min(wm,Math.floor(e)))}function isProcessAlive(e){try{process.kill(e,0)}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`EPERM`)return!1}if(e<0||process.platform!==`linux`)return!0;try{let t=h(`/proc/${e}/status`,`utf8`);return!(t.match(/^State:\s+(\S)/m)?.[1]===`Z`&&/^Threads:[ \t]+1[ \t]*$/m.test(t))}catch{return!0}}function parseProcessGroupId(e){if(typeof e!=`string`||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}function readPsOutput(e){try{let t=Ie(`ps`,e,{encoding:`utf8`,timeout:500});return t.error||t.status!==0?void 0:t.stdout}catch{return}}function readProcStatFields(e){try{let t=h(`/proc/${e}/stat`,`utf8`),n=t.lastIndexOf(`)`);return n<0?void 0:t.slice(n+1).trim().split(/\s+/)}catch{return}}function isProcessGroupLeader(e){return((process.platform===`linux`?parseProcessGroupId(readProcStatFields(e)?.[2]):void 0)??parseProcessGroupId(readPsOutput([`-p`,String(e),`-o`,`pgid=`])))===e}function parsePositivePids(e){return typeof e==`string`?e.trim().split(/\s+/u).map(e=>Number(e)).filter(e=>Number.isSafeInteger(e)&&e>0):[]}function readUnixProcessIdentity(e,t){return readUnixProcessInstance(e,t)?.identity}function readUnixProcessInstance(e,t){if(t!==void 0&&Date.now()>=t||process.platform!==`linux`)return;let n=readProcStatFields(e),r=Number(n?.[1]),i=n?.[19];if(i&&/^\d+$/u.test(i)&&Number.isSafeInteger(r))return{identity:`${e}:${i}`,ppid:r}}function verifiedProcessInstanceAlive(e){return!e.identity||!isProcessAlive(e.pid)?!1:readUnixProcessIdentity(e.pid)===e.identity}function capturedProcessInstanceMayBeAlive(e){if(!e.identity||!isProcessAlive(e.pid))return!1;let t=readUnixProcessIdentity(e.pid);return t===void 0||t===e.identity}function*readUnixProcessChildren(e,t){let n;try{for(n=m(`/proc/${e}/task`);t();){let t=n.readSync();if(!t)return;let r=parseProcessGroupId(t.name);if(r)try{yield*parsePositivePids(h(`/proc/${e}/task/${r}/children`,`utf8`))}catch{}}}catch{}finally{try{n?.closeSync()}catch{}}}function collectUnixProcessTree(e){if(process.platform!==`linux`)return;let t=[],n=/* @__PURE__ */ new Set([e]),r=0,i=Date.now()+Em,a=readUnixProcessIdentity(e,i);if(!a||Date.now()>=i)return;let withinBounds=e=>Date.now()<i&&e<=Om,hasCapacity=()=>n.size<Dm,visit=(e,a,s)=>{if(!withinBounds(s)||!hasCapacity()||readUnixProcessIdentity(e,i)!==a)return;let c=readUnixProcessChildren(e,()=>withinBounds(s)&&hasCapacity()&&r++<Dm&&readUnixProcessIdentity(e,i)===a);for(let r of c){if(!withinBounds(s+1)||!hasCapacity())return;if(n.has(r)||r===process.pid)continue;n.add(r);let a=readUnixProcessInstance(r,i);a&&a.ppid===e&&withinBounds(s+1)&&(visit(r,a.identity,s+1),t.push({pid:r,identity:a.identity}))}};return visit(e,a,0),[...t,{pid:e,identity:a}]}function signalProcessTreeUnix(e,t,n,r){if(n){signalUnixTarget(-e,t);return}let i=r??[{pid:e}];for(let e of i)(!r||verifiedProcessInstanceAlive(e))&&signalUnixTarget(e.pid,t)}function signalUnixTarget(e,t){try{process.kill(e,t)}catch{}}function runTaskkill(e,t){return new Promise(n=>{let r=!1,finish=e=>{r||(r=!0,clearTimeout(i),t?.(e),n())},i=setTimeout(()=>finish(null),Tm);i.unref?.();try{let t=Fe(`taskkill`,e,{stdio:`ignore`,detached:!0,windowsHide:!0});t.once(`error`,()=>finish(null)),t.once(`close`,e=>finish(e))}catch{finish(null)}})}function killProcessTreeWindows(e,t){let n=!1,r,forceKill=()=>{n||(n=!0,r!==void 0&&(clearTimeout(r),r=void 0),isProcessAlive(e)&&signalProcessTreeWindowsAndWait(e,`SIGKILL`))};signalProcessTreeWindowsAndWait(e,`SIGTERM`,e=>{e!==null&&e!==0&&forceKill()}),r=setTimeout(forceKill,t),r.unref()}function signalProcessTreeWindowsAndWait(e,t,n){return runTaskkill(t===`SIGKILL`?[`/F`,`/T`,`/PID`,String(e)]:[`/T`,`/PID`,String(e)],n)}var Cm,wm,Tm,Em,Dm,Om,km=__esmMin((()=>{Cm=3e3,wm=6e4,Tm=3e3,Em=500,Dm=4096,Om=128})),Am=__esmMin((()=>{km()})),jm=__esmMin((()=>{Cn()}));function failure(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(st(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:Mm[e.state],owner:e.owner}}function census(e,t){try{let n=ct({timeoutMs:remaining(e),...t?{pids:t}:{}}).filter(hasReadableTopology);return remaining(e),n}catch(t){throw remaining(e),failure(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,Mm,Nm=__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`}},Mm={running:`R`,sleeping:`S`,stopped:`T`,zombie:`Z`,idle:`I`,unknown:`?`}}));function readLinuxProcessUid(e){try{let t=h(`/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 parseLinuxProcessGroupMember(e,t){let n=/^(\d+) \([\s\S]*\) (\S) (\d+) (-1|\d+)(?:\s|$)/.exec(t);if(!n||Number(n[1])!==e)throw Error(`Process group census is unavailable`);return{pid:e,ppid:Number(n[3]),pgid:Number(n[4]),state:n[2]}}async function readLinuxProcessGroupMemberAsync(e){let t=await w.readFile(`/proc/${e}/stat`,`utf8`);return{...parseLinuxProcessGroupMember(e,t),startedAt:parseLinuxProcessStat(e,t)?.startedAt??null}}function*readProcessGroupMembers(e,t){let n=t!==void 0;if(process.platform===`linux`){let t=Date.now()+e;for(let e of g(`/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=h(`/proc/${e}/stat`,`utf8`),n){s=readLinuxProcessUid(r);try{a=h(`/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=parseLinuxProcessGroupMember(r,i);if(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:l.pgid,state:l.state,...a?{command:{ppid:l.ppid,argv:a,...s===void 0?{}:{uid:s}}}:c&&s!==void 0?{command:{ppid:l.ppid,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 at)||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=Ie(`/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 isOwnProcfs(){if(process.platform!==`linux`)return!0;try{return _(`/proc/self`)===String(process.pid)}catch{return!1}}function isProcessGroupGoneByCensus(e){if(!isOwnProcfs())return!1;try{for(let t of readProcessGroupMembers(1e3))if(t.pgid===e&&isLiveCensusMember(t))return!1;return!0}catch{return!1}}async function*readLinuxProcessGroupMembersAsync(e){if(process.platform!==`linux`)throw Error(`Asynchronous Linux process census requires Linux`);let t=Date.now()+e;for(let e of await w.readdir(`/proc`)){if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);if(!/^\d+$/.test(e))continue;let n=Number(e),r;try{r=await w.readFile(`/proc/${e}/stat`,`utf8`)}catch(e){if(n!==process.pid&&[`ENOENT`,`ESRCH`].includes(extractErrorCode(e)??``))continue;throw e}if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);yield parseLinuxProcessGroupMember(n,r)}if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`)}async function isOwnProcfsAsync(){if(process.platform!==`linux`)return!0;try{return await w.readlink(`/proc/self`)===String(process.pid)}catch{return!1}}async function isProcessGroupGoneByCensusAsync(e){if(!await isOwnProcfsAsync())return!1;try{for await(let t of readLinuxProcessGroupMembersAsync(1e3))if(t.pgid===e&&(!t.state.startsWith(`Z`)||!await isPidDefinitelyDeadAsync(t.pid)))return!1;return!0}catch{return!1}}var Pm=__esmMin((()=>{O(),Sm(),Nm()}));function isDeniedProcessGroupProbe(e,t=0){if(process.platform!==`linux`||!C(e,`EPERM`))return!1;try{return process.kill(-4194305,t),!1}catch(e){return C(e,`EPERM`)}}function probeProcessGroup(e){try{return process.kill(-e,0),`alive`}catch(e){return C(e,`ESRCH`)?`gone`:isDeniedProcessGroupProbe(e)?`denied`:`alive`}}function isProcessGroupGoneByKernel(e){return probeProcessGroup(e)===`gone`}function isProcessGroupGone(e){let t=probeProcessGroup(e);return t===`gone`||t===`denied`&&isProcessGroupGoneByCensus(e)}async function isProcessGroupGoneAsync(e){let t=probeProcessGroup(e);return t===`gone`||t===`denied`&&await isProcessGroupGoneByCensusAsync(e)}var Fm=__esmMin((()=>{Cn(),jm(),Pm()}));function readCommandProcessStartTime(e,t={}){return process.platform!==`linux`&&process.platform!==`android`?t.instance?getProcessInstanceStartTime(e):getFileLockProcessStartTime(e):w.readFile(`/proc/${e}/stat`,`utf8`).then(n=>t.child&&(t.child.exitCode!=null||t.child.signalCode!=null)?null:parseLinuxProcessStat(e,n)?.startedAt??null,()=>null)}var Im=__esmMin((()=>{Sm()})),Lm,Rm=__esmMin((()=>{Lm=5e3}));function isBrokerChildGroupAlive(e){if(isProcessGroupGone(e.pid))return!1;let t=getProcessInstanceStartTime(e.pid);if(e.isLeaderAlive)return e.isLeaderAlive()||isPidDefinitelyDead(e.pid)?e.startedAt===null||t===null||t===e.startedAt:!1;if(e.startedAt===null||t===null&&!isPidDefinitelyDead(e.pid))throw new SpawnBrokerError(`Spawn broker group leader identity is unavailable for pid=${e.pid}`);return t===null||t===e.startedAt}function signalRevalidatedGroupMembers(e,t,{snapshot:n,signaled:r}){if(!isOwnProcfs())throw new SpawnBrokerError(`Spawn broker cannot verify the process table belongs to its PID namespace`);let i=n.filter(t=>t.pid!==process.pid&&t.pgid===e&&!isPidDefinitelyDead(t.pid));if(!i.length)return 0;let a=new Map(i.map(e=>[e.pid,getProcessInstanceStartTime(e.pid)])),s;for(let n of readProcessGroupMembers(1e3)){if(n.pid===process.pid||n.pgid!==e||!a.has(n.pid))continue;let i=a.get(n.pid);if(i===null){if(!isPidDefinitelyDead(n.pid))throw new SpawnBrokerError(`Spawn broker cannot identify remaining group member pid=${n.pid}`);continue}if(getProcessInstanceStartTime(n.pid)!==i)continue;let c=`${n.pid}:${i}`;if(r.get(c)!==t){try{process.kill(n.pid,t)}catch(e){if(extractErrorCode(e)!==`ESRCH`){s??={error:e};continue}}r.set(c,t)}}if(s)throw s.error;return i.length}async function signalRevalidatedGroupMembersAsync(e,t,{snapshot:n,signaled:r}){if(!await isOwnProcfsAsync())throw new SpawnBrokerError(`Spawn broker cannot verify the process table belongs to its PID namespace`);let i=/* @__PURE__ */ new Map;for(let t of n)t.pid!==process.pid&&t.pgid===e&&!await isPidDefinitelyDeadAsync(t.pid)&&i.set(t.pid,await readCommandProcessStartTime(t.pid,{instance:!0}));if(!i.size)return 0;let a;for await(let n of readLinuxProcessGroupMembersAsync(1e3)){if(n.pid===process.pid||n.pgid!==e||!i.has(n.pid))continue;let s=i.get(n.pid);if(s===null){if(!await isPidDefinitelyDeadAsync(n.pid))throw new SpawnBrokerError(`Spawn broker cannot identify remaining group member pid=${n.pid}`);continue}let c=await readLinuxProcessGroupMemberAsync(n.pid).catch(()=>void 0),l=t();if(!l)return i.size;if(!c||c.pgid!==e||c.startedAt!==s)continue;let u=`${n.pid}:${s}`;if(r.get(u)!==l){try{process.kill(n.pid,l)}catch(e){if(extractErrorCode(e)!==`ESRCH`){a??={error:e};continue}}r.set(u,l)}}if(a)throw a.error;return i.size}function terminateRetainedBrokerChildGroup(e){let t=!1,n=!1,r,i,a=`SIGTERM`,s=/* @__PURE__ */ new Map,signalMembers=()=>{try{signalRevalidatedGroupMembers(e.pid,a,{snapshot:[...readProcessGroupMembers(1e3)],signaled:s})}catch(e){r=e}},signal=n=>{if(!t){if(!isBrokerChildGroupAlive(e))t=!0;else{a=n;try{process.kill(-e.pid,n)}catch(e){if(isDeniedProcessGroupProbe(e,n))i=e,signalMembers();else if(extractErrorCode(e)===`ESRCH`)t=!0;else throw e}}}},force=()=>{t||n||(n=!0,signal(`SIGKILL`))};return{force,settled:(async()=>{let n=performance.now()+Lm,a=n+2e3;try{for(signal(`SIGTERM`);!t&&isBrokerChildGroupAlive(e);){if(performance.now()>=n&&force(),i&&!t&&signalMembers(),performance.now()>=a)throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e.pid}`,{cause:r??i});await tt(50)}}finally{t=!0}})()}}function terminateLostBrokerChild(e,t,n){if(t&&n){if(n.pid!==e)throw new SpawnBrokerError(`Spawn broker cleanup identity changed`);return terminateRetainedBrokerChildGroup(n)}let r=killProcessTree(e,{detached:t,graceMs:Lm}),i=performance.now()+Lm+2e3;return{force:()=>r?.force(),settled:(async()=>{for(;;){if(t){if(r?.exited(),await isPidDefinitelyDeadAsync(e)&&await isProcessGroupGoneAsync(e))break}else if(await isPidDefinitelyDeadAsync(e)&&(r?.exited()??!0))break;if(performance.now()>=i)throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e}`);await tt(50)}})()}}function terminateBrokerProcessGroup(e){let t=!1,n,r,i=`SIGTERM`,a=/* @__PURE__ */ new Map,s,retire=()=>{t=!0,clearTimeout(s)},signalMembers=async()=>{try{let n=[];for await(let e of readLinuxProcessGroupMembersAsync(1e3))n.push(e);await signalRevalidatedGroupMembersAsync(e,()=>t?void 0:i,{snapshot:n,signaled:a})}catch(e){n=e}},signal=async a=>{if(t||isProcessGroupGoneByKernel(e))retire();else{i=a;try{process.kill(-e,a)}catch(e){isDeniedProcessGroupProbe(e,a)?(r=e,await signalMembers()):extractErrorCode(e)!==`ESRCH`&&(n=e)}}},force=()=>{if(!t){if(isProcessGroupGone(e))retire();else{i=`SIGKILL`,clearTimeout(s);try{process.kill(-e,i)}catch(t){if(isDeniedProcessGroupProbe(t,i)){r=t;try{signalRevalidatedGroupMembers(e,i,{snapshot:[...readProcessGroupMembers(1e3)],signaled:a})}catch(e){n=e}}else extractErrorCode(t)!==`ESRCH`&&(n=t)}}}},c,escalate=()=>{t||c||(i=`SIGKILL`,c=(async()=>{await isProcessGroupGoneAsync(e)?retire():t||await signal(`SIGKILL`)})().catch(e=>{n=e}))};return{force,settled:(async()=>{try{if(await isProcessGroupGoneAsync(e))return;await signal(i),!t&&i===`SIGTERM`&&(s=setTimeout(escalate,Lm));let a=performance.now()+Lm+2e3;for(;await c,!(t||await isProcessGroupGoneAsync(e));){if(performance.now()>=a)throw new SpawnBrokerError(`Spawn broker group cleanup could not be confirmed for pgid=${e}`,{cause:n??r});r&&await signalMembers(),await tt(50)}}finally{retire(),await c}})()}}var zm=__esmMin((()=>{O(),Sm(),Fm(),Im(),Am(),Rm(),Pm(),lm()}));function brokerSpawnOptions(e){let t=e.stdio??`pipe`,n=typeof t==`string`?[t,t,t]:[...t],r=[];for(let e=0;e<Math.max(3,n.length);e+=1){let t=n[e]??(e<3?`pipe`:`ignore`);if(t===`inherit`&&e!==0||t!==`pipe`&&t!==`ignore`&&t!==`inherit`&&t!==`ipc`)return;r.push(t)}if(e.signal||e.timeout||e.killSignal)throw Error(`Unsupported spawn broker cancellation options`);return{cwd:e.cwd instanceof URL?c(e.cwd):e.cwd,env:e.env?{...e.env}:{...process.env},argv0:e.argv0,detached:e.detached,shell:e.shell,windowsHide:e.windowsHide,windowsVerbatimArguments:e.windowsVerbatimArguments,serialization:e.serialization,uid:e.uid,gid:e.gid,stdio:r}}function holdPipe(e){let t={read:e.read.bind(e),resumed:!1,onResume:()=>{t.resumed=!0}};Bm.set(e,t),e.on(`resume`,t.onResume),e.on(`readable`,holdReadable),e.read=()=>null}function restoreStdinPipe(e){let t=Reflect.get(e,`_readableState`);if(!t||typeof t!=`object`||[`ended`,`endEmitted`,`reading`].some(e=>typeof Reflect.get(t,e)!=`boolean`))throw new SpawnBrokerError(`Spawn broker requires a Node readable state for stdin`);stopPipeReads(e),Object.assign(t,{readable:!1,ended:!0,endEmitted:!0,reading:!1})}function stopPipeReads(e){let t=Reflect.get(e,`_handle`);if(!t||typeof t!=`object`||!(`readStop`in t)||typeof t.readStop!=`function`||!(`reading`in t)||typeof t.reading!=`boolean`)throw new SpawnBrokerError(`Spawn broker requires a transferable Node pipe handle`);if(t.readStop()!==0)throw new SpawnBrokerError(`Spawn broker could not stop pipe reads`);t.reading=!1}function releasePipe(e){let t=restoreReader(e);t&&process.nextTick(()=>{e.destroyed||(e.emit(`readable`),t.resumed&&e.resume())})}function restoreReader(e){let t=Bm.get(e);if(t)return e.read=t.read,Bm.delete(e),e.removeListener(`resume`,t.onResume),e.removeListener(`readable`,holdReadable),t}var Bm,holdReadable,Vm=__esmMin((()=>{lm(),Bm=/* @__PURE__ */ new WeakMap,holdReadable=()=>{}})),BrokerChild,Hm=__esmMin((()=>{O(),Ao(),Vm(),lm(),BrokerChild=class extends ut{constructor(e,t,n,r=!1){super(),this.requestId=e,this.transmit=n,this.fileOutputPending=r,this.callbackContext=new je(`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}settleFileOutput(){this.fileOutputPending=!1,this.finishClose()}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 ut,{ref(){},unref(){}})),this.opened.resolve(),setImmediate(()=>{this.closed||(this.emit(`spawn`),setImmediate(()=>{for(let[e,t]of this.stdio.entries())e>0&&t instanceof rt&&!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);let t=this.connected;this.connected=!1,this.channel=void 0,this.failSends(e),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.fileOutputPending||(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,je.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`)}}}));function createBrokerCommandRequest(e,t,n){let r=e.type!==`spawn-execa`&&e.outputFile?createDeferredCore():void 0,i=e.type===`spawn-execa`?createDeferredCore():void 0;return r?.promise.catch(()=>{}),i?.promise.catch(()=>{}),{child:new BrokerChild(e.id,e.argv,n,!!r),initiateSpawn:t,result:i,output:r,childClosed:!1,resultSettled:!i&&!r,detached:e.options.detached===!0||e.type===`spawn-execa`&&e.options.killDescendants===!0}}function createBrokerCommands(e){let native=(t,n,r,i,a,s)=>{let c={type:i?`prepare-spawn`:`spawn`,id:e.nextId(),argv:[t,...n],options:r,execCgroup:a};return s&&(c.outputFile=s),e.admit(c,i)};return{spawn:(e,t,n,r,i)=>{let a=brokerSpawnOptions(n);if(!a)throw Error(`Unsupported spawn broker stdio or process options`);return native(e,t,a,r,i).child},spawnToFile:(e,t,n,r,i,a)=>{let s=native(e,t,n,i,a,r);return{child:s.child,output:s.output.promise}},spawnExeca:(t,n,r)=>{let i=e.nextId(),a=e.admit({type:`spawn-execa`,id:i,argv:t,options:n,execCgroup:r});return{child:a.child,result:a.result.promise,cancel:()=>{e.cancel(i).catch(e=>a.child.fail(toErrorObject(e,`Spawn broker cancellation delivery failed`)))}}}}}function receiveBrokerCommandResponse(e,t,n,r){if(t.type===`pipe`){try{if(t.closed&&t.fd===0){let n=new rt;e.child.attachPipe(t.fd,n),n.destroy()}else if(n instanceof rt)t.fd===0?restoreStdinPipe(n):holdPipe(n),e.child.attachPipe(t.fd,n);else throw new SpawnBrokerError(`Spawn broker pipe transfer failed`)}catch(e){throw n instanceof rt&&n.destroy(),e}return r({type:`pipe-received`,id:t.id,fd:t.fd})}if(t.type===`pipe-prefix`){let n=e.child.stdio[t.fd];n instanceof rt&&t.bytes.length>0&&n.unshift(t.bytes)}else t.type===`file-output`?(e.nativeClosed=!0,`error`in t?e.output?.reject(Object.assign(Error(t.error.message),t.error)):e.output?.resolve(t.bytes),e.resultSettled=!0,e.child.settleFileOutput()):t.type===`execa-result`?(e.pid===void 0&&t.result.failed&&e.child.markNotStarted(),e.result?.resolve(t.result),e.resultSettled=!0):(t.type===`closed`?e.nativeClosed=!0:t.type===`error`&&t.notStarted&&e.child.markNotStarted(),t.type===`error`&&t.resultUnavailable&&e.output&&(e.output.reject(Object.assign(Error(t.error.message),t.error)),e.resultSettled=!0,e.child.settleFileOutput()),t.type===`error`&&t.resultUnavailable&&e.result&&(e.result.reject(Object.assign(Error(t.error.message),t.error)),e.resultSettled=!0),e.child.receive(t))}var Um=__esmMin((()=>{O(),Ao(),Hm(),Vm(),lm()})),BrokerFileReads,Wm=__esmMin((()=>{Ao(),lm(),BrokerFileReads=class{constructor(e){this.host=e,this.pending=/* @__PURE__ */ new Map,this.sequence=0}get size(){return this.pending.size}async read(e,t){return(await this.request({filePath:e},t)).buffer}async readPage(e,t,n){return this.request({filePath:e,page:t},n)}async request(e,t){if(t?.throwIfAborted(),await this.host.ready(),t?.throwIfAborted(),!this.host.canAdmit())throw new SpawnBrokerError(`Spawn broker cannot admit a raw file read`);let n=++this.sequence,r=createDeferredCore();this.pending.set(n,{chunks:[],result:r});let abort=()=>{r.reject(t?.reason),this.host.send({type:`cancel-read-file`,id:n}).catch(()=>{})};t?.addEventListener(`abort`,abort,{once:!0}),this.host.send({type:`read-file`,id:n,...e}).catch(r.reject);try{return await r.promise}finally{t?.removeEventListener(`abort`,abort),this.pending.delete(n)}}receive(e){if(e.type!==`file-read-chunk`&&e.type!==`file-read-result`)return!1;let t=this.pending.get(e.id);return t&&(e.type===`file-read-chunk`?t.chunks.push(e.bytes):e.error?t.result.reject(Object.assign(e.error,{code:e.code})):t.result.resolve(e.page??{buffer:Buffer.concat(t.chunks)})),!0}fail(e){for(let t of this.pending.values())t.result.reject(e);this.pending.clear()}}}));function createBrokerSender(e){let t=0,n=0,r=0,i=Promise.resolve(),write=(t,n,r)=>new Promise((i,a)=>{try{let launch=()=>e(t,n,e=>e?a(e):i());r?r(launch):launch()}catch(e){a(toErrorObject(e,`Spawn broker IPC write failed`))}}),enqueue=(e,r)=>{if(t+e>268435456||n>=1024)return Promise.reject(new BrokerIpcAdmissionError(`Spawn broker IPC capacity exceeded`));t+=e,n+=1;let a=i.then(r);return i=a.then(()=>{},()=>{}),a.finally(()=>{t-=e,--n})};return Object.assign((e,t,n)=>{let i=qe(e),a=i.byteLength;if(a>Gm&&t)return Promise.reject(new BrokerIpcAdmissionError(`Spawn broker handle metadata exceeds one IPC frame`));let s=++r;return enqueue(a,async()=>{if(a<=Gm)await write(e,t,n);else for(let e=0;e<a;e+=Gm){let t={kind:Km,id:s,total:a,offset:e,bytes:i.subarray(e,e+Gm)};await write(t,void 0,e+Gm>=a?n:void 0)}})},{reserve(e){return enqueue(Gm,()=>e(async e=>{if(qe(e).byteLength>Gm)throw new SpawnBrokerError(`Spawn broker reserved publication exceeds one IPC frame`);await write(e)}))}})}function createBrokerReceiver(){let e,clear=()=>{e=void 0};return{receive(t){if(!t||typeof t!=`object`||!(`kind`in t)||t.kind!==Km)return clear(),t;let n=t;if(!Number.isSafeInteger(n.id)||!Number.isSafeInteger(n.total)||n.total<=Gm||n.total>268435456||!Number.isSafeInteger(n.offset)||!Buffer.isBuffer(n.bytes)||n.bytes.length===0||n.bytes.length>Gm)throw new SpawnBrokerError(`Invalid spawn broker IPC frame`);let r=e?.id===n.id?e:void 0;if(!r){if(n.offset!==0)throw new SpawnBrokerError(`Spawn broker receive capacity exceeded`);e=r={id:n.id,total:n.total,received:0,chunks:[]}}if(r.total!==n.total||r.received!==n.offset||r.received+n.bytes.length>r.total)throw new SpawnBrokerError(`Out-of-order spawn broker IPC frame`);if(r.chunks.push(n.bytes),r.received+=n.bytes.length,!(r.received<r.total))return clear(),We(Buffer.concat(r.chunks,r.total))},clear}}var Gm,Km,BrokerIpcAdmissionError,qm=__esmMin((()=>{O(),lm(),Gm=1048576,Km=`openclaw-spawn-broker-frame`,BrokerIpcAdmissionError=class extends SpawnBrokerError{}}));function fitsBrokerSocketPath(e,t){return process.platform===`win32`||Buffer.byteLength(n.join(e,t))<=103}var Jm=__esmMin((()=>{}));function createNativeResourceAuthority(){let e=`oc-br-${x(16).toString(`hex`)}`,t=a(ge(),e),n=process.platform===`win32`?void 0:fitsBrokerSocketPath(t,`resource.sock`)?t:a(`/tmp`,e),r=x(32).toString(`hex`);return{directory:n,secret:r,endpoint:n?a(n,`resource.sock`):`\\\\.\\pipe\\oc-br-${r}`}}var Ym=__esmMin((()=>{Jm()}));function decodeNativeWorkerFailure(e){let t=/* @__PURE__ */ new Map,decode=e=>{if(e.kind===`value`)return e.value;let n=t.get(e);if(n)return n;let r=Xm.get(e.constructorName)??Error,i=e.constructorName===`AggregateError`?AggregateError([],e.message):e.constructorName===`SuppressedError`?new SuppressedError(void 0,void 0,e.message):new r(e.message);t.set(e,i),i.name=e.name,i.stack=e.stack;let defineField=(e,t,n=!1)=>{Object.defineProperty(i,e,{value:t,writable:!0,configurable:!0,enumerable:n})};for(let t of[`code`,`errcode`,`errno`])e[t]!==void 0&&defineField(t,e[t],!0);e.cause&&defineField(`cause`,decode(e.cause)),e.errors&&defineField(`errors`,e.errors.map(decode));for(let t of[`error`,`suppressed`]){let n=e[t];n&&defineField(t,decode(n))}return i};return decode(e)}var Xm,Zm=__esmMin((()=>{Xm=new Map([EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Error].map(e=>[e.name,e]))}));function spawnBrokerStartupNowMs(){return Number($m()/1000000n)}var Qm,$m,BrokerNativeResourceCloseError,eh=__esmMin((()=>{Qm=15e3,$m=process.hrtime.bigint.bind(process.hrtime),BrokerNativeResourceCloseError=class extends Error{constructor(e){super(`Native resource cleanup failed`),this.payload=e,this.name=`BrokerNativeResourceCloseError`}}})),BrokerResourceClaims,th=__esmMin((()=>{O(),wo(),Zm(),Ao(),qm(),lm(),eh(),BrokerResourceClaims=class{constructor(e){this.host=e,this.claims=/* @__PURE__ */ new Map,this.bufferedBytes=0,this.bufferedMessages=0,this.closeSequence=0,this.sealed=!1}get size(){return this.claims.size}get hasOpenClaims(){return[...this.claims.values()].some(e=>!e.closed)}get needsReference(){return[...this.claims.values()].some(e=>!e.closed&&(!e.created||!!(e.failure||e.pending)||e.ownerMessages.size>0))}get admissionClosed(){return this.failure!==void 0||this.sealed}capture(e,t){if(this.admissionClosed)throw this.failure??new SpawnBrokerError(`Native resource source is sealed`);let n=qe(e);if(n.length>268435456)throw new SpawnBrokerError(`Native resource input exceeds IPC capacity`);let r=We(n),i={attachment:r,callbacks:t,inContext:D.snapshot(),attached:createDeferredCore(),ready:!1,created:!1,closed:!1,lastSequence:0,ownerSequence:0,ownerMessages:/* @__PURE__ */ new Map};i.attached.promise.catch(()=>{}),this.claims.set(r.id,i),this.host.refreshReference();let active=()=>{if(this.claims.get(r.id)!==i)throw new SpawnBrokerError(`Native resource claim is released`);if(i.failure)throw i.failure};return{attachment:r,receive:e=>{if(e.id!==r.id)throw new SpawnBrokerError(`Native resource response belongs to another claim`);this.receive(e)},ownerMessage:e=>{if(active(),i.closed)throw new SpawnBrokerError(`Native resource is closed`);let t=i.ownerSequence+1,n=qe({type:`resource-owner`,id:r.id,sequence:t,value:e});if(this.bufferedBytes+n.length>268435456||this.bufferedMessages>=1024)throw new SpawnBrokerError(`Native resource owner delivery capacity exceeded`);i.ownerSequence=t;let a=We(n);return i.ownerMessages.set(t,{request:a,size:n.length}),this.bufferedBytes+=n.length,this.bufferedMessages++,this.host.refreshReference(),(async()=>{await i.attached.promise,active();let e=i.ownerMessages.get(t);!i.closed&&e&&await this.host.transmit(e.request)})().catch(e=>{let t=toErrorObject(e,`Native resource owner delivery failed`);this.claims.get(r.id)===i&&!i.closed&&!i.failure&&i.inContext(()=>i.callbacks.failed(t))}),{sequence:t}},close:()=>{if(i.closed)return Promise.resolve();try{active()}catch(e){return Promise.reject(toErrorObject(e,`Native resource is unavailable`))}if(i.pending)return i.pending.completion.promise;let e=--this.closeSequence,t=createDeferredCore();return t.promise.catch(()=>{}),i.pending={requestId:e,completion:t},this.host.refreshReference(),(async()=>{await i.attached.promise,active(),!i.closed&&i.pending?.requestId===e&&await this.host.transmit({type:`resource-close`,id:r.id,requestId:e})})().catch(n=>{i.pending?.requestId===e&&(i.pending=void 0,this.host.refreshReference(),t.reject(toErrorObject(n,`Native resource close delivery failed`)))}),t.promise},release:()=>{if(this.claims.get(r.id)===i){if(!i.closed)throw new SpawnBrokerError(`Native resource must close before release`);this.host.transmit({type:`resource-release`,id:r.id}).catch(()=>{}),this.remove(i)}},abandonUnattached:()=>{if(this.claims.get(r.id)!==i)return;if(i.ready||i.created)throw new SpawnBrokerError(`Attached native resource cannot be abandoned`);let e=new SpawnBrokerError(`Native resource was never dispatched`);i.attached.reject(e),i.pending?.completion.reject(e),this.remove(i)}}}receive(e){let t=this.claims.get(e.id);if(!(!t||t.failure&&e.type!==`resource-closed`)){if(e.type===`resource-ready`){if(this.host.markReady(e.pid,e.generation),t.ready)return;t.ready=!0,t.attached.resolve()}else if(e.type===`resource-created`){if(t.created)return;t.created=!0,this.host.refreshReference()}else if(e.type===`resource-owner-received`||e.type===`resource-owner-rejected`){let n=t.ownerMessages.get(e.sequence);if(n&&(t.ownerMessages.delete(e.sequence),this.bufferedBytes-=n.size,this.bufferedMessages--,this.host.refreshReference(),e.type===`resource-owner-rejected`)){let n=toErrorObject(decodeNativeWorkerFailure(e.error),`Native resource owner callback failed`);t.inContext(()=>t.callbacks.failed(n))}return}else if(e.type===`resource-owner`){if(e.sequence<=t.lastSequence)return;t.lastSequence=e.sequence,t.inContext(()=>t.callbacks.message(e));return}else if(e.type===`resource-closed`){if(t.closed)return;t.closed=!0,this.clearOwnerMessages(t),t.pending?.completion.resolve(),t.pending=void 0,this.host.refreshReference()}else if(e.type===`resource-close-error`){if(t.pending?.requestId===e.requestId){let n=t.pending;t.pending=void 0,this.host.refreshReference(),n.completion.reject(e.resourceError?new BrokerNativeResourceCloseError(e.error):toErrorObject(decodeNativeWorkerFailure(e.error),`Native resource cleanup failed`))}}else if(e.type===`resource-failed`){let n=toErrorObject(decodeNativeWorkerFailure(e.error),`Native resource failed`);t.inContext(()=>t.callbacks.failed(n));return}t.inContext(()=>t.callbacks.message(e))}}closeAdmission(){this.sealed=!0}seal(){return this.sealPromise||=(this.closeAdmission(),this.host.transmit({type:`resource-seal`}).then(()=>{for(let e of this.claims.values())e.attached.resolve()},e=>{throw materializeErrorStack(e),e})),this.sealPromise}closeBeforeStartup(){for(let e of this.claims.values())this.receive({type:`resource-closed`,id:e.attachment.id,requestId:0})}fail(e){materializeErrorStack(e),this.failure??=e;let t=collectSynchronousErrors([...this.claims.values()].filter(t=>this.rejectClaim(t,e)),t=>t.inContext(()=>t.callbacks.failed(e)));if(t.length)throw AggregateError(t,`Native resource failure callback failed`)}rejectClaim(e,t){return e.failure||e.closed?!1:(e.failure=t,this.host.refreshReference(),e.attached.reject(t),e.pending?.completion.reject(t),e.pending=void 0,!0)}clearOwnerMessages(e){for(let t of e.ownerMessages.values())this.bufferedBytes-=t.size,this.bufferedMessages--;e.ownerMessages.clear()}remove(e){this.clearOwnerMessages(e),this.claims.delete(e.attachment.id),this.host.refreshReference()}}})),nh,rh,BrokerHost,createSpawnBrokerHost,ih=__esmMin((()=>{O(),nm(),Cn(),pu(),Du(),Pu(),Ao(),im(),am(),um(),zm(),Um(),Wm(),qm(),lm(),Ym(),th(),eh(),nh=[100,250,500,1e3,2e3],rh=1024,BrokerHost=class{constructor(e={}){if(this.options=e,this.runInContext=D.snapshot(),this.readiness=createDeferredCore(),this.available=!1,this.hasBeenReady=!1,this.closing=!1,this.generation=0,this.consecutiveFailures=0,this.sequence=0,this.requests=/* @__PURE__ */ new Map,this.childAdmissions=/* @__PURE__ */ new Map,this.pendingSpawns=/* @__PURE__ */ new Set,this.fileReads=new BrokerFileReads({ready:()=>this.ready(),send:e=>this.transmit(e),canAdmit:()=>!this.resourceClaims&&!this.closing&&this.pendingSpawns.size+this.fileReads.size<256}),this.cleanups=/* @__PURE__ */ new Set,this.cleanupErrors=[],this.startupDeadline=0,this.onParentExit=()=>{this.process?.connected&&this.process.disconnect();for(let e of this.cleanups)e.force()},this.readFilePage=this.fileReads.readPage.bind(this.fileReads),this.commands=createBrokerCommands({nextId:()=>++this.sequence,admit:(e,t)=>this.admit(e,t),cancel:e=>this.transmit({type:`cancel`,id:e})}),this.spawn=this.commands.spawn,this.spawnExeca=this.commands.spawnExeca,this.spawnToFile=this.commands.spawnToFile,this.workerUrl=e.workerUrl??resolveRuntimeWorkerUrl(Eu.spawnBroker),this.entryPath=c(this.workerUrl),e.nativeResources){let{directory:e,...t}=createNativeResourceAuthority();this.resourceDirectory=e,this.resourceAuthority=t,this.resourceClaims=new BrokerResourceClaims({transmit:async e=>{this.available||await this.ready(),await this.transmit(e)},markReady:(e,t)=>{if(!this.markNativeReady)throw new SpawnBrokerError(`Native resource broker unavailable`);this.markNativeReady(e,t)},refreshReference:()=>this.refreshNativeReference()})}this.readiness.promise.catch(()=>{}),this.start(),this.unregisterExitCleanup=registerProcessExitCleanup(this.onParentExit)}get pid(){return this.process?.pid}get hasOpenNativeResourceClaims(){return this.resourceClaims?.hasOpenClaims??!1}get nativeResourceAdmissionClosed(){return(this.resourceClaims?.admissionClosed??!1)||this.process?.connected===!1}ready(){return this.closing?Promise.reject(new SpawnBrokerError(`Spawn broker is closing`)):this.readiness.promise}readFile(e,t){return this.fileReads.read(e,t)}captureNativeResource(e,t){if(!this.resourceClaims||!this.resourceAuthority||this.closing||this.resourceClaims.size>=256)throw new SpawnBrokerError(`Native resource broker is unavailable or at capacity`);return this.resourceClaims.capture({...e,...e.moduleUrl.startsWith(`file:`)&&runtimeNeedsTypeScriptLoader(c(e.moduleUrl))?{sourceLoaderUrl:import.meta.resolve(`tsx/esm/api`)}:{},...this.resourceAuthority,generation:this.generation-1,startupDeadline:this.available?void 0:this.startupDeadline,id:++this.sequence},t)}sealNativeResources(){return this.resourceClaims&&!this.available?Promise.reject(new SpawnBrokerError(`Native resource broker is not ready for cleanup`)):this.resourceClaims?.seal()??Promise.reject(new SpawnBrokerError(`Native resources are disabled`))}serviceNativeResources(){this.serviceStartup?.()}refreshNativeReference(){this.resourceClaims&&this.process&&(this.closing||this.resourceClaims.needsReference||this.requests.size>0?(this.process.ref(),process.ref(this.process.stderr),this.process.channel?.ref?.()):(this.process.unref(),process.unref(this.process.stderr),this.process.channel?.unref?.()))}admit(e,t){e.admission=getSpawnBrokerAdmission();let n=childCapacityError(this.childAdmissions.values(),e.admission),r=createBrokerCommandRequest(e,t,this.transmit.bind(this)),{child:i,result:a,output:s}=r,fail=e=>{r.resultSettled=!0,a?.reject(e),s?.reject(e),i.settleFileOutput(),i.fail(e)};return!this.available||this.closing||this.pendingSpawns.size+this.fileReads.size>=256||n?(i.markNotStarted(),queueMicrotask(()=>fail(new SpawnBrokerError(this.available&&!this.closing?n??`Spawn broker startup capacity exceeded`:`Spawn broker is unavailable`))),r):(this.childAdmissions.set(e.id,e.admission),this.requests.set(e.id,r),this.pendingSpawns.add(e.id),this.refreshNativeReference(),i.waitForClose().then(()=>{r.childClosed=!0,this.retire(e.id,r)}),this.transmit(e).catch(t=>{if(this.pendingSpawns.delete(e.id),t instanceof BrokerIpcAdmissionError)i.markNotStarted();else if(r.output){this.process?.connected&&this.process.disconnect();return}!r.nativeInitiated&&e.type===`prepare-spawn`&&i.markNotStarted(),fail(new SpawnBrokerError(`Spawn broker request delivery failed`,{cause:t}))}),r)}retire(e,t){if(t.childClosed&&t.resultSettled&&!t.nativeInitiated){if(t.child.notStarted||!t.recovering&&t.nativeClosed)this.childAdmissions.delete(e);else if(!t.recovering||t.pid===void 0)return;this.requests.delete(e),this.refreshNativeReference()}}retainCleanup(e,t){this.cleanups.add(e),e.settled.then(()=>{this.cleanups.delete(e),t!==void 0&&this.childAdmissions.delete(t)},t=>{this.cleanupErrors.push(toErrorObject(t,`Spawn broker cleanup failed`)),this.cleanups.delete(e)})}transmit(e,t,n){return!this.available||!this.sendMessage?Promise.reject(new SpawnBrokerError(`Spawn broker is unavailable`)):this.sendMessage(e,t,n)}start(){if(this.closing)return;try{assertChildRuntimeAvailable()}catch(e){this.readiness.reject(e);return}let e=this.generation++,t={type:`bootstrap`,...this.resourceAuthority?{nativeResource:{...this.resourceAuthority,generation:e}}:{}};if(qe(t).byteLength>rh)throw new SpawnBrokerError(`Spawn broker bootstrap exceeds its IPC bound`);let n=Fe(process.execPath,resolveRuntimeWorkerArgv(this.workerUrl),{stdio:[`inherit`,`ignore`,`pipe`,`ipc`],detached:!0,serialization:`advanced`});this.process=n;let r=observeBrokerChildDiagnostics(n),i=!1,a=waitForBrokerChildCompletion(n),s,prepareTerminalDiagnosis=()=>s??=f?r():a.then(r),c;this.brokerClosed=a.then(async()=>{await c,i&&n.pid&&(n.exitCode!==0||n.signalCode!==null)&&this.cleanupErrors.push(new SpawnBrokerError(`Spawn broker shutdown failed`,{cause:await prepareTerminalDiagnosis().catch(e=>toErrorObject(e,`Spawn broker exit diagnosis failed`))}))});let l=createBrokerReceiver(),u=createDeferredCore(),d=!1,f=!1;this.startupDeadline=spawnBrokerStartupNowMs()+Qm;let checkStartup=()=>{!d&&!f&&spawnBrokerStartupNowMs()>=this.startupDeadline&&fail(/* @__PURE__ */ Error(`readiness deadline exceeded after 15000ms`))},p=this.resourceClaims?void 0:setTimeout(checkStartup,Qm);this.serviceStartup=checkStartup;let fail=(e,t=!1)=>{if(d)return;i=this.closing,d=!0,clearTimeout(p),this.markNativeReady=void 0,l.clear(),this.available=!1,this.resourceClaims?.closeAdmission(),this.sendMessage=void 0,n.connected&&n.disconnect();let r=this.readiness;this.readiness=createDeferredCore(),this.readiness.promise.catch(()=>{});let s=this.requests;this.requests=/* @__PURE__ */ new Map,this.pendingSpawns.clear();let m=[];for(let[e,t]of s){if(t.recovering=!0,t.pid&&!t.nativeClosed){let r=t.pid;if(this.closing){let i;this.retainCleanup({force:()=>i?.force(),settled:u.promise.then(async()=>{(n.exitCode!==0||n.signalCode!==null)&&(i=terminateLostBrokerChild(r,t.detached),await i.settled)})},e)}else this.retainCleanup(terminateLostBrokerChild(r,t.detached),e)}else(t.child.notStarted||t.nativeClosed)&&this.childAdmissions.delete(e);t.output&&m.push(t)}if(this.refreshNativeReference(),n.pid&&process.platform!==`win32`){let e=n.pid,t;this.retainCleanup({force:()=>t?.force(),settled:u.promise.then(async()=>{t=terminateBrokerProcessGroup(e),await t.settled})})}c=prepareBrokerFailureCause(t?prepareTerminalDiagnosis():prepareChildRuntimeFailure({error:e,started:f}),e).then(e=>{let t=createBrokerFailureError(e,this.hasBeenReady);r.reject(t),this.fileReads.fail(t);for(let e of s.values())e.result?.reject(t),e.child.fail(t);if(s.clear(),m.length&&Promise.allSettled([a,...[...this.cleanups].map(e=>e.settled)]).then(()=>{for(let e of m)e.output?.reject(t),e.child.settleFileOutput();m.length=0}),this.resourceClaims||this.closing||!this.hasBeenReady||C(e,`NODE_RUNTIME_UNAVAILABLE`)){this.readiness.reject(t),this.resourceClaims?.fail(t);return}let n=nh[this.consecutiveFailures++];n===void 0?this.readiness.reject(t):this.restartTimer=setTimeout(()=>this.start(),n)})},markReady=(t,r)=>{if(d||t!==n.pid||r!==e)throw new SpawnBrokerError(`Native resource readiness does not match the captured broker`);f||(f=!0,clearTimeout(p),this.hasBeenReady=!0,this.consecutiveFailures=0,this.available=!0,this.readiness.resolve(),this.runInContext(()=>this.options.onReady?.(t,e>0)))};this.markNativeReady=markReady,n.once(`error`,fail),n.once(`exit`,()=>{d||(i=this.closing),u.resolve(),fail(void 0,!0)}),n.once(`disconnect`,()=>{f&&fail(/* @__PURE__ */ Error(`IPC channel disconnected`))}),n.on(`message`,(t,n)=>{if(d||this.closing){n instanceof rt&&n.destroy();return}let r;try{r=l.receive(t)}catch(e){fail(toErrorObject(e,`Spawn broker receive failed`));return}if(r===void 0)return;let i=r;if(i.type===`startup-failed`){if(!f&&this.resourceClaims){let e=this.resourceClaims;this.brokerClosed?.then(()=>e.closeBeforeStartup()).catch(e=>{this.cleanupErrors.push(toErrorObject(e,`Spawn broker startup cleanup failed`))})}fail(Object.assign(Error(i.error.message),i.error));return}if(i.type===`ready`){try{markReady(i.pid,e)}catch(e){fail(toErrorObject(e,`Spawn broker readiness failed`))}return}if(i.type===`resource-ready`||i.type===`resource-created`||i.type===`resource-target`||i.type===`resource-owner`||i.type===`resource-owner-received`||i.type===`resource-owner-rejected`||i.type===`resource-closed`||i.type===`resource-close-error`||i.type===`resource-failed`){try{this.resourceClaims?.receive(i)}catch(e){fail(toErrorObject(e,`Spawn broker native resource receive failed`))}return}if(this.fileReads.receive(i))return;(i.type===`spawned`||i.type===`error`)&&this.pendingSpawns.delete(i.id);let a=this.requests.get(i.id);if(!a)n instanceof rt&&n.destroy(),i.type===`pipe`?this.transmit({type:`pipe-received`,id:i.id,fd:i.fd}).catch(fail):i.type===`prepared`&&this.transmit({type:`launch`,id:i.id,allowed:!1}).catch(fail);else if((i.type===`owned`||i.type===`error`)&&(a.nativeInitiated?.resolve(),a.nativeInitiated=void 0),i.type===`prepared`){let e=a.initiateSpawn;a.initiateSpawn=void 0;let t=this.brokerClosed,n=e?a.nativeInitiated??=createDeferredCore():void 0,r=t&&n?Promise.race([n.promise,t]):Promise.reject(/* @__PURE__ */ Error(`Spawn broker retirement is unavailable`));r.catch(()=>{}),this.transmit({type:`launch`,id:i.id,allowed:!0},void 0,t=>{if(!e||!n||a.childClosed)throw new SpawnBrokerError(`Spawn broker launch grant is unavailable`);return e(t,r)}).catch(()=>{this.transmit({type:`launch`,id:i.id,allowed:!1}).catch(fail)})}else if(i.type===`owned`)a.pid=i.pid,a.childClosed&&(a.recovering=!0,this.retainCleanup(terminateLostBrokerChild(i.pid,a.detached),i.id),this.retire(i.id,a));else{try{receiveBrokerCommandResponse(a,i,n,e=>this.transmit(e))?.catch(fail)}catch(e){fail(toErrorObject(e,`Spawn broker pipe setup failed`));return}this.retire(i.id,a)}});try{n.send(t,e=>{e&&fail(e)})}catch(e){fail(toErrorObject(e,`Spawn broker bootstrap delivery failed`))}d||(this.sendMessage=createBrokerSender((e,t,r)=>n.send(e,t,{keepOpen:!0},r))),this.refreshNativeReference()}async waitForCleanup(){if(await Promise.allSettled([...this.cleanups].map(e=>e.settled)),this.cleanupErrors.length)throw AggregateError(this.cleanupErrors,`Spawn broker cleanup did not complete`)}close(){return this.resourceClaims?.hasOpenClaims?Promise.reject(new SpawnBrokerError(`Native resource claims must close before broker shutdown`)):this.closePromise??=this.closeInternal()}async closeInternal(){this.closing=!0,this.refreshNativeReference(),this.readiness.reject(new SpawnBrokerError(`Spawn broker is closing`)),this.fileReads.fail(new SpawnBrokerError(`Spawn broker is closing`)),clearTimeout(this.restartTimer);try{let e=this.process;e&&e.exitCode===null&&e.signalCode===null&&(this.resourceClaims?this.transmit({type:`shutdown`}).catch(()=>{e.connected&&e.disconnect()}):e.connected&&e.disconnect()),await this.brokerClosed;try{await this.waitForCleanup()}finally{this.resourceDirectory&&this.hasBeenReady&&await de(this.resourceDirectory,{recursive:!0,force:!0})}}finally{this.unregisterExitCleanup()}this.options.onClosed?.()}},createSpawnBrokerHost=e=>new BrokerHost(e)}));function createBrokerResourceSocket(e,t){let n=createBrokerReceiver(),r=Buffer.alloc(4),i=0,a,s=0,c=!1,l,u,stop=t=>{c||(c=!0,materializeErrorStack(t),l=t,n.clear(),a=void 0,u?.(t??new SpawnBrokerError(`Spawn broker resource socket closed`)),e.destroy())},d=createBrokerSender((t,n,r)=>{if(c||e.destroyed){r(l??new SpawnBrokerError(`Spawn broker resource socket closed`));return}let i=qe(t);if(i.length>268435456){r(new SpawnBrokerError(`Spawn broker resource frame exceeds capacity`));return}let a=Buffer.allocUnsafe(4+i.length);a.writeUInt32BE(i.length),i.copy(a,4);let complete=e=>{u===complete&&(u=void 0,r(e),e&&stop(e))};u=complete;try{e.write(a,e=>complete(e??null))}catch(e){complete(toErrorObject(e,`Spawn broker resource write failed`))}});return e.on(`data`,e=>{try{let l=0;for(;l<e.length&&!c;){if(!a){let t=Math.min(4-i,e.length-l);if(e.copy(r,i,l,l+t),i+=t,l+=t,i!==4)continue;let n=r.readUInt32BE();if(n===0||n>268435456)throw new SpawnBrokerError(`Invalid spawn broker resource frame length`);a=Buffer.allocUnsafe(n),i=0}let c=Math.min(a.length-s,e.length-l);if(e.copy(a,s,l,l+c),s+=c,l+=c,s!==a.length)continue;let u=n.receive(We(a));if(a=void 0,s=0,u!==void 0){if(!u||typeof u!=`object`||!(`value`in u))throw new SpawnBrokerError(`Invalid spawn broker resource message`);t.message(u.value)}}}catch(e){stop(toErrorObject(e,`Spawn broker resource read failed`))}}),e.once(`end`,()=>stop(a||i?new SpawnBrokerError(`Spawn broker resource socket ended during a frame`):void 0)),e.once(`error`,stop),e.once(`close`,()=>{stop(),t.close(l)}),{async send(t){if(c||e.destroyed)throw l??new SpawnBrokerError(`Spawn broker resource socket closed`);await d({value:t})},close:()=>stop()}}var ah=__esmMin((()=>{O(),wo(),qm(),lm()}));function attachBrokerNativeResource(e,t,n,r){let i=createDeferredCore();i.promise.catch(()=>{});let a,s,c,l=0,u=!1,d=!1,f=!1,p=!1,m,h=!1,g,recordFailure=e=>{if(p)return;let n=m===void 0;materializeErrorStack(e),m??=e,clearTimeout(c),clearTimeout(_),i.reject(e),g?.completion.reject(e),g=void 0,t.close(),n&&r(e)},lose=e=>{p||h||(h=!0,recordFailure(e),a?.close())},transmit=async(e,t=!1)=>{if(m&&(!t||h))throw m;if(!a||p)throw Error(`Native resource attachment is closed`);await a.send(e)},receive=r=>{if(!isRecord(r)||r.id!==e.id||typeof r.type!=`string`){lose(/* @__PURE__ */ Error(`Invalid native resource response identity`));return}let c=r;if(c.type===`resource-target`)t.postMessage(c.value,[]);else if(n(c),c.type===`resource-ready`)u=!0,clearTimeout(_);else if(c.type===`resource-created`)d=!0,s?.unref(),i.resolve();else if(c.type===`resource-closed`)p=!0,clearTimeout(_),g?.completion.resolve(),g=void 0,t.close(),a?.close();else if(c.type===`resource-close-error`){if(g?.id===c.requestId){let e=g;g=void 0,e.completion.reject(c.resourceError?new BrokerNativeResourceCloseError(c.error):toErrorObject(decodeNativeWorkerFailure(c.error),`Native resource close failed`))}}else c.type===`resource-failed`&&recordFailure(toErrorObject(decodeNativeWorkerFailure(c.error),`Native resource failed`))},start=()=>{if(m||p)return;let t;try{t=it(e.endpoint)}catch(e){queueMicrotask(()=>lose(toErrorObject(e,`Native resource attachment failed`)));return}s=t;let n=!1,r;t.once(`error`,e=>{r=e}),a=createBrokerResourceSocket(t,{message:receive,close(t){p||h||(!n&&!u&&e.startupDeadline!==void 0&&spawnBrokerStartupNowMs()<e.startupDeadline?c=setTimeout(start,10):lose(t??r??/* @__PURE__ */ Error(`Native resource attachment lost`)))}}),t.once(`connect`,()=>{n=!0,f=!0,transmit({type:`resource-attach`,attachment:e}).catch(e=>lose(toErrorObject(e,`Native resource attachment failed`)))})},_=e.startupDeadline===void 0?void 0:setTimeout(()=>{u||lose(/* @__PURE__ */ Error(`Spawn broker readiness deadline exceeded`))},Math.max(0,e.startupDeadline-spawnBrokerStartupNowMs()));start();let assertCleanupAvailable=()=>{if(h&&m)throw m},failDelivery=(e,t)=>{let n=toErrorObject(e,t);n!==m&&lose(n)};return i.promise.then(()=>{t.on(`message`,t=>{transmit({type:`resource-target`,id:e.id,value:t}).catch(e=>failDelivery(e,`Native resource input delivery failed`))}),t.unref()},()=>{}),{get dispatched(){return f},ownerMessage(t,n){i.promise.then(()=>transmit({type:`resource-owner`,id:e.id,sequence:n,value:t},!0)).catch(e=>failDelivery(e,`Native resource owner delivery failed`))},async close(){if(p)return;if(assertCleanupAvailable(),!d)try{await i.promise}catch(e){if(!u||h)throw e}if(p)return;assertCleanupAvailable(),s?.ref();let t=g??{id:++l,completion:createDeferredCore()};g||(g=t,t.completion.promise.catch(()=>{}),transmit({type:`resource-close`,id:e.id,requestId:t.id},!0).catch(e=>lose(toErrorObject(e,`Native resource close delivery failed`)))),await t.completion.promise},dispose(){clearTimeout(c),clearTimeout(_),a?.close()}}}var oh=__esmMin((()=>{O(),k(),wo(),Zm(),Ao(),eh(),ah()}));function resolveRuntimeWorkerGenerationUrl(e,t){return isEmbeddedStandaloneModule(e.href)?e:t?.resolve(e)??e}function captureRuntimeWorkerSource(e){let t=sh.getStore()?.generation,n=resolveRuntimeWorkerGenerationUrl(e,t);return n.href===e.href?{moduleUrl:e}:{moduleUrl:n,runtimeGeneration:t}}var sh,ch=__esmMin((()=>{Tu(),Qn(),Jl(),j(),ud(),sh=resolveGlobalSingleton(Symbol.for(`openclaw.runtimeWorkerGeneration`),()=>new D)}));function nativePortIsOpen(e){if(process.versions.bun){let t=e.hasRef();e.unref(),e.ref();let n=e.hasRef();return t||e.unref(),n}try{structuredClone(uh,{transfer:[e]})}catch(e){if(e===lh)return!0;if(e instanceof DOMException&&e.name===`DataCloneError`)return!1;throw e}throw Error(`Native port validation did not abort serialization`)}var lh,uh,dh=__esmMin((()=>{lh=/* @__PURE__ */ Error(`Native worker port validation reached the live sentinel`),lh.stack=void 0,uh={get value(){throw lh}}})),NativeWorkerTaskPort,fh=__esmMin((()=>{O(),wo(),Ol(),Dc(),dh(),NativeWorkerTaskPort=class{constructor(e,t){this.port=e,this.callbacks=t,this.pending=[],this.readMessage=()=>Ee(this.port),this.started=!1,this.disposed=!1,this.portClosed=!1,this.receive=e=>{observeWorkerMessage(e,`from_worker`),this.pending.push({type:`message`,value:e}),this.drain()},this.receiveError=e=>{this.pending.push({type:`messageerror`,error:e}),this.drain()},this.closed=()=>{this.portClosed=!0,this.drain(),this.fail(/* @__PURE__ */ Error(`Native worker task channel closed`))},e.on(`message`,this.receive),e.on(`messageerror`,this.receiveError),e.on(`close`,this.closed),e.unref()}fail(e){this.disposed||this.failure||(materializeErrorStack(e),this.failure=e,this.callbacks.unavailable())}start(){this.started=!0}drain(){if(!this.disposed&&this.started)for(;;){let e=this.pending.shift();if(e)e.type===`message`?this.callbacks.message(e.value):this.callbacks.messageerror(e.error);else{if(this.portClosed||this.failure)return;let e;try{e=runWithMainThreadTask(`worker:message-decode`,this.readMessage)}catch(e){this.fail(toErrorObject(e,`Native worker task channel observation failed`));return}if(!e)return;observeWorkerMessage(e.message,`from_worker`),this.callbacks.message(e.message)}if(this.disposed)return}}service(){if(this.drain(),this.disposed||this.failure)return;if(this.portClosed){this.fail(/* @__PURE__ */ Error(`Native worker task channel closed`));return}let e;try{e=nativePortIsOpen(this.port)}catch(e){this.fail(toErrorObject(e,`Native worker task channel observation failed`));return}e||(this.portClosed=!0,this.fail(/* @__PURE__ */ Error(`Native worker task channel closed`)))}assertAvailable(){if(this.failure)throw this.failure;if(this.disposed||this.portClosed)throw Error(`Native worker task channel is closed`)}postMessage(e,t){this.assertAvailable();let n=workerMessagePayloadBytes(e);this.port.postMessage(e,t),observeWorkerMessage(e,`to_worker`,`other`,n??null)}close(){this.disposed||(this.disposed=!0,this.pending.length=0,this.port.off(`message`,this.receive),this.port.off(`messageerror`,this.receiveError),this.port.off(`close`,this.closed),this.port.close())}}}));function workerRequestKind(e){return mh.get(r(e.pathname).replace(/\.(?:ts|mjs)$/,`.js`))??`extension`}var ph,mh,hh=__esmMin((()=>{Du(),ph={"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`},mh=new Map([...Object.entries(Eu).map(([e,t])=>[r(t.distWorkerPath),e]),...Object.entries(ph)])})),NativeWorker,gh=__esmMin((()=>{O(),cd(),eh(),wo(),Ol(),Ld(),Zm(),fh(),hh(),NativeWorker=class extends ut{get sourcePath(){if(!this.evalSource)return this.filename instanceof URL?this.filename.protocol===`file:`?c(this.filename):void 0:this.filename}get taskChannelFailure(){return this.taskPort?.failure}constructor(e,t,n,r,i,a,s){super(),this.runtime=e,this.id=t,this.filename=n,this.evalSource=r,this.ownsNativeResource=i,this.resourceConnection=a,this.runInContext=D.snapshot(),this.threadId=0,this.started=!1,this.executionStopped=!1,this.referenced=!0,this.stopping=!1,this.joined=!1,this.servicingResource=!1,this.resourceClosed=!1,this.supervisorJoined=!1,this.terminalObserved=!1,this.taskPortLossReported=!1,this.requestId=0,this.stopCompletion=createRetainedOperation(()=>this.service()),this.cpuRequests=/* @__PURE__ */ new Map,this.heapRequests=/* @__PURE__ */ new Map,this.diagnosticName=`worker:${!r&&n instanceof URL?workerRequestKind(n):`other`}`,s&&(this.taskPort=new NativeWorkerTaskPort(s,{message:e=>this.runInContext(()=>runWithMainThreadTask(this.diagnosticName,()=>this.emit(`message`,e))),messageerror:e=>this.runInContext(()=>this.emit(`messageerror`,e)),unavailable:()=>this.observeTaskPortLoss()}))}get needsReference(){return this.referenced||this.stopping||this.executionStopped&&this.ownsNativeResource&&!this.joined||this.cpuRequests.size>0||this.heapRequests.size>0}service(){this.runtime.service()}serviceTaskPort(){let e=this.taskPort;e&&(runWithMainThreadTask(this.diagnosticName,()=>e.service()),this.observeTaskPortLoss())}observeTaskPortLoss(){let e=this.taskPort?.failure;!e||!this.started||!this.referenced||this.taskPortLossReported||this.terminalObserved||this.stopping||this.joined||this.executionStopped||this.runtime.failure||(this.taskPortLossReported=!0,this.runInContext(()=>this.emit(`error`,e)))}serviceResource(){if(!(!this.resourceBinding||this.servicingResource||this.joined)){this.servicingResource=!0;try{this.resourceBinding.service()}catch(e){this.resourceFailed(e)}finally{this.servicingResource=!1}}}attachResource(e){return this.resourceBinding=this.bindResource(e),{workerDataKey:e.workerDataKey,attachment:this.resourceBinding.attachment}}bindResource(e){let t=this.runtime.resourceBroker(),n=this.resourceConnection,r=!1,i=t.captureNativeResource({moduleUrl:e.moduleUrl,input:e.input,ownerPort:!!n},{message:e=>{e.type===`resource-owner`?n?.port.postMessage(e.value,[]):e.type===`resource-closed`&&this.runInContext(()=>{this.resourceClosed=!0,(this.supervisorJoined||this.executionStopped)&&this.finishJoined(this.executionExitCode)})},failed:e=>this.resourceFailed(e)}),forward=e=>{if(!r)try{let t=i.ownerMessage(e);this.runtime.failure||this.runtime.post({type:`resource-owner`,id:this.id,sequence:t.sequence,value:e})}catch(e){this.resourceFailed(toErrorObject(e,`Native resource owner delivery failed`))}};n?.port.on(`message`,forward),n?.port.unref();let dispose=()=>{r||(r=!0,n?.port.off(`message`,forward),n?.port.close(),n?.dispose())};return{attachment:i.attachment,receive(e){i.receive(e)},service(){if(!r&&n)for(n.service();;){let e=Ee(n.port);if(!e)break;forward(e.message)}},async closeAfterSupervisor(){try{await t.sealNativeResources(),await i.close()}catch(e){throw e instanceof BrokerNativeResourceCloseError&&n?.decodeCloseError?n.decodeCloseError(e.payload):e}},release(){i.release(),dispose()},abandonUnattached(){i.abandonUnattached(),dispose()}}}abandonResource(){this.taskPort?.close(),this.resourceBinding?this.resourceBinding.abandonUnattached():this.resourceConnection?.dispose()}resourceFailed(e){this.runInContext(()=>{this.rejectStopCompletion(e),this.emit(`error`,toErrorObject(e,`Native resource observation failed`))})}rejectStopCompletion(e){materializeErrorStack(e),this.stopCompletion.reject(e)}recoverResource(){if(!this.resourceBinding||this.joined||this.resourceRecovery)return;let e=this.resourceBinding.closeAfterSupervisor();this.resourceRecovery=e,e.then(()=>this.runInContext(()=>{this.finishJoined(void 0)}),e=>this.runInContext(()=>{this.stopping=!1,this.rejectStopCompletion(e)}))}postMessage(e,t=[]){if(this.joined||this.stopping||this.executionStopped)throw Error(`Native worker is closing`);if(this.runtime.failure)throw this.runtime.failure;this.taskPort?this.taskPort.postMessage(e,t):this.runtime.post({type:`post`,id:this.id,value:e,transferList:t},t)}ref(){if(this.runtime.failure)throw this.runtime.failure;return this.taskPort?.assertAvailable(),this.referenced=!0,this.runtime.refreshReference(),this}unref(){if(this.referenced=!1,!this.joined&&this.runtime.failure)throw this.runtime.failure;return this.runtime.refreshReference(),this}stop(){if(this.joined)return this.stopCompletion.operation.read().status!==`fulfilled`&&(this.stopCompletion=createRetainedOperation(()=>this.service()),this.stopCompletion.resolve()),this.stopCompletion.operation;if(this.stopCompletion.operation.read().status===`rejected`&&(this.stopCompletion=createRetainedOperation(()=>this.service())),this.supervisorJoined&&this.resourceBinding)return this.rejectStopCompletion(Error(`Native resource cleanup is still retained after supervisor loss`,{cause:this.runtime.failure})),this.recoverResource(),this.stopCompletion.operation;if(!this.stopping){this.stopping=!0;try{this.runtime.post({type:`stop`,id:this.id})}catch(e){this.stopping=!1,this.rejectStopCompletion(e)}this.runtime.refreshReference()}return this.stopCompletion.operation}terminate(){return this.stop().result}cpuUsage(e){return this.requestSample(this.cpuRequests,{type:`cpu`,previous:e})}getHeapStatistics(){return this.requestSample(this.heapRequests,{type:`heap`})}requestSample(e,t){if(this.joined)return Promise.reject(/* @__PURE__ */ Error(`Native worker exited`));let n=createRetainedOperation(()=>this.service()),r=++this.requestId;e.set(r,n);try{this.runtime.post({...t,id:this.id,requestId:r})}catch(t){e.delete(r),n.reject(t)}return this.runtime.refreshReference(),n.operation.result}rejectSamples(e){for(let t of[...this.cpuRequests.values(),...this.heapRequests.values()])t.reject(e);this.cpuRequests.clear(),this.heapRequests.clear()}ownerFailed(e){this.runInContext(()=>{this.terminalFailure??=e,this.taskPort?.close(),this.stopping=!1,this.rejectSamples(e),this.rejectStopCompletion(e),this.emit(`error`,e)})}ownerJoined(e){this.runInContext(()=>{if(this.terminalFailure??=e,this.stopping=!1,this.supervisorJoined=!0,this.rejectSamples(e),this.finishExecution(void 0),this.ownsNativeResource){if(this.resourceClosed){this.finishJoined(void 0);return}this.rejectStopCompletion(Error(`Native resource cleanup outcome is unavailable after owner loss`,{cause:e})),this.recoverResource()}else this.finishJoined(void 0)})}finishJoined(e){this.joined||(this.joined=!0,this.taskPort?.close(),this.threadId=-1,this.stopping=!1,this.referenced=!1,this.rejectSamples(/* @__PURE__ */ Error(`Native worker exited`)),this.stopCompletion.resolve(),this.runtime.handles.delete(this.id),this.runtime.failure||this.runtime.post({type:`release`,id:this.id}),this.runtime.refreshReference(),this.resourceBinding?this.resourceBinding.release():this.resourceConnection?.dispose(),this.finishExecution(e),this.emit(`exit`,e))}finishExecution(e){this.executionStopped||(this.taskPort?.close(),this.executionStopped=!0,this.executionExitCode=e,this.emit(`execution-exit`,e)),this.resourceClosed&&!this.joined&&this.finishJoined(e)}receive(e){this.runInContext(()=>runWithMainThreadTask(this.diagnosticName,()=>{(e.type===`error`||e.type===`messageerror`||e.type===`create-error`||e.type===`execution-exit`||e.type===`stopped`||e.type===`stop-error`)&&(this.terminalObserved=!0,this.taskPort?.drain()),this.receiveOwned(e)}))}receiveOwned(e){if(e.type===`created`)this.started=!0,this.threadId=e.threadId,trackNativeWorkerForCpu(this,this.filename,this.evalSource),this.taskPort?.start(),this.emit(`started`),this.taskPort?.drain(),this.observeTaskPortLoss();else if(e.type===`message`)this.emit(`message`,e.value);else if(e.type===`resource-message`)this.resourceBinding?.receive(e.response);else if(e.type===`error`||e.type===`messageerror`){let t=toErrorObject(decodeNativeWorkerFailure(e.error),`Native worker failed`);this.terminalFailure??=t,this.emit(e.type,t)}else if(e.type===`create-error`){this.joined=!0,this.threadId=-1,this.referenced=!1;let t=toErrorObject(decodeNativeWorkerFailure(e.error),`Native worker creation failed`);this.rejectSamples(t),this.stopCompletion.resolve(),this.runtime.handles.delete(this.id),this.runtime.refreshReference(),this.abandonResource(),this.emit(`error`,t)}else if(e.type===`stopped`)this.finishExecution(e.code),this.finishJoined(e.code);else if(e.type===`execution-exit`)this.finishExecution(e.code);else if(e.type===`stop-error`){let t=this.stopping;this.stopping=!1;let n;try{if(e.resourceError){if(!this.resourceConnection?.decodeCloseError)throw Error(`Native resource cleanup error decoder is unavailable`,{cause:e.error});n=this.resourceConnection.decodeCloseError(e.error)}else n=toErrorObject(decodeNativeWorkerFailure(e.error),`Native worker stop failed`)}catch(e){n=toErrorObject(e,`Native resource cleanup error decoding failed`)}this.rejectStopCompletion(n),t||this.emit(`error`,n)}else if(e.type===`cpu`)this.cpuRequests.get(e.requestId)?.resolve(e.value),this.cpuRequests.delete(e.requestId);else if(e.type===`heap`)this.heapRequests.get(e.requestId)?.resolve(e.value),this.heapRequests.delete(e.requestId);else if(e.type===`request-error`){let t=toErrorObject(decodeNativeWorkerFailure(e.error),`Native worker observation failed`);this.cpuRequests.get(e.requestId)?.reject(t),this.heapRequests.get(e.requestId)?.reject(t),this.cpuRequests.delete(e.requestId),this.heapRequests.delete(e.requestId)}this.runtime.refreshReference()}}})),_h,vh=__esmMin((()=>{_h=Symbol.for(`openclaw.nativeWorkerLifetimes`)}));async function closeDefaultRetainedNativeWorkerSource(){await yh.defaultSource?.close()}function forgetNativeSource(e){e.runtimeGeneration?yh.sources.get(e.runtimeGeneration)===e&&yh.sources.delete(e.runtimeGeneration):yh.defaultSource===e&&(yh.defaultSource=void 0)}function nativeCleanupFailures(e){return e.flatMap(e=>e.status===`rejected`?[e.reason]:[])}function nativeResourceBroker(e){return e.broker.host??=runInDetachedAsyncContext(()=>createSpawnBrokerHost({nativeResources:!0,workerUrl:e.brokerModuleUrl}))}async function retireNativeResourceBroker(e){let t=e.broker;if(await t.closing,e.hasActiveWorkers||t.retainedUntilProcessExit||t.host?.hasOpenNativeResourceClaims)return!1;let n=t.host;return t.host=void 0,await(t.closing=n?.close()),t.closing=void 0,!0}function nativeRuntime(e){if(e.closing)throw Error(`Native worker source is closing`);let t=e.runtime;if(t){if(t.failure)throw t.failure;return t}return runInDetachedAsyncContext(()=>{let{port1:t,port2:n}=new be,r=e.moduleUrl,i=createSqliteDatabaseAdmissionCursor();captureSqliteDatabaseAdmissions(i);let a;try{a=createCpuTrackedWorker(r,{execArgv:resolveRuntimeWorkerThreadExecArgv(r),env:Se,workerData:{port:n},transferList:[n]})}catch(e){throw t.close(),n.close(),e}let s=/* @__PURE__ */ new Map,c=createDeferredCore();c.promise.catch(()=>void 0);let l=!1,terminateOwner=()=>{if(!l){l=!0,a.ref(),t.ref();try{a.terminate().catch(c.reject)}catch(e){c.reject(e)}}},receive=e=>{observeWorkerMessage(e,`from_worker`,`lifecycle`),s.get(e.id)?.receive(e)},readControlMessage=()=>Ee(t),u={databaseAdmissionCursor:i,handles:s,service(){for(;;){let e=runWithMainThreadTask(`worker:control-decode`,readControlMessage);if(!e)break;receive(e.message)}let n=[...s.values()];for(let e of n)e.serviceTaskPort(),e.serviceResource();if(u.failure)return;let r;try{r=nativePortIsOpen(t)}catch(e){fail(Error(`Native worker lifetime channel observation failed`,{cause:e})),terminateOwner();return}r?e.broker.host?.serviceNativeResources():(fail(/* @__PURE__ */ Error(`Native worker lifetime channel closed`)),terminateOwner())},post(e,n=[]){if(u.failure)throw u.failure;let r=workerMessagePayloadBytes(e);t.postMessage(e,n),observeWorkerMessage(e,`to_worker`,`lifecycle`,r??null)},resourceBroker(){return nativeResourceBroker(e)},refreshReference(){[...s.values()].some(e=>e.needsReference)?(a.ref(),t.ref()):(a.unref(),t.unref())},close(){return u.failure??=/* @__PURE__ */ Error(`Native worker lifetime owner is closing`),materializeErrorStack(u.failure),terminateOwner(),c.promise}},fail=e=>{if(!u.failure){u.failure=toErrorObject(e,`Native worker lifetime owner failed`),materializeErrorStack(u.failure);for(let e of s.values())e.ownerFailed(u.failure)}};return t.on(`message`,receive),t.on(`messageerror`,e=>{try{fail(e)}finally{terminateOwner()}}),a.on(`message`,e=>receiveWorkerMemoryPort(a,e)),a.on(`error`,fail),a.once(`exit`,()=>{setImmediate(()=>{let n=u.failure??/* @__PURE__ */ Error(`Native worker lifetime owner exited`);materializeErrorStack(n),u.failure=n,e.closing=!0;for(let e of s.values())e.ownerJoined(n);t.close(),c.resolve()})}),e.runtime=u,u.refreshReference(),u})}function captureRetainedNativeWorkerSource(e){let t=resolveRuntimeProcessEntrypointUrl(`workerNativeLifecycle`),n=e===void 0?captureRuntimeWorkerSource(t):{moduleUrl:resolveRuntimeWorkerGenerationUrl(t,e.runtimeGeneration),runtimeGeneration:e.runtimeGeneration},r=n.runtimeGeneration?yh.sources.get(n.runtimeGeneration):yh.defaultSource;if(r)return r;!n.runtimeGeneration&&yh.defaultBroker.host?.nativeResourceAdmissionClosed&&(yh.defaultBroker={});let i={...n,broker:n.runtimeGeneration?{}:yh.defaultBroker,brokerModuleUrl:resolveRuntimeWorkerGenerationUrl(resolveRuntimeProcessEntrypointUrl(`spawnBroker`),n.runtimeGeneration),closing:!1,get hasActiveWorkers(){return!!i.runtime?.handles.size},activeWorkerPaths(){return[...i.runtime?.handles.values()??[]].map(e=>e.sourcePath)},retireIdleBroker(){return retireNativeResourceBroker(i)},close(){return s??=Promise.resolve().then(async()=>{try{let e=nativeCleanupFailures(await Promise.allSettled([...a.values()].map(e=>e())));if(e.length)throw AggregateError(e,`Native worker execution owner cleanup failed`);if(i.hasActiveWorkers)throw Error(`Native worker execution owners have not joined`);i.closing=!0,await i.runtime?.close(),await retireNativeResourceBroker(i),forgetNativeSource(i),a.clear()}catch(e){throw i.closing||(s=void 0),materializeErrorStack(e),e}})},create(e,t,n,r){try{return startNativeWorker(nativeRuntime(i),e,t??{},n,r)}catch(e){throw r?.host.close(),r?.worker.close(),e}},async captureIndependentResource(e,t){if(await i.broker.closing,i.closing)throw Error(`Native worker source is closing`);let r=nativeResourceBroker(i),{port1:s,port2:c}=new be,l=createDeferredCore(),fail=e=>{l.reject(e),c.close()},u=r.captureNativeResource({moduleUrl:String(resolveRuntimeWorkerGenerationUrl(e,n.runtimeGeneration)),input:t,ownerPort:!1},{message(e){e.type===`resource-created`&&l.resolve()},failed:fail}),d=attachBrokerNativeResource(u.attachment,s,e=>u.receive(e),fail),f=!1,p={port:c,retainBrokerUntilProcessExit(){i.broker.retainedUntilProcessExit=!0},async close(){f||(d.dispatched?(await d.close(),await u.close(),u.release()):u.abandonUnattached(),d.dispose(),s.close(),c.close(),f=!0,a.delete(p),i.closing&&await retireNativeResourceBroker(i))}};try{return await l.promise,p}catch(e){try{await p.close()}catch(t){throw i.retain(p,()=>p.close()),AggregateError([e,t],`Native resource creation cleanup failed`,{cause:t})}throw e}},captureResource(e,t,r,i){let a=D.snapshot();return Object.freeze({moduleUrl:String(resolveRuntimeWorkerGenerationUrl(e,n.runtimeGeneration)),workerDataKey:t,input:r===void 0?void 0:structuredClone(r),connect:i?()=>a(()=>{let e=i(),t=e.decodeCloseError?.bind(e);return{port:e.port,service:()=>a(()=>e.service()),dispose:()=>a(()=>e.dispose()),decodeCloseError:t?e=>a(()=>t(e)):void 0}}):void 0})},retain(e,t){a.set(e,t),n.runtimeGeneration?.retain(i,()=>i.close())}},a=/* @__PURE__ */ new Map,s;return n.runtimeGeneration?yh.sources.set(n.runtimeGeneration,i):yh.defaultSource=i,i}function createRetainedNativeWorker(e,t={},n,r,i){try{return(n??captureRetainedNativeWorkerSource({runtimeGeneration:void 0})).create(e,t,r,i)}catch(e){throw i?.host.close(),i?.worker.close(),e}}function startNativeWorker(e,t,n,r,i){let a=++yh.nextId,s,c,l=!1;try{s=r?.connect?.(),c=new NativeWorker(e,a,t,n.eval===!0,r!==void 0,s,i?.host);let{env:u,transferList:d=[],...f}=n;e.handles.set(a,c);let p=r?c.attachResource(r):void 0,m=captureSqliteDatabaseAdmissions(e.databaseAdmissionCursor);l=!0,e.post({type:`create`,id:a,filename:{kind:t instanceof URL?`url`:`path`,value:String(t)},environmentData:captureSqliteWorkerEnvironmentData(m),options:{...f,environment:{...u===Se?process.env:u??process.env},shareEnvironment:u===Se},transferList:[...d],resource:p,taskPort:i?.worker},i?[...d,i.worker]:d)}catch(t){throw l&&(e.databaseAdmissionCursor=createSqliteDatabaseAdmissionCursor()),e.handles.delete(a),e.refreshReference(),c?c.abandonResource():(i?.host.close(),s?.dispose()),i?.worker.close(),t}return e.refreshReference(),c}var yh,bh=__esmMin((()=>{O(),ih(),oh(),Ao(),Do(),j(),mf(),wo(),Ol(),Iu(),ch(),Pu(),Rp(),Ld(),Dc(),gh(),vh(),dh(),yh=resolveGlobalSingleton(_h,()=>({nextId:0,sources:/* @__PURE__ */ new WeakMap,defaultBroker:{}}),closeDefaultRetainedNativeWorkerSource,`native-workers`)}));function resolveWorkerComputeLimit(){return Math.max(1,he()-1)}function resolveWorkerPoolSize(e){return Math.min(e===`reader`||e===`file-reader`?2:e===`compute`?4:1,resolveWorkerComputeLimit())}var xh=__esmMin((()=>{resolveWorkerPoolSize(`reader`)})),Sh=/* @__PURE__ */ __exportAll({reportSlowWorkerDelivery:()=>reportSlowWorkerDelivery});function reportSlowWorkerDelivery(e){Ch.warn(`slow SQLite worker delivery`,e)}var Ch,wh=__esmMin((()=>{v_(),Ch=createSubsystemLogger(`worker/delivery`)}));function captureWorkerStartObserver(e){let t=Th.getStore();return t?()=>t(workerScriptName(e)):void 0}function trackWorkerRequest(e,t,n){let r=normalizeWorkerRequestClass(t),i=e===`sqlite_writer`?Oh.getStore():void 0,a=performance.now(),s=e===`sqlite_writer`&&(kh||Dh.size>0||hasInternalDiagnosticEventInterest(`worker.request`,!0))?{enqueued:a}:void 0,c,l=!1,u,emit=(t,n,i)=>{if(!areDiagnosticsEnabledForProcess())return;let a=Ah.get(e)??0,c=t===`completed`?s:void 0;for(let s of Dh)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=()=>Ah.set(e,(Ah.get(e)??0)-1);Ah.set(e,(Ah.get(e)??0)+1),emit(`queued`);let d={requestClass:r,timing:s,...i?{recordTransactions:e=>{i.transactionCount=(i.transactionCount??0)+e}}:{},started:(e,t)=>{l||c!==void 0||(c=performance.now(),s&&t&&(u={performance:t,atStart:t.eventLoopUtilization(),threadId:e}),i&&(d.startedAt=c,d.threadId=e,i.active=d,i.operations.add(i.operations.has(r)||i.operations.size<8?r:`other`)),s&&(s.dispatched=c),n?.removeEventListener(`abort`,d.completed),dequeue(),emit(`started`,c-a))},completed:()=>{if(!l){if(l=!0,i?.active===d&&(i.active=void 0),n?.removeEventListener(`abort`,d.completed),c===void 0&&dequeue(),u&&s?.posted!==void 0&&s.received!==void 0&&s.received-s.posted>=Eh){let e=u.performance.eventLoopUtilization(u.atStart),t=s.executeStarted!==void 0&&s.executeFinished!==void 0?s.executeFinished-s.executeStarted:0,n={requestClass:r,threadId:u.threadId,deliveryMs:Math.round(s.received-s.posted),executeMs:Math.round(t),workerActiveMs:Math.round(e.active),workerIdleMs:Math.round(e.idle),workerActiveOutsideExecuteMs:Math.round(Math.max(0,e.active-t))};Promise.resolve().then(()=>(wh(),Sh)).then(({reportSlowWorkerDelivery:e})=>e(n)).catch(e=>{process.emitWarning(e instanceof Error?e:String(e))})}emit(`completed`,void 0,c===void 0?void 0:performance.now()-c)}}};return n?.addEventListener(`abort`,d.completed,{once:!0}),n?.aborted&&d.completed(),d}var Th,Eh,Dh,Oh,kh,Ah,jh=__esmMin((()=>{j(),Vc(),Gl(),yl(),Tc(),Ll(),Th=resolveGlobalSingleton(Symbol.for(`openclaw.workerStartObservation`),()=>new D),Eh=1e3,Dh=resolveGlobalSingleton(Symbol.for(`openclaw.workerRequestMetricsListeners`),()=>/* @__PURE__ */ new Set),Oh=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerReservationObservation`),()=>new D),kh=isDiagnosticFlagEnabled(`sqlite.worker-timing`),Ah=resolveGlobalSingleton(Symbol.for(`openclaw.workerRequestQueueDepth`),()=>/* @__PURE__ */ new Map)}));function getWorkerComputeCapacity(){return resolveGlobalSingleton(Symbol.for(`openclaw.workerComputeCapacity`),()=>createWorkerComputeCapacity(resolveWorkerComputeLimit()))}var Mh=__esmMin((()=>{td(),j(),xh()})),Nh=__esmMin((()=>{Do(),j(),resolveGlobalSingleton(Symbol.for(`openclaw.activeStoreWriters`),()=>new D),resolveGlobalSingleton(Symbol.for(`openclaw.storeWriterTurn`),()=>({started:0,startedAt:0,reset:void 0,wait:void 0}))})),Ph,Fh=__esmMin((()=>{j(),Nh(),Ph=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseWriteAdmission`),()=>({queues:/* @__PURE__ */ new Map})),Ph.queues}));function*reachablePools(){for(let e of Ih){let t=e.deref();t?yield{pool:t,reference:e}:Ih.delete(e)}}var Ih,Lh,Rh=__esmMin((()=>{td(),j(),Fh(),Ih=resolveGlobalSingleton(Symbol.for(`openclaw.workerTaskPools`),()=>/* @__PURE__ */ new Set),Lh={register(e){for(let t of reachablePools())if(t.pool===e)return e;return Ih.add(new WeakRef(e)),e},async close(e,t,n){await joinOwnedWorkerTasks(t),await n();for(let t of reachablePools())t.pool===e&&Ih.delete(t.reference)}}}));async function runBestEffortCleanup(e){try{return await e.cleanup()}catch(t){try{e.onError?.(t)}catch{}return}}var zh=__esmMin((()=>{}));function readDarwinImagePath(e){let t={encoding:`utf8`,timeout:2e3},r=Ie(`/usr/sbin/lsof`,[`-a`,`-p`,String(e),`-d`,`txt`,`-Fn`],t),i=r.status===0?/^n(\/.+)$/mu.exec(r.stdout)?.[1]:void 0,a=i&&Ie(`/bin/ps`,[`-o`,`ucomm=`,`-p`,String(e)],t);return a&&a.status===0&&a.stdout.trim()===n.basename(i).slice(0,16)?i:void 0}function isRedactedSystemImage(e){if(!e.startsWith(`/System/`))return!1;let t=Ie(`/usr/bin/codesign`,[`-d`,`--entitlements`,`-`,e],{encoding:`utf8`,timeout:2e3});return t.status===0&&Vh.test(t.stdout)}function readCommandWithServiceMarker(e){try{return lt(e,{environmentKeys:[`OPENCLAW_SERVICE_MARKER`]})}catch(t){if(!(t instanceof at)||t.code!==`incomplete`)throw t;let r=lt(e);return r&&[r.executable,r.argv[0]??``].some(e=>isNodeRuntime(e)||isBunRuntime(e)||n.basename(e)===`tsx`)?{...r,serviceMarkerUnavailable:!0}:r}}function readDarwinProcessCommand(e,t,n={}){try{let t=n.serviceMarker===!1?lt(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 at))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 Bh||(Bh=!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 Bh,Vh,Hh=__esmMin((()=>{Nu(),v_(),Sm(),Bh=!1,Vh=/\[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 Uh=__esmMin((()=>{}));function isRosettaTranslatedProcess(){return process.platform!==`darwin`||process.arch!==`x64`?!1:(Wh??=me.cpus()[0]?.model.includes(`Apple`)===!0,Wh)}var Wh,Gh=__esmMin((()=>{}));function isValueToken(e){return!e||e===`--`?!1:!e.startsWith(`-`)||/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){let n=e[t];return n?Kh.has(n)||n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`)?1:qh.has(n)?isValueToken(e[t+1])?2:1:0:0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,Kh,qh,`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}var Kh,qh,Jh=__esmMin((()=>{Kh=/* @__PURE__ */ new Set([`--dev`,`--no-color`]),qh=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`])})),Yh=__esmMin((()=>{Jh()}));function isContainerEnvironment(){return Xh??=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 u.accessSync(e,u.constants.F_OK),!0}catch{}try{let e=u.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 Xh,Zh=__esmMin((()=>{})),Qh=__esmMin((()=>{qt()}));function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}var $h=__esmMin((()=>{Qh(),Co(),wn(),Bo()}));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 r=e;;){let e;try{e=JSON.parse(u.readFileSync(n.join(r,`package.json`),`utf8`))}catch(e){let i=n.dirname(r);if(t&&extractErrorCode(e)===`ENOENT`){if(i===r)return{kind:`absent`};if(n.basename(r)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};r=i;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)),r=/* @__PURE__ */ new Map;if(t.size===0)return r;if(process.platform===`linux`){for(let e of t)try{r.set(e,u.readlinkSync(`/proc/${e}/cwd`))}catch{}return r}try{if(process.platform===`darwin`){let e=Ie(`/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 r;let i=e.stdout.split(`\0`);i.pop();let a=/* @__PURE__ */ new Set,s;for(let e of i){let i=e.replace(/^\n/,``);if(i.startsWith(`p`)){let e=/^p(\d+)$/.exec(i);s=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else s!==void 0&&i.startsWith(`n`)&&n.isAbsolute(i.slice(1))&&(r.delete(s)?a.add(s):a.has(s)||r.set(s,i.slice(1)))}}}catch{}return r}function classifyEntrypoint(e,t={}){let r=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(r.endsWith(`/openclaw`)||r===`openclaw`))return{kind:`openclaw`,entryIndex:0};let i=/(?:^|\/)openclaw\.mjs$/.test(r)?0:resolveRuntimeScriptPosition(e).position;if(typeof i!=`number`)return i.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:i.reason}:{kind:`other`};let a=e[i];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&n.isAbsolute(t.cwd)&&isBunRuntime(e[0]??``)&&!/[\\/]/u.test(a)&&!n.extname(a)){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[a]:void 0;if(typeof n==`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}let s=classifyOpenClawEntrypointPath(a,t);return s.kind===`openclaw`?{...s,entryIndex:i}:s}function classifyOpenClawEntrypointPath(e,t={}){let r=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(r))return{kind:`openclaw`};let i=[...eg,...t.additionalEntrypoints??[]],a=e;if(!n.isAbsolute(e)){let r=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!r||!n.isAbsolute(r))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};a=n.resolve(r,e)}let s,c;try{if(s=u.realpathSync(a),t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(s))return{kind:`openclaw`,artifactPath:s};let n=t.requirePackageIdentity||t.inspectPackage?u.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(r))return{kind:`openclaw`};let d=c?void 0:i.find(e=>l.endsWith(`/${e}`));if(!d&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};let f=d?s.slice(0,-d.length):c?s:n.dirname(s),p=readProcessPackageIdentity(f,t.inspectPackage&&!t.requirePackageIdentity||!d&&!c);return p.kind===`unknown`?{kind:`unclassified`,cause:`package-identity`,reason:p.reason}:p.kind===`package`&&p.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:n.resolve(f),entrypoint:s}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){let{command:n,owner:r,pid:i,port:a}=t;if(!t.requirePackageIdentity&&n===`gateway`&&r?.pid===i&&r?.state===`live`&&(a===void 0||r.port===a))return{kind:`openclaw`};let s=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(s))return!n||s===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};let c=classifyEntrypoint(e,t);if(n)return c.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(c.entryIndex)],1)[0]??``)!==n?{kind:`other`}:c;if(c.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return c.kind===`openclaw`?c:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let l=t.serviceMarker;if(i!==void 0&&process.platform===`linux`&&(isNodeRuntime(s)||isBunRuntime(s)||s===`tsx`))try{l=u.readFileSync(`/proc/${i}/environ`,`utf8`).split(`\0`).find(e=>e.startsWith(`OPENCLAW_SERVICE_MARKER=`))?.slice(24)}catch(e){return{kind:`unclassified`,cause:`service-marker`,reason:`process identity inspection failed (${extractErrorCode(e)??`unavailable`})`}}return!t.requirePackageIdentity&&l===`openclaw`?{kind:`openclaw`}:c}var eg,tg=__esmMin((()=>{O(),k(),yt(),Nu(),$h(),Yh(),fm(),eg=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`]}));function readWindowsProcessCensus(e){return ct({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(dt.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{st(e)}catch(e){e instanceof at&&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 ng=__esmMin((()=>{kl()})),rg=/* @__PURE__ */ __exportAll({logAppContainerTokenProbeFailure:()=>logAppContainerTokenProbeFailure});function logAppContainerTokenProbeFailure(e){createSubsystemLogger(`process`).debug(`AppContainer token probe failed; allowing spawn`,{error:String(e)})}var ig=__esmMin((()=>{v_()}));function assertAppContainerSpawnSupported(e){if(process.platform===`win32`&&!(e===`ignore`||e===`inherit`||Array.isArray(e)&&e.length>=3&&e.every(e=>e!=null&&e!==`pipe`&&e!==`overlapped`&&e!==`ipc`&&!(typeof e==`number`&&e<0)))){if(!ag){ag=!0;try{let{readCurrentAppContainerSid:e}=t(import.meta.url)(`@openclaw/proc-safe/windows-token`),n=e(),r=process.versions.uv,i=Number(r.split(`.`)[0]),a=Number(r.split(`.`)[1]);n!==null&&(i<1||i===1&&a<53)&&(og=new AppContainerSpawnUnsupportedError(r))}catch(e){Promise.resolve().then(()=>(ig(),rg)).then(({logAppContainerTokenProbeFailure:t})=>t(e)).catch(()=>{})}}if(og)throw og}}var AppContainerSpawnUnsupportedError,ag,og,sg=__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`}},ag=!1}));function locateWindowsRegExe(){let e=n.win32.join(cg,`System32`,`reg.exe`);return canAccessSync(e,u.constants.R_OK)?e:null}function trimTrailingSeparators(e){let t=n.win32.parse(e),r=e;for(;r.length>t.root.length&&/[\\/]/.test(r.at(-1)??``);)r=r.slice(0,-1);return r}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 r=trimTrailingSeparators(n.win32.normalize(t));if(!n.win32.isAbsolute(r)||r.startsWith(`\\\\`))return null;let i=n.win32.parse(r);return!/^[A-Za-z]:\\$/.test(i.root)||r.length<=i.root.length?null:r}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?ug:Math.min(ug,Math.ceil(n-performance.now()));if(a<=0)return null;assertAppContainerSpawnSupported();try{let n=Pe(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`))??cg}function getProcessRoots(e){if(!dg){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(lg,`SystemRoot`,e)??void 0)??resolveSystemRootFromEnv(t)};if(e!==void 0&&performance.now()>=e)return n;dg=n}return dg}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 n.win32.join(getWindowsSystemRoot(e,t),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}var cg,lg,ug,dg,fg=__esmMin((()=>{Yn(),Co(),fm(),sg(),cg=`C:\\Windows`,lg=`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`,ug=5e3,dg=null}));function readWindowsUserSid(){if(process.platform===`win32`)try{let e=Ie(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 pg=__esmMin((()=>{fg()})),mg=/* @__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(n.basename((e[0]??``).replaceAll(`\\`,`/`)).replace(/\.(exe|cmd|bat)$/iu,``)===`openclaw-gateway`)return!0;if(t.kind!==`openclaw`||t.entryIndex===void 0)return!1;let r=(e[t.entryIndex]??``).replaceAll(`\\`,`/`);return gg.some(e=>r.endsWith(`/${e}`))||getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(t.entryIndex)]),1)[0]===`gateway`}function classifyProcessArtifactCustody(e,t,r){if(!e)return{kind:`unknown`,reason:`process command is unavailable`};let i=`argv`in e?e.argv:[],a=[...i.map(e=>e.replace(/^--[^=]+=/u,``).replace(/^-r(?=.)/u,``)),r??``,`executable`in e?e.executable??``:``].filter(referencesRetainedArtifact);if(`argvUnavailable`in e||i.length===0)return a.length?{kind:`holder`}:{kind:`not-holder`};let{position:s,operands:l}=resolveRuntimeScriptPosition(i),u={pid:t,cwd:r??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:hg,inspectPackage:!0},d,f=a.flatMap(e=>{let t=classifyOpenClawEntrypointPath(e,u);return t.kind===`openclaw`&&t.artifactPath?[t.artifactPath]:(d??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`,[])});if(a.length&&l.length===0)return d?{kind:`unknown`,reason:d}:{kind:`holder`,paths:f};let p=classifyOpenClawArgv(i,u),m=process.getuid?.(),h=process.platform===`linux`&&p.kind===`unclassified`&&p.cause===`service-marker`&&e.uid!==void 0&&m!==void 0&&e.uid!==m,g=isGatewayProcess(i,p),_=a.length>0||f.length>0,unscoped=()=>_||!g?{kind:`holder`}:{kind:`holder`,gateway:!0};if(p.kind===`openclaw`){if(!p.artifactPath)return l.some(({module:e})=>e)?{kind:`holder`}:unscoped();f.push(p.artifactPath),_=!0}let v=f.length?{kind:`holder`,paths:f}:void 0;if(d??=p.kind===`unclassified`&&p.cause!==`runtime-syntax`?p.reason:void 0,!r||!n.isAbsolute(r)){if(p.kind===`other`&&typeof s!=`number`&&s.kind===`not-runtime`&&a.length===0)return{kind:`not-holder`};if(!h)return{kind:`unknown`,reason:d??`working directory is unavailable`}}let y=r&&n.isAbsolute(r)&&typeof s!=`number`&&s.kind!==`not-runtime`?readProcessPackageIdentity(r,!0):void 0;y?.kind===`package`&&y.name===`openclaw`&&(v=unscoped());let b=y?.kind===`package`?y.scripts:{};y?.kind===`unknown`&&(d??=y.reason);for(let{value:e,module:t}of l){let r=e;if(t){if(e.startsWith(`file:`))try{r=c(e)}catch(e){d??=String(e);continue}else if(!n.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){d??=`runtime module package identity is unavailable`;continue}}else if(isBunRuntime(i[0]??``)&&!/[\\/]/u.test(e)&&!n.extname(e)&&typeof b[e]==`string`&&b[e].trim())continue;let a=classifyOpenClawEntrypointPath(r,u);a.kind===`unclassified`?d??=a.reason:a.kind===`openclaw`&&(_||=a.artifactPath!==void 0,v=a.artifactPath&&(!v||v.paths)?{kind:`holder`,paths:[...v?.paths??[],a.artifactPath]}:unscoped())}return h&&!_&&!v?{kind:`not-holder`}:d?{kind:`unknown`,reason:d}:v??{kind:`not-holder`}}function classifyOpaqueWindowsCustody(e,t){let r=e.commandLine?parseWindowsNativeCommandLine(e.commandLine):null;if(r?.length)return classifyProcessArtifactCustody({argv:r,...e.executable?{executable:e.executable}:{}},t,e.cwd);if([e.executable,e.cwd].some(e=>e&&referencesRetainedArtifact(e)))return{kind:`holder`};if(e.foreignOwner||e.accessDenied)return{kind:`not-holder`};let i=e.executable;return i&&!isNodeRuntime(i)&&!isBunRuntime(i)&&!/openclaw/iu.test(n.win32.basename(i))?{kind:`not-holder`}:{kind:`unknown`,reason:`process command line is unavailable`}}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,r=typeof e==`string`?e:void 0,i=[],a={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`,s=Date.now()+(t?15e3:1e3),c=e?[...readWindowsProcessCensus(15e3)]:void 0,u=new Map(c?.map(e=>[e.pid,e])),d=e&&t?.windowsUserSid!==void 0&&readWindowsUserSid()===t.windowsUserSid,f=c?.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})],p=new Map(f.map(e=>[e.pid,e])),m=p.get(process.pid);if(!m||!t&&(!m.command&&process.platform!==`darwin`||process.platform===`linux`&&f.some(e=>e.command&&!(`argv`in e.command))))throw Error(`OpenClaw process census is incomplete.`);let h=c?new Map(c.map(({pid:e,cwd:t})=>[e,t])):readProcessWorkingDirectories(f.map(({pid:e})=>e)),g=/* @__PURE__ */ new Set,_=!t&&isUpdateCommandArgv(process.argv),v=/* @__PURE__ */ new Set([process.pid]),y=m,b=m.command?.ppid??m.ppid??0;for(;b>0;){let n=p.get(b);if(!n?.command||v.has(b)){if(t||(n?!n.command:e))break;throw Error(`OpenClaw process ancestry is incomplete.`)}let r=u.get(b)?.startIdentity,i=u.get(y.pid)?.startIdentity;if(e&&(!r||!i||BigInt(r)>=BigInt(i)))break;if(v.add(b),`argv`in n.command){let{argv:e,serviceMarker:r,serviceMarkerUnavailable:i}=n.command,a=classifyOpenClawArgv(e,{pid:b,serviceMarker:r,serviceMarkerUnavailable:i,cwd:h.get(b)??``,additionalEntrypoints:hg}),s=a.kind===`openclaw`&&a.entryIndex!==void 0?getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(a.entryIndex)]),1)[0]:void 0;(s===(t?`update`:`doctor`)||_&&s===`update`&&b===(m.command?.ppid??m.ppid))&&g.add(b)}y=n,b=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(/[\\/]+$/,``),l(t,{windows:e}).href]);return RegExp(`(?:^|[^\\w-])(?:${t?literal(t.runId):`(?!)`}(?=$|[^\\w-])|(?:${r.map(literal).join(`|`)||`(?!)`})(?=$|[/\\s"'\x60);,\\]]))`)},x=t?.artifactPaths??(r?[r]:[]),S=referencePattern(x),rootKey=e=>normalize(e.replace(/[\\/]+$/,``)),ee=new Set(t?.sharedRoots?.map(rootKey)),te=referencePattern(x.filter(e=>!ee.has(rootKey(e)))),ne=process.getuid?.(),outsideHandoffFamily=(e,t)=>{let n;try{n=ot(e,{throughPid:process.pid})}catch{return!1}return n?.stoppedBy===`through-pid`||t!==void 0&&n?.stoppedBy===`root`&&n.chain.every(e=>{let n=p.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:c,state:l,command:m}of f){if(t&&Date.now()>=s)throw Error(`Process census deadline exceeded`);if(c===process.pid||g.has(c)||(l?.startsWith(`Z`)||t)&&isPidDefinitelyDead(c))continue;let f=m&&`argv`in m?m.argv:void 0;if(t){if(!e&&f?.length===0)continue;let r=u.get(c),s=h.get(c),l=[...f??[],r?.commandLine??``,r?.executable??``,s??``],g=classifyOpenClawArgv(f??[r?.executable??``],{pid:c,cwd:s??``,serviceMarker:m&&`argv`in m?m.serviceMarker:void 0,additionalEntrypoints:hg});if(l.some(e=>S.test(normalize(e)))||!t.artifactPathsOnly&&g.kind===`openclaw`){outsideHandoffFamily(c,l.some(e=>te.test(normalize(e)))?void 0:t.familyDeadline)||a.matchingPids.push(c);continue}let _=t.familyExited?`unrelated`:r&&classifyWindowsHandoffAncestry(r,u,t.drivers??[]);if(_===`descendant`){a.matchingPids.push(c);continue}if(_===`unrelated`||d&&r?.accessDenied)continue;let v=r?.foreignOwner||m?.owner===`different`||m?.uid!==void 0&&ne!==void 0&&m.uid!==ne;if((!f||s===void 0)&&!v&&!isStandardSystemdLoginProcess(m,p.get(m?.ppid??0)?.command,ne)&&!outsideHandoffFamily(c)&&!predatesHandoffDrivers(c)){a.unverifiedPids.push(c);let t=r?.executable??f?.[0];i.push(`Could not verify handoff ancestry for PID ${c} (${t?(e?n.win32:n).basename(t):`image unavailable`}).`)}continue}let _=u.get(c),v=_&&!m?classifyOpaqueWindowsCustody(_,c):classifyProcessArtifactCustody(m,c,h.get(c));v.kind!==`not-holder`&&(v.kind===`holder`&&r&&(v.paths?!v.paths.some(e=>S.test(normalize(e))):v.gateway)||(a.matchingPids.push(c),v.kind===`unknown`&&i.push(`Could not verify runtime custody for PID ${c}: ${v.reason}`)))}}catch(e){let n=/Could not classify PID (\d+):/.exec(e instanceof Error?e.message:``);t&&n&&a.unverifiedPids.push(Number(n[1])),a.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?{...a,...i.length?{warnings:i}:{}}:a.error?{error:a.error}:{pids:a.matchingPids,...i.length?{warnings:i}:{}}}var hg,gg,_g=__esmMin((()=>{Nu(),Hh(),Pm(),Uh(),Sm(),Yn(),Gh(),Yh(),Zh(),tg(),Du(),ng(),pg(),hg=Object.values(Eu).flatMap(e=>[n.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`]),gg=[Eu.spawnBroker,Eu.directoryWatchHost,Eu.serviceChildWindowsJobAnchor].flatMap(e=>[n.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`])})),vg=/* @__PURE__ */ __exportAll({maintainRetainedUpdateRuntimes:()=>maintainRetainedUpdateRuntimes,registerRetainedUpdateRuntime:()=>registerRetainedUpdateRuntime,removeTemporaryArtifacts:()=>removeTemporaryArtifacts,reportRetainedUpdateRuntime:()=>reportRetainedUpdateRuntime,resolveRetainedUpdateRuntimeParents:()=>resolveRetainedUpdateRuntimeParents});function registerRetainedUpdateRuntime(e){return bg.add(e),()=>void bg.delete(e)}function reportRetainedUpdateRuntime(e,t){let n=`Runtime retained at ${e}: ${t}`;try{yg.warn(n)}catch{}return n}function resolveRetainedUpdateRuntimeParents(e,t=[]){let r=e.split(n.sep),i=r.indexOf(`node_modules`),a=[r.slice(0,i>=0?i+1:r.length).join(n.sep),...t],s=n.dirname(e),c=[s];for(;a.some(e=>se(e,s));){let e=n.dirname(s);if(e===s)break;s=e,c.push(s)}return c}async function isRetainedRuntimeMarker(e){if(await w.realpath(e).catch(()=>void 0)!==e)return!1;let t=JSON.parse(await w.readFile(e,`utf8`));return isRecord(t)&&t.name===`openclaw`}function projectRetainedSource(e,t){let r=n.parse(t).root;return n.join(e,`tree`,Buffer.from(r).toString(`hex`),n.relative(r,t))}async function recognizesShippedRuntime(e){let t=await w.readdir(e,{withFileTypes:!0});if(t.length!==Sg.size||!t.every(e=>Sg.has(e.name)&&(e.name===`tree`?e.isDirectory():e.isFile())))return!1;let r=await w.open(n.join(e,xg),`r`),i;try{let e=Buffer.alloc(65536),{bytesRead:t}=await r.read(e,0,e.length,0);i=e.toString(`utf8`,0,t)}finally{await r.close()}let a=/^\[("(?:[^"\\]|\\.)*")/u.exec(i)?.[1],s=a?JSON.parse(a):void 0;return typeof s==`string`&&n.isAbsolute(s)&&n.normalize(s)===s&&n.basename(s)===`package.json`&&await isRetainedRuntimeMarker(projectRetainedSource(e,s))}async function recognizesRetainedRuntime(e,t){let r=projectRetainedSource(e,t);if(await isRetainedRuntimeMarker(n.join(r,`package.json`)))return!0;let i=n.dirname(r),a=n.dirname(i),s=n.dirname(a);if(n.basename(r)!==`openclaw`||n.basename(i)!==`node_modules`||!n.basename(a).startsWith(`openclaw@`)||n.basename(s)!==`.pnpm`||await w.realpath(s).catch(()=>void 0)!==s)return!1;let c=0;for await(let e of await w.opendir(s)){if(++c>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(n.join(s,e.name,`node_modules/openclaw/package.json`)))return!0}return!1}async function maintainRetainedUpdateRuntimes(e){let t=[],r=e.packageRoots.map(resolveIdentityPathViaExistingAncestorSync),i=new Set([me.tmpdir(),...e.temporaryDirectories??[],...r.flatMap(e=>resolveRetainedUpdateRuntimeParents(e))].map(resolveIdentityPathViaExistingAncestorSync));for(let a of i)try{for(let i of await w.readdir(a,{withFileTypes:!0})){if(!/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(i.name))continue;let s=n.join(a,i.name);try{let n=await w.lstat(s);if(!n.isDirectory()||process.getuid&&n.uid!==process.getuid())throw Error(`directory ownership is unknown; inspect it before manual cleanup`);if(bg.has(s))throw Error(`the creating update still owns this runtime`);let i=!1;for(let e of r)if(await recognizesRetainedRuntime(s,e)){i=!0;break}if(i||=await recognizesShippedRuntime(s),!i)throw Error(`it does not match a runtime an OpenClaw updater created, so it is kept`);if(!e.repair){t.push(`Runtime retained at ${s}: run \`openclaw doctor --fix\` after its workers stop`);continue}let{inspectOtherOpenClawProcesses:a}=await Promise.resolve().then(()=>(_g(),mg)),c=await w.lstat(s);if(c.dev!==n.dev||c.ino!==n.ino||c.ctimeMs!==n.ctimeMs||bg.has(s))throw Error(`directory identity or custody changed`);e.assertCurrent();let l=a(s);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?.(s),e.assertCurrent();let u;await removeTemporaryArtifacts(s,`Updater runtime`,e=>{u=`cleanup failed: ${formatErrorMessage(e)}`}),t.push(u?reportRetainedUpdateRuntime(s,u):`Removed abandoned updater runtime: ${s}`)}catch(e){C(e,`ENOENT`)||t.push(reportRetainedUpdateRuntime(s,formatErrorMessage(e)))}}}catch(e){C(e,`ENOENT`)||t.push(`Cannot inspect updater runtimes in ${a}: ${formatErrorMessage(e)}`)}return t}function removeTemporaryArtifacts(e,t,n=n=>yg.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:()=>w.rm(e,{recursive:!0,force:!0}),onError:n})}var yg,bg,xg,Sg,Cg=__esmMin((()=>{k(),Xt(),v_(),j(),Cn(),So(),zh(),Co(),wn(),yg=createSubsystemLogger(`infra:temp-artifacts`),bg=resolveGlobalSingleton(Symbol.for(`openclaw.retainedUpdateRuntimes`),()=>/* @__PURE__ */ new Set),xg=`retained-files.json`,Sg=/* @__PURE__ */ new Set([xg,`tree`,`update-native-gate.mjs`])}));function createWorkerTaskHost(e={},t){let n=t&&t!==`writer`&&t!==`singleton`,r=e.retainedTransport?e.nativeSource??captureRetainedNativeWorkerSource({runtimeGeneration:void 0}):void 0;return{maxWorkers:t?resolveWorkerPoolSize(t):void 0,requiresReady:e.retainedTransport,createWorker(t,i){let a={execArgv:resolveRuntimeWorkerThreadExecArgv(t),...i};if(a.env===void 0&&(a.env=resolveNodeCompileCacheEnv()),n){let e=a.resourceLimits;a.resourceLimits={maxOldGenerationSizeMb:e?.maxOldGenerationSizeMb??512,maxYoungGenerationSizeMb:e?.maxYoungGenerationSizeMb,codeRangeSizeMb:e?.codeRangeSizeMb,stackSizeMb:e?.stackSizeMb}}if(e.retainedTransport){let{port1:n,port2:i}=new be,s=createRetainedNativeWorker(t,a,r,e.nativeResource,{host:n,worker:i});return{worker:s,native:s}}return{worker:createCpuTrackedWorker(t,a)}},serviceNativeWorkers(e){for(let{owner:e}of Eg.values())e.service();e[0]?.service()},prepareResources:Tg,async releaseTemporaryDirectory(e){let{removeTemporaryArtifacts:t}=await Tg();await t(e,`Worker task`)},captureTaskContext(e){let t=Eg.get(e);t||(t={owner:runInDetachedAsyncContext(()=>createSqliteDatabaseAdmissionRelay(()=>{if(Eg.get(e)?.retiring!==!1)throw Error(`SQLite creation relay's task worker is retiring`)})),sent:!1,retiring:!1},Eg.set(e,t));let n=getDatabaseEngineSelection(),r={collectWorkerMetrics:isWorkerGcObservationEnabled(),...n?{databaseEngineSelection:n}:{},deletedAgentDatabaseFences:captureDeletedAgentDatabaseFences(),databaseAdmissionDeadlineAtMs:readSqliteDatabaseAdmissionDeadline(),...t.sent?{}:{databaseAdmissionPort:t.owner.port}};return t.postgresSent||(r.postgresPool=createPostgresPoolEndpoints(),t.postgresSent=r.postgresPool!==void 0),t.sent=!0,r},taskContextTransferList(e){let t=e,n=postgresPoolTransferList(t.postgresPool);return t.databaseAdmissionPort?[t.databaseAdmissionPort,...n]:n},createTaskObserver(e){let t=workerRequestKind(e);return e=>trackWorkerRequest(t,e===void 0?`task`:classifyWorkerRequest(e))},describeTask(e,t,n){if(n!==void 0){let t=wg.has(n)?n:classifyWorkerRequest(n);return`${workerRequestKind(e)}.${t}`}let r=typeof t==`object`&&t?Object.getOwnPropertyDescriptor(t,`kind`)?.value:void 0,i=typeof r==`string`&&wg.has(r)?r:`task`;return`${workerRequestKind(e)}.${i}`},receiveMessage:receiveWorkerMemoryPort,observeResourceReply:()=>recordWorkerMessage(`resource`,`from_worker`),captureWorkerStartObserver,workerStarted(e,n){trackSqliteDatabaseAdmissionWorker(e),attributeWorkerToPool(e,n,t)},workerRetiring(e,t){let n=Eg.get(e);n&&(n.retiring=!0),markWorkerRetirement(e,t)},workerStopped(e){let t=Eg.get(e);if(t){t.retiring=!0;let n=t.owner.finish();if(n)return n.then(()=>{Eg.delete(e)});Eg.delete(e)}},flushWorkerDiagnostics,computeCapacity:getWorkerComputeCapacity(),pools:Lh}}var wg,Tg,Eg,Dg=__esmMin((()=>{Do(),j(),hu(),Fs(),Rs(),rd(),zd(),Pu(),Rp(),Fc(),qp(),Tc(),Ld(),Dc(),bh(),xh(),jh(),hh(),Mh(),Rh(),wg=/* @__PURE__ */ new Set([`prepare`,`prepare-session`,`transcript-stats`,`session-entries`,`session-cleanup`,`session-memory-capture`,`history-page`,`historical-eviction-candidates`,`usage-cost`,`model-context`,`context-messages`,`transcript-search`,`session-target-prepare`,`session-store-target`,`session-target-inventory`,`combined-store-topology`]),Tg=createLazyRuntimeModule(()=>Promise.resolve().then(()=>(Cg(),vg))),Eg=resolveGlobalSingleton(Symbol.for(`openclaw.workerTaskDatabaseAdmissionChannels`),()=>/* @__PURE__ */ new Map)})),WorkerTaskPool,Og=__esmMin((()=>{td(),Dg(),WorkerTaskPool=class{constructor(e){this.core=new WorkerTaskPoolCore(e,createWorkerTaskHost(void 0,e.workerClass),{close:e=>this.close(e),getSnapshot:()=>this.getSnapshot()})}run(e,t){return this.core.run(e,t)}get isClosed(){return this.core.isClosed}getSnapshot(){return this.core.getSnapshot()}retryFailedRetirements(){return this.core.retryFailedRetirements()}rotate(){return this.core.rotate()}close(e,t){return this.core.close(e,t)}}})),kg=/* @__PURE__ */ __exportAll({runFileLogIOInWorker:()=>runFileLogIOInWorker});async function runFileLogIOInWorker(e,t){let n=resolveGlobalSingleton(Symbol.for(`openclaw.fileLogWorker`),()=>({}),async e=>{await t(),await e.pool?.close(),e.pool=void 0});return await(n.pool??=new WorkerTaskPool({workerUrl:resolveRuntimeProcessEntrypointUrl(`fileLog`),workerClass:`writer`})).run(e,{inputBytes:Buffer.byteLength(e.file)+(e.type===`append`?Buffer.byteLength(e.payload):0)})}var Ag=__esmMin((()=>{Iu(),Og(),j()}));async function runFileLogIO(e){return T?(await jg())(e,()=>Jg.flush()):await executeFileLogIO(e)}function resolveTarget(e,t=!1){let r=e.defaultRoot;if(!r)return t?e.file:Promise.resolve(e.file);if(r.directory!==void 0){let i=n.join(r.directory,e.file);return t?i:Promise.resolve(i)}if(t){let t=resolveDefaultFileLogTarget(e.file,r.options);return r.directory=n.dirname(t),t}return(r.resolution??=runFileLogIO({type:`resolveDefault`,file:e.file,root:r.options}).then(e=>r.directory=n.dirname(e)).catch(e=>{throw r.resolution=void 0,e})).then(t=>n.join(t,e.file))}function prepareTarget(e,t){if(e.prepared)return t?void 0:Promise.resolve();if(t)try{prepareFileLogTarget(resolveTarget(e,!0),e.rolling),e.prepared=!0}catch{}else return e.ready??=resolveTarget(e).then(t=>runFileLogIO({type:`prepare`,file:t,rolling:e.rolling})).then(()=>{e.prepared=!0}).catch(()=>{e.ready=void 0})}function getCurrentLogFileBytesSync(e){try{return u.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?u.writeSync(process.stderr.fd,n):process.stderr.write(n),!0}catch{return!1}}function warnAboutRotationFailure(e,t){Gg.get(e.file)!==e.maxFileBytes&&(Gg.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(Kg.has(e.file))return;let n=Kg.size>=Pg;n&&qg||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?qg=!0:Kg.add(e.file))}function clearAppendFailure(e){Kg.delete(e.file)&&(qg=!1)}function claimQueuedEntries(){let e=Ig===0?Fg:[...Fg.slice(Ig),...Fg.slice(0,Ig)];return Fg=[],Ig=0,zg>0&&Bg&&e.unshift(buildDroppedMarker(Bg,zg)),zg=0,Bg=null,e}function prepareWrite(e,t,n,r,i){let a=Buffer.byteLength(e.payload,`utf8`),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||n.targetPreparation!==e.targetPreparation)break;let i=Buffer.byteLength(n.payload,`utf8`);if(a+i>Ng||t+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(Ug)return;let r=e[n];if(!r)return;let i;try{i=r.targetPreparation?await resolveTarget(r.targetPreparation):r.file}catch{warnAboutAppendFailure(r,!1),r.payload=``,Rg=++n;continue}r.targetPreparation&&await prepareTarget(r.targetPreparation,!1);let a=t.get(i);if(!a){if(a={bytes:await runFileLogIO({type:`size`,file:i}).catch(()=>0)},Ug)return;t.set(i,a)}let s=a.bytes>0&&a.bytes+Buffer.byteLength(r.payload)>r.maxFileBytes,c=prepareWrite(r,s?0:a.bytes,!1,e,n);Rg=c.nextIndex;try{let e=await runFileLogIO({type:`append`,file:i,payload:c.payload,rotate:s});e.rotation===`rotated`?(a.bytes=0,Gg.delete(r.file)):e.rotation===`failed`&&warnAboutRotationFailure(r,!1),e.appended?(a.bytes+=c.payloadBytes,clearAppendFailure(r)):warnAboutAppendFailure(r,!1)}catch{t.delete(i),warnAboutAppendFailure(r,!1)}finally{for(let t of e.slice(n,c.nextIndex))t.payload=``;n=c.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;try{i=r.targetPreparation?resolveTarget(r.targetPreparation,!0):r.file}catch{warnAboutAppendFailure(r,!0),r.payload=``,n++;continue}let a=t.get(i);a||(a={bytes:getCurrentLogFileBytesSync(i)},t.set(i,a)),r.targetPreparation&&prepareTarget(r.targetPreparation,!0),a.bytes>0&&a.bytes+Buffer.byteLength(r.payload)>r.maxFileBytes&&(rotateLogFile(i)?(a.bytes=0,Gg.delete(r.file)):warnAboutRotationFailure(r,!0));let s=prepareWrite(r,a.bytes,!0,e,n);try{ee({filePath:i,content:s.payload}),a.bytes+=s.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!0)}r.payload=``,n=s.nextIndex}}async function runFlushLoop(){for(;;){if(Ug)return;let e=claimQueuedEntries();if(e.length===0)return;Lg=e,Rg=0,await writeEntries(e),Lg=null,Rg=0}}function startFlush(){if(Hg||Ug)return;let e=runFlushLoop().catch(()=>void 0);Hg=e,e.then(()=>{Hg=null,(Fg.length>0||zg>0)&&scheduleFlush()})}function scheduleFlush(){Vg||Hg||Ug||(Vg=setImmediate(()=>{Vg=null,startFlush()}))}function handleProcessBeforeExit(){flushFileLogQueue()}function handleProcessExit(){Ug=!0,drainFileLogQueueSync()}function installProcessHooks(){Wg||(Wg=!0,process.on(`beforeExit`,handleProcessBeforeExit),registerProcessExitCleanup(handleProcessExit))}function enqueueFileLog(e){if(Ug)writeEntriesSync([e]);else{if(installProcessHooks(),Fg.length>=Mg){let t=Fg[Ig];t&&(t.payload=``,Bg??=t,zg+=1),Fg[Ig]=e,Ig=(Ig+1)%Fg.length}else Fg.push(e);scheduleFlush()}}async function flushFileLogQueue(){for(;;){Vg&&=(clearImmediate(Vg),null),!Hg&&(Fg.length>0||zg>0)&&startFlush();let e=Hg;if(!e)return;await e}}function drainFileLogQueueSync(){Vg&&=(clearImmediate(Vg),null);let e=Lg?Lg.slice(Rg):[];Lg=null,Rg=0,e.push(...claimQueuedEntries()),writeEntriesSync(e)}var jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg=__esmMin((()=>{Kn(),pu(),j(),hu(),eu(),vu(),xo(),$l(),jg=createLazyRuntimeNamedExport(()=>Promise.resolve().then(()=>(Ag(),kg)),`runFileLogIOInWorker`),Mg=4096,Ng=65536,Pg=64,Fg=[],Ig=0,Lg=null,Rg=0,zg=0,Bg=null,Vg=null,Hg=null,Ug=!1,Wg=!1,Gg=/* @__PURE__ */ new Map,Kg=/* @__PURE__ */ new Set,qg=!1,Jg=resolveGlobalSingleton(Symbol.for(`openclaw.fileLogTransport`),()=>(process.env.VITEST!==`true`&&installProcessHooks(),{prepareTarget:(e,t,n=!1)=>({file:e,rolling:t,prepared:!1,...n?{defaultRoot:typeof n==`boolean`?{options:{stateDir:resolveStateDir()}}:n}:{}}),resolveTarget,drainSync:drainFileLogQueueSync,enqueue:enqueueFileLog,flush:flushFileLogQueue}))}));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<=Zg?t:`-3${b(`sha256`).update(e).digest(`hex`)}`}function resolveDefaultRollingLogFileName(){let e=/* @__PURE__ */ new Date,t=resolveLogProfileSegment(),n=t?`-${t}`:``;return`${lu}${n}-${formatLocalDate(e)}${uu}`}function isLegacyRollingLogFilePath(e){let t=n.basename(e);return t===`openclaw-YYYY-MM-DD.log`||Xg.exec(t)?.[1]===`openclaw`}function resolveRollingLogFilePathForDate(e,t){let r=Xg.exec(n.basename(e));return r?n.join(n.dirname(e),`${r[1]}-${formatLocalDate(t)}${uu}`):isLegacyRollingLogFilePath(e)?n.join(n.dirname(e),`${lu}-${formatLocalDate(t)}${uu}`):e}var Xg,Zg,Qg=__esmMin((()=>{du(),Yg(),Xg=/^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u,Zg=220}));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(),o_);return c_.test(t)?t:void 0}function assignDiagnosticLogAttribute(e,t,n,r){if(t.count>=i_)return;let i=n.trim();if(isBlockedObjectKey(i)||redactSensitiveText(i)!==i||!c_.test(i))return;let a;if(typeof r==`string`)a=sanitizeDiagnosticLogText(r,a_);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>=i_)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 extractTraceContext(e){return normalizeDiagnosticTraceContext(e)??normalizeDiagnosticTraceContext(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,s_):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(t_)return t_;let e=me.hostname().trim();return e?(t_=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<=n_&&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()),r_):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,o_));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&&!M.overrideSettings}function resolveDefaultActiveLogFile(){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG===`1`?n.join(process.cwd(),`.artifacts`,`test-logs`,`${lu}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date)}${uu}`):resolveDefaultRollingLogFileName()}function resolveSettings(){if(!canUseNodeFs())return{level:`silent`,file:$g,maxFileBytes:e_,rolling:!1};let e=resolveEnvLogLevelOverride();if(canUseSilentVitestFileLogFastPath(e))return{level:`silent`,file:resolveDefaultRollingLogFileName(),maxFileBytes:e_,rolling:!0,defaultRoot:!0};let t=M.overrideSettings??readLoggingConfig(),n=process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`?`silent`:`info`,r=normalizeLogLevel(t?.level,n),i=e??r,a=!t?.file||isLegacyRollingLogFilePath(t.file);return{level:i,file:resolveActiveLogFileWithMode(t?.file??resolveDefaultActiveLogFile(),a),maxFileBytes:resolveMaxLogFileBytes(t?.maxFileBytes),rolling:a,defaultRoot:!t?.file&&(process.env.VITEST!==`true`||process.env.OPENCLAW_TEST_FILE_LOG!==`1`)}}function getRuntimeFileTarget(e){let t=resolveActiveLogFileWithMode(e.file,e.rolling);return e.target?.file!==t&&(e.target=Jg.prepareTarget(t,e.rolling,e.target?.defaultRoot??e.defaultRoot)),e.target}function getRuntimeSettings(){let e=M.cachedSettings??resolveSettings();return M.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 initializeLoggerSourceMapPolicy(){typeof process<`u`&&process.env&&(process.env.TSLOG_SOURCE_MAPS??=`off`)}function buildLogger(){initializeLoggerSourceMapPolicy();let e=new RuntimeLogger({name:`openclaw`,mask:{keys:[]},meta:{property:`_meta`},minLevel:levelToMinLevel(`fatal`),type:`hidden`});return inheritLogLevel(e,()=>levelToMinLevel(getRuntimeSettings().level)),e.attachTransport({format:()=>``,write:e=>{try{let t=getRuntimeSettings();if(t.level===`silent`)return;let n=getRuntimeFileTarget(t),r=formatTimestamp(e.date??/* @__PURE__ */ new Date,{style:`long`}),{fields:i,messageParts:a}=prepareFileLogRecord(e),s=serializeFileLogRecord({...e,_meta:withResolvedLogMetaHostname(e._meta,i.hostname),time:r,...i},a);Jg.enqueue({file:n.file,targetPreparation:n,hostname:i.hostname,maxFileBytes:t.maxFileBytes,payload:`${s}\n`})}catch{}}}),attachDiagnosticEventTransport(e),e}function resolveMaxLogFileBytes(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):e_}function getLogger(){let e=M.cachedLogger;if(e)return e;getRuntimeSettings();let t=buildLogger();return M.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}var $g,e_,t_,n_,r_,i_,a_,o_,s_,c_,RuntimeLogger,l_=__esmMin((()=>{k(),Xt(),Vc(),Gl(),Zc(),Vn(),on(),su(),cu(),gr(),iu(),ru(),Qg(),du(),vr(),Yg(),xo(),mr(),$l(),$g=`${au}/openclaw.log`,e_=104857600,t_=null,n_=8192,r_=4096,i_=32,a_=2048,o_=120,s_=512,c_=/^[A-Za-z0-9_.:-]{1,64}$/u,RuntimeLogger=class extends Ze{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&&!M.overrideSettings)return{level:`silent`,style:normalizeConsoleStyle(void 0)};let t=M.overrideSettings??readLoggingConfig();return{level:e??normalizeConsoleLevel(t?.consoleLevel),style:normalizeConsoleStyle(t?.consoleStyle)}}function getConsoleSettings(){let e=M.cachedConsoleSettings;if(e)return e;let t=resolveConsoleSettings();return M.cachedConsoleSettings=t,t}function shouldLogSubsystemToConsole(e){let t=M.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 u_=__esmMin((()=>{yt(),Ln(),Jl(),zc(),gr(),iu(),eu(),ru(),l_(),xo(),mr(),$l(),`${process.release.name}${process.pid}`}));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=p_.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)%f_.length;return expectDefined(f_[r],`subsystem colors entry at idx`)}function formatSubsystemForConsole(e){let t=e.split(`/`).filter(Boolean),n=t.join(`/`)||e;for(;t[0]!==void 0&&m_.has(t[0]);)t.shift();let r=t.at(0);return r===void 0?n:h_.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=d_[s]??=new Xe({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`||M.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=M.rawConsole??console;M.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=\p{Cc}]/u.test(e)||e.length===0?stringifyConsoleMetaValue(e):e:e===null||typeof e==`number`||typeof e==`boolean`?String(e):stringifyConsoleMetaValue(e)}function stringifyConsoleMetaValue(e){return JSON.stringify(e).replace(/[\u007f-\u009f\u2028\u2029]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}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>__?`${r.slice(0,__)}...(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&&g_.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}`)}}}var d_,f_,p_,m_,h_,g_,__,v_=__esmMin((()=>{Zt(),O(),yt(),Lc(),zc(),Vc(),Gl(),ql(),u_(),ru(),l_(),xo(),mr(),d_=[],f_=[`cyan`,`green`,`yellow`,`blue`,`magenta`,`red`],p_=/* @__PURE__ */ new Map([[`gmail-watcher`,`blue`]]),m_=/* @__PURE__ */ new Set([`gateway`,`channels`,`providers`]),h_=/* @__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(`.`)),g_=/* @__PURE__ */ new Set([`warn`,`error`,`fatal`]),__=2048})),y_=/* @__PURE__ */ __exportAll({reportSlowIdleWorkerGc:()=>reportSlowIdleWorkerGc});function reportSlowIdleWorkerGc(e){b_.warn(`slow idle worker garbage collection`,e)}var b_,x_=__esmMin((()=>{v_(),b_=createSubsystemLogger(`worker/idle-gc`)}));const S_=33554432,C_=typeof Bun==`object`?Bun:void 0;let w_={heapUsed:0,external:0},T_,E_,D_=!1;function hasIdleGarbageGrowth(){let e=process.memoryUsage();return e.heapUsed>w_.heapUsed+S_||e.external>w_.external+S_}async function collectWorkerIdleGarbage(){if(E_=void 0,!hasIdleGarbageGrowth())return;D_=!0;let e=process.memoryUsage(),t=Date.now();try{if(C_)C_.gc(!0);else{if(!T_){let e=new Ye;e.connect(),T_=e}await T_.post(`HeapProfiler.collectGarbage`)}w_=process.memoryUsage();let n=Date.now()-t;if(n>=1e3){let t={elapsedMs:n,threadId:E,heapUsedBeforeBytes:e.heapUsed,heapUsedAfterBytes:w_.heapUsed,externalBeforeBytes:e.external,externalAfterBytes:w_.external};Promise.resolve().then(()=>(x_(),y_)).then(({reportSlowIdleWorkerGc:e})=>e(t)).catch(e=>{process.emitWarning(e instanceof Error?e:String(e))})}}catch(e){process.emitWarning(e instanceof Error?e:String(e))}finally{D_=!1}}function scheduleWorkerIdleGc(){T||E_||D_||hasIdleGarbageGrowth()&&(E_=setTimeout(()=>{collectWorkerIdleGarbage()},1e3).unref())}function cancelWorkerIdleGc(){clearTimeout(E_),E_=void 0}const O_={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},k_=/* @__PURE__ */ new Set;let A_,j_,M_;function getOldGenerationAfterGcBytes(){return M_}function drain(e){let t=A_?.stop();e&&A_?.start();let n=[];for(let e of t?.statistics??[]){let t=O_[e.gcType];if(!t)continue;let r=e.beforeGC.heapStatistics.usedHeapSize,i={kind:t,reason:`other`,durationMs:e.cost/1e3,heapUsedBeforeBytes:r,reclaimedBytes:Math.max(0,r-e.afterGC.heapStatistics.usedHeapSize)};if(t===`mark_sweep_compact`){i.heapUsedAfterMajorGcBytes=e.afterGC.heapStatistics.usedHeapSize,i.heapUsedAfterMajorGcTimestampSeconds=Date.now()/1e3,M_=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(M_+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of k_)e(n)}function flushGcSamples(){A_&&drain(!0)}function observeGcSamples(e){if(!process.versions.bun)return A_?drain(!0):(A_=new Ue,A_.start(),j_=setInterval(()=>drain(!0),1e3).unref()),k_.add(e),()=>{if(!k_.has(e))return;let t=k_.size===1;drain(!t),k_.delete(e),t&&(clearInterval(j_),j_=void 0,A_=void 0,M_=void 0)}}dc(),Ld();function serveWorkerMemorySamples(e,t){let{port1:n,port2:r}=new be,i=observeSqliteReaderCounters(e=>{n.postMessage({sqliteReaderCounter:e})}),a=observeTrackedPostgresBridgeCounters(()=>{n.postMessage({postgresBridgeCounters:getTrackedPostgresBridgeCounters()})}),s=process.versions.bun?void 0:Ke().heap_size_limit,c,l=!1,flushGc=()=>{c&&=(n.postMessage({gc:c}),void 0)},sample=()=>{let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:a}=process.memoryUsage(),l=process.versions.bun?void 0:Ge().map(({space_name:e,space_used_size:t})=>({space_name:e,space_used_size:t}));n.postMessage({heapUsed:e,heapTotal:r,external:i,arrayBuffers:a,heapSizeLimitBytes:s,oldGenerationAfterGcBytes:getOldGenerationAfterGcBytes(),heapSpaces:l,retainedData:t?.(),gc:c}),c=void 0},u,setGcEnabled=e=>{e?u??=observeGcSamples(e=>{(c??=[]).push(...e),(l||c.length>=256)&&flushGc()}):(u?.(),u=void 0,c=void 0)};return n.on(`message`,e=>{if(e&&`flush`in e)flushGcSamples(),flushGc(),n.postMessage({flushed:!0,heapUsed:Ke().used_heap_size});else if(e&&`captureGcProfile`in e){let t=e.captureGcProfile;Promise.resolve().then(()=>(Fd(),kd)).then(({captureWorkerGcProfiles:e})=>e()).then(e=>{n.postMessage({gcStorm:e.status===`complete`?{...t,captureStatus:`complete`,profiles:e.result}:{...t,captureStatus:`unavailable`,captureReason:e.reason}})}).catch(()=>{n.postMessage({gcStorm:{...t,captureStatus:`unavailable`,captureReason:`capture-failed`}})})}else e?setGcEnabled(e.gc):sample()}),n.once(`close`,()=>{a(),i(),u?.(),c=void 0}),n.on(`messageerror`,()=>n.close()),n.unref(),sample(),e.postMessage({status:`memory`,port:r,postgresBridgeCounters:getTrackedPostgresBridgeCounters()},[r]),{setTaskMetrics(e){l=e,setGcEnabled(e)},collectTask(){return l?!0:void 0},close(){a(),i(),u?.(),u=void 0,flushGc(),n.close()}}}Do(),k(),Ns(),mr(),Fs(),Rs(),Bs(),$s(),Fc();function serveWorkerTasks(e,t={}){serveOwnedWorkerTasks(e,t)}function serveOwnedWorkerTasks(e,t={}){let n,r,i,a,s,c,runWithTaskContext=async e=>{let run=async()=>{let t=i;if(!t)return e();let n=!0;try{return await withSqliteDatabaseAdmissionExchange((e,r,i,a)=>{if(!n)throw Error(`SQLite admission facts outlived their worker task`);return exchangeSqliteDatabaseAdmissions(t,e,r,i,a)},e)}finally{n=!1}};return s?withDatabaseEngineSelection(s,run):run()};serveOwnedWorkerTasks$1(typeof e==`function`?(t,n,r)=>withSqliteDatabaseAdmissionWait({deadlineAtMs:a,assertActive:()=>r.throwIfCancelled()},()=>runWithTaskContext(async()=>{let i=await e(t,n,r),a=postgresPoolWorkerFailure();if(a)throw a;return i})):e,{...t,get retireOnError(){return t.retireOnError||postgresPoolWorkerFailure()!==void 0},closesBesideExecution:e=>{let t=decodeAgentDatabaseReaderRequest(e);return t?.kind===`revive`||t?.kind===`close`&&t.deleted},closeResource:e=>runWithTaskContext(async()=>{let n=decodeAgentDatabaseReaderRequest(e);if(!n&&!t.closeResource)throw Error(`Worker does not own retained resources`);n&&await applyAgentDatabaseReaderRequest(n),n&&n.kind!==`close`||await t.closeResource?.(e)})},{selectStartupPort(e){if(isRecord(e)&&e.type===`openclaw.worker-task-port`){if(!(e.port instanceof xe))throw Error(`Retained worker task port is invalid`);return r=e.port,r}},initialize(e){M.forceConsoleToStderr=!0,n=e},onReady(){r?.postMessage({status:`ready`},[])},onMessage(e){e&&!c&&(c=serveWorkerMemorySamples(n,t.retainedData)),cancelWorkerIdleGc()},installTaskContext(e){c?.setTaskMetrics(e.collectWorkerMetrics===!0),a=e.databaseAdmissionDeadlineAtMs,s=e.databaseEngineSelection,e.postgresPool&&bindPostgresPool(e.postgresPool),installDeletedAgentDatabaseFences(e.deletedAgentDatabaseFences),e.databaseAdmissionPort&&bindSqliteDatabaseAdmissionUpstream(e.databaseAdmissionPort),i??=e.databaseAdmissionPort},onIdle(){scheduleOpenClawCompileCacheFlush(),t.idleGc!==!1&&scheduleWorkerIdleGc()},collectTaskDiagnostics:()=>c?.collectTask(),onRetire(){cancelWorkerIdleGc();try{c?.close()}finally{i?.close()}}})}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(e){return typeof e==`object`&&!!e}function freeze(e){return Object.freeze(e)}function asArray(e){return isReadonlyArray(e)?e:[e]}function isReadonlyArray(e){return Array.isArray(e)}function noop(e){return e}function getMessage(e){return e instanceof Error?e.message:String(e)}const B=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]})}}),V=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),N_=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:V.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),P_=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:V.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),F_=[`preserve rows`,`delete rows`,`drop`],H=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})}}),I_=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:V.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:V.create(e),identifier:V.create(t)})}}),L_=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:I_.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),R_=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:V.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),z_=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),B_=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),V_=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:I_.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:I_.createWithSchema(e,t)})}});function isOperationNodeSource(e){return isObject(e)&&isFunction(e.toOperationNode)}function isExpression(e){return isObject(e)&&`expressionType`in e&&isOperationNodeSource(e)}function isAliasedExpression(e){return isObject(e)&&`expression`in e&&isString(e.alias)&&isOperationNodeSource(e)}const H_=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})}}),U_=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),W_=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),G_=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`?U_.create(e.on,n):W_.create(e.on,n)})}}),K_=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:G_.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?G_.cloneWithOperation(e.on,`And`,t):G_.create(t)})}}),q_=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),J_=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(J_);const Y_=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(Y_);const X_=freeze({"->":!0,"->>":!0}),Z_=Object.keys(X_),Q_=freeze({...J_,...Y_,"||":!0}),$_=Object.keys(Q_),ev=freeze({exists:!0,"not exists":!0});Object.keys(ev);const tv=freeze({...ev,"-":!0,not:!0}),nv=Object.keys(tv);[...$_,...Z_,...nv];const rv=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&Q_[e]}function isJSONOperator(e){return isString(e)&&X_[e]}function isUnaryOperator(e){return isString(e)&&tv[e]}const U=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:V.create(e)})}}),iv=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),av=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:iv.create()})}});var DynamicReferenceBuilder=class{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return parseSimpleReferenceExpression(this.#e)}};function isDynamicReferenceBuilder(e){return isObject(e)&&isOperationNodeSource(e)&&isString(e.dynamicReference)}const ov=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})}}),W=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return W.create([e],[])},createWithChild(e){return W.create([``,``],[e])},createWithChildren(e){return W.create(Array(e.length+1).fill(``),e)}}),sv=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:V.create(e)})}});var cv=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:ov.cloneWith(this.#e.node,{direction:W.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:ov.cloneWith(this.#e.node,{direction:W.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:ov.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:ov.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:ov.cloneWith(this.#e.node,{collation:sv.create(e)})})}toOperationNode(){return this.#e.node}};const lv=/* @__PURE__ */ new Set;function logOnce(e){lv.has(e)||(lv.add(e),console.log(e))}function isOrderByDirection(e){return e===`asc`||e===`desc`}function parseOrderBy(e){if(e.length===2)return[parseOrderByItem(e[0],e[1])];if(e.length===1){let[t]=e;return Array.isArray(t)?(logOnce(`orderBy(array) is deprecated, use multiple orderBy calls instead.`),t.map(e=>parseOrderByItem(e))):[parseOrderByItem(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function parseOrderByItem(e,t){let n=parseOrderByExpression(e);if(ov.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 ov.create(e,W.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),ov.create(e,t.toOperationNode());let n=ov.create(e);return t?t(new cv({node:n})).toOperationNode():n}const uv=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})}}),dv=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])})}}),fv=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 uv.create(parseStringReference(e),dv.create(rv.create(t)));if(t===`->$`||t===`->>$`)return uv.create(parseStringReference(e),fv.create(rv.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return av.create(U.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 B_.create(parseStringReference(n),V.create(r))}return parseStringReference(e)}function parseColumnName(e){return U.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 av.create(U.create(r),V_.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return av.create(U.create(n),V_.create(t))}function trim$2(e){return e.trim()}const pv=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),mv=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),G=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):G.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 G.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?mv.create(e.map(e=>parseValueExpression(e))):pv.create(e)}const hv=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)?q_.create(parseReferenceExpression(e),parseBinaryOperator(t),G.createImmediate(n)):q_.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return q_.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`?U_.create:W_.create;if(e.length===0)return q_.create(G.createImmediate(1),rv.create(`=`),G.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?hv.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 rv.create(e);if(isOperationNodeSource(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function toOperationNode(e){return isOperationNodeSource(e)?e.toOperationNode():e}const gv=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])})}}),_v=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])})}}),vv=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?gv.cloneWithItems(e.orderBy,t):gv.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?_v.cloneWithItems(e.partitionBy,t):_v.create(t)})}}),yv=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])})}}),bv=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])})}}),xv=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`?U_.create(e.having,n):W_.create(e.having,n)})}}),K=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})}}),Sv=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Cv=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Sv.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?yv.cloneWithFroms(e.from,t):yv.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),wv=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])})}}),Tv=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:yv.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>q.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>q.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?wv.create(t):wv.cloneWithTables(e.using,t)})}}),Ev=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`?U_.create(e.where,n):W_.create(e.where,n)})}}),Dv=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)})}}),Ov=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),kv=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),Av=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),kv.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),jv=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)})}}),q=freeze({is(e){return J.is(e)||K.is(e)||Cv.is(e)||Tv.is(e)||Av.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?Ev.cloneWithOperation(e.where,`And`,t):Ev.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?Dv.cloneWithSelections(e.returning,t):Dv.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:Ov.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?jv.cloneWithSelections(e.output,t):jv.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?gv.cloneWithItems(e.orderBy,t):gv.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),J=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:yv.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)=>q.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?bv.cloneWithItems(e.groupBy,t):bv.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?xv.cloneWithOperation(e.having,`And`,t):xv.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=>q.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var Mv=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:K_.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:K_.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:K_.cloneWithOn(this.#e.joinNode,W.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const Nv=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(Nv.create)}var Pv=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:vv.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:q.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:vv.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const Fv=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:iv.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:av.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)?Fv.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?Fv.create(e.toOperationNode()):Fv.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[Fv.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return Fv.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const Iv=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),Lv=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(U.create)),Iv.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=Lv.create();return mv.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return pv.create(r)}const Rv=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?[Rv.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])=>Rv.create(U.create(e),parseValueExpression(t)))}const zv=freeze({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return freeze({kind:`OnDuplicateKeyNode`,updates:e})}});var InsertResult=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}},NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}const Bv=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?Ev.cloneWithOperation(e.indexWhere,`And`,t):Ev.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?Ev.cloneWithOperation(e.indexWhere,`Or`,t):Ev.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?Ev.cloneWithOperation(e.updateWhere,`And`,t):Ev.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?Ev.cloneWithOperation(e.updateWhere,`Or`,t):Ev.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var Vv=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=U.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:Bv.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(U.create);return new OnConflictBuilder({...this.#e,onConflictNode:Bv.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:Bv.cloneWith(this.#e.onConflictNode,{constraint:V.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:Bv.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:Bv.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:Bv.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:Bv.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:Bv.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new Hv({...this.#e,onConflictNode:Bv.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}},Hv=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:Bv.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:Bv.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:Bv.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const Uv=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 Uv.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const Wv=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var Gv=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{columns:freeze(e.map(U.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{orAction:Wv.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{orAction:Wv.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{orAction:Wv.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{orAction:Wv.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{orAction:Wv.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{orAction:Wv.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{onConflict:e(new Vv({onConflictNode:Bv.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:K.cloneWith(this.#e.queryNode,{onDuplicateKey:zv.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:q.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:q.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const Kv=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var Y,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new Y({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new Y({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new Y({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new Y({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new Y({...this.#e,queryNode:Tv.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 Y({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new Y({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new Y({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new Y({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new Y({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new Y({...this.#e,queryNode:q.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new Y({...this.#e,queryNode:Tv.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new Y({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new Y({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new Y({...this.#e,queryNode:Tv.cloneWithLimit(this.#e.queryNode,Kv.create(parseValueExpression(e)))})}modifyEnd(e){return new Y({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new Y({...this.#e})}$castTo(){return new Y(this.#e)}$narrowType(){return new Y(this.#e)}$assertType(){return new Y(this.#e)}withPlugin(e){return new Y({...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 Y({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};Y=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},X,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new X({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new X({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new X({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new X({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new X({...this.#e,queryNode:Cv.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 X({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new X({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new X({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new X({...this.#e,queryNode:Cv.cloneWithLimit(this.#e.queryNode,Kv.create(parseValueExpression(e)))})}set(...e){return new X({...this.#e,queryNode:Cv.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new X({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new X({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new X({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new X({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new X({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new X({...this.#e,queryNode:q.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new X({...this.#e})}$castTo(){return new X(this.#e)}$narrowType(){return new X(this.#e)}$assertType(){return new X(this.#e)}withPlugin(e){return new X({...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 X({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};X=UpdateQueryBuilder;const qv=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:V_.create(e),columns:t?freeze(t.map(U.create)):void 0})}}),Jv=freeze({is(e){return e.kind===`CommonTableExpressionNode`},create(e,t){return freeze({kind:`CommonTableExpressionNode`,name:e,expression:t})},cloneWith(e,t){return freeze({...e,...t})}});var Yv=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:Jv.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:Jv.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():Jv.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new Yv({node:Jv.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 qv.create(n,r)}return qv.create(e)}const Xv=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])})}}),Zv=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return Zv[~~(Math.random()*Zv.length)]}function createQueryId(){return new LazyQueryId}var LazyQueryId=class{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}},OperationNodeTransformer=class{nodeStack=[];#e=freeze({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(e,t){if(!e)return e;this.nodeStack.push(e);let n=this.transformNodeImpl(e,t);return this.nodeStack.pop(),freeze(n)}transformNodeImpl(e,t){return this.#e[e.kind](e,t)}transformNodeList(e,t){return e&&freeze(e.map(e=>this.transformNode(e,t)))}transformSelectQuery(e,t){return{kind:`SelectQueryNode`,from:this.transformNode(e.from,t),selections:this.transformNodeList(e.selections,t),distinctOn:this.transformNodeList(e.distinctOn,t),joins:this.transformNodeList(e.joins,t),groupBy:this.transformNode(e.groupBy,t),orderBy:this.transformNode(e.orderBy,t),where:this.transformNode(e.where,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),limit:this.transformNode(e.limit,t),offset:this.transformNode(e.offset,t),with:this.transformNode(e.with,t),having:this.transformNode(e.having,t),explain:this.transformNode(e.explain,t),setOperations:this.transformNodeList(e.setOperations,t),fetch:this.transformNode(e.fetch,t),top:this.transformNode(e.top,t)}}transformSelection(e,t){return{kind:`SelectionNode`,selection:this.transformNode(e.selection,t)}}transformColumn(e,t){return{kind:`ColumnNode`,column:this.transformNode(e.column,t)}}transformAlias(e,t){return{kind:`AliasNode`,node:this.transformNode(e.node,t),alias:this.transformNode(e.alias,t)}}transformTable(e,t){return{kind:`TableNode`,table:this.transformNode(e.table,t)}}transformFrom(e,t){return{kind:`FromNode`,froms:this.transformNodeList(e.froms,t)}}transformReference(e,t){return{kind:`ReferenceNode`,column:this.transformNode(e.column,t),table:this.transformNode(e.table,t)}}transformAnd(e,t){return{kind:`AndNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformOr(e,t){return{kind:`OrNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformValueList(e,t){return{kind:`ValueListNode`,values:this.transformNodeList(e.values,t)}}transformParens(e,t){return{kind:`ParensNode`,node:this.transformNode(e.node,t)}}transformJoin(e,t){return{kind:`JoinNode`,joinType:e.joinType,table:this.transformNode(e.table,t),on:this.transformNode(e.on,t)}}transformRaw(e,t){return{kind:`RawNode`,sqlFragments:freeze([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,t)}}transformWhere(e,t){return{kind:`WhereNode`,where:this.transformNode(e.where,t)}}transformInsertQuery(e,t){return{kind:`InsertQueryNode`,into:this.transformNode(e.into,t),columns:this.transformNodeList(e.columns,t),values:this.transformNode(e.values,t),returning:this.transformNode(e.returning,t),onConflict:this.transformNode(e.onConflict,t),onDuplicateKey:this.transformNode(e.onDuplicateKey,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orAction:this.transformNode(e.orAction,t),replace:e.replace,explain:this.transformNode(e.explain,t),defaultValues:e.defaultValues,top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformValues(e,t){return{kind:`ValuesNode`,values:this.transformNodeList(e.values,t)}}transformDeleteQuery(e,t){return{kind:`DeleteQueryNode`,from:this.transformNode(e.from,t),using:this.transformNode(e.using,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orderBy:this.transformNode(e.orderBy,t),limit:this.transformNode(e.limit,t),explain:this.transformNode(e.explain,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformReturning(e,t){return{kind:`ReturningNode`,selections:this.transformNodeList(e.selections,t)}}transformCreateTable(e,t){return{kind:`CreateTableNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),constraints:this.transformNodeList(e.constraints,t),indexes:this.transformNodeList(e.indexes,t),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),selectQuery:this.transformNode(e.selectQuery,t)}}transformColumnDefinition(e,t){return{kind:`ColumnDefinitionNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),references:this.transformNode(e.references,t),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,t),check:this.transformNode(e.check,t),generated:this.transformNode(e.generated,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,t){return{kind:`AddColumnNode`,column:this.transformNode(e.column,t)}}transformDropTable(e,t){return{kind:`DropTableNode`,table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade,temporary:e.temporary}}transformOrderBy(e,t){return{kind:`OrderByNode`,items:this.transformNodeList(e.items,t)}}transformOrderByItem(e,t){return{kind:`OrderByItemNode`,orderBy:this.transformNode(e.orderBy,t),direction:this.transformNode(e.direction,t),collation:this.transformNode(e.collation,t),nulls:e.nulls}}transformGroupBy(e,t){return{kind:`GroupByNode`,items:this.transformNodeList(e.items,t)}}transformGroupByItem(e,t){return{kind:`GroupByItemNode`,groupBy:this.transformNode(e.groupBy,t)}}transformUpdateQuery(e,t){return{kind:`UpdateQueryNode`,table:this.transformNode(e.table,t),from:this.transformNode(e.from,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),updates:this.transformNodeList(e.updates,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),explain:this.transformNode(e.explain,t),limit:this.transformNode(e.limit,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t),orderBy:this.transformNode(e.orderBy,t)}}transformColumnUpdate(e,t){return{kind:`ColumnUpdateNode`,column:this.transformNode(e.column,t),value:this.transformNode(e.value,t)}}transformLimit(e,t){return{kind:`LimitNode`,limit:this.transformNode(e.limit,t)}}transformOffset(e,t){return{kind:`OffsetNode`,offset:this.transformNode(e.offset,t)}}transformOnConflict(e,t){return{kind:`OnConflictNode`,columns:this.transformNodeList(e.columns,t),constraint:this.transformNode(e.constraint,t),indexExpression:this.transformNode(e.indexExpression,t),indexWhere:this.transformNode(e.indexWhere,t),updates:this.transformNodeList(e.updates,t),updateWhere:this.transformNode(e.updateWhere,t),doNothing:e.doNothing}}transformOnDuplicateKey(e,t){return{kind:`OnDuplicateKeyNode`,updates:this.transformNodeList(e.updates,t)}}transformCreateIndex(e,t){return{kind:`CreateIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,t),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,t){return{kind:`ListNode`,items:this.transformNodeList(e.items,t)}}transformDropIndex(e,t){return{kind:`DropIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,t){return{kind:`PrimaryKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,t){return{kind:`UniqueConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,t){return{kind:`ForeignKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),references:this.transformNode(e.references,t),name:this.transformNode(e.name,t),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,t){return{kind:`SetOperationNode`,operator:e.operator,expression:this.transformNode(e.expression,t),all:e.all}}transformReferences(e,t){return{kind:`ReferencesNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,t){return{kind:`CheckConstraintNode`,expression:this.transformNode(e.expression,t),name:this.transformNode(e.name,t)}}transformWith(e,t){return{kind:`WithNode`,expressions:this.transformNodeList(e.expressions,t),recursive:e.recursive}}transformCommonTableExpression(e,t){return{kind:`CommonTableExpressionNode`,name:this.transformNode(e.name,t),materialized:e.materialized,expression:this.transformNode(e.expression,t)}}transformCommonTableExpressionName(e,t){return{kind:`CommonTableExpressionNameNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t)}}transformHaving(e,t){return{kind:`HavingNode`,having:this.transformNode(e.having,t)}}transformCreateSchema(e,t){return{kind:`CreateSchemaNode`,schema:this.transformNode(e.schema,t),ifNotExists:e.ifNotExists}}transformDropSchema(e,t){return{kind:`DropSchemaNode`,schema:this.transformNode(e.schema,t),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,t){return{kind:`AlterTableNode`,table:this.transformNode(e.table,t),renameTo:this.transformNode(e.renameTo,t),setSchema:this.transformNode(e.setSchema,t),columnAlterations:this.transformNodeList(e.columnAlterations,t),addConstraint:this.transformNode(e.addConstraint,t),dropConstraint:this.transformNode(e.dropConstraint,t),renameConstraint:this.transformNode(e.renameConstraint,t),addIndex:this.transformNode(e.addIndex,t),dropIndex:this.transformNode(e.dropIndex,t)}}transformDropColumn(e,t){return{kind:`DropColumnNode`,column:this.transformNode(e.column,t),ifExists:e.ifExists}}transformRenameColumn(e,t){return{kind:`RenameColumnNode`,column:this.transformNode(e.column,t),renameTo:this.transformNode(e.renameTo,t)}}transformAlterColumn(e,t){return{kind:`AlterColumnNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),dataTypeExpression:this.transformNode(e.dataTypeExpression,t),setDefault:this.transformNode(e.setDefault,t),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,t){return{kind:`ModifyColumnNode`,column:this.transformNode(e.column,t)}}transformAddConstraint(e,t){return{kind:`AddConstraintNode`,constraint:this.transformNode(e.constraint,t)}}transformDropConstraint(e,t){return{kind:`DropConstraintNode`,constraintName:this.transformNode(e.constraintName,t),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,t){return{kind:`RenameConstraintNode`,oldName:this.transformNode(e.oldName,t),newName:this.transformNode(e.newName,t)}}transformCreateView(e,t){return{kind:`CreateViewNode`,name:this.transformNode(e.name,t),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,t),as:this.transformNode(e.as,t)}}transformRefreshMaterializedView(e,t){return{kind:`RefreshMaterializedViewNode`,name:this.transformNode(e.name,t),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,t){return{kind:`DropViewNode`,name:this.transformNode(e.name,t),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,t){return{kind:`GeneratedNode`,byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,t)}}transformDefaultValue(e,t){return{kind:`DefaultValueNode`,defaultValue:this.transformNode(e.defaultValue,t)}}transformOn(e,t){return{kind:`OnNode`,on:this.transformNode(e.on,t)}}transformSelectModifier(e,t){return{kind:`SelectModifierNode`,modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,t),of:this.transformNodeList(e.of,t)}}transformCreateType(e,t){return{kind:`CreateTypeNode`,name:this.transformNode(e.name,t),enum:this.transformNode(e.enum,t)}}transformDropType(e,t){return{kind:`DropTypeNode`,name:this.transformNode(e.name,t),additionalNames:this.transformNodeList(e.additionalNames,t),cascade:e.cascade,ifExists:e.ifExists}}transformExplain(e,t){return{kind:`ExplainNode`,format:e.format,options:this.transformNode(e.options,t)}}transformSchemableIdentifier(e,t){return{kind:`SchemableIdentifierNode`,schema:this.transformNode(e.schema,t),identifier:this.transformNode(e.identifier,t)}}transformAggregateFunction(e,t){return{kind:`AggregateFunctionNode`,func:e.func,aggregated:this.transformNodeList(e.aggregated,t),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,t),withinGroup:this.transformNode(e.withinGroup,t),filter:this.transformNode(e.filter,t),over:this.transformNode(e.over,t)}}transformOver(e,t){return{kind:`OverNode`,orderBy:this.transformNode(e.orderBy,t),partitionBy:this.transformNode(e.partitionBy,t)}}transformPartitionBy(e,t){return{kind:`PartitionByNode`,items:this.transformNodeList(e.items,t)}}transformPartitionByItem(e,t){return{kind:`PartitionByItemNode`,partitionBy:this.transformNode(e.partitionBy,t)}}transformBinaryOperation(e,t){return{kind:`BinaryOperationNode`,leftOperand:this.transformNode(e.leftOperand,t),operator:this.transformNode(e.operator,t),rightOperand:this.transformNode(e.rightOperand,t)}}transformUnaryOperation(e,t){return{kind:`UnaryOperationNode`,operator:this.transformNode(e.operator,t),operand:this.transformNode(e.operand,t)}}transformUsing(e,t){return{kind:`UsingNode`,tables:this.transformNodeList(e.tables,t)}}transformFunction(e,t){return{kind:`FunctionNode`,func:e.func,arguments:this.transformNodeList(e.arguments,t)}}transformCase(e,t){return{kind:`CaseNode`,value:this.transformNode(e.value,t),when:this.transformNodeList(e.when,t),else:this.transformNode(e.else,t),isStatement:e.isStatement}}transformWhen(e,t){return{kind:`WhenNode`,condition:this.transformNode(e.condition,t),result:this.transformNode(e.result,t)}}transformJSONReference(e,t){return{kind:`JSONReferenceNode`,reference:this.transformNode(e.reference,t),traversal:this.transformNode(e.traversal,t)}}transformJSONPath(e,t){return{kind:`JSONPathNode`,inOperator:this.transformNode(e.inOperator,t),pathLegs:this.transformNodeList(e.pathLegs,t)}}transformJSONPathLeg(e,t){return{kind:`JSONPathLegNode`,type:e.type,value:e.value}}transformJSONOperatorChain(e,t){return{kind:`JSONOperatorChainNode`,operator:this.transformNode(e.operator,t),values:this.transformNodeList(e.values,t)}}transformTuple(e,t){return{kind:`TupleNode`,values:this.transformNodeList(e.values,t)}}transformMergeQuery(e,t){return{kind:`MergeQueryNode`,into:this.transformNode(e.into,t),using:this.transformNode(e.using,t),whens:this.transformNodeList(e.whens,t),with:this.transformNode(e.with,t),top:this.transformNode(e.top,t),endModifiers:this.transformNodeList(e.endModifiers,t),output:this.transformNode(e.output,t),returning:this.transformNode(e.returning,t)}}transformMatched(e,t){return{kind:`MatchedNode`,not:e.not,bySource:e.bySource}}transformAddIndex(e,t){return{kind:`AddIndexNode`,name:this.transformNode(e.name,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists}}transformCast(e,t){return{kind:`CastNode`,expression:this.transformNode(e.expression,t),dataType:this.transformNode(e.dataType,t)}}transformFetch(e,t){return{kind:`FetchNode`,rowCount:this.transformNode(e.rowCount,t),modifier:e.modifier}}transformTop(e,t){return{kind:`TopNode`,expression:e.expression,modifiers:e.modifiers}}transformOutput(e,t){return{kind:`OutputNode`,selections:this.transformNodeList(e.selections,t)}}transformAlterType(e,t){return{kind:`AlterTypeNode`,name:this.transformNode(e.name,t),addValue:this.transformNode(e.addValue,t),renameTo:this.transformNode(e.renameTo,t),renameValue:this.transformNode(e.renameValue,t),setSchema:this.transformNode(e.setSchema,t)}}transformAddValue(e,t){return{kind:`AddValueNode`,value:this.transformNode(e.value,t),ifNotExists:e.ifNotExists,isBefore:e.isBefore,neighborValue:this.transformNode(e.neighborValue,t)}}transformRenameValue(e,t){return{kind:`RenameValueNode`,oldValue:this.transformNode(e.oldValue,t),newValue:this.transformNode(e.newValue,t)}}transformDataType(e,t){return e}transformSelectAll(e,t){return e}transformIdentifier(e,t){return e}transformValue(e,t){return e}transformPrimitiveValueList(e,t){return e}transformOperator(e,t){return e}transformDefaultInsertValue(e,t){return e}transformOrAction(e,t){return e}transformCollate(e,t){return e}};function isOperationNode(e){return isObject(e)&&isString(e.kind)}const Qv={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function isRootOperationNode(e){return isOperationNode(e)&&Qv[e.kind]===!0}const $v=freeze({json_agg:!0,to_json:!0});var WithSchemaTransformer=class extends OperationNodeTransformer{#e;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,t){if(!isRootOperationNode(e))return super.transformNodeImpl(e,t);let n=this.#a(e);for(let e of n)this.#n.add(e);let r=this.#i(e);for(let e of r)this.#t.add(e);let i=super.transformNodeImpl(e,t);for(let e of r)this.#t.delete(e);for(let e of n)this.#n.delete(e);return i}transformSchemableIdentifier(e,t){let n=super.transformSchemableIdentifier(e,t);return n.schema||!this.#t.has(e.identifier.name)?n:{...n,schema:V.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:V_.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=>V_.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return $v[e.func]?e[n].map(e=>!V_.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&&I_.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&&(K_.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(V_.is(e))return this.#s(e.table,t);if(B_.is(e)&&V_.is(e.node))return this.#s(e.node.table,t);if(Sv.is(e))for(let n of e.items)this.#o(n,t);else if(wv.is(e))for(let n of e.tables)this.#o(n,t)}#s(e,t){let n=e.identifier.name;!this.#t.has(n)&&!this.#n.has(n)&&t.add(n)}#c(e,t){for(let n of e.expressions){let e=n.name.table.table.identifier.name;this.#n.has(e)||t.add(e)}}},WithSchemaPlugin=class{#e;constructor(e){this.#e=new WithSchemaTransformer(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}};const ey=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 kv.create(parseFilterList([ey.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)?W.create([e],[]):isOperationNodeSource(e)?e.toOperationNode():e}var Deferred=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function provideControlledConnection(e,t){let n=new Deferred,r=new Deferred;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),freeze({connection:await n.promise,release:r.resolve})}function getInflightQueryAbortHandler(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function throwUnsupportedInflightQueryAbortStrategyError(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function assertNotAborted(e,t,n){e?.aborted&&(n?.(),throwReasonWithTiming(e.reason,t))}function throwReasonWithTiming(e,t){throw decorateWithTiming(e,t),e}const ty={};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(ty);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==ty)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(ty)}}function printBackgroundFail(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${getMessage(t)}`)}function decorateWithTiming(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}const ny=freeze([]);var QueryExecutorBase=class{#e;constructor(e=ny){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(ty);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})===ty&&(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===ty?(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===ty&&(f.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),p}finally{l(ty),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(ty);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===ty&&(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===ty&&(u=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{c(ty),r.removeEventListener(`abort`,abortListener);let e=(l?.return?.()||Promise.resolve()).finally(()=>u).finally(a);u||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(freeze({queryId:t,result:e,signal:r}));return e}};const ry=new class NoopQueryExecutor extends QueryExecutorBase{get adapter(){throw Error(`this query cannot be compiled to SQL`)}compileQuery(){throw Error(`this query cannot be compiled to SQL`)}provideConnection(){throw Error(`this query cannot be executed`)}withConnectionProvider(){throw Error(`this query cannot have a connection provider`)}withPlugin(e){return new NoopQueryExecutor([...this.plugins,e])}withPlugins(e){return new NoopQueryExecutor([...this.plugins,...e])}withPluginAtFront(e){return new NoopQueryExecutor([e,...this.plugins])}withoutPlugins(){return new NoopQueryExecutor([])}};var MergeResult=class{numChangedRows;constructor(e){this.numChangedRows=e}},iy=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new ay({...this.#e,queryNode:Av.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},ay=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:q.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:Av.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:q.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:Av.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 ay({...this.#e,queryNode:Av.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new ay({...this.#e,queryNode:Av.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new ay({...this.#e,queryNode:Av.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:ry,queryNode:Cv.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new ay({...this.#e,queryNode:Av.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new ay({...this.#e,queryNode:Av.cloneWithThen(this.#e.queryNode,parseMergeThen(K.cloneWith(K.createWithoutInto(),{columns:t,values:n})))})}},oy=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:J.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:J.cloneWithSelections(J.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new Gv({queryId:createQueryId(),executor:this.#e.executor,queryNode:K.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new Gv({queryId:createQueryId(),executor:this.#e.executor,queryNode:K.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Tv.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Cv.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new iy({queryId:createQueryId(),executor:this.#e.executor,queryNode:Av.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?Xv.cloneWithExpression(this.#e.withNode,n):Xv.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?Xv.cloneWithExpression(this.#e.withNode,n):Xv.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 oy({executor:ry})}function createJoinBuilder(e,t){return new Mv({joinNode:K_.create(e,parseTableExpression(t))})}function createOverBuilder(){return new Pv({overNode:vv.create()})}function parseJoin(e,t){if(t.length===3)return parseSingleOnJoin(e,t[0],t[1],t[2]);if(t.length===2)return parseCallbackJoin(e,t[0],t[1]);if(t.length===1)return parseOnlessJoin(e,t[0]);throw Error(`not implemented`)}function parseCallbackJoin(e,t,n){return n(createJoinBuilder(e,t)).toOperationNode()}function parseSingleOnJoin(e,t,n,r){return K_.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return K_.create(e,parseTableExpression(t))}const sy=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),cy=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(cy.create)}const ly=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=>ly.create(e,parseExpression(t),n))}var Z=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new uy(W_.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new dy(U_.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 B_.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():V.create(this.#t))}},uy=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(W_.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return hv.create(this.#e)}},dy=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(U_.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return hv.create(this.#e)}};const fy=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:G.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 fy.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var Q,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new Q({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new Q({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new Q({...this.#e,queryNode:J.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new Q({...this.#e,queryNode:J.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new Q({...this.#e,queryNode:J.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new Q({...this.#e,queryNode:J.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new Q({...this.#e,queryNode:J.cloneWithFrontModifier(this.#e.queryNode,H_.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.createWithExpression(e.toOperationNode()))})}distinct(){return new Q({...this.#e,queryNode:J.cloneWithFrontModifier(this.#e.queryNode,H_.create(`Distinct`))})}forUpdate(e){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.create(`SkipLocked`))})}noWait(){return new Q({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,H_.create(`NoWait`))})}selectAll(e){return new Q({...this.#e,queryNode:J.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 Q({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new Q({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new Q({...this.#e,queryNode:J.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new Q({...this.#e,queryNode:J.cloneWithLimit(this.#e.queryNode,Kv.create(parseValueExpression(e)))})}offset(e){return new Q({...this.#e,queryNode:J.cloneWithOffset(this.#e.queryNode,sy.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new Q({...this.#e,queryNode:J.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new Q({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new Q({...this.#e,queryNode:J.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new Q({...this.#e,queryNode:J.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new Q({...this.#e,queryNode:J.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new Q({...this.#e,queryNode:J.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new Q({...this.#e,queryNode:J.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new Q({...this.#e,queryNode:J.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new Q({...this.#e,queryNode:J.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new Q({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new Q({...this.#e,queryNode:J.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new Q({...this.#e,queryNode:J.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new Q({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new Q({...this.#e,queryNode:J.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new Q({...this.#e})}$castTo(){return new Q(this.#e)}$narrowType(){return new Q(this.#e)}$assertType(){return new Q(this.#e)}$asTuple(){return new Z(this.toOperationNode())}$asScalar(){return new Z(this.toOperationNode())}withPlugin(e){return new Q({...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 Q({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};Q=SelectQueryBuilderImpl;function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var AliasedSelectQueryBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return B_.create(this.#e.toOperationNode(),V.create(this.#t))}};const py=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]?gv.cloneWithItems(e[r],t):gv.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?Ev.cloneWithOperation(e.filter,`And`,t):Ev.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?Ev.cloneWithOperation(e.filter,`Or`,t):Ev.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),my=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var hy=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:py.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:q.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:q.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:py.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:py.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:py.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:py.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 B_.create(this.#e.toOperationNode(),V.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new Z(my.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new hy({aggregateFunctionNode:py.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 hy({aggregateFunctionNode:py.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 hy({aggregateFunctionNode:py.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new Z(my.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const gy=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 gy.create(rv.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const _y=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),kv.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:_y.cloneWithWhen(this.#e.node,kv.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:_y.cloneWithWhen(this.#e.node,kv.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:_y.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:_y.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:_y.cloneWithWhen(this.#e.node,kv.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:_y.cloneWithWhen(this.#e.node,kv.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:_y.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:_y.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new Z(_y.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Z(_y.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new Z(_y.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Z(_y.cloneWith(this.#e.node,{isStatement:!0}))}};const vy=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),yy=/^#-\d+$/;var JSONPathBuilder=class{#e;constructor(e){this.#e=e}at(e){if(typeof e!=`number`&&typeof e!=`string`||typeof e==`number`&&!Number.isInteger(e)||typeof e==`string`&&e!==`last`&&!yy.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 uv.is(this.#e)?new by(uv.cloneWithTraversal(this.#e,fv.is(this.#e.traversal)?fv.cloneWithLeg(this.#e.traversal,vy.create(e,t)):dv.cloneWithValue(this.#e.traversal,G.createImmediate(t)))):new by(fv.cloneWithLeg(this.#e,vy.create(e,t)))}},by=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 B_.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():V.create(this.#t))}};const xy=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Sy=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}),Cy=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+\)$/]),wy=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Sy[e]||Cy.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return wy.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Ty=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=ry){function binary(e,t,n){return new Z(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new Z(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:J.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:_y.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new Z(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(fv.create())},table(e){return new Z(parseTable(e))},val(e){return new Z(parseValueExpression(e))},refTuple(...e){return new Z(xy.create(e.map(parseReferenceExpression)))},tuple(...e){return new Z(xy.create(e.map(parseValueExpression)))},lit(e){return new Z(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 Z(q_.create(parseReferenceExpression(e),rv.create(`between`),U_.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new Z(q_.create(parseReferenceExpression(e),rv.create(`between symmetric`),U_.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new Z(parseFilterList(e,`and`)):new Z(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new Z(parseFilterList(e,`or`)):new Z(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return hv.is(t)?new Z(t):new Z(hv.create(t))},cast(e,t){return new Z(Ty.create(parseReferenceExpression(e),parseDataTypeExpression(t)))}});return t.fn=createFunctionModule(),t.eb=t,t}function expressionBuilder(e){return createExpressionBuilder()}function parseExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function parseAliasedExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function isExpressionOrFactory(e){return isExpression(e)||isAliasedExpression(e)||isFunction(e)}var DynamicTableBuilder=class{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new AliasedDynamicTableBuilder(this.#e,e)}},AliasedDynamicTableBuilder=class{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,t){this.#e=e,this.#t=t}toOperationNode(){return B_.create(parseTable(this.#e),V.create(this.#t))}};function isAliasedDynamicTableBuilder(e){return isObject(e)&&isOperationNodeSource(e)&&isString(e.table)&&isString(e.alias)}function parseTableExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseTableExpression(e)):[parseTableExpression(e)]}function parseTableExpression(e){return isString(e)?parseAliasedTable(e):isAliasedDynamicTableBuilder(e)?e.toOperationNode():parseAliasedExpression(e)}function parseAliasedTable(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$1);return B_.create(parseTable(n),V.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return V_.createWithSchema(t,n)}return V_.create(e)}function trim$1(e){return e.trim()}const Ey=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),$=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:U.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})}}),Dy=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:U.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Oy=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:U.create(e),renameTo:U.create(t)})}}),ky=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?V.create(t):void 0})}}),Ay=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(Ay);const jy=freeze({is(e){return e.kind===`ReferencesNode`},create(e,t){return freeze({kind:`ReferencesNode`,table:e,columns:freeze([...t])})},cloneWithOnDelete(e,t){return freeze({...e,onDelete:t})},cloneWithOnUpdate(e,t){return freeze({...e,onUpdate:t})}});function isOnModifyForeignAction(e){return isString(e)&&Ay[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():G.createImmediate(e)}const My=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})}}),Ny=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 Py=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||iv.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder($.cloneWith(this.#e,{references:jy.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($.cloneWith(this.#e,{references:jy.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($.cloneWith(this.#e,{references:jy.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{defaultTo:Ny.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{check:ky.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{generated:My.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{generated:My.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{generated:My.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder($.cloneWith(this.#e,{generated:My.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder($.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder($.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder($.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Fy=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),Iy=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:jy.create(t,n),name:r?V.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var Ly=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(Iy.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(Iy.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(Iy.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(Iy.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(Iy.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(Iy.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Ry=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),zy=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(U.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?V.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),By=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:V.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Vy=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:U.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(Vy.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(Vy.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(Vy.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(Vy.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(Vy.create(this.#e,`dropNotNull`,!0))}$call(e){return e(this)}},AlteredColumnBuilder=class{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}},AlterTableExecutor=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Hy=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(B.cloneWithTableProps(this.#e.node,{addConstraint:Ry.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)}},Uy=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{dropConstraint:By.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{dropConstraint:By.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{dropConstraint:By.cloneWith(this.#e.node.dropConstraint,{modifier:`restrict`})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Wy=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(U.create)),name:t?V.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),Gy=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:V.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var Ky=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addIndex:Gy.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addIndex:Gy.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addIndex:Gy.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addIndex:Gy.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addIndex:Gy.cloneWith(this.#e.node.addIndex,{using:W.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)}},qy=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(zy.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(zy.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(zy.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(zy.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(zy.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},Jy=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(Wy.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(Wy.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(Wy.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(Wy.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},CheckConstraintBuilder=class{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}};const Yy=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:V.create(e),newName:V.create(t)})}});var Xy=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Dy.cloneWith(this.#e.node,{ifExists:!0})})}toOperationNode(){return this.#e.node}},AlterTableBuilder=class{#e;constructor(e){this.#e=freeze(e)}renameTo(e){return new AlterTableExecutor({...this.#e,node:B.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:B.cloneWithTableProps(this.#e.node,{setSchema:V.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new Zy({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new Xy({node:Dy.create(e)}));return new Zy({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new Zy({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,Oy.create(e,t))})}addColumn(e,t,n=noop){let r=n(new Py($.create(e,parseDataTypeExpression(t))));return new Zy({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,Ey.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new Py($.create(e,parseDataTypeExpression(t))));return new Zy({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,Fy.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new qy(zy.create(t.map(e=>isString(e)?U.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addConstraint:Ry.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(ky.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addConstraint:Ry.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Ly(Iy.create(t.map(U.create),parseTable(n),r.map(U.create),e)));return new Hy({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new Jy(Wy.create(t,e)));return new AlterTableExecutor({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addConstraint:Ry.create(r.toOperationNode())})})}dropConstraint(e){return new Uy({...this.#e,node:B.cloneWithTableProps(this.#e.node,{dropConstraint:By.create(e)})})}renameConstraint(e,t){return new Uy({...this.#e,node:B.cloneWithTableProps(this.#e.node,{renameConstraint:Yy.create(e,t)})})}addIndex(e){return new Ky({...this.#e,node:B.cloneWithTableProps(this.#e.node,{addIndex:Gy.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:B.cloneWithTableProps(this.#e.node,{dropIndex:L_.create(e)})})}$call(e){return e(this)}},Zy=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new Xy({node:Dy.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,Oy.create(e,t))})}addColumn(e,t,n=noop){let r=n(new Py($.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,Ey.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new Py($.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:B.cloneWithColumnAlteration(this.#e.node,Fy.create(r.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},ImmediateValueTransformer=class extends OperationNodeTransformer{transformPrimitiveValueList(e){return mv.create(e.values.map(G.createImmediate))}transformValue(e){return G.createImmediate(e.value)}},Qy=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:N_.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:N_.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:N_.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:N_.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:N_.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:N_.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:N_.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:N_.cloneWith(this.#e.node,{using:W.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:q.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)}},$y=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:P_.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(F_.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var eb=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(Gy.cloneWith(this.#e,{using:W.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},tb=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:H.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:H.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:H.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new Py($.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:H.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new Jy(Wy.create(t,e)));return new CreateTableBuilder({...this.#e,node:H.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new qy(zy.create(t.map(e=>isString(e)?U.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:H.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new eb(Gy.cloneWithColumns(Gy.create(e),t.map(e=>isString(e)?U.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:H.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(ky.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:H.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Ly(Iy.create(t.map(U.create),parseTable(n),r.map(U.create),e)));return new CreateTableBuilder({...this.#e,node:H.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:H.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:H.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:H.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)}},nb=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:L_.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:L_.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:L_.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)}},rb=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:R_.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:R_.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)}},ib=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:z_.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:z_.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:z_.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const ab=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:I_.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var ImmediateValuePlugin=class{#e=new ImmediateValueTransformer;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}},ob=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:ab.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:ab.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:ab.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:ab.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:ab.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:ab.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const sb=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:I_.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var cb=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:sb.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:sb.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:sb.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const lb=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:mv.create(t.map(G.createImmediate))})}});var ub=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:lb.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const db=freeze({is(e){return e.kind===`DropTypeNode`},create(e){return Array.isArray(e)||(e=[e]),freeze({kind:`DropTypeNode`,name:e[0],additionalNames:e.slice(1)})},cloneWith(e,t){return freeze({...e,...t})}});var fb=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:db.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:db.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 I_.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return I_.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const pb=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:I_.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var mb=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:pb.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:pb.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:pb.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const hb=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),gb=freeze({is(e){return e.kind===`AddValueNode`},create(e){return freeze({kind:`AddValueNode`,value:e})},cloneWith(e,t){return freeze({...e,...t})}});var QueryFinalizer=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){return await this.#e.executor.executeQuery(this.compile(),e)}},_b,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new _b({...this.#e,node:hb.cloneWith(this.#e.node,{addValue:gb.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 _b({...this.#e,node:hb.cloneWith(this.#e.node,{addValue:gb.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:G.createImmediate(e)})})})}};_b=AlterTypeAddValueBuilder;const vb=freeze({is(e){return e.kind===`RenameValueNode`},create(e,t){return freeze({kind:`RenameValueNode`,oldValue:e,newValue:t})}});var AlterTypeBuilder=class{#e;constructor(e){this.#e=freeze(e)}addValue(e){return new AlterTypeAddValueBuilder({...this.#e,node:hb.cloneWith(this.#e.node,{addValue:gb.create(G.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:hb.cloneWith(this.#e.node,{renameTo:V.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:hb.cloneWith(this.#e.node,{renameValue:vb.create(G.createImmediate(e),G.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:hb.cloneWith(this.#e.node,{setSchema:V.create(e)})})}},yb=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new tb({queryId:createQueryId(),executor:this.#e,node:H.create(parseTable(e))})}dropTable(e){return new ib({queryId:createQueryId(),executor:this.#e,node:z_.create(parseTable(e))})}createIndex(e){return new Qy({queryId:createQueryId(),executor:this.#e,node:N_.create(e)})}dropIndex(e){return new nb({queryId:createQueryId(),executor:this.#e,node:L_.create(e)})}createSchema(e){return new $y({queryId:createQueryId(),executor:this.#e,node:P_.create(e)})}dropSchema(e){return new rb({queryId:createQueryId(),executor:this.#e,node:R_.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:B.create(parseTable(e))})}createView(e){return new ob({queryId:createQueryId(),executor:this.#e,node:ab.create(e)})}refreshMaterializedView(e){return new mb({queryId:createQueryId(),executor:this.#e,node:pb.create(e)})}dropView(e){return new cb({queryId:createQueryId(),executor:this.#e,node:sb.create(e)})}createType(e){return new ub({queryId:createQueryId(),executor:this.#e,node:lb.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:hb.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new fb({queryId:createQueryId(),executor:this.#e,node:db.create(parseSchemableIdentifierArray(e))})}withPlugin(e){return new SchemaModule(this.#e.withPlugin(e))}withoutPlugins(){return new SchemaModule(this.#e.withoutPlugins())}withSchema(e){return new SchemaModule(this.#e.withPluginAtFront(new WithSchemaPlugin(e)))}},DynamicModule=class{ref(e){return new DynamicReferenceBuilder(e)}table(e){return new DynamicTableBuilder(e)}},DefaultConnectionProvider=class{#e;constructor(e){this.#e=e}async provideConnection(e,t){let n=await this.#e.acquireConnection(t);try{return await e(n)}finally{await this.#e.releaseConnection(n,t)}}},bb=class DefaultQueryExecutor extends QueryExecutorBase{#e;#t;#n;constructor(e,t,n,r=[]){super(r),this.#e=e,this.#t=t,this.#n=n}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return this.#n.provideConnection(e,t)}withPlugins(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,...e])}withPlugin(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,e])}withPluginAtFront(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[e,...this.plugins])}withConnectionProvider(e){return new DefaultQueryExecutor(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[])}};function performanceNow(){return typeof performance<`u`&&isFunction(performance.now)?performance.now():Date.now()}var ConnectionMutex=class{#e;#t;async obtainLock(){for(;this.#e;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}releaseLock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},RuntimeDriver=class{#e;#t;#n;#r;#i;#a=/* @__PURE__ */ new WeakSet;#o;constructor(e,t,n){this.#e=e,this.#r=!1,this.#t=n,t.supportsMultipleConnections===!1&&(this.#o=new ConnectionMutex)}async init(e){if(this.#i)throw Error(`driver has already been destroyed`);this.#n??=this.#e.init(e).then(()=>{this.#r=!0}).catch(e=>{throw this.#n=void 0,e}),await waitOrAbort(this.#n,e?.signal,`init`)}async acquireConnection(e){if(this.#i)throw Error(`driver has already been destroyed`);if(this.#r||await this.init(e),this.#o){let t=this.#o.obtainLock();await waitOrAbort(t,e?.signal,`acquireConnection:mutex`,()=>t.then(()=>this.#o?.releaseLock()))}let t=this.#e.acquireConnection(e),n=await waitOrAbort(t,e?.signal,`acquireConnection:acquire`,()=>t?.then(e=>this.releaseConnection(e).catch(printBackgroundFail(`driver.releaseConnection`))).catch(printBackgroundFail(`driver.acquireConnection`)));return this.#a.has(n)||(this.#s()&&this.#c(n),this.#a.add(n)),n}async releaseConnection(e,t){await this.#e.releaseConnection(e,t),this.#o?.releaseLock()}async beginTransaction(e,t){return await this.#e.beginTransaction(e,t)}async commitTransaction(e){return await this.#e.commitTransaction(e)}async rollbackTransaction(e){return await this.#e.rollbackTransaction(e)}async savepoint(e,t,n){if(this.#e.savepoint)return await this.#e.savepoint(e,t,n);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(e,t,n){if(this.#e.rollbackToSavepoint)return await this.#e.rollbackToSavepoint(e,t,n);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(e,t,n){if(this.#e.releaseSavepoint)return await this.#e.releaseSavepoint(e,t,n);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(e){this.#n&&(await waitOrAbort(this.#n,e?.signal,`destroy:initPromise`),this.#i??=this.#e.destroy(e).catch(e=>{throw this.#i=void 0,e}),await waitOrAbort(this.#i,e?.signal,`destroy`))}#s(){return this.#t.isLevelEnabled(`query`)||this.#t.isLevelEnabled(`error`)}#c(e){let t=e.executeQuery,n=e.streamQuery,r=this;e.executeQuery=async(n,i)=>{let a,s=performanceNow();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,s),e}finally{a||await r.#u(n,s)}},e.streamQuery=async function*(t,i,a){let s,c=performanceNow();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw s=e,await r.#l(e,t,c),e}finally{s||await r.#u(t,c,!0)}}}async#l(e,t,n){await this.#t.error(()=>({level:`error`,error:e,query:t,queryDurationMillis:this.#d(n)}))}async#u(e,t,n=!1){await this.#t.query(()=>({level:`query`,isStream:n,query:e,queryDurationMillis:this.#d(t)}))}#d(e){return performanceNow()-e}};const ignoreError=()=>{};var SingleConnectionProvider=class{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch(ignoreError);return this.#t=this.#n(e).finally(()=>{this.#t=void 0}),this.#t}async#n(e){return await e(this.#e)}};const xb=[`read only`,`read write`],Sb=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!xb.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Sb.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}freeze([`query`,`error`]);var Log=class{#e;#t;constructor(e){isFunction(e)?(this.#t=e,this.#e=freeze({query:!0,error:!0})):(this.#t=defaultLogger,this.#e=freeze({query:e.includes(`query`),error:e.includes(`error`)}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}};function defaultLogger(e){if(e.level===`query`){let t=`kysely:query:${e.isStream?`stream:`:``}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else e.level===`error`&&(e.error instanceof Error?console.error(`kysely:error: ${e.error.stack??e.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`))}function isCompilable(e){return isObject(e)&&isFunction(e.compile)}Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`);var Cb=class Kysely extends oy{#e;constructor(e){let t,n;if(isKyselyProps(e))t={executor:e.executor},n={...e};else{let r=e.dialect,i=r.createDriver(),a=r.createQueryCompiler(),s=r.createAdapter(),c=new RuntimeDriver(i,s,new Log(e.log??[])),l=new bb(a,s,new DefaultConnectionProvider(c),e.plugins??[]);t={executor:l},n={config:e,executor:l,dialect:r,driver:c}}super(t),this.#e=freeze(n)}get schema(){return new yb(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:_y.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Tb({...this.#e})}startTransaction(){return new Eb({...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()}},wb=class Transaction extends Cb{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw Error(`calling the transaction method for a Transaction is not supported`)}startTransaction(){throw Error(`calling the controlled transaction method for a Transaction is not supported`)}connection(){throw Error(`calling the connection method for a Transaction is not supported`)}destroy(){throw Error(`calling the destroy method for a Transaction is not supported`)}withPlugin(e){return new Transaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Transaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Transaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new Transaction({...this.#e})}$extendTables(){return new Transaction({...this.#e})}$omitTables(){return new Transaction({...this.#e})}$pickTables(){return new Transaction({...this.#e})}};function isKyselyProps(e){return isObject(e)&&isObject(e.config)&&isObject(e.driver)&&isObject(e.executor)&&isObject(e.dialect)}var ConnectionBuilder=class{#e;constructor(e){this.#e=freeze(e)}async execute(e,t){return this.#e.executor.provideConnection(async t=>{let n=this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t));return await e(new Cb({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Tb=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 Ob(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),s=new wb({...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}})}},Eb=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 Db({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Db=class ControlledTransaction extends wb{#e;#t;constructor(e){e={...e,executor:new Ob(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(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(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(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(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(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=class{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}};function assertNotCommittedOrRolledBack(e){if(e.isCommitted)throw Error(`Transaction is already committed`);if(e.isRolledBack)throw Error(`Transaction is already rolled back`)}var Ob=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)}},kb=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?ry:e.getExecutor();return this.#e.plugins===void 0?t:t.withPlugins(this.#e.plugins)}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}};function createRawBuilder(e){return new kb(e)}var AliasedRawBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return B_.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():V.create(this.#t))}};const Ab=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:W.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:W.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:W.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:W.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:W.create(t,e.map(V.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:W.createWithChild(G.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:W.createWithSql(e)})},join(e,t=Ab`, `){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:W.createWithChildren(n)})}});function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var OperationNodeVisitor=class{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=freeze({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}};const jb=/'/g,Mb=/['"]/g;var DefaultQueryCompiler=class extends OperationNodeVisitor{#e=``;#t=[];get numParameters(){return this.#t.length}compileQuery(e,t){return this.#e=``,this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),freeze({query:e,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){let t=this.parentNode!==void 0&&!hv.is(this.parentNode)&&!K.is(this.parentNode)&&!H.is(this.parentNode)&&!ab.is(this.parentNode)&&!ly.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&&!hv.is(this.parentNode)&&!W.is(this.parentNode)&&!kv.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&&!hv.is(this.parentNode)&&!W.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(Fb[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&&!hv.is(this.parentNode)&&!W.is(this.parentNode)&&!kv.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(Nb[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 rv.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&&H.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(jb,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(Mb,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?Pb[e.modifier]-Pb[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const Nb=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),Pb=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Fb=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`}),Ib=freeze({raw(e,t=[]){return freeze({sql:e,query:W.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}});var DialectAdapterBase=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function parseSavepointCommand(e,t){return W.createWithChildren([W.createWithSql(`${e} `),V.create(t)])}var SqliteDriver=class{#e;#t;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#t=isFunction(this.#e.database)?await this.#e.database(e):this.#e.database,this.#n=new SqliteConnection(this.#t),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#n,e)}async acquireConnection(){return this.#n}async beginTransaction(e){await e.executeQuery(Ib.raw(`begin`))}async commitTransaction(e){await e.executeQuery(Ib.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Ib.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(!J.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let s=a.iterate(r);for(let e of s)yield{rows:[e]}}};const Lb=/"/g,Rb=/[\\'"]/g;var SqliteQueryCompiler=class extends DefaultQueryCompiler{visitOrAction(e){this.append(`or `),this.append(e.action)}getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}sanitizeIdentifier(e){return e.replace(Lb,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(Rb,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const zb=`kysely_migration`,Bb=`kysely_migration_lock`;freeze({__noMigrations__:!0});var SqliteIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#n(e)}#t(e,t){let n=e.selectFrom(`sqlite_master`).where(`type`,`in`,[`table`,`view`]).where(`name`,`not like`,`sqlite_%`).select([`name`,`sql`,`type`]).orderBy(`name`);return t.withInternalKyselyTables||(n=n.where(`name`,`!=`,zb).where(`name`,`!=`,Bb)),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`,Ab`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject(e)&&isString(e.stack)}const Vb=Symbol();var PostgresDriver=class{#e;#t=/* @__PURE__ */ new WeakMap;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#n=isFunction(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#n.connect();if(!this.#n)throw t.release(),Error(`driver has already been destroyed`);let n=this.#t.get(t);return n||(n=new PostgresConnection(t,{controlClient:this.#e.controlClient||this.#n.Client,cursor:this.#e.cursor??null,poolOptions:this.#n.options}),this.#t.set(t,n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){let n=`begin`;(t.isolationLevel||t.accessMode)&&(n=`start transaction`,t.isolationLevel&&(n+=` isolation level ${t.isolationLevel}`),t.accessMode&&(n+=` ${t.accessMode}`)),await e.executeQuery(Ib.raw(n))}async commitTransaction(e){await e.executeQuery(Ib.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Ib.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[Vb]()}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}}[Vb](){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(Ib.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,Ab`col_description(a.attrelid, a.attnum)`.as(`column_description`),Ab`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(Ab`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`,`!=`,zb).where(`c.relname`,`!=`,Bb));let n=await t.execute();return this.#t(n)}#t(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=n.get(r.schema);e||(e=/* @__PURE__ */ new Map,n.set(r.schema,e));let i=e.get(r.table);i||(i=freeze({columns:[],isForeign:r.table_type===`f`,isView:r.table_type===`v`,name:r.table,schema:r.schema}),e.set(r.table,i),t.push(i)),i.columns.push(freeze({comment:r.column_description??void 0,dataType:r.type,dataTypeSchema:r.type_schema,hasDefaultValue:r.has_default,isAutoIncrementing:r.auto_incrementing!==null,isNullable:!r.not_null,name:r.column}))}return t}};const Hb=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(Hb,`""`)}};const Ub=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await Ab`
with set_timeout as (
select set_config('lock_timeout', '${Ab.lit(36e5)}', true) as config_val
)
select pg_advisory_lock(${Ab.lit(Ub)})
from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await Ab`select pg_advisory_unlock(${Ab.lit(Ub)})`.execute(e)}},PostgresDialect=class{#e;constructor(e){this.#e=e}createDriver(){return new PostgresDriver(this.#e)}createQueryCompiler(){return new PostgresQueryCompiler}createAdapter(){return new PostgresAdapter}createIntrospector(e){return new PostgresIntrospector(e)}};const Wb=/^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,Gb=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],Kb=Gb[Gb.length-1];`${Gb.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<Gb.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=Wb.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>Kb.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(Wb.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(Gb)};
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)`}renderProcessNodeVersionCheck();const templateFragments=(e,t)=>e,qb=templateFragments`(SELECT value FROM json_each(${0}))`,Jb=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!W.is(e)||e.sqlFragments!==qb||e.parameters.length!==1)return;let t=e.parameters[0];for(;W.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!G.is(t)||t.immediate||typeof t.value!=`string`)return;let n;try{n=JSON.parse(t.value)}catch{return}if(Array.isArray(n)&&n.every(e=>typeof e==`string`))return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(rv.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===qb;!t&&e.sqlFragments!==Jb?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}};O(),ls(),Vf(),mc();const Yb=parseNodeReleaseVersion(process.versions.node),Xb=!process.versions.bun&&(Yb?.major===24&&isNodeVersionAtLeast(Yb,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(Yb,{major:26,minor:6,patch:0})),Zb=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),Qb=/* @__PURE__ */ new WeakMap,$b=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(isPostgresSqlConnection(e)){let t=Qb.get(e);return t||(t=new Cb({dialect:$b}),Qb.set(e,t)),t}let t=us.get(e);if(t)return t;let n=new Cb({dialect:Zb});return us.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{ds.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&&J.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(J.is(t.query)||i.columns().length>0){if(Xb)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 K.is(t.query)&&s>0?{...l,insertId:BigInt(c)}:l})}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}}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),Ab`${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]}j();const{busyTimeoutByDatabase:ex,trackedDatabases:tx}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}));function rememberSqliteBusyTimeout(e,t){tx.has(e)||(tx.add(e),registerNodeSqliteDisposeCallback(e,()=>ex.delete(e))),ex.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 setSqliteBusyTimeout(e,t){let n=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`);ex.get(e)!==n&&(e.exec(`PRAGMA busy_timeout = ${n}`),rememberSqliteBusyTimeout(e,n))}const nx={name:`database.engine.schema`,schemaDependent:!0};Rp(),Rp(),ls(),Rp(),$f();function getPostgresPhysicalFacts(e,t){if(isPostgresSqlConnection(e)&&e.isTransaction&&!t?.refresh){let t=Zf.get(e);if(t?.schema.store===`agent`)return e.isOpen&&e.anchor.isOpen?t.schema:void 0}return mp(e,nx,t)}j(),Rf();const rx=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap);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(!T&&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)}}}k(),Rp();const ix={name:`sqlite-schema`,writer:`connection`,lifetime:`process`,schemaDependent:!0,read:e=>isRecord(e)?e:void 0},ax={name:`sqlite-text-encoding`,writer:`connection`,lifetime:`process`,read:e=>typeof e==`string`?e:void 0};function readSqliteTextEncoding(e){let t=mp(e,ax);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=mp(e,ax),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:S(),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,ax,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}Rp();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=hp(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)}Jd();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}`}))]}}ls(),Rp(),Yf(),Vf(),Wf(),$f();function invalidateSqliteSchemaFacts(e){hp(e),invalidateSchemaFacts(e,!0)}function invalidateSchemaFacts(e,t,n=`main`,r=n!==`temp`){let i=Qf.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 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!==hp(e))t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.transactionalFacts=!0;else if(observeSchemaLifetime(e,t,void 0),!t.facts&&!t.transactionalSchema){let n=mp(e,ix);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=hp(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,_=c&&!n.temporaryTableSchemaChange||h&&t.transactionalSchema,v=l||g?`main`:h?t.transactionalTempSchema&&!t.transactionalSchema?`temp`:`rollback`:n.temporaryTableSchemaChange?`temp`:`local`;h&&discardSqliteDatabaseTransactionAdmissions(e),(c||h)&&invalidateSchemaFacts(e,!1,v,_),(s||n.temporaryTableSchemaChange||a?.kind===`ROLLBACK`)&&(t.mutationRevision+=1),i!==`bind`&&f&&!a&&!t.transactionCatalogBound&&(t.transactionRead=!0);let y=c||s||a!==void 0,b=n.temporaryWriteTables?.every(e=>t.isolatedTempTables.has(e));(s&&!b||l)&&beginSqliteDatabaseWrite(e,l||t.nativeDepth>0),y&&(t.mutationDepth+=1),t.nativeDepth+=1;let x=beginSqliteDatabaseAdmissionOperation(e),S=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),x(),--t.nativeDepth,y&&--t.mutationDepth,!e.isOpen)return;(c||h)&&(h&&discardSqliteDatabaseTransactionAdmissions(e),invalidateSchemaFacts(e,!1,v,_));let s=n&&f&&a?.outerRollback===!0&&!e.isTransaction&&!l&&t.schemaMutationRevision===S;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 trackSqliteSchema(e,t,n=!0){if(!Qf.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};Qf.set(e,r),trackSchemaChanges(e,r,t,n);let i=hp(e,{existingOnly:!0}),a=mp(e,ix,{existingOnly:!0});a&&(r.admitted=!0,r.facts={...a,revision:r.revision},r.processRevision=i)}}function getAdmittedSqliteSchemaFacts(e,t){if(isPostgresSqlConnection(e))return;let n=Qf.get(e);if(!n?.admitted||n.authorizerActive)return;let r=getSqlitePinnedReadSnapshot(e),i=e.isTransaction&&(n.transactionRead||n.transactionCatalogBound)&&n.processRevision!==hp(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:mp(e,ix);if(c)return t?.(c.userVersion),n.facts={...c,revision:n.revision},n.facts;let l=hp(e);n.facts=captureTrackedSqliteSchemaFacts(e,n,t),n.iteratorFacts||=n.unmanagedSnapshots.size>0,n.qualifiedSnapshot=r,n.transactionCatalogBound||=e.isTransaction,s||publishSqliteDatabaseAdmission(e,ix,n.facts,{schemaRevision:l})}return n.facts}mf(),Rp(),Sf(),mc();function resolveSqliteFilesystemPath(e){return process.platform===`win32`?n.toNamespacedPath(n.resolve(e)):e}function resolveNodeSqliteLocation(e){return e===``||e===`:memory:`||e.startsWith(`file:`)?e:resolveSqliteFilesystemPath(e)}function openNodeSqliteDatabase(e,t,n){let r=requireNodeSqlite(),i=resolveNodeSqliteLocation(e),a=t?.open===!1?void 0:op(i,{create:t?.readOnly!==!0});if(t?.open!==!1&&n!==void 0&&a!==n)throw Error(`SQLite staging database changed before native open`);let s=new r.DatabaseSync(i,t??{});if(s.isOpen)try{bindSqliteDatabaseAdmission(s,a)}catch(e){throw s.close(),e}return s.open=()=>{let e=op(i,{create:t?.readOnly!==!0});if(n!==void 0&&e!==n)throw Error(`SQLite staging database changed before native open`);r.DatabaseSync.prototype.open.call(s);try{bindSqliteDatabaseAdmission(s,e)}catch(e){throw s.close(),e}},trackSqliteSchema(s,{DatabaseSync:r.DatabaseSync,StatementSync:r.StatementSync},t?.readOnly!==!0),s.isOpen&&t?.timeout!==void 0&&rememberSqliteBusyTimeout(s,Math.max(0,t.timeout)),getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources||registerNodeSqliteDisposeCallback(s,()=>{}),registerSqliteReaderConnection(s),s}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};ls(),Rp(),Vf();function getStateSchemaFacts(e){return isPostgresSqlConnection(e)?getPostgresPhysicalFacts(e):getAdmittedSqliteSchemaFacts(e)}const ox={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}}},sx=/* @__PURE__ */ new WeakMap;function rememberConnectionVersion(e,t){let n=sx.get(e),install=t=>{t?sx.set(e,t):sx.delete(e)};stageSqliteTransactionState(e,{stage:()=>install(t),commit:()=>{},rollback:()=>install(n)})||install(t)}function schemaVersionKey(e){return{name:`state.schema-version:${e}`,read:ox.read}}function getStateSchemaVersionAdmission(e){let t=getStateSchemaFacts(e);if(!t)return;let n=sx.get(e);if(n?.schema===t)return n.facts;let r=mp(e,schemaVersionKey(t.admissionId)),i=r?void 0:mp(e,ix);if(!r&&!isPostgresSqlConnection(e)&&i?.admissionId!==t.admissionId)return;let a=r??mp(e,ox);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=mp(e,ix);(isPostgresSqlConnection(e)||r?.admissionId===n.admissionId)&&(publishSqliteDatabaseAdmission(e,schemaVersionKey(n.admissionId),t),publishSqliteDatabaseAdmission(e,ox,t))}ls(),Rf();function tableExists(e,t){if(isPostgresSqlConnection(e)){let n=getPostgresPhysicalFacts(e);return n?n.catalog.some(e=>e.table===t&&e.kind===`table`):e.prepare(`SELECT 1 AS present FROM pg_catalog.pg_class
WHERE relnamespace = current_schema()::regnamespace AND relname = ? AND relkind IN ('r', 'p')`).get(t)?.present===1}let n=getAdmittedSqliteSchemaFacts(e);return n?n.tables.has(t):executeWithCachedStatement(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}var OpenClawStateDatabaseSchemaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(e,`OpenClaw state database schema migration required (${e}) at ${t}; run openclaw doctor --fix to migrate it.`),this.kind=e,this.pathname=t,this.name=`OpenClawStateDatabaseSchemaMigrationRequiredError`}};function normalizeOpenClawStateSchemaReadError(e,t){if(e instanceof Error&&e.message.startsWith(`malformed database schema (idx_skill_workshop_collection_reviews_workspace_time)`)){let n=new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-workshop-review-index`,t);return n.cause=e,n}return e}ls();const cx=`state.schema.contentVersion`;var PostgresSchemaAdmissionUnavailableError=class extends Error{};const lx=createSqliteQueryCache(e=>prepareSqliteQuerySync(e,()=>getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,cx)));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 lx(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 ${cx}.`,{cause:e})}if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${cx}.`);return 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>40?a:readStateSchemaContentVersion(e,a,r,a));if(s>40)throw createNewerSqliteSchemaVersionError(`OpenClaw state database`,t,s,40,readSqliteWriterAppVersion(e),i);return a}catch(e){throw normalizeOpenClawStateSchemaReadError(e,t)}}function readNativeHookRelayBridgeRow(e,t){return executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`native_hook_relay_bridges`).selectAll().where(`relay_id`,`=`,t))}function readNativeHookRelayBridgeRecordRow(e){if(!(!e||typeof e.relay_id!=`string`||e.relay_id.length===0||!Number.isSafeInteger(e.pid)||e.hostname!==`127.0.0.1`||!Number.isSafeInteger(e.port)||Number(e.port)<=0||Number(e.port)>65535||typeof e.token!=`string`||e.token.length===0||!Number.isSafeInteger(e.expires_at_ms)))return{relayId:e.relay_id,pid:Number(e.pid),hostname:e.hostname,port:Number(e.port),token:e.token,expiresAtMs:Number(e.expires_at_ms)}}function readNativeHookRelayClientRecord(e,t){let n=openNodeSqliteDatabase(e.stateDbPath,{readOnly:!0});try{return setSqliteBusyTimeout(n,t),assertSupportedStateSchemaVersion(n,e.stateDbPath),readNativeHookRelayBridgeRecordRow(readNativeHookRelayBridgeRow(n,e.relayId))}finally{clearNodeSqliteKyselyCacheForDatabase(n),n.close()}}O(),serveWorkerTasks(e=>{try{return{ok:!0,record:readNativeHookRelayClientRecord(e,5e3)}}catch(e){let t=toStringifiedError(e);return{ok:!1,error:serializeNativeErrorResponse(t),newerSchema:t instanceof SqliteSchemaVersionError}}});export{};