openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
12 lines • 11.5 kB
JavaScript
import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{p as parseNodeReleaseVersion}from"./node-version-EaZf6kHy.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import fs,{readFile,readFileSync}from"node:fs";import path from"node:path";import{createHash}from"node:crypto";import{readdir}from"node:fs/promises";import os from"node:os";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";
//!src/process/child-memory.ts
const rssField=Buffer.from(`
VmRSS:`);const swapField=Buffer.from(`
VmSwap:`);const pssField=Buffer.from(`
Pss:`);const swapPssField=Buffer.from(`
SwapPss:`);const nodeVersion=parseNodeReleaseVersion(process.versions.node);const reuseReadBuffer=!process.versions.bun&&nodeVersion&&(nodeVersion.major===24&&nodeVersion.minor>=19||nodeVersion.major===26&&nodeVersion.minor>=4&&nodeVersion.minor<8);const nativeReadFile=promisify(readFile);const readKernelFile=reuseReadBuffer?readSmallKernelFile:nativeReadFile;function readSmallKernelFile(e,t=Buffer.allocUnsafe(4096)){return new Promise((n,r)=>{readFile(e,{buffer:t},(t,i)=>{if(hasErrnoCode(t,`ERR_INVALID_ARG_VALUE`))nativeReadFile(e).then(n,r);else if(t)r(t);else n(i)})})}function readStatusNumber(e,t){const n=e.indexOf(t);if(n<0)return 0;let r=n+t.length;while(e[r]===32||e[r]===9)r++;let i=0;while(true){const 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(readFileSync(`/proc/self/cgroup`,`utf8`))?.[1]}catch{return}if(!t)return;const n=`/sys/fs/cgroup`;let r=path.resolve(n,`.${t}`);if(r!==n&&!r.startsWith(`${n}/`))return;for(;;){for(const t of[`memory.max`,`memory.high`,`memory.swap.max`])try{const n=readFileSync(path.join(r,t),`utf8`).trim();if(/^\d+$/u.test(n)){const r=t===`memory.swap.max`?`swapBytes`:`memoryBytes`;e[r]=Math.min(e[r],Number(n))}}catch{}if(r===n)break;r=path.dirname(r)}}function resolveHostExecMemoryBudget(){if(process.platform!==`linux`)return;const e=process.constrainedMemory();const t={memoryBytes:e>0?Math.min(os.totalmem(),e):os.totalmem(),swapBytes:0};try{t.swapBytes=Number(/^SwapTotal:\s+(\d+)/mu.exec(readFileSync(`/proc/meminfo`,`utf8`))?.[1]??0)*1024}catch{}constrainToCgroupAncestors(t);const n=t.memoryBytes;const r=process.memoryUsage.rss();const i=Math.max(256*1024**2,n/8);const a=Math.max(n/8,r*1.5);const o=Math.min(n/4,(n-r)/2);const s=Math.max(1,Math.floor(Math.max(n-i-a,o)));return{memoryBytes:s<1024**2?s:Math.floor(s/1024**2)*1024**2,swapBytes:Math.floor(Math.min(t.swapBytes,n/4))}}const owner=resolveGlobalSingleton(Symbol.for(`openclaw.hostExecMemory`),()=>({watches:/* @__PURE__ */ new Set,sampling:false,assessmentPending:false}));function getHostExecMemoryBudget(){if(process.platform!==`linux`)return;return owner.budget??=resolveHostExecMemoryBudget()}function formatLimit(e,t){const 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){const t=/* @__PURE__ */ new Map;return n=>{let r=t.get(n);if(!r){r=e(n);t.set(n,r)}return r}}async function readMemory(e){try{const t=await readKernelFile(`/proc/${e}/smaps_rollup`);if(t.includes(pssField))return{memoryBytes:readStatusNumber(t,pssField)*1024,swapBytes:readStatusNumber(t,swapPssField)*1024}}catch{}const t=await readKernelFile(`/proc/${e}/status`);return{memoryBytes:readStatusNumber(t,rssField)*1024,swapBytes:readStatusNumber(t,swapField)*1024}}async function readCgroupMemoryUsage(e){const[t,n]=await Promise.all([readKernelFile(`${e}/memory.current`),readKernelFile(`${e}/memory.swap.current`)]);const r=Number(t.toString().trim());const i=Number(n.toString().trim());if(!Number.isFinite(r)||r<0||!Number.isFinite(i)||i<0)throw new Error(`Host exec cgroup memory usage is unavailable`);return{memoryBytes:r,swapBytes:i}}async function readChildren(e){const t=[];const n=reuseReadBuffer?Buffer.allocUnsafe(4096):void 0;for(const r of await readdir(`/proc/${e}/task`))try{const i=await readKernelFile(`/proc/${e}/task/${r}/children`,n);let a=0;for(let e=0;e<=i.length;e++){const n=i[e];if(n!==void 0&&n>=48&&n<=57)a=a*10+n-48;else{if(a>0)t.push(a);a=0}}}catch(e){if(!hasErrnoCode(e,`ENOENT`)&&!hasErrnoCode(e,`ESRCH`))throw e}return t}async function readTreeMemory(e,t,n){const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Set([e]);for(const e of i){if(t())break;try{r.set(e,await n.memory(e));if(t())break;for(const t of await n.children(e))i.add(t)}catch(e){if(!hasErrnoCode(e,`ENOENT`)&&!hasErrnoCode(e,`ESRCH`))throw e}}return{pids:r,extra:{memoryBytes:0,swapBytes:0}}}function totalUsage(){const e={memoryBytes:0,swapBytes:0};const t=/* @__PURE__ */ new Map;for(const{snapshot:n}of owner.watches){e.memoryBytes+=n.extra.memoryBytes;e.swapBytes+=n.extra.swapBytes;for(const[e,r]of n.pids){const n=t.get(e);t.set(e,{memoryBytes:Math.max(n?.memoryBytes??0,r.memoryBytes),swapBytes:Math.max(n?.swapBytes??0,r.swapBytes)})}}for(const 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(){if(owner.assessmentPending)return;owner.assessmentPending=true;queueMicrotask(()=>{owner.assessmentPending=false;const e=getHostExecMemoryBudget();if(!e)return;const t=totalUsage();if(nearBudget(t,e)){for(const e of owner.watches)if(Number.isFinite(e.due))e.due=Math.min(e.due,performance.now()+1e3);schedule()}const n=t.memoryBytes>e.memoryBytes?`memoryBytes`:t.swapBytes>e.swapBytes?`swapBytes`:void 0;if(!n||Array.from(owner.watches).some(e=>e.cancelling))return;let r;let i=0;for(const e of owner.watches){let t=e.snapshot.extra[n];for(const r of e.snapshot.pids.values())t+=r[n];if(t>i){i=t;r=e}}if(r){const n=r;n.cancelling=true;n.limit(t,e).catch(()=>{n.cancelling=false;process.emitWarning(`Host exec memory cancellation failed; shared memory protection is degraded`)})}})}function schedule(){clearTimeout(owner.timer);if(owner.sampling||!owner.watches.size)return;const e=Math.min(...Array.from(owner.watches,e=>e.due));if(!Number.isFinite(e))return;owner.timer=runInDetachedAsyncContext(()=>setTimeout(()=>sample(),Math.max(0,Math.ceil(e-performance.now()))));owner.timer.unref()}function sample(){owner.sampling=true;const e=Array.from(owner.watches).filter(e=>e.due<=performance.now()+999);const t={memory:shareReads(readMemory),children:shareReads(readChildren)};for(const n of e){n.due=Infinity;n.sample(t).catch(()=>{})}owner.sampling=false;schedule()}function watchHostExecMemory(e){if(!getHostExecMemoryBudget())return()=>{};let t=false;const n={due:performance.now()+1e3,snapshot:{pids:/* @__PURE__ */ new Map,extra:{memoryBytes:0,swapBytes:0}},cancelling:false,limit:AsyncLocalStorage.bind(async(t,n)=>{try{e.onDiagnostic(`\n${formatLimit(t,n)}\n`)}finally{await e.onLimit()}}),sample:AsyncLocalStorage.bind(async r=>{if(!owner.watches.has(n))return;let i=1e3;try{const t=e.readUsage?{pids:/* @__PURE__ */ new Map,extra:await e.readUsage()}:await readTreeMemory(e.pid,()=>!owner.watches.has(n),r);if(!owner.watches.has(n))return;const a=n.snapshot.pids;n.snapshot=t;i=5e3;if(Array.from(t.pids.keys()).some(t=>!a.has(t)&&t!==e.pid))i=1e3;assess()}catch{if(owner.watches.has(n)&&!t){t=true;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()}})};owner.watches.add(n);schedule();return()=>{owner.watches.delete(n);schedule()}}
//!src/process/linux-exec-cgroup.ts
const cgroupMount=`/sys/fs/cgroup`;const controllers=[`cpu`,`io`,`memory`];function prepareAgentExecCgroupScope(e,t){const n=t?.trim();const r=path.join(e,n?`session-${createHash(`sha256`).update(n).digest(`hex`).slice(0,32)}`:`unscoped`);fs.mkdirSync(r,{recursive:true});const i=fs.readFileSync(path.join(e,`io.max`),`utf8`).trim();for(const e of i.split(`
`)){const[t,...n]=e.split(/\s+/u);if(!t)continue;const i=n.map(e=>{const[t,n]=e.split(`=`);const r=Number(n);return`${t}=${r>0&&Number.isFinite(r)?Math.max(1,Math.floor(r/2)):n}`});fs.writeFileSync(path.join(r,`io.max`),[t,...i].join(` `))}return r}function resolveGatewayServiceCgroupDirectory(){const e=/^0::(.+)$/mu.exec(fs.readFileSync(`/proc/self/cgroup`,`utf8`))?.[1];const t=e&&/^(\/(?:[^/]+\/)*[^/]+\.service)\/(?:gateway|agent-exec(?:\/(?:session-[a-f0-9]{32}|unscoped))?)$/u.exec(e);if(!t)return;const n=path.join(cgroupMount,t[1]);fs.accessSync(n,fs.constants.W_OK|fs.constants.X_OK);fs.accessSync(path.join(n,`cgroup.subtree_control`),fs.constants.W_OK);fs.accessSync(path.join(n,`gateway`,`cgroup.procs`),fs.constants.W_OK);const r=new Set(fs.readFileSync(path.join(n,`cgroup.controllers`),`utf8`).trim().split(/\s+/u));if(!controllers.every(e=>r.has(e)))throw new Error(`the service has not delegated cpu, io, and memory controllers`);if(fs.readFileSync(path.join(n,`cgroup.procs`),`utf8`).trim())throw new Error(`the service root still contains processes; move its launcher into the gateway leaf`);return n}async function applyAgentExecMemoryBudget(){if(process.platform!==`linux`)return;try{const e=resolveGatewayServiceCgroupDirectory();const t=/^0::(.+)$/mu.exec(fs.readFileSync(`/proc/self/cgroup`,`utf8`))?.[1];if(!e||path.join(cgroupMount,t??``)!==path.join(e,`gateway`))return;const n=path.join(e,`agent-exec`);if(fs.readFileSync(path.join(n,`cpu.weight`),`utf8`).trim()!==`10`)return;const r=getHostExecMemoryBudget();if(!r)return;const{memoryBytes:i}=r;const a=path.join(n,`memory.high`);if(fs.readFileSync(a,`utf8`).trim()!==String(i))await fs.promises.writeFile(a,String(i),{flag:fs.constants.O_WRONLY|fs.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`)return;try{const t=resolveGatewayServiceCgroupDirectory();if(!t)return;const n=new Set(fs.readFileSync(path.join(t,`cgroup.subtree_control`),`utf8`).trim().split(/\s+/u));const r=path.join(t,`agent-exec`);fs.accessSync(r,fs.constants.W_OK|fs.constants.X_OK);fs.accessSync(path.join(r,`cgroup.procs`),fs.constants.W_OK);const i=fs.readFileSync(path.join(r,`io.max`),`utf8`).trim();const a=fs.readFileSync(path.join(r,`cpu.weight`),`utf8`).trim();if(controllers.every(e=>n.has(e))&&i&&a===`10`){const t=new Set(fs.readFileSync(path.join(r,`cgroup.subtree_control`),`utf8`).trim().split(/\s+/u));if(!controllers.every(e=>t.has(e)))return r;try{return prepareAgentExecCgroupScope(r,e)}catch(e){process.emitWarning(`Session exec IO policy unavailable; using the shared exec budget: ${String(e)}`);return path.join(r,`unscoped`)}}}catch{}}function enterAgentExecCgroup(e){const t=getAgentExecCgroup(e);if(t)try{fs.writeFileSync(path.join(t,`cgroup.procs`),`0`)}catch(e){process.emitWarning(`Agent exec cgroup placement failed: ${String(e)}`)}}export{resolveGatewayServiceCgroupDirectory as a,watchHostExecMemory as c,prepareAgentExecCgroupScope as i,enterAgentExecCgroup as n,getHostExecMemoryBudget as o,getAgentExecCgroup as r,readCgroupMemoryUsage as s,applyAgentExecMemoryBudget as t};