UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines (8 loc) • 31.6 kB
import{E as e,l as t,o as n,w as r}from"./git-operation.worker-map-size-CypexNQj.mjs";import{_ as i}from"./git-operation.worker-diagnostic-events-B5MedM3R.mjs";import{t as a}from"./git-operation.worker-runtime-process-manifest-BlrvoYG_.mjs";import{n as o,r as s}from"./git-operation.worker-process-env-DgVwfN3Y.mjs";import{On as c}from"./git-operation.worker.js";import{createRequire as l}from"node:module";import u,{opendirSync as d,readFileSync as f,readdirSync as p,readlinkSync as m}from"node:fs";import h,{readFile as g,readdir as _}from"node:fs/promises";import v from"node:path";import{stripVTControlCharacters as y}from"node:util";import"node:os";import{AsyncResource as b}from"node:async_hooks";import{fileURLToPath as x,pathToFileURL as S}from"node:url";import C,{spawn as w,spawnSync as T}from"node:child_process";import{Buffer as E}from"node:buffer";import{EventEmitter as D}from"node:events";import{ProcSafeError as O}from"@openclaw/proc-safe/errors";import{readProcessIdentity as k}from"@openclaw/proc-safe/identity";import{inspectChildWaitState as A,isSupported as j,reapChild as M}from"@openclaw/proc-safe/reaper";import"node:timers/promises";import{listProcesses as N}from"@openclaw/proc-safe/inspect";import{Socket as P}from"node:net";function isContinuationByte(e){return e!==void 0&&(e&192)==128}function truncateUtf8Suffix(e,t){if(t<=0)return``;if(e.length<=t&&E.byteLength(e)<=t)return e;let n=E.from(Number.isInteger(t)?e.slice(-t-1):e),r=n.byteLength-t;for(;r<n.byteLength&&isContinuationByte(n[r]);)r+=1;return n.subarray(r).toString(`utf8`)}const F=`C:\\Windows`;function readNativeProcessStartTime(e){if(!(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=k(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){let t=s(e,`SystemRoot`,`win32`)??s(e,`WINDIR`,`win32`);if(!t)return F;let n=v.win32.normalize(t);return/^[A-Za-z]:\\/.test(n)&&!n.startsWith(`\\\\`)?n:F}function windowsPowerShellPath(e){return v.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return v.win32.join(windowsSystemRoot(e),`System32`,`wbem`,`wmic.exe`)}function decodeWindowsProcessOutput(e){return Buffer.isBuffer(e)?e.length>=2&&e[0]===255&&e[1]===254?e.toString(`utf16le`):e.toString(`utf8`):e}function parseWindowsProcessStartTime(e){let t=decodeWindowsProcessOutput(e).split(/\r?\n/).map(e=>e.trim()).filter(Boolean),n=t.find(e=>e.toLowerCase().startsWith(`creationdate=`))?.slice(13).trim()??t.find(e=>e.toLowerCase()!==`creationdate`)??``,r=Date.parse(n);if(Number.isFinite(r))return r;let i=n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);if(!i)return null;let[,a,o,s,c,l,u,d,f,p]=i;return Date.UTC(Number(a),Number(o)-1,Number(s),Number(c),Number(l),Number(u),Math.floor(Number(d)/1e3))-Number(p)*6e4*(f===`+`?1:-1)}function readWindowsProcessStartTimeSync(e,t=1e4,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;let r=performance.now()+t,i=readNativeProcessStartTime(e);if(i!==void 0)return i;let a=Math.ceil(r-performance.now());if(a<=0)return null;let s=T(windowsPowerShellPath(n),[`-NoProfile`,`-NonInteractive`,`-Command`,`$process = [System.Diagnostics.Process]::GetProcessById(${e}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`],{encoding:`utf8`,env:o(n,`win32`),timeout:Math.min(a,5e3),windowsHide:!0});if(!s.error&&s.status===0){let e=parseWindowsProcessStartTime(s.stdout);if(e!==null)return e}let c=Math.ceil(r-performance.now());if(c<=0)return null;let l=T(windowsWmicPath(n),[`process`,`where`,`ProcessId=${e}`,`get`,`CreationDate`,`/value`],{env:o(n,`win32`),timeout:c,windowsHide:!0,stdio:[`ignore`,`pipe`,`ignore`]});return!l.error&&l.status===0?parseWindowsProcessStartTime(l.stdout):null}let I;function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`FreeBSD process identity is unavailable in this sealed runtime`);return I||=l(import.meta.url)(`@openclaw/proc-safe/identity`),I}function readFreeBsdProcessStartTime(e){if(process.platform!==`freebsd`||!Number.isInteger(e)||e<=0||e>2147483647)return null;try{return loadFreeBsdProcessIdentityNative().readProcessIdentity(e)?.startTimeSinceBootMicros??null}catch{return null}}function readDarwinNativeIdentity(e){if(!(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=k(e);return t&&!t.exited?{startedAt:Math.floor(t.startTimeMicros/1e6),startTimeMicros:t.startTimeMicros}:null}catch{return}}function readNativeLiveness(e){if(!(![`darwin`,`win32`,`freebsd`].includes(process.platform)||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=k(e);return t!==null&&!t.exited}catch(e){return e instanceof O&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`)?void 0:!0}}let L=null;function isValidPid(e){return Number.isInteger(e)&&e>0}function hasLinuxProcfs(){return process.platform===`linux`||process.platform===`android`}function exitedLinuxStatus(e,t){let n=t.match(/^State:\s+(\S)/m)?.[1],r=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(r===`0`)return;let i=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return i!==void 0&&Number(i)!==e||(n===`Z`||n===`X`)&&r===`1`}function isMissingPid(e){try{process.kill(e,0)}catch(e){return r(e,`ESRCH`)}return!1}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return!1;try{let t=exitedLinuxStatus(e,u.readFileSync(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}async function isPidDefinitelyDeadAsync(e){if(!hasLinuxProcfs())return isPidDefinitelyDead(e);if(!isValidPid(e))return!0;try{process.kill(e,0)}catch(e){return r(e,`ESRCH`)}try{let t=exitedLinuxStatus(e,await u.promises.readFile(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}function isPidAlive(t){if(!isValidPid(t))return!1;try{process.kill(t,0)}catch(n){let r=e(n)?n.code:void 0;if(r!==`EPERM`)return r===`ESRCH`?readNativeLiveness(t)??!1:!1}return readNativeLiveness(t)??!isExitedLinuxProcess(t)}function isPidDefinitelyDead(t){if(!isValidPid(t))return!0;let n=!1;try{process.kill(t,0)}catch(t){let r=e(t)?t.code:void 0;if(r!==`ESRCH`&&(process.platform!==`win32`||r!==`EPERM`))return!1;n=r===`ESRCH`}let r=readNativeLiveness(t);return r===void 0?n&&process.platform!==`freebsd`||isExitedLinuxProcess(t):!r}function getDarwinProcessStartTime(e,t,n){let r=performance.now(),i=readDarwinNativeIdentity(e);if(i!==void 0)return i?.startedAt??null;let a=n===void 0?1e3:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{let n=C.execFileSync(`/bin/ps`,[`-o`,`lstart=`,`-p`,String(e)],{encoding:`utf8`,env:{...o(t),LC_ALL:`C`,TZ:`UTC`},stdio:[`ignore`,`pipe`,`ignore`],timeout:a,killSignal:`SIGKILL`}).trim(),r=Date.parse(`${n} UTC`);return Number.isFinite(r)?Math.floor(r/1e3):null}catch{return null}}function parseLinuxProcessStat(e,t){let n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;let r=t.slice(n+1).trimStart().split(/\s+/),i=Number(r[19]),a=Number(r[1]);return Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(a)&&a>=0?{parentPid:a,startedAt:i}:null}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{return parseLinuxProcessStat(e,u.readFileSync(`/proc/${e}/stat`,`utf8`))}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getProcessInstanceStartTime(e){if(!isValidPid(e))return null;if(hasLinuxProcfs()){let t=getProcessStartTime(e);return Number.isSafeInteger(t)?t:null}let t=readDarwinNativeIdentity(e);if(!t)return null;let n=t.startTimeMicros;return Number.isSafeInteger(n)?n:null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&L!==null)return L;let i=process.platform===`darwin`?getDarwinProcessStartTime(e,t,n):process.platform===`win32`?readWindowsProcessStartTimeSync(e,n,t):process.platform===`freebsd`?readFreeBsdProcessStartTime(e):getProcessStartTime(e);return r&&i!==null&&(L=i),i}const R=4096;function killProcessTree(e,t){if(!Number.isFinite(e)||e<=0)return;if(process.platform===`win32`){if(t?.force===!0){signalProcessTreeWindowsAndWait(e,`SIGKILL`);return}killProcessTreeWindows(e,normalizeGraceMs(t?.graceMs));return}let n=t?.detached===!0||t?.detached!==!1&&isProcessGroupLeader(e),r=t?.detached===!1&&!n&&process.platform===`linux`,i=r?collectUnixProcessTree(e):void 0;if(r&&!i){signalProcessTreeUnix(e,t?.force===!0?`SIGKILL`:`SIGTERM`,!1);return}let a=!1,force=()=>{if(a)return;a=!0;let t=i?.filter(verifiedProcessInstanceAlive)??[];(n?isProcessAlive(-e):r?t.length>0:isProcessAlive(e))&&signalProcessTreeUnix(e,`SIGKILL`,n,i?t:void 0)};if(t?.force===!0){i?force():signalProcessTreeUnix(e,`SIGKILL`,n);return}signalProcessTreeUnix(e,`SIGTERM`,n,i);let o=normalizeGraceMs(t?.graceMs),s=setTimeout(force,o);r||s.unref();let c=!1;return{force:()=>{clearTimeout(s),force()},exited:()=>(c||=n?!isProcessAlive(-e):i?!i.some(capturedProcessInstanceMayBeAlive):!isProcessAlive(e),c&&(a=!0,clearTimeout(s)),c)}}function normalizeGraceMs(e){return typeof e!=`number`||!Number.isFinite(e)?3e3:Math.max(0,Math.min(6e4,Math.floor(e)))}function isProcessAlive(e){try{process.kill(e,0)}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`EPERM`)return!1}if(e<0||process.platform!==`linux`)return!0;try{let t=f(`/proc/${e}/status`,`utf8`);return!(t.match(/^State:\s+(\S)/m)?.[1]===`Z`&&/^Threads:[ \t]+1[ \t]*$/m.test(t))}catch{return!0}}function parseProcessGroupId(e){if(typeof e!=`string`||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}function readPsOutput(e){try{let t=T(`ps`,e,{encoding:`utf8`,timeout:500});return t.error||t.status!==0?void 0:t.stdout}catch{return}}function readProcStatFields(e){try{let t=f(`/proc/${e}/stat`,`utf8`),n=t.lastIndexOf(`)`);return n<0?void 0:t.slice(n+1).trim().split(/\s+/)}catch{return}}function isProcessGroupLeader(e){return((process.platform===`linux`?parseProcessGroupId(readProcStatFields(e)?.[2]):void 0)??parseProcessGroupId(readPsOutput([`-p`,String(e),`-o`,`pgid=`])))===e}function parsePositivePids(e){return typeof e==`string`?e.trim().split(/\s+/u).map(e=>Number(e)).filter(e=>Number.isSafeInteger(e)&&e>0):[]}function readUnixProcessIdentity(e,t){return readUnixProcessInstance(e,t)?.identity}function readUnixProcessInstance(e,t){if(t!==void 0&&Date.now()>=t||process.platform!==`linux`)return;let n=readProcStatFields(e),r=Number(n?.[1]),i=n?.[19];if(i&&/^\d+$/u.test(i)&&Number.isSafeInteger(r))return{identity:`${e}:${i}`,ppid:r}}function verifiedProcessInstanceAlive(e){return!e.identity||!isProcessAlive(e.pid)?!1:readUnixProcessIdentity(e.pid)===e.identity}function capturedProcessInstanceMayBeAlive(e){if(!e.identity||!isProcessAlive(e.pid))return!1;let t=readUnixProcessIdentity(e.pid);return t===void 0||t===e.identity}function*readUnixProcessChildren(e,t){let n;try{for(n=d(`/proc/${e}/task`);t();){let t=n.readSync();if(!t)return;let r=parseProcessGroupId(t.name);if(r)try{yield*parsePositivePids(f(`/proc/${e}/task/${r}/children`,`utf8`))}catch{}}}catch{}finally{try{n?.closeSync()}catch{}}}function collectUnixProcessTree(e){if(process.platform!==`linux`)return;let t=[],n=/* @__PURE__ */ new Set([e]),r=0,i=Date.now()+500,a=readUnixProcessIdentity(e,i);if(!a||Date.now()>=i)return;let withinBounds=e=>Date.now()<i&&e<=128,hasCapacity=()=>n.size<R,visit=(e,a,o)=>{if(!withinBounds(o)||!hasCapacity()||readUnixProcessIdentity(e,i)!==a)return;let s=readUnixProcessChildren(e,()=>withinBounds(o)&&hasCapacity()&&r++<R&&readUnixProcessIdentity(e,i)===a);for(let r of s){if(!withinBounds(o+1)||!hasCapacity())return;if(n.has(r)||r===process.pid)continue;n.add(r);let a=readUnixProcessInstance(r,i);a&&a.ppid===e&&withinBounds(o+1)&&(visit(r,a.identity,o+1),t.push({pid:r,identity:a.identity}))}};return visit(e,a,0),[...t,{pid:e,identity:a}]}function signalProcessTreeUnix(e,t,n,r){if(n){signalUnixTarget(-e,t);return}let i=r??[{pid:e}];for(let e of i)(!r||verifiedProcessInstanceAlive(e))&&signalUnixTarget(e.pid,t)}function signalUnixTarget(e,t){try{process.kill(e,t)}catch{}}function runTaskkill(e,t){return new Promise(n=>{let r=!1,finish=e=>{r||(r=!0,clearTimeout(i),t?.(e),n())},i=setTimeout(()=>finish(null),3e3);i.unref?.();try{let t=w(`taskkill`,e,{stdio:`ignore`,detached:!0,windowsHide:!0});t.once(`error`,()=>finish(null)),t.once(`close`,e=>finish(e))}catch{finish(null)}})}function killProcessTreeWindows(e,t){let n=!1,r,forceKill=()=>{n||(n=!0,r!==void 0&&(clearTimeout(r),r=void 0),isProcessAlive(e)&&signalProcessTreeWindowsAndWait(e,`SIGKILL`))};signalProcessTreeWindowsAndWait(e,`SIGTERM`,e=>{e!==null&&e!==0&&forceKill()}),r=setTimeout(forceKill,t),r.unref()}function signalProcessTreeWindowsAndWait(e,t,n){return runTaskkill(t===`SIGKILL`?[`/F`,`/T`,`/PID`,String(e)]:[`/T`,`/PID`,String(e)],n)}const z=/* @__PURE__ */ new WeakSet,B=/* @__PURE__ */ new Map,V=3e4;let H,U=0,W=!1;function schedule(e){let t=performance.now()+e;H&&U<=t||(clearTimeout(H),U=t,H=setTimeout(()=>void tick(),e).unref())}function onExit(){schedule(25)}async function tick(){if(H=void 0,W)schedule(25);else{W=!0;try{for(let[e,t]of B)if(performance.now()>=t)B.delete(e);else try{process.kill(-e,0)}catch(t){r(t,`ESRCH`)&&B.delete(e)}if(B.size===0)return;for(let e of await _(`/proc/self/task`)){let t;try{t=await g(`/proc/self/task/${e}/children`,`utf8`)}catch{continue}for(let e of t.trim().split(/\s+/u).filter(Boolean)){let t=Number(e),n;try{n=await g(`/proc/${t}/stat`,`utf8`)}catch{continue}let[r,i,a]=n.slice(n.lastIndexOf(`)`)+2).split(` `);if(B.has(Number(a))&&t!==Number(a)&&Number(i)===process.pid&&r===`Z`)try{if(!j()){B.clear();return}A(t).kind===`exited`&&M(t)}catch{}}}}catch{}finally{W=!1,B.size>0?schedule(1e3):(clearTimeout(H),H=void 0,process.off(`SIGCHLD`,onExit))}}}function scheduleAdoptedChildZombieReapAfterExit(e,t,n=V){if(process.platform!==`linux`||!t||e.pid===void 0||z.has(e))return;let r=e.pid;z.add(e);let start=()=>{B.size===0&&process.on(`SIGCHLD`,onExit),B.set(r,performance.now()+Math.max(V,n)),onExit()};e.exitCode!==null||e.signalCode!==null?start():e.once(`exit`,start)}var DarwinProcessInspectionError=class extends Error{constructor(e,t){super(`Darwin process inspection ${e}`,t),this.reason=e,this.name=`DarwinProcessInspectionError`,this.code=e===`deadline`?`ETIMEDOUT`:e===`permission`?`EPERM`:`EIO`}};function failure(e){if(e instanceof DarwinProcessInspectionError)return e;let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return new DarwinProcessInspectionError(t===`ETIMEDOUT`||t===`ABORT_ERR`||t===`timeout`?`deadline`:[`EACCES`,`EPERM`,`ERR_ACCESS_DENIED`,`access-denied`].includes(String(t))?`permission`:`unavailable`,{cause:e})}function remaining(e){let t=Math.floor(e-performance.now());if(t<=0)throw new DarwinProcessInspectionError(`deadline`);return t}const G={running:`R`,sleeping:`S`,stopped:`T`,zombie:`Z`,idle:`I`,unknown:`?`};function hasReadableTopology(e){if(e.parentPid===void 0||e.processGroupId===void 0||e.state===void 0){if(k(e.pid)===null)return!1;throw new DarwinProcessInspectionError(`unavailable`)}return!0}function topology(e){return{pid:e.pid,ppid:e.parentPid,pgid:e.processGroupId,state:G[e.state],owner:e.owner}}function census(e,t){try{let n=N({timeoutMs:remaining(e),...t?{pids:t}:{}}).filter(hasReadableTopology);return remaining(e),n}catch(t){throw remaining(e),failure(t)}}function*readDarwinProcessCensus(e){let t=performance.now()+e,n=census(t).map(topology);for(let e of n)remaining(t),yield e;remaining(t)}function readLinuxProcessUid(e){try{let t=f(`/proc/${e}/status`,`utf8`).split(` `).filter(e=>e.startsWith(`Uid:`)),n=(t.length===1?/^Uid:[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]*$/.exec(t[0]):null)?.slice(1).map(Number),r=process.getuid?.();return n?.every(e=>Number.isSafeInteger(e)&&e<=4294967295)?n.find(e=>e===r)??n[0]:void 0}catch{return}}function parseLinuxProcessGroupMember(e,t){let n=/^(\d+) \([\s\S]*\) (\S) (\d+) (-1|\d+)(?:\s|$)/.exec(t);if(!n||Number(n[1])!==e)throw Error(`Process group census is unavailable`);return{pid:e,ppid:Number(n[3]),pgid:Number(n[4]),state:n[2]}}async function readLinuxProcessGroupMemberAsync(e){let t=await h.readFile(`/proc/${e}/stat`,`utf8`);return{...parseLinuxProcessGroupMember(e,t),startedAt:parseLinuxProcessStat(e,t)?.startedAt??null}}function*readProcessGroupMembers(e,t){let r=t!==void 0;if(process.platform===`linux`){let t=Date.now()+e;for(let e of p(`/proc`)){if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);if(!/^\d+$/.test(e))continue;let i=Number(e),a,o,s,c=!1;try{if(a=f(`/proc/${e}/stat`,`utf8`),r){s=readLinuxProcessUid(i);try{o=f(`/proc/${e}/cmdline`,`utf8`).split(`\0`).filter(Boolean)}catch(e){let t=process.getuid?.();if(c=s!==void 0&&t!==void 0&&s!==t&&[`EACCES`,`EPERM`].includes(n(e)??``),!c)throw e}}}catch(e){if(i!==process.pid&&[`ENOENT`,`ESRCH`].includes(n(e)??``))continue;throw Error(`Could not classify PID ${i}: process command inspection failed (${n(e)??`unavailable`}).`,{cause:e})}let l=parseLinuxProcessGroupMember(i,a);if(Date.now()>=t)throw Error(`Process group census is unavailable`);if(o?.length===0){let e=Number(a.slice(a.lastIndexOf(`)`)+2).split(/\s+/)[6]);if(!(Number.isInteger(e)&&e&2097152)&&!isPidDefinitelyDead(i)){let e=process.getuid?.();if(s!==void 0&&e!==void 0&&s!==e)c=!0,o=void 0;else throw Error(`Could not classify PID ${i}: live userspace process has no readable arguments.`)}}yield{pid:i,pgid:l.pgid,state:l.state,...o?{command:{ppid:l.ppid,argv:o,...s===void 0?{}:{uid:s}}}:c&&s!==void 0?{command:{ppid:l.ppid,argvUnavailable:!0,uid:s}}:{}}}if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);return}if(process.platform===`darwin`){for(let n of readDarwinProcessCensus(e)){let e={pid:n.pid,pgid:n.pgid,state:n.state},i;try{i=r?n.state.startsWith(`Z`)||n.pid===0?{argv:[]}:t?.readDarwinCommand(n.pid,n.owner):void 0}catch(t){if(!(t instanceof O)||t.code!==`incomplete`&&t.code!==`layout-mismatch`)throw t;yield{...e,ppid:n.ppid};continue}(!r||i)&&(yield{...e,...i?{command:{ppid:n.ppid,owner:n.owner,...i}}:{}})}return}if(r)throw Error(`Exact process command census is unavailable on ${process.platform}.`);let i=Date.now()+e,a=T(`/bin/ps`,[`-A`,`-o`,`pid=,pgid=,stat=`],{encoding:`utf8`,timeout:e,maxBuffer:4194304});if(a.error||a.status!==0)throw Error(`Process group census is unavailable`);for(let e of a.stdout.split(` `)){if(!e.trim())continue;let t=/^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(e);if(!t)throw Error(`Process group census is unavailable`);let n=Number(t[1]);n!==a.pid&&(yield{pid:n,pgid:Number(t[2]),state:t[3]})}if(r&&Date.now()>=i)throw Error(`Process group census exceeded its deadline`)}function isLiveCensusMember({pid:e,state:t}){return!t.startsWith(`Z`)||process.platform===`linux`&&!isPidDefinitelyDead(e)}function isOwnProcfs(){if(process.platform!==`linux`)return!0;try{return m(`/proc/self`)===String(process.pid)}catch{return!1}}function isProcessGroupGoneByCensus(e){if(!isOwnProcfs())return!1;try{for(let t of readProcessGroupMembers(1e3))if(t.pgid===e&&isLiveCensusMember(t))return!1;return!0}catch{return!1}}async function*readLinuxProcessGroupMembersAsync(e){if(process.platform!==`linux`)throw Error(`Asynchronous Linux process census requires Linux`);let t=Date.now()+e;for(let e of await h.readdir(`/proc`)){if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);if(!/^\d+$/.test(e))continue;let r=Number(e),i;try{i=await h.readFile(`/proc/${e}/stat`,`utf8`)}catch(e){if(r!==process.pid&&[`ENOENT`,`ESRCH`].includes(n(e)??``))continue;throw e}if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`);yield parseLinuxProcessGroupMember(r,i)}if(Date.now()>=t)throw Error(`Process group census exceeded its deadline`)}async function isOwnProcfsAsync(){if(process.platform!==`linux`)return!0;try{return await h.readlink(`/proc/self`)===String(process.pid)}catch{return!1}}async function isProcessGroupGoneByCensusAsync(e){if(!await isOwnProcfsAsync())return!1;try{for await(let t of readLinuxProcessGroupMembersAsync(1e3))if(t.pgid===e&&(!t.state.startsWith(`Z`)||!await isPidDefinitelyDeadAsync(t.pid)))return!1;return!0}catch{return!1}}function shouldDetachChildForProcessTree(){return process.platform!==`win32`}function isDeniedProcessGroupProbe(e,t=0){if(process.platform!==`linux`||!r(e,`EPERM`))return!1;try{return process.kill(-4194305,t),!1}catch(e){return r(e,`EPERM`)}}function probeProcessGroup(e){try{return process.kill(-e,0),`alive`}catch(e){return r(e,`ESRCH`)?`gone`:isDeniedProcessGroupProbe(e)?`denied`:`alive`}}function isProcessGroupGoneByKernel(e){return probeProcessGroup(e)===`gone`}function isProcessGroupGone(e){let t=probeProcessGroup(e);return t===`gone`||t===`denied`&&isProcessGroupGoneByCensus(e)}async function isProcessGroupGoneAsync(e){let t=probeProcessGroup(e);return t===`gone`||t===`denied`&&await isProcessGroupGoneByCensusAsync(e)}async function isChildProcessTreeAliveAsync(e){return typeof e.pid!=`number`||e.pid<=0?!1:shouldDetachChildForProcessTree()?!await isProcessGroupGoneAsync(e.pid):isChildProcessTreeAlive(e)}function isChildProcessTreeAlive(e){if(typeof e.pid!=`number`||e.pid<=0)return!1;if(shouldDetachChildForProcessTree())return!isProcessGroupGone(e.pid);try{return process.kill(e.pid,0),!0}catch(e){return!r(e,`ESRCH`)}}function readCommandProcessStartTime(e,t={}){return process.platform!==`linux`&&process.platform!==`android`?t.instance?getProcessInstanceStartTime(e):getFileLockProcessStartTime(e):h.readFile(`/proc/${e}/stat`,`utf8`).then(n=>t.child&&(t.child.exitCode!=null||t.child.signalCode!=null)?null:parseLinuxProcessStat(e,n)?.startedAt??null,()=>null)}function childCapacityError(e,t){let n=0,r=0;for(let t of e)n++,t===`mcp`&&r++;if(n>=512)return`Spawn broker child capacity exceeded (512); close running processes before retrying`;if(t===`mcp`&&r>=448)return`Spawn broker MCP child capacity exceeded (448); close unused MCP sessions before retrying`}var SpawnBrokerError=class extends Error{constructor(e,t){super(e,t),this.code=`ERR_SPAWN_BROKER_UNAVAILABLE`,this.name=`SpawnBrokerError`}};function serializeBrokerError(e){return{message:e.message,code:e.code,errno:e.errno,syscall:e.syscall,path:e.path}}function brokerSpawnOptions(e){let t=e.stdio??`pipe`,n=typeof t==`string`?[t,t,t]:[...t],r=[];for(let e=0;e<Math.max(3,n.length);e+=1){let t=n[e]??(e<3?`pipe`:`ignore`);if(t===`inherit`&&e!==0||t!==`pipe`&&t!==`ignore`&&t!==`inherit`&&t!==`ipc`)return;r.push(t)}if(e.signal||e.timeout||e.killSignal)throw Error(`Unsupported spawn broker cancellation options`);return{cwd:e.cwd instanceof URL?x(e.cwd):e.cwd,env:e.env?{...e.env}:{...process.env},argv0:e.argv0,detached:e.detached,shell:e.shell,windowsHide:e.windowsHide,windowsVerbatimArguments:e.windowsVerbatimArguments,serialization:e.serialization,uid:e.uid,gid:e.gid,stdio:r}}const K=/* @__PURE__ */ new WeakMap,holdReadable=()=>{};function holdPipe(e){let t={read:e.read.bind(e),resumed:!1,onResume:()=>{t.resumed=!0}};K.set(e,t),e.on(`resume`,t.onResume),e.on(`readable`,holdReadable),e.read=()=>null}function restoreStdinPipe(e){let t=Reflect.get(e,`_readableState`);if(!t||typeof t!=`object`||[`ended`,`endEmitted`,`reading`].some(e=>typeof Reflect.get(t,e)!=`boolean`))throw new SpawnBrokerError(`Spawn broker requires a Node readable state for stdin`);stopPipeReads(e),Object.assign(t,{readable:!1,ended:!0,endEmitted:!0,reading:!1})}function stopPipeReads(e){let t=Reflect.get(e,`_handle`);if(!t||typeof t!=`object`||!(`readStop`in t)||typeof t.readStop!=`function`||!(`reading`in t)||typeof t.reading!=`boolean`)throw new SpawnBrokerError(`Spawn broker requires a transferable Node pipe handle`);if(t.readStop()!==0)throw new SpawnBrokerError(`Spawn broker could not stop pipe reads`);t.reading=!1}function releasePipe(e){let t=restoreReader(e);t&&process.nextTick(()=>{e.destroyed||(e.emit(`readable`),t.resumed&&e.resume())})}function restoreReader(e){let t=K.get(e);if(t)return e.read=t.read,K.delete(e),e.removeListener(`resume`,t.onResume),e.removeListener(`readable`,holdReadable),t}var BrokerChild=class extends D{constructor(e,t,n,r=!1){super(),this.requestId=e,this.transmit=n,this.fileOutputPending=r,this.callbackContext=new b(`OpenClawSpawnBrokerChild`),this.stdin=null,this.stdout=null,this.stderr=null,this.connected=!1,this.killed=!1,this.exitCode=null,this.signalCode=null,this.stdio=[null,null,null,null,null],this.opened=c(),this.completion=c(),this.pipes=/* @__PURE__ */ new Set,this.sends=/* @__PURE__ */ new Map,this.sendSequence=0,this.spawnReceived=!1,this.eventsReleased=!1,this.pendingEventOverflow=!1,this.pendingEvents=[],this.exited=!1,this.closed=!1,this.processNotStarted=!1,this.spawnfile=t[0],this.spawnargs=[...t],this.opened.promise.catch(()=>{}),this.on(`error`,()=>{})}markNotStarted(){this.processNotStarted=!0}get notStarted(){return this.processNotStarted}ready(){return this.opened.promise}emit(e,...t){return this.callbackContext.runInAsyncScope(()=>super.emit(e,...t))}waitForClose(){return this.completion.promise}settleFileOutput(){this.fileOutputPending=!1,this.finishClose()}attachPipe(e,t){t.emit=this.callbackContext.bind(t.emit.bind(t)),this.stdio[e]=t,e===0&&(this.stdin=t),e===1&&(this.stdout=t),e===2&&(this.stderr=t),this.pipes.add(t);let n=!1,acknowledge=t=>{n||(n=!0,this.transmit({type:`output-drained`,id:this.requestId,fd:e,error:t?serializeBrokerError(t):void 0}).catch(()=>{}))};t.once(e===0?`finish`:`end`,()=>acknowledge()),t.on(`error`,acknowledge),t.once(`close`,()=>{acknowledge(),this.pipes.delete(t),this.finishClose()})}receive(e){if(e.type===`spawned`){if(this.spawnReceived||this.closed)return;for(this.spawnReceived=!0,this.pid=e.pid,this.spawnfile=e.spawnfile,this.spawnargs=e.spawnargs,this.connected=e.connected,this.stdio.splice(e.stdioLength);this.stdio.length<e.stdioLength;)this.stdio.push(null);this.connected&&(this.channel=Object.assign(new D,{ref(){},unref(){}})),this.opened.resolve(),setImmediate(()=>{this.closed||(this.emit(`spawn`),setImmediate(()=>{for(let[e,t]of this.stdio.entries())e>0&&t instanceof P&&!t.destroyed&&releasePipe(t);this.eventsReleased=!0;for(let e of this.pendingEvents.splice(0))e()}))})}else!this.eventsReleased&&(this.spawnReceived||e.type!==`error`)?this.deferEvent(()=>this.emitMessage(e)):this.emitMessage(e)}deferEvent(e){this.pendingEventOverflow||(this.pendingEvents.length>=64?(this.pendingEventOverflow=!0,this.pendingEvents.splice(0),this.pendingEvents.push(()=>{this.kill(`SIGKILL`),this.failNow(new SpawnBrokerError(`Spawn broker startup event capacity exceeded`))})):this.pendingEvents.push(e))}emitMessage(e){switch(e.type){case`error`:{let t=Object.assign(Error(e.error.message),e.error);this.opened.reject(t),this.emit(`error`,t),this.pid||(this.exited=!0,this.finishClose());break}case`exit`:this.exited=!0,this.exitCode=e.code,this.signalCode=e.signal,this.stdin?.destroy(),this.emit(`exit`,e.code,e.signal),process.nextTick(()=>{for(let e of this.pipes)e.readable&&e.resume()}),this.finishClose();break;case`ipc-sent`:this.finishSend(e.sequence,e.error?Object.assign(Error(e.error.message),e.error):null);break;case`disconnect`:this.failSends(/* @__PURE__ */ Error(`Child process IPC channel is closed`)),this.connected=!1,this.channel=void 0,this.emit(`disconnect`),this.finishClose();break;case`ipc`:this.emit(`message`,e.message);break;case`closed`:this.finishClose()}}fail(e){this.spawnReceived&&!this.eventsReleased?this.deferEvent(()=>this.failNow(e)):this.failNow(e)}failNow(e){if(this.closed)return;this.opened.reject(e);let t=this.connected;this.connected=!1,this.channel=void 0,this.failSends(e),t&&this.emit(`disconnect`),this.exited||this.emit(`error`,e);for(let t of this.pipes)t.destroy(e);this.exited=!0,this.finishClose()}finishClose(){!this.exited||this.channel||this.pipes.size>0||this.closed||this.fileOutputPending||(this.closed=!0,this.completion.resolve(),this.emit(`close`,this.exitCode,this.signalCode))}kill(e=`SIGTERM`){return!this.exited&&(this.killed=!0,this.transmit({type:`kill`,id:this.requestId,signal:e}).catch(e=>this.fail(t(e,`Spawn broker signal delivery failed`))),!0)}send(e,n,r,i,a){let o=typeof n==`function`?n:typeof r==`function`?r:i;if(!this.connected||this.sends.size>=1024){let e=/* @__PURE__ */ Error(this.connected?`Child process IPC capacity exceeded`:`Child process IPC channel is closed`);return queueMicrotask(()=>o?o(e):this.emit(`error`,e)),!1}let s=++this.sendSequence;this.sends.set(s,b.bind(e=>{o?o(e):e&&this.emit(`error`,e)}));let c=typeof n==`function`?void 0:n;return this.transmit({type:`ipc`,id:this.requestId,sequence:s,message:e},c,a).catch(e=>this.finishSend(s,t(e,`Spawn broker IPC delivery failed`))),!0}finishSend(e,t){let n=this.sends.get(e);this.sends.delete(e),n?.(t)}failSends(e){for(let t of this.sends.keys())this.finishSend(t,e)}disconnect(){this.connected&&(this.connected=!1,this.transmit({type:`disconnect`,id:this.requestId}).catch(e=>this.fail(t(e,`Spawn broker disconnect failed`))))}ref(){}unref(){}[Symbol.dispose](){this.kill(`SIGTERM`)}};const q=`--openclaw-sqlite-readonly-child`,J=a(import.meta.url),Y=new i(Symbol(`spawnBroker`)),X={startupDisabled:!1};function getSpawnBroker(){let e=Y.getStore();return X.startupDisabled||e===null?void 0:e??X.host}const Z=new TextDecoder,Q=/* @__PURE__ */ new Map([[` `,` `],[` `,` `],[`\b`,`\\b`],[`\f`,`\\f`],[`\r`,`\\r`],[` `,`\\t`]]);function renderOutput(e){let t=typeof e==`string`?e:Z.decode(e);return t.endsWith(` `)&&(t=t.slice(0,t.endsWith(`\r `)?-2:-1)),y(t).replace(/[\p{Separator}\p{Other}]/gu,e=>{let t=Q.get(e);if(t!==void 0)return t;let n=e.codePointAt(0),r=n.toString(16);return n<=65535?`\\u${r.padStart(4,`0`)}`:`\\U${r}`})}function decodeExecaMessage(e,t){return e.messageOutputs?[e.message,...e.messageOutputs.map(e=>renderOutput(t[e]))].join(` `):e.message}function restoreError(e,t){let n=Error(decodeExecaMessage(e,t),{cause:e.cause?restoreError(e.cause,t):void 0});return Object.assign(n,{name:e.name,code:e.code})}function restoreExecaResult(e){let{error:t,...n}=e,r={...n,stdout:n.stdout,stderr:n.stderr,shortMessage:n.shortMessage,code:n.code};if(t){let e=restoreError(t,r);return Object.assign(e,r,{cause:e.cause})}return{...r,cause:void 0}}const $={npm:`npm-cli.js`,npx:`npx-cli.js`};resolveRuntimeProcessDistRoot(x(import.meta.url));function resolveRuntimeProcessDistRoot(e){let t=e.replaceAll(v.sep,`/`).lastIndexOf(`/dist/`);return t>=0?e.slice(0,t+6):void 0}function resolveRuntimeDependencyEntrypointUrlFromDirectory(e,t){return S(v.join(t,$[e]))}export{isPidDefinitelyDead as A,readLinuxProcessGroupMembersAsync as C,getFileLockProcessStartTime as D,killProcessTree as E,readLinuxProcessStat as M,truncateUtf8Suffix as N,getProcessInstanceStartTime as O,readLinuxProcessGroupMemberAsync as S,scheduleAdoptedChildZombieReapAfterExit as T,isProcessGroupGone as _,q as a,isOwnProcfs as b,brokerSpawnOptions as c,SpawnBrokerError as d,childCapacityError as f,isDeniedProcessGroupProbe as g,isChildProcessTreeAliveAsync as h,getSpawnBroker as i,isPidDefinitelyDeadAsync as j,isPidAlive as k,holdPipe as l,isChildProcessTreeAlive as m,resolveRuntimeProcessDistRoot as n,J as o,readCommandProcessStartTime as p,restoreExecaResult as r,BrokerChild as s,resolveRuntimeDependencyEntrypointUrlFromDirectory as t,restoreStdinPipe as u,isProcessGroupGoneAsync as v,readProcessGroupMembers as w,isOwnProcfsAsync as x,isProcessGroupGoneByKernel as y};