UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

16 lines • 51.5 kB
import{i as e}from"./transcript-global-singleton-DIJgobpU.mjs";import{A as t,_ as n}from"./transcript-plugin-instance-invocation-7pP9ZY8b.mjs";import{p as r,w as i}from"./transcript-worker-cpu-DTToyx8O.mjs";import"./transcript-detached-async-context-BKXaSw-L.mjs";import{r as a}from"./transcript-redact-Zu5ZXEyS.mjs";import{S as o,a as s,p as c,s as l,st as u,t as d,x as f}from"./transcript-sqlite-database-admission-Cro6ZHgY.mjs";import"./transcript-errno-CsW5NI8i.mjs";import{C as p,_ as m,b as h,g,v as ee,x as te,y as ne}from"./transcript-sqlite-error-diagnostics-Bzt01wuM.mjs";import{o as _,p as v}from"./transcript-subsystem-er2pCebD.mjs";import{r as y}from"./transcript-string-coerce-BxRUqIXb.mjs";import{n as re}from"./transcript-number-coercion-Dr06QpMa.mjs";import{a as ie,n as b,r as x,t as ae}from"./transcript-sql-connection-CRz-dHXM.mjs";import{c as oe,i as se,n as ce,s as le}from"./transcript-sqlite-post-commit-BDZjIt2B.mjs";import{D as S,F as ue,G as de,I as C,K as fe,L as pe,M as me,N as he,P as ge,R as w,S as _e,V as ve,W as ye,j as be,k as xe,r as Se,w as Ce,z as we}from"./transcript-sqlite-schema-facts-C4Tsn8VX.mjs";import{_ as Te,a as Ee,d as De,f as Oe,g as T,m as E,p as ke,r as D}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import{c as Ae,l as O}from"./transcript-sqlite-transaction-BxeoS_ke.mjs";import{l as je,r as Me,t as Ne}from"./transcript-runtime-worker-url-D1R86-Xb.mjs";import{n as Pe}from"./transcript-node-crypto-2Kpo-Xy-.mjs";import{t as Fe}from"./transcript-sqlite-schema-catalog-DeSRZE9G.mjs";import{d as Ie,f as k,m as Le,n as Re,s as ze,t as Be,u as A,v as Ve}from"./transcript-child-CaF3s4Mr.mjs";import{g as He,h as Ue,m as We,s as Ge}from"./transcript-sqlite-search-schema-6CT7CNVB.mjs";import{t as Ke}from"./transcript-windows-appcontainer-spawn-B5U_BRTp.mjs";import{serialize as qe}from"node:v8";import{MessageChannel as Je,receiveMessageOnPort as Ye,threadId as j}from"node:worker_threads";import M from"node:path";import{AsyncLocalStorage as N}from"node:async_hooks";import{createHash as P}from"node:crypto";import F,{readFile as Xe}from"node:fs";import"node:os";import{promisify as Ze}from"node:util";import{spawn as I}from"node:child_process";function toStringifiedError(e){return e instanceof Error?e:Error(String(e))}function normalizeExecutableToken(e){let t=M.win32.basename(e),n=M.posix.basename(e),r=t.length<n.length?t:n;return y(r).replace(/\.(?:exe|cmd|bat|com)$/,``)}const L=/* @__PURE__ */ new Set([`-lc`,`-c`,`--command`,`--commands`,`--cmdline`]);[...L];function expandPowerShellSwitchPrefixForms(e,t){let n=[];for(let r=t.length;r<=e.length;r+=1){let t=e.slice(0,r);n.push(`-${t}`,`--${t}`,`/${t}`)}return n}function expandPowerShellSwitchForms(e){return e.flatMap(e=>{let t=y(e);return[`-${t}`,`--${t}`,`/${t}`]})}const R=[...expandPowerShellSwitchPrefixForms(`command`,`c`),...expandPowerShellSwitchPrefixForms(`commandwithargs`,`cwa`),...expandPowerShellSwitchForms([`cwa`])],z=expandPowerShellSwitchPrefixForms(`file`,`f`),Qe=new Set(z);new Set(expandPowerShellSwitchPrefixForms(`noprofile`,`nop`)),[...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchForms([`ea`]),...expandPowerShellSwitchPrefixForms(`interactive`,`i`),...expandPowerShellSwitchPrefixForms(`login`,`l`),...expandPowerShellSwitchPrefixForms(`namedpipeservermode`,`nam`),...expandPowerShellSwitchPrefixForms(`noexit`,`noe`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchForms([`pscf`]),...expandPowerShellSwitchPrefixForms(`servermode`,`s`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`socketservermode`,`so`),...expandPowerShellSwitchPrefixForms(`sshservermode`,`ssh`),...expandPowerShellSwitchPrefixForms(`v2socketservermode`,`v2so`)];const $e=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`encodedcommand`,`e`),...expandPowerShellSwitchPrefixForms(`ec`,`e`)]),et=/* @__PURE__ */ new Set([...R,...z,...$e]),tt=new Set(R),nt=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchPrefixForms(`executionpolicy`,`ex`),...expandPowerShellSwitchPrefixForms(`inputformat`,`inp`),...expandPowerShellSwitchPrefixForms(`outputformat`,`o`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`token`,`to`),...expandPowerShellSwitchPrefixForms(`utctimestamp`,`utc`),...expandPowerShellSwitchPrefixForms(`version`,`v`),...expandPowerShellSwitchPrefixForms(`windowstyle`,`w`),...expandPowerShellSwitchPrefixForms(`workingdirectory`,`w`),...expandPowerShellSwitchForms([`ea`,`ep`,`if`,`of`,`pscf`,`wd`])]),rt=/* @__PURE__ */ new Set([`--init-file`,`--rcfile`]);function countSeparateValueOptionChars(e,t){let n=0;for(let r=1;r<e.length;r+=1){let i=e[r];(i===`o`||i===`O`&&t!==`zsh`)&&(n+=1)}return n}function parseCombinedCommandFlag(e,t){if(e.length<2||e[0]!==`-`||e[1]===`-`)return null;let n=e.slice(1),r=n.indexOf(`c`);if(r===-1||n.includes(`-`))return null;let i=n.slice(r+1);return i&&!/^[A-Za-z]+$/.test(i)?{attachedCommand:i,separateValueCount:0}:{attachedCommand:null,separateValueCount:countSeparateValueOptionChars(e,t)}}function combinedSeparateValueOptionCount(e,t){return e.length<2||e[0]!==`-`&&e[0]!==`+`||e[1]===`-`||e.slice(1).includes(`-`)?0:countSeparateValueOptionChars(e,t)}function advancePosixInlineOptionScan(e,t){let n=combinedSeparateValueOptionCount(e,t);return n>0?1+n:rt.has(e)?2:1}function isPowerShellOptionToken(e){return e.startsWith(`-`)||/^\/[A-Za-z][A-Za-z0-9]*$/.test(e)}function resolveInlineCommandMatch(e,t,n={}){let r=normalizeExecutableToken(e[0]??``);for(let i=1;i<e.length;){let a=e[i]?.trim();if(!a){i+=1;continue}let o=y(a);if(o===`--`)break;let s=n.allowCombinedC?a:o,c=t.has(s),l=!c&&n.allowCombinedC?parseCombinedCommandFlag(a,r):null;if(c||l){if(l&&l.attachedCommand!==null)return{command:l.attachedCommand.trim()||null,valueTokenIndex:i};let t=i+1+(l?.separateValueCount??0),r=!l&&t>=e.length?null:t;return{command:(c&&n.restValueFlags?.has(s)?e.slice(i+1).map(e=>e.trim()).join(` `).trim():e[t]?.trim())||null,valueTokenIndex:r}}if(n.valueOptions?.has(o)){i+=2;continue}let u=n.isOptionToken?.(a)??(a.startsWith(`-`)||a.startsWith(`+`));if(n.stopAtFirstNonOption&&!u||n.allowCombinedC&&!a.startsWith(`-`)&&!a.startsWith(`+`))break;i+=n.allowCombinedC?advancePosixInlineOptionScan(a,r):1}return{command:null,valueTokenIndex:null}}function resolvePowerShellInlineCommandMatch(e){return resolveInlineCommandMatch(e,et,{isOptionToken:isPowerShellOptionToken,restValueFlags:tt,stopAtFirstNonOption:!0,valueOptions:nt})}function isPowerShellInlineFileCommandFlag(e){return Qe.has(y(e))}const B=`OPENCLAW_CHILD_OOM_SCORE_ADJ`,V=`/bin/sh`,H='echo 1000 > /proc/self/oom_score_adj 2>/dev/null; if [ "${OC_INTERNAL_OOM_EXEC_BASH_ENV+x}" = x ]; then BASH_ENV="$OC_INTERNAL_OOM_EXEC_BASH_ENV"; export BASH_ENV; fi; unset OC_INTERNAL_OOM_EXEC_BASH_ENV; if [ "${OC_INTERNAL_OOM_EXEC_ENV+x}" = x ]; then ENV="$OC_INTERNAL_OOM_EXEC_ENV"; export ENV; fi; unset OC_INTERNAL_OOM_EXEC_ENV; if [ "${OC_INTERNAL_OOM_EXEC_CDPATH+x}" = x ]; then CDPATH="$OC_INTERNAL_OOM_EXEC_CDPATH"; export CDPATH; fi; unset OC_INTERNAL_OOM_EXEC_CDPATH; if [ "${OC_INTERNAL_OOM_EXEC_PS4+x}" = x ]; then PS4="$OC_INTERNAL_OOM_EXEC_PS4"; export PS4; fi; unset OC_INTERNAL_OOM_EXEC_PS4; exec "$0" "$@"';function raiseChildOomScore(e){if(e!==void 0)try{F.writeFileSync(`/proc/${e}/oom_score_adj`,`1000`)}catch{}}function shouldAdjustChildOomScore(e){if((e?.platform??process.platform)!==`linux`)return!1;let n=e?.env?.[B]??process.env[B];return t(n)!==!1}function isWrapped(e,t){return e===`/bin/sh`&&t[0]===`-c`&&t[1]===`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`}function resolveOomScoreWrappedCommand(e,t){return e===`/bin/sh`&&t[0]===`-c`&&(t[1]===`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`||t[1]===H)&&t[2]?t[2]:void 0}const U=e(Symbol.for(`openclaw.childProcessSpawnCounts`),()=>({counts:/* @__PURE__ */ new Map,sampledAt:performance.now()})),it=/^(node|bun|git|ps|pgrep|lsof|sh|bash|zsh|cmd|powershell|pwsh|npm|pnpm|python|python3|uv|ssh|openclaw)$/,at=e(Symbol.for(`openclaw.gitSpawnOperation`),()=>new N),ot=e(Symbol.for(`openclaw.childSpawnOperation`),()=>new N);function unscopedProcessOperation(e,t,n){if(n[0]===`--version`||n[0]===`-v`&&(e===`node`||e===`bun`||t===`gh`))return`unscoped.version`;if(e===`powershell`||e===`pwsh`){let e=[t,...n],{command:r,valueTokenIndex:i}=resolvePowerShellInlineCommandMatch(e);return r!==null&&i!==null&&!isPowerShellInlineFileCommandFlag(e[i-1]??``)?`unscoped.shell-command`:`unscoped.shell`}return/^(sh|bash|zsh)$/.test(e)?resolveInlineCommandMatch([t,...n],L,{allowCombinedC:!0}).command===null?`unscoped.shell`:`unscoped.shell-command`:e===`cmd`?n.some(e=>/^-[a-z]*c$/.test(e)||/^\/(?:c|k)$/i.test(e))?`unscoped.shell-command`:`unscoped.shell`:e===`node`||e===`bun`?`unscoped.runtime`:e===`other`&&/^(gh|docker|podman|which|uname|sw_vers|sysctl|curl|tar)$/.test(t)?`unscoped.${t}`:`unscoped.command`}function unscopedGitOperation(e){let t=0;for(;t<e.length;){let n=e[t];if([`-C`,`-c`,`--git-dir`,`--work-tree`,`--namespace`,`--config-env`].includes(n))t+=2;else if(/^--(?:git-dir|work-tree|namespace|config-env|attr-source)=/u.test(n))t++;else if([`--no-pager`,`--no-optional-locks`,`--no-lazy-fetch`,`--literal-pathspecs`,`--bare`].includes(n))t++;else break}let n=e[t]??``;return/^(config|rev-parse|status|diff|ls-files|rev-list|merge-base|cat-file|symbolic-ref|for-each-ref|show-ref|remote|log|show|hash-object|update-ref|worktree|branch|fetch|clone|init|checkout|read-tree|write-tree|commit-tree|pack-objects|index-pack|maintenance|multi-pack-index|gc|fast-import|add|commit|push|reset|clean|merge|tag|describe|switch|ls-tree|update-index|check-ref-format|diff-tree|diff-index|diff-files|sparse-checkout|checkout-index|check-attr|mktree|var|apply|fsck|ls-remote|rebase|reflog)$/u.test(n)?`unscoped.${n}`:n===`--version`||n===`version`?`unscoped.version`:`unscoped.other`}function prepareChildProcessSpawnRecorder(e,t=[],n){if(!_())return;let r=resolveOomScoreWrappedCommand(e,t),i=r?t.slice(3):t,a=M.win32.basename(r??e).toLowerCase().replace(/\.(exe|cmd)$/,``),o=it.test(a)?a:`other`,s=o===`git`?at.getStore()??ot.getStore()??unscopedGitOperation(i):n??ot.getStore()??unscopedProcessOperation(o,a,i),c=`${o}:${s}`;return()=>{if(_()){let e=U.counts.get(c);U.counts.set(c,{family:o,operation:s,count:(e?.count??0)+1})}}}function recordChildProcessSpawn(e,t,n,r=[]){let i=prepareChildProcessSpawnRecorder(e,r,n);i&&t.once(`spawn`,i)}const st=e(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return st.role}let W=0;function withEngineStoreAdmission(e){W+=1;try{let t=e();if(ie(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--W}}function assertEngineStoreExecutionAllowed(){if(j===0&&W===0&&st.role!==`cli-oneshot`)throw Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}const G=18e5;function resolveAgentDatabaseIdleHandleTtlMs(){return getDatabaseProcessRole()===`cli-oneshot`?3e4:G}const ct=36e5,K=/* @__PURE__ */ new Map;function closeBridge(e){e.port.close()}function closeIdleBridges(){let e=[...K.values()];K.clear(),unwatch();for(let{bridge:t,timeout:n}of e)clearTimeout(n),closeBridge(t)}function unwatch(){K.size||(process.off(`beforeExit`,closeIdleBridges),process.off(`exit`,closeIdleBridges))}function removeIdleBridge(e){let t=K.get(e);return K.delete(e),t&&clearTimeout(t.timeout),unwatch(),t}function takeIdlePostgresBridge(e){let t=removeIdleBridge(e);if(t){if(Atomics.load(t.bridge.service,1))closeBridge(t.bridge);else return{bridge:t.bridge,validate:Date.now()-t.releasedAt>=1e3}}}function retainIdlePostgresBridge(e,t){let n=removeIdleBridge(e);if(n&&closeBridge(n.bridge),K.size===2){let e=K.keys().next().value;closeBridge(removeIdleBridge(e).bridge)}K.size||(process.once(`beforeExit`,closeIdleBridges),process.once(`exit`,closeIdleBridges));let r=setTimeout(()=>{let t=removeIdleBridge(e);t&&closeBridge(t.bridge)},18e4);r.unref(),K.set(e,{bridge:t,timeout:r,releasedAt:Date.now()})}function postgresBridgeReuseKey(e){return Pe(JSON.stringify([e.url,e.lockTimeoutMs??6e4,e.statementTimeoutMs??9e4,e.readOnly===!0]))}function preparedBridgeKey(e){return JSON.stringify([postgresBridgeReuseKey(e),e.schema,e.storeId])}function createPostgresBridge(e){let{port1:t,port2:n}=new Je,r=new SharedArrayBuffer(8),a=new Int32Array(r),{port:o,signal:s,nextStep:c}=Ve(),l=new Int32Array(s);if(Atomics.load(l,1)){t.close(),n.close();let e=/* @__PURE__ */ Error(`PostgreSQL I/O service is unavailable.${c?` Run ${c}.`:``}`);throw i(e),e}try{o.postMessage({connection:{port:n,signal:r,url:e.url,schema:e.schema,connectTimeoutMs:6e4,lockTimeoutMs:e.lockTimeoutMs??6e4,statementTimeoutMs:e.statementTimeoutMs??9e4,readOnly:e.readOnly===!0}},[n])}catch(e){throw t.close(),n.close(),e}return t.unref(),{port:t,control:a,service:l,nextStep:c,requestId:0}}const lt=new N;function findPreparedBridge(e){let t=lt.getStore();for(;t;){if(t.key===e&&t.bridge&&!Atomics.load(t.bridge.service,1))return t;t=t.parent}}function takePreparedPostgresBridge(e){let t=findPreparedBridge(preparedBridgeKey(e)),n=t?.bridge;return t&&n&&(t.bridge=void 0,t.detachAbort()),n}function assertPostgresOperationCurrent(){let e=Le.getStore();if(e&&(!e.active||e.owner.refusal))throw e.owner.refusal??/* @__PURE__ */ Error(`PostgreSQL worker operation is no longer active`)}function runPostgresTransactionSync(e,t,n,r=!1,i=!1){assertPostgresOperationCurrent();let a=x(e);return oe(a,()=>{let a=e.isTransaction&&!i,o=!1,s;try{r&&!a&&(s=Se(e)),a?e.exec(`SAVEPOINT openclaw_tx_nested`):e.isTransaction||e.exec(r?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);let i=n?.maintenance&&a?String(e.prepare(`SHOW statement_timeout`).get().statement_timeout):void 0;n?.maintenance&&e.exec(`SET LOCAL statement_timeout = '${ct}ms'`);let c=t();if(ae(c),a)i!==void 0&&e.prepare(`SELECT set_config('statement_timeout', ?, true)`).get(i),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||se(e),e.exec(r?`ROLLBACK`:`COMMIT`),o=!r};n?.withCommit?ae(n.withCommit(commit)):commit()}return c}catch(t){let n=p(t)||o;if(!n)try{a?(e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)):e.isTransaction&&e.exec(`ROLLBACK`)}catch{n=!0}if(n)try{ce(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{s?.()}})}function beginPostgresReadOnlyTransaction(e){if(e.isTransaction)throw Error(`A held PostgreSQL read snapshot requires an idle connection`);assertPostgresOperationCurrent();let t,end=()=>{try{e.isTransaction&&e.exec(`ROLLBACK`)}catch{try{e.close()}catch{}}finally{t?.()}};try{t=Se(e),e.exec(`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`)}catch(e){throw end(),e}return end}var PostgresSyncConnection=class{constructor(e,t,n,r,i){this.schema=t,this.anchor=n,this.storeId=r,this.isOpen=!0,this.isTransaction=!1,this.mutationRevision=0,this.lastResponseAt=Date.now(),this.outcomeUnknown=!0,this.readOnlyTransaction=!1,this.pendingWrite=!1,this.mainThread=j===0,this.maintenance=!1,assertEngineStoreExecutionAllowed(),this.admissionReadOnly=i?.readOnly===!0,Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=P(`sha256`).update(r).digest().readBigInt64BE(),this.bridgeParameters={url:e,schema:t,storeId:r,...i},this.reuseKey=i?.reuse?postgresBridgeReuseKey(this.bridgeParameters):void 0,this.connect()}connect(){let e=this.reuseKey?takeIdlePostgresBridge(this.reuseKey):void 0,t=e?.bridge??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(this.bridgeParameters);if(this.bridge=t,this.idleCheckout=e?e.validate?`validate`:`reconnect`:void 0,t.port.unref(),e)return t;try{this.request({operation:`connect`,schema:this.schema})}catch(e){throw this.isOpen=!1,this.isTransaction=!1,this.bridge=void 0,t.port.close(),e}return t}runTransaction(e,t,...n){let r=this.maintenance;this.maintenance=r||t?.maintenance===!0;try{return runPostgresTransactionSync(this,e,t,this.admissionReadOnly||n[0],n[1])}finally{this.maintenance=r}}readRecoveryGeneration(e=!1){return this.request({operation:`recovery-generation`,schema:this.schema,storeId:this.storeId,lock:e},!1)}loseConnection(){!this.failure&&this.outcomeUnknown&&(this.pendingWrite=!0,d(x(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new te(`PostgreSQL connection lost; outcome unknown`,`outcome-unknown`):/* @__PURE__ */ Error(`PostgreSQL connection lost; transaction rolled back`);let e=this.bridge;return e?.nextStep&&!this.failure.message.includes(e.nextStep)&&(this.failure.message+=` Run ${e.nextStep}.`),e&&Atomics.load(e.service,1)&&i(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,s(x(this)))}assertOpen(){if(this.failure)throw this.failure;if(!this.isOpen)throw Error(`PostgreSQL connection is closed`)}request(e,t=!0){this.mainThread&&e.operation!==`close`&&e.operation!==`release`&&assertEngineStoreExecutionAllowed(),this.assertOpen();let n=this.bridge??this.connect();this.outcomeUnknown=t;let i=++n.requestId;if(i>2147483647)throw this.loseConnection();let a=(this.maintenance?ct:this.bridgeParameters.statementTimeoutMs??9e4)+3e4,o=performance.now()+a,s=n.inTransaction===!1,c=(this.idleCheckout!==void 0||s)&&(e.operation===`query`||e.operation===`recovery-generation`),l=c&&(this.idleCheckout===`validate`||s&&Date.now()-this.lastResponseAt>=1e3);n.inTransaction=void 0,this.idleCheckout=void 0,n.port.postMessage({...e,...c?{reconnectIfIdle:c}:{},...l?{validateIfIdle:l}:{},id:i,deadlineMs:a},[]),r(`sqlite_request`,`to_worker`);for(let e=Atomics.load(n.control,0);e!==i;e=Atomics.load(n.control,0)){if(Atomics.load(n.service,1))throw this.loseConnection();let t=o-performance.now();if(t<=0)throw Atomics.store(n.service,1,1),Atomics.notify(n.service,1),this.loseConnection();Atomics.wait(n.control,0,e,Math.min(t,50))}let u=Ye(n.port)?.message;if(u&&r(`sqlite_reply`,`from_worker`),!u||u.id!==i)throw this.loseConnection();if(`error`in u)throw e.operation===`connect`?g(u.error):ee(u.error.code)?this.loseConnection():(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)&&(this.isTransaction=!1,this.finishWrite()),g(u.error));return this.lastResponseAt=Date.now(),`reusable`in u?(n.inTransaction=!u.reusable,u.reusable):(n.inTransaction=`generation`in u?u.inTransaction:u.result.inTransaction,`generation`in u?u.generation:u.result)}query(e,t=[],n=!1){return O(`postgres`,`statement`,e,()=>this.execute(ne(e),t,n))}execute({sql:e,mutation:t},n,r){h(n);let i=this.isTransaction;/^\s*BEGIN\b/i.test(e)&&(this.isTransaction=!0);let a=this.request({operation:`query`,schema:this.schema,sql:e,parameters:n},!i||/^\s*COMMIT\b/i.test(e)),o=this.readOnlyTransaction;if(this.isTransaction=a.inTransaction,this.readOnlyTransaction=this.isTransaction&&(o||/^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e)),/^\s*COMMIT\s*;?\s*$/i.test(e)&&a.command!==`COMMIT`)throw this.finishWrite(),Error(`PostgreSQL transaction rolled back instead of committing`);let s=a.mutation===`unscoped`||t===`unscoped`?`unscoped`:a.mutation??t,c=s!==void 0;if(c){if(o||this.readOnlyTransaction)throw Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++,this.pendingWrite=!0,d(x(this),s===`unscoped`)}return!this.isTransaction&&(c||i)&&oe(x(this),()=>{this.finishWrite()}),this.outcomeUnknown=!this.isTransaction,{rows:m(a,r),rowCount:a.rowCount,columns:a.fields.map(({name:e})=>({name:e}))}}exec(e){this.query(e)}prepare(e){this.assertOpen();let t=ne(e),n=!1,r=[],execute=i=>{let a=O(`postgres`,`statement`,e,()=>this.execute(t,i,n));return r=a.columns,a};return{get:(...e)=>execute(e).rows[0],all:(...e)=>execute(e).rows,iterate:(...e)=>execute(e).rows[Symbol.iterator](),run:(...e)=>({changes:execute(e).rowCount,lastInsertRowid:0}),columns:()=>r,setReadBigInts:e=>{n=e}}}releaseIdleTransport(){let e=this.bridge;if(!this.isOpen||!e||!this.reuseKey||this.isTransaction)return;let t=!1;try{e.inTransaction===!1||this.request({operation:`release`})?(retainIdlePostgresBridge(this.reuseKey,e),t=!0):(this.isOpen=!1,this.finishWrite())}finally{this.bridge=void 0,t||e.port.close()}}close(){if(this.isOpen)try{this.reuseKey&&!this.isTransaction?this.releaseIdleTransport():this.bridge&&this.request({operation:`close`})}finally{this.finishWrite(),this.isOpen=!1,this.isTransaction=!1,this.bridge?.port.close(),this.bridge=void 0}}};function matchesVectorRow(e,t){return!e||typeof e!=`object`?!1:Object.entries(t).every(([t,n])=>{let r=Reflect.get(e,t);return typeof n==`string`?n===`finite-number`?typeof r==`number`&&Number.isFinite(r):typeof r===n:typeof r==`string`&&n.includes(r)})}function bindPostgresVector(e,t,r){let i=Ee(e),a=w(r.extensionSchema??`public`),o=S(e)?.postgresVectorSearchVersion===2,own=n=>{if(!e.isOpen||n.store!==t)throw Error(`Vector index is not admitted to this open store`);return n.postgres},write=t=>{let n=own(t);if(!e.isTransaction)throw Error(`Vector mutation requires the owner's transaction`);return n};return{idSet(e,t){return own(e),E`SELECT value FROM json_array_elements_text(${JSON.stringify(t)}::json)`},prepareExists(t){own(t);let n=e.prepare(`SELECT id FROM ${w(t.table)} WHERE id = ?`);return e=>!!n.get(e)},async nearest(t){let r=own(t.index);if(t.signal?.throwIfAborted(),t.vector.length!==r.dimensions||t.vector.some(e=>!Number.isFinite(e)||!Number.isFinite(Math.fround(e)))||!t.vector.some(e=>Math.fround(e)!==0))throw Error(`PostgreSQL cosine query requires a finite nonzero vector matching the admitted dimensions; rebuild for a changed embedding model.`);let s=`[${t.vector.map(Math.fround).join(`,`)}]`,c=E.ref(`${t.index.alias}.embedding`),l=E`${E.ref(`${t.index.alias}.embedding`)} ${E.raw(`OPERATOR(${a}.<=>)`)} ${s}::${E.raw(a)}.vector`,u=E.ref(`${t.index.alias}.embedding_bits`),d=o?E`${u} IS NOT NULL`:E`${E.raw(a)}.vector_norm(${c}) > 0`,f=o?t.candidates?.({match:d,distance:E`${u} ${E.raw(`OPERATOR(${a}.<~>)`)} ${E.raw(a)}.binary_quantize(${s}::${E.raw(a)}.vector)`,limit:t.limit*8}):void 0,p=t.query({match:f?E`${E.ref(`${t.index.alias}.id`)} IN (SELECT id FROM openclaw_vector_candidates)`:d,distance:l}),m=f?E`WITH openclaw_vector_candidates AS MATERIALIZED (${f})`:E``,h=D(e,{compile:()=>E`${m} SELECT * FROM (${p}) AS openclaw_candidates LIMIT ${t.limit}`.compile(i)}).rows;if(!h.every(t.isRow)||!h.every(e=>matchesVectorRow(e,t.index.rowShape)))throw Error(`PostgreSQL vector query returned an invalid row`);for(let e of h){let r=t.textPrefix;if(r&&e&&typeof e==`object`){let t=Reflect.get(e,r.column);typeof t==`string`&&Reflect.set(e,r.column,n(t,r.maxChars))}}return{rows:h,fallbackScanRequired:!1}},remove(t,n){write(t);let r=`toOperationNode`in n?E`${n}`:E`SELECT value FROM json_array_elements_text(${JSON.stringify(n)}::json)`;D(e,{compile:()=>E`DELETE FROM ${E.table(t.table)} WHERE id IN (${r})`.compile(i)})},drop(){throw Error(`PostgreSQL vector DDL belongs to store schema admission; rebuild the projection instead`)},create(e,t){if(write(e).dimensions!==t)throw Error(`PostgreSQL vector dimensions changed; reopen with the new search schema and rebuild`)},write(t,n){let r=write(t),i=e.prepare(`INSERT INTO ${w(t.table)}(id, embedding) SELECT ${w(r.key)}, openclaw_vector(${w(r.embedding)}, ${r.dimensions}) FROM ${w(r.source)} WHERE ${w(r.key)} = ? AND octet_length(${w(r.embedding)}) > 0 ON CONFLICT (id) DO UPDATE SET embedding = excluded.embedding`);for(let e of n)i.run(e.id)}}}function searchTextFor(e){let t=ve;return e===2?e=>E`regexp_replace(${e}, ${t}, ' ', 'g')`:e=>E`${e}`}function tsquery(e,t,n){if(e.kind===`contains`)throw Error(`Contains is only available on an admitted trigram index`);if(e.kind!==`term`&&e.kind!==`phrase`){if(e.clauses.every(e=>e.kind===`term`||e.kind===`phrase`)){let r=e.kind===`all`?` & `:` | `;return E`coalesce((
        SELECT string_agg('(' || nullif(parsed.value::text, '') ||
          CASE WHEN atom.prefix THEN ':*' ELSE '' END || ')', ${r})
        FROM json_to_recordset(${JSON.stringify(e.clauses)}::json)
          AS atom(kind text, text text, prefix boolean)
        CROSS JOIN LATERAL (SELECT CASE WHEN atom.kind = 'term'
          THEN plainto_tsquery(${E.lit(t)}::regconfig, ${n(E`atom.text`)})
          ELSE phraseto_tsquery(${E.lit(t)}::regconfig, ${n(E`atom.text`)})
        END AS value) AS parsed
      ), '')::tsquery`}let r=e.clauses.map(e=>tsquery(e,t,n));return r.length?E`(${E.join(r,E.raw(e.kind===`all`?` && `:` || `))})`:E`''::tsquery`}let r=e.kind===`term`?E`plainto_tsquery(${E.lit(t)}::regconfig, ${n(e.text)})`:E`phraseto_tsquery(${E.lit(t)}::regconfig, ${n(e.text)})`;return e.kind===`phrase`&&e.prefix?E`coalesce((nullif(${r}::text, '') || ':*')::tsquery, ''::tsquery)`:r}function bindPostgresSearch(e,t){pe(e,t);let n=`${w(_e(e).namespace)}.${w(fe)}`,r=w(t.extensionSchema??`public`),i=S(e)?.postgresTextSearchVersion,a=searchTextFor(i),o={},s=Object.fromEntries(Object.entries(t.text??{}).map(([e,t])=>[e,{...t,store:o}])),c=Object.fromEntries(Object.entries(t.vector??{}).map(([e,t])=>[e,{...t,store:o}])),relation=(t,n=`openclaw_search`)=>{if(!e.isOpen||t.store!==o)throw Error(`Text index is not admitted to this open store`);return E.ref(`${t.alias??t.table}.${n}`)},requireQuery=e=>{if(!e)throw Error(`PostgreSQL rank and snippet require the literal search query`);return tsquery(e,n,a)};return{text:s,vectors:c,diagnostics:[],rebuild:()=>de(e,t),fullText:Object.keys(s).length?{match(e,t){let r=relation(e,t.kind===`contains`?e.fields[0]:void 0);if(t.kind===`any`&&t.clauses.length>128&&t.clauses.every(e=>e.kind===`phrase`&&!e.prefix)){let e=t.clauses.map(e=>e.text);return E`EXISTS (SELECT 1 FROM json_array_elements_text(${JSON.stringify(e)}::json) AS search_terms(value) WHERE ${r} @@ phraseto_tsquery(${E.lit(n)}::regconfig, ${a(E`search_terms.value`)}))`}if(t.kind===`contains`){if(e.postgres?.mode!==`trigram`)throw Error(`Contains requires a declared PostgreSQL trigram index`);let n=`%${t.text.replaceAll(`\\`,`\\\\`).replaceAll(`%`,`\\%`).replaceAll(`_`,`\\_`)}%`;return E`${r} ILIKE ${n} ESCAPE '\\'`}return E`${r} @@ ${tsquery(t,n,a)}`},rank(e,t,n){if(t?.kind===`contains`){if(e.postgres?.mode!==`trigram`)throw Error(`Contains requires a declared PostgreSQL trigram index`);return{value:E`${E.raw(r)}.word_similarity(${t.text}, ${relation(e,e.fields[0])})`,order:`desc`,toRank:e=>e}}let i=relation(e),a=n?.postgres?.rank===`frequency`?E`ts_rank`:E`ts_rank_cd`;return{value:E`${a}(${i}, ${requireQuery(t)}, ${n?.postgres?.normalization??2})`,order:`desc`,toRank:e=>e}},snippet(e,t,r,a,o=500){if(r<2)throw Error(`PostgreSQL snippets require at least two tokens`);if(!e.fields.includes(t))throw Error(`Text index has no field ${t}`);let s=`StartSel='', StopSel='', MaxWords=${Math.max(1,Math.min(48,Math.trunc(r)))}, MinWords=1, MaxFragments=1, FragmentDelimiter=' … '`,c=Math.max(1,Math.min(500,Math.trunc(o))),l=relation(e,t);if(i!==2)return E`left(ts_headline(${E.lit(n)}::regconfig, ${l}, ${requireQuery(a)}, ${s}), ${c})`;let u=E`regexp_replace(${l}, '[[:punct:]]', ' ', 'g')`;return E`(SELECT left(substr(${l}, strpos(normalized, headline), length(headline)), ${c}) FROM (SELECT normalized, ts_headline(${E.lit(n)}::regconfig, normalized, ${requireQuery(a)}, ${s}) AS headline FROM (SELECT ${u} AS normalized OFFSET 0) AS headline_input OFFSET 0) AS headline_result)`},identity:e=>E`${relation(e,e.postgres.identity)}`,allocatedIdentity(){throw Error(`PostgreSQL insert identities must use RETURNING`)}}:null,vector:t.mode===`keyword-only`||!Object.keys(c).length?null:bindPostgresVector(e,o,t)}}function literalQuery(e){if(e.kind===`contains`)throw Error(`Literal contains requires the owner's SQLite substring policy`);if(e.kind===`term`||e.kind===`phrase`)return`"${e.kind===`term`?e.text.replaceAll(`"`,``):e.text.replaceAll(`"`,`""`)}"${e.kind===`phrase`&&e.prefix?`*`:``}`;let t=e.kind===`any`?` OR `:` AND `;return e.kind===`all`&&e.clauses.every(e=>e.kind===`phrase`)&&(t=` `),e.clauses.map(e=>e.kind===`any`?`(${literalQuery(e)})`:literalQuery(e)).join(t)}function bindSqliteFullText(e,t){let relation=n=>{if(n.store!==e||t&&!t.isOpen)throw Error(`Text index is not admitted to this open store`);return n.alias??n.table};return{match(e,t){let n=relation(e),r=literalQuery(t);return e.matchField?E`${E.ref(`${n}.${e.matchField}`)} match ${r}`:E`${E.raw(n)} MATCH ${r}${E.raw(e.hiddenRank?` AND ${n}.rank MATCH 'bm25()'`:``)}`},rank(e){let t=relation(e);return{value:E`${E.raw(e.hiddenRank?`${t}.rank`:`bm25(${t})`)}`,order:`asc`,toRank:e=>Number.isFinite(e)?-e:0}},snippet(e,t,n,r,i,a){let o=relation(e),s=e.fields.indexOf(t);if(s<0)throw Error(`Text index has no field ${t}`);let c=a?E.val(a.start):E.lit(``),l=a?E.val(a.end):E.lit(``),u=T()(`snippet`,[E.table(o),E.lit(s),c,l,E.lit(` … `),E.lit(n)]);return E`${u}`},identity:e=>E`${E.raw(`${relation(e)}.rowid`)}`,allocatedIdentity:e=>(relation(e),E`${T()(`last_insert_rowid`,[])}`)}}function vectorAdmission(e,t){let n=Ue({kind:`vector`,tableName:e,dimensions:t});return{name:`memory.vector-schema:${JSON.stringify([e,t,n.fingerprint])}`,schemaDependent:!0,read:e=>e===!0||void 0}}function createSqliteMemoryVectorSchema(e,t,n,r){e.exec(We({tableName:t,dimensions:n,ifNotExists:r})),r||f(e,vectorAdmission(t,n),!0)}function admitSqliteMemoryVectorSearch(e,t){let n=t.vector.chunks,r=n.postgres.dimensions,i=vectorAdmission(n.table,r);if(l(e,i))return;let a=Fe(e,[n.table]).readCatalog([n.table],[n.table]);if(a.tables.some(e=>e.name===n.table)){if(!He(a,{kind:`vector`,tableName:n.table,dimensions:r}))throw Error(`Memory vector schema differs for ${n.table}; rebuild the derived memory index.`);f(e,i,!0)}else{if(a.views.some(e=>e.name===n.table))throw Error(`cannot modify ${n.table} because it is a view`);createSqliteMemoryVectorSchema(e,n.table,r,!1)}}Buffer.from(`
VmRSS:`),Buffer.from(`
VmSwap:`),Buffer.from(`
Pss:`),Buffer.from(`
SwapPss:`);const q=Oe(process.versions.node);!process.versions.bun&&q&&(q.major===24&&q.minor>=19||q.major===26&&q.minor>=4&&q.minor),Ze(Xe),e(Symbol.for(`openclaw.hostExecMemory`),()=>({watches:/* @__PURE__ */ new Set,sampling:!1,assessmentPending:!1}));const J=[`cpu`,`io`,`memory`];function prepareAgentExecCgroupScope(e,t){let n=t?.trim(),r=M.join(e,n?`session-${P(`sha256`).update(n).digest(`hex`).slice(0,32)}`:`unscoped`);F.mkdirSync(r,{recursive:!0});let i=F.readFileSync(M.join(e,`io.max`),`utf8`).trim();for(let e of i.split(`
`)){let[t,...n]=e.split(/\s+/u);if(!t)continue;let i=n.map(e=>{let[t,n]=e.split(`=`),r=Number(n);return`${t}=${r>0&&Number.isFinite(r)?Math.max(1,Math.floor(r/2)):n}`});F.writeFileSync(M.join(r,`io.max`),[t,...i].join(` `))}return r}function resolveGatewayServiceCgroupDirectory(){let e=/^0::(.+)$/mu.exec(F.readFileSync(`/proc/self/cgroup`,`utf8`))?.[1],t=e&&/^(\/(?:[^/]+\/)*[^/]+\.service)\/(?:gateway|agent-exec(?:\/(?:session-[a-f0-9]{32}|unscoped))?)$/u.exec(e);if(!t)return;let n=M.join(`/sys/fs/cgroup`,t[1]);F.accessSync(n,F.constants.W_OK|F.constants.X_OK),F.accessSync(M.join(n,`cgroup.subtree_control`),F.constants.W_OK),F.accessSync(M.join(n,`gateway`,`cgroup.procs`),F.constants.W_OK);let r=new Set(F.readFileSync(M.join(n,`cgroup.controllers`),`utf8`).trim().split(/\s+/u));if(!J.every(e=>r.has(e)))throw Error(`the service has not delegated cpu, io, and memory controllers`);if(F.readFileSync(M.join(n,`cgroup.procs`),`utf8`).trim())throw Error(`the service root still contains processes; move its launcher into the gateway leaf`);return n}function getAgentExecCgroup(e){if(process.platform===`linux`)try{let t=resolveGatewayServiceCgroupDirectory();if(!t)return;let n=new Set(F.readFileSync(M.join(t,`cgroup.subtree_control`),`utf8`).trim().split(/\s+/u)),r=M.join(t,`agent-exec`);F.accessSync(r,F.constants.W_OK|F.constants.X_OK),F.accessSync(M.join(r,`cgroup.procs`),F.constants.W_OK);let i=F.readFileSync(M.join(r,`io.max`),`utf8`).trim(),a=F.readFileSync(M.join(r,`cpu.weight`),`utf8`).trim();if(J.every(e=>n.has(e))&&i&&a===`10`){let t=new Set(F.readFileSync(M.join(r,`cgroup.subtree_control`),`utf8`).trim().split(/\s+/u));if(!J.every(e=>t.has(e)))return r;try{return prepareAgentExecCgroupScope(r,e)}catch(e){return process.emitWarning(`Session exec IO policy unavailable; using the shared exec budget: ${String(e)}`),M.join(r,`unscoped`)}}}catch{}}const ut=[[`BASH_ENV`,`OC_INTERNAL_OOM_EXEC_BASH_ENV`],[`ENV`,`OC_INTERNAL_OOM_EXEC_ENV`],[`CDPATH`,`OC_INTERNAL_OOM_EXEC_CDPATH`],[`PS4`,`OC_INTERNAL_OOM_EXEC_PS4`]],dt=/^(?:SHELLOPTS|BASHOPTS|BASH_FUNC_.*)$/u;let Y=null;function defaultShellAvailable(){if(Y!==null)return Y;try{Y=F.statSync(V).isFile()}catch{Y=!1}return Y}function hardenShellEnv(e){let t={...e??process.env};for(let[e]of ut)delete t[e];for(let e of Object.keys(t))dt.test(e)&&delete t[e];return t}function prepareOomScoreAdjustedSpawnWithExecEnvPolicy(e,t=[],n,r=!1){let i=[...t],a={command:e,args:i,...n?.argv0===void 0?{}:{argv0:n.argv0},env:n?.env,wrapped:!1};if(!e||e.startsWith(`-`)||!shouldAdjustChildOomScore(n)||e===process.execPath&&!Ie().available)return a;if(n?.argv0!==void 0&&n.argv0!==e)return{...a,afterSpawn:raiseChildOomScore};if(!(n?.shellAvailable??defaultShellAvailable)())return a;if(!r&&isWrapped(e,i))return{command:e,args:i,env:hardenShellEnv(n?.env),wrapped:!0};let o=n?.env??process.env;if(r&&Object.entries(o).some(([e,t])=>t!==void 0&&dt.test(e)))return a;let s=hardenShellEnv(o);if(r)for(let[e,t]of ut){if(o[t]!==void 0)return a;delete s[t],o[e]!==void 0&&(s[t]=o[e])}return{command:V,args:[`-c`,r?H:`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`,e,...i],env:s,wrapped:!0}}function prepareOomScoreAdjustedSpawn(e,t=[],n){return prepareOomScoreAdjustedSpawnWithExecEnvPolicy(e,t,n)}function spawnProcess(e,t,n,r,i=`gateway-internal`,a){Ke(n.stdio);let o=k(),s=o&&Re(n)?o.spawn(e,t,n,r,i===`agent-tool`?getAgentExecCgroup(a):void 0):r?r(()=>v(`process:spawn`,()=>I(e,t,n),`native`)):v(`process:spawn`,()=>I(e,t,n),`native`);return!n.shell&&n.argv0!==void 0&&prepareOomScoreAdjustedSpawn(e,t,n).afterSpawn?.(s.pid),recordChildProcessSpawn(e,s,void 0,t),s}function scheduleAbsoluteDeadline(e,t,n=()=>Date.now(),{unref:r=!1}={}){let i,checkDeadline=()=>{let a=Math.max(0,e-n());a===0?t():(i=setTimeout(checkDeadline,Math.min(a,re)),r&&i.unref())};return checkDeadline(),()=>{clearTimeout(i)}}function createPermitPool(e){let t=0,n=[],r=0,compactWaiters=()=>{r>=n.length?(n.length=0,r=0):r>256&&r*2>n.length&&(n.splice(0,r),r=0)},createRelease=()=>{t+=1;let e=!1;return()=>{if(!e){e=!0,--t;for(let e=n[r];e;e=n[r]){r+=1;let t=e.expired();if(e.settle(t?null:createRelease()),!t)break}compactWaiters()}}},tryAcquire=()=>t<e?createRelease():null;return{get pendingCount(){return n.length-r},tryAcquire,async acquire({signal:e,deadlineAtMs:t}={}){let expired=()=>e?.aborted===!0||t!==void 0&&Date.now()>=t;return expired()?null:tryAcquire()||await new Promise(i=>{let a,cancel=()=>{let e=n.indexOf(o,r);e>=r&&(n.splice(e,1),compactWaiters()),o.settle(null)},o={expired,settle:t=>{a?.(),e?.removeEventListener(`abort`,cancel),i(t)}};e?.addEventListener(`abort`,cancel,{once:!0}),n.push(o),t!==void 0&&(a=scheduleAbsoluteDeadline(t,cancel,void 0,{unref:!0}))})}}}var VectorKnnSubprocessError=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`VectorKnnSubprocessError`}};function buildChildEnv(){let e={};for(let t of[`PATH`,`SystemRoot`,`SYSTEMROOT`,`WINDIR`,`TEMP`,`TMP`,`TMPDIR`])process.env[t]&&(e[t]=process.env[t]);return e}function toAbortError(e){return e.reason instanceof Error?e.reason:/* @__PURE__ */ Error(`memory vector KNN aborted`)}const X=createPermitPool(2),Z=/* @__PURE__ */ new Map,Q=/* @__PURE__ */ new Map;function setChildReferenced(e,t){e[t?`ref`:`unref`]();for(let n of[e.stdin,e.stdout,e.stderr])n&&(t&&`ref`in n&&typeof n.ref==`function`&&n.ref(),!t&&`unref`in n&&typeof n.unref==`function`&&n.unref())}function parseChildResult(e,t,n){let r;try{r=JSON.parse(e.toString(`utf8`))}catch{throw new VectorKnnSubprocessError(`memory vector KNN child returned malformed JSON`,`protocol`)}if(!r||typeof r!=`object`||!(`status`in r))throw new VectorKnnSubprocessError(`memory vector KNN child returned an invalid envelope`,`protocol`);if(r.status===`failed`&&`error`in r&&typeof r.error==`string`)throw new VectorKnnSubprocessError(r.error||`memory vector KNN child failed`,`failed`);let i=`value`in r?r.value:void 0;if(r.status!==`ok`||!i||typeof i!=`object`||!(`rows`in i)||!Array.isArray(i.rows)||i.rows.length>t||!i.rows.every(n)||!(`fallbackScanRequired`in i)||typeof i.fallbackScanRequired!=`boolean`)throw new VectorKnnSubprocessError(`memory vector KNN child returned an invalid result`,`protocol`);return{rows:i.rows,fallbackScanRequired:i.fallbackScanRequired}}async function runVectorKnnInSubprocess(e){let t=Z.get(e.databasePath);t||(t={admission:createPermitPool(1),users:0},Z.set(e.databasePath,t)),t.users+=1;let n;try{if(n=await t.admission.acquire({signal:e.signal})??void 0,!n)throw toAbortError(e.signal);return await runAdmittedVectorKnn(e)}finally{n?.(),--t.users===0&&Z.delete(e.databasePath)}}async function runAdmittedVectorKnn(e){if(e.signal?.aborted)throw toAbortError(e.signal);let t=u(),n={databasePath:e.databasePath,extensionPath:e.extensionPath,...t.source===`runtime`?{}:{sqliteLibraryPath:t.path},request:qe(e.request).toString(`base64`)},r=Buffer.from(JSON.stringify(n),`utf8`);if(r.byteLength>1048576)throw new VectorKnnSubprocessError(`memory vector KNN child input is too large`,`protocol`);let i=k(),a=Q.get(e.databasePath);if(a&&a.broker!==i&&(a.retire(),a=void 0),!a){let t=X.tryAcquire();if(!t){let n=[...Q.values()].find(e=>e.idleTimer);n&&n.retire(),t=await X.acquire({signal:e.signal})}if(!t)throw toAbortError(e.signal);let n=t;if(e.signal?.aborted)throw n(),toAbortError(e.signal);let r;try{ze();let e=Me(je.sqliteVector);r=spawnProcess(process.execPath,Ne(e),{env:buildChildEnv(),shell:!1,stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0});let t=r instanceof Be?r:void 0;if(t)try{await t.ready()}catch(e){throw await t.waitForClose(),e}}catch(e){throw n(),await A({error:e})??new VectorKnnSubprocessError(e instanceof Error?e.message:String(e),`unavailable`)}let{stdin:o,stdout:s,stderr:c}=r;if(!o||!s||!c)throw r.once(`close`,n),r.once(`error`,()=>{}),r.kill(`SIGKILL`),new VectorKnnSubprocessError(`memory vector KNN child did not provide pipes`,`unavailable`);a={child:r,stdin:o,stdout:s,stderr:c,broker:i,retire:()=>{Q.get(e.databasePath)===l&&(setChildReferenced(r,!0),Q.delete(e.databasePath),clearTimeout(l.idleTimer),o.destroy(),r.kill(`SIGKILL`))}};let l=a;r.once(`close`,()=>{clearTimeout(l.idleTimer),Q.get(e.databasePath)===l&&Q.delete(e.databasePath),n()}),r.on(`error`,l.retire),o.on(`error`,l.retire),Q.set(e.databasePath,a)}let{child:o,stdin:s,stdout:c,stderr:l}=a,d=a;return clearTimeout(a.idleTimer),a.idleTimer=void 0,c.removeAllListeners(`data`),setChildReferenced(o,!0),await new Promise((t,n)=>{let i=[],a=!1,u=!1,f,p,m,settleCaller=t=>{u||(u=!0,e.signal?.removeEventListener(`abort`,abort),c.removeAllListeners(`data`),l.removeAllListeners(`data`),s.removeListener(`error`,onStdinError),o.removeListener(`error`,onError),o.removeListener(`close`,onClose),t())},requestTermination=e=>{f||a||(f=e,d.retire(),m=setTimeout(()=>{a||(s.destroy(),c.destroy(),l.destroy(),o.unref(),settleCaller(()=>n(new VectorKnnSubprocessError(`memory vector KNN child did not exit after SIGKILL`,`termination-timeout`))))},2e3))},abort=()=>{requestTermination(toAbortError(e.signal))};e.signal?.addEventListener(`abort`,abort,{once:!0}),e.signal?.aborted&&abort();for(let n of[`stdout`,`stderr`]){let r=n===`stderr`?i:[],a=n===`stdout`?2097152:65536,s=0;d[n].on(`data`,i=>{s+=i.byteLength;let l=+(n===`stdout`&&i[i.length-1]===10);if(s>a+l){n===`stdout`&&(r.length=0),requestTermination(new VectorKnnSubprocessError(`memory vector KNN child ${n} exceeded its limit`,`protocol`));return}if(r.push(i),n===`stderr`)return;let u=i.indexOf(10);if(!(u<0))try{if(u!==i.length-1)throw new VectorKnnSubprocessError(`memory vector KNN child returned extra output`,`protocol`);d.started=!0;let n=parseChildResult(Buffer.concat(r),e.request.limit,e.isRow);if(f)return;settleCaller(()=>t(n)),c.on(`data`,d.retire),d.idleTimer=setTimeout(d.retire,G),d.idleTimer.unref(),X.pendingCount>0?d.retire():setChildReferenced(o,!1)}catch(e){requestTermination(e instanceof Error?e:Error(String(e)))}})}let onStdinError=e=>{!f&&e.code!==`EPIPE`&&requestTermination(new VectorKnnSubprocessError(e.message,`failed`))};s.on(`error`,onStdinError);let onError=e=>{p=e,requestTermination(new VectorKnnSubprocessError(e.message,`unavailable`))};o.once(`error`,onError);let finishClose=async(t,r)=>{a=!0,m&&=(clearTimeout(m),void 0),e.signal?.removeEventListener(`abort`,abort);let o=p??f,s=await A({error:o,stderr:Buffer.concat(i).toString(`utf8`),signal:r,started:d.started}).catch(e=>o?AggregateError([o,e],`Child runtime diagnosis failed`,{cause:o}):toStringifiedError(e));settleCaller(()=>{if(s){n(s);return}if(f){n(f);return}let e=Buffer.concat(i).toString(`utf8`).trim();n(new VectorKnnSubprocessError(`memory vector KNN child exited before returning a result (code ${t}, signal ${r??`none`})${e?`: ${e}`:``}`,`failed`))})},onClose=(e,t)=>{finishClose(e,t)};o.once(`close`,onClose),s.write(Buffer.concat([r,Buffer.from(`
`)]))})}const $=4096,ft=new ke,vectorToBlob=e=>Buffer.from(new Float32Array(e).buffer);function compileStatement(e){let{sql:t,parameters:n}=ft.compileQuery(e.toOperationNode(),Te());return{sql:t,parameters:n}}function runSqliteVectorQuery(e,t){let run=r=>{let i=[...t.query.parameters];i[t.candidateParameter]=r;let a=e.prepare(t.query.sql).all(...i);for(let e of a){if(!matchesVectorRow(e,t.rowShape))throw Error(`memory vector KNN query returned an invalid row`);let r=t.textPrefix,i=r&&e[r.column];r&&typeof i==`string`&&(e[r.column]=n(i,r.maxChars))}return a},r=Math.min(t.limit*8,$),i=run(r);if(i.length<t.limit){let n=Number(e.prepare(t.scopeCount.sql).get(...t.scopeCount.parameters)?.count??0);if(n>i.length){let a=Number(e.prepare(`SELECT COUNT(*) AS count FROM (SELECT 1 FROM ${t.vectorTable} LIMIT ?)`).get(4097)?.count??0),o=Math.min(a,$);if(o>r&&(i=run(o)),a>$&&i.length<Math.min(t.limit,n))return{rows:[],fallbackScanRequired:!0}}}return{rows:i,fallbackScanRequired:!1}}function bindSqliteVectorCapability(e,t){let own=n=>{if(n.store!==e.store||t&&!t.isOpen)throw Error(`Vector index is not admitted to this open store`)};return{idSet(e,t){return own(e),E`SELECT value FROM ${De(JSON.stringify(t))}`},prepareExists(e){if(own(e),!t)throw Error(`Vector lookup requires the admitted reader`);let n=t.prepare(`SELECT id FROM ${e.table} WHERE id = ?`);return t=>(own(e),!!n.get(t))},async nearest(n){own(n.index);let r=Symbol(`vector-candidate-limit`),i=E.raw(`${n.index.alias}.embedding`),a=e.databasePath?n.vector.map(e=>Number.isFinite(e)?e+0:0):n.vector,o=vectorToBlob(a),s=compileStatement(n.query({match:E`${i} MATCH ${o} AND k = ${r}`,distance:E`vec_distance_cosine(${i}, ${o})`})),c={query:s,scopeCount:compileStatement(n.scopeCount),vectorTable:n.index.table,rowShape:n.index.rowShape,textPrefix:n.textPrefix,limit:n.limit,candidateParameter:s.parameters.findIndex(e=>e===r)};if(c.candidateParameter<0)throw Error(`Vector query omitted native candidate matching`);c.query.parameters[c.candidateParameter]=0;let l;if(t&&!e.databasePath){let e=runSqliteVectorQuery(t,c);if(!e.rows.every(n.isRow))throw Error(`memory vector KNN query returned an invalid row`);l={rows:e.rows,fallbackScanRequired:e.fallbackScanRequired}}else l=await runVectorKnnInSubprocess({databasePath:e.databasePath,extensionPath:n.extensionPath,request:c,isRow:n.isRow,signal:n.signal});return own(n.index),{rows:l.rows,fallbackScanRequired:l.fallbackScanRequired}},remove(e,n){if(own(e),!t)throw Error(`Vector deletion requires the admitted writer`);if(`toOperationNode`in n){let r=compileStatement(n);t.prepare(`DELETE FROM ${e.table} WHERE id IN (${r.sql})`).run(...r.parameters)}else{let r=t.prepare(`DELETE FROM ${e.table} WHERE id = ?`);for(let e of n)r.run(e)}},drop(e){if(own(e),!t)throw Error(`Vector deletion requires the admitted writer`);t.exec(`DROP TABLE IF EXISTS ${e.table}`)},create(e,n,r=!1){if(own(e),!t)throw Error(`Vector index creation requires the admitted writer`);createSqliteMemoryVectorSchema(t,e.table,n,r)},write(e,n){if(own(e),!t)throw Error(`Vector writes require the admitted writer`);if(n.length===0)return;let r=[...new Map(n.map(e=>[e.id,e])).values()],i=t.prepare(`DELETE FROM ${e.table} WHERE id = ?`);for(let e of r)i.run(e.id);t.prepare(`INSERT INTO ${e.table} (id, embedding) VALUES ${r.map(()=>`(?, ?)`).join(`,`)}`).run(...r.flatMap(e=>[e.id,vectorToBlob(e.embedding)]))}}}function bindStoreSearch(e,t){if(`databasePath`in e?e.input:b(e)){if(`databasePath`in e||!b(e))throw Error(`PostgreSQL search requires the admitted worker connection`);return bindPostgresSearch(e,t)}let n=`databasePath`in e||b(e)?void 0:e,r=`databasePath`in e?e.databasePath:n?.location()??``,i={},bindIndexes=(e={})=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,store:i}]));return{fullText:bindSqliteFullText(i,n),vector:bindSqliteVectorCapability({store:i,databasePath:r},n),text:bindIndexes(t.text),vectors:bindIndexes(t.vector),diagnostics:[]}}var SearchExtensionDefinitionChangedError=class extends Error{constructor(...e){super(...e),this.name=`SearchExtensionDefinitionChangedError`}};function admitStoreSearchExtension(e,t,n){if(!b(e))return t===`memory.vector`&&admitSqliteMemoryVectorSearch(e,n),bindStoreSearch(e,t===`memory.text`?Ge(e,n):n);let r=S(e),i=_e(e);if(!r||!i)throw Error(`Search extensions require an admitted PostgreSQL store`);if(JSON.stringify(r.searchExtensions?.[t])===JSON.stringify(n))return bindStoreSearch(e,n);if(r.searchExtensions?.[t])throw new SearchExtensionDefinitionChangedError(`Search extension ${t} changed. Restore its previous definition, or rebuild the derived extension from canonical source data before using the new definition.`);return e.runTransaction(()=>{C(e,n,i.namespace,r.postgresVectorSearchVersion);let a=[r.search,...Object.values(r.searchExtensions??{})].filter(e=>e!==void 0);if(a.some(e=>(e.extensionSchema??`public`)!==(n.extensionSchema??`public`)))throw Error(`Search extensions must use the store's admitted extension schema`);let s={...r,searchExtensions:{...r.searchExtensions,[t]:n}};e.exec(we(n,i.namespace,{text:a.some(e=>Object.keys(e.text??{}).length>0),vector:a.some(e=>e.mode!==`keyword-only`&&Object.keys(e.vector??{}).length>0)},r.postgresVectorDecoderVersion,r.postgresVectorSearchVersion,r.postgresTextSearchVersion)),Object.keys(r.searchExtensions??{}).length||e.exec(`ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS search_extensions TEXT`),e.prepare(`UPDATE openclaw_schema_meta SET search_extensions = ? WHERE store = ?`).run(JSON.stringify(s.searchExtensions),r.id);let l=he(e,i.namespace,s);c(e),le(e,{commit:()=>o(e)}),me(e,s),Ce(e,i,l.catalog,s);for(let t of[s.search,...Object.values(s.searchExtensions)].filter(e=>e!==void 0))ye(e,t,r.postgresVectorSearchVersion)},{maintenance:!0}),bindStoreSearch(e,n)}function admitStoreSearch(e,t,n){if(n){if(`databasePath`in e)throw Error(`Search extension admission requires the owner's connection`);return admitStoreSearchExtension(e,n.extension,t)}return bindStoreSearch(e,t)}const pt={sqlite:{openConnection:({anchor:e})=>Ae(e),schema:{bootstrap:e=>e.openSqlite()}},postgres:{openConnection:e=>{if(!e.input||!e.storeId||!e.namespace)throw Error(`PostgreSQL store is not admitted`);try{return new PostgresSyncConnection(e.input.connection,e.namespace,e.anchor,e.storeId,{reuse:e.reusePostgresConnection,readOnly:e.input.readOnly,lockTimeoutMs:6e4,statementTimeoutMs:9e4})}catch(t){let n=t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``,r=a(`${n}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${r}; verify database.postgres.connection and server availability.`,{cause:t})}},schema:{bootstrap:(e,t)=>{if(!e.schema.postgres)throw Error(`Store has no PostgreSQL schema`);t.exec(xe(e.schema,e.namespace)),t.prepare(`INSERT INTO openclaw_schema_meta (store, version, store_id) VALUES (?, ?, ?)`).run(e.schema.id,e.schema.version,e.storeId)},migrate:(e,t,n)=>{if(t>e.schema.version)throw Error(`PostgreSQL ${e.schema.id} schema ${t} is newer than this build (expected ${e.schema.version}); use a compatible binary, or reverse-port with a compatible binary before downgrading.`);for(let r=t+1;r<=e.schema.version;r++){let t=e.schema.postgresMigrations?.find(e=>e.version===r);if(!t)throw Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);let i=be(n,e.namespace,e.schema.id),a=ue(e.schema,i);if(ge(n,e.namespace,{...a,version:r-1,postgres:t.fromSchema.postgres,postgresFragments:t.fromSchema.postgresFragments,postgresWithoutOptionalColumn:t.fromSchema.postgresWithoutOptionalColumn,postgresVectorDecoderVersion:t.fromSchema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.fromSchema.postgresVectorSearchVersion,postgresTextSearchVersion:t.fromSchema.postgresTextSearchVersion},i),t.schema.postgresVectorSearchVersion===2&&t.fromSchema.postgresVectorSearchVersion!==2)for(let t of[a.search,...Object.values(a.searchExtensions??{})])t&&C(n,t,e.namespace,2);e.beforeMigrate?.(n,r-1,new Set(i.catalog.filter(e=>e.kind===`table`).map(e=>e.table))),n.exec(t.sql),n.prepare(`UPDATE openclaw_schema_meta SET version = ? WHERE store = ?`).run(r,e.schema.id),he(n,e.namespace,{...a,version:r,postgres:t.schema.postgres,postgresFragments:t.schema.postgresFragments,postgresWithoutOptionalColumn:t.schema.postgresWithoutOptionalColumn,postgresVectorDecoderVersion:t.schema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.schema.postgresVectorSearchVersion,postgresTextSearchVersion:t.schema.postgresTextSearchVersion})}}}}};function beginEngineStoreReadSnapshot(e){if(e.isTransaction)throw Error(`Streaming read snapshot requires a dedicated connection`);return e.exec(b(e)?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN DEFERRED`),{close(){e.isTransaction&&e.exec(`ROLLBACK`)}}}const mt={text:{transcript:{table:`session_transcript_fts`,fields:[`text`],postgres:{identity:`rowid`}}}};export{bindSqliteFullText as a,resolveAgentDatabaseIdleHandleTtlMs as c,withEngineStoreAdmission as d,recordChildProcessSpawn as f,admitStoreSearch as i,assertEngineStoreExecutionAllowed as l,beginEngineStoreReadSnapshot as n,beginPostgresReadOnlyTransaction as o,toStringifiedError as p,pt as r,G as s,mt as t,getDatabaseProcessRole as u};