openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 13.6 kB
JavaScript
import{i as e}from"./transcript-global-singleton-DIJgobpU.mjs";import{t}from"./transcript-subsystem-er2pCebD.mjs";import{t as n}from"./transcript-state-dir-BTeq06tQ.mjs";import{t as r}from"./transcript-openclaw-root-D71x7s4L.mjs";import"./transcript-cli-invocation-9KSnD_FV.mjs";import{t as i}from"./transcript-json-utf8-bytes-C2npPbGW.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 codePath(e){return l.sep===`/`?e:e.replaceAll(l.sep,`/`)}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?codePath(l.relative(t,n)):``,i=(t&&!r.startsWith(`..`)?`/${r}`:codePath(l.normalize(n))).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=r||n!==void 0&&e.functionName.length<=256&&/^(?:(?:(?:get|set) )?#?[$A-Z_a-z][$\w]*(?:\.#?[$A-Z_a-z][$\w]*)*)?$/.test(e.functionName),a=n?.startsWith(`node_modules/`)&&!(n.startsWith(`node_modules/@openclaw/`)&&i)?`[dep:${n.slice(13)}]`:e.scriptId===`0`&&e.url===``&&e.lineNumber<0&&!r?`[native]`:void 0;return{redacted:!i&&!a,callFrame:{functionName:a??(i?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 sanitizeNode(e,t){let{callFrame:n,redacted:r}=sanitizeDiagnosticProfileFrame(e.callFrame,t);return{redacted:r||e.deoptReason!==void 0,node:{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]`}}}}function sanitizeCpuProfileResult(e,t,{durationMs:n,startBlockedMs:r}){assertProfile(e.samples!==void 0&&e.timeDeltas!==void 0);let i=0,a=e.nodes.map(e=>{let n=sanitizeNode(e,t);return i+=Number(n.redacted),n.node});return{requestedDurationMs:5e3,actualDurationMs:n,startBlockedMs:r,samplingIntervalMicros:1e4,sampleLossCount:null,redactedNodeCount:i,profile:{nodes:a,startTime:e.startTime,endTime:e.endTime,samples:e.samples,timeDeltas:e.timeDeltas}}}function sanitizeDiagnosticCpuProfile(e,t,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=sanitizeCpuProfileResult(e,t,n),{nodes:a}=r.profile;if(i(r,1048576).complete)return r;let o=new Map(a.map(e=>[e.id,e])),s=/* @__PURE__ */ new Map;for(let e of a)for(let t of e.children??[])s.set(t,e.id);let c=/* @__PURE__ */ new Map;for(let t of e.samples)c.set(t,(c.get(t)??0)+1);let l=/* @__PURE__ */ new Map;for(let[e,t]of c){let n=[],r=o.get(e);for(;r&&n.length<8;)n.push(r.callFrame),r=o.get(s.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=o.get(s.get(r.id));r&&(n.push(r.callFrame),i=e)}let a=JSON.stringify({stack:n,elidedFrameCount:i}),c=l.get(a);c?c.sampleCount+=t:l.set(a,{stack:n,elidedFrameCount:i,sampleCount:t})}let u=[],d={...r,profile:void 0,truncated:!0,originalNodeCount:a.length,sampleCount:e.samples.length,omittedSampleCount:e.samples.length,summary:u},f=Buffer.byteLength(JSON.stringify(d));for(let e of[...l.values()].toSorted((e,t)=>t.sampleCount-e.sampleCount)){let t=Buffer.byteLength(JSON.stringify(e))+Number(d.summary.length>0);if(d.summary.length===128||f+t>1048576)break;d.summary.push(e),d.omittedSampleCount-=e.sampleCount,f+=t}return d}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,r){let a=e.samples,o=/* @__PURE__ */ new Map,s=[{source:e.head}],c=0,l=0;for(let{source:e,parent:n}of s){++l%1024==0&&await p();let{callFrame:r,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);c+=Number(i);let a={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]},u={node:a,parent:n,totalBytes:a.selfSize,count:0,frameId:0};o.set(a.id,u),n?.node.children.push(a);for(let t of e.children)s.push({source:t,parent:u}),++l%1024==0&&await p()}s.length=0;let u=[],d=0,f=0;for(let e of a){++l%1024==0&&await p();let t=o.get(e.nodeId);t?(t.count++,u.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})):(d++,f+=e.size)}let m=[...o.values()];o.clear();for(let e=m.length-1;e>=0;e--){++l%1024==0&&await p();let t=m[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let h={...n,redactedNodeCount:c,unattributedSampleCount:d,unattributedSampleBytes:f},g={...h,truncated:d>0,profile:{head:m[0].node,samples:u}};if(i(g,1048576).complete)return g;let _=await r?.(g.profile),v=/* @__PURE__ */ new Map,y=/* @__PURE__ */ new Map,b=[],x=[],S=[];for(let e of m){++l%1024==0&&await p();let t=JSON.stringify(e.node.callFrame),n=v.get(t);n===void 0&&(n=v.size,v.set(t,n)),e.frameId=n;let{totalBytes:r,count:i}=e;if(r===0)continue;let a=e.node.selfSize;e.app=e.node.callFrame.url.startsWith(`openclaw:`)?e:e.parent?.app,e.owner=e.parent?.owner??e.app;let o=e.parent;for(let t=1;o&&t<=32;t++,o=o.parent){if(o.frameId!==n)continue;let r=e.parent,i=o.parent,a=1;for(;a<t&&r&&i&&r.frameId===i.frameId;)r=r.parent,i=i.parent,a++;if(a===t){let n=o.cycle;e.cycle={width:t,count:n?.width===t?n.count+1:2,next:n?.width===t?n.next:i};break}}x.length=S.length=b.length=0,x.push(e),S.push(1),b.push(n);let s=e.parent;for(;s&&x.length<32;){let e=s.cycle,t=e&&e.width<=32-x.length?e.width:1,n=t===e?.width?e.count:1,r=n>1?e.next:s.parent;for(let e=0;e<t;e++){let r=s,i=e===t-1&&n>1;x.push(r),S.push(i?n:1),b.push(i?`${r.frameId}x${n}`:r.frameId),s=r.parent}s=r}if(s){let t=x[29].app,n=t?t===e.owner?[t]:[t,e.owner]:[];x.length=S.length=b.length=29,x.push(void 0,...n),S.push(1,1,1),b.push(`...`,...n.map(e=>e.frameId))}let c=b.join(`,`),u=y.get(c);if(u)u.selfBytes+=a,u.totalBytes+=r,u.count+=i;else{let t=[e.node.callFrame];for(let e=1;e<x.length;e++){let n=x[e]?.node.callFrame;t.push(n?S[e]>1?{...n,functionName:`${n.functionName} ×${S[e]}`}:n:{functionName:`[...]`,url:``,scriptId:`0`,lineNumber:-1,columnNumber:-1})}y.set(c,{stack:t,selfBytes:a,totalBytes:r,count:i})}}v.clear(),x.length=0,m.length=0;let C={...h,..._,truncated:!0,summary:[]},w=Buffer.byteLength(JSON.stringify(C));for(let e of await sortAllocationSummaries(y.values())){++l%1024==0&&await p();let t=Buffer.byteLength(JSON.stringify(e))+Number(C.summary.length>0);if(w+t>1048576)break;C.summary.push(e),w+=t}return C}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};