openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 12.3 kB
JavaScript
import{i as e}from"./transcript-global-singleton-DIJgobpU.mjs";import{t}from"./transcript-subsystem-C0UTtuvS.mjs";import{t as n}from"./transcript-state-dir-DEo0wD2Q.mjs";import{t as r}from"./transcript-openclaw-root-MOWp8O-B.mjs";import"./transcript-cli-invocation-xwXCxqwu.mjs";import{t as i}from"./transcript-json-utf8-bytes-CWHhKtrl.mjs";import*as a from"node:v8";import{getEnvironmentData as o,isMainThread as s,setEnvironmentData as c}from"node:worker_threads";import l from"node:path";import{randomUUID as u}from"node:crypto";import d from"node:fs/promises";import{fileURLToPath as f}from"node:url";import{setImmediate as p,setTimeout as m}from"node:timers/promises";import{replaceFileAtomic as h}from"@openclaw/fs-safe/atomic";function parseNodeOptionsEnvVar(e){let t=[],n=``,r=!1,i=e??``;for(let e=0;e<i.length;e+=1){let a=i.charAt(e);if(a===`\\`&&r){if(e+=1,e>=i.length)return null;a=i.charAt(e)}else if(a===` `&&!r){n.length>0&&(t.push(n),n=``);continue}else if(a===`"`){r=!r;continue}n+=a}return r?null:(n.length>0&&t.push(n),t)}e(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=o(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return c(e,n),new Int32Array(n)});const g=/* @__PURE__ */ new Set([`(root)`,`(program)`,`(idle)`,`(garbage collector)`,`(GC)`,`(PARSER)`,`(COMPILER)`,`(BYTECODE_COMPILER)`,`(V8 API)`,`(EXTERNAL)`,`(LOGGING)`,`(IDLE_EXTERNAL)`,`(IDLE)`,`(JS)`,`(deopt)`]);let _=!1;var ProfileFailure=class extends Error{constructor(e){super(e),this.reason=e}};function assertProfile(e){if(!e)throw new ProfileFailure(`invalid-profile`)}function createInspectorProfileCapture(e,t){let n=new e.Session;return n.connect(),{setup:()=>t.setup(n),start:()=>t.start(n),stop:()=>t.stop(n),close:async()=>{let e=!1;try{await t.disable(n),e=!0}catch{}if(n.disconnect(),!e)throw new ProfileFailure(`cleanup-failed`)}}}function hasProfilerConflict(){let e=parseNodeOptionsEnvVar(process.env.NODE_OPTIONS);return e===null||!!process.env.NODE_V8_COVERAGE||!!(process.versions.bun&&(process.env.BUN_INSPECT||process.env.BUN_INSPECT_CONNECT_TO))||[...process.execArgv,...e??[]].some(e=>/^--(?:inspect|cpu-prof|heap-prof|prof|perf-|.*coverage)/.test(e.replaceAll(`_`,`-`)))}function codeUrl(e,t){if(/^node:[a-zA-Z0-9_./-]+$/.test(e))return e;if(e.length>2048||/[?#]/.test(e))return;let n=e;if(e.startsWith(`file:`))try{n=f(e)}catch{return}if(!l.isAbsolute(n))return;let r=t?l.relative(t,n).split(l.sep).join(`/`):``,i=(t&&!r.startsWith(`..`)?`/${r}`:l.normalize(n).split(l.sep).join(`/`)).match(/.*\/node_modules\/((?:@[a-zA-Z0-9_-][a-zA-Z0-9._-]*\/)?[a-zA-Z0-9_-][a-zA-Z0-9._-]*)\//)?.[1];return i?`node_modules/${i}`:/^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?(?:src|dist)\/[a-zA-Z0-9_@./+-]+\.[cm]?js$/.test(r)||/^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?src\/[a-zA-Z0-9_@./+-]+\.ts$/.test(r)?`openclaw:${r}`:void 0}function sanitizeDiagnosticProfileFrame(e,t){assertProfile(!!e&&typeof e.functionName==`string`&&typeof e.url==`string`&&typeof e.scriptId==`string`&&/^-?\d{1,32}$/.test(e.scriptId)&&Number.isSafeInteger(e.lineNumber)&&Number.isSafeInteger(e.columnNumber));let n=codeUrl(e.url,t),r=e.url===``&&g.has(e.functionName),i=n?.startsWith(`node_modules/`)?`[dep:${n.slice(13)}]`:e.scriptId===`0`&&e.url===``&&e.lineNumber<0&&!r?`[native]`:void 0,a=r||n!==void 0&&e.functionName.length<=256&&/^(?:(?:(?:get|set) )?[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*)?$/.test(e.functionName);return{redacted:!a&&!i,callFrame:{functionName:i??(a?e.functionName:`[redacted]`),scriptId:e.scriptId,url:n??``,lineNumber:e.lineNumber,columnNumber:e.columnNumber}}}async function captureDiagnosticProfile(e){let unavailable=(e,t=!1)=>({status:`unavailable`,reason:e,cleanupFailed:t});if(_)return unavailable(`busy`);_=!0;let t,n=!1,i=!1,o,c=!1,l,u,d,f=0,p=0,h=null,assertActive=()=>{if(e.signal?.aborted||!e.hasAuthority())throw new ProfileFailure(`cancelled`)};try{assertActive();let o=await import(`node:inspector/promises`).catch(()=>{throw new ProfileFailure(`unsupported`)}),c=!s&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(c())throw new ProfileFailure(`tracing-active`)};if(h=await r({moduleUrl:import.meta.url}),assertActive(),o.url()||hasProfilerConflict())throw new ProfileFailure(`conflict`);assertTracingInactive(),t=e.create(o),await t.setup?.(),assertActive(),assertTracingInactive(),u={...process.memoryUsage(),heapSpaces:a.getHeapSpaceStatistics()};let g=performance.now();n=!0;let _=t.start();p=performance.now()-g,await _,e.durationMs>0&&await m(e.durationMs,void 0,{signal:e.signal}),assertActive(),i=!0;let v=await t.stop();if(!v)throw new ProfileFailure(`capture-failed`);({profile:l}=v),f=performance.now()-g,d={...process.memoryUsage(),heapSpaces:a.getHeapSpaceStatistics()}}catch(t){o=t instanceof ProfileFailure?t.reason:e.signal?.aborted?`cancelled`:t instanceof Error&&t.message.startsWith(`Inspector error -32601:`)?`unsupported`:`capture-failed`}finally{if(t){if(n&&!i)try{await t.stop()}catch{c=!0}try{await t.close()}catch{c=!0}}}if(o||c)return _=!1,unavailable(o??`cleanup-failed`,c);try{assertActive();let t=await e.sanitize(l,h,{durationMs:f,startBlockedMs:p,before:u,after:d});return assertActive(),{status:`complete`,result:t}}catch(e){return unavailable(e instanceof ProfileFailure?e.reason:`invalid-profile`)}finally{_=!1}}function sanitizeDiagnosticCpuProfile(e,t,{startBlockedMs:n}){if(assertProfile(e.samples!==void 0&&e.timeDeltas!==void 0),e.nodes.length>16384||e.samples.length>65536)throw new ProfileFailure(`profile-too-large`);let r=0,a=e.nodes.map(e=>{let{callFrame:n,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);return r+=Number(i||e.deoptReason!==void 0),{id:e.id,callFrame:n,...e.children===void 0?{}:{children:e.children},...e.hitCount===void 0?{}:{hitCount:e.hitCount},...e.positionTicks===void 0?{}:{positionTicks:e.positionTicks},...e.deoptReason===void 0?{}:{deoptReason:`[redacted]`}}}),o={requestedDurationMs:5e3,actualDurationMs:(e.endTime-e.startTime)/1e3,startBlockedMs:n,samplingIntervalMicros:1e4,sampleLossCount:null,redactedNodeCount:r,profile:{nodes:a,startTime:e.startTime,endTime:e.endTime,samples:e.samples,timeDeltas:e.timeDeltas}};if(i(o,1048576).complete)return o;let s=new Map(a.map(e=>[e.id,e])),c=/* @__PURE__ */ new Map;for(let e of a)for(let t of e.children??[])c.set(t,e.id);let l=/* @__PURE__ */ new Map;for(let t of e.samples)l.set(t,(l.get(t)??0)+1);let u=/* @__PURE__ */ new Map;for(let[e,t]of l){let n=[],r=s.get(e);for(;r&&n.length<8;)n.push(r.callFrame),r=s.get(c.get(r.id));let i=0;if(!n.some(e=>e.url.startsWith(`openclaw:`))){let e=0;for(;r&&!r.callFrame.url.startsWith(`openclaw:`);)e++,r=s.get(c.get(r.id));r&&(n.push(r.callFrame),i=e)}let a=JSON.stringify({stack:n,elidedFrameCount:i}),o=u.get(a);o?o.sampleCount+=t:u.set(a,{stack:n,elidedFrameCount:i,sampleCount:t})}let d=[],f={...o,profile:void 0,truncated:!0,originalNodeCount:a.length,sampleCount:e.samples.length,omittedSampleCount:e.samples.length,summary:d},p=Buffer.byteLength(JSON.stringify(f));for(let e of[...u.values()].toSorted((e,t)=>t.sampleCount-e.sampleCount)){let t=Buffer.byteLength(JSON.stringify(e))+Number(f.summary.length>0);if(f.summary.length===128||p+t>1048576)break;f.summary.push(e),f.omittedSampleCount-=e.sampleCount,p+=t}return f}async function sortAllocationSummaries(e){let compare=(e,t)=>t.totalBytes-e.totalBytes||t.selfBytes-e.selfBytes,t=[],n=[];for(let r of e)n.push(r),n.length===2048&&(t.push(n.toSorted(compare)),n=[],await p());for(n.length&&t.push(n.toSorted(compare));t.length>1;){let e=[];for(let n=0;n<t.length;n+=2){let r=t[n],i=t[n+1];if(!i){e.push(r);continue}let a=[],o=0,s=0;for(;o<r.length||s<i.length;)a.push(s===i.length||o<r.length&&compare(r[o],i[s])<=0?r[o++]:i[s++]),a.length%2048==0&&await p();e.push(a)}t=e}return t[0]??[]}async function sanitizeDiagnosticHeapProfile(e,t,n){let r=e.samples,a=/* @__PURE__ */ new Map,o=[{source:e.head}],s=0,c=0;for(let{source:e,parent:n}of o){++c%1024==0&&await p();let{callFrame:r,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);s+=Number(i);let l={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]},u={node:l,parent:n,totalBytes:l.selfSize,count:0,frameId:0};a.set(l.id,u),n?.node.children.push(l);for(let t of e.children)o.push({source:t,parent:u}),++c%1024==0&&await p()}o.length=0;let l=[],u=0,d=0;for(let e of r){++c%1024==0&&await p();let t=a.get(e.nodeId);t?(t.count++,l.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})):(u++,d+=e.size)}let f=[...a.values()];a.clear();for(let e=f.length-1;e>=0;e--){++c%1024==0&&await p();let t=f[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let m={...n,redactedNodeCount:s,unattributedSampleCount:u,unattributedSampleBytes:d},h={...m,truncated:u>0,profile:{head:f[0].node,samples:l}};if(i(h,1048576).complete)return h;let g=/* @__PURE__ */ new Map,_=/* @__PURE__ */ new Map,v=[];for(let e of f){++c%1024==0&&await p();let t=JSON.stringify(e.node.callFrame),n=g.get(t);n===void 0&&(n=g.size,g.set(t,n)),e.frameId=n;let{totalBytes:r,count:i}=e;if(r===0)continue;let a=e.node.selfSize,o=[e.node.callFrame];v.length=0,v.push(n);for(let t=e.parent;t&&o.length<8;t=t.parent)o.push(t.node.callFrame),v.push(t.frameId);let s=v.join(`,`),l=_.get(s);l?(l.selfBytes+=a,l.totalBytes+=r,l.count+=i):_.set(s,{stack:o,selfBytes:a,totalBytes:r,count:i})}g.clear(),f.length=0;let y={...m,truncated:!0,summary:[]},b=Buffer.byteLength(JSON.stringify(y));for(let e of await sortAllocationSummaries(_.values())){++c%1024==0&&await p();let t=Buffer.byteLength(JSON.stringify(e))+Number(y.summary.length>0);if(b+t>1048576)break;y.summary.push(e),b+=t}return y}const v=5e3,y=262144,b=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let x=Promise.resolve();async function reportWorkerGcStorm(e,n,r){let{profiles:i,...a}=e,o={...a,workerThreadId:n,workerSlot:r},s=t(`agents/code-mode`);if(i)try{let e=await writeWorkerGcProfiles(i);s.warn(`Code Mode worker GC storm`,{...o,profileFiles:e})}catch{s.warn(`Code Mode worker GC storm`,{...o,captureStatus:`unavailable`,captureReason:`profile-write-failed`})}else s.warn(`Code Mode worker GC storm`,o);if(a.captureStatus===`requested`){let{getEnabledCategories:e}=await import(`node:trace_events`);if(e())s.warn(`Code Mode worker GC storm`,{...o,captureStatus:`unavailable`,captureReason:`tracing-active`});else return a}}function captureWorkerGcProfiles(){return captureDiagnosticProfile({hasAuthority:()=>!0,durationMs:v,workerTracingInactive:!0,create:e=>createInspectorProfileCapture(e,{setup:async e=>{await e.post(`HeapProfiler.enable`),await e.post(`Profiler.enable`),await e.post(`Profiler.setSamplingInterval`,{interval:1e4})},start:async e=>{await e.post(`HeapProfiler.startSampling`,{samplingInterval:y,includeObjectsCollectedByMajorGC:!0,includeObjectsCollectedByMinorGC:!0}),await e.post(`Profiler.start`)},stop:async e=>{let[t,n]=await Promise.all([e.post(`HeapProfiler.stopSampling`),e.post(`Profiler.stop`)]);return{profile:{heap:t.profile,cpu:n.profile}}},disable:e=>Promise.all([e.post(`HeapProfiler.disable`),e.post(`Profiler.disable`)])}),sanitize:async({heap:e,cpu:t},n,r)=>({heap:JSON.stringify(await sanitizeDiagnosticHeapProfile(e,n,{durationMs:r.durationMs,requestedDurationMs:v,effectiveDurationMs:v,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:y,includeObjectsCollectedByMajorGC:!0,includeObjectsCollectedByMinorGC:!0,heapUsedBefore:r.before.heapUsed,heapUsedAfter:r.after.heapUsed,heapSpacesBefore:r.before.heapSpaces,heapSpacesAfter:r.after.heapSpaces,rssBefore:r.before.rss,rssAfter:r.after.rss})),cpu:JSON.stringify(sanitizeDiagnosticCpuProfile(t,n,r))})})}function writeWorkerGcProfiles(e){let t=x.then(async()=>{let t=l.join(n(),`diagnostics`);await d.mkdir(t,{recursive:!0,mode:448});let r=(await d.readdir(t)).filter(e=>b.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-20+2)))await d.unlink(l.join(t,e));let i=`code-mode-gc-${Date.now()}-${u()}`,a=[];for(let[n,r]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${i}.${n}profile.json`;await h({filePath:l.join(t,e),content:r,mode:384,dirMode:448}),a.push(e)}return a});return x=t.catch(()=>{}),t}export{captureWorkerGcProfiles,reportWorkerGcStorm};