UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,749 lines • 681 kB
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 o}from"node:path";import{fileURLToPath as s,pathToFileURL as c}from"node:url";import l,{existsSync as u,fstatSync as d,mkdirSync as f,readFileSync as p,readdirSync as m,default as h}from"node:fs";import{createHash as g,randomUUID as _}from"node:crypto";import{appendRegularFile as v,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{AsyncLocalStorage as y,AsyncResource as ae}from"node:async_hooks";import{hasNodeErrorCode as b,isPathInside as oe,normalizeWindowsPathForComparison as se}from"@openclaw/fs-safe/path";import x,{mkdtemp as ce,realpath as le,rm as ue,stat as de,default as fe}from"node:fs/promises";import S,{tmpdir as pe}from"node:os";import{channel as me}from"node:diagnostics_channel";import{performance as he}from"node:perf_hooks";import{MessageChannel as ge,MessagePort as _e,Worker as ve,getEnvironmentData as ye,isMainThread as C,parentPort as be,receiveMessageOnPort as xe,setEnvironmentData as Se,threadId as w,workerData as Ce}from"node:worker_threads";import{isUtf8 as we}from"node:buffer";import{spawnSync as Te}from"node:child_process";import{isPromise as Ee}from"node:util/types";import{isDeepStrictEqual as De,toUSVString as Oe,types as ke}from"node:util";import{Session as Ae}from"node:inspector/promises";import*as je from"node:v8";import{GCProfiler as Me,getHeapSpaceStatistics as Ne,getHeapStatistics as Pe,setFlagsFromString as Fe}from"node:v8";import{replaceFileAtomic as Ie}from"@openclaw/fs-safe/atomic";import{setImmediate as Le,setTimeout as Re}from"node:timers/promises";import{Chalk as ze}from"chalk";import{Logger as Be}from"tslog";import{readRootJsonObjectSync as Ve}from"@openclaw/fs-safe/json";import{parse as He}from"semver";var Ue=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)Ue(n,r,{get:e[r],enumerable:!0});return t||Ue(n,Symbol.toStringTag,{value:`Module`}),n};function isProviderAuthPersistenceError(e){try{return We in e&&e[We]===!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(`
`),o=a<0?r:r.slice(0,a);return o===t?i+r.slice(o.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 toStringifiedError(e){return e instanceof Error?e:Error(String(e))}function extractErrorCode(e){if(!e||typeof e!=`object`)return;let t=readProperty(e,`code`);return typeof t==`string`||typeof t==`number`?String(t):void 0}function collectErrorGraphCandidates(e,t){if(e==null)return[];let n=[e],r=(/* @__PURE__ */ new Set()).add(e);for(let e of n)if(e&&typeof e==`object`&&t)for(let i of t(e))i!=null&&!r.has(i)&&(r.add(i),n.push(i));return n}function collectNestedErrorCandidates(e){return collectErrorGraphCandidates(e,e=>{let t=[readProperty(e,`cause`),readProperty(e,`reason`),readProperty(e,`original`),readProperty(e,`error`),readProperty(e,`suppressed`),readProperty(e,`data`)],n=readProperty(e,`errors`);return Array.isArray(n)&&t.push(...n),t})}var We,Ge=__esmMin((()=>{We=Symbol.for(`openclaw.provider-auth-persistence-error`)}));Ge();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 Ke=/^(?<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=Ke.exec(t)?.groups;if(!n)return null;let r=Number(n.year),i=Number(n.month),a=Number(n.patch),o=n.prerelease===void 0?void 0:Number(n.prerelease),s=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||o!==void 0&&!Number.isSafeInteger(o)||s!==void 0&&!Number.isSafeInteger(s))return null;let c=n.channel===`alpha`?`alpha`:n.channel===`beta`?`beta`:`stable`;return{version:t,baseVersion:`${r}.${i}.${a}`,channel:c,year:r,month:i,patch:a,alphaNumber:c===`alpha`?o:void 0,betaNumber:c===`beta`?o:void 0,...s===void 0?{}:{correctionNumber:s}}}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 T=__esmMin((()=>{}));const qe=/* @__PURE__ */ `sandbox_persistent_execs.user_profile_identities.user_background_images.local_workspace_projections.local_workspace_manifest_nodes.local_workspace_tree_packs.local_workspace_source_path_sets.update_runs.session_repository_workspaces.github_repository_publication_requests.github_publication_session_lifecycles.skill_library_entries.skill_library_revisions.skill_library_events.skill_library_uploads.github_personal_publication_requests.cron_job_runtime_authorities.cron_run_trigger_state_retirements.execution_identity_contexts.mcp_oauth_pending_authorizations.node_worker_launch_containers.node_worker_launch_boots.node_worker_launch_cleanup.node_worker_launch_process_scopes.node_worker_launches.node_worker_prepared_workspaces.node_worker_turns.operator_approval_execution_identities.operator_approval_standing_grants.operator_approval_standing_grant_generations.web_push_approval_deliveries.execution_decision_facts.execution_owner_lifecycle_bindings.outbound_message_execution_bindings.outbound_message_progress`.split(`.`),Je=[`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`];[...qe],[...Je];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 Ye=__esmMin((()=>{}));function normalizeUrlQueryParamName(e){let t=e.replace(Ze,``);for(let e=0;e<=$e;e+=1){let e;try{e=decodeURIComponent(t).replace(Ze,``)}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||Xe.has(t.value)||Qe.test(t.value)}var Xe,Ze,Qe,$e,et=__esmMin((()=>{Ye(),Xe=/* @__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(`.`)),Ze=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,Qe=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u,$e=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=ut.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(),o=a===r?r:a.startsWith(i)?i:null;if(!o)return!1;let s=t+o.length,c=skipSerializedBackslashes(e,s);if(e[c]===`"`||e[c]===`'`)c+=1;else if(c>s)return!1;return c=skipHorizontalWhitespace(e,c),e[c]===`:`||e[c]===`=`}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 o=(n.awsScope?dt:ut).exec(e.slice(t));return o?t+o[0].length:null}function findStructuredAuthParamRanges(e){let t=[];for(let n of e.matchAll(lt)){let r=(n[2]??``).toLowerCase(),i=(n.index??0)+n[0].length,a=i,o=i,s=readAuthParamName(e,i),c=s?skipAuthWhitespace(e,s.end):void 0;if(!s||c===void 0||e[c]!==`=`||e[c+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}o=Math.max(o,findAuthFieldEnd(e,i));break}o=n;let a=skipAuthWhitespace(e,n);if(e[a]!==`,`){if(!isAuthFieldEnd(e[a])){let t=findNextAuthParamStart(e,a);if(t!==null){i=t;continue}o=Math.max(o,findAuthFieldEnd(e,a))}break}let s=findNextAuthParamStart(e,a+1);if(s===null)break;i=s}o>a&&t.push({start:a,end:o})}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,nt,rt,it,at,ot,st,ct,E,lt,ut,dt,ft=__esmMin((()=>{tt="[A-Za-z0-9!#$%&'*+.^_`|~-]+",nt=String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`,rt=String.raw`\\{1,64}t`,it=String.raw`(?:[ \t]+|${rt})`,at=String.raw`(?:[ \t]*\r?\n${it}|[ \t]*\\{1,64}r\\{1,64}n${it}|[ \t]*\\{1,64}n${it}|[ \t]*${rt}[ \t]*|[ \t]*)`,ot=String.raw`(?:[ \t]*\r?\n${it}|[ \t]*\\{1,64}r\\{1,64}n${it}|[ \t]*\\{1,64}n${it}|[ \t]*${rt}[ \t]*|[ \t]+)`,st=String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${rt})|[ \t]*\\{1,64}n(?:[ \t]*|${rt})|[ \t]*${rt}[ \t]*)`,ct=String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`,E=String.raw`(?:\\{1,64}["']|["']|)`,String.raw`${ct}(?:x-goog-api-key|api-key|apikey|x-api-token|x-access-token)${E}[ \t]*[:=]${at}${E}([^\s\\"',;]+)`,lt=new RegExp(String.raw`${ct}(?:Proxy-)?Authorization${E}[ \t]*[:=]${at}${E}(${tt})${ot}`,`giu`),ut=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u,dt=/^[A-Za-z0-9!#$%&'*+.^_`|~:/-]+/u})),pt=__esmMin((()=>{})),mt=__esmMin((()=>{})),ht,gt=__esmMin((()=>{ht=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]],RegExp(`[${ht.flatMap(e=>e.map(([e,t])=>`\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join(``)}]`,`u`),(()=>{let e=Math.max(...ht.flatMap(e=>e.map(([,e])=>e))),t=new Uint8Array(e+1);for(let[e,n]of ht.entries())for(let[r,i]of n)t.fill(e+1,r,i+1);return t})()})),_t=__esmMin((()=>{}));function expectDefined(e,t){if(e==null)throw Error(`expected `+t+` to be defined`);return e}var vt=__esmMin((()=>{})),yt=__esmMin((()=>{})),bt=__esmMin((()=>{})),xt,St=__esmMin((()=>{xt=2147e6,Math.floor(xt/1e3)})),Ct=__esmMin((()=>{})),wt=__esmMin((()=>{})),Tt=__esmMin((()=>{})),Et=__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 Dt=__esmMin((()=>{})),Ot=__esmMin((()=>{pt(),mt(),gt(),_t(),Ge(),vt(),yt(),bt(),St(),T(),Ct(),wt(),Ye(),Tt(),Et(),Dt()}));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 kt=__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),o=a;if(e[i]===`,`){i+=1;let t=i;for(;i<e.length&&/\d/.test(e.charAt(i));)i+=1;o=i===t?null:Number.parseInt(e.slice(t,i),10)}return e[i]!==`}`||(i+=1,e[i]===`?`&&(i+=1),o!==null&&o<a)?null:{consumed:i-t,minRepeat:a,maxRepeat:o}}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 o=expectDefined(t[t.length-1],`frames entry at frames.length 1`),s=o.lastToken;if(!s)continue;if(s.containsRepetition||s.hasAmbiguousAlternation&&a.maxRepeat===null)return!0;let c=s.minLength,l=s.maxLength;s.minLength=multiplyLength(s.minLength,a.minRepeat),s.maxLength=a.maxRepeat===null?1/0:multiplyLength(s.maxLength,a.maxRepeat),s.containsRepetition=!0,o.containsRepetition=!0,o.branchMinLength=o.branchMinLength-c+s.minLength,o.branchMaxLength=addLength(Number.isFinite(o.branchMaxLength)&&Number.isFinite(l)?o.branchMaxLength-l:1/0,s.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=jt.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 jt.set(r,a),pruneMapToMaxSize(jt,At),a}var At,jt,Mt=__esmMin((()=>{Ot(),kt(),At=256,jt=/* @__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 Nt=__esmMin((()=>{Mt()}));function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.prototype.toString.call(e)===`[object Object]`}var Pt=__esmMin((()=>{}));function isBlockedObjectKey(e){return Ft.has(e)}var Ft,It=__esmMin((()=>{Ft=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`])}));function getSealedRuntimeJson5(){return Lt?.json5}function getSealedRuntimeSecureTempRoot(){return Lt?.resolveSecureTempRoot}var Lt,Rt=__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 zt=t,t}function loadJson5Parser(){if(zt)return zt;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 zt,Bt=__esmMin((()=>{Rt()}));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 Vt=__esmMin((()=>{})),Ht,Ut=__esmMin((()=>{Ht=`default`}));function parseEnvTemplateSecretRef(e,t=Ht){if(typeof e!=`string`)return null;let n=e.trim(),r=Wt.exec(n)??Gt.exec(n);return r?{source:`env`,provider:t.trim()||`default`,id:expectDefined(r[1],`types.secrets regex capture 1`)}:null}var Wt,Gt,Kt=__esmMin((()=>{Ot(),Ut(),Wt=/^\$\{([A-Z][A-Z0-9_]{0,127})\}$/,Gt=/^\$([A-Z][A-Z0-9_]{0,127})$/}));function renderEnvTemplateToken(e){return e.defaultValue===void 0?`\${${e.name}}`:`\${${e.name}${Jt}${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),o=a.indexOf(Jt),s=o===-1?a:a.slice(0,o),c=o===-1?void 0:a.slice(o+2);!qt.test(s)||c?.includes(`$`)||c?.includes(`{`)||(yield{kind:n?`escaped`:`substitution`,name:s,defaultValue:c,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=[],o=0;for(let s of iterateEnvTemplateTokens(e)){if(a.push(e.slice(o,s.start)),o=s.end+1,s.kind===`escaped`){a.push(renderEnvTemplateToken(s));continue}let c=t[s.name];if(c===void 0||c===``){if(s.defaultValue!==void 0){a.push(s.defaultValue);continue}if(r?.onMissing){r.onMissing({varName:s.name,configPath:n}),i?.id===s.name&&r.onPendingEnvSecretRef?.(s.name,n),a.push(renderEnvTemplateToken(s));continue}throw new MissingEnvVarError(s.name,n)}i?.id===s.name&&r?.onResolvedEnvSecretRef?.(s.name,n),a.push(c)}return a.push(e.slice(o)),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 qt,Jt,MissingEnvVarError,Yt=__esmMin((()=>{Pt(),Vt(),Kt(),qt=/^[A-Z_][A-Z0-9_]*$/,Jt=`:-`,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`}}})),Xt=__esmMin((()=>{}));function isMissingPathError(e){return b(e,`ENOENT`)||b(e,`ENOTDIR`)||b(e,`not-found`)}var Zt=__esmMin((()=>{})),Qt=__esmMin((()=>{Zt()})),$t=__esmMin((()=>{Qt(),y.snapshot()}));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,o]of Object.entries(t)){if(isBlockedObjectKey(e)||o===void 0&&i===`skip`)continue;let t=a[e];a[e]=isPlainObject(o)?isPlainObject(t)?mergeDeep(t,o,n):sanitizePlainObject(o):r===`concat`&&Array.isArray(t)&&Array.isArray(o)?[...t,...o]:o}return a}var en=__esmMin((()=>{Pt(),It()})),tn=__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=S.homedir){let r=resolveRawOsHomeDir(e,t);return r?n.resolve(r):void 0}function resolveEffectiveHomeDir(e=process.env,t=S.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 nn=__esmMin((()=>{})),rn,an,on,sn,cn=__esmMin((()=>{rn=`(?:\\x1b\\]|\\x9d)`,an=`(?:\\x1b\\\\|\\x07|\\x9c)`,on=`${rn}[^\\x07\\x1b\\x9c]*${an}`,sn=`[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,new RegExp(on,`y`)})),ln,un=__esmMin((()=>{cn(),ln=`${rn}[\\s\\S]*?${an}`,RegExp(`${ln}|${sn}`,`y`),new Intl.Segmenter(void 0,{granularity:`grapheme`})})),dn=__esmMin((()=>{un()}));function resolveGlobalSingletonResetRegistry(){let e=globalThis,t=e[pn];if(t instanceof Map)return t;let n=/* @__PURE__ */ new Map;return e[pn]=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 pn,D=__esmMin((()=>{pn=Symbol.for(`openclaw.globalSingletonLifecycleResets`)}));function tryProcessCwd(){try{return process.cwd()}catch{return}}var mn=__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=S.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??S.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??S.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=S.homedir){return e?resolveHomeRelativePath(e,{env:t,homedir:n}):``}var hn=__esmMin((()=>{nn(),D(),mn()}));function isValidProfileName(e){return gn.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 gn,_n=__esmMin((()=>{Ye(),hn(),gn=/^[a-z0-9][a-z0-9_-]{0,63}$/i})),LruCache,vn=__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=S.homedir){let r=e.OPENCLAW_STATE_DIR?.trim();if(r&&process.platform!==`win32`&&n.isAbsolute(r)){let e=yn.peek(r);if(e!==void 0)return e;let t=n.resolve(r);return yn.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 yn,bn=__esmMin((()=>{_n(),hn(),vn(),yn=new LruCache(64)}));function resolveConfigDir(e=process.env,t=S.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 xn=__esmMin((()=>{bn(),hn()}));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 Sn=__esmMin((()=>{})),Cn=__esmMin((()=>{Sn()}));function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var wn=__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 o=r.signal;o&&(onAbort=()=>settle(()=>{if(r.onAbort)return r.onAbort(o);throw createAbortError(`Operation aborted`,{cause:o.reason})}),o.addEventListener(`abort`,onAbort,{once:!0}),o.aborted&&onAbort())}),o;try{o=typeof e==`function`?e():e}catch(e){throw a.catch(()=>{}),e}return await Promise.race([o,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?Tn:Number.isFinite(e)?e:0),0),Tn)}function resolveRetryConfig(e=En,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,o=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):o}}function applyJitter(e,t,n,r){if(t===`full`)return n===`symmetric`?Math.max(0,Math.round(e*(.5+r()*.5))):Math.max(0,Math.ceil(e*(1+r())));if(t<=0)return n===`positive`?Math.ceil(e):e;let i=r(),a=e*(1+(n===`positive`?i*t:(i*2-1)*t));return Math.max(0,n===`positive`?Math.ceil(a):Math.round(a))}function toRetryError(e,t=`Non-Error thrown`){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);let n=Error(t,{cause:e});return(typeof e==`object`&&e||typeof e==`function`)&&Object.assign(n,e),n}function createRetryRunner(e={}){let t=e.sleep??defaultSleep,n=e.random??Math.random,r=e.createFailure??(e=>toRetryError(e.at(-1)??/* @__PURE__ */ Error(`Retry failed`)));return async function(i,a=3,o=300){let s=[],c=typeof a==`number`,l=typeof a==`number`?{attempts:a}:a,u=resolveRetryConfig(En,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??n,g=l.sleep??t,_=l.shouldRetry??(()=>!0);for(let n=1;n<=d;n+=1)try{return await i()}catch(r){if(s.push(r),n>=d||e.shouldRetry?.(r)===!1||!_(r,n))break;if(c){await t(resolveRetryDelayMs(o*2**(n-1)));continue}let i={attempt:n,maxAttempts:d,err:r,label:l.label},a=l.retryAfterMs?.(r),v=typeof a==`number`&&Number.isFinite(a),ee=typeof l.delayMs==`function`?l.delayMs(i):l.delayMs,te=ee===void 0?void 0:resolveRetryDelayMs(ee),ne=v?Math.max(a,f):te===void 0?f*2**(n-1):Math.max(te,f),re=v?m:p,ie=Math.min(ne,re),y=v&&(a??0)<=re,ae=u.jitter===`full`&&!v||y;ie=applyJitter(ie,u.jitter,ae?`positive`:`symmetric`,h),ie=Math.min(Math.max(ie,f),re),await l.onRetry?.({...i,delayMs:ie}),ie>0&&await g(ie)}throw r(s)}}var Tn,En,defaultSleep,Dn=__esmMin((()=>{Tn=2147e6,En={attempts:3,minDelayMs:300,maxDelayMs:3e4,jitter:0},defaultSleep=async e=>{let t=e;do{let e=Math.min(t,Tn);await new Promise(t=>{setTimeout(t,e)}),t-=e}while(t>0)},createRetryRunner()})),On=__esmMin((()=>{Dn()})),kn=__esmMin((()=>{St(),Dn(),On()})),An=__esmMin((()=>{dn(),xn(),Cn(),Pt(),kn(),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){try{return l.realpathSync(e)}catch{return 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??l,r=e.maxBytes??Mn;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=Pn,r={}){let i=createConfigIncludeBoundary(t,r.allowedRoots??[]);return new IncludeProcessor(t,n,i).process(e)}function resolveConfigIncludesForTopLevelKey(e,t,n,r=Pn,i={}){let a=createConfigIncludeBoundary(t,i.allowedRoots??[]);return new IncludeProcessor(t,r,a,/* @__PURE__ */ new Set([n])).process(e)}var jn,Mn,Nn,ConfigIncludeError,ConfigIncludeReadError,CircularIncludeError,IncludeProcessor,Pn,Fn=__esmMin((()=>{Ot(),Xt(),$t(),en(),Zt(),tn(),An(),Bt(),jn=`$include`,Mn=2097152,Nn=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[o,s]of Object.entries(e))i&&this.rootProjectionKeys&&!this.rootProjectionKeys.has(o)||(a[o]=isConfigContainer(s)?yield{value:s,pathLink:{parent:t,key:o},hasArrayAncestor:n,context:r}:s);return a}return yield*this.traverseInclude(e,t,n,r)}*traverseInclude(e,t,n,r){let i=e[jn],a=t===null,o=Object.keys(e).filter(e=>e!==`$include`&&(!a||!this.rootProjectionKeys||this.rootProjectionKeys.has(e))),s=Array.isArray(i);if(!s&&typeof i!=`string`)throw new ConfigIncludeError(`Invalid $include value: expected string or array of strings, got ${typeof i}`,String(i));let c=[];for(let e of s?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);c.push({value:yield{value:i.parsed,pathLink:t,hasArrayAncestor:n,context:i.nestedContext},targetPath:i.resolvedPath})}let l=s?c.reduce((e,t)=>deepMerge(e,t.value),{}):c[0].value;if(this.resolver.onIncludeResolved?.({path:includeLogicalPath(t),value:l,kind:s?`multiple`:`single`,hasSiblingOverrides:o.length>0,hasArrayAncestor:n,...s?{targetPaths:c.map(e=>e.targetPath)}:{targetPath:c[0].targetPath}}),o.length===0)return l;if(!isPlainObject(l))throw new ConfigIncludeError(`Sibling keys require included content to be an object`,typeof i==`string`?i:jn);let u={};for(let i of o){let a=e[i];u[i]=isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:i},hasArrayAncestor:n,context:r}:a}return deepMerge(l,u)}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>=Nn)throw new ConfigIncludeError(`Include path exceeds maximum length (${Nn} 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>=Nn)throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${Nn} characters)`,e);let o=this.findContainingRoot(a,`rootDir`);if(!o)throw new ConfigIncludeError(`Include path escapes config directory: ${e} (root: ${this.rootDir})`,e);this.resolver.onLexicalPath?.(a);try{let t=l.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:o};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)}}},Pn={readFile:e=>l.readFileSync(e,`utf-8`),readFileWithGuards:readConfigIncludeFileWithGuards,parseJson:parseJsonWithJson5Fallback}})),In=__esmMin((()=>{St()}));function resolveIsNixMode(e=process.env){return e.OPENCLAW_NIX_MODE===`1`}function envHomedir(e){return()=>resolveRequiredHomeDir(e,S.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 o=n.resolve(resolveHomeRelativePath(r,{env:e,homedir:effectiveHomedir}));i.has(o)||(i.add(o),a.push(o))}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),Ln)}var Ln,Rn=__esmMin((()=>{hn(),In(),bn(),resolveIsNixMode(),Ln=`openclaw.json`,resolveStateDir(),resolveConfigPathCandidate()}));function createUnownedAppliedLoggingConfig(){return Bn}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 zn,Bn,Vn,O,Hn=__esmMin((()=>{zn=Symbol.for(`openclaw.loggingState`),Bn=`unowned`,Vn=globalThis,O=Vn[zn]??createLoggingState(),Vn[zn]=O}));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(O.appliedConfig!==`unowned`)return O.appliedConfig;let e=resolveLoggingConfigSelector();if(Un?.selector===e)return Un.logging;let t=resolveConfigPath();if(!l.existsSync(t)){Un={selector:e,logging:void 0};return}let n=parseJsonWithJson5Fallback(l.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 o=isRecord(a)?a.logging:void 0,s=isRecord(o)?o:void 0;return Un={selector:e,logging:s},s}catch{return}}var Un,Wn=__esmMin((()=>{T(),Yt(),Fn(),Rn(),mn(),Bt(),Hn()}));function clampMessage(e){return e.length>Gn?`${truncateUtf16Safe(e,Gn)}...(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 Gn,Kn=__esmMin((()=>{T(),Dt(),Gn=4096}));function replacePatternBounded(e,t,n){if(e.length<=qn)return e.replace(t,n);let r;for(let i=0;i<e.length;i+=Jn){let a=e.slice(i,i+Jn),o=a.replace(t,n);r===void 0?o!==a&&(r=e.slice(0,i)+o):r+=o}return r??e}var qn,Jn,Yn=__esmMin((()=>{qn=32768,Jn=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=[],o=0,s=0,c=0,consume=(t,n)=>{if(t===c){let t=r[o];if(!t)return{start:e,end:e};let n=t.replacement===void 0?t.start+s:t.start;return{start:n,end:t.replacement!==void 0&&s>0?t.end:n}}let i,l=0;for(;c<t;){let e=expectDefined(r[o],`current redaction piece`),u=e.replacement?.length??e.end-e.start,d=Math.min(u-s,t-c),f=e.replacement===void 0?e.start+s:e.start,p=e.replacement===void 0?f+d:e.end;i??=f,l=p,n&&d>0&&a.push({start:f,end:p,replacement:e.replacement?.slice(s,s+d)}),c+=d,s+=d,s===u&&(o+=1,s=0)}return{start:i??l,end:l}};for(let e of n)consume(e.start,!0),a.push({...consume(e.end,!1),replacement:e.replacement});for(;o<r.length;){let e=expectDefined(r[o],`remaining redaction piece`);consume(c+(e.replacement?.length??e.end-e.start)-s,!0)}let l=[],u=[],d,flush=()=>{d&&(d.replacement=u.join(``),l.push(d),d=void 0,u=[])};for(let e of a){if(e.replacement===void 0){flush();continue}let t=d&&d.start===e.start&&d.end===e.end&&e.start===e.end;!d||e.start>=d.end&&!t?(flush(),d={start:e.start,end:e.end,replacement:``}):d.end=Math.max(d.end,e.end),u.push(e.replacement)}return flush(),l}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 o=r[n-1];return e+(o?o.currentEnd-o.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 Xn=__esmMin((()=>{Ot()}));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(Zn)){let i=t[0],a=r.at(-1);if(i===`{`||i===`[`){let e=valueContext(a),o=i===`[`;r.push({array:o,nextIndex:0,context:o?{...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 o=t.index,s=o+i.length,c=i.startsWith(`"`),l=c?JSON.parse(i):i,u=skipWhitespace(e,s),d=c&&e[u]===`:`,f;if(d){let t=expectDefined(a,`JSON property container`),n=t.context;f={key:``,path:[],origin:n.origin,objectPath:!1,rootKey:n.rootKey,rootValueStart:n.rootValueStart};let i=skipWhitespace(e,u+1);t.field={key:l,path:[...n.path,l],origins:n.origins?.children.get(l),origin:n.origins?.value??n.origin,objectPath:n.objectPath,rootKey:r.length===1?l:n.rootKey,rootValueStart:r.length===1?i:n.rootValueStart}}else f=valueContext(a);let p=d?{structured:!1,primitiveMask:!1}:f.origins?.value??f.origin;n.push({...f,origin:p,start:o,end:s,isKey:d,string:c,value:l,escaped:c&&i.includes(`\\`),edits:[],projectedEdits:[],currentValue:l,currentStart:o,currentEnd:s})}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 Zn,Qn=__esmMin((()=>{Ot(),Zn=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\]]/g}));function parseRedactPatternSource(e){let t=e.match(/^\/(.+)\/([gimsuy]*)$/);if(!t)return[e,`gi`];let n=t[1]??``,r=t[2]??``;return[n,r.includes(`g`)?r:`${r}g`]}function escapeAtomEnd(e,t){let n=e[t+1];if(n===void 0)return-1;if(nr.has(n))return t+2;if(n===`x`)return tr.test(e[t+2]??``)&&tr.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&&tr.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 o=e[a],s=a+1,c=!0;if(o===`\\`)s=escapeAtomEnd(e,a),s<0?(s=a+1,c=!1):t.includes(`u`)&&isHighSurrogateEscape(e,a)&&e[s]===`\\`&&isLowSurrogateEscape(e,s)?s=escapeAtomEnd(e,s):c=!nr.has(e[a+1]);else if(o===`[`){if(s=classAtomEnd(e,a),s<0)return e}else if(o===`{`){let t=$n.exec(e.slice(a)),o=t&&r>=0?t:er.exec(e.slice(a));if(o){n+=o===t?`{${t[1]}}${e.slice(r,i)}*`:o[0],a+=o[0].length,e[a]===`?`&&(n+=`?`,a+=1),r=-1;continue}}else t.includes(`u`)&&o>=`\ud800`&&o<=`\udbff`&&a+1<e.length&&e[a+1]>=`\udc00`&&e[a+1]<=`\udfff`?s=a+2:c=!`*+?()|^$`.includes(o);n+=e.slice(a,s),r=c?a:-1,i=s,a=s}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(rr.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;rr.set(e,o=>e.source!==n||e.exec!==r||e instanceof RegExp&&(e.flags!==i||e[Symbol.replace]!==a)||t(o))}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 o=ir.get(e);o||(o=new RegExp(e.source,`${e.flags.replace(`d`,``).replace(`g`,``)}dg`),ir.set(e,o)),o.lastIndex=r;let s=o.exec(t),c=s?.indices?.[a+1];return s?.index===r&&s[0]===n&&c?c[0]-r:n.lastIndexOf(i.value)}function visitRedactMatches(e,t,n){if(rr.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:ar.get(t);r||(r=new RegExp(t.source,`${t.flags}g`),ar.set(t,r));let i=r.unicode||r.flags.includes(`v`),a=0;for(;a<=e.length;){let o=r.lastIndex,s;try{r.lastIndex=a,s=r.exec(e)}finally{r.lastIndex=o}if(!s)return;if(a=s.index+s[0].length,!s[0]){let t=e.codePointAt(a);a+=i&&t!==void 0&&t>65535?2:1}n({match:s[0],groups:s.slice(1).map(e=>e??``),input:e,offset:s.index},t)}}function replaceRedactPattern(e,t,n,r){if(t instanceof RegExp)return rr.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 $n,er,tr,nr,escapeHexValue,isHighSurrogateEscape,isLowSurrogateEscape,rr,ir,ar,or=__esmMin((()=>{$n=/^\{(\d+),\}/,er=/^\{(?:\d+(?:,\d*)?|,\d+)\}/,tr=/[0-9A-Fa-f]/,nr=/* @__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||!tr.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},rr=/* @__PURE__ */ new WeakMap,ir=/* @__PURE__ */ new WeakMap,ar=/* @__PURE__ */ new WeakMap}));function stringBoundaries(e,t,n){let r=/* @__PURE__ */ new Map,i=0;for(let a=t;a<n;i+=1)r.set(a,i),a+=e[a]===`\\`?e[a+1]===`u`?6:2:1;return r.set(n,i),r}function decodedBoundary(e,t,n){return t.escaped?(t.boundaries??=stringBoundaries(e,t.start+1,t.end-1),t.boundaries.get(n)):n-t.start-1}function encodedBoundary(e,t,n){if(!t.escaped)return t.start+1+n;if(!t.encodedBoundaries){t.boundaries??=stringBoundaries(e,t.start+1,t.end-1),t.encodedBoundaries=[];for(let[e,n]of t.boundaries)t.encodedBoundaries[n]=e}return expectDefined(t.encodedBoundaries[n],`decoded JSON edit boundary`)}function projectMessageEdits(e,t,n,r){let i=new Map(n.parts.map(e=>[e.key,e])),a=[];for(let o of t){if(!o.isKey&&o.path.length===1&&o.key===`message`)continue;let t=o.rootKey===void 0?void 0:i.get(o.rootKey);if(!t||!t.json&&(o.isKey||(t.messageField?o.path.length!==2||o.key!==`message`:o.path.length!==1)))continue;let s=r(o);for(let r of s){let i,s,c=r.replacement;if(t.json){let n=t.start-expectDefined(o.rootValueStart,`displayed JSON argument`);o.string?(i=n+encodedBoundary(e,o,r.start),s=n+encodedBoundary(e,o,r.end),c=JSON.stringify(c).slice(1,-1)):(i=n+o.start,s=n+o.end,c=JSON.stringify(c))}else i=t.start+r.start,s=t.start+r.end;i<n.contentLength&&a.push({start:i,end:Math.min(s,n.contentLength),replacement:c,scalar:t.json&&!o.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,o=0;for(let s of t.edits){let c=t.string?encodedBoundary(e,t,s.start):t.start+s.start,l=t.string?encodedBoundary(e,t,s.end):t.start+s.end,u=JSON.stringify(s.replacement).slice(1,-1),d=a+c-i,f=d+u.length;r.push({start:d,end:f,decodedStart:s.start+o,decodedEnd:s.start+o+s.replacement.length,sourceEnd:l,sourceDecodedEnd:s.end,replacement:u}),n.push(e.slice(i,c),u),a=f,o+=s.replacement.length-(s.end-s.start),i=l}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 o=0,s=a.length;for(;o<s;){let e=o+s>>>1;expectDefined(a[e],`current encoded edit`).end<i?o=e+1:s=e}let c=a[o];if(c&&i>=c.start){let e=i-c.start;if(!c.replacement.includes(`\\`))return c.decodedStart+e;let t=r.get(c.replacement);t||(t=stringBoundaries(c.replacement,0,c.replacement.length),r.set(c.replacement,t));let n=t.get(e);return n===void 0?void 0:c.decodedStart+n}let l=a[o-1],u=decodedBoundary(e,t,i+(l?l.sourceEnd-l.end:t.start+1));return u===void 0?void 0:u+(l?l.decodedEnd-l.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,o=0;for(let s of n){let n=s.currentStart,c=s.currentEnd;if(r.has(s)){updateCurrentToken(e,s);let r=expectDefined(s.currentRaw,`changed JSON token`);i.push(t.slice(a,n),r),a=c,s.currentStart=n+o,o+=r.length-(c-n)}else s.currentStart=n+o;s.currentEnd=c+o}return i.push(t.slice(a)),i.join(``)}function projectedStringEnd(e,t,n,r,i,a){let o=new Set(n.parts.filter(e=>e.json).map(e=>e.key)),s=projectMessageEdits(e,t,n,e=>e.string&&!e.isKey&&e.rootKey!==void 0&&o.has(e.rootKey)?[{start:0,end:e.value.length,replacement:``}]:[]).filter(e=>e.end<n.contentLength),c=rebaseRedactionEdits(r.edits,s).filter(e=>e.start<=i&&i<e.end&&a<=e.end);return c.length===1?expectDefined(c[0],`displayed source string`).end:r.currentValue.length}function redactJsonRecord(e,t,n,r,i,a,o,s,c,l){let u=l?[]:readScalarTokens(e,t),d=c?u.find(e=>!e.isKey&&e.path.length===1&&e.key===`message`):void 0,f=/* @__PURE__ */ new Map,p=[],m=d?.value??``,h=e,g=/* @__PURE__ */ new Set;for(let e of u)commitOriginalEdits(e,o(e))&&g.add(e);g.size>0&&(h=updateCurrentRecord(e,h,u,g));let _=u.filter(e=>!e.isKey&&e.string&&!s(e,e.currentValue)),projectMessage=()=>{if(!d||!c)return!1;let t=projectMessageEdits(e,u,c,e=>{let t=changedRedactionEdits(e.projectedEdits,e.edits);return e.projectedEdits=e.edits,t});if(t.length===0)return!1;let n=rebaseRedactionEdits(p,t),r=rebaseRedactionEdits(d.edits,t),i=0;for(let e=0;e<r.length;e+=1){let a=expectDefined(r[e],`projected message edit`),o=expectDefined(n[e],`projected source edit`),s=expectDefined(t[e],`source projection`);for(;d.edits[i]&&expectDefined(d.edits[i],`generated message span`).start<s.start;)i+=1;let c=d.edits[i],l=s.scalar&&c?.start===s.start&&c.end===s.end&&a.replacement===JSON.stringify(c.replacement),u=d.currentValue.slice(a.start,a.end);!l&&u!==a.replacement&&u!==m.slice(o.start,o.end)&&(a.replacement=s.scalar?JSON.stringify(`***`):`***`)}return d.pending=r,m=applyRedactionEdits(m,n),p=composeRedactionEdits(d.value.length,p,n),commitPatternEdits(d)};for(let[o,s]of n.entries()){let n=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set,add=(e,t)=>{(e.pending??=[]).push(t),p.add(e)},m,visitDecodedMatch=(e,t)=>{let n=r(e,t),i=n?.redact(n);i&&i.end>=i.start&&add(m,i)};for(let i of s)if(!i.couldMatch||i.couldMatch(h))for(let a of i.patterns){if(o===0)for(m of _)visitRedactMatches(m.currentValue,a,visitDecodedMatch);else visitRedactMatches(h,a,n=>{let i=r(n,a);if(!(!i||i.end<i.start)){l&&u.length===0&&(u=readBatchTokens(e,t,l.preserveLines));for(let t=firstIntersectingToken(u,i.start);t<u.length;t+=1){let n=expectDefined(u[t],`serialized capture token`);if(n.currentStart>=i.end)break;let r=n.raw||n.deferEncoding,a=+!r,o=i.start>=n.currentStart+a&&i.end<=n.currentEnd-a;if(l&&n.isKey&&!o)continue;let s=n.currentValue;if(!n.raw&&!n.string&&n.edits.length===0){add(n,{start:0,end:s.length,replacement:`***`});continue}let p=Math.max(i.start,n.currentStart+a),m=r?p-n.currentStart:currentDecodedBoundary(e,n,p,f),g=Math.min(i.end,n.currentEnd-a),_=r?g-n.currentStart:currentDecodedBoundary(e,n,g,f);if(m===void 0||_===void 0){for(;m===void 0;)m=currentDecodedBoundary(e,n,--p,f);for(;_===void 0;)_=currentDecodedBoundary(e,n,++g,f);let t=n===d&&c?projectedStringEnd(e,u,c,n,m,_):s.length;add(n,{start:m,end:t,replacement:`***`});continue}if(_<m||l&&_===m)continue;let{start:v,end:ee}=i,te=i.redact({start:m,end:_,value:h.slice(Math.max(v,n.currentStart+a),Math.min(ee,n.currentEnd-a))});if(!te)continue;let ne=`***`;if(o)try{ne=r?te.replacement:JSON.parse(`"${te.replacement}"`)}catch{}add(n,{...te,replacement:ne})}}});if(p.size!==0){for(let e of p)commitPatternEdits(e)?o===0&&n.add(e):p.delete(e);o!==0&&p.size>0&&(h=updateCurrentRecord(e,h,u,p)),p.clear()}}for(let e of u)o===0?(e.pending=i(e,e.currentValue),commitPatternEdits(e)&&n.add(e)):commitOriginalEdits(e,a(e))&&n.add(e);(o!==0||g.size>0||n.size>0)&&projectMessage()&&d&&n.add(d),n.size>0&&(h=updateCurrentRecord(e,h,u,n))}if(d&&c){let e=c.finish(d.currentValue);if(e!==d.currentValue)return applyRedactionEdits(h,[{start:d.currentStart,end:d.currentEnd,replacement:JSON.stringify(e)}])}return applyRedactionEdits(h,u.flatMap(e=>e.deferEncoding&&e.edits.length>0?[{start:e.currentStart,end:e.currentEnd,replacement:JSON.stringify(e.currentValue)}]:[]))}var sr=__esmMin((()=>{Ot(),Xn(),Qn(),or()}));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 o=Math.max(0,(n?a.bodyStart:a.start)-i),s=(n?a.bodyEnd:a.end)-i;s<=o||(yield{match:e.slice(o,s),groups:[],input:e,offset:o,...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 cr,lr,ur=__esmMin((()=>{cr=String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----`,lr={source:cr,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:cr,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 Br.test(e);t=n+40}return!1}function*matchAwsSecretAccessKeys(e){if(!couldMatchAwsSecretAccessKey(e))return;let t={'"':`"`,"'":`'`,"`":"`","<":`>`,"(":`)`,"[":`]`,"{":`}`},n=-1,r=-1,i,a=0,o=[];for(let s=0;s<=e.length;s++){let c=e[s]??``,l=s===e.length||Vr.test(c),u=a;if(a=c===`\\`?a+1:0,c&&isAwsValueCharacter(c)?n===-1&&(n=s):n!==-1&&(s-n===40?o.push({start:n,end:s,origin:n,url:i}):s-n>40&&c===`@`&&e[s-41]===`/`&&o.push({start:s-40,end:s,origin:n,url:i}),n=-1),l){i&&(i.end=Math.min(i.end,s));for(let t of o){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]??``,o=t.start!==t.origin,s=n&&n.portStart!==-1&&t.origin===n.portStart+1&&n.authorityEnd>t.origin&&t.end>n.authorityEnd&&a===`@`;if(!o&&(i===`_`||isAwsValueCharacter(i))||a===`_`||e.slice(t.origin-8,t.origin)===`;base64,`||r&&!s&&t.start>=n.start&&t.end<=n.end)continue;let c=e.slice(t.start,t.end);Br.test(c)&&(yield{match:c,groups:[c],input:e,offset:t.start})}o.length=0,r=-1,i=void 0}else if(i&&s>=i.start&&(c===i.closing&&u===i.closingEscapeDepth?(i.end=Math.min(i.end,s),i=void 0):(`?#"'<>\`|()[]{}`.includes(c)&&(i.end=Math.min(i.end,s)),i.queryOrFragment||=c===`?`||c===`#`,i.authorityEnd===-1&&(i.hasAt||=c===`@`,`/?#`.includes(c)?i.authorityEnd=s:s<i.end&&(c===`:`?(i.portValid&&=i.portStart===-1,i.portStart=s):i.portStart!==-1&&(c<`0`||c>`9`)&&(i.portValid=!1))))),Hr.test(c))r===-1&&(r=s);else{if((!i||s>=i.end&&!i.queryOrFragment)&&c===`:`&&e.startsWith(`//`,s+1)&&r!==-1&&Ur.test(e[r])){let n=e[r-1],a=0;for(let t=r-2;t>=0&&e[t]===`\\`;t--)a++;i={start:s+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(Gr)];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 o=e[i-1]??``,s=a[1]!==`pass`||o===`.`||o===`-`||o===`_`;if(s||r||o!==` `||!qr.test(e[i-2]??``)){r=!0;let o=i+a[0].length;if(!s){Kr.lastIndex=o;let t=Kr.exec(e)?.[0];t&&(o+=t.length,yield{match:e.slice(i,o),groups:[t],input:e,offset:i})}let c=t[n];for(;c&&c.index<o;)n++,c=t[n];i=o-1;continue}}let o=e[i];o===`
`||o===`\r`?r=!1:(o===`=`||o===`:`&&!Jr.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(`^(?:${Qr}|${$r})$`,`i`),n=/* @__PURE__ */ new Set([ni,ii]),r=/* @__PURE__ */ new Set([wr,Tr,Er,Dr]),i=new RegExp(String.raw`[:=](?<=(?:${vr})\s*[:=])`),a=new RegExp(String.raw`[:=](?<=(?:${vr})\s*[:=])\s*["'\x60]`),o=new RegExp(String.raw`[:=](?<=\.(?:${vr})\s*[:=])`),s=new RegExp(String.raw`=(?<=(?:^|[\s,;({\["])(?:${_r})=)`,`i`);return{bodySecretKeys:e,credentialHeaderField:t,formAware:n,shellReferencePreserving:r,prefilters:new Map([[wr,e=>/KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD|CVC|CVV|SECURITY|PAYMENT/.test(e)],[Tr,e=>e.includes(`\\`)],[Er,e=>/[=]["'`]/.test(e)],[Dr,e=>s.test(e)],[kr,e=>/["'`]/.test(e)&&a.test(e)],[Ar,e=>(e.includes(`:`)||e.includes(`=`))&&i.test(e)],[jr,e=>e.includes(`=`)],[Mr,e=>/[-_](?:password|passphrase|pass|passwd)\s*[:=]/.test(e)],[Nr,e=>o.test(e)],[Ir,e=>/["']/.test(e)],[Lr,e=>/["']/.test(e)],...ai.slice(0,4).map(e=>[e,e=>/authorization/i.test(e)]),[ti,e=>/api-key|apikey|api-token|access-token/i.test(e)],[ni,e=>/api-key|apikey|api-token|access-token/i.test(e)],[Pr,e=>e.includes(`"`)],[Fr,e=>e.includes(`"`)],[ri,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)],[ii,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)]]),chunkUnsafe:/* @__PURE__ */ new Set([Xr,Zr,oi,si,ci,li,...ai,...di.filter(e=>e.startsWith(Rr))])}}var dr,fr,pr,mr,hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,base64SafeToken,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,di,fi,pi=__esmMin((()=>{ft(),ur(),dr=String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`,fr=String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`,pr=String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`,mr=String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`,hr=String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${mr}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`,gr=String.raw`${hr}|app[-_]?secret|credential|${fr}`,_r=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|${fr}`,vr=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|${fr}`,yr=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|${fr}`,br=String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`,xr=String.raw`password|passphrase|pass|passwd`,Sr=String.raw`${mr}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${fr}`,Cr=String.raw`\p{C}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0`,wr=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${dr})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`,Tr=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${dr})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`,Er=String.raw`(^|[\s,;({\["])(?:${_r})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`,Dr=String.raw`(^|[\s,;({\["])(?:${_r})=(["'\x60]?[^\s&#"'\x60<>]+)`,Or=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|${fr}`,kr=String.raw`/(^|[\s,{])(?:(?:${Or})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${xr})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${vr})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`,Ar=String.raw`/(^|[\s,{])(?:(?:${yr})\s*:\s*|(?:${vr})(?:\s+=\s*|=\s+))([^\s#"'\x60<>]+)/g`,jr=String.raw`/(^|[\s,{])(?:${br})=([^\s#"'\x60<>]+)/g`,Mr=String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${xr})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,Nr=String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${vr})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,Pr=String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${mr}|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*"([^"]+)"`,Fr=String.raw`"(?:${pr})"\s*:\s*"([^"]+)"`,Ir=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`,Lr=String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,Rr=String.raw`(^|[^A-Za-z0-9])`,base64SafeToken=e=>String.raw`${Rr}(?=${e})(?<!;base64,[A-Za-z0-9+/=]*)(${e})`,zr=String.raw`(^|[^A-Za-z0-9_])`,Br=/(?=[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,Vr=/\s/,Hr=/[A-Za-z0-9+.-]/,Ur=/[A-Za-z]/,Wr=Object.freeze({source:`aws-secret-access-key`,exec:matchAwsSecretAccessKeys,couldMatch:couldMatchAwsSecretAccessKey}),Gr=new RegExp(String.raw`(?<![A-Za-z0-9])(pass|${yr})\s*:\s*`,`gi`),Kr=/[^\s#"'\x60<>]+/y,qr=/[A-Za-z0-9]/,Jr=/[ \t\r\n]/,Yr=Object.freeze({source:`bare-pass-assignment`,exec:matchBarePassAssignments}),Xr=String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`,Zr=String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`,Qr=`x-goog-api-key|api-key|apikey|x-api-token|x-access-token`,$r=`X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token`,ei=String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`,ti=String.raw`${ei}(?:${Qr})${E}[ \t]*:${at}${E}([^\s\\"',;]+)`,ni=String.raw`${ei}(?:${Qr})${E}[ \t]*=${at}${E}([^\s\\"',;]+)`,ri=String.raw`${ei}(?:${$r})\s*:\s*([^\s"',;]+)`,ii=String.raw`${ei}(?:${$r})\s*=\s*([^\s"',;]+)`,ai=[String.raw`${ct}Proxy-Authorization${E}[ \t]*[:=]${at}${E}${tt}${ot}(${nt})`,String.raw`${ct}Proxy-Authorization${E}[ \t]*[:=]${at}${E}(${nt})[ \t]*(?=${E}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,String.raw`${ct}Authorization${E}[ \t]*[:=]${at}${E}(?!(?:Bearer|Basic|Bot)(?=${ot}))${tt}${ot}(${nt})`,String.raw`${ct}Authorization${E}[ \t]*[:=]${at}${E}(?!(?:Bearer|Basic|Bot)(?=${ot}))(${nt})[ \t]*(?=${E}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,ti,ni],oi=String.raw`Authorization${E}[ \t]*[:=]${st}${E}Bearer${ot}(${nt})`,si=String.raw`Authorization${E}[ \t]*[:=]${st}${E}Basic${ot}(${nt})`,ci=String.raw`Authorization${E}[ \t]*[:=]${st}${E}Bot${ot}(${nt})`,li=String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`,ui=[wr,Tr,Pr,Fr,Ir,Lr,String.raw`--(?:${Sr})=([^\s"']+)`,String.raw`--(?:${Sr})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,oi,si,ci,...ai,ri,ii,li,String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,String.raw`(^|[\s,;])(?:${gr})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,Er,Dr,kr,Ar,Yr,jr,Mr,Nr,cr,String.raw`(^|[\s,{])["']?(?:${mr})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`],di=[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`${zr}(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`${zr}(fw-[A-Za-z0-9]{30,})`,String.raw`${zr}(fw_[A-Za-z0-9]{30,})`,String.raw`${zr}(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,})`,Xr,Zr],fi=[...ui,...di,Wr]}));function isJsWhitespaceAt(e,t){if(t>=e.length)return!1;let n=e.charCodeAt(t);return mi.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=hi.get(t);n||(n=[],hi.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,o=0;for(let n of scanPrefixOccurrences(e,t)){if(n<o||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 s=n>0?n-1:0;yield{match:e.slice(s,t),groups:[n>0?e[n-1]:``,e.slice(n,t)],input:e,offset:s},o=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=gi(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,o)=>{let s=o+n;if(s<e||s>=t){t=runEndOf(a,s,AT_VALUE_CHAR),e=s,i=void 0;for(let e=s;e<t;e++)a[e]===`=`&&r(a,e)!==null&&(i=e)}let c=s+1;return i!==void 0&&i>=c?i+9:null}})}function makeUserInfoMatcher(e,t,n){function*exec(e){let r=0,i=-1,a=e.indexOf(`://`);for(;a!==-1;){let o=a;for(;o>0&&isWordChar(e[o-1]);)--o;let s=e.slice(o,a).toLowerCase(),c=o;if(!t.has(s)&&o>=8&&s===`srv`&&e.slice(o-8,o).toLowerCase()===`mongodb+`&&(s=`mongodb+srv`,c=o-8),a>=r&&t.has(s)&&(c===0||!isWordChar(e[c-1]))){let t=a+3;for(;t<e.length&&e[t]!==`:`&&e[t]!==`/`&&e[t]!==`@`&&!isJsWhitespaceAt(e,t);)t+=1;if(e[t]===`:`){let o=t+1;if(o>=i){let t=runEndOf(e,o,e=>!n(e));if(e[t]===`@`&&t>o){yield{match:e.slice(c,t+1),groups:[e.slice(o,t)],input:e,offset:c},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,o=0;try{for(;;){i.lastIndex=o;let t=i.exec(e);if(!t)return;let n=t.index,r=t[2],s=n+t[0].length,c=a.get(r),l=-1;if(!(c!==void 0&&s>=c.start&&s<c.end))for(l=s;l<e.length;){let t=e[l];if(t===r||t===`\r`||t===`
`)break;l+=1}if(l>s&&e[l]===r){let i=l+1;yield{match:e.slice(n,i),groups:[t[1]??``,r,e.slice(s,l)],input:e,offset:n},o=i}else l!==-1&&a.set(r,{start:s,end:l}),o=n+1}}finally{i.lastIndex=0,r.push(i)}}return Object.freeze({source:e,exec})}var mi,hi,GAAAA_VALUE_CHAR,ATBB_VALUE_CHAR,AT_VALUE_CHAR,gi,_i,vi,yi,bi,xi,Si,Ci,wi,JWT_SEGMENT_CHAR,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,FORM_FIRST_PAIR_KEY_CHAR,FORM_FIRST_PAIR_TAIL_CHAR,Pi,Fi,Ii,Li,Ri,zi,Bi=__esmMin((()=>{pi(),mi=/* @__PURE__ */ new Set([9,10,11,12,13,32,160,5760,8232,8233,8239,8287,12288,65279]),hi=/* @__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===`_`,gi=fixedTailTokenEnd(4,32,isHexChar),_i=makeBase64SafeTokenMatcher(`vendor-token gAAAA (linear)`,`gAAAA`,()=>(e,t)=>{let n=runEndOf(e,t+5,GAAAA_VALUE_CHAR);return n-(t+5)>=20?n:null}),vi=makeBase64SafeTokenMatcher(`vendor-token ATBB (linear)`,`ATBB`,()=>(e,t)=>{let n=runEndOf(e,t+4,ATBB_VALUE_CHAR);return n-(t+4)>=16?n:null}),yi=makeBase64SafeTokenMatcher(`vendor-token AKIA (linear)`,`AKIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),bi=makeBase64SafeTokenMatcher(`vendor-token ASIA (linear)`,`ASIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),xi=makeBase64SafeTokenMatcher(`vendor-token dapi (linear)`,`dapi`,()=>dapiTokenEnd),Si=makeAtEqualsTokenMatcher(`vendor-token ATCTT3xFfG (linear)`,`ATCTT3xFfG`),Ci=makeAtEqualsTokenMatcher(`vendor-token ATATT (linear)`,`ATATT`),wi=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===`-`,Ti=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 o=t(a+3);if(o-(a+3)<10||e[o]!==`.`)continue;let s=n(o+1);if(s-(o+1)<10||e[s]!==`.`)continue;let c=r(s+1);if(c-(s+1)<10)continue;let l=e.slice(a,c);yield{match:l,groups:[l],input:e,offset:a},i=c}}}),Ei=String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,Di=String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,Oi=/* @__PURE__ */ new Set([`http`,`https`,`ws`,`wss`,`ftp`]),ki=/* @__PURE__ */ new Set([`postgres`,`postgresql`,`mysql`,`mongodb`,`mongodb+srv`,`redis`,`rediss`,`amqp`,`amqps`]),Ai=makeUserInfoMatcher(`url-userinfo (linear)`,Oi,e=>e===`/`||e===`@`||isJsWhitespaceChar(e)),ji=makeUserInfoMatcher(`connection-string (linear)`,ki,e=>e===`@`||isJsWhitespaceChar(e)),Mi=String.raw`(^|[\s,;])(?:${gr})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,Ni=RegExp(`^(?:${gr})$`,`i`),FORM_FIRST_PAIR_KEY_CHAR=e=>isAlnumChar(e)||e===`-`||e===`_`,FORM_FIRST_PAIR_TAIL_CHAR=e=>isAlnumChar(e)||e===`_`||e===`.`||e===`-`,Pi=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&&Ni.test(a)&&(i===0||e[i-1]===`,`||e[i-1]===`;`||isJsWhitespaceAt(e,i-1))){let a=r+1,o=t(a);if(o>a&&o<e.length&&e[o]===`&`&&isFormPairBoundary(e,o)){let t=i>0?i-1:0;yield{match:e.slice(t,o),groups:[i>0?e[i-1]:``,e.slice(a,o)],input:e,offset:t},n=o,r=e.indexOf(`=`,o);continue}}r=e.indexOf(`=`,r+1)}}}),Fi=String.raw`(^|[\s,;({\["])(?:${_r})=(["'\x60])`,Ii=String.raw`(^|[\s,{])(?:(?:${Or})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${xr})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${vr})\s*[:=]\s*)(["'\x60])`,Li=makeQuotedAssignmentMatcher(`standalone-quoted-assignment (linear)`,Fi,`gi`),Ri=makeQuotedAssignmentMatcher(`config-quoted-assignment (linear)`,Ii,`g`),zi=/* @__PURE__ */ new Map([[base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),_i],[base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Si],[base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Ci],[base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),vi],[base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),xi],[base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),yi],[base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),bi],[wi,Ti],[Ei,Ai],[Di,ji],[Mi,Pi],[Er,Li],[kr,Ri]])}));function maskToken(e){return e.length<Vi?`***`:`${sliceUtf16Safe(e,0,Hi)}…${sliceUtf16Safe(e,-4)}`}function splitSecretValueForMask(e){let t=e[0]??``,n=+!!Gi.has(t);if(n){let n=e.lastIndexOf(t);if(n>0){let t=e.slice(n+1);if(Wi.test(t))return{maskable:e.slice(1,n),suffix:t,maskStart:0,maskEnd:n+1}}}let r=e.slice(n),i=r.match(Ui)?.[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 Vi,Hi,Ui,Wi,Gi,Ki=__esmMin((()=>{Dt(),Vi=18,Hi=6,Ui=/(["'`,;)}\]]+)$/u,Wi=/^["'`,;)}\]]*$/u,Gi=/* @__PURE__ */ new Set([`"`,`'`,"`"])}));function startRedactionMeasurement(e){if(!qi.hasSubscribers)return;let t=he.now(),n=process.threadCpuUsage();return(r,i,a)=>{let o=he.now()-t,s=process.threadCpuUsage(n);qi.publish({operation:e,outcome:r,pid:process.pid,threadId:w,isMainThread:C,elapsedMs:o,threadCpuMs:(s.user+s.system)/1e3,...i===void 0?{}:{inputChars:i},...a===void 0?{}:{patternCount:a}})}}var qi,Ji=__esmMin((()=>{qi=me(`openclaw.redaction`)}));function couldMatchDefaultRedactPatterns(e){return Yi.test(e)||(e.includes(`-`)||e.includes(`_`))&&Xi.test(e)||Zi.test(e)||e.includes(`://`)&&e.includes(`@`)||e.includes(`=`)&&Qi.test(e)||Wr.couldMatch(e)}function couldMatchDefaultFullContextPatterns(e){return couldMatchDefaultRedactPatterns(e)||$i.test(e)}function couldMatchVendorRedactPatterns(e){return(e.includes(`-`)||e.includes(`_`))&&Xi.test(e)||Zi.test(e)||$i.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 Yi,Xi,Zi,Qi,$i,ea=__esmMin((()=>{pi(),Yi=/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,Xi=/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,Zi=/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,Qi=RegExp(`[${Cr}+%]`,`u`),$i=/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 ta=__esmMin((()=>{}));function invalidateMatcher(){ra.revision+=1,ra.registeredValueRedactor=void 0}function redactRegisteredSecretValues(e,t){return!e||ra.registeredValues.size===0?e:(ra.registeredValueRedactor??=createSecretValueRedactor([...ra.registeredValues.keys()]),ra.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,na));t={prefixes:new RegExp([...n.keys()].map(escapeRegExp).join(`|`),`g`),buckets:n}}let{prefixes:o,buckets:s}=t,c=[];o.lastIndex=0;for(let e=o.exec(r);e;e=o.exec(r)){let t=e.index,n=s.get(e[0])?.find(e=>r.startsWith(e,t));n!==void 0&&c.push({index:t,value:n}),o.lastIndex=t+(n?.length??1)}let l=``,u=0;for(let e of c)l+=`${r.slice(u,e.index)}${i(e.value,e.index)}`,u=e.index+e.value.length;return l+r.slice(u)}}function resetSecretRedactionRegistryForTest(){ra.registeredValues.clear(),invalidateMatcher()}var na,ra,ia=__esmMin((()=>{ta(),D(),wn(),na=6,ra=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`:oa.has(e)?`certificate_invalid`:null}function classifyMessage(e){return sa.some(t=>t.test(e))?`hostname_mismatch`:ca.some(t=>t.test(e))?`certificate_invalid`:null}function inspectTlsCertificateErrorInternal(e,t,n){if(n>la)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,o=i?classifyCode(i):null;if(i&&o)return{kind:o,code:i,message:a??i};let s=Array.isArray(r.errors)?r.errors:[];for(let e of[r.cause,r.error,...s]){let r=inspectTlsCertificateErrorInternal(e,t,n+1);if(r)return r}let c=a?classifyMessage(a):null;return c&&a?{kind:c,message:a}:null}function inspectTlsCertificateError(e){return inspectTlsCertificateErrorInternal(e,/* @__PURE__ */ new Set,0)}var aa,oa,sa,ca,la,ua=__esmMin((()=>{aa=/* @__PURE__ */ new Set([`ERR_TLS_CERT_ALTNAME_INVALID`,`HOSTNAME_MISMATCH`]),oa=/* @__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(`.`)),sa=[/hostname\/ip does not match certificate(?:'s)? altnames/i,/hostname mismatch/i,/host: .+ is not in the cert(?:ificate)?(?:'s)? altnames/i],ca=[/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],la=8}));function isKnownTransportErrorCode(e){return pa.some(({code:t})=>t.exec(e)?.[0]===e)||inspectTlsCertificateError({code:e})?.code===e}var da,fa,pa,ma=__esmMin((()=>{ua(),da=/(?:\s*:\s*|\s+)/,RegExp(`^(?:http\\s*)?(\\d{3})${da.source}(.+)$`,`i`),RegExp(`^(?:http\\s*)?(\\d{3})(?:${da.source}([\\s\\S]+))?$`,`i`),fa="Couldn't connect to the AI service. Check your connection, then try again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`.",pa=[{code:/\beconnrefused\b/i,phrases:/connection refused|actively refused/i,message:fa},{code:/\beconnreset\b|\beconnaborted\b|\benetreset\b|\bepipe\b/i,phrases:/socket hang up|connection reset|connection aborted/i,message:"Lost the connection to the AI service. Check the conversation before trying again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`."},{code:/\benotfound\b|\beai_again\b|\benetunreach\b|\behostunreach\b|\behostdown\b/i,phrases:/getaddrinfo|no such host|\bdns\b|network is unreachable|host is unreachable|fetch failed|connection error|network request failed/i,message:fa}]}));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 ha=__esmMin((()=>{ma()}));function parsePattern(e){if(e===cr)return lr;if(typeof e!=`string`&&!(e instanceof RegExp))return typeof e==`object`&&e&&typeof e.exec==`function`?e:null;let t=typeof e==`string`?zi.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=Ca.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`&&_a.shellReferencePreserving.has(e)&&va.add(t),t&&typeof e==`string`&&_a.formAware.has(e)&&wa.add(t),t&&typeof e==`string`&&(e.startsWith(zr)||_a.chunkUnsafe.has(e))&&Sa.add(t),t&&typeof e==`string`){if(Ca.has(e)&&ya.add(t),n&&xa.has(e)&&!ba.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;ba.set(t,()=>t.source===e&&t.exec===n&&(!(t instanceof RegExp)||t.flags===r&&t[Symbol.replace]===i))}let r=_a.prefilters.get(e);n&&r&&setRedactPatternPrefilter(t,r)}return t}function resolvePatterns(e){if(usesBuiltInRedactPatterns(e))return Ta??=fi.map(parsePattern).filter(e=>!!e),Ta;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(!Ea){Ea=!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(Wr),[...t]}function usesBuiltInRedactPatterns(e){return e===void 0||e===fi||Array.isArray(e)&&e.length===0}function normalizeSensitiveKeyName(e){let t=e.replace(Oa,``);try{return decodeURIComponent(t).replace(Oa,``).toLowerCase().replaceAll(`-`,`_`)}catch{return t.toLowerCase().replaceAll(`-`,`_`)}}function isSensitiveBodyKey(e){return isSensitiveUrlQueryParamName(e)||_a.bodySecretKeys.has(normalizeSensitiveKeyName(e))}function hasEncodedOrInvisibleFormKey(e){return ka.test(e)||e.replace(Da,``)!==e}function visitSensitiveAssignments(e,t,n){if(!e||t===`url`&&!e.includes(`?`)||t===`encoded`&&!e.includes(`%`)&&e.replace(Da,``)===e||t===`context`&&!/[=:]/u.test(e))return;let visitPair=(e,r,i)=>{if(t===`encoded`&&!hasEncodedOrInvisibleFormKey(e)||!isSensitiveBodyKey(e))return;let{maskable:a,maskStart:o,maskEnd:s}=splitSecretValueForMask(r);n(i+o,i+s,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`?Ra:t===`encoded`?Ia:La,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,(o,s,c)=>{let l=t===`url`?maskToken(c):`***`;r.push(e.slice(a,o),l),n&&i.push({start:o,end:s,replacement:l}),a=s}),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(Pa.test(n))return redactAssignmentValues(n,`form`,t);let r=[],i=n.replace(Fa,(e,n,i,a)=>{let o=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 o===i?e:`${n}${o}`});return r.length>0&&t?.(r),redactAssignmentValues(redactAssignmentValues(i,`encoded`,t),`context`,t)}function redactFormBody(e,t){if(!e.includes(`=`))return e;if(za.test(e)){let n=0;return e.split(za).map(e=>{let r=Ba.test(e)?e:redactFormBodyLine(e,t?e=>t(e.map(e=>({...e,start:n+e.start,end:n+e.end}))):void 0);return n+=r.length,r}).join(``)}return redactFormBodyLine(e,t)}function isShellReferenceToKey(e,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(e))return!1;let n=t.match(/^\$([A-Z_][A-Z0-9_]*)$/);return n?n[1]===e:t.match(/^\$\{([A-Z_][A-Z0-9_]*)(?::[-=?+])?\}$/)?.[1]===e}function maskSecretFieldValue(e,t){let n=t.match(/^\$\{([A-Z_][A-Z0-9_]*):[-=?+][^{}]+\}(?![\s\S])/);return n&&n[1]===e?`${t.slice(0,t.indexOf(`:`)+2)}***}`:`***`}function shouldPreserveShellReferenceMatch(e,t){let n=e.match(/\b([A-Z_][A-Z0-9_]*)\b\s*[=:]/)?.[1];return n?isShellReferenceToKey(n,t):!1}function isEmptyShellParameterExpansionTail(e){return/^[-=?+]\}$/.test(e)}function prepareRedactionCapture({match:e,groups:t,input:n,offset:r,replacement:i},a){if(e.includes(`PRIVATE KEY-----`))return{start:r,end:r+e.length,value:e,redact:e=>({start:e.start,end:e.end,value:e.value,replacement:i??redactPemBlock(e.value,`…redacted…`)})};let o=selectSecretCapture(e,t);if(o.value===`***`)return;let s=o.value===e?0:getSecretCaptureStart(a,n,e,r,o);if(s<0)return;let c=r+s;return{start:c,end:c+o.value.length,value:o.value,redact:t=>{let n=t.value,r=wa.has(a)?splitFormAwareCredentialValue(n):{secret:n,suffix:``};if(splitSecretValueForMask(r.secret).maskable===`***`)return;let o=va.has(a);if(o&&(shouldPreserveShellReferenceMatch(e,n)||isEmptyShellParameterExpansionTail(n)))return;let s=i??(o?maskToken(n):`${maskSecretValue(r.secret)}${r.suffix}`);return{start:t.start,end:t.end,replacement:s}}}}function redactMatch(e,t){let n=prepareRedactionCapture(e,t),r=n?.redact(n);return r?e.match.slice(0,r.start-e.offset)+r.replacement+e.match.slice(r.end-e.offset):e.match}function redactText(e,t,n){let r=startRedactionMeasurement(`text`),i=`error`;try{let r=redactFormBody(redactAssignmentValues(redactStructuredAuthHeaders(e,`***`),`url`)),a,replace=e=>redactMatch(e,a),replaceRegex=(...e)=>replace(readRedactMatch(e)),o,s=!1;for(a of t)ba.get(a)?.()&&(o!==r&&(o=r,s=couldMatchVendorRedactPatterns(r)),!s)?a instanceof RegExp&&(a.lastIndex=0):r=a instanceof RegExp&&!n?.fullContext&&!ya.has(a)&&!Sa.has(a)?replacePatternBounded(r,a,replaceRegex):replaceRedactPattern(r,a,replace,replaceRegex);return i=`ok`,r}finally{r?.(i,e.length,t.length)}}function looksLikeAppSpecificPassword(e){return e.split(`-`).every(e=>!Ga.has(e.toLowerCase()))}function redactAppSpecificPasswords(e){return e.includes(`-`)?e.replace(Wa,(e,t)=>looksLikeAppSpecificPassword(t)?maskToken(t):e):e}function resolveConfigRedaction(){let e=readLoggingConfig();return{mode:ga,patterns:e?.redactPatterns}}function resolveRedactOptions(e){let t=e??resolveConfigRedaction(),n=t.mode===`off`?`off`:ga;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,...fi]:t}}function redactToolPayloadText(e){return redactToolPayloadTextWithConfig(e,readLoggingConfig())}function redactToolPayloadTextWithConfig(e,t){return redactSensitiveText(e,resolveToolPayloadRedaction(t))}function isSensitiveFieldKey(e){return Va.test(e)||Ka.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 o=redactRegisteredSecretValues(t,maskToken);if(isPublicShareIdPath(r))return maskToken(o);let s=resolveRedactOptions(n);if(s.mode===`off`)return o;let c=!usesBuiltInRedactPatterns(n.patterns)||a(o)?redactText(o,s.patterns):o;if(c!==t||Ua.test(e)){let e=redactAppSpecificPasswords(c);if(e!==t)return e}return c===t?shouldRedactStructuredStringField(e,o,r,i)?maskToken(o):o:c}function shouldRedactStructuredPrimitiveField(e,t){let n=e.toLowerCase();return isPublicShareIdPath(t)||shouldRedactStructuredAuthorizationCode(n,t)||isSensitiveFieldKey(e)}function isPlainRedactableObject(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function redactStructuredSecretValue(e,t,n,r,i,a=e?[e]:[],o=!0){if(typeof t==`string`)return redactSensitiveFieldValueWithOptions(e,t,r,a,o,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 o=t.map(t=>redactStructuredSecretValue(e,t,n,r,i,a,!1));return n.delete(t),o}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,s]=t;t[1]=redactStructuredSecretValue(e,s,n,r,i,[...a,e],o)}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`&&Ha.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`:_a.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 o=i,receive=e=>{o=composeRedactionEdits(r.length,o,e)},s=findStructuredAuthParamRanges(a).map(({start:e,end:t})=>({start:e,end:t,replacement:`***`}));return receive(s),redactFormBody(redactAssignmentValues(applyRedactionEdits(a,s),`url`,receive),receive),o}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 o=[];if(t!==r||Ua.test(n))for(let e of t.matchAll(Wa))looksLikeAppSpecificPassword(e[0])&&o.push({start:e.index,end:e.index+e[0].length,replacement:maskToken(e[0])});return o.length>0||t!==r?o:classifyLogFieldProtection(n,i,a,t)===`legacy`?[{start:0,end:t.length,replacement:maskToken(t)}]:[]}function*redactionEditMatches(e,t){for(let n of t)yield{match:e.slice(n.start,n.end),groups:[],input:e,offset:n.start,replacement:n.replacement}}function redactLogRecordForTransport(e,t){let n=startRedactionMeasurement(`log-record`),r=`error`,i;try{let n=t?.redaction??resolveRedactOptions(),a={value:{structured:!0,primitiveMask:!1},children:/* @__PURE__ */ new Map},o=[],s=JSON.stringify(e,function(e,t){for(;o.length>0&&o.at(-1)?.value!==this;)o.pop();let n=o.at(-1),r=Array.isArray(this),i=r&&n?n.key:e,s=r&&n?n.path:n?[...n.path,e]:[],c=t,l=(n?.structured??!0)&&(typeof c!=`object`||!c||Array.isArray(c)||isPlainRedactableObject(c)),u=l&&[`number`,`boolean`,`bigint`].includes(typeof c)&&classifyLogFieldProtection(i,s,!r,void 0)===`legacy`,d=typeof t==`object`&&!!t&&o.some(e=>e.value===t),f=d?`[Circular]`:typeof t==`bigint`?String(t):t,p=typeof f==`object`&&!!f,m=a;return n&&n.structured&&(p||!l||u||d)?(m={value:{structured:l&&!d,primitiveMask:u},children:/* @__PURE__ */ new Map},n.origins.children.set(e,m)):n?m=n.origins:a.value={structured:l,primitiveMask:u},p&&o.push({value:f,path:s,key:i,origins:m,structured:l}),f});i=s.length;let c=createRedactPrefilter(couldMatchDefaultFullContextPatterns),l=JSON.parse(redactJsonRecord(s,a,[[{patterns:n.patterns}],[{patterns:qa},{patterns:n.patterns,...n.patterns===Ta?{couldMatch:c}:{}}]],prepareRedactionCapture,t?getLegacyFieldRecordEdits:()=>[],e=>getFieldRecordEdits(e,n.mode),e=>getTextRecordEdits(e,n.mode,t!==void 0),(e,t)=>e.path.length===1&&Ja.has(e.key)||n.patterns===Ta&&!c(t),t?.message));return r=`ok`,l}finally{n?.(r,i)}}var ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya=__esmMin((()=>{et(),ft(),Nt(),Wn(),Yn(),Xn(),sr(),Bi(),Ki(),or(),pi(),ur(),Ji(),ea(),ia(),ha(),ga=`tools`,_a=createBackendRedactPatterns(),va=/* @__PURE__ */ new WeakSet,ya=/* @__PURE__ */ new WeakSet,ba=/* @__PURE__ */ new WeakMap,xa=new Set(di),Sa=/* @__PURE__ */ new WeakSet,Ca=new Set(fi.filter(e=>typeof e==`string`)),wa=/* @__PURE__ */ new WeakSet,Ea=!1,Da=new RegExp(String.raw`[${Cr}+]`,`gu`),Oa=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,ka=/%[0-9A-Fa-f]{2}/u,Aa=String.raw`[${Cr}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${Cr}+])*`,ja=`[^&\\s<>]*`,Ma=`[^&#\\s<>]*`,Na=String.raw`${Aa}=${ja}`,Pa=new RegExp(String.raw`^${Na}(?:&${Na})+$`,`u`),Fa=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`])(${Na}(?:&${Na})+)`,`gu`),Ia=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`&])(${Aa})=(${ja})`,`gu`),La=new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${Aa})=(${ja})(["'\x60]?)`,`giu`),Ra=new RegExp(String.raw`([?&])(${Aa})=(${Ma})`,`gu`),za=/(\r\n|\r|\n)/u,Ba=/^(?:\r\n|\r|\n)$/u,Va=new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${mr}|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|${fr}|${pr})$`,`i`),Ha=/^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u,Ua=/^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i,Wa=/\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g,Ga=/* @__PURE__ */ new Set([`case`,`claw`,`demo`,`file`,`main`,`name`,`open`,`path`,`slug`,`test`]),Ka=new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${dr})$`,`i`),qa=[{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)}}],Ja=/* @__PURE__ */ new Set([`time`,`level`])}));Ge(),Ya(),Zt();function formatErrorMessage(e){return formatErrorMessage$1(e,{redact:redactSensitiveText})}wn(),Qt();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=l.openSync(e,l.constants.O_RDONLY|(l.constants.O_NONBLOCK??0));try{let e=l.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{l.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let r=readGitMetadataFile(e),i=r.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!we(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 l.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=n.join(e,`.git`);try{let e=l.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=l.openSync(e,l.constants.O_RDONLY|(l.constants.O_NONBLOCK??0));try{if(!l.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{l.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)||l.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{}}var Xa=__esmMin((()=>{Ge()})),Za,Qa=__esmMin((()=>{D(),Za=typeof process>`u`?void 0:process.getBuiltinModule?.(`node:async_hooks`),Za&&resolveGlobalSingleton(Symbol.for(`openclaw.detachedAsyncContext`),()=>new Za.AsyncResource(`openclaw.detached-async-context`))}));function enterAsyncStore(e,t){return this.enterWith(e),t()}function runWithAsyncStore(e,t,n){return e.getStore()===t?n():new ae(`OpenClawAsyncStore`).runInAsyncScope(enterAsyncStore,e,t,n)}var $a=__esmMin((()=>{}));function createDeferredCore(){return eo.withResolvers()}var eo,to=__esmMin((()=>{eo=Promise})),no=__esmMin((()=>{Dn()}));function runOutsideAsyncWorkScope(e){return ro.getStore()===void 0?io.getStore()===void 0?e():io.exit(e):runWithAsyncStore(ro,void 0,()=>(io.enterWith(void 0),e()))}var ro,io,ao,oo,so=__esmMin((()=>{Xa(),Qa(),$a(),to(),D(),no(),ro=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScope`),()=>new y),io=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new y),ao=resolveGlobalSingleton(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}}),oo=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=ro.getStore();if(t===this)return e();let n=io.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return runWithAsyncStore(ro,this,()=>(io.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new ao;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 ao);let t=createDeferredCore();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(materializeErrorStack(e),this.failures.add(e))});try{t.resolve(this.enter(e))}catch(e){t.reject(e)}return t.promise}beginClose(e){this.phase===`open`&&(this.phase=`closing`,this.controller.abort(e),materializeErrorStack(this.controller.signal.reason))}runWhenIdle(e){return AsyncWorkScope.runWhenAllIdle(()=>[this],()=>this.track(e))}static async runWhenAllIdle(e,t){let n=e();for(;n.some(e=>e.pending.size>0);)await Promise.allSettled(n.flatMap(e=>Array.from(e.pending))),n=e();return t()}async drain(){for(this.beginClose();this.pending.size>0;)await Promise.allSettled(this.pending);this.phase=`closed`}},resolveGlobalSingleton(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}})}));function appendPluginInstanceCleanupFailures(e,t,n){for(let r of n.errors)e.some(e=>e.pluginId===t&&e.error===r)||e.push({pluginId:t,hookId:`instance`,error:r})}var co=__esmMin((()=>{}));function createPluginCacheSdk(){return{hosts:/* @__PURE__ */ new Map,contexts:/* @__PURE__ */ new Map,roots:/* @__PURE__ */ new Set,packageNames:/* @__PURE__ */ new Map,packageSearches:/* @__PURE__ */ new Map,argvDirectories:/* @__PURE__ */ new Map,devSourceRoots:/* @__PURE__ */ new Map,runtimeModules:/* @__PURE__ */ new Map,normalizedJitiAliases:/* @__PURE__ */ new Map,aliasFacts:/* @__PURE__ */ new WeakMap,native:{sdkProviders:/* @__PURE__ */ new Map,nextSdkProviderOrder:0,parents:/* @__PURE__ */ new Map,aliases:/* @__PURE__ */ new Map,registeredHosts:/* @__PURE__ */ new Set,hostRoots:/* @__PURE__ */ new Map,nearestPackageRoots:/* @__PURE__ */ new Map,loaderPackageRoots:/* @__PURE__ */ new Map,allowedParentRoots:/* @__PURE__ */ new Map}}}var lo=__esmMin((()=>{})),uo,fo=__esmMin((()=>{D(),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`}}),uo=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 po(e)}var po,mo,ho,go=__esmMin((()=>{$a(),D(),po=class InvocationFrame{constructor(e,t=e.invocation){this.retentionOwner=e.retentionOwner,this.invocation=t,this.metadataScope=e.metadataScope,this.cacheScope=e.cacheScope,this.sourceCaptureStorage=e.sourceCaptureStorage}get runtimePluginId(){}withScopes(e){return new InvocationFrame(e)}},mo=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new y;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)}}}),mo.invocation,ho=mo.getFrame,mo.runFrame}));function releasePluginCacheInstance(e,t){let n=yo.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&&yo.delete(e)}function getPluginCacheRetainers(e){let t=vo.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:createDeferredCore()},vo.set(e,t)),t}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:!1,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},snapshots:/* @__PURE__ */ new Map,derivedIndexes:/* @__PURE__ */ new WeakMap,preparedManifests:/* @__PURE__ */ new WeakMap,snapshotManifestFacts:/* @__PURE__ */ new WeakMap,discovery:/* @__PURE__ */ new Map,sharedDiscovery:/* @__PURE__ */ new Map,projections:/* @__PURE__ */ new WeakMap,projectionSources:/* @__PURE__ */ new WeakMap,completions:/* @__PURE__ */ new WeakMap,indexFacts:/* @__PURE__ */ new WeakMap,providerPolicyOwners:/* @__PURE__ */ new WeakMap,channelAdapters:/* @__PURE__ */ new WeakMap,bundledChannelCatalogs:/* @__PURE__ */ new Map,bundledProviderPolicySurfaces:/* @__PURE__ */ new WeakMap,staticCatalogStates:/* @__PURE__ */ new WeakMap,modelSuppressionResolvers:/* @__PURE__ */ new WeakMap,mcpAuthDeclarations:/* @__PURE__ */ new WeakMap}}function createPluginCache(e={}){return{async[Symbol.asyncDispose](){await retirePluginCache(this)},kind:e.kind??`operation`,roots:/* @__PURE__ */ new Map,rootAliases:/* @__PURE__ */ new Map,sdk:createPluginCacheSdk(),setupModules:/* @__PURE__ */ new Map,instances:/* @__PURE__ */ new Set,metadata:createPluginMetadataCache(),installRecords:/* @__PURE__ */ new Map,persistedInstalledIndex:/* @__PURE__ */ new Map,preparedBundledDiscoveryModes:/* @__PURE__ */ new Map,dependencyStatus:/* @__PURE__ */ new WeakMap,moduleLoaders:/* @__PURE__ */ new Map,sources:/* @__PURE__ */ new Map,sourceAliases:/* @__PURE__ */ new Map,runtimeRecordRoots:/* @__PURE__ */ new WeakMap}}function getProcessPluginCache(){return _o.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return ho()?.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 oo;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]),o=await Promise.allSettled([...i].map(async e=>({resource:e,result:await e.dispose(void 0,n)}))),s=e.sourceAdmissions;if(s){let e=o.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof uo?[e.settled]:[]):[]);e.length>0?Promise.allSettled(e).then(()=>s.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`)):await s.dispose()}e.setupModules.clear();for(let t of e.instances)releasePluginCacheInstance(t,e);let c=[...a.status===`rejected`?[a.reason]:[],...o.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(c.length)throw AggregateError(c,`Plugin cache resources failed to retire`);let l=a.status===`fulfilled`?a.value:void 0,u=[...l?.failures??[]];for(let e of o){if(e.status!==`fulfilled`)continue;let{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(u,t.pluginId,n)}return{cleanupCount:l?.cleanupCount??0,failures:u}})().then(r.resolve,r.reject),r.promise}var _o,vo,yo,bo=__esmMin((()=>{Xa(),so(),to(),D(),co(),lo(),fo(),go(),_o=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),vo=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),yo=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap)})),xo=__esmMin((()=>{}));function createRuntimeProcessEntrypoints(e){function runtimeProcessEntrypoint(t,n=t,r=`.js`,i){return{currentModuleUrl:e,sourceModulePath:`src/${t}${i??`.ts`}`,sourceExtension:i,sourceWorkerName:t.startsWith(`infra/`)?t.slice(6):`../${t}`,distWorkerPath:`${n}${r}`}}let loaderFreeEntrypoint=e=>runtimeProcessEntrypoint(e,void 0,void 0,`.mjs`);return{daemonRuntimeProbe:runtimeProcessEntrypoint(`infra/daemon-runtime-probe.entry`),pluginToolsServe:runtimeProcessEntrypoint(`mcp/plugin-tools-serve`),openclawToolsServe:runtimeProcessEntrypoint(`mcp/openclaw-tools-serve`),repositoryPublicationRestore:loaderFreeEntrypoint(`gateway/repository-publication-restore.generated.worker`),nodeWorkspacePublicationSnapshot:loaderFreeEntrypoint(`node-host/node-worker-publication-snapshot.generated.worker`),nodeWorkspaceManifest:loaderFreeEntrypoint(`node-host/node-worker-workspace-manifest.generated.worker`),nodeWorkspaceGitHistory:loaderFreeEntrypoint(`node-host/node-worker-workspace-git-history.generated.worker`),doctorDatabaseEngineInspection:runtimeProcessEntrypoint(`commands/doctor-database-engine-inspection.worker`),backupDatabaseDiscovery:runtimeProcessEntrypoint(`infra/backup-database-discovery.worker`),sqliteHeaderProbe:runtimeProcessEntrypoint(`infra/sqlite-header-probe.worker`),databaseBackup:runtimeProcessEntrypoint(`snapshot/database-backup.worker`),managedHandoffEngine:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-engine.worker`),updatePostgresState:runtimeProcessEntrypoint(`infra/update-candidate-state.postgres.worker`),databasePortCommand:runtimeProcessEntrypoint(`infra/database-engine/port-command.entry.worker`),systemCaWarmup:runtimeProcessEntrypoint(`gateway/system-ca-warmup.worker`),shutdownHardExit:loaderFreeEntrypoint(`cli/gateway-cli/shutdown-hard-exit.worker`),packageIntegrityHasher:runtimeProcessEntrypoint(`infra/package-update-integrity-hasher.worker`),packageLocalOverrides:runtimeProcessEntrypoint(`infra/package-local-overrides.worker`),directoryWatchHost:runtimeProcessEntrypoint(`infra/directory-watch-host.worker`),directoryWatchParent:runtimeProcessEntrypoint(`infra/directory-watch-parent.worker`),workspaceQuiescenceAcquire:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-acquire.generated.worker`),workspaceQuiescenceRenew:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-renew.generated.worker`),workspaceQuiescenceRelease:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-release.generated.worker`),packageActivationRecovery:runtimeProcessEntrypoint(`infra/package-update-activation-sealed`,`package-update-activation-recovery`,`.mjs`),managedHandoffPostgresBridge:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-postgres.worker`,`managed-handoff-postgres-bridge.worker`,`.mjs`),managedHandoffRuntime:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-sealed`,`managed-handoff-runtime`,`.mjs`),sqliteVector:runtimeProcessEntrypoint(`infra/database-engine/sqlite-vector.child`),postgresBridge:runtimeProcessEntrypoint(`infra/postgres-sync/bridge.worker`),secretEgressProxy:runtimeProcessEntrypoint(`secrets/egress-proxy/proxy.worker`),codeModeNode:runtimeProcessEntrypoint(`agents/code-mode-node.worker`),cronReadOnly:runtimeProcessEntrypoint(`cron/store/read-only.worker`),stateRead:runtimeProcessEntrypoint(`state/openclaw-state-read.worker`),workerNativeLifecycle:runtimeProcessEntrypoint(`infra/worker-native-lifecycle.worker`),spawnBroker:runtimeProcessEntrypoint(`process/spawn-broker/worker`),cronStreamMatcher:runtimeProcessEntrypoint(`gateway/cron-stream-matcher.worker`),controlUiFile:runtimeProcessEntrypoint(`gateway/control-ui-file.worker`),publicSessionCard:runtimeProcessEntrypoint(`gateway/control-ui-public-session-card.worker`),nodeBootstrapArtifact:runtimeProcessEntrypoint(`gateway/worker-environments/node-bootstrap-artifact.worker`),nativeHookRelayClient:runtimeProcessEntrypoint(`agents/harness/native-hook-relay-client.worker`),computerHost:runtimeProcessEntrypoint(`gateway/desktop/computer.worker`),imageProcessor:runtimeProcessEntrypoint(`media/image-processor.worker`),fileToolPlanning:runtimeProcessEntrypoint(`agents/sessions/tools/file-tool-planning.worker`),fileToolRead:runtimeProcessEntrypoint(`agents/sessions/tools/read-file.worker`),attachmentProcessor:runtimeProcessEntrypoint(`media/attachment-processor.worker`),widgetScriptSyntax:runtimeProcessEntrypoint(`canvas/widget-script-syntax.worker`),gitOperations:runtimeProcessEntrypoint(`infra/git-operation.worker`),gitPackCleanup:runtimeProcessEntrypoint(`agents/worktrees/git-pack-cleanup.worker`),fsSafeCopy:runtimeProcessEntrypoint(`infra/fs-safe-copy.worker`),sharedStateStore:runtimeProcessEntrypoint(`state/openclaw-state.worker`),clientCredentials:runtimeProcessEntrypoint(`infra/client-credential.worker`),ttsPreferences:runtimeProcessEntrypoint(`tts/tts-settings-write.worker`),authProfileInlineUsage:runtimeProcessEntrypoint(`agents/auth-profiles/inline-usage.worker`),pluginModelCatalogRead:runtimeProcessEntrypoint(`agents/plugin-model-catalog-read.worker`),pluginModelCatalogCredentials:runtimeProcessEntrypoint(`agents/plugin-model-catalog.worker`),pluginCaptureNativeResource:runtimeProcessEntrypoint(`plugins/plugin-capture-native-resource`),pluginGenerationPreparation:runtimeProcessEntrypoint(`plugins/plugin-generation-preparation.worker`),agentDatabaseExecution:runtimeProcessEntrypoint(`state/openclaw-agent-execution.worker`),workspaceMemory:runtimeProcessEntrypoint(`worker/memory-worker-entry`,`agents/workspace-memory.worker`),localAgentAvatar:runtimeProcessEntrypoint(`agents/identity-avatar-file.worker`),identityFile:runtimeProcessEntrypoint(`agents/identity-file.worker`),workspaceSkills:runtimeProcessEntrypoint(`worker/skills-worker-entry`,`agents/workspace-skills.worker`),skillsDiscovery:runtimeProcessEntrypoint(`skills/runtime/discovery.worker`),boardStore:runtimeProcessEntrypoint(`boards/sqlite-board-store.worker`),progressCardStore:runtimeProcessEntrypoint(`session-cards/progress-card-store.worker`),sessionSharingStore:runtimeProcessEntrypoint(`config/sessions/session-sharing-store.worker`),sessionForkDomain:runtimeProcessEntrypoint(`config/sessions/session-fork-domain.worker`),sessionGoalOperations:runtimeProcessEntrypoint(`config/sessions/goals-operations.worker`),sessionLifecyclePlanningDomain:runtimeProcessEntrypoint(`config/sessions/session-lifecycle-projection.worker`),sessionMessageRewriteDomain:runtimeProcessEntrypoint(`config/sessions/session-message-rewrite.worker`),sessionDiskBudget:runtimeProcessEntrypoint(`config/sessions/disk-budget.worker`),contextEngineTurnOutbox:runtimeProcessEntrypoint(`agents/harness/context-engine-turn-outbox.worker`),sqliteStore:runtimeProcessEntrypoint(`infra/sqlite-store.worker`),sqliteWriterAdmission:runtimeProcessEntrypoint(`infra/sqlite-writer-admission.worker`),agentSchemaInspection:runtimeProcessEntrypoint(`state/openclaw-agent-schema-inspection.worker`),stateMigrationSnapshot:runtimeProcessEntrypoint(`infra/state-migrations.snapshot.worker`),githubExec:runtimeProcessEntrypoint(`agents/github-exec-launcher`),shellSnapshotEnvironment:runtimeProcessEntrypoint(`agents/shell-snapshot-env.worker`),sqliteReadOnly:runtimeProcessEntrypoint(`infra/sqlite-readonly-location.worker`),sqliteSnapshotStaging:runtimeProcessEntrypoint(`infra/sqlite-snapshot-staging.worker`),sqliteReadOnlyNativeResource:runtimeProcessEntrypoint(`infra/sqlite-readonly-native-resource`),sqliteSourceRevision:runtimeProcessEntrypoint(`infra/sqlite-source-revision.worker`),sqliteIntegrity:runtimeProcessEntrypoint(`infra/sqlite-integrity.worker`),sqliteCloseProbe:runtimeProcessEntrypoint(`infra/bun-sqlite-close-probe.worker`),preparedModelCatalog:runtimeProcessEntrypoint(`agents/prepared-model-catalog.worker`),providerPromptState:runtimeProcessEntrypoint(`agents/embedded-agent-runner/provider-prompt-state.worker`),retiredWorktreeCleanup:runtimeProcessEntrypoint(`agents/worktrees/retired-worktree-cleanup.worker`),updateNativeGate:runtimeProcessEntrypoint(`cli/update-cli/update-command-native-gate.worker`),updateStateSizes:runtimeProcessEntrypoint(`infra/update-state-sizes.entry`),updateRepair:runtimeProcessEntrypoint(`infra/update-repair.worker`),immutableBuild:runtimeProcessEntrypoint(`infra/update-immutable-build.worker`),updateMigratedFinalize:runtimeProcessEntrypoint(`infra/update-migrated-finalize.worker`),updateAutomaticCleanup:runtimeProcessEntrypoint(`infra/update-automatic-cleanup.worker`),updateCandidateState:runtimeProcessEntrypoint(`infra/update-candidate-state.worker`),doctorLint:runtimeProcessEntrypoint(`commands/doctor-lint.worker`),doctor:runtimeProcessEntrypoint(`commands/doctor.worker`),databaseVerify:runtimeProcessEntrypoint(`state/openclaw-database-verify.worker`),stateOwnership:runtimeProcessEntrypoint(`state/openclaw-state-ownership.worker`),stateLeaseHeartbeat:runtimeProcessEntrypoint(`state/openclaw-state-lease-heartbeat.worker`),gatewayStateOwnerHeartbeat:runtimeProcessEntrypoint(`infra/gateway-state-owner-heartbeat.worker`),sessionTranscriptArchive:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-archive.worker`),sessionTranscript:runtimeProcessEntrypoint(`config/sessions/session-transcript.worker`),usageOverview:runtimeProcessEntrypoint(`infra/session-cost-usage-overview-report.worker`),workerTranscriptCommit:runtimeProcessEntrypoint(`gateway/worker-environments/transcript-commit.worker`),sessionManagerMetadata:runtimeProcessEntrypoint(`agents/sessions/session-manager-metadata.worker`),sessionTranscriptProjectionPublication:runtimeProcessEntrypoint(`config/sessions/session-transcript-projection-publication.worker`),sessionTranscriptReports:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-transcript-reports.worker`),sessionTranscriptReconcile:runtimeProcessEntrypoint(`config/sessions/session-transcript-reconcile.worker`),tailscaleRouteOwner:runtimeProcessEntrypoint(`infra/tailscale-route-owner.worker`),serviceChildRelay:runtimeProcessEntrypoint(`process/supervisor/service-child-relay`),terminalPty:runtimeProcessEntrypoint(`process/terminal-pty-worker`),serviceChildGroupAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-group-anchor`),serviceChildWindowsJobAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-windows-job-anchor`),bunSqliteLibrary:runtimeProcessEntrypoint(`infra/bun-sqlite-library`)}}function pluginRuntimeProcess(e,t,n){return{plugin:e,ownerSource:`extensions/${e}/${t}.ts`,sourceWorkerName:n,distWorkerPath:`extensions/${e}/${n}.js`,package:{name:`@openclaw/${e}`,distWorkerPath:`${n}.js`}}}var So,Co,wo=__esmMin((()=>{So={browserNativeHost:{...pluginRuntimeProcess(`browser`,`native-host-entry`,`native-host-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`native-host-entry.js`}},browserRelayDaemon:{...pluginRuntimeProcess(`browser`,`native-host-entry`,`relay-daemon-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`relay-daemon-entry.js`}},browserSetup:{...pluginRuntimeProcess(`browser`,`setup-entry`,`setup-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`setup-entry.js`}},quickJsCodeMode:{...pluginRuntimeProcess(`code-mode-quickjs`,`src/executor`,`src/code-mode.worker`),sourceWorkerName:`code-mode.worker`},codexStdio:pluginRuntimeProcess(`codex`,`stdio-worker-entrypoint`,`stdio.worker`),codexCatalogPage:pluginRuntimeProcess(`codex`,`catalog-page-worker-entrypoint`,`catalog-page.worker`),codexSessionHistory:pluginRuntimeProcess(`codex`,`session-history-worker-entrypoint`,`session-history.worker`),discordAudio:{...pluginRuntimeProcess(`discord`,`src/voice/audio-worker-thread`,`src/voice/audio-worker.runtime`),sourceWorkerName:`audio-worker.runtime`},documentExtractor:{...pluginRuntimeProcess(`document-extract`,`document-extractor-worker-entrypoint`,`document-extractor.worker`),package:{name:`@openclaw/document-extract-plugin`,distWorkerPath:`document-extractor.worker.js`}},webReadability:{...pluginRuntimeProcess(`web-readability`,`web-content-extractor-worker.runtime`,`web-content-extractor.worker`),package:{name:`@openclaw/web-readability-plugin`,distWorkerPath:`web-content-extractor.worker.js`}},fileTransferDirFetch:{plugin:`file-transfer`,ownerSource:`extensions/file-transfer/src/node-host/dir-fetch-archive.ts`,sourceWorkerName:`dir-fetch-archive.worker`,distWorkerPath:`extensions/file-transfer/src/node-host/dir-fetch-archive.worker.js`,package:{name:`@openclaw/file-transfer`,distWorkerPath:`src/node-host/dir-fetch-archive.worker.js`}},fileTransferDirList:{plugin:`file-transfer`,ownerSource:`extensions/file-transfer/src/node-host/dir-list-worker-command.ts`,sourceWorkerName:`dir-list.worker`,distWorkerPath:`extensions/file-transfer/src/node-host/dir-list.worker.js`,package:{name:`@openclaw/file-transfer`,distWorkerPath:`src/node-host/dir-list.worker.js`}},iMessageChatDb:{...pluginRuntimeProcess(`imessage`,`src/chat-db`,`src/chat-db.worker`),sourceWorkerName:`chat-db.worker`},knowledgeRegistry:{...pluginRuntimeProcess(`knowledge`,`src/registry-client`,`src/registry-worker`),sourceWorkerName:`registry-worker`},knowledgeStorage:{...pluginRuntimeProcess(`knowledge`,`src/storage-client`,`src/storage-worker`),sourceWorkerName:`storage-worker`},mxcLauncher:{plugin:`mxc`,ownerSource:`extensions/mxc/src/plugin-root.ts`,sourceWorkerName:`mxc-spawn-launcher`,sourceExtension:`.mjs`,build:`static-asset`,distWorkerPath:`extensions/mxc/mxc-spawn-launcher.mjs`,package:{name:`@openclaw/mxc-sandbox`,distWorkerPath:`mxc-spawn-launcher.mjs`}},onePasswordSecretResolver:{plugin:`onepassword`,ownerSource:`extensions/onepassword/onepassword-secret-ref-resolver.js`,sourceWorkerName:`onepassword-secret-ref-resolver`,sourceExtension:`.js`,build:`static-asset`,distWorkerPath:`extensions/onepassword/onepassword-secret-ref-resolver.js`,package:{name:`@openclaw/onepassword`,distWorkerPath:`onepassword-secret-ref-resolver.js`}},vaultSecretResolver:{plugin:`vault`,ownerSource:`extensions/vault/vault-secret-ref-resolver.js`,sourceWorkerName:`vault-secret-ref-resolver`,sourceExtension:`.js`,build:`static-asset`,distWorkerPath:`extensions/vault/vault-secret-ref-resolver.js`,package:{name:`@openclaw/vault`,distWorkerPath:`vault-secret-ref-resolver.js`}},memorySearch:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-search.worker`),sourceWorkerName:`manager-search.worker`,distWorkerPath:`extensions/memory-core/memory-search.worker.js`},memoryIndex:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-index.worker`),sourceWorkerName:`manager-index.worker`,distWorkerPath:`extensions/memory-core/memory-index.worker.js`},memoryPublication:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-publication.worker`),sourceWorkerName:`manager-publication.worker`,distWorkerPath:`extensions/memory-core/memory-publication.worker.js`},memoryStandingIntents:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/standing-intents.worker`),sourceWorkerName:`../standing-intents.worker`,distWorkerPath:`extensions/memory-core/standing-intents.worker.js`},memoryEntryOrigins:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory-entry-origins.worker`),sourceWorkerName:`../memory-entry-origins.worker`,distWorkerPath:`extensions/memory-core/memory-entry-origins.worker.js`},memoryStatsRuntime:pluginRuntimeProcess(`memory-lancedb`,`memory-stats-entrypoint`,`memory-stats.worker`),memoryWikiQuery:{...pluginRuntimeProcess(`memory-wiki`,`src/query-reader`,`src/query-reader.worker`),sourceWorkerName:`query-reader.worker`},openAiRealtimeAudio:{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-peer.runtime`,`realtime-quicksilver-audio.worker`),package:{name:`@openclaw/openai-provider`,distWorkerPath:`realtime-quicksilver-audio.worker.js`}},openAiRealtimeSocket:{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-socket`,`realtime-quicksilver-socket.worker`),package:{name:`@openclaw/openai-provider`,distWorkerPath:`realtime-quicksilver-socket.worker.js`}},qaExecutionIdentityInspection:{...pluginRuntimeProcess(`qa-lab`,`src/execution-identity-storage-inspection`,`src/execution-identity-storage-inspection.worker`),sourceWorkerName:`execution-identity-storage-inspection.worker`},telegramIngress:{...pluginRuntimeProcess(`telegram`,`src/telegram-ingress-worker`,`src/telegram-ingress-worker.runtime`),sourceWorkerName:`telegram-ingress-worker.runtime`,distWorkerPath:`telegram-ingress-worker.runtime.js`},telegramWidgetCheck:{...pluginRuntimeProcess(`telegram`,`src/widgets/widget-check`,`src/widgets/widget-check.worker`),sourceWorkerName:`widget-check.worker`},onnxInference:pluginRuntimeProcess(`onnx`,`index`,`src/inference.worker`),teamReportsStore:pluginRuntimeProcess(`team-reports`,`index`,`src/store.worker`),teamReportsRun:pluginRuntimeProcess(`team-reports`,`index`,`src/run.worker`),logbookStore:pluginRuntimeProcess(`logbook`,`index`,`src/store.worker`),workboardSqlite:pluginRuntimeProcess(`workboard`,`index`,`src/sqlite-store.worker`)},Co={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 fe.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(h.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,o=[];try{let e=h.realpathSync(a);e!==a&&o.push(n.dirname(e))}catch{}o.push(n.dirname(a));let s=a.split(n.sep),c=s.lastIndexOf(`.bin`);if(c>0&&s[c-1]===`node_modules`){let e=n.basename(a),t=s.slice(0,c).join(n.sep);o.push(n.join(t,e))}let l=dedupeCandidates(o);return t.set(r,l),[...l]}function preparePackageRootSearch(e,t){let n=buildCandidates(e),r=n.join(`\0`),i=getPluginCache().sdk.packageSearches,a=i.get(r);return{candidates:n,first:a?.all?a.all[0]??null:a?.first,complete(e){return i.set(r,t?{...i.get(r),first:e}:{first:e}),e}}}async function resolveOpenClawPackageRoot(e){e.signal?.throwIfAborted();let t=preparePackageRootSearch(e,!0);if(t.first!==void 0)return t.first;for(let n of t.candidates){let r=await findPackageRoot(n,e.signal);if(r)return t.complete(r)}return t.complete(null)}function resolveOpenClawPackageRootSync(e){let t=preparePackageRootSearch(e,!1);if(t.first!==void 0)return t.first;for(let e of t.candidates){let n=findPackageRootSync(e);if(n)return t.complete(n)}return t.complete(null)}function buildCandidates(e){let t=[];if(e.moduleUrl)try{t.push(n.dirname(s(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 To=__esmMin((()=>{bo(),xo(),wo()}));T(),Ye(),vn(),To();const formatCommit=e=>{let t=e?.match(/[0-9a-fA-F]{7,40}/);return t?normalizeLowercaseStringOrEmpty(t[0].slice(0,7)):null},Eo=new LruCache(256),resolveCommitSearchDir=e=>{if(e.cwd)return n.resolve(e.cwd);if(e.moduleUrl)try{return n.dirname(s(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(Eo.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=s(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=Eo.get(i);if(a!==void 0)return a;let o=resolveOpenClawPackageRootSync({cwd:e.cwd,moduleUrl:e.moduleUrl});try{let e=readCommitFromGit(i,o);if(e!==void 0)return cacheGitCommit(i,e)}catch{}let s=readCommitFromBuildInfo();if(s)return cacheGitCommit(i,s);let c=readCommitFromPackageJson();return c?cacheGitCommit(i,c):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}Ye();const Do=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],Oo=[`../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,Do,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,Oo,`version`)}function readBuildProvenanceForModuleUrl(e){try{let n=t(e);for(let e of Oo)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 ko=resolveLoadedCommitHash({moduleUrl:import.meta.url});function resolveRuntimeServiceCommit(){return ko}const Ao=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 jo=__esmMin((()=>{}));jo();const Mo=Symbol.for(`openclaw.postgres-sync-connection`);function isPostgresSqlConnection(e){return Mo in e&&e[Mo]===!0}function sqlPublicationAnchor(e){return isPostgresSqlConnection(e)?e.anchor:e}D();const{kyselyByDatabase:No,queryErrorHandlerByDatabase:Po}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap})),Fo=Symbol.for(`openclaw.kyselySyncStatementCache`),Io=Symbol.for(`openclaw.kyselySyncStatementInvalidation`),Lo=Symbol.for(`openclaw.kyselySyncStatementCacheEnabled`),Ro=Symbol.for(`openclaw.kyselySyncAuthorizerActive`),zo=Symbol.for(`openclaw.sqliteDisposeCallbacks`),Bo=Symbol.for(`openclaw.sqliteDisposeGuards`),Vo=65536;function disposeSqliteStatement(e){e[Symbol.dispose]?.()}function clearStatementCache(e){let t=e[Fo];if(delete e[Fo],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[zo]??=/* @__PURE__ */ new Set,t)}function assertNodeSqliteDisposalAllowed(e){for(let t of e[Bo]??[])t()}function disposeNodeSqliteDependents(e,t=`close`){assertNodeSqliteDisposalAllowed(e);for(let n of e[zo]??[])n(t)}function clearNodeSqliteKyselyCacheForDatabase(e){clearStatementCache(e),No.delete(e),Po.delete(e)}function installStatementInvalidation(e){if(!e[Io]){if(typeof e.setAuthorizer==`function`){let t=e.setAuthorizer.bind(e);Object.defineProperty(e,"setAuthorizer",{configurable:!0,writable:!0,value(e){t(e),this[Ro]=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,Io,{configurable:!0,value:!0})}}function queryFitsStatementCache(e,t){let n=Buffer.byteLength(e);if(n>Vo)return!1;for(let e of t){if(typeof e==`string`){if(e.length>Vo-n)return!1;n+=Buffer.byteLength(e)}else ArrayBuffer.isView(e)&&(n+=e.byteLength);if(n>Vo)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[Lo]||a[Ro]||!queryFitsStatementCache(t,n)){let n=e.prepare(t);return executeLeased(n,()=>disposeSqliteStatement(n))}let o=a[Fo];o||(o={statements:/* @__PURE__ */ new Map,candidates:/* @__PURE__ */ new Set,active:/* @__PURE__ */ new WeakSet},Object.defineProperty(a,Fo,{configurable:!0,value:o}));let s=o.statements.get(t),c;if(s&&!o.active.has(s))o.statements.delete(t),o.statements.set(t,s),c=s;else if(c=e.prepare(t),!s&&o.candidates.delete(t)){if(o.statements.set(t,c),o.statements.size>64){let e=o.statements.entries().next().value;o.statements.delete(e[0]),o.active.has(e[1])||disposeSqliteStatement(e[1])}}else if(!s&&(o.candidates.add(t),o.candidates.size>64)){let e=o.candidates.values().next().value;e!==void 0&&o.candidates.delete(e)}return o.active.add(c),executeLeased(c,()=>{o.active.delete(c),(a[Fo]!==o||o.statements.get(t)!==c)&&disposeSqliteStatement(c)})}const Ho={"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 Ho[this.kind]}};To();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 ${Ao} (${e})`:`OpenClaw ${Ao}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,Ao)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){let o=isNewerSqliteWriterVersion(i),s=o?`; it is newer than this Gateway (${Ao}).`: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!==Ao)?`It was written by OpenClaw ${i}${s}\n`:``)+`Refused by ${describeRunningOpenClawBuild()}.\n`+(o?`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.`)}const Uo=Symbol.for(`openclaw.workerTaskNativeSection`),Wo=globalThis,Go=Wo[Uo]??=new y;function assertWorkerTaskActive(e,t){if(!t()||e&1)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+2)===n)break}let n=!1;return()=>{n||(n=!0,Atomics.sub(e,0,2),Atomics.notify(e,0))}}function withWorkerTaskNativeSectionScope(e,t,n){return Go.run(()=>acquireWorkerNativeSection(e,t),n)}function observeWorkerTaskCancellation(e,t,n){let r=!0,i=(async()=>{for(;;){if(!r||!t())return;let i=Atomics.load(e,0);if(i&1){n();return}await Atomics.waitAsync(e,0,i).value}})();return()=>(r=!1,Atomics.notify(e,0),i)}function createWorkerTaskControl(e,t){let throwIfCancelled=()=>assertWorkerTaskActive(Atomics.load(e,0),t);return{throwIfCancelled,runNativeSection:async n=>{let r=acquireWorkerNativeSection(e,t),i;try{i=await n()}finally{r()}return throwIfCancelled(),i}}}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(!be)return;let r=be,i=r,a=!1,o=!1;n.initialize(i);let s,c=Promise.resolve(),l=Promise.resolve(),u;i.on(`message`,function receive(d){if(o){d.resourcePort?.close();return}if(!a){a=!0;let e=n.selectStartupPort?.(d);if(e){i.off(`message`,receive),i=e,n.initialize(i),i.on(`message`,receive),n.onReady?.();return}}if(n.onMessage(d.sampleMemory===!0),d.closeResource&&d.resourcePort){let e=d.resourcePort,r=c;l=l.then(()=>r).then(async()=>{if(o)throw Error(`Worker is retiring after a terminal task failure`);await t.closeResource(d.key),e.postMessage({ok:!0},[])}).catch(n=>{e.postMessage({ok:!1,error:n instanceof Error?n.message:String(n),detail:t.encodeResourceError?.(n)},[])}).finally(()=>{e.close(),!s&&!o&&n.onIdle()});return}if(d.responseId!==void 0){if(d.taskId===u?.taskId&&d.responseId===u.responseId)return;if(!s||d.taskId!==s.taskId||d.responseId!==s.responseId||!s.pending)throw Error(`stale worker task response`);try{s.assertCurrent()}catch(e){s.cancelPending(e);return}let e=s.pending;s.pending=void 0;let t=!1,n=d.taskId,r=d.responseId,a=s.progressSignal;e.resolve({input:d.input,consumed:()=>{t||(t=!0,postTaskMessage(i,{status:`consumed`,taskId:n,id:r},a))}});return}if(s)throw Error(`overlapping worker tasks`);let f=new Int32Array(d.nativeSections),p={taskId:d.taskId,responseId:0,progressSignal:d.progressSignal,assertCurrent:()=>m.throwIfCancelled(),cancelPending:e=>{let t=p.pending;t&&(p.pending=void 0,u={taskId:p.taskId,responseId:p.responseId},t.reject(e))}},m=createWorkerTaskControl(f,()=>s===p);s=p;let h=d.interactive?observeWorkerTaskCancellation(f,()=>s===p,()=>p.cancelPending(/* @__PURE__ */ Error(`worker task cancelled`))):void 0,g=d.interactive?{notify:e=>{m.throwIfCancelled(),postTaskMessage(i,{status:`notification`,taskId:p.taskId,value:e},p.progressSignal)},consumeInput:()=>postTaskMessage(i,{status:`consumed`,taskId:p.taskId,id:0},p.progressSignal),request:(e,t)=>{if(m.throwIfCancelled(),s!==p||p.pending)throw Error(`closed or busy worker channel`);let n=Promise.withResolvers();p.pending=n;try{let n=t?[...t]:[];m.throwIfCancelled(),postTaskMessage(i,{status:`request`,taskId:p.taskId,id:++p.responseId,value:e},p.progressSignal,n)}catch(e){p.pending=void 0,n.reject(e)}return n.promise}}:void 0,_=l;c=Promise.resolve().then(async()=>{try{return await _,m.throwIfCancelled(),n.installTaskContext(d.taskContext),await withWorkerTaskNativeSectionScope(f,()=>s===p,()=>e(d.input,g,m))}finally{await h?.(),s=void 0}}).then(e=>{postTaskMessage(i,{status:`ok`,value:e,taskId:p.taskId,...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},p.progressSignal,t.transferList?.(e)??[])}).catch(e=>{t.retireOnError?o=!0:postTaskMessage(i,{status:`failed`,taskId:p.taskId,error:e instanceof Error?e.message:String(e),...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},p.progressSignal)}).finally(()=>{o?(async()=>{try{await l}finally{try{await n.onRetire?.()}finally{process.exitCode=1;try{i.close()}finally{i!==r&&r.close()}}}})().catch(()=>{process.exitCode=1}):n.onIdle()})}),n.onReady?.()}C&&process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED===`gateway`&&(delete process.env.NODE_DISABLE_COMPILE_CACHE,delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED);const Ko=36e5,qo=3e4,Jo=/^(?:[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`};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())}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||!Jo.test(n.basename(e)))return;let i=Date.now(),a=await x.lstat(t).catch(()=>void 0);for(let r of[t,n.dirname(e),e]){let e=r===t?a:await x.lstat(r).catch(()=>void 0);if(e&&!e.isDirectory())return}if(a&&i-a.mtimeMs<Ko)return;await x.mkdir(t,{recursive:!0});let o=`${t}.maintenance`,s=await x.lstat(o).catch(()=>void 0);if(s&&i-s.mtimeMs>3e5&&await x.rmdir(o).catch(()=>{}),!await x.mkdir(o).then(()=>!0,()=>!1))return;let c=[],l=0,u=0,d=!1;async function prune(){for(c.sort((e,t)=>t.mtimeMs-e.mtimeMs);c.length;){if(Date.now()-i>qo)return!1;let e=c[c.length-1];if(l<=536870912&&c.length<=4096&&i-e.mtimeMs<=6048e5)break;await x.unlink(e.file).catch(e=>{if(e.code!==`ENOENT`)throw e}),l-=e.size,c.pop()}return!0}async function visit(e){for await(let t of await x.opendir(e)){if(++u>16384||Date.now()-i>qo)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 x.lstat(r).catch(e=>{if(e.code!==`ENOENT`)throw e});if(!e)continue;if(l+=e.size,c.push({file:r,size:e.size,mtimeMs:e.mtimeMs}),c.length%256==0&&!await prune())return!1}}return!0}try{if(i-(await x.lstat(t)).mtimeMs<Ko){d=!0;return}let e=await visit(t);if(await prune()&&e){let e=/* @__PURE__ */ new Date;await x.utimes(t,e,e),d=!0}}finally{d||await x.utimes(t,a?.atime??/* @__PURE__ */ new Date(0),a?.mtime??/* @__PURE__ */ new Date(0)).catch(()=>{}),await x.rmdir(o)}}process.argv[2]===`--maintain`&&process.argv[1]===s(import.meta.url)&&process.argv[3]&&maintain(process.argv[3]).catch(()=>{}),T(),D(),Xa();const Yo=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseReaders`),()=>({closers:/* @__PURE__ */ new Set,deleted:/* @__PURE__ */ new Map}));function installDeletedAgentDatabaseFences(e){Yo.deleted.clear();for(let[t,n]of e)Yo.deleted.set(t,n)}async function applyAgentDatabaseReaderRequest(e){if(e.kind===`revive`){for(let[t,n]of Yo.deleted)e.agentIds.includes(n)&&Yo.deleted.delete(t);return}if(e.deleted)for(let t of e.candidates)Yo.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([...Yo.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}}}D(),resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineSelection`),()=>({}));const Xo=resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineMaintenanceSelection`),()=>new y);function withDatabaseEngineSelection(e,t){return Xo.run(e,t)}D();const Zo=Ce,Qo=resolveGlobalSingleton(Symbol.for(`openclaw.postgresIoPool`),()=>({endpoints:Zo?.postgresPool,workers:void 0,nextStep:void 0,ready:[],refresh:void 0,failure:void 0}));function postgresPoolWorkerFailure(){return Qo.failure}function bindPostgresPool(e){if(Qo.endpoints){if(Qo.endpoints===e)return;for(let{port:t}of e.services)t.close()}else Qo.endpoints=e}const $o=`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}Zt(),Sn();const es=process.platform!==`linux`&&process.platform!==`android`;function databaseFileIdentityKey(e){return`${e.dev}:${e.ino}`}function readDatabaseIdentityBirthtime(e){return es?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(!b(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 de(e,{bigint:!0}).catch(e=>{if(!b(e,`ENOENT`))throw e});if(t){if(!t.isFile())return;try{let n=await le(e);return existingIdentity(t,await de(n,{bigint:!0}),n)}catch(e){throw b(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 le(r),...t))}catch(e){r=missingAncestorParent(r,t,e)}}function isSoleDatabaseFileDescriptor(e,t,n){if(process.platform!==`linux`)return!1;try{for(let r of m(`/proc/self/fd`))if(/^\d+$/u.test(r)&&Number(r)!==e&&!n?.has(Number(r)))try{let e=d(Number(r),{bigint:!0});if(e.dev===t.dev&&e.ino===t.ino)return!1}catch(e){if(!b(e,`EBADF`))return!1}return!0}catch{return!1}}D();function readSqliteDatabaseAdmissionIdentity(e){return`${e.dev}:${e.ino}:${readDatabaseIdentityBirthtime(e)}`}const k={schemaRevision:0,factRevision:1,publicationRevision:2,retired:3,writeRevision:4,hostRevision:5,unscopedWriteRevision:6,writeScopeRevision:7,sealPresent:8},ts=Object.keys(k).length,ns=Symbol.for(`openclaw.sqliteDatabaseAdmission.decodedValue`);function readSqliteDatabaseAdmissionFact(e,t){return e[ns]??={value:t.read?t.read(e.value):e.value},e[ns].value}function admitSqliteDatabaseFactValue(e,t){let n={value:t};return readSqliteDatabaseAdmissionFact(n,e),n}const rs=1048576,is=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseWriteScopeRetention`),()=>/* @__PURE__ */ new WeakMap),writeScopeBytes=e=>e.length*2+256;function retainSqliteDatabaseWriteScope(e,t,n){let r=e.writeScopes,i=is.get(r);i||(i={bytes:[...r.keys()].reduce((e,t)=>e+writeScopeBytes(t),0),retired:/* @__PURE__ */ new Set},is.set(r,i)),r.delete(t)||(i.bytes+=writeScopeBytes(t)),r.set(t,n),pruneSqliteDatabaseWriteScopes(e)}function pruneSqliteDatabaseWriteScopes(e){let t=is.get(e.writeScopes);if(t.bytes<=rs)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<=rs))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),k[t])}function advanceSqliteDatabaseGeneration(e,t){return Atomics.add(new Int32Array(e.generation),k[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 o=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);return Atomics.store(new Int32Array(o),0,1),e.facts.set(t.name,{...n,revision:r,schemaDependent:t.schemaDependent===!0,lifetime:t.lifetime,publication:i,current:o}),advanceSqliteDatabaseGeneration(e,`publicationRevision`),!0}const as=Array.from({length:128},()=>/* @__PURE__ */ new Map);function snapshotWriteScopes(e,t=as,n){let r=t,i=is.get(e),visit=(n,a)=>{let o=0;for(let e=0;e<a.length;e++)o=o*31+a.charCodeAt(e)|0;let s=o&as.length-1,c=!n||Atomics.load(n.state,1)!==0;c&&e.delete(a)&&i&&(i.bytes-=writeScopeBytes(a)),!(c?!t[s].has(a):t[s].get(a)===n)&&(r===t&&(r=t.slice()),r[s]===t[s]&&(r[s]=new Map(t[s])),c?r[s].delete(a):r[s].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 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(w);return n||(n=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),e.references.set(w,n)),Atomics.add(new Int32Array(n),0,t)+t===+(t===1)&&(t===-1&&this.retireUnreferenced(e),this.publish(e),!0)}retireUnreferenced(e){if(w!==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),k.retired,0,2),e.writeScopes.clear()}releaseWorker(e){let t=/* @__PURE__ */ new Map;for(let n of this.records.values()){let r=e>0?n.references.get(e):void 0;r&&(Atomics.store(new Int32Array(r),0,-1),this.retireUnreferenced(n),t.set(n,void 0))}t.size>0&&this.publish(t)}observeLocation(e,t){let r=normalizeDatabasePath(n.resolve(e));t===void 0?this.locations.delete(r):this.locations.set(r,t)}forLocation(e){let t=this.locations.get(normalizeDatabasePath(n.resolve(e))),r=t===void 0?void 0:this.records.get(t);return r&&!isSqliteDatabaseAdmissionRetired(r)?r:void 0}hasSchemaAdmissionForIdentity(e){if(!e.key.startsWith(`file:`)||e.birthtime===void 0)return!1;let t=`${e.key.slice(5)}:${e.birthtime}`;return hasSqliteDatabaseSchemaAdmission(this.records.get(t))}forget(e){this.records.delete(e),this.published.delete(e);for(let[t,n]of this.locations)n===e&&this.locations.delete(t)}retainDescriptorCustody(e,t){let n=readSqliteDatabaseAdmissionIdentity(t),r=this.descriptors.get(n);r&&r.descriptor!==e&&(r.additionalDescriptors??=/* @__PURE__ */ new Set).add(e),r||this.descriptors.set(n,{descriptor:e,file:t,facts:/* @__PURE__ */ new Map})}retainDescriptor(e,t,n){let r=this.descriptors.get(readSqliteDatabaseAdmissionIdentity(n)),i={identity:readSqliteDatabaseAdmissionIdentity(n),physicalIdentity:{key:`file:${n.dev}:${n.ino}`,birthtime:readDatabaseIdentityBirthtime(n)},location:e,descriptor:t,descriptorOwner:0,generationId:_(),generation:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*ts),writeScopes:/* @__PURE__ */ new Map,writeScopeRevision:0,references:/* @__PURE__ */ new Map,facts:new Map([...r?.facts??[]].filter(([,e])=>Atomics.load(new Int32Array(e.current),0)===1).map(([e,t])=>[e,{...t,revision:0}]))};this.records.set(i.identity,i);let a=r?.descriptor===t?r:{descriptor:t,file:n,facts:/* @__PURE__ */ new Map};return a.file=n,a.facts=/* @__PURE__ */ new Map,this.descriptors.set(i.identity,a),this.observeLocation(e,i.identity),this.publish(i),i}retireDescriptor(e,t){let n=this.records.get(e),r=this.descriptors.get(e),i=r?.descriptor??n?.descriptor;if(i===void 0)return!1;let a=l.fstatSync(i,{bigint:!0});return a.nlink>1n||t.requireSoleDescriptor&&!isSoleDatabaseFileDescriptor(i,a,r?.additionalDescriptors)?!1:(n&&Atomics.store(new Int32Array(n.generation),k.retired,1),l.closeSync(i),r?.additionalDescriptors?.forEach(e=>l.closeSync(e)),this.descriptors.delete(e),this.forget(e),this.publish(),!0)}publish(e,t){let n=e instanceof Map;if(!e||n||this.records.get(e.identity)===e){for(let r of this.records.values()){if(isSqliteDatabaseAdmissionRetired(r)){readSqliteDatabaseGeneration(r,`retired`)===1&&(this.descriptors.get(r.identity)?.additionalDescriptors?.forEach(l.closeSync),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),o=readSqliteDatabaseGeneration(r,`writeScopeRevision`),s=a&&e?n?e.get(r):t:void 0,c=s===void 0&&this.scopeSweeps.get(r)!==o,u=snapshotWriteScopes(r.writeScopes,a?.writeScopes,s??(c?void 0:[]));if(c&&this.scopeSweeps.set(r,o),i||=u!==a?.writeScopes,!i)continue;w===0&&(r.writeScopeRevision=readSqliteDatabaseGeneration(r,`writeScopeRevision`));let{writeScopes:d,...f}=r,p={...f,facts:new Map(r.facts),references:new Map(r.references),hostRevision:w===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++,Se($o,[...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||w===0&&t&&Atomics.load(t.state,1)===0)){if(w===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`);(w===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);w!==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}};D();const A=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 y,exchanging:!1,publication:0}));function installSqliteDatabaseAdmissions(e){A.registry.install(e)}function exchangeSqliteDatabaseAdmission(e,t,n=!1,r){let i=A.exchange.getStore();if(i&&!A.exchanging){A.exchanging=!0;try{let a=typeof e==`string`?{location:e}:{admissions:[e]},o=A.registry.captureExchange(a,e);if(n&&o.length===0)return;installSqliteDatabaseAdmissions(i(o,typeof e==`string`?e:void 0,t,r))}catch(e){throw A.registry.resetExchangeCursor(),e}finally{A.exchanging=!1}}}function withSqliteDatabaseAdmissionExchange(e,t){return A.exchange.run(e,t)}const os=readSqliteDatabaseAdmissions(ye($o));os&&(installSqliteDatabaseAdmissions(os),A.registry.captureExchange()),D();var 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 StateDatabaseAccessError{constructor(e){super(`Internal state ownership error at ${e}: this process holds maintenance ownership without an active schema lease or maintenance scope. Retry the command; if it persists, report this error.`),this.name=`StateDatabaseMaintenanceScopeError`}});const ss=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseAdmissionPendingError`),()=>class extends StateDatabaseAccessError{constructor(e,t){super(t),this.databasePath=e}});resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseOfflineMaintenanceError`),()=>class extends StateDatabaseAccessError{constructor(e,t){super(t),this.databasePath=e}});var cs,AsyncContext,ls=__esmMin((()=>{D(),cs=resolveGlobalSingleton(Symbol.for(`openclaw.asyncContext`),()=>new y),AsyncContext=class{constructor(e){this.key=e}getStore(){return cs.getStore()?.[this.key]}run(e,t){let n=cs.getStore(),r=n?.[this.key];if(Object.is(r,e))return t();let i={...n,[this.key]:e};cs.enterWith(i);try{return t()}finally{let e=cs.getStore();cs.enterWith(e===i?n:{...e,[this.key]:r})}}exit(e){return this.run(void 0,e)}enterWith(e){cs.enterWith({...cs.getStore(),[this.key]:e})}}}));ls(),D();const us=new AsyncContext(Symbol.for(`openclaw.sqliteReaderOwners`)),ds=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteReaderConnections`),()=>({nextId:0,byDatabase:/* @__PURE__ */ new WeakMap,byPath:/* @__PURE__ */ new Map,finalizer:new FinalizationRegistry(e=>forgetConnection(e))}));function sqliteReaderDatabasePathKey(e){let t=n.resolve(e);return process.platform===`win32`?se(t):t}function boundedOperation(e){return(e.trim()||`sqlite reader`).slice(0,120)}function currentSqliteOperationTiming(){return us.getStore()?.timing}function currentOwner(e,t){let n=t??us.getStore();return{operation:boundedOperation(n?.operation??e),ownerKind:n?.ownerKind??(C?`main`:`worker`),...n?.actorId===void 0?{}:{actorId:n.actorId}}}function connectionFor(e){let t=ds.byDatabase.get(e);if(!t){let n=Date.now(),r=e.location();t={id:++ds.nextId,path:r?sqliteReaderDatabasePathKey(r):void 0,database:new WeakRef(e),owner:currentOwner(`sqlite connection`),openedAtMs:n,readers:/* @__PURE__ */ new Map},ds.byDatabase.set(e,t),ds.finalizer.register(e,t,t)}if(t.path){let e=ds.byPath.get(t.path)??/* @__PURE__ */ new Map;e.set(t.id,t),ds.byPath.set(t.path,e)}return t}function forgetConnection(e){if(e.path){let t=ds.byPath.get(e.path);t?.delete(e.id),t?.size===0&&ds.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:w,startedAtMs:i,lastProgressAtMs:i},o=Symbol(a.operation),s=r.readers;return s.set(o,a),{progress(){s.has(o)&&(a.lastProgressAtMs=Date.now())},release(){s.delete(o)}}}Ge();const fs=Symbol.for(`openclaw.sqliteWorkerErrorCode`);var SqliteWorkerError=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`SqliteWorkerError`,Object.defineProperty(this,fs,{value:t})}};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=>De(t,e))===t);return Object.assign(t===void 0?Error(e):new SqliteWorkerError(e,t),{cause:r.length>1?AggregateError(r,e):r[0]})}D();const ps=process.hrtime;function readSqliteWorkerMonotonicNs(){return ps.bigint()}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`}}),D();var SqliteDatabaseAdmissionTimeoutError=class extends SqliteWorkerError{constructor(){super(`SQLite admission facts exchange timed out; the host did not reply`,`unavailable`)}};const ms=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionWait`),()=>new y);function withSqliteDatabaseAdmissionWait(e,t){let n={wait:e,parent:ms.getStore(),active:!0},close=()=>{n.active=!1},r=!1;try{let e=ms.run(n,t);return Ee(e)&&(r=!0,e.then(close,close)),e}finally{r||close()}}function readSqliteDatabaseAdmissionDeadline(){let e;for(let t=ms.getStore();t;t=t.parent){if(!t.active)continue;let n=t.wait.deadlineAtMs;n!==void 0&&(e=Math.min(e??1/0,n))}return e}function assertSqliteDatabaseAdmissionWaitActive(){try{for(let e=ms.getStore();e;e=e.parent)e.active&&e.wait.assertActive?.()}catch(e){throw wrapSqliteWorkerError(`SQLite admission facts exchange cancelled by its caller`,`unavailable`,e)}}const hs=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionUpstream`),()=>({}));function bindSqliteDatabaseAdmissionUpstream(e){let t=hs.connection;if(t){if(t.port!==e)throw new SqliteWorkerError(`SQLite admission upstream changed owner`,`closed`);return}let n={port:e,closed:!1};hs.connection=n,e.once(`close`,()=>{n.closed=!0}),e.unref()}function exchangeSqliteDatabaseAdmissions(e,t,n,r){return exchangeDatabaseAdmissions(e,t,n,r)}function exchangeDatabaseAdmissions(e,t,n,r){let{port1:i,port2:a}=new ge,o=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),s=currentSqliteOperationTiming(),c=Date.now(),l=readSqliteDatabaseAdmissionDeadline(),u=l===void 0?6e5:Math.max(0,l-Date.now()),d=readSqliteWorkerMonotonicNs()+BigInt(Math.ceil(u))*1000000n,remaining=()=>{assertSqliteDatabaseAdmissionWaitActive();let e=Number(d-readSqliteWorkerMonotonicNs())/1e6;if(e<=0)throw new SqliteDatabaseAdmissionTimeoutError;return e};try{for(remaining(),e.postMessage({kind:`sqlite-database-admissions`,admissions:t,location:n,create:r,deadlineAtMs:l,port:a,decision:o.buffer},[a]);Atomics.load(o,0)===0;){let e=remaining();Atomics.wait(o,0,0,ms.getStore()?Math.min(100,e):e)}remaining();let s=Atomics.load(o,0);if(s===4&&n&&r===!0)throw new ss(n,`OpenClaw state at ${n} is undergoing schema admission; retry when it finishes.`);if(s!==1)throw new SqliteWorkerError(`SQLite admission facts exchange failed`,`unavailable`);let c=readSqliteDatabaseAdmissions(xe(i)?.message);if(!c)throw new SqliteWorkerError(`SQLite admission facts reply is unavailable`,`unavailable`);return c}finally{Atomics.compareExchange(o,0,0,2),s&&(s.databaseAdmissionWaitMs+=Date.now()-c),i.close(),a.close()}}const gs=33554432;let _s={heapUsed:0,external:0},vs,ys,bs=!1;function hasIdleGarbageGrowth(){let e=process.memoryUsage();return e.heapUsed>_s.heapUsed+gs||e.external>_s.external+gs}async function collectWorkerIdleGarbage(){if(ys=void 0,hasIdleGarbageGrowth()){bs=!0;try{if(!vs){let e=new Ae;e.connect(),vs=e}await vs.post(`HeapProfiler.collectGarbage`),_s=process.memoryUsage()}catch(e){e instanceof Error&&e.message.startsWith(`Inspector error -32601:`)?vs=null:process.emitWarning(e instanceof Error?e:String(e))}finally{bs=!1}}}function scheduleWorkerIdleGc(){C||vs===null||ys||bs||hasIdleGarbageGrowth()&&(ys=setTimeout(()=>{collectWorkerIdleGarbage()},1e3).unref())}function cancelWorkerIdleGc(){clearTimeout(ys),ys=void 0}const xs={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},Ss=/* @__PURE__ */ new Set;let Cs,ws,Ts;function getOldGenerationAfterGcBytes(){return Ts}function drain(e){let t=Cs?.stop();e&&Cs?.start();let n=[];for(let e of t?.statistics??[]){let t=xs[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,Ts=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(Ts+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of Ss)e(n)}function flushGcSamples(){Cs&&drain(!0)}function observeGcSamples(e){if(!process.versions.bun)return Cs?drain(!0):(Cs=new Me,Cs.start(),ws=setInterval(()=>drain(!0),1e3).unref()),Ss.add(e),()=>{if(!Ss.has(e))return;let t=Ss.size===1;drain(!t),Ss.delete(e),t&&(clearInterval(ws),ws=void 0,Cs=void 0,Ts=void 0)}}const Es=`${process.execArgv.join(` `)} ${process.env.NODE_OPTIONS??``}`;C&&!process.versions.bun&&/--max[-_](?:old[-_]space[-_]size(?:[-_]percentage)?|heap[-_]size)(?:=|\s)/u.test(Es)&&(/--(?:freeze[-_]flags[-_]after[-_]init|(?:abort|exit)[-_]on[-_]contradictory[-_]flags)(?:=(?:true|1))?(?:\s|$)/u.test(Es)?process.emitWarning(`V8 startup flags prevent enforcing per-worker heap limits.`):Fe(`--max-old-space-size=0 --max-heap-size=0`));var Ds=__esmMin((()=>{Qa(),D(),resolveGlobalSingleton(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new y}))})),Os,ks=__esmMin((()=>{wo(),Os={managedHandoff:{ownerSource:`src/infra/update-managed-service-handoff-sealed.ts`,entries:[[`postgresBridge`,`managedHandoffPostgresBridge`]]},worker:{ownerSource:`src/worker/worker-deploy-runtime.ts`,entries:[[`clientCredentials`,`client-credential.worker`],[`codeModeNode`,`code-mode-node.worker`],[`stateRead`,`openclaw-state-read.worker`],[`workerNativeLifecycle`,`worker-native-lifecycle.worker`],[`fileToolPlanning`,`file-tool-planning.worker`],[`fileToolRead`,`file-tool-read.worker`],[`gatewayStateOwnerHeartbeat`,`gateway-state-owner-heartbeat.worker`],[`githubExec`,`github-exec-launcher`],[`imageProcessor`,`image-processor.worker`],[`serviceChildRelay`,`service-child-relay`],[`sqliteSourceRevision`,`sqlite-source-revision.worker`],[`sqliteStore`,`sqlite-store.worker`],[`sharedStateStore`,`sqlite-store.worker`]]},serviceChildRelay:{ownerSource:`src/process/supervisor/service-child-relay.ts`,entries:[[`serviceChildGroupAnchor`,`service-child-group-anchor`]]}}}));function normalizeDiagnosticWorkerScript(e){return typeof e==`string`&&Ms.has(e)?e:`other`}var scriptBasename,As,js,Ms,Ns=__esmMin((()=>{wo(),ks(),scriptBasename=e=>r(e).replace(/\.[cm]?[jt]s$/u,`.js`),As=createRuntimeProcessEntrypoints(import.meta.url),js=/* @__PURE__ */ new Map;for(let e of Object.values(As)){let t=scriptBasename(e.distWorkerPath);js.set(t,t),js.set(scriptBasename(e.sourceModulePath),t)}for(let e of Object.values(So)){let t=scriptBasename(e.distWorkerPath);js.set(t,t),js.set(scriptBasename(e.package.distWorkerPath),t),js.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(let e of Object.values(Os))for(let[t,n]of e.entries){let e=scriptBasename(`${n}.mjs`);js.has(e)||js.set(e,scriptBasename(As[t].distWorkerPath))}Ms=new Set(js.values())}));Ds(),Ns();const Ps=/* @__PURE__ */ `admit,audit.events.list,audit.writer.process,audit.writer.prune,database.domain.bind,database.domain.close,database.domain.publish,database.prepareWrite,database.walMaintenance,stateLease.acquire,stateLease.release,stateLease.renew,stateLease.verify,worktrees.assertPredicates,worktrees.delete,worktrees.slotCount,worktrees.pendingSlots,worktrees.reservePending,worktrees.releasePending,worktrees.insert,worktrees.update,worktrees.claimRemoval,worktrees.finalizeRemoval,worktrees.abortRemoval,worktrees.findLiveByOwner,worktrees.get,worktrees.sessionBinding,worktrees.findLiveByPath,worktrees.list,worktrees.liveIds,worktrees.provisionedPaths,worktrees.provisionedState,worktrees.provisionedChunk,worktrees.writeProvisionedSnapshot,worktrees.retireMissing,worktrees.deferCleanup,worktrees.admitRunLease,worktrees.releaseRunLease,worktrees.reapRunLeases,worktrees.reserveCapacity,worktrees.recoverPending,worktrees.templates.read,worktrees.templates.has,worktrees.templates.list,worktrees.templates.reserve,worktrees.templates.ready,worktrees.templates.delete,worktrees.templates.retainReader,worktrees.templates.releaseReader,worktrees.templates.hasReaders`.split(`,`),Fs=/* @__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(`.`),Is=/* @__PURE__ */ new Set([...Ps,...Fs]),Ls=/* @__PURE__ */ new Set(/* @__PURE__ */ `devicePairing.lookup,devicePairing.list,devicePairing.updateMetadata,devicePairing.updatePresence,devicePairing.verifyToken,devicePairing.ensureToken,session.actor.read,session.actor.acceptInput,session.actor.adoptRun,session.actor.appendToolResult,session.actor.appendTranscriptEvent,session.actor.completeTurn,session.actor.deliveryPending,session.actor.deliverySettled,session.actor.patch,session.entry.read,session.entry.patch.prepare,session.entry.patch.commit,session.entry.replacements.prepare,session.entry.replacements.commit,session.lifecycle.project,session.maintenance.metadata,session.maintenance.prepare,session.maintenance.finalize,session.maintenance.size,session.rowTranscript.backfill,usageCache.writeRollup,usageCache.writeQuarters,usageCache.prune,trajectory.events.append,trajectory.retention.begin,trajectory.retention.delete,session.pendingInputs.read,session.pendingInputs.mutate,session.turn.prepare,session.turn.commit,transcript.prepare,transcript.commit`.split(`,`)),Rs=/* @__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`]]),zs=[[`pluginState.`,`plugin_state`],[`session.history.`,`transcript_read`],[`trajectory.`,`transcripts`],[`session.transcript.`,`transcripts`],[`transcripts.`,`transcripts`],[`session.`,`sessions`],[`cron.`,`cron`]],Bs=/* @__PURE__ */ new Set([...Ls,...Rs.values(),...Is,...zs.map(([,e])=>e),`task`,`open`,`close`,`execute`,`domain_execute`,`auth_profiles`]);function normalizeWorkerRequestClass(e){return e!==void 0&&Bs.has(e)?e:`other`}T(),D();const Vs=resolveGlobalSingleton(Symbol.for(`openclaw.workerMessageMetrics`),()=>/* @__PURE__ */ new Map);function recordWorkerMessage(e,t,n,r){if(!C)return;let i=Vs.get(e);i||(i={},Vs.set(e,i));let a=i[t]??={kind:e,direction:t,messages:0,payloadBytes:0,unmeasuredMessages:0};if(a.messages++,n===void 0)a.unmeasuredMessages++;else if(a.payloadBytes+=n,e===`sqlite_request`||e===`sqlite_reply`||e===`authority`){let e=a.payloadBytesByRequestClass??={},t=normalizeWorkerRequestClass(r);e[t]=(e[t]??0)+n}}function messageData(e){return isRecord(e)&&!ke.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(!C)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(!ke.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){C&&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}function collectPostgresBridgeCounters(e,t,n){let r=/* @__PURE__ */ new Map([[w,{threadId:w,count:e,selfRootCount:n}]]);for(let e of t)for(let t of e.postgresBridgeCounters??[])r.set(t.threadId,t);return[...r.values()]}function jsonUtf8BytesOrInfinity(e){try{let t=JSON.stringify(e);return typeof t==`string`?Buffer.byteLength(t,`utf8`):1/0}catch{return 1/0}}function jsonStringByteLengthUpToLimit(e,t){return e.length+2>t||e.length*3+2>t&&Buffer.byteLength(e,`utf8`)+2>t?t+1:jsonUtf8BytesOrInfinity(e)}function boundedJsonUtf8Bytes(e,t){let n=0,r,add=e=>{if(n+=e,n>t)throw Error(`json_byte_limit_exceeded`)},visit=(e,i)=>{if(e===null){add(4);return}switch(typeof e){case`string`:add(jsonStringByteLengthUpToLimit(e,t-n));return;case`number`:add(jsonUtf8BytesOrInfinity(Number.isFinite(e)?e:null));return;case`boolean`:add(e?4:5);return;case`undefined`:case`function`:case`symbol`:i&&add(4);return;case`bigint`:throw Error(`json_byte_length_unsupported`)}let a=e;if((r??=/* @__PURE__ */ new WeakSet).has(a))throw Error(`json_byte_length_circular`);if(typeof a.toJSON==`function`&&!(a instanceof Date))throw Error(`json_byte_length_custom_to_json`);r.add(a);try{if(a instanceof Date){visit(a.toJSON(),i);return}let e=Array.isArray(a);if(add(1),e)for(let e=0;e<a.length;e+=1)e>0&&add(1),visit(a[e],!0);else{let e=!1,r=a;for(let i in r){if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=r[i];a!==void 0&&typeof a!=`function`&&typeof a!=`symbol`&&(e&&add(1),e=!0,add(jsonStringByteLengthUpToLimit(i,t-n)),add(1),visit(a,!1))}}add(1)}finally{r.delete(a)}};try{return visit(e,!1),{bytes:n,complete:!0}}catch{return{bytes:Math.max(n,t+1),complete:!1}}}var Hs=__esmMin((()=>{})),Us,Ws,Gs,Ks=__esmMin((()=>{Us=Symbol.for(`openclaw.cliRespawnParent`),Ws=`OPENCLAW_CLI_RESPAWN_PARENT`,Gs=process.env[Ws],delete process.env[Ws],Gs===String(process.ppid)&&(globalThis[Us]={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 qs=__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),o=n.join(a,`manifest.json`),s;try{s=p(o,`utf8`)}catch(e){if(e?.code===`ENOENT`||e?.code===`ENOTDIR`)return;throw e}let c;try{c=JSON.parse(s)}catch(e){throw Error(`Invalid standalone runtime manifest: ${o}`,{cause:e})}let nonBlank=e=>typeof e==`string`&&e.trim().length>0;if(c?.schemaVersion!==1||![`jit`,`bytecode`,`aot`].includes(c.mode)||!nonBlank(c.executable?.path)||!nonBlank(c.runtime?.path)||!nonBlank(c.openclaw?.version)||!nonBlank(c.bun?.version))throw Error(`Invalid standalone runtime manifest: ${o}`);let l=n.relative(a,n.resolve(a,c.executable.path)),u=n.relative(a,n.resolve(a,c.runtime.path));if(n.isAbsolute(c.executable.path)||!l||l===`..`||l.startsWith(`..${n.sep}`)||e&&n.resolve(a,c.executable.path)!==n.resolve(e)||t&&n.resolve(a,c.runtime.path)!==n.resolve(t)||n.isAbsolute(c.runtime.path)||!u||u===`..`||u.startsWith(`..${n.sep}`))throw Error(`Invalid standalone runtime manifest: ${o}`);return{schemaVersion:1,mode:c.mode,executable:{path:c.executable.path,...nonBlank(c.executable.sha256)?{sha256:c.executable.sha256}:{}},runtime:{path:c.runtime.path,...nonBlank(c.runtime.sha256)?{sha256:c.runtime.sha256}:{}},openclaw:{version:c.openclaw.version,...nonBlank(c.openclaw.commit)?{commit:c.openclaw.commit}:{}},bun:{version:c.bun.version},...r?projectStandaloneBuildInfo(c):{}}}function getEmbeddedStandaloneRuntimeRoot(){let e=globalThis.__openclawStandaloneRootUrl;return typeof e==`string`?s(e):void 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 Js=__esmMin((()=>{Ks()})),Ys=__esmMin((()=>{Js(),D(),resolveGlobalSingleton(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=ye(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return Se(e,n),new Int32Array(n)})})),Xs=__esmMin((()=>{Js(),Ys()}));function assertProfile(e){if(!e)throw new ProfileFailure(`invalid-profile`)}function createInspectorProfileCapture(e,t){let n=new e.Session;return n.connect(),{setup:()=>t.setup(n),start:()=>t.start(n),stop:()=>t.stop(n),close:async()=>{let e=!1;try{await t.disable(n),e=!0}catch{}if(n.disconnect(),!e)throw new ProfileFailure(`cleanup-failed`)}}}function hasProfilerConflict(){let e=parseNodeOptionsEnvVar(process.env.NODE_OPTIONS);return e===null||!!process.env.NODE_V8_COVERAGE||!!(process.versions.bun&&(process.env.BUN_INSPECT||process.env.BUN_INSPECT_CONNECT_TO))||[...process.execArgv,...e??[]].some(e=>/^--(?:inspect|cpu-prof|heap-prof|prof|perf-|.*coverage)/.test(e.replaceAll(`_`,`-`)))}function codeUrl(e,t){if(/^node:[a-zA-Z0-9_./-]+$/.test(e))return e;if(e.length>2048||/[?#]/.test(e))return;let r=e;if(e.startsWith(`file:`))try{r=s(e)}catch{return}if(!n.isAbsolute(r))return;let i=t?n.relative(t,r).split(n.sep).join(`/`):``,a=(t&&!i.startsWith(`..`)?`/${i}`:n.normalize(r).split(n.sep).join(`/`)).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===``&&Zs.has(e.functionName),i=n?.startsWith(`node_modules/`)?`[dep:${n.slice(13)}]`:e.scriptId===`0`&&e.url===``&&e.lineNumber<0&&!r?`[native]`:void 0,a=r||n!==void 0&&e.functionName.length<=256&&/^(?:(?:(?:get|set) )?[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*)?$/.test(e.functionName);return{redacted:!a&&!i,callFrame:{functionName:i??(a?e.functionName:`[redacted]`),scriptId:e.scriptId,url:n??``,lineNumber:e.lineNumber,columnNumber:e.columnNumber}}}async function captureDiagnosticProfile(e){let unavailable=(e,t=!1)=>({status:`unavailable`,reason:e,cleanupFailed:t});if(Qs)return unavailable(`busy`);Qs=!0;let t,n=!1,r=!1,i,a=!1,o,s,c,l=0,u=0,d=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=!C&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(a())throw new ProfileFailure(`tracing-active`)};if(d=await resolveOpenClawPackageRoot({moduleUrl:import.meta.url}),assertActive(),i.url()||hasProfilerConflict())throw new ProfileFailure(`conflict`);assertTracingInactive(),t=e.create(i),await t.setup?.(),assertActive(),assertTracingInactive(),s={...process.memoryUsage(),heapSpaces:je.getHeapSpaceStatistics()};let f=performance.now();n=!0;let p=t.start();u=performance.now()-f,await p,e.durationMs>0&&await Re(e.durationMs,void 0,{signal:e.signal}),assertActive(),r=!0;let m=await t.stop();if(!m)throw new ProfileFailure(`capture-failed`);({profile:o}=m),l=performance.now()-f,c={...process.memoryUsage(),heapSpaces:je.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 Qs=!1,unavailable(i??`cleanup-failed`,a);try{assertActive();let t=await e.sanitize(o,d,{durationMs:l,startBlockedMs:u,before:s,after:c});return assertActive(),{status:`complete`,result:t}}catch(e){return unavailable(e instanceof ProfileFailure?e.reason:`invalid-profile`)}finally{Qs=!1}}var Zs,Qs,ProfileFailure,$s=__esmMin((()=>{qs(),To(),Zs=/* @__PURE__ */ new Set([`(root)`,`(program)`,`(idle)`,`(garbage collector)`,`(GC)`,`(PARSER)`,`(COMPILER)`,`(BYTECODE_COMPILER)`,`(V8 API)`,`(EXTERNAL)`,`(LOGGING)`,`(IDLE_EXTERNAL)`,`(IDLE)`,`(JS)`,`(deopt)`]),Qs=!1,ProfileFailure=class extends Error{constructor(e){super(e),this.reason=e}}}));function sanitizeDiagnosticCpuProfile(e,t,{startBlockedMs:n}){if(assertProfile(e.samples!==void 0&&e.timeDeltas!==void 0),e.nodes.length>nc||e.samples.length>rc)throw new ProfileFailure(`profile-too-large`);let r=0,i=e.nodes.map(e=>{let{callFrame:n,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);return r+=Number(i||e.deoptReason!==void 0),{id:e.id,callFrame:n,...e.children===void 0?{}:{children:e.children},...e.hitCount===void 0?{}:{hitCount:e.hitCount},...e.positionTicks===void 0?{}:{positionTicks:e.positionTicks},...e.deoptReason===void 0?{}:{deoptReason:`[redacted]`}}}),a={requestedDurationMs:ec,actualDurationMs:(e.endTime-e.startTime)/1e3,startBlockedMs:n,samplingIntervalMicros:tc,sampleLossCount:null,redactedNodeCount:r,profile:{nodes:i,startTime:e.startTime,endTime:e.endTime,samples:e.samples,timeDeltas:e.timeDeltas}};if(boundedJsonUtf8Bytes(a,1048576).complete)return a;let o=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=o.get(e);for(;r&&n.length<ic;)n.push(r.callFrame),r=o.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=o.get(s.get(r.id));r&&(n.push(r.callFrame),i=e)}let a=JSON.stringify({stack:n,elidedFrameCount:i}),c=l.get(a);c?c.sampleCount+=t:l.set(a,{stack:n,elidedFrameCount:i,sampleCount:t})}let u=[],d={...a,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===ac||f+t>1048576)break;d.summary.push(e),d.omittedSampleCount-=e.sampleCount,f+=t}return d}var ec,tc,nc,rc,ic,ac,oc=__esmMin((()=>{Hs(),Xs(),$s(),ec=5e3,tc=1e4,nc=16384,rc=65536,ic=8,ac=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 Le());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=[],o=0,s=0;for(;o<r.length||s<i.length;)a.push(s===i.length||o<r.length&&compare(r[o],i[s])<=0?r[o++]:i[s++]),a.length%2048==0&&await Le();e.push(a)}t=e}return t[0]??[]}async function sanitizeDiagnosticHeapProfile(e,t,n){let r=e.samples,i=/* @__PURE__ */ new Map,a=[{source:e.head}],o=0,s=0;for(let{source:e,parent:n}of a){++s%1024==0&&await Le();let{callFrame:r,redacted:c}=sanitizeDiagnosticProfileFrame(e.callFrame,t);o+=Number(c);let l={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]},u={node:l,parent:n,totalBytes:l.selfSize,count:0,frameId:0};i.set(l.id,u),n?.node.children.push(l);for(let t of e.children)a.push({source:t,parent:u}),++s%1024==0&&await Le()}a.length=0;let c=[],l=0,u=0;for(let e of r){++s%1024==0&&await Le();let t=i.get(e.nodeId);t?(t.count++,c.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})):(l++,u+=e.size)}let d=[...i.values()];i.clear();for(let e=d.length-1;e>=0;e--){++s%1024==0&&await Le();let t=d[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let f={...n,redactedNodeCount:o,unattributedSampleCount:l,unattributedSampleBytes:u},p={...f,truncated:l>0,profile:{head:d[0].node,samples:c}};if(boundedJsonUtf8Bytes(p,1048576).complete)return p;let m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=[];for(let e of d){++s%1024==0&&await Le();let t=JSON.stringify(e.node.callFrame),n=m.get(t);n===void 0&&(n=m.size,m.set(t,n)),e.frameId=n;let{totalBytes:r,count:i}=e;if(r===0)continue;let a=e.node.selfSize,o=[e.node.callFrame];g.length=0,g.push(n);for(let t=e.parent;t&&o.length<8;t=t.parent)o.push(t.node.callFrame),g.push(t.frameId);let c=g.join(`,`),l=h.get(c);l?(l.selfBytes+=a,l.totalBytes+=r,l.count+=i):h.set(c,{stack:o,selfBytes:a,totalBytes:r,count:i})}m.clear(),d.length=0;let _={...f,truncated:!0,summary:[]},v=Buffer.byteLength(JSON.stringify(_));for(let e of await sortAllocationSummaries(h.values())){++s%1024==0&&await Le();let t=Buffer.byteLength(JSON.stringify(e))+Number(_.summary.length>0);if(v+t>1048576)break;_.summary.push(e),v+=t}return _}var sc=__esmMin((()=>{Hs(),Xs(),$s()}));function clearActiveProgressLine(){cc?.isTTY&&cc.write(`\r\x1B[2K`)}var cc,lc=__esmMin((()=>{cc=null}));function isVerbose(){return uc}var uc,dc=__esmMin((()=>{uc=!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?fc.trustedInterest:fc.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}var fc,pc=__esmMin((()=>{D(),fc=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}))})),j,mc,hc,gc,_c=__esmMin((()=>{j={priority:!1,publicExcluded:!1},mc=[{...j,name:`worker.request`},{...j,name:`diagnostic.gc`,publicExcluded:!0},{...j,name:`gateway.event_loop.sample`,publicExcluded:!0},{...j,name:`gateway.main_thread.stall`,publicExcluded:!0},{...j,name:`gateway.http.cancelled`,publicExcluded:!0},{...j,name:`gateway.rpc`,publicExcluded:!0},{...j,name:`sessions.list.baseline.retired`},{...j,name:`sessions.list.retention`,publicExcluded:!0},{...j,name:`sessions.event.retention`,publicExcluded:!0},{...j,name:`sessions.event.rows.reset`,publicExcluded:!0},{...j,name:`gateway.ws.event`,publicExcluded:!0},{...j,name:`gateway.ws.connections`,publicExcluded:!0},{...j,name:`tool.execution.started`},{...j,name:`tool.execution.completed`,priority:!0},{...j,name:`tool.execution.error`,priority:!0},{...j,name:`tool.execution.blocked`,priority:!0},{...j,name:`skill.used`},{...j,name:`exec.process.completed`},{...j,name:`exec.approval.followup_suppressed`},{...j,name:`message.delivery.started`},{...j,name:`message.delivery.completed`},{...j,name:`message.delivery.error`},{...j,name:`talk.event`},{...j,name:`model.call.started`},{...j,name:`model.call.completed`,priority:!0},{...j,name:`model.call.error`,priority:!0},{...j,name:`model.response.observed`},{...j,name:`run.progress`},{...j,name:`run.execution_phase`},{...j,name:`agent.commentary`},{...j,name:`harness.run.completed`,priority:!0},{...j,name:`harness.run.error`,priority:!0},{...j,name:`context.assembled`},{...j,name:`log.record`,publicExcluded:!0}],hc=mc.map(e=>e.name),gc=mc.filter(e=>e.priority).map(e=>e.name),mc.filter(e=>e.publicExcluded).map(e=>e.name)}));function isNonZeroHex(e){return!/^0+$/.test(e)}function isValidDiagnosticTraceId(e){return typeof e==`string`&&vc.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&yc.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&bc.test(e)}function getActiveDiagnosticTraceContext(){return Sc.getStore()}var vc,yc,bc,xc,Sc,Cc=__esmMin((()=>{Ot(),ls(),vc=/^[0-9a-f]{32}$/,yc=/^[0-9a-f]{16}$/,bc=/^[0-9a-f]{2}$/,xc=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`),Sc=new AsyncContext(xc)}));function cloneDiagnosticValueForListener(e,t=!1){if(wc.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return wc.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&wc.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return wc.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(wc.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 wc,Tc=__esmMin((()=>{pc(),Cc(),It(),wc=/* @__PURE__ */ new WeakSet})),Ec,Dc=__esmMin((()=>{Ec=`coreModelRequestLifecycle`}));function isTrustedOtelDiagnosticListener(e){return Oc.has(e)}var Oc,kc=__esmMin((()=>{Oc=/* @__PURE__ */ new WeakSet})),Ac,jc=__esmMin((()=>{Ac=`coreSemanticRunProgress`})),Mc,Nc=__esmMin((()=>{ls(),D(),Mc=`toolExecutionLiveness`,resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new AsyncContext(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}))}));function hasDiagnosticTracePropagationConsumer(){return Fc.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=Fc.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=Fc.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 Pc,Fc,Ic=__esmMin((()=>{D(),Cc(),Pc=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),Fc=resolveGlobalSingleton(Pc,()=>({marker:Pc,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}))})),Lc=__esmMin((()=>{St()}));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 Rc=__esmMin((()=>{})),zc,Bc=__esmMin((()=>{zc=[`FS_SAFE_PYTHON_MODE`,`OPENCLAW_FS_SAFE_PYTHON_MODE`],[...zc]})),Vc=__esmMin((()=>{Bc()}));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:Hc,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`}var Hc,Uc,Wc=__esmMin((()=>{Lc(),D(),Cc(),Vc(),Hc=`openclaw.diagnostics.v1`,Uc=65536,new y,new y,resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e,t,n,r=!1,a=!1,o=/* @__PURE__ */ new Set;function append(e,t){try{let n=i(e.path);o.has(n)||(f(n,{recursive:!0}),o.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,o){e?.path!==i&&(flush(),e={path:i,id:_(),sequence:0,failedWrites:0});let s=serializeTimelineEvent({...a,attributes:{...a.attributes,captureId:e.id,sequence:++e.sequence,failedWrites:e.failedWrites}},o),c=Buffer.byteLength(s,`utf8`);t&&t.bytes+c>Uc&&flush(),r||c>Uc?append(e,s):(t?(t.content+=s,t.bytes+=c):t={capture:e,content:s,bytes:c},n??=setImmediate(flush).unref())}}})}));function areDiagnosticsEnabledForProcess(){return Zc.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),o=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,s]of e.trustedListeners)if(isInternalDiagnosticEventInterested(s,t.type,n.trusted))try{let e=a(),t=isTrustedOtelDiagnosticListener(r),c=Gc;if(s?.includePrivateData!==!1&&(c=o?.()??Gc,t&&(i.hostPluginId||Object.hasOwn(c,`hostPluginId`)))){let e={...c,hostPluginId:i.hostPluginId};i.hostPluginId||Reflect.deleteProperty(e,`hostPluginId`),c=Object.freeze(e)}r(e,n,c)}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&&Xc.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,qc);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:Kc,drainBatchSize:qc}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=Zc,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 o=enrichDiagnosticEvent(r,i??e,!n.queuedPhase);if(t&&o.type===`diagnostic.gc`){switch(o.kind){case`scavenge`:case`mark_sweep_compact`:case`incremental`:case`weak_processing`:break;default:o.kind=void 0}switch(o.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:o.reason=`other`}o.thread=o.thread===void 0||o.thread===`main`?`main`:normalizeDiagnosticWorkerScript(o.thread),(o.thread!==`code-mode-node.worker.js`||typeof o.workerSlot!=`number`||!Number.isInteger(o.workerSlot)||o.workerSlot<1||o.workerSlot>64)&&(o.workerSlot=void 0)}let{hostPluginId:s,internal:c=!1,privateData:l}=n,u=n.trustedTraceContext===!0,d=Object.freeze({...c?{internal:!0}:{},trusted:t,...n.toolExecutionLiveness?{[Mc]:n.toolExecutionLiveness}:{},...n.coreModelRequestLifecycle?{[Ec]:n.coreModelRequestLifecycle}:{},...n.coreSemanticRunProgress?{[Ac]:n.coreSemanticRunProgress}:{},...u?{trustedTraceContext:u}:{}}),f=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(o),p=a&&(n.queuedPhase||Yc.has(o.type));if(p){if(r.asyncQueue.length>=Kc){if(!t||!Xc.has(o.type)){noteAsyncDiagnosticDrop(r,{event:o,metadata:d,privateData:l,hostPluginId:s});return}let e=makeRoomForPriorityAsyncDiagnosticEvent(r);e&&noteAsyncDiagnosticDrop(r,e)}let e={event:o,metadata:d,privateData:l,hostPluginId:s};if(!captureQueuedDiagnosticEvent(e,r.trustedListeners.values()))return;o=e.event,r.asyncQueue.push(e)}f&&(p||(o=cloneDiagnosticValueForListener(o,!0)),prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o),d)),p?scheduleAsyncDiagnosticDrain(r):a&&dispatchDiagnosticEvent(r,o,d,l,{hostPluginId:s})}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})}var Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc=__esmMin((()=>{Ge(),go(),D(),pc(),_c(),Tc(),Dc(),kc(),jc(),Nc(),Cc(),Ic(),Wc(),Gc=Object.freeze({}),Kc=1e4,qc=100,Jc=Symbol.for(`openclaw.diagnosticEvents.state.v1`),Yc=new Set(hc),Xc=new Set(gc),Zc=resolveGlobalSingleton(Jc,()=>({marker:Jc,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}))})),$c=__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 el=__esmMin((()=>{lc(),$c(),Hn(),{...createRuntimeIo()}})),tl=__esmMin((()=>{D(),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=nl.get(e);if(t!==void 0)return t;let n;try{new Intl.DateTimeFormat(`en`,{timeZone:e}).format(),n=!0}catch{n=!1}return nl.set(e,n),n}function resolveEffectiveTimeZone(e){let t=e??process.env.TZ;return t&&isValidTimeZone(t)?t:il??=Intl.DateTimeFormat().resolvedOptions().timeZone}function getTimestampParts(e,t){let n=resolveEffectiveTimeZone(t),r=Math.floor(e.getTime()/1e3);if(al?.second===r&&al.timeZone===n)return al.parts;let i=rl.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`}),rl.set(n,i));let a={};for(let t of i.formatToParts(e))a[t.type]=t.value;return al={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),o=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}.${o}${a}`;case`long`:return`${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}.${o}${a}`}throw Error(`Unsupported timestamp style`)}var nl,rl,il,al,ol=__esmMin((()=>{nl=/* @__PURE__ */ new Map,rl=/* @__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(O.overrideSettings?.consoleStyle??readLoggingConfig()?.consoleStyle)===`json`?formatJsonConsoleLine(e):e.message}var sl=__esmMin((()=>{Wn(),Ya(),Hn(),ol()}));function tryParseLogLevel(e){if(typeof e!=`string`)return;let t=e.trim();return cl.includes(t)?t:void 0}function normalizeLogLevel(e,t=`info`){return tryParseLogLevel(e)??t}function levelToMinLevel(e){return ll[e]}function isLogLevelEnabled(e,t){return e!==`silent`&&t!==`silent`&&levelToMinLevel(e)>=levelToMinLevel(t)}var cl,ll,ul=__esmMin((()=>{cl=[`silent`,`fatal`,`error`,`warn`,`info`,`debug`,`trace`],ll={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){O.invalidEnvLogLevelValue=null;return}let t=tryParseLogLevel(e);if(t)return O.invalidEnvLogLevelValue=null,t;if(O.invalidEnvLogLevelValue!==e){O.invalidEnvLogLevelValue=e;let t=`[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${redactToolPayloadText(e)}" (allowed: ${cl.join(`|`)}).`;process.stderr.write(`${formatConsoleDiagnosticLine({level:`warn`,message:t})}\n`)}}var dl=__esmMin((()=>{Ye(),sl(),ul(),Ya(),Hn()}));function loadResolveSecureTempRoot(){if(pl)return pl;let e=getSealedRuntimeSecureTempRoot();if(e)return pl=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 pl=process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@openclaw/fs-safe/secure-temp-root`).resolveSecureTempRoot,pl}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,o=t.lstatSync?n.resolve(e):i.realpathSync.native(e);for(let e=n.dirname(o);;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 o=resolveStateDir();try{let i=t({...r,preferredDir:void 0,tmpdir:()=>n.join(o,`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(o)}: ${String(e)}`,{cause:e})}}var fl,pl,ml=__esmMin((()=>{bn(),Rt(),fl=`/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 hl=__esmMin((()=>{}));function ensureLogDirectorySync(e,t=!0,r=511){try{l.mkdirSync(e,{mode:r})}catch(i){let a=extractErrorCode(i);if(a===`EEXIST`&&l.statSync(e).isDirectory())return;let o=n.dirname(e);if(!t||a!==`ENOENT`||o===e)throw i;ensureLogDirectorySync(o,!0,r),ensureLogDirectorySync(e,!1,r)}}var gl=__esmMin((()=>{Ge()}));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 _l,vl,yl=__esmMin((()=>{_l=`openclaw`,vl=`.log`}));function encodeLogProfileSegment(e){let t=``;for(let n of e)/^[a-z0-9]$/u.test(n)?t+=n:n===`-`?t+=`--`:n===`_`?t+=`-0`:/^[A-Z]$/u.test(n)?t+=`-1${n.toLowerCase()}`:t+=`-2${n.codePointAt(0)?.toString(16)??`0`}-`;return t}function resolveLogProfileSegment(){let e=process.env.OPENCLAW_PROFILE?.trim();if(!e||e.toLowerCase()==="default")return null;let t=encodeLogProfileSegment(e);return t.length<=xl?t:`-3${g(`sha256`).update(e).digest(`hex`)}`}function resolveDefaultRollingLogFile(e){let t=/* @__PURE__ */ new Date,r=fl;if(canUseNodeFs()){let t=resolveStateDir();r=n.join(t,`logs`),e?.prepare!==!1&&(ensureLogDirectorySync(t,!0,448),r=resolvePreferredOpenClawTmpDir({preferredDir:r,tmpdir:()=>n.join(t,`tmp`)}))}let i=resolveLogProfileSegment(),a=i?`-${i}`:``;return n.join(r,`${_l}${a}-${formatLocalDate(t)}${vl}`)}function isLegacyRollingLogFilePath(e){let t=n.basename(e);return t===`openclaw-YYYY-MM-DD.log`||bl.exec(t)?.[1]===`openclaw`}function resolveRollingLogFilePathForDate(e,t){let r=bl.exec(n.basename(e));return r?n.join(n.dirname(e),`${r[1]}-${formatLocalDate(t)}${vl}`):isLegacyRollingLogFilePath(e)?n.join(n.dirname(e),`${_l}-${formatLocalDate(t)}${vl}`):e}var bl,xl,Sl=__esmMin((()=>{bn(),ml(),gl(),yl(),bl=/^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u,xl=220}));function rotatedLogPath(e,t){let r=n.extname(e);return`${e.slice(0,e.length-r.length)}.${t}${r}`}function rotateLogFile(e){try{ensureLogDirectorySync(n.dirname(e)),l.rmSync(rotatedLogPath(e,Tl),{force:!0});for(let t=4;t>=1;--t){let n=rotatedLogPath(e,t);l.existsSync(n)&&l.renameSync(n,rotatedLogPath(e,t+1))}return l.existsSync(e)&&l.renameSync(e,rotatedLogPath(e,1)),!0}catch{return!1}}async function getCurrentLogFileBytes(e){try{return(await x.stat(e)).size}catch{return 0}}function getCurrentLogFileBytesSync(e){try{return l.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?l.writeSync(process.stderr.fd,n):process.stderr.write(n),!0}catch{return!1}}function warnAboutRotationFailure(e,t){Il.get(e.file)!==e.maxFileBytes&&(Il.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(Ll.has(e.file))return;let n=Ll.size>=El;n&&Rl||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?Rl=!0:Ll.add(e.file))}function clearAppendFailure(e){Ll.delete(e.file)&&(Rl=!1)}function claimQueuedEntries(){let e=Dl===0?M:[...M.slice(Dl),...M.slice(0,Dl)];return M=[],Dl=0,Al>0&&jl&&e.unshift(buildDroppedMarker(jl,Al)),Al=0,jl=null,e}function prepareWrite(e,t,n,r,i){let a=Buffer.byteLength(e.payload,`utf8`);t.bytes>0&&t.bytes+a>e.maxFileBytes&&(rotateLogFile(e.file)?(t.bytes=0,Il.delete(e.file)):warnAboutRotationFailure(e,n));let o=i+1;if(n)return{payload:e.payload,payloadBytes:a,nextIndex:o};let s=[e.payload];for(;o<r.length;o+=1){let n=r[o];if(!n||n.file!==e.file||n.maxFileBytes!==e.maxFileBytes)break;let i=Buffer.byteLength(n.payload,`utf8`);if(a+i>wl||t.bytes+a+i>e.maxFileBytes)break;s.push(n.payload),a+=i}return{payload:s.join(``),payloadBytes:a,nextIndex:o}}async function writeEntries(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){if(Pl)return;let r=e[n];if(!r)return;let i=t.get(r.file);if(!i){if(i={bytes:await getCurrentLogFileBytes(r.file)},Pl)return;t.set(r.file,i)}let a=prepareWrite(r,i,!1,e,n);kl=a.nextIndex;try{await v({filePath:r.file,content:a.payload}),i.bytes+=a.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!1)}finally{for(let t of e.slice(n,a.nextIndex))t.payload=``;n=a.nextIndex}}}function writeEntriesSync(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){let r=e[n];if(!r)return;let i=t.get(r.file);i||(i={bytes:getCurrentLogFileBytesSync(r.file)},t.set(r.file,i));let a=prepareWrite(r,i,!0,e,n);try{ee({filePath:r.file,content:a.payload}),i.bytes+=a.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!0)}r.payload=``,n=a.nextIndex}}async function runFlushLoop(){for(;;){if(Pl)return;let e=claimQueuedEntries();if(e.length===0)return;Ol=e,kl=0,await writeEntries(e),Ol=null,kl=0}}function startFlush(){if(Nl||Pl)return;let e=runFlushLoop().catch(()=>void 0);Nl=e,e.then(()=>{Nl=null,(M.length>0||Al>0)&&scheduleFlush()})}function scheduleFlush(){Ml||Nl||Pl||(Ml=setImmediate(()=>{Ml=null,startFlush()}))}function handleProcessBeforeExit(){flushFileLogQueue()}function handleProcessExit(){Pl=!0,drainFileLogQueueSync()}function installProcessHooks(){Fl||(Fl=!0,process.on(`beforeExit`,handleProcessBeforeExit),process.on(`exit`,handleProcessExit))}function enqueueFileLog(e){if(Pl)writeEntriesSync([e]);else{if(installProcessHooks(),M.length>=Cl){let t=M[Dl];t&&(t.payload=``,jl??=t,Al+=1),M[Dl]=e,Dl=(Dl+1)%M.length}else M.push(e);scheduleFlush()}}async function flushFileLogQueue(){for(;;){Ml&&=(clearImmediate(Ml),null),!Nl&&(M.length>0||Al>0)&&startFlush();let e=Nl;if(!e)return;await e}}function drainFileLogQueueSync(){Ml&&=(clearImmediate(Ml),null);let e=Ol?Ol.slice(kl):[];Ol=null,kl=0,e.push(...claimQueuedEntries()),writeEntriesSync(e)}var Cl,wl,Tl,El,M,Dl,Ol,kl,Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl=__esmMin((()=>{D(),sl(),gl(),Ya(),ol(),Cl=4096,wl=65536,Tl=5,El=64,M=[],Dl=0,Ol=null,kl=0,Al=0,jl=null,Ml=null,Nl=null,Pl=!1,Fl=!1,Il=/* @__PURE__ */ new Map,Ll=/* @__PURE__ */ new Set,Rl=!1,zl=resolveGlobalSingleton(Symbol.for(`openclaw.fileLogTransport`),()=>(process.env.VITEST!==`true`&&installProcessHooks(),{drainSync:drainFileLogQueueSync,enqueue:enqueueFileLog,flush:flushFileLogQueue}))}));function clampLogText(e,t){return e.length>t?`${truncateUtf16Safe(e,t)}...(truncated)`:e}function sanitizeDiagnosticLogText(e,t){return clampLogText(redactSensitiveText(clampLogText(e,t)),t)}function normalizeDiagnosticLogName(e){if(!e||e.trim().startsWith(`{`))return;let t=sanitizeDiagnosticLogText(e.trim(),Yl);return Zl.test(t)?t:void 0}function assignDiagnosticLogAttribute(e,t,n,r){if(t.count>=ql)return;let i=n.trim();if(isBlockedObjectKey(i)||redactSensitiveText(i)!==i||!Zl.test(i))return;let a;if(typeof r==`string`)a=sanitizeDiagnosticLogText(r,Jl);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>=ql)break;Object.hasOwn(n,r)&&r!==`trace`&&assignDiagnosticLogAttribute(e,t,r,n[r])}}function isPlainLogRecordObject(e){if(!isRecord(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function normalizeTraceContext(e){let t=asOptionalRecord(e);if(t&&isValidDiagnosticTraceId(t.traceId)&&(t.spanId===void 0||isValidDiagnosticSpanId(t.spanId))&&(t.parentSpanId===void 0||isValidDiagnosticSpanId(t.parentSpanId))&&(t.traceFlags===void 0||isValidDiagnosticTraceFlags(t.traceFlags)))return{traceId:t.traceId,...t.spanId?{spanId:t.spanId}:{},...t.parentSpanId?{parentSpanId:t.parentSpanId}:{},...t.traceFlags?{traceFlags:t.traceFlags}:{}}}function extractTraceContext(e){return normalizeTraceContext(e)??normalizeTraceContext(asOptionalRecord(e)?.trace)}function getSortedNumericLogEntries(e){return Object.entries(e).filter(([e])=>/^\d+$/.test(e)).toSorted((e,t)=>Number(e[0])-Number(t[0]))}function normalizeFileLogContextValue(e){if(typeof e==`string`){let t=e.trim();return t?clampLogText(t,Xl):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(Wl)return Wl;let e=S.hostname().trim();return e?(Wl=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<=Gl&&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,o=[a,n,e],s=a&&typeof a.message!=`string`?1:0,c=t.slice(t.length-r.length+s).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}),l=readFirstContextString(o,[`agent_id`,`agentId`]),u=readFirstContextString(o,[`session_id`,`sessionId`,`sessionKey`]),d=readFirstContextString(o,[`channel`,`messageProvider`]);return{fields:{hostname:resolveLogHostname(),...l?{agent_id:l}:{},...u?{session_id:u}:{},...d?{channel:d}:{},...i},messageParts:c}}function buildDiagnosticLogRecord(e){let t=e._meta,{bindings:n,args:r}=extractLogBindingPrefix(getSortedNumericLogEntries(e).map(([,e])=>e)),{trace:i,trustedTraceContext:a}=resolveLogTraceContext(n,r),o=r[0],s=isPlainLogRecordObject(o)?o:void 0;s&&r.shift();let c=``;r.length>0&&typeof r[r.length-1]==`string`?c=sanitizeDiagnosticLogText(String(r.pop()),Kl):r.length===1&&(typeof r[0]==`number`||typeof r[0]==`boolean`)&&(c=String(r[0]),r.length=0),c||=`log`;let l=Object.create(null),u={count:0};addDiagnosticLogAttributesFrom(l,u,n),addDiagnosticLogAttributesFrom(l,u,s);let d={};if(t?.path?.fileLine){let e=Number(t.path.fileLine);Number.isFinite(e)&&(d.line=e)}t?.path?.method&&(d.functionName=sanitizeDiagnosticLogText(t.path.method,Yl));let f=normalizeDiagnosticLogName(t?.name),p=t?.parentNames?.map(normalizeDiagnosticLogName).filter(e=>!!e);return{event:{type:`log.record`,level:t?.logLevelName??`INFO`,message:c,...f?{loggerName:f}:{},...p?.length?{loggerParents:p}:{},...Object.keys(l).length>0?{attributes:l}:{},...Object.keys(d).length>0?{code:d}:{},...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&&!O.overrideSettings}function resolveDefaultActiveLogFile(e=!1){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG===`1`?n.join(process.cwd(),`.artifacts`,`test-logs`,`${_l}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date)}${vl}`):resolveDefaultRollingLogFile(e?void 0:{prepare:!1})}function resolveSettings(e=!1){if(!canUseNodeFs())return{level:`silent`,file:Vl,maxFileBytes:Ul,rolling:!1,defaultFile:!1};let t=resolveEnvLogLevelOverride();if(canUseSilentVitestFileLogFastPath(t))return{level:`silent`,file:resolveDefaultRollingLogFile(e?void 0:{prepare:!1}),maxFileBytes:Ul,rolling:!0,defaultFile:!0};let n=O.overrideSettings??readLoggingConfig(),r=process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`?`silent`:`info`,i=normalizeLogLevel(n?.level,r),a=t??i,o=!n?.file||isLegacyRollingLogFilePath(n.file);return{level:a,file:resolveActiveLogFileWithMode(n?.file??resolveDefaultActiveLogFile(e),o),maxFileBytes:resolveMaxLogFileBytes(n?.maxFileBytes),rolling:o,defaultFile:!n?.file}}function getRuntimeSettings(){let e=O.cachedSettings??resolveSettings();return O.cachedSettings=e,e}function isFileLogLevelEnabled(e){return isLogLevelEnabled(e,getRuntimeSettings().level)}function inheritLogLevel(e,t){let resolveLevel=t;Object.defineProperty(e.settings,"minLevel",{configurable:!0,enumerable:!0,get:()=>resolveLevel(),set:e=>{resolveLevel=()=>e}})}function buildLogger(){let e=new RuntimeLogger({name:`openclaw`,mask:{keys:[]},meta:{property:`_meta`},minLevel:levelToMinLevel(`fatal`),type:`hidden`});inheritLogLevel(e,()=>levelToMinLevel(getRuntimeSettings().level));let t,r;return e.attachTransport({format:()=>``,write:e=>{try{let i=getRuntimeSettings();if(i.level===`silent`)return;r?.settings!==i&&(r={settings:i,file:i.defaultFile?resolveDefaultActiveLogFile(!0):i.file});let a=resolveActiveLogFileWithMode(r.file,i.rolling);if(a!==t){t=a;try{ensureLogDirectorySync(n.dirname(t)),i.rolling&&pruneOldRollingLogs(n.dirname(t))}catch{}}let o=formatTimestamp(e.date??/* @__PURE__ */ new Date,{style:`long`}),{fields:s,messageParts:c}=prepareFileLogRecord(e),l=serializeFileLogRecord({...e,_meta:withResolvedLogMetaHostname(e._meta,s.hostname),time:o,...s},c);zl.enqueue({file:t,hostname:s.hostname,maxFileBytes:i.maxFileBytes,payload:`${l}\n`})}catch{}}}),attachDiagnosticEventTransport(e),e}function resolveMaxLogFileBytes(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):Ul}function getLogger(){let e=O.cachedLogger;if(e)return e;getRuntimeSettings();let t=buildLogger();return O.cachedLogger=t,t}function getChildLogger(e,t){let n=getLogger(),r=e?JSON.stringify(e):void 0;return n.getSubLogger({name:r,prefix:e?[r??``]:[],...t?.level?{minLevel:levelToMinLevel(t.level)}:{}})}function resolveActiveLogFileWithMode(e,t){let n=expandHomePrefix(e);return t?resolveRollingLogFilePathForDate(n,/* @__PURE__ */ new Date):n}function pruneOldRollingLogs(e){try{let t=l.readdirSync(e,{withFileTypes:!0}),r=Date.now()-Hl;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{l.statSync(t).mtimeMs<r&&l.rmSync(t,{force:!0})}catch{}}}catch{}}var Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,RuntimeLogger,Ql=__esmMin((()=>{T(),Dt(),pc(),Qc(),Cc(),hn(),It(),ml(),hl(),Wn(),dl(),ul(),gl(),Sl(),yl(),Kn(),Bl(),Ya(),Hn(),ol(),Vl=`${fl}/openclaw.log`,Hl=864e5,Ul=104857600,Wl=null,Gl=8192,Kl=4096,ql=32,Jl=2048,Yl=120,Xl=512,Zl=/^[A-Za-z0-9_.:-]{1,64}$/u,RuntimeLogger=class extends Be{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&&!O.overrideSettings)return{level:`silent`,style:normalizeConsoleStyle(void 0)};let t=O.overrideSettings??readLoggingConfig();return{level:e??normalizeConsoleLevel(t?.consoleLevel),style:normalizeConsoleStyle(t?.consoleStyle)}}function getConsoleSettings(){let e=O.cachedConsoleSettings;if(e)return e;let t=resolveConsoleSettings();return O.cachedConsoleSettings=t,t}function shouldLogSubsystemToConsole(e){let t=O.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 $l=__esmMin((()=>{Ye(),un(),tl(),dc(),Wn(),dl(),sl(),ul(),Ql(),Ya(),Hn(),ol(),`${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=nu.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)%tu.length;return expectDefined(tu[r],`subsystem colors entry at idx`)}function formatSubsystemForConsole(e){let t=e.split(`/`).filter(Boolean),n=t.join(`/`)||e;for(;t[0]!==void 0&&ru.has(t[0]);)t.shift();let r=t.at(0);return r===void 0?n:iu.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 o=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,s=eu[o]??=new ze({level:o}),c=e===`error`||e===`fatal`?s.red:e===`warn`?s.yellow:e===`debug`||e===`trace`?s.gray:s.cyan,l=stripRedundantSubsystemPrefixForConsole(redactSensitiveText(i),t),u=a===`pretty`||O.consoleTimestampPrefix?s.gray(formatConsoleTimestamp(a)):``,d=s[r](n);return`${u?`${u} ${d}`:d} ${c(l)}`}}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=O.rawConsole??console;O.forceConsoleToStderr||e===`error`||e===`fatal`?(a.error??console.error)(i):e===`warn`?(a.warn??console.warn)(i):(a.log??console.log)(i)}function shouldSuppressProbeConsoleLine(e){if(isVerbose()||e.level===`error`||e.level===`fatal`)return!1;let t=typeof e.message==`string`?e.message:``;return e.suppressProbeMessages?(typeof e.meta?.runId==`string`?e.meta.runId:typeof e.meta?.sessionId==`string`?e.meta.sessionId:void 0)?.startsWith(`probe-`)?!0:/(sessionId|runId)=probe-/.test(t):!1}function formatConsoleMetaValue(e){if(e!==void 0)return typeof e==`string`?/\s|=/.test(e)||e.length===0?JSON.stringify(e):e:e===null||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function prepareLogMetaRecord(e,t=!1){let n;for(let[r,i]of Object.entries(e))i instanceof Error&&(n??={...e},n[r]={name:i.name,message:i.message,errorCode:extractErrorCode(i),stack:t?i.stack?.split(`
`).slice(0,6).join(`
`):i.stack});return n??e}function formatConsoleMeta(e){let t;try{t=redactLogRecordForTransport(e)}catch{return``}let n=[];for(let[e,r]of Object.entries(t)){let t=formatConsoleMetaValue(r);t!==void 0&&n.push(`${e}=${t}`)}let r=n.join(` `);return r.length>ou?`${r.slice(0,ou)}...(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 o=getConsoleSettings(),s=i?.consoleMessage!==!1&&isLogLevelEnabled(e,o.level)&&shouldLogSubsystemToConsole(t),c=isFileLogLevelEnabled(e);if(!s&&!c)return;let l,u=i,d=i;if(i&&Object.keys(i).length>0){let{consoleMessage:e,...t}=i;typeof e==`string`&&(l=e),u=Object.keys(t).length>0?prepareLogMetaRecord(t):void 0,d=u&&s?prepareLogMetaRecord(t,!0):void 0}if(c&&logToFile(getFileLogger(e),e,r,u),!s)return;let f=o.style!==`json`&&l===void 0&&d&&au.has(e)?formatConsoleMeta(d):``,p=l??(f?`${r} ${f}`:r);shouldSuppressProbeConsoleLine({level:e,suppressProbeMessages:n,message:p,meta:d})||writeConsoleLine(e,o.style===`json`?formatJsonConsoleLine({level:e,subsystem:t,message:r,meta:d}):(a??=createConsoleLineFormatter(t))(e,p,o.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 eu,tu,nu,ru,iu,au,ou,su=__esmMin((()=>{Ot(),Ge(),Ye(),lc(),dc(),pc(),Qc(),el(),$l(),ul(),Ql(),Ya(),Hn(),eu=[],tu=[`cyan`,`green`,`yellow`,`blue`,`magenta`,`red`],nu=/* @__PURE__ */ new Map([[`gmail-watcher`,`blue`]]),ru=/* @__PURE__ */ new Set([`gateway`,`channels`,`providers`]),iu=/* @__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(`.`)),au=/* @__PURE__ */ new Set([`warn`,`error`,`fatal`]),ou=2048})),cu=/* @__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},o=createSubsystemLogger(`agents/code-mode`);if(r)try{let e=await writeWorkerGcProfiles(r);o.warn(`Code Mode worker GC storm`,{...a,profileFiles:e})}catch{o.warn(`Code Mode worker GC storm`,{...a,captureStatus:`unavailable`,captureReason:`profile-write-failed`})}else o.warn(`Code Mode worker GC storm`,a);if(i.captureStatus===`requested`){let{getEnabledCategories:e}=await import(`node:trace_events`);if(e())o.warn(`Code Mode worker GC storm`,{...a,captureStatus:`unavailable`,captureReason:`tracing-active`});else return i}}function captureWorkerGcProfiles(){return captureDiagnosticProfile({hasAuthority:()=>!0,durationMs:lu,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:uu,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:lu,effectiveDurationMs:lu,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:uu,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=pu.then(async()=>{let t=n.join(resolveStateDir(),`diagnostics`);await x.mkdir(t,{recursive:!0,mode:448});let r=(await x.readdir(t)).filter(e=>fu.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-du+2)))await x.unlink(n.join(t,e));let i=`code-mode-gc-${Date.now()}-${_()}`,a=[];for(let[r,o]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${i}.${r}profile.json`;await Ie({filePath:n.join(t,e),content:o,mode:384,dirMode:448}),a.push(e)}return a});return pu=t.catch(()=>{}),t}var lu,uu,du,fu,pu,mu=__esmMin((()=>{bn(),oc(),sc(),$s(),su(),lu=5e3,uu=262144,du=20,fu=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/,pu=Promise.resolve()}));T(),D(),Ds(),Ns(),me(`openclaw.code-mode.gc-storm`);const N=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 getTrackedPostgresBridgeCounters(){return collectPostgresBridgeCounters(N.postgresBridgeCount,N.workers.values(),N.postgresPoolSelfRootCount)}function observeTrackedPostgresBridgeCounters(e){return N.postgresBridgeObservers.add(e),()=>N.postgresBridgeObservers.delete(e)}function publishPostgresBridgeCounters(){for(let e of N.postgresBridgeObservers)e()}function forgetWorker(e){let t=N.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(N.postgresBridgeCount,0,1),t.memoryFlush?.resolve(),t.memoryPort?.close(),N.workers.delete(e),N.revision++,N.cpuSources=void 0,t.postgresBridgeCounters&&publishPostgresBridgeCounters()}function countWorkerStart(e){let t=N.lifecycle.get(e.script);return t||(t={started:0,retired:/* @__PURE__ */ new Map},N.lifecycle.set(e.script,t)),e.started||(e.started=!0,t.started++),t}function trackWorker(e){if(N.workers.has(e))return;if(C&&e instanceof ve&&recordWorkerMessage(`lifecycle`,`to_worker`),C&&e instanceof ve&&canObserveWorkerMessages(e)){let t=Object.getPrototypeOf(e)===ve.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??ve.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??ve.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())}}};N.workers.set(e,n),queueMicrotask(()=>countWorkerStart(n)),N.revision++,N.cpuSources=void 0,e.once(`exit`,()=>forgetWorker(e))}function serveWorkerMemorySamples(e,t){let{port1:n,port2:r}=new ge,i=observeTrackedPostgresBridgeCounters(()=>{n.postMessage({postgresBridgeCounters:getTrackedPostgresBridgeCounters()})}),a=process.versions.bun?void 0:Pe().heap_size_limit,o,s=!1,flushGc=()=>{o&&=(n.postMessage({gc:o}),void 0)},sample=()=>{let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:s}=process.memoryUsage(),c=process.versions.bun?void 0:Ne().map(({space_name:e,space_used_size:t})=>({space_name:e,space_used_size:t}));n.postMessage({heapUsed:e,heapTotal:r,external:i,arrayBuffers:s,heapSizeLimitBytes:a,oldGenerationAfterGcBytes:getOldGenerationAfterGcBytes(),heapSpaces:c,retainedData:t?.(),gc:o}),o=void 0},c,setGcEnabled=e=>{e?c??=observeGcSamples(e=>{(o??=[]).push(...e),(s||o.length>=256)&&flushGc()}):(c?.(),c=void 0,o=void 0)};return n.on(`message`,e=>{if(e&&`flush`in e)flushGcSamples(),flushGc(),n.postMessage({flushed:!0,heapUsed:Pe().used_heap_size});else if(e&&`captureGcProfile`in e){let t=e.captureGcProfile;Promise.resolve().then(()=>(mu(),cu)).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`,()=>{i(),c?.(),o=void 0}),n.on(`messageerror`,()=>n.close()),n.unref(),sample(),e.postMessage({status:`memory`,port:r,postgresBridgeCounters:getTrackedPostgresBridgeCounters()},[r]),{setTaskMetrics(e){s=e,setGcEnabled(e)},collectTask(){return s?!0:void 0},close(){i(),c?.(),c=void 0,flushGc(),n.close()}}}Qa(),T(),Hn();function serveWorkerTasks(e,t={}){serveOwnedWorkerTasks(e,t)}function serveOwnedWorkerTasks(e,t={}){let n,r,i,a,o,s,runWithTaskContext=async e=>{let run=async()=>{let t=i;if(!t)return e();let n=!0;try{return await withSqliteDatabaseAdmissionExchange((e,r,i)=>{if(!n)throw Error(`SQLite admission facts outlived their worker task`);return exchangeSqliteDatabaseAdmissions(t,e,r,i)},e)}finally{n=!1}};return o?withDatabaseEngineSelection(o,run):run()};serveOwnedWorkerTasks$1((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})),{...t,get retireOnError(){return t.retireOnError||postgresPoolWorkerFailure()!==void 0},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 _e))throw Error(`Retained worker task port is invalid`);return r=e.port,r}},initialize(e){O.forceConsoleToStderr=!0,n=e},onReady(){r?.postMessage({status:`ready`},[])},onMessage(e){e&&!s&&(s=serveWorkerMemorySamples(n,t.retainedData)),cancelWorkerIdleGc()},installTaskContext(e){s?.setTaskMetrics(e.collectWorkerMetrics===!0),a=e.databaseAdmissionDeadlineAtMs,o=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:()=>s?.collectTask(),onRetire(){cancelWorkerIdleGc();try{s?.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 P=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]})}}),F=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),hu=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:F.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),gu=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:F.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),_u=[`preserve rows`,`delete rows`,`drop`],I=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})}}),vu=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:F.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:F.create(e),identifier:F.create(t)})}}),yu=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:vu.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),bu=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:F.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),xu=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),Su=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),Cu=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:vu.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:vu.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 wu=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})}}),Tu=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),Eu=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),Du=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`?Tu.create(e.on,n):Eu.create(e.on,n)})}}),Ou=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:Du.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?Du.cloneWithOperation(e.on,`And`,t):Du.create(t)})}}),ku=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),Au=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(Au);const ju=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(ju);const Mu=freeze({"->":!0,"->>":!0}),Nu=Object.keys(Mu),Pu=freeze({...Au,...ju,"||":!0}),Fu=Object.keys(Pu),Iu=freeze({exists:!0,"not exists":!0});Object.keys(Iu);const Lu=freeze({...Iu,"-":!0,not:!0}),Ru=Object.keys(Lu);[...Fu,...Nu,...Ru];const zu=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&Pu[e]}function isJSONOperator(e){return isString(e)&&Mu[e]}function isUnaryOperator(e){return isString(e)&&Lu[e]}const L=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:F.create(e)})}}),Bu=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Vu=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:Bu.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 Hu=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})}}),R=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return R.create([e],[])},createWithChild(e){return R.create([``,``],[e])},createWithChildren(e){return R.create(Array(e.length+1).fill(``),e)}}),Uu=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:F.create(e)})}});var Wu=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:Hu.cloneWith(this.#e.node,{direction:R.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:Hu.cloneWith(this.#e.node,{direction:R.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:Hu.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:Hu.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:Hu.cloneWith(this.#e.node,{collation:Uu.create(e)})})}toOperationNode(){return this.#e.node}};const Gu=/* @__PURE__ */ new Set;function logOnce(e){Gu.has(e)||(Gu.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(Hu.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 Hu.create(e,R.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Hu.create(e,t.toOperationNode());let n=Hu.create(e);return t?t(new Wu({node:n})).toOperationNode():n}const Ku=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})}}),qu=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])})}}),Ju=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 Ku.create(parseStringReference(e),qu.create(zu.create(t)));if(t===`->$`||t===`->>$`)return Ku.create(parseStringReference(e),Ju.create(zu.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Vu.create(L.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 Su.create(parseStringReference(n),F.create(r))}return parseStringReference(e)}function parseColumnName(e){return L.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 Vu.create(L.create(r),Cu.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Vu.create(L.create(n),Cu.create(t))}function trim$2(e){return e.trim()}const Yu=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),Xu=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),z=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):z.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 z.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Xu.create(e.map(e=>parseValueExpression(e))):Yu.create(e)}const Zu=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)?ku.create(parseReferenceExpression(e),parseBinaryOperator(t),z.createImmediate(n)):ku.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return ku.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`?Tu.create:Eu.create;if(e.length===0)return ku.create(z.createImmediate(1),zu.create(`=`),z.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?Zu.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 zu.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 Qu=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])})}}),$u=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])})}}),ed=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Qu.cloneWithItems(e.orderBy,t):Qu.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?$u.cloneWithItems(e.partitionBy,t):$u.create(t)})}}),td=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])})}}),nd=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])})}}),rd=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`?Tu.create(e.having,n):Eu.create(e.having,n)})}}),B=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})}}),id=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),ad=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:id.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?td.cloneWithFroms(e.from,t):td.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),od=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])})}}),sd=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:td.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>H.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>H.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?od.create(t):od.cloneWithTables(e.using,t)})}}),V=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`?Tu.create(e.where,n):Eu.create(e.where,n)})}}),cd=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)})}}),ld=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),ud=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),dd=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),ud.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),fd=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)})}}),H=freeze({is(e){return U.is(e)||B.is(e)||ad.is(e)||sd.is(e)||dd.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?V.cloneWithOperation(e.where,`And`,t):V.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?cd.cloneWithSelections(e.returning,t):cd.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:ld.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?fd.cloneWithSelections(e.output,t):fd.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Qu.cloneWithItems(e.orderBy,t):Qu.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),U=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:td.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)=>H.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?nd.cloneWithItems(e.groupBy,t):nd.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?rd.cloneWithOperation(e.having,`And`,t):rd.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=>H.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var pd=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:Ou.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:Ou.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:Ou.cloneWithOn(this.#e.joinNode,R.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const md=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(md.create)}var hd=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:ed.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:H.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:ed.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const gd=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:Bu.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Vu.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)?gd.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?gd.create(e.toOperationNode()):gd.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[gd.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return gd.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const _d=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),vd=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(L.create)),_d.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 o of n){let n=t.get(o);if(isUndefined(n)){a--;continue}let s=e[o];(isUndefined(s)||isExpressionOrFactory(s))&&(i=!0),r[n]=s}if(a<t.size||i){let e=vd.create();return Xu.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Yu.create(r)}const yd=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?[yd.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])=>yd.create(L.create(e),parseValueExpression(t)))}const bd=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 W=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?V.cloneWithOperation(e.indexWhere,`And`,t):V.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?V.cloneWithOperation(e.indexWhere,`Or`,t):V.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?V.cloneWithOperation(e.updateWhere,`And`,t):V.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?V.cloneWithOperation(e.updateWhere,`Or`,t):V.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var xd=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=L.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(L.create);return new OnConflictBuilder({...this.#e,onConflictNode:W.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:W.cloneWith(this.#e.onConflictNode,{constraint:F.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:W.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new Sd({...this.#e,onConflictNode:W.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}},Sd=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:W.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:W.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:W.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const Cd=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 Cd.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const wd=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var Td=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{columns:freeze(e.map(L.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:wd.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:wd.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:wd.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:wd.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:wd.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:wd.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{onConflict:e(new xd({onConflictNode:W.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{onDuplicateKey:bd.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:H.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:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const Ed=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var G,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new G({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new G({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new G({...this.#e,queryNode:H.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new G({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new G({...this.#e,queryNode:sd.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 G({...this.#e,queryNode:H.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new G({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new G({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new G({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new G({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new G({...this.#e,queryNode:H.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new G({...this.#e,queryNode:sd.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new G({...this.#e,queryNode:H.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new G({...this.#e,queryNode:H.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new G({...this.#e,queryNode:sd.cloneWithLimit(this.#e.queryNode,Ed.create(parseValueExpression(e)))})}modifyEnd(e){return new G({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new G({...this.#e})}$castTo(){return new G(this.#e)}$narrowType(){return new G(this.#e)}$assertType(){return new G(this.#e)}withPlugin(e){return new G({...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 G({...this.#e,queryNode:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};G=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},K,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new K({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new K({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new K({...this.#e,queryNode:H.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new K({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new K({...this.#e,queryNode:ad.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 K({...this.#e,queryNode:H.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new K({...this.#e,queryNode:H.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new K({...this.#e,queryNode:H.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new K({...this.#e,queryNode:ad.cloneWithLimit(this.#e.queryNode,Ed.create(parseValueExpression(e)))})}set(...e){return new K({...this.#e,queryNode:ad.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new K({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new K({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new K({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new K({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new K({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new K({...this.#e,queryNode:H.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new K({...this.#e})}$castTo(){return new K(this.#e)}$narrowType(){return new K(this.#e)}$assertType(){return new K(this.#e)}withPlugin(e){return new K({...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 K({...this.#e,queryNode:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};K=UpdateQueryBuilder;const Dd=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:Cu.create(e),columns:t?freeze(t.map(L.create)):void 0})}}),Od=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 kd=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:Od.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:Od.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():Od.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new kd({node:Od.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 Dd.create(n,r)}return Dd.create(e)}const Ad=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])})}}),jd=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return jd[~~(Math.random()*jd.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 Md={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)&&Md[e.kind]===!0}const Nd=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:F.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:Cu.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=>Cu.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return Nd[e.func]?e[n].map(e=>!Cu.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&&vu.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&&(Ou.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(Cu.is(e))return this.#s(e.table,t);if(Su.is(e)&&Cu.is(e.node))return this.#s(e.node.table,t);if(id.is(e))for(let n of e.items)this.#o(n,t);else if(od.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 Pd=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 ud.create(parseFilterList([Pd.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)?R.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 q={};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(q);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==q)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(q)}}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 Fd=freeze([]);var QueryExecutorBase=class{#e;constructor(e=Fd){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),o=this.provideConnection.bind(this),{promise:s,resolve:c}=new Deferred,abortListener=()=>c(q);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let c=getInflightQueryAbortHandler(n,i,a);if(c&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([s,e]).catch(e=>{throw a(),e})===q&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let l=i.executeQuery(e,t),u=await Promise.race([s,l]).catch(e=>{throw a(),e});u===q?(Promise.allSettled([l.catch(printBackgroundFail(`query`)),c?.(o).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let d=this.#t(u,e.queryId,t),f=await Promise.race([s,d]);return f===q&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(q),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:o,resolve:s}=new Deferred,abortListener=()=>s(q);r.addEventListener(`abort`,abortListener,{once:!0});let c,l;assertNotAborted(r,`before query streaming`,a);let{queryId:u}=e;try{for(c=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=c.next(),t=await Promise.race([o,e]);if(t===q&&(l=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,u,n),a=await Promise.race([o,i]);a===q&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(q),r.removeEventListener(`abort`,abortListener);let e=(c?.return?.()||Promise.resolve()).finally(()=>l).finally(a);l||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 Id=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}},Ld=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new Rd({...this.#e,queryNode:dd.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},Rd=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.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:dd.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:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:dd.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 Rd({...this.#e,queryNode:dd.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new Rd({...this.#e,queryNode:dd.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new Rd({...this.#e,queryNode:dd.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:Id,queryNode:ad.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new Rd({...this.#e,queryNode:dd.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new Rd({...this.#e,queryNode:dd.cloneWithThen(this.#e.queryNode,parseMergeThen(B.cloneWith(B.createWithoutInto(),{columns:t,values:n})))})}},zd=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:U.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:U.cloneWithSelections(U.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new Td({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new Td({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:sd.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:ad.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new Ld({queryId:createQueryId(),executor:this.#e.executor,queryNode:dd.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?Ad.cloneWithExpression(this.#e.withNode,n):Ad.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?Ad.cloneWithExpression(this.#e.withNode,n):Ad.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 zd({executor:Id})}function createJoinBuilder(e,t){return new pd({joinNode:Ou.create(e,parseTableExpression(t))})}function createOverBuilder(){return new hd({overNode:ed.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 Ou.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return Ou.create(e,parseTableExpression(t))}const Bd=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),Vd=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(Vd.create)}const Hd=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=>Hd.create(e,parseExpression(t),n))}var J=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Ud(Eu.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new Wd(Tu.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 Su.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():F.create(this.#t))}},Ud=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(Eu.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Zu.create(this.#e)}},Wd=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(Tu.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Zu.create(this.#e)}};const Gd=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:z.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 Gd.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var Y,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new Y({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new Y({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new Y({...this.#e,queryNode:U.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new Y({...this.#e,queryNode:U.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new Y({...this.#e,queryNode:U.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new Y({...this.#e,queryNode:U.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new Y({...this.#e,queryNode:U.cloneWithFrontModifier(this.#e.queryNode,wu.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.createWithExpression(e.toOperationNode()))})}distinct(){return new Y({...this.#e,queryNode:U.cloneWithFrontModifier(this.#e.queryNode,wu.create(`Distinct`))})}forUpdate(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.create(`SkipLocked`))})}noWait(){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,wu.create(`NoWait`))})}selectAll(e){return new Y({...this.#e,queryNode:U.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 Y({...this.#e,queryNode:H.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new Y({...this.#e,queryNode:H.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new Y({...this.#e,queryNode:U.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new Y({...this.#e,queryNode:U.cloneWithLimit(this.#e.queryNode,Ed.create(parseValueExpression(e)))})}offset(e){return new Y({...this.#e,queryNode:U.cloneWithOffset(this.#e.queryNode,Bd.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new Y({...this.#e,queryNode:U.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new Y({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new Y({...this.#e,queryNode:U.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new Y({...this.#e,queryNode:H.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new Y({...this.#e,queryNode:U.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new Y({...this.#e,queryNode:U.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new Y({...this.#e,queryNode:H.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new Y({...this.#e,queryNode:U.cloneWithoutGroupBy(this.#e.queryNode)})}$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)}$asTuple(){return new J(this.toOperationNode())}$asScalar(){return new J(this.toOperationNode())}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();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 Y({...this.#e,queryNode:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};Y=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 Su.create(this.#e.toOperationNode(),F.create(this.#t))}};const Kd=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]?Qu.cloneWithItems(e[r],t):Qu.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`And`,t):V.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`Or`,t):V.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),qd=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var Jd=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:Kd.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:H.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:H.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Kd.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Kd.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Kd.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Kd.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 Su.create(this.#e.toOperationNode(),F.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new J(qd.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new Jd({aggregateFunctionNode:Kd.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 Jd({aggregateFunctionNode:Kd.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 Jd({aggregateFunctionNode:Kd.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new J(qd.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Yd=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 Yd.create(zu.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const X=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),ud.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:X.cloneWithWhen(this.#e.node,ud.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,ud.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:X.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:X.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,ud.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,ud.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:X.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:X.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new J(X.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new J(X.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new J(X.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new J(X.cloneWith(this.#e.node,{isStatement:!0}))}};const Xd=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Zd=/^#-\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`&&!Zd.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 Ku.is(this.#e)?new Qd(Ku.cloneWithTraversal(this.#e,Ju.is(this.#e.traversal)?Ju.cloneWithLeg(this.#e.traversal,Xd.create(e,t)):qu.cloneWithValue(this.#e.traversal,z.createImmediate(t)))):new Qd(Ju.cloneWithLeg(this.#e,Xd.create(e,t)))}},Qd=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 Su.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():F.create(this.#t))}};const $d=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),ef=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}),tf=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+\)$/]),nf=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return ef[e]||tf.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return nf.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const rf=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=Id){function binary(e,t,n){return new J(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new J(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:U.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:X.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new J(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Ju.create())},table(e){return new J(parseTable(e))},val(e){return new J(parseValueExpression(e))},refTuple(...e){return new J($d.create(e.map(parseReferenceExpression)))},tuple(...e){return new J($d.create(e.map(parseValueExpression)))},lit(e){return new J(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 J(ku.create(parseReferenceExpression(e),zu.create(`between`),Tu.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new J(ku.create(parseReferenceExpression(e),zu.create(`between symmetric`),Tu.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new J(parseFilterList(e,`and`)):new J(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new J(parseFilterList(e,`or`)):new J(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Zu.is(t)?new J(t):new J(Zu.create(t))},cast(e,t){return new J(rf.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 Su.create(parseTable(this.#e),F.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 Su.create(parseTable(n),F.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return Cu.createWithSchema(t,n)}return Cu.create(e)}function trim$1(e){return e.trim()}const af=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),Z=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:L.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})}}),of=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:L.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),sf=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:L.create(e),renameTo:L.create(t)})}}),cf=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?F.create(t):void 0})}}),lf=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(lf);const uf=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)&&lf[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():z.createImmediate(e)}const df=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})}}),ff=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 pf=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||Bu.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{references:uf.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error(`on delete constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{references:uf.cloneWithOnDelete(this.#e.references,parseOnModifyForeignAction(e))}))}onUpdate(e){if(!this.#e.references)throw Error(`on update constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{references:uf.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{defaultTo:ff.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{check:cf.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:df.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:df.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:df.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:df.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(Z.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(Z.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const mf=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),hf=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:uf.create(t,n),name:r?F.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var gf=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(hf.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(hf.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(hf.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(hf.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(hf.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(hf.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const _f=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),vf=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(L.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?F.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),yf=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:F.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),bf=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:L.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(bf.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(bf.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(bf.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(bf.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(bf.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)}},xf=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(P.cloneWithTableProps(this.#e.node,{addConstraint:_f.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)}},Sf=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{dropConstraint:yf.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{dropConstraint:yf.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{dropConstraint:yf.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 Cf=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(L.create)),name:t?F.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),wf=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:F.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var Tf=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addIndex:wf.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addIndex:wf.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addIndex:wf.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addIndex:wf.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addIndex:wf.cloneWith(this.#e.node.addIndex,{using:R.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)}},Ef=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(vf.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(vf.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(vf.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(vf.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(vf.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},Df=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(Cf.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(Cf.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(Cf.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(Cf.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 Of=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:F.create(e),newName:F.create(t)})}});var kf=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:of.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:P.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:P.cloneWithTableProps(this.#e.node,{setSchema:F.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new Af({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new kf({node:of.create(e)}));return new Af({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new Af({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,sf.create(e,t))})}addColumn(e,t,n=noop){let r=n(new pf(Z.create(e,parseDataTypeExpression(t))));return new Af({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,af.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new pf(Z.create(e,parseDataTypeExpression(t))));return new Af({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,mf.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new Ef(vf.create(t.map(e=>isString(e)?L.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addConstraint:_f.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(cf.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addConstraint:_f.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new gf(hf.create(t.map(L.create),parseTable(n),r.map(L.create),e)));return new xf({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new Df(Cf.create(t,e)));return new AlterTableExecutor({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addConstraint:_f.create(r.toOperationNode())})})}dropConstraint(e){return new Sf({...this.#e,node:P.cloneWithTableProps(this.#e.node,{dropConstraint:yf.create(e)})})}renameConstraint(e,t){return new Sf({...this.#e,node:P.cloneWithTableProps(this.#e.node,{renameConstraint:Of.create(e,t)})})}addIndex(e){return new Tf({...this.#e,node:P.cloneWithTableProps(this.#e.node,{addIndex:wf.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:P.cloneWithTableProps(this.#e.node,{dropIndex:yu.create(e)})})}$call(e){return e(this)}},Af=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new kf({node:of.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,sf.create(e,t))})}addColumn(e,t,n=noop){let r=n(new pf(Z.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,af.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new pf(Z.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:P.cloneWithColumnAlteration(this.#e.node,mf.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 Xu.create(e.values.map(z.createImmediate))}transformValue(e){return z.createImmediate(e.value)}},jf=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:hu.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:hu.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:hu.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:hu.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:hu.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:hu.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:hu.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:hu.cloneWith(this.#e.node,{using:R.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:H.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)}},Mf=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:gu.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(_u.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var Nf=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(wf.cloneWith(this.#e,{using:R.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},Pf=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:I.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:I.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:I.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new pf(Z.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:I.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new Df(Cf.create(t,e)));return new CreateTableBuilder({...this.#e,node:I.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new Ef(vf.create(t.map(e=>isString(e)?L.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:I.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new Nf(wf.cloneWithColumns(wf.create(e),t.map(e=>isString(e)?L.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:I.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(cf.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:I.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new gf(hf.create(t.map(L.create),parseTable(n),r.map(L.create),e)));return new CreateTableBuilder({...this.#e,node:I.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:I.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:I.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:I.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)}},Ff=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:yu.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:yu.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:yu.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)}},If=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:bu.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:bu.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)}},Lf=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:xu.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:xu.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:xu.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 Rf=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:vu.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)}},zf=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:Rf.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:Rf.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:Rf.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:Rf.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:Rf.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:Rf.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 Bf=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:vu.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Vf=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:Bf.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:Bf.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:Bf.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 Hf=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Xu.create(t.map(z.createImmediate))})}});var Uf=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:Hf.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 Wf=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 Gf=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:Wf.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:Wf.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 vu.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return vu.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Kf=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:vu.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var qf=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Kf.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Kf.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Kf.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 Jf=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),Yf=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)}},Xf,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Xf({...this.#e,node:Jf.cloneWith(this.#e.node,{addValue:Yf.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 Xf({...this.#e,node:Jf.cloneWith(this.#e.node,{addValue:Yf.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:z.createImmediate(e)})})})}};Xf=AlterTypeAddValueBuilder;const Zf=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:Jf.cloneWith(this.#e.node,{addValue:Yf.create(z.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:Jf.cloneWith(this.#e.node,{renameTo:F.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:Jf.cloneWith(this.#e.node,{renameValue:Zf.create(z.createImmediate(e),z.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:Jf.cloneWith(this.#e.node,{setSchema:F.create(e)})})}},Qf=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new Pf({queryId:createQueryId(),executor:this.#e,node:I.create(parseTable(e))})}dropTable(e){return new Lf({queryId:createQueryId(),executor:this.#e,node:xu.create(parseTable(e))})}createIndex(e){return new jf({queryId:createQueryId(),executor:this.#e,node:hu.create(e)})}dropIndex(e){return new Ff({queryId:createQueryId(),executor:this.#e,node:yu.create(e)})}createSchema(e){return new Mf({queryId:createQueryId(),executor:this.#e,node:gu.create(e)})}dropSchema(e){return new If({queryId:createQueryId(),executor:this.#e,node:bu.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:P.create(parseTable(e))})}createView(e){return new zf({queryId:createQueryId(),executor:this.#e,node:Rf.create(e)})}refreshMaterializedView(e){return new qf({queryId:createQueryId(),executor:this.#e,node:Kf.create(e)})}dropView(e){return new Vf({queryId:createQueryId(),executor:this.#e,node:Bf.create(e)})}createType(e){return new Uf({queryId:createQueryId(),executor:this.#e,node:Hf.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:Jf.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new Gf({queryId:createQueryId(),executor:this.#e,node:Wf.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)}}},$f=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,o=performanceNow();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,o),e}finally{a||await r.#u(n,o)}},e.streamQuery=async function*(t,i,a){let o,s=performanceNow();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw o=e,await r.#l(e,t,s),e}finally{o||await r.#u(t,s,!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 ep=[`read only`,`read write`],tp=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!ep.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!tp.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 np=class Kysely extends zd{#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(),o=r.createAdapter(),s=new RuntimeDriver(i,o,new Log(e.log??[])),c=new $f(a,o,new DefaultConnectionProvider(s),e.plugins??[]);t={executor:c},n={config:e,executor:c,dialect:r,driver:s}}super(t),this.#e=freeze(n)}get schema(){return new Qf(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:X.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new ip({...this.#e})}startTransaction(){return new ap({...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()}},rp=class Transaction extends np{#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 np({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},ip=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 sp(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),o=new rp({...r,executor:a}),s=!1;try{await this.#e.driver.beginTransaction(t,i),s=!0;let r=await e(o);return await this.#e.driver.commitTransaction(t),n.isCommitted=!0,r}catch(e){throw s&&(await this.#e.driver.rollbackTransaction(t),n.isRolledBack=!0),e}})}},ap=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 op({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},op=class ControlledTransaction extends rp{#e;#t;constructor(e){e={...e,executor:new sp(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 sp=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)}},cp=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?Id: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 cp(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 Su.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():F.create(this.#t))}};const Q=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:R.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:R.create(t,e.map(F.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(z.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithSql(e)})},join(e,t=Q`, `){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:R.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 lp=/'/g,up=/['"]/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&&!Zu.is(this.parentNode)&&!B.is(this.parentNode)&&!I.is(this.parentNode)&&!Rf.is(this.parentNode)&&!Hd.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&&!Zu.is(this.parentNode)&&!R.is(this.parentNode)&&!ud.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&&!Zu.is(this.parentNode)&&!R.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(pp[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&&!Zu.is(this.parentNode)&&!R.is(this.parentNode)&&!ud.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(dp[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 zu.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||!I.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(lp,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(up,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?fp[e.modifier]-fp[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const dp=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),fp=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),pp=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`}),mp=freeze({raw(e,t=[]){return freeze({sql:e,query:R.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 R.createWithChildren([R.createWithSql(`${e} `),F.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(mp.raw(`begin`))}async commitTransaction(e){await e.executeQuery(mp.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(mp.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(!U.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let o=a.iterate(r);for(let e of o)yield{rows:[e]}}};const hp=/"/g,gp=/[\\'"]/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(hp,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(gp,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const _p=`kysely_migration`,vp=`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`,`!=`,_p).where(`name`,`!=`,vp)),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`,Q`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 yp=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(mp.raw(n))}async commitTransaction(e){await e.executeQuery(mp.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(mp.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[yp]()}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}}[yp](){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(mp.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`,Q`col_description(a.attrelid, a.attnum)`.as(`column_description`),Q`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(Q`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`,`!=`,_p).where(`c.relname`,`!=`,vp));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 bp=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(bp,`""`)}};const xp=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await Q`
    with set_timeout as (
      select set_config('lock_timeout', '${Q.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${Q.lit(xp)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await Q`select pg_advisory_unlock(${Q.lit(xp)})`.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 Sp=/^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,Cp=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],wp=Cp[Cp.length-1];`${Cp.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<Cp.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=Sp.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>wp.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(Sp.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(Cp)};
  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,Tp=templateFragments`(SELECT value FROM json_each(${0}))`,Ep=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!R.is(e)||e.sqlFragments!==Tp||e.parameters.length!==1)return;let t=e.parameters[0];for(;R.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!z.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(zu.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===Tp;!t&&e.sqlFragments!==Ep?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}};D(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteCoordinatorError`),()=>class extends Error{constructor(e,t){super(e),this.cause=t,this.name=`SqliteCoordinatorError`}});function createSqliteLifecycleAggregateError(e,t,n){return AggregateError(e,t,{cause:n})}su(),D(),createSubsystemLogger(`sqlite/publication`);const Dp=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePostCommitPublications`),()=>/* @__PURE__ */ new WeakMap),Op=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteTransactionState`),()=>/* @__PURE__ */ new WeakMap);function hasSqlitePostCommitScope(e){return Dp.has(sqlPublicationAnchor(e))}function stageSqliteTransactionState(e,t){let n=Op.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);Dp.get(r)?.splice(0);let i=Op.get(r)?.splice(0)??[];Dp.delete(r),Op.delete(r),rollbackTransactionState(i,t,n)}Ge();const kp=parseNodeReleaseVersion(process.versions.node),Ap=!process.versions.bun&&(kp?.major===24&&isNodeVersionAtLeast(kp,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(kp,{major:26,minor:6,patch:0})),jp=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),Mp=/* @__PURE__ */ new WeakMap,Np=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(isPostgresSqlConnection(e)){let t=Mp.get(e);return t||(t=new np({dialect:Np}),Mp.set(e,t)),t}let t=No.get(e);if(t)return t;let n=new np({dialect:jp});return No.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{Po.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&&U.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(U.is(t.query)||i.columns().length>0){if(Ap)return{rows:i.all(...r)};let t=i.iterate(...r),n=retainSqliteReader(e,`kysely eager query`),a=!1,o,s=[];try{for(let e of t)n.progress(),s.push(e)}catch(e){a=!0,o=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw toErrorObject(o,`SQLite query failed`);return{rows:s}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:o,lastInsertRowid:s}=a,c={numAffectedRows:BigInt(o),rows:[]};return B.is(t.query)&&o>0?{...c,insertId:BigInt(s)}:c})}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),Q`${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]}function materializeRuntimeProcessScriptFile(e,t={}){let r=l.mkdtempSync(n.join(t.parentDirectory??S.tmpdir(),`openclaw-script-`)),i=n.join(r,e.fileName),a=!1,dispose=()=>{if(!a)try{l.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 l.writeFileSync(i,e.source,{mode:384,flag:`wx`}),{url:c(i),dispose}}catch(e){throw dispose(),e}}Js(),wo();function probeBunSqliteLibrary(e){let t=materializeRuntimeProcessScriptFile({fileName:Co.bunSqliteLibraryProbe.fileName,source:`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}
`});try{let r=s(t.url),i=n.dirname(r),a=n.join(i,`bunfig.toml`);l.writeFileSync(a,``,{mode:384,flag:`wx`});let o={};for(let e of[`SystemRoot`,`SYSTEMROOT`,`WINDIR`,`TEMP`,`TMP`,`TMPDIR`])process.env[e]&&(o[e]=process.env[e]);let c=Te(process.execPath,[`--no-install`,`--no-env-file`,`--config=${a}`,r,n.resolve(e)],{cwd:i,env:resolveRuntimeScriptEnv(o),encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,killSignal:`SIGKILL`,maxBuffer:4096});if(c.error)throw c.error;let u;try{u=JSON.parse(c.stdout)}catch{throw Error(`SQLite library probe returned invalid output`)}if(typeof u!=`object`||!u||Array.isArray(u)||!(`protocol`in u)||u.protocol!==1)throw Error(`SQLite library probe returned invalid output`);if(c.status!==0)throw Error(`error`in u&&typeof u.error==`string`?u.error.slice(0,512):`SQLite library probe failed (${c.signal??c.status})`);if(!(`version`in u)||typeof u.version!=`string`||u.version.length>64||!(`extensionLoadingSupported`in u)||typeof u.extensionLoadingSupported!=`boolean`)throw Error(`SQLite library probe returned invalid output`);return{version:u.version,extensionLoadingSupported:u.extensionLoadingSupported}}finally{t.dispose()}}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 Pp,Fp=__esmMin((()=>{wo(),Pp=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 Ip=__esmMin((()=>{resolveRuntimeProcessDistRoot(s(import.meta.url))})),Lp,Rp=__esmMin((()=>{Lp=/* @__PURE__ */ new Set([`-r`,`--preload`,`--require`,`--import`,`--loader`,`--experimental-loader`,`--test-reporter`,`--test-global-setup`]),[...Lp]}));function resolveRuntimeWorkerUrl(e){if(e.root!==void 0)return c(n.join(e.root,`dist`,e.distWorkerPath));let t=s(e.currentModuleUrl),r=resolveRuntimeProcessDistRoot(t);if(r!==void 0){let t=e.distWorkerPath;if(e.package){let i=n.resolve(r,`..`),a=Ve({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 c(n.join(r,t))}let i=e.sourceExtension??(n.extname(t)||`.js`);return new URL(`./${e.sourceWorkerName}${i}`,e.currentModuleUrl)}var zp=__esmMin((()=>{Js(),Ip(),Rp()})),Bp=/* @__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 Le(void 0,{ref:!n})),t&&await ue(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 ce(a(pe(),`openclaw-sqlite-close-`)),e=await le(e),Vp.publish({phase:`start`}),t=new ve(resolveRuntimeWorkerUrl(Pp.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,o=cleanupProbe(t,e,i);if(i)return r;let s=await o;return s?{explicitSqliteCloseReleasesNativeResources:!1,reason:s}:r}var Vp,Hp=__esmMin((()=>{Dn(),Fp(),zp(),Vp=me(`openclaw.sqlite.close-probe`)}));Js(),D(),Rc();const Up=`openclaw.bunSqliteLibrarySelection`,Wp=`openclaw.sqliteRuntimeCapabilities`,Gp=`openclaw.sqliteNativeRuntimeAdmission`;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),Se(Wp,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(!C)return decide({...i,reason:`Parent did not complete SQLite close admission`,...ye(Wp)})}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(()=>(Hp(),Bp));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?o.join(i,`lib/libsqlite3.dylib`):void 0,s=process.env.HOMEBREW_PREFIX?.trim(),c=r===void 0?[.../* @__PURE__ */ new Set([...a?[a]:[],...s?[o.join(s,`opt/sqlite/lib/libsqlite3.dylib`)]:[],`/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib`,`/usr/local/opt/sqlite/lib/libsqlite3.dylib`,`/opt/local/lib/libsqlite3.dylib`])]:[r],l=[];for(let n of c){let i=r===void 0?n===a?`bundled`:`discovered`:`env`,o,s=!0;try{try{o=probeBunSqliteLibrary(n)}catch(e){throw s=u(n),s?e:Error(`missing file`,{cause:e})}if(!isSqliteWalResetSafeVersion(o.version))throw Error(`SQLite version ${o.version} below the WAL safety floor`);if(!o.extensionLoadingSupported)throw Error(`built with SQLITE_OMIT_LOAD_EXTENSION`)}catch(e){if(r===void 0){(s||n===a)&&l.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:o.version,extensionLoadingSupported:!0},e}throw t=/* @__PURE__ */ Error(`No supported SQLite library for Bun on macOS (${process.arch})`+(l.length>0?`; unusable: ${l.join(`, `)}`:``)+`. Apple's system SQLite fails OpenClaw's read-only database connections. `+(a?`Rebuild or replace the complete standalone artifact to restore its bundled SQLite library. `:``)+`Install one with brew install sqlite, or set OPENCLAW_SQLITE_LIBRARY to a libsqlite3.dylib built for ${process.arch}.`),t}}function selectionError(e,t,n=!1){let r=n?`Rebuild or replace the complete standalone artifact (openclaw and runtime/), or set OPENCLAW_SQLITE_LIBRARY to a supported library.`:`Fix or unset OPENCLAW_SQLITE_LIBRARY; install a supported library with brew install sqlite.`;return Error(`Cannot use ${n?`bundled `:``}SQLite library ${e}: ${t instanceof Error?t.message:String(t)}. ${r}`,{cause:t})}function createRuntimeSelector(){let e=!!process.versions.bun&&process.platform===`darwin`,t;e&&!C&&(t=ye(Up));let n=createSelector(),r=!1;return i=>{let a=t??n(i);return e&&C&&!r&&(Se(Up,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 ensureSqliteLibrarySelected(e){return runtimeSelector()(e)}D();const{busyTimeoutByDatabase:Kp,trackedDatabases:qp}=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}));function rememberSqliteBusyTimeout(e,t){qp.has(e)||(qp.add(e),registerNodeSqliteDisposeCallback(e,()=>Kp.delete(e))),Kp.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`);Kp.get(e)!==n&&(e.exec(`PRAGMA busy_timeout = ${n}`),rememberSqliteBusyTimeout(e,n))}T(),Zt();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 g(`sha256`).update(e).digest(`hex`).slice(0,16)}function hasNoJournal(e){return[`-wal`,`-journal`].every(t=>{try{let n=l.statSync(`${e}${t}`,{bigint:!0});return n.isFile()&&n.size===0n}catch(e){if(b(e,`ENOENT`))return!0;throw e}})}function readSqliteCleanCloseSeal(e,t,n){let refuse=e=>{n?.(e)};try{let n=`${e}.seal`;return l.lstatSync(n).isFile()?decodeSqliteCleanCloseSeal(l.readFileSync(n,`utf8`),t,hasNoJournal(e),refuse):refuse(`malformed-proof`)}catch(e){return refuse(b(e,`ENOENT`)?`no-proof`:`malformed-proof`)}}function decodeSqliteCleanCloseSeal(e,t,n,r){let i=JSON.parse(e);if(!isRecord(i)||typeof i.payload!=`string`||i.checksum!==checksum(i.payload))return r(`malformed-proof`);let a=JSON.parse(i.payload);if(!isRecord(a)||a.version!==1||typeof a.schemaIdentity!=`string`||typeof a.verifiedAt!=`number`||!Number.isSafeInteger(a.verifiedAt)||!(`facts`in a)||!t.isFile())return r(`malformed-proof`);let o=Date.now()-a.verifiedAt;return o<0||o>6048e5?r(`expired-proof`):Object.entries(fileFields(t)).every(([e,t])=>a[e]===t)?n?{schemaIdentity:a.schemaIdentity,verifiedAt:a.verifiedAt,facts:a.facts,...a.identity===void 0?{}:{identity:a.identity}}:r(`journal-present`):r(`file-mismatch`)}async function readSqliteCleanCloseSealAsync(e,t,n){let refuse=e=>{n?.(e)};try{let n=e+`.seal`;return(await l.promises.lstat(n)).isFile()?decodeSqliteCleanCloseSeal(await l.promises.readFile(n,`utf8`),t,(await Promise.all([`-wal`,`-journal`].map(async t=>{try{let n=await l.promises.stat(e+t,{bigint:!0});return n.isFile()&&n.size===0n}catch(e){if(b(e,`ENOENT`))return!0;throw e}}))).every(Boolean),refuse):refuse(`malformed-proof`)}catch(e){return refuse(b(e,`ENOENT`)?`no-proof`:`malformed-proof`)}}function invalidateSqliteCleanCloseSeal(e){try{l.unlinkSync(`${e}.seal`)}catch(e){if(!b(e,`ENOENT`))throw e}}function writeSqliteCleanCloseSeal(e,t,n,r){try{let i=`${e}.seal`,a=l.lstatSync(i,{throwIfNoEntry:!1});if(!n.isFile()||a&&!a.isFile()||!hasNoJournal(e))return invalidateSqliteCleanCloseSeal(e),!1;let o=JSON.stringify({version:1,schemaIdentity:t,...fileFields(n),verifiedAt:r.verifiedAt,facts:r.facts,identity:r.identity});return l.writeFileSync(i,JSON.stringify({payload:o,checksum:checksum(o)})),!0}catch{try{invalidateSqliteCleanCloseSeal(e)}catch{}return!1}}to(),Zt();function resolveSqliteDatabaseFilePath(e){if(!e.startsWith(`file:`))return e;let[t=``]=e.slice(5).split(/[?#]/u,1);return t.startsWith(`/`)?s(e):decodeURIComponent(t)}function createSqliteDatabaseDescriptorOwner(e){function prepareSqliteDatabaseAdmissionAsync(t){let n=resolveAdmissionTarget(t.location,t.create!==void 0);if(!n)return Promise.resolve(void 0);let{filename: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 o=n.key.startsWith(`file:`),s=!o&&i?t.create:void 0;if(!o&&!s)return n;let c=`${n.key.slice(5)}:${n.birthtime}`;if(t.observedLocation&&t.observedLocation.identity!==c)throw Error(`SQLite database changed while retaining its admission identity`);if(w!==0){if(s)throw Error(`SQLite descriptor creation belongs to the host`);return pathAdmission(r,c),t.assertCurrent(),n}let u=o?A.registry.descriptors.get(c):void 0;if(u&&(assertDatabaseFileIdentity(u.file,n),retainPreparedSqliteDatabaseAdmissionLocation(r,void 0,{identity:c,canonicalPath:n.canonicalPath})))return n;let d,f;if(u)d=u.descriptor,f=u.file;else{s&&await s.authorize(n.canonicalPath),t.assertCurrent();let e=s?createDeferredCore():void 0;e&&s?.retain(e.promise);let i;try{i=await new Promise((e,t)=>{l.open(r,s?`wx`:`r`,420,(n,r)=>n?t(n):e(r))}),d=i,f=await new Promise((e,t)=>{l.fstat(d,{bigint:!0},(n,r)=>n?t(n):e(r))}),o&&assertDatabaseFileIdentity(f,n),A.registry.retainDescriptorCustody(d,f),e?.resolve()}catch(t){if(i===void 0){if(e?.resolve(),s&&b(t,`EEXIST`))return prepare()}else e?.reject(t);throw t}}let p=o?n:{key:`file:${f.dev}:${f.ino}`,canonicalPath:n.canonicalPath,birthtime:readDatabaseIdentityBirthtime(f)},m,h=o?await readSqliteCleanCloseSealAsync(n.canonicalPath,f,e=>{m=e}):void 0,g=await inspectDatabasePathIdentity(r);if(!g||g.key!==p.key||g.birthtime!==p.birthtime||g.canonicalPath!==p.canonicalPath)throw Error(`SQLite database changed identity during admission`);t.assertCurrent();let _=A.registry.records.get(readSqliteDatabaseAdmissionIdentity(f)),v=_&&!isSqliteDatabaseAdmissionRetired(_)?_:A.registry.retainDescriptor(p.canonicalPath,A.registry.descriptors.get(readSqliteDatabaseAdmissionIdentity(f))?.descriptor??d,f);return A.registry.observeLocation(r,v.identity),o?e.load(v,{seal:h,refusal:m}):e.markLoaded(v),p},o=A.descriptorPreparation.then(prepare);return A.descriptorPreparation=o.then(()=>{},()=>{}),o}function retainPreparedSqliteDatabaseAdmissionLocation(t,n,r){let i=!r&&A.registry.forLocation(t),a=i&&A.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 o=r&&A.registry.descriptors.get(r.identity);if(r&&o&&e.isLoaded(o)){n&&assertDatabaseFileIdentity(o.file,n);let i=A.registry.records.get(r.identity),a=i&&!isSqliteDatabaseAdmissionRetired(i)?i:A.registry.retainDescriptor(r.canonicalPath,o.descriptor,o.file);return A.registry.observeLocation(t,a.identity),e.markLoaded(a),!0}return!1}function retainSqliteDatabaseAdmissionLocation(t,n,r){if(retainPreparedSqliteDatabaseAdmissionLocation(t,n,r))return;let i=l.statSync(t,{bigint:!0});if(!i.isFile())return;let a=readSqliteDatabaseAdmissionIdentity(i),o=A.registry.records.get(a);if(o&&!isSqliteDatabaseAdmissionRetired(o)){A.registry.observeLocation(t,a),e.load(o);return}if(w!==0)return;let s=A.registry.descriptors.get(a)?.descriptor??l.openSync(t,`r`),c=l.fstatSync(s,{bigint:!0});if(!c.isFile()||readSqliteDatabaseAdmissionIdentity(c)!==a)throw Error(`SQLite database changed while retaining its admission identity`);let u=A.registry.retainDescriptor(l.realpathSync.native(t),s,c);A.registry.observeLocation(t,u.identity),e.load(u)}function pathAdmission(t,n){try{let r=A.registry.forLocation(t);if(!r){let e=n;if(e===void 0&&w!==0){let n=l.statSync(t,{bigint:!0});if(!n.isFile())return;e=readSqliteDatabaseAdmissionIdentity(n)}exchangeSqliteDatabaseAdmission(t,void 0,!1,e!==void 0&&w!==0?{identity:e,canonicalPath:l.realpathSync.native(t)}:void 0),r=A.registry.forLocation(t)}return r?(e.load(r),r):(retainSqliteDatabaseAdmissionLocation(t),A.registry.forLocation(t))}catch(e){if(b(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=l.statSync(i,{bigint:!0});if(!e.isFile()){A.registry.observeLocation(i,void 0);return}let t=readSqliteDatabaseAdmissionIdentity(e);return A.registry.observeLocation(i,t),t}catch(t){if(b(t,`ENOENT`)){if(A.registry.observeLocation(i,void 0),!a)return;if(w!==0){let e=A.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=l.openSync(i,`wx`,420)}catch(e){if(b(e,`EEXIST`))return prepareSqliteDatabaseAdmission(i);throw e}let r=l.fstatSync(n,{bigint:!0}),o=A.registry.retainDescriptor(l.realpathSync.native(i),n,r);if(e.markLoaded(o),prepareSqliteDatabaseAdmission(i)!==o.identity)throw Error(`SQLite database changed identity during file creation`,{cause:t});return o.identity}throw t}}return{prepareSqliteDatabaseAdmissionAsync,retainSqliteDatabaseAdmissionLocation,prepareSqliteDatabaseAdmission,pathAdmission}}D();const Jp=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeAdmissions`),()=>({operations:/* @__PURE__ */ new WeakMap}));function getSqliteNativeAdmissionFacts(e){return Jp.operations.get(e)?.facts}function beginSqliteDatabaseAdmissionOperation(e){let t=Jp.operations.get(e)??{depth:0,facts:/* @__PURE__ */ new Map};return t.depth+=1,Jp.operations.set(e,t),()=>{--t.depth,t.depth===0&&Jp.operations.delete(e)}}function createSqliteDatabaseAdmissionReader(e){let{state:t,admission:n,pathAdmission:r,exchange:i,retain:a,release:o,publishFact:s}=e;function withPathAdmission(e,t){let n=r(e);if(!n)return t(void 0);try{return a(n),t(n)}finally{o(n)}}function getSqliteDatabaseAdmission(e,r,a={}){let o=sqlPublicationAnchor(e);if(!o.isOpen||t.suspended.has(o))return;let s=n(o,a.existingOnly!==!0&&!e.isTransaction);if(!s)return;let c=(isPostgresSqlConnection(e)?void 0:getSqliteNativeAdmissionFacts(e))?.get(r.name)??t.local.get(o)?.get(r.name);if(c&&c.revision===readSqliteDatabaseFactRevision(s,c.schemaDependent)&&(!c.schemaDependent||c.ddlRevision===(t.ddlRevisions.get(o)??0)))return readSqliteDatabaseAdmissionFact(c,r);if(r.schemaDependent&&t.schemaDirty.has(o))return;if(t.rolledBack.has(o)){if(e.isTransaction)return;t.rolledBack.delete(o)}let l=s.facts.get(r.name);if(!l||!isSqliteDatabaseAdmissionFactCurrent(s,l)||a.refresh&&r.writer!==`host`){if(r.writer===`host`)return e.isTransaction||w===0||s.hostRevision===readSqliteDatabaseGeneration(s,`hostRevision`)?void 0:(i(s),l=s.facts.get(r.name),l&&isSqliteDatabaseAdmissionFactCurrent(s,l)?readSqliteDatabaseAdmissionFact(l,r):void 0);let n=readSqliteDatabaseGeneration(s,`publicationRevision`),o=t.misses.get(s)??/* @__PURE__ */ new Map;t.misses.set(s,o),r.writer!==`connection`&&!e.isTransaction&&(a.refresh||o.get(r.name)!==n)&&(i(s),l=s.facts.get(r.name),o.set(r.name,readSqliteDatabaseGeneration(s,`publicationRevision`)))}return l&&isSqliteDatabaseAdmissionFactCurrent(s,l)?readSqliteDatabaseAdmissionFact(l,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),o=n();return o!==void 0&&s(e,t,admitSqliteDatabaseFactValue(t,o),a),o};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?k.schemaRevision:k.factRevision,o=n.facts.get(t.name),s=o&&new Int32Array(o.current);return()=>{if(Atomics.load(i,k.retired)!==0)return;let e=n.facts.get(t.name);return e!==o&&(o=e,s=o&&new Int32Array(o.current)),o&&s&&Atomics.load(s,0)===1&&o.revision===Atomics.load(i,a)?readSqliteDatabaseAdmissionFact(o,t):void 0}}function getSqliteDatabaseSchemaRevision(e,r={}){let i=sqlPublicationAnchor(e),a=n(i,r.existingOnly!==!0);if(a)return readSqliteDatabaseGeneration(a,`schemaRevision`);let o=t.openedIdentities.get(i);return o?t.localSchemaRevisions.get(o)??0:void 0}function hasSqliteDatabaseSchemaAdmissionForPath(e){return hasSqliteDatabaseSchemaAdmission(r(e))}function getSqliteDatabaseAdmissionIdentityForPath(e){return t.registry.forLocation(e)?.physicalIdentity}function hasSqliteDatabaseSchemaAdmissionForIdentity(e){return t.registry.hasSchemaAdmissionForIdentity(e)}return{getSqliteDatabaseAdmission,getSqliteDatabaseSchemaRevision,getOrLoadSqliteDatabaseAdmissionForPath,peekSqliteDatabaseAdmissionForPath,prepareSqliteDatabaseAdmissionForPath,hasSqliteDatabaseSchemaAdmissionForPath,getSqliteDatabaseAdmissionIdentityForPath,hasSqliteDatabaseSchemaAdmissionForIdentity}}const Yp=/* @__PURE__ */ new Set([`CHECK`,`FOREIGN`,`PRIMARY`,`UNIQUE`]);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&&Yp.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,o=i[0][0]??``,s=skipSqlQuoted(e,a,o),c=i[0];if(s!==a)c=e.slice(a,s),r.lastIndex=s;else{let t=skipSqlComment(e,a);if(t!==a){n=!0,r.lastIndex=t;continue}if(/\s/u.test(o)){n=!0;continue}}n&&t.length>0&&(t+=` `),t+=c,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}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 o of splitSqlList(e.slice(n+1,r))){let e=normalizeSqlWhitespace(o);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()}}const Xp=[{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`}];function hasPendingAgentStartupColumns(e){let t=/* @__PURE__ */ new Map;return Xp.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)})}function compareValidSemver(e,t){let n=He(e),r=He(t);return n&&r?n.compare(r):null}T(),D();const Zp=Symbol.for(`openclaw.warning-filter`);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,o;return t instanceof Error?(i=t.name,o=t.message,a=t.code):typeof t==`string`&&(o=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:o}}function installProcessWarningFilter(){let e=resolveGlobalSingleton(Zp,()=>({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}T();const Qp=t(import.meta.url);let $p;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(De(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(ye(Gp))}function assertSafeSqliteRuntime(e){if($p===e)return;let t=parseSqliteNativeRuntimeAdmission(ye(Gp));if(t){assertSqliteWalResetSafeVersion(t.version,process.versions.node),compareValidSemver(t.version,`3.45.0`),t.extensionLoadingSupported,$p=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()}compareValidSemver(r,`3.45.0`),$p=e,Se(Gp,{format:1,runtime:sqliteNativeRuntimeIdentity(),version:r,storageIdentity:i,extensionLoadingSupported:a})}function requireNodeSqlite(){installProcessWarningFilter();try{ensureSqliteLibrarySelected();let e=Qp("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})}}const em=`-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;
-- session_entry_snapshots owns keyed cold values. Promoted node columns are query
-- indexes; session_windows and their children own transcript generations.
-- Legacy ACP provenance is private import evidence carried with its logical session.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

CREATE INDEX IF NOT EXISTS idx_agent_session_input_completions_session_key
  ON session_input_completions(session_key);
`,tm=`

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
  grant_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

-- One owner-native receipt is also the durable execution fence. Receipts
-- survive job deletion so operators can distinguish a run from log inference.
CREATE TABLE IF NOT EXISTS cron_run_receipts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT PRIMARY KEY,
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  config_revision TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  request_run_id TEXT,
  delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started')),
  status TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  started_at_ms INTEGER NOT NULL,
  finished_at_ms INTEGER,
  error_text TEXT,
  CHECK (status IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded')),
  CHECK (
    (status = 'running' AND finished_at_ms IS NULL)
    OR
    (status != 'running' AND finished_at_ms IS NOT NULL)
  )
) STRICT;

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

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

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

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

-- Runtime-private authority is independent of job_json so downgraded writers
-- can rewrite recognized job config without erasing or silently widening it.
CREATE TABLE IF NOT EXISTS cron_job_runtime_authorities (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  authority_json TEXT,
  authority_input_fingerprint TEXT,
  recovery_required INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  FOREIGN KEY (store_key, job_id)
    REFERENCES cron_jobs(store_key, job_id) ON DELETE CASCADE,
  CHECK (recovery_required IN (0, 1)),
  CHECK (
    (recovery_required = 0 AND authority_json IS NOT NULL AND authority_input_fingerprint IS NOT NULL)
    OR
    (recovery_required = 1 AND authority_json IS NULL AND authority_input_fingerprint IS NULL)
  )
) STRICT;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

-- scope_id is non-null because SQLite treats NULLs as distinct in unique indexes/PKs,
-- which would allow duplicate team rows. This PK also avoids a rebuild for identity scope.
CREATE TABLE IF NOT EXISTS secret_store_entries (
  scope_kind TEXT NOT NULL CHECK (scope_kind IN ('team', 'identity')),
  scope_id TEXT NOT NULL,
  name TEXT NOT NULL,
  value TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('secret', 'env')),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  updated_by TEXT,
  deleted_at_ms INTEGER,
  allowed_hosts TEXT,
  CHECK ((scope_kind = 'team' AND scope_id = '') OR (scope_kind = 'identity' AND length(scope_id) > 0)),
  PRIMARY KEY (scope_kind, scope_id, name)
) STRICT;
CREATE INDEX IF NOT EXISTS secret_store_entries_live_idx
  ON secret_store_entries (scope_kind, scope_id, name) WHERE deleted_at_ms IS NULL;
`;function sqliteDatabaseSealSchemaFor(e){requireNodeSqlite();let t=captureSqliteNativeRuntimeAdmission(),n=t?.storageIdentity;if(!t||!n)return;let r=[t.runtime.nodeVersion,t.runtime.bunVersion??null],i=JSON.stringify([t.version,n.sourceId,n.compileOptions,...r]),a=g(`sha256`).update(JSON.stringify([3,i,e])),o=g(`sha256`).update(e);return e!==`state`&&(a.update(`38`),a.update(em),o.update(`38`),o.update(em)),e!==`agent`&&(a.update(`36`),a.update(tm),o.update(`36`),o.update(tm)),{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:o.digest(`hex`),policy:3}}}T();const nm={};function sealSchema(e){let t=e.includes(`agent.schema-metadata`),n=t===e.includes(`state.schema-version`)?`other`:t?`agent`:`state`;return nm[n]??=sqliteDatabaseSealSchemaFor(n)}const rm={name:`sqlite.full-verification`,lifetime:`process`,read:e=>typeof e==`number`&&Number.isSafeInteger(e)?e:void 0},im={...rm,name:`sqlite.quick-verification`},am=/* @__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`]);function isSealedKey(e){return am.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 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),k.sealPresent,Atomics.load(new Int32Array(n),k.sealPresent)),this.loaded.set(t,e.generation)}load(e,t){if(w!==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,l.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===rm.name||e===im.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 o=r.find(([e])=>e===`sqlite-schema`)?.[2];if(!(o.tableSql instanceof Map))return;if(hasPendingAgentStartupColumns(o.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),k.sealPresent,1)}catch{}finally{this.references.publish(e)}}}invalidate(e,t){invalidateSqliteCleanCloseSeal(t?.location??e),t&&Atomics.store(new Int32Array(t.generation),k.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=l.fstatSync(t.descriptor,{bigint:!0});if(readSqliteDatabaseAdmissionIdentity(l.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),k.sealPresent,+!!r),r}catch{return!1}}:()=>!1}};T(),D(),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteInspectionOperations`),()=>/* @__PURE__ */ new WeakMap),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeOpenFailures`),()=>/* @__PURE__ */ new WeakSet),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotFailureScopes`),()=>new y);const om=/* @__PURE__ */ new Set([`SQLITE_BUSY`,`SQLITE_LOCKED`]);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&255}function isSqliteLockError(e){let t=sqliteErrorCode(e);if(t!==void 0&&om.has(t))return!0;let n=sqlitePrimaryResultCode(e);return n===5||n===6}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}const sm=/^(?:\s|;|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/u,cm=/^(BEGIN|SAVEPOINT|COMMIT|END|RELEASE|ROLLBACK)\b/i;function readTransactionControl(e,t){let n,r=!1,i=!1,a=0,o=e;for(;o&&(o=o.replace(sm,``),o);){a+=1;let e=o.includes(`;`)?findSqlCharacter(o,`;`):-1,s=e<0?o:o.slice(0,e),c=cm.exec(s)?.[1]?.toUpperCase();if(c===`ROLLBACK`?(n=c,i||=r,r=!/^ROLLBACK(?: TRANSACTION)? TO\b/iu.test(normalizeSqlWhitespace(s)),i||=!r):(c||!/^SELECT\b/iu.test(s)&&(changesSchema(s)||changesData(s)))&&(i=!0),n||=c,e<0||t===`statement`)break;o=o.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)}}D();const lm=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteNativeExecution`),()=>/* @__PURE__ */ new WeakMap),um=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePreparedNativeMutation`),()=>/* @__PURE__ */ new WeakMap);function isPreparingSqliteNativeMutation(e){return um.get(e)?.phase===`preparing`}const dm=new FinalizationRegistry(e=>{for(let t of e)t.finish(!1,!0)});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}const fm={schemaChange:!1,mainSchemaChange:!1,temporaryTableSchemaChange:!1,dataChange:!1,temporaryWriteTables:void 0,control:void 0};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=um.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 lm.set(e,(lm.get(e)??0)+1),{...a,finish(t,n,r){try{a.finish(t,n,r)}finally{let t=(lm.get(e)??1)-1;t===0?lm.delete(e):lm.set(e,t)}}}},r=/* @__PURE__ */ new Set,execute=(t,n,r=`execute`)=>{let i=um.get(e),a=begin(n,r),o=!1,s=!1,c=!1;try{i&&(i.phase=`preparing`,i.prepare(),i.phase=`executing`);let e=t();return s=!0,r!==`bind`&&a.stepped?.(),o=!0,e}catch(t){if(c=!(!i||i.phase!==`preparing`&&(s||!isSqliteLockError(t)&&sqlitePrimaryResultCode(t)!==19)),i&&!c){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(o,!1,c)}};return e.exec=n=>execute(()=>t.DatabaseSync.prototype.exec.call(e,n),classifySqliteMutation(n,`batch`),`exec`),e.prepare=(...n)=>{let i=t.DatabaseSync.prototype.prepare.call(e,...n),a=classifySqliteMutation(n[0],`statement`),o=Object.hasOwn(i,`run`)?i.run.bind(i):void 0,s=Object.hasOwn(i,`get`)?i.get.bind(i):void 0,c=Object.hasOwn(i,`all`)?i.all.bind(i):void 0,l=Object.hasOwn(i,`iterate`)?i.iterate.bind(i):void 0,u=/* @__PURE__ */ new Set,d=!1,reset=(e,t=`reuse`)=>{if(u.size===0)return e();let n=[...u],r=e();for(let e of n)t===`return`?e.pause():e.invalidate();return r},wrap=e=>(...t)=>execute(()=>reset(()=>callStatement(e(),t)),a);i.run=wrap(()=>o??t.StatementSync.prototype.run.bind(i)),i.get=wrap(()=>s??t.StatementSync.prototype.get.bind(i)),i.all=wrap(()=>c??t.StatementSync.prototype.all.bind(i)),i.iterate=(...n)=>{d||=(dm.register(i,u),!0);let o=execute(()=>reset(()=>callStatement(l??t.StatementSync.prototype.iterate.bind(i),n)),fm,`bind`),s=new WeakRef(o),c=createIteratorLifetime(u,r),f=o.next,p=o.return,m;return o.next=function(...t){if(m&&this===s.deref()&&e.isOpen)return{...m};if(this!==s.deref()||c.invalidated||!e.isOpen)return f.apply(this,t);c.finished&&(c.finished=!1,u.add(c)),c.observed??=begin(a,`iterate`),r.add(c);let n=f.apply(this,t);return n.done?(p?.call(this),m={...n},c.finish(!0)):c.observed?.stepped?.(),n},p&&(o.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`),fm,`bind`);return n.done&&(m={...n}),c.finish(),n}),o};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}D(),jo();const $=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseWriteScopes`),()=>({writeScopes:/* @__PURE__ */ new WeakMap,pendingWriteScopes:/* @__PURE__ */ new WeakMap,localScopeRevisions:/* @__PURE__ */ new WeakMap,localUnscopedRevisions:/* @__PURE__ */ new WeakMap}));function createSqliteDatabaseWriteReceipts(e){function onSqliteDatabaseWriteSettled(t,n){let r=sqlPublicationAnchor(t),i=e.admission(r);if(!i)return;let a=e.writeListeners.get(i);return a||(a=/* @__PURE__ */ new Set,e.writeListeners.set(i,a)),registerListener(a,n)}function settleWorker(t,n){let r=n>0?t.references.get(n):void 0;if(r&&Atomics.exchange(new Int32Array(r),1,0)>0){advanceSqliteDatabaseGeneration(t,`writeRevision`),advanceSqliteDatabaseGeneration(t,`unscopedWriteRevision`);let n=e.writeListeners.get(t);n&&notifyListeners(n,void 0)}}function withSqliteDatabaseWriteScope(t,n,r){let i=sqlPublicationAnchor(t),a=e.admission(i);if(!(a?readSqliteDatabaseGeneration(a,`writeScopeRevision`)>0:$.localScopeRevisions.has(i))){let e=r();if(e instanceof Promise)throw Error(`SQLite write scopes cannot await work`);return e}let o=normalizedWriteScopes(n),s=$.writeScopes.get(i);$.writeScopes.set(i,o);try{let e=r();if(e instanceof Promise)throw Error(`SQLite write scopes cannot await work`);return e}finally{s?$.writeScopes.set(i,s):$.writeScopes.delete(i)}}function withoutSqliteDatabaseWriteScope(e,t){let n=sqlPublicationAnchor(e),r=$.writeScopes.get(n);$.writeScopes.delete(n);try{return t()}finally{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),w===0&&advanceSqliteDatabaseGeneration(t,`writeScopeRevision`),i=!0),r&&r.push(n),retainSqliteDatabaseWriteScope(t,e,n)}i&&(advanceSqliteDatabaseGeneration(t,`publicationRevision`),e.publish(t,n))}function pinWriteScope(e){let t=Atomics.load(e.state,2);for(;t>=0;){let n=Atomics.compareExchange(e.state,2,t,t+1);if(n===t)return!0;t=n}return!1}function createScopeRevision(){return{identity:_(),state:new Int32Array(new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT))}}function retainSqliteDatabaseWriteScopesForPath(t,n){let r=e.pathAdmission(t);if(!r||isSqliteDatabaseAdmissionRetired(r))return;let i=[],a=!1,release=()=>{if(!a){a=!0;try{for(let e of i)Atomics.sub(e.state,2,1);i.length>0&&!isSqliteDatabaseAdmissionRetired(r)&&pruneSqliteDatabaseWriteScopes(r)&&(advanceSqliteDatabaseGeneration(r,`publicationRevision`),e.publish(r,[]))}finally{e.release(r)}}};try{return e.retain(r),ensureWriteScopes(r,normalizedWriteScopes(n),i),release}catch(e){throw release(),e}}function retireSqliteDatabaseWriteScopes(t,n){let r=sqlPublicationAnchor(t),i=normalizedWriteScopes(n),a=e.admission(r),retire=()=>{let t=a?.writeScopes??$.localScopeRevisions.get(r),o=n.flatMap(e=>typeof e!=`string`&&e.partition===void 0?[normalizedWriteScopes([e])[0].slice(0,-1)+`,`]:[]);for(let e of t?.keys()??[])o.some(t=>e.startsWith(t))&&i.push(e);if(!a){let e=$.localScopeRevisions.get(r);for(let t of i)e?.delete(t);return}if(isSqliteDatabaseAdmissionRetired(a))return;let s=!1;for(let e of i){let t=a.writeScopes.get(e);t&&Atomics.exchange(t.state,1,1)===0&&(s=!0)}s&&(advanceSqliteDatabaseGeneration(a,`writeScopeRevision`),advanceSqliteDatabaseGeneration(a,`publicationRevision`),e.publish(a,i))};!stageSqliteTransactionState(r,{commit:retire})&&!t.isTransaction&&retire()}function scopedWriteToken(e,t,n,r=0){let i=readSqliteDatabaseGeneration(e,`schemaRevision`)+r|0,a=[];for(let r of t){let o=e.writeScopes.get(r);if(!o||Atomics.load(o.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,o.identity,Atomics.load(o.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`,($.localUnscopedRevisions.get(e)??0)+ +(n===null),t.map(t=>[t,$.localScopeRevisions.get(e).get(t).identity,Atomics.load($.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`,Oe(e)]:[`session-id`,Oe(e.sessionId),...e.partition===void 0?[]:[Oe(e.partition)]])))].toSorted()}function ensureLocalWriteScopes(e,t){let n=$.localScopeRevisions.get(e)??/* @__PURE__ */ new Map;for(let e of t)n.has(e)||n.set(e,createScopeRevision());$.localScopeRevisions.set(e,n)}function readScopedWriteToken(t,n,r,i=0){let a=normalizedWriteScopes(n),o=e.admission(t);if(o?ensureWriteScopes(o,a):ensureLocalWriteScopes(t,a),e.readRevision(t)!==void 0)return o?scopedWriteToken(o,a,r,i):localScopedWriteToken(t,a,r)}function readSqliteDatabaseScopedWriteToken(e,t){return readScopedWriteToken(sqlPublicationAnchor(e),t)}function readSqliteDatabaseScopedWriteTokenForPath(t,n){let r=normalizedWriteScopes(n),i=e.pathAdmission(t);if(i&&!isSqliteDatabaseAdmissionRetired(i))return ensureWriteScopes(i,r),scopedWriteToken(i,r)}function readSqliteDatabaseScopedWriteTokensForPath(t,n){let r=e.pathAdmission(t);if(!r||isSqliteDatabaseAdmissionRetired(r))return;let i=n.map(normalizedWriteScopes);return ensureWriteScopes(r,i.flat()),i.map(e=>scopedWriteToken(r,e))}function readSqliteDatabasePendingScopedWriteToken(t,n){let r=sqlPublicationAnchor(t);return readScopedWriteToken(r,n,$.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){$.pendingWriteScopes.delete(e)},begin(e,t){let n=t?void 0:$.writeScopes.get(e),r=$.pendingWriteScopes.get(e);if(!n||r===null)$.pendingWriteScopes.set(e,null);else{let t=r??/* @__PURE__ */ new Set;for(let e of n)t.add(e);$.pendingWriteScopes.set(e,t)}},finish(e,t){let n=$.pendingWriteScopes.get(e);$.pendingWriteScopes.delete(e);let r=!n;if(n){let i=$.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&&($.localUnscopedRevisions.set(e,($.localUnscopedRevisions.get(e)??0)+1),t&&advanceSqliteDatabaseGeneration(t,`unscopedWriteRevision`))},settleWorker,onSqliteDatabaseWriteSettled,retireSqliteDatabaseWriteScopes,retainSqliteDatabaseWriteScopesForPath,withSqliteDatabaseWriteScope,withoutSqliteDatabaseWriteScope,readSqliteDatabaseScopedWriteToken,readSqliteDatabaseScopedWriteTokenForPath,readSqliteDatabaseScopedWriteTokensForPath,readSqliteDatabasePendingScopedWriteToken,readSqliteDatabaseWriteTokenForPath,readSqliteDatabasePendingWriteToken}}D();const pm=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSchemaFacts`),()=>/* @__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 o=e.isTransaction;!i&&n&&!o&&(t.mutationRevision+=1),t.transactionOpen=o,(!n||!o)&&(t.transactionMutationRevision=o?a:void 0),(n!==o||r)&&(t.transactionSnapshot=void 0,t.transactionRead=!1,t.transactionCatalogBound=!1)}D(),jo();const mm=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseCleanCloseSeals`),()=>new SqliteDatabaseCleanCloseSeals(publishFact,{retain:e=>A.registry.changeReferences(e,1),release:releaseReference,publish:e=>A.registry.publish(e),descriptor:e=>A.registry.descriptors.get(e.identity)})),hm=createSqliteDatabaseDescriptorOwner(mm),{prepareSqliteDatabaseAdmissionAsync:gm,prepareSqliteDatabaseAdmission:_m,retainSqliteDatabaseAdmissionLocation:vm}=hm,{pathAdmission:ym}=hm,{getSqliteDatabaseAdmission:bm,getSqliteDatabaseSchemaRevision:xm,getOrLoadSqliteDatabaseAdmissionForPath:Sm,peekSqliteDatabaseAdmissionForPath:Cm,prepareSqliteDatabaseAdmissionForPath:wm,hasSqliteDatabaseSchemaAdmissionForPath:Tm,getSqliteDatabaseAdmissionIdentityForPath:Em,hasSqliteDatabaseSchemaAdmissionForIdentity:Dm}=createSqliteDatabaseAdmissionReader({state:A,admission,pathAdmission:ym,exchange:exchangeSqliteDatabaseAdmission,publishFact,retain:retainReference,release:releaseReference}),Om=createSqliteDatabaseWriteReceipts({admission,pathAdmission:ym,retain:retainReference,release:releaseReference,writeListeners:A.writeListeners,readRevision:readSqliteDatabaseWriteRevision,writer:e=>A.dataWriters.get(e),suspended:e=>A.suspended.has(e),hasPendingSchemaMutation:e=>e.isTransaction&&pm.get(e)?.transactionalSchema===!0,publish(e,t){A.registry.publish(e,t),exchangeSqliteDatabaseAdmission(e)}}),{onSqliteDatabaseWriteSettled:km,retireSqliteDatabaseWriteScopes:Am,retainSqliteDatabaseWriteScopesForPath:jm,withSqliteDatabaseWriteScope:Mm,withoutSqliteDatabaseWriteScope:Nm,readSqliteDatabaseScopedWriteToken:Pm,readSqliteDatabaseScopedWriteTokenForPath:Fm,readSqliteDatabaseScopedWriteTokensForPath:Im,readSqliteDatabasePendingScopedWriteToken:Lm,readSqliteDatabaseWriteTokenForPath:Rm,readSqliteDatabasePendingWriteToken:zm}=Om;function bindSqliteDatabaseAdmission(e,t){A.connections.delete(e),A.openedIdentities.delete(e),A.unproven.delete(e);let n=e.location();if(!n||n===`:memory:`)return;let r=_m(n);if(t!==void 0&&r!==t)throw Error(`SQLite database changed identity during native open`);if(!r)return;if(A.openedIdentities.set(e,r),t===void 0){A.unproven.add(e);return}let i=A.registry.records.get(r);(i&&!isSqliteDatabaseAdmissionRetired(i)||A.registry.descriptors.get(r)?.facts.size)&&admission(e)}function admission(e,t=!0){let n=A.openedIdentities.get(e);if(!e.isOpen||n===void 0||A.unproven.has(e))return;let r=A.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?ym(i):A.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=A.registry.changeReferences(r,1),i=!1;try{t&&exchangeSqliteDatabaseAdmission(r);let n=readSqliteDatabaseGeneration(r,`retired`);if(n===0)return A.connections.set(e,r),i=!0,r;if(n!==2)throw Error(`SQLite database admission retired during native open`)}finally{i||A.registry.changeReferences(r,-1)}let a=e.location(),o=e.isTransaction?A.registry.records.get(n):a?ym(a):void 0;if(!o||isSqliteDatabaseAdmissionRetired(o))throw Error(`SQLite database admission unavailable during native open`);r=o}}catch(t){throw A.openedIdentities.delete(e),t}}function releaseSqliteDatabaseAdmission(e){let t=A.connections.get(e);A.openedIdentities.delete(e)&&t&&(A.local.delete(e),releaseReference(t))}function retainReference(e){A.registry.changeReferences(e,1)&&exchangeSqliteDatabaseAdmission(e)}function releaseReference(e){A.registry.changeReferences(e,-1)&&(A.localSchemaRevisions.delete(e.identity),exchangeSqliteDatabaseAdmission(e))}function publishFact(e,t,n,r){if(t.writer===`host`&&w!==0)throw Error(`SQLite host-owned admission facts require the host publisher`);publishSqliteDatabaseFact(e,t,n,r,`${w}:${++A.publication}`)&&(A.registry.publish(e),t.writer!==`connection`&&exchangeSqliteDatabaseAdmission(e))}function beginSqliteDatabaseWrite(e,t=!1){let n=admission(e);n&&Atomics.load(new Int32Array(n.generation),k.sealPresent)===1&&mm.invalidate(n.location,n),Om.begin(e,t),!A.dataWriters.has(e)&&(A.dataWriters.set(e,n),n&&Atomics.add(new Int32Array(n.references.get(w)),1,1))}function finishSqliteDatabaseWrite(e,t=!1){if(!A.dataWriters.has(e))return;let n=A.dataWriters.get(e);if(A.dataWriters.delete(e),t)Om.cancel(e),n&&Atomics.sub(new Int32Array(n.references.get(w)),1,1);else if(A.localWriteRevisions.set(e,(A.localWriteRevisions.get(e)??0)+1),Om.finish(e,n),n){advanceSqliteDatabaseGeneration(n,`writeRevision`),Atomics.sub(new Int32Array(n.references.get(w)),1,1);let e=A.writeListeners.get(n);e&&notifyListeners(e,void 0)}}function readSqliteDatabaseWriteRevision(e){let t=sqlPublicationAnchor(e);if(!t.isOpen||A.suspended.has(t))return;let n=admission(t);if(!n){let e=t.location();return!e||e===`:memory:`?A.localWriteRevisions.get(t)??0:void 0}return readSqliteDatabaseGeneration(n,`writeRevision`)}function publishSqliteDatabaseAdmission(e,t,n,r={}){let i=sqlPublicationAnchor(e),a=admission(i,!e.isTransaction);if(!a||isSqliteDatabaseAdmissionRetired(a)||A.suspended.has(i))return;if(t.writer===`host`&&w!==0)throw Error(`SQLite host-owned admission facts require the host publisher`);let o=(t.schemaDependent?r.schemaRevision:void 0)??readSqliteDatabaseFactRevision(a,t.schemaDependent),s=isPostgresSqlConnection(e)?void 0:getSqliteNativeAdmissionFacts(e),c=admitSqliteDatabaseFactValue(t,n);if(!s&&!e.isTransaction&&!hasSqlitePostCommitScope(e)){publishFact(a,t,c,o);return}let l={...c,revision:o,schemaDependent:t.schemaDependent===!0,ddlRevision:A.ddlRevisions.get(i)??0};if(s){s.set(t.name,l);return}let u=A.local.get(i)??/* @__PURE__ */ new Map;A.local.set(i,u);let d=u.get(t.name);stageSqliteTransactionState(i,{stage:()=>u.set(t.name,l),rollback:()=>{A.local.get(i)===u&&(d===void 0?u.delete(t.name):u.set(t.name,d))},commit:()=>{A.local.get(i)===u&&u.get(t.name)===l&&(u.delete(t.name),l.revision===readSqliteDatabaseFactRevision(a,l.schemaDependent)&&(!l.schemaDependent||l.ddlRevision===(A.ddlRevisions.get(i)??0))&&publishFact(a,t,l,l.revision))}})}function invalidateLocalSqliteSchemaAdmissions(e){let t=sqlPublicationAnchor(e),n=A.ddlRevisions.get(t)??0,r=A.schemaDirty.has(t),stage=()=>{A.ddlRevisions.set(t,n+1),A.schemaDirty.add(t)};stageSqliteTransactionState(t,{stage,commit:()=>{},rollback:()=>{A.ddlRevisions.set(t,n),r||A.schemaDirty.delete(t)}})||stage()}function discardSqliteDatabaseTransactionAdmissions(e){let t=sqlPublicationAnchor(e),n=admission(t,!1);for(let r of[isPostgresSqlConnection(e)?void 0:getSqliteNativeAdmissionFacts(e),A.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()}A.local.delete(t),A.rolledBack.add(t),e.isTransaction||A.schemaDirty.delete(t)}function publishSqliteDatabaseSchemaChange(e){let t=sqlPublicationAnchor(e),n=admission(t,!1);if(n){let e=advanceSqliteDatabaseGeneration(n,`schemaRevision`),r=A.ddlRevisions.get(t)??0;for(let n of A.local.get(t)?.values()??[])n.schemaDependent&&n.revision===e&&n.ddlRevision===r&&(n.revision=e+1)}else{let e=A.openedIdentities.get(t);e&&A.localSchemaRevisions.set(e,(A.localSchemaRevisions.get(e)??0)+1)}e.isTransaction||A.schemaDirty.delete(t)}function suspendSqliteDatabaseAdmission(e,t){t?A.suspended.add(e):A.suspended.delete(e)}const Bm={name:`database.engine.schema`,schemaDependent:!0};function getPostgresPhysicalFacts(e,t){return bm(e,Bm,t)}D();const Vm=resolveGlobalSingleton(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap);function getSqlitePinnedReadSnapshot(e){return Vm.get(e)}function runSqliteSchemaReadSnapshotSync(e,t){let n=Vm.get(e);for(let r=0;;r+=1){Vm.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(!C&&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||Vm.delete(e)}}}T();const Hm={name:`sqlite-schema`,writer:`connection`,lifetime:`process`,schemaDependent:!0,read:e=>isRecord(e)?e:void 0},Um={name:`sqlite-text-encoding`,writer:`connection`,lifetime:`process`,read:e=>typeof e==`string`?e:void 0};function readSqliteTextEncoding(e){let t=bm(e,Um);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=bm(e,Um),i=runSqliteSchemaReadSnapshotSync(e,i=>{let a=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get()),o=Number(a?.user_version??0);n?.(o);let s=r??readSqliteTextEncoding(e),c=readSqliteSchemaObjects(e),l={admissionId:_(),revision:t,userVersion:o,textEncoding:s,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 c){if(typeof e.name!=`string`)continue;let t=typeof e.sql==`string`?e.sql:null;switch(e.type){case`table`:l.tables.add(e.name),l.tableSql.set(e.name,t);break;case`view`:l.views.add(e.name);break;case`index`:l.indexes.add(e.name),typeof e.tbl_name==`string`&&l.indexDefinitions.set(e.name,{table:e.tbl_name,sql:t});break;case`trigger`:typeof e.tbl_name==`string`&&l.triggers.set(e.name,{table:e.tbl_name,sql:t})}}return l});return r===void 0&&(i.tables.size>0||i.views.size>0)&&publishSqliteDatabaseAdmission(e,Um,i.textEncoding),i}function captureTrackedSqliteSchemaFacts(e,t,n){t.capturing=!0;try{return captureSqliteSchemaFacts(e,t.revision,n)}finally{t.capturing=!1}}function invalidateTrackedSqliteSchemaFacts(e){e.revision+=1,e.facts=void 0}function observeSchemaLifetime(e,t,n){t.snapshot&&t.snapshot!==n&&((!e.isTransaction||!t.transactionCatalogBound)&&invalidateTrackedSqliteSchemaFacts(t),t.snapshot=void 0,t.qualifiedSnapshot=void 0);let r=xm(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)}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),o=r.filter(e=>e.type===`table`).map(e=>e.name),s=[...a,...o],c=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 (${o.map(()=>`?`).join(`,`)}))`,s,e=>e.all(...s)),l=c.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(c.flatMap(e=>e.type===`trigger`&&typeof e.name==`string`?[e.name.toLowerCase()]:[]))),unexpected:l}}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`,o=`${r} ON ${n}(state, session_id)`,s=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.${o};
    ${s.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 ${o}`},...s.map(e=>({name:e.name,type:`trigger`,table:e.table,sql:`CREATE ${e.definition}`}))]}}D(),resolveGlobalSingleton(Symbol.for(`openclaw.postgresReadSnapshots`),()=>/* @__PURE__ */ new WeakMap);function invalidateSqliteSchemaFacts(e){xm(e),invalidateSchemaFacts(e,!0)}function invalidateSchemaFacts(e,t,n=`main`,r=n!==`temp`){let i=pm.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:o}=n,s=a?.outerRollback!==!0&&n.schemaChange,c=n.mainSchemaChange&&a?.outerRollback!==!0;observeSqliteTransactionState(e,t);let l=i===`bind`?void 0:getSqlitePinnedReadSnapshot(e),u=i!==`bind`&&!l&&!t.capturing?{}:void 0;if(l&&l!==t.snapshot&&!t.capturing){if(e.isTransaction&&(t.transactionRead||t.transactionCatalogBound)&&t.processRevision!==xm(e))t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.transactionalFacts=!0;else if(observeSchemaLifetime(e,t,void 0),!t.facts&&!t.transactionalSchema){let n=bm(e,Hm);n&&(t.facts={...n,revision:t.revision})}t.snapshot=l,t.qualifiedSnapshot=l}t.nativeDepth===0&&settle();let d=e.isTransaction;if((r||t.processRevision===void 0)&&!d&&(a?.kind===`BEGIN`||a?.kind===`SAVEPOINT`)){let n=xm(e);t.processRevision??=n}let f=!d&&a?.kind===`BEGIN`&&a.single?t.mutationRevision:void 0;!d&&a?.kind===`BEGIN`&&t.admitted&&getAdmittedSqliteSchemaFacts(e);let p=!!a&&!canPreserveTransactionSnapshot(a,d),m=a?.kind===`ROLLBACK`,h=m&&t.transactionalSchema&&!a.outerRollback,g=s&&!n.temporaryTableSchemaChange||m&&t.transactionalSchema,_=c||h?`main`:m?t.transactionalTempSchema&&!t.transactionalSchema?`temp`:`rollback`:n.temporaryTableSchemaChange?`temp`:`local`;m&&discardSqliteDatabaseTransactionAdmissions(e),(s||m)&&invalidateSchemaFacts(e,!1,_,g),(o||n.temporaryTableSchemaChange||a?.kind===`ROLLBACK`)&&(t.mutationRevision+=1),i!==`bind`&&d&&!a&&!t.transactionCatalogBound&&(t.transactionRead=!0);let v=s||o||a!==void 0,ee=n.temporaryWriteTables?.every(e=>t.isolatedTempTables.has(e));(o&&!ee||c)&&beginSqliteDatabaseWrite(e,c||t.nativeDepth>0),v&&(t.mutationDepth+=1),t.nativeDepth+=1;let te=beginSqliteDatabaseAdmissionOperation(e),ne=t.schemaMutationRevision;return c&&(t.schemaMutationRevision+=1),t.pendingSchema||=c,u&&t.unmanagedSnapshots.add(u),{stepped:()=>{l&&t.facts&&e.isTransaction&&(t.transactionCatalogBound=!0)},finish:(n,r,i)=>{if(u&&t.unmanagedSnapshots.delete(u)&&t.iteratorFacts&&(invalidateTrackedSqliteSchemaFacts(t),t.iteratorFacts=!1),te(),--t.nativeDepth,v&&--t.mutationDepth,!e.isOpen)return;(s||m)&&(m&&discardSqliteDatabaseTransactionAdmissions(e),invalidateSchemaFacts(e,!1,_,g));let o=n&&d&&a?.outerRollback===!0&&!e.isTransaction&&!c&&t.schemaMutationRevision===ne;if(o&&(settle(!1,!0),t.pendingSchema=!1),t.nativeDepth===0){t.settling=!0;try{let i=t.pendingSchema||t.transactionalSchema;!o&&t.pendingSchema&&!e.isTransaction&&!t.transactionalSchema&&publishSqliteDatabaseSchemaChange(e),o||settle(p),i&&!e.isTransaction&&!o&&(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,d,p,n,f),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:o}=prepareSqliteTempTrackingSchema(e,r);try{if(i(()=>n.DatabaseSync.prototype.exec.call(e,a),{schemaChange:o,mainSchemaChange:o,temporaryTableSchemaChange:!1,dataChange:!0,temporaryWriteTables:[],control:void 0}),!o)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(!pm.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};pm.set(e,r),trackSchemaChanges(e,r,t,n);let i=xm(e,{existingOnly:!0}),a=bm(e,Hm,{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=pm.get(e);if(!n?.admitted||n.authorizerActive)return;let r=getSqlitePinnedReadSnapshot(e),i=e.isTransaction&&(n.transactionRead||n.transactionCatalogBound)&&n.processRevision!==xm(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 o=i||!!r||n.transactionalSchema,s=n.transactionalSchema||o?void 0:bm(e,Hm);if(s)return t?.(s.userVersion),n.facts={...s,revision:n.revision},n.facts;let c=xm(e);n.facts=captureTrackedSqliteSchemaFacts(e,n,t),n.iteratorFacts||=n.unmanagedSnapshots.size>0,n.qualifiedSnapshot=r,n.transactionCatalogBound||=e.isTransaction,o||publishSqliteDatabaseAdmission(e,Hm,n.facts,{schemaRevision:c})}return n.facts}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){let n=requireNodeSqlite(),r=resolveNodeSqliteLocation(e),i=t?.open===!1?void 0:_m(r,{create:t?.readOnly!==!0}),a=new n.DatabaseSync(r,t??{});if(a.isOpen)try{bindSqliteDatabaseAdmission(a,i)}catch(e){throw a.close(),e}return a.open=()=>{let e=_m(r,{create:t?.readOnly!==!0});n.DatabaseSync.prototype.open.call(a);try{bindSqliteDatabaseAdmission(a,e)}catch(e){throw a.close(),e}},trackSqliteSchema(a,{DatabaseSync:n.DatabaseSync,StatementSync:n.StatementSync},t?.readOnly!==!0),a.isOpen&&t?.timeout!==void 0&&rememberSqliteBusyTimeout(a,Math.max(0,t.timeout)),getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources||registerNodeSqliteDisposeCallback(a,()=>{}),registerSqliteReaderConnection(a),a}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};function getStateSchemaFacts(e){return isPostgresSqlConnection(e)?getPostgresPhysicalFacts(e):getAdmittedSqliteSchemaFacts(e)}const Wm={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}}},Gm=/* @__PURE__ */ new WeakMap;function rememberConnectionVersion(e,t){let n=Gm.get(e),install=t=>{t?Gm.set(e,t):Gm.delete(e)};stageSqliteTransactionState(e,{stage:()=>install(t),commit:()=>{},rollback:()=>install(n)})||install(t)}function schemaVersionKey(e){return{name:`state.schema-version:${e}`,read:Wm.read}}function getStateSchemaVersionAdmission(e){let t=getStateSchemaFacts(e);if(!t)return;let n=Gm.get(e);if(n?.schema===t)return n.facts;let r=bm(e,schemaVersionKey(t.admissionId)),i=r?void 0:bm(e,Hm);if(!r&&!isPostgresSqlConnection(e)&&i?.admissionId!==t.admissionId)return;let a=r??bm(e,Wm);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=bm(e,Hm);(isPostgresSqlConnection(e)||r?.admissionId===n.admissionId)&&(publishSqliteDatabaseAdmission(e,schemaVersionKey(n.admissionId),t),publishSqliteDatabaseAdmission(e,Wm,t))}function tableExists(e,t){if(isPostgresSqlConnection(e))return getPostgresPhysicalFacts(e)?.catalog.some(e=>e.table===t&&e.kind===`table`)??!1;let n=getAdmittedSqliteSchemaFacts(e);return n?n.tables.has(t):executeWithCachedStatement(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}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}const Km=`state.schema.contentVersion`;var PostgresSchemaAdmissionUnavailableError=class extends Error{};const qm=createSqliteQueryCache(e=>prepareSqliteQuerySync(e,()=>getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,Km)));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),o=parseStateSchemaContentVersion(tableExists(e,`config_machine_state`)?n(e)?.value_json:void 0);return rememberStateSchemaVersionAdmission(e,{userVersion:a,contentVersion:o}),Math.max(t??a,o)}function readStateSchemaContentVersionRow(e){return qm(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 ${Km}.`,{cause:e})}if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${Km}.`);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),o=n?.contentVersion??(a>36?a:readStateSchemaContentVersion(e,a,r,a));if(o>36)throw createNewerSqliteSchemaVersionError(`OpenClaw state database`,t,o,36,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()}}Ge(),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{};