UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines • 9.54 kB
import{t as e}from"./fs-safe-copy.worker-errno-CsW5NI8i.mjs";import{i as t}from"./fs-safe-copy.worker-global-singleton-DIJgobpU.mjs";import{a as n}from"./fs-safe-copy.worker-worker-diagnostic-script-C6p7spUr.mjs";import{r}from"./fs-safe-copy.worker-node-version-CFmGtosp.mjs";import i,{readFile as a,readFileSync as o}from"node:fs";import{readdir as s}from"node:fs/promises";import c from"node:path";import{promisify as l}from"node:util";import{AsyncLocalStorage as u}from"node:async_hooks";import d from"node:os";import{createHash as f}from"node:crypto";const p=Buffer.from(` VmRSS:`),m=Buffer.from(` VmSwap:`),h=Buffer.from(` Pss:`),g=Buffer.from(` SwapPss:`),_=r(process.versions.node),v=!process.versions.bun&&_&&(_.major===24&&_.minor>=19||_.major===26&&_.minor>=4&&_.minor<8),y=l(a),b=v?readSmallKernelFile:y;function readSmallKernelFile(t,n=Buffer.allocUnsafe(4096)){return new Promise((r,i)=>{a(t,{buffer:n},(n,a)=>{e(n,`ERR_INVALID_ARG_VALUE`)?y(t).then(r,i):n?i(n):r(a)})})}function readStatusNumber(e,t){let n=e.indexOf(t);if(n<0)return 0;let r=n+t.length;for(;e[r]===32||e[r]===9;)r++;let i=0;for(;;){let t=e[r++];if(t===void 0||t<48||t>57)return i;i=i*10+t-48}}function constrainToCgroupAncestors(e){let t;try{t=/^0::(\/.*)$/mu.exec(o(`/proc/self/cgroup`,`utf8`))?.[1]}catch{return}if(!t)return;let n=`/sys/fs/cgroup`,r=c.resolve(n,`.${t}`);if(r===n||r.startsWith(`${n}/`))for(;;){for(let t of[`memory.max`,`memory.high`,`memory.swap.max`])try{let n=o(c.join(r,t),`utf8`).trim();if(/^\d+$/u.test(n)){let r=t===`memory.swap.max`?`swapBytes`:`memoryBytes`;e[r]=Math.min(e[r],Number(n))}}catch{}if(r===n)break;r=c.dirname(r)}}function resolveHostExecMemoryBudget(){if(process.platform!==`linux`)return;let e=process.constrainedMemory(),t={memoryBytes:e>0?Math.min(d.totalmem(),e):d.totalmem(),swapBytes:0};try{t.swapBytes=Number(/^SwapTotal:\s+(\d+)/mu.exec(o(`/proc/meminfo`,`utf8`))?.[1]??0)*1024}catch{}constrainToCgroupAncestors(t);let n=t.memoryBytes,r=process.memoryUsage.rss(),i=Math.max(256*1024**2,n/8),a=Math.max(n/8,r*1.5),s=Math.min(n/4,(n-r)/2),c=Math.max(1,Math.floor(Math.max(n-i-a,s)));return{memoryBytes:c<1024**2?c:Math.floor(c/1024**2)*1024**2,swapBytes:Math.floor(Math.min(t.swapBytes,n/4))}}const x=t(Symbol.for(`openclaw.hostExecMemory`),()=>({watches:/* @__PURE__ */ new Set,sampling:!1,assessmentPending:!1}));function getHostExecMemoryBudget(){if(process.platform===`linux`)return x.budget??=resolveHostExecMemoryBudget()}function formatLimit(e,t){let mib=e=>Math.ceil(e/1024**2);return`Command killed because the shared host exec memory budget was exceeded (RAM ${mib(e.memoryBytes)}/${mib(t.memoryBytes)} MiB; swap ${mib(e.swapBytes)}/${mib(t.swapBytes)} MiB). Reduce concurrent work or input size. Check completed side effects before retrying; commands are never automatically replayed.`}function shareReads(e){let t=/* @__PURE__ */ new Map;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}async function readMemory(e){try{let t=await b(`/proc/${e}/smaps_rollup`);if(t.includes(h))return{memoryBytes:readStatusNumber(t,h)*1024,swapBytes:readStatusNumber(t,g)*1024}}catch{}let t=await b(`/proc/${e}/status`);return{memoryBytes:readStatusNumber(t,p)*1024,swapBytes:readStatusNumber(t,m)*1024}}async function readChildren(t){let n=[],r=v?Buffer.allocUnsafe(4096):void 0;for(let i of await s(`/proc/${t}/task`))try{let e=await b(`/proc/${t}/task/${i}/children`,r),a=0;for(let t=0;t<=e.length;t++){let r=e[t];r!==void 0&&r>=48&&r<=57?a=a*10+r-48:(a>0&&n.push(a),a=0)}}catch(t){if(!e(t,`ENOENT`)&&!e(t,`ESRCH`))throw t}return n}async function readTreeMemory(t,n,r){let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set([t]);for(let t of a){if(n())break;try{if(i.set(t,await r.memory(t)),n())break;for(let e of await r.children(t))a.add(e)}catch(t){if(!e(t,`ENOENT`)&&!e(t,`ESRCH`))throw t}}return{pids:i,extra:{memoryBytes:0,swapBytes:0}}}function totalUsage(){let e={memoryBytes:0,swapBytes:0},t=/* @__PURE__ */ new Map;for(let{snapshot:n}of x.watches){e.memoryBytes+=n.extra.memoryBytes,e.swapBytes+=n.extra.swapBytes;for(let[e,r]of n.pids){let n=t.get(e);t.set(e,{memoryBytes:Math.max(n?.memoryBytes??0,r.memoryBytes),swapBytes:Math.max(n?.swapBytes??0,r.swapBytes)})}}for(let n of t.values())e.memoryBytes+=n.memoryBytes,e.swapBytes+=n.swapBytes;return e}function nearBudget(e,t){return e.memoryBytes>=t.memoryBytes/2||e.swapBytes>0&&e.swapBytes>=t.swapBytes/2}function assess(){x.assessmentPending||(x.assessmentPending=!0,queueMicrotask(()=>{x.assessmentPending=!1;let e=getHostExecMemoryBudget();if(!e)return;let t=totalUsage();if(nearBudget(t,e)){for(let e of x.watches)Number.isFinite(e.due)&&(e.due=Math.min(e.due,performance.now()+1e3));schedule()}let n=t.memoryBytes>e.memoryBytes?`memoryBytes`:t.swapBytes>e.swapBytes?`swapBytes`:void 0;if(!n||Array.from(x.watches).some(e=>e.cancelling))return;let r,i=0;for(let e of x.watches){let t=e.snapshot.extra[n];for(let r of e.snapshot.pids.values())t+=r[n];t>i&&(i=t,r=e)}if(r){let n=r;n.cancelling=!0,n.limit(t,e).catch(()=>{n.cancelling=!1,process.emitWarning(`Host exec memory cancellation failed; shared memory protection is degraded`)})}}))}function schedule(){if(clearTimeout(x.timer),x.sampling||!x.watches.size)return;let e=Math.min(...Array.from(x.watches,e=>e.due));Number.isFinite(e)&&(x.timer=n(()=>setTimeout(()=>sample(),Math.max(0,Math.ceil(e-performance.now())))),x.timer.unref())}function sample(){x.sampling=!0;let e=Array.from(x.watches).filter(e=>e.due<=performance.now()+999),t={memory:shareReads(readMemory),children:shareReads(readChildren)};for(let n of e)n.due=1/0,n.sample(t).catch(()=>{});x.sampling=!1,schedule()}function watchHostExecMemory(e){if(!getHostExecMemoryBudget())return()=>{};let t=!1,n={due:performance.now()+1e3,snapshot:{pids:/* @__PURE__ */ new Map,extra:{memoryBytes:0,swapBytes:0}},cancelling:!1,limit:u.bind(async(t,n)=>{try{e.onDiagnostic(`\n${formatLimit(t,n)}\n`)}finally{await e.onLimit()}}),sample:u.bind(async r=>{if(!x.watches.has(n))return;let i=1e3;try{let t=e.readUsage?{pids:/* @__PURE__ */ new Map,extra:await e.readUsage()}:await readTreeMemory(e.pid,()=>!x.watches.has(n),r);if(!x.watches.has(n))return;let a=n.snapshot.pids;n.snapshot=t,i=5e3,Array.from(t.pids.keys()).some(t=>!a.has(t)&&t!==e.pid)&&(i=1e3),assess()}catch{x.watches.has(n)&&!t&&(t=!0,e.onDiagnostic(` Warning: OpenClaw could not read workload memory usage; shared memory protection is degraded. Check procfs and cgroup permissions. `))}finally{n.due=performance.now()+i,schedule()}})};return x.watches.add(n),schedule(),()=>{x.watches.delete(n),schedule()}}const S=`/sys/fs/cgroup`,C=[`cpu`,`io`,`memory`];function prepareAgentExecCgroupScope(e,t){let n=t?.trim(),r=c.join(e,n?`session-${f(`sha256`).update(n).digest(`hex`).slice(0,32)}`:`unscoped`);i.mkdirSync(r,{recursive:!0});let a=i.readFileSync(c.join(e,`io.max`),`utf8`).trim();for(let e of a.split(` `)){let[t,...n]=e.split(/\s+/u);if(!t)continue;let a=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}`});i.writeFileSync(c.join(r,`io.max`),[t,...a].join(` `))}return r}function resolveGatewayServiceCgroupDirectory(){let e=/^0::(.+)$/mu.exec(i.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=c.join(S,t[1]);i.accessSync(n,i.constants.W_OK|i.constants.X_OK),i.accessSync(c.join(n,`cgroup.subtree_control`),i.constants.W_OK),i.accessSync(c.join(n,`gateway`,`cgroup.procs`),i.constants.W_OK);let r=new Set(i.readFileSync(c.join(n,`cgroup.controllers`),`utf8`).trim().split(/\s+/u));if(!C.every(e=>r.has(e)))throw Error(`the service has not delegated cpu, io, and memory controllers`);if(i.readFileSync(c.join(n,`cgroup.procs`),`utf8`).trim())throw Error(`the service root still contains processes; move its launcher into the gateway leaf`);return n}async function applyAgentExecMemoryBudget(){if(process.platform===`linux`)try{let e=resolveGatewayServiceCgroupDirectory(),t=/^0::(.+)$/mu.exec(i.readFileSync(`/proc/self/cgroup`,`utf8`))?.[1];if(!e||c.join(S,t??``)!==c.join(e,`gateway`))return;let n=c.join(e,`agent-exec`);if(i.readFileSync(c.join(n,`cpu.weight`),`utf8`).trim()!==`10`)return;let r=getHostExecMemoryBudget();if(!r)return;let{memoryBytes:a}=r,o=c.join(n,`memory.high`);i.readFileSync(o,`utf8`).trim()!==String(a)&&await i.promises.writeFile(o,String(a),{flag:i.constants.O_WRONLY|i.constants.O_NONBLOCK})}catch(e){process.emitWarning(`Agent exec cache protection unavailable; continuing with shared sampled memory protection: ${String(e)}`)}}function getAgentExecCgroup(e){if(process.platform===`linux`)try{let t=resolveGatewayServiceCgroupDirectory();if(!t)return;let n=new Set(i.readFileSync(c.join(t,`cgroup.subtree_control`),`utf8`).trim().split(/\s+/u)),r=c.join(t,`agent-exec`);i.accessSync(r,i.constants.W_OK|i.constants.X_OK),i.accessSync(c.join(r,`cgroup.procs`),i.constants.W_OK);let a=i.readFileSync(c.join(r,`io.max`),`utf8`).trim(),o=i.readFileSync(c.join(r,`cpu.weight`),`utf8`).trim();if(C.every(e=>n.has(e))&&a&&o===`10`){let t=new Set(i.readFileSync(c.join(r,`cgroup.subtree_control`),`utf8`).trim().split(/\s+/u));if(!C.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)}`),c.join(r,`unscoped`)}}}catch{}}export{getAgentExecCgroup as n,watchHostExecMemory as r,applyAgentExecMemoryBudget as t};