openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 13.6 kB
JavaScript
import{G as e,Kt as t,t as n}from"./disk-budget.worker-subsystem-9qP7ka6r.mjs";import"./disk-budget.worker-cli-invocation-OtTkpH1g.mjs";import{t as r}from"./disk-budget.worker-openclaw-root-DFzofuF0.mjs";import{getEnvironmentData as i,isMainThread as a,setEnvironmentData as o}from"node:worker_threads";import{randomUUID as s}from"node:crypto";import c from"node:fs/promises";import l from"node:path";import{fileURLToPath as u}from"node:url";import*as d from"node:v8";import{setImmediate as f,setTimeout as p}from"node:timers/promises";import{replaceFileAtomic as m}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)}function jsonUtf8BytesOrInfinity(e){try{let t=JSON.stringify(e);return typeof t==`string`?Buffer.byteLength(t,`utf8`):1/0}catch{return 1/0}}function jsonStringByteLengthUpToLimit(e,t){return e.length+2>t||e.length*3+2>t&&Buffer.byteLength(e,`utf8`)+2>t?t+1:jsonUtf8BytesOrInfinity(e)}function boundedJsonUtf8Bytes(e,t){let n=0,r,add=e=>{if(n+=e,n>t)throw Error(`json_byte_limit_exceeded`)},visit=(e,i)=>{if(e===null){add(4);return}switch(typeof e){case`string`:add(jsonStringByteLengthUpToLimit(e,t-n));return;case`number`:add(jsonUtf8BytesOrInfinity(Number.isFinite(e)?e:null));return;case`boolean`:add(e?4:5);return;case`undefined`:case`function`:case`symbol`:i&&add(4);return;case`bigint`:throw Error(`json_byte_length_unsupported`)}let a=e;if((r??=/* @__PURE__ */ new WeakSet).has(a))throw Error(`json_byte_length_circular`);if(typeof a.toJSON==`function`&&!(a instanceof Date))throw Error(`json_byte_length_custom_to_json`);r.add(a);try{if(a instanceof Date){visit(a.toJSON(),i);return}let e=Array.isArray(a);if(add(1),e)for(let e=0;e<a.length;e+=1)e>0&&add(1),visit(a[e],!0);else{let e=!1,r=a;for(let i in r){if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=r[i];a!==void 0&&typeof a!=`function`&&typeof a!=`symbol`&&(e&&add(1),e=!0,add(jsonStringByteLengthUpToLimit(i,t-n)),add(1),visit(a,!1))}}add(1)}finally{r.delete(a)}};try{return visit(e,!1),{bytes:n,complete:!0}}catch{return{bytes:Math.max(n,t+1),complete:!1}}}t(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=i(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return o(e,n),new Int32Array(n)});const h=/* @__PURE__ */ new Set([`(root)`,`(program)`,`(idle)`,`(garbage collector)`,`(GC)`,`(PARSER)`,`(COMPILER)`,`(BYTECODE_COMPILER)`,`(V8 API)`,`(EXTERNAL)`,`(LOGGING)`,`(IDLE_EXTERNAL)`,`(IDLE)`,`(JS)`,`(deopt)`]);let g=!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=u(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===``&&h.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(g)return unavailable(`busy`);g=!0;let t,n=!1,i=!1,o,s=!1,c,l,u,f=0,m=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`)}),s=!a&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(s())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(),l={...process.memoryUsage(),heapSpaces:d.getHeapSpaceStatistics()};let g=performance.now();n=!0;let _=t.start();m=performance.now()-g,await _,e.durationMs>0&&await p(e.durationMs,void 0,{signal:e.signal}),assertActive(),i=!0;let v=await t.stop();if(!v)throw new ProfileFailure(`capture-failed`);({profile:c}=v),f=performance.now()-g,u={...process.memoryUsage(),heapSpaces:d.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{s=!0}try{await t.close()}catch{s=!0}}}if(o||s)return g=!1,unavailable(o??`cleanup-failed`,s);try{assertActive();let t=await e.sanitize(c,h,{durationMs:f,startBlockedMs:m,before:l,after:u});return assertActive(),{status:`complete`,result:t}}catch(e){return unavailable(e instanceof ProfileFailure?e.reason:`invalid-profile`)}finally{g=!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,i=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]`}}}),a={requestedDurationMs:5e3,actualDurationMs:(e.endTime-e.startTime)/1e3,startBlockedMs:n,samplingIntervalMicros:1e4,sampleLossCount:null,redactedNodeCount:r,profile:{nodes:i,startTime:e.startTime,endTime:e.endTime,samples:e.samples,timeDeltas:e.timeDeltas}};if(boundedJsonUtf8Bytes(a,1048576).complete)return a;let o=new Map(i.map(e=>[e.id,e])),s=/* @__PURE__ */ new Map;for(let e of i)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={...a,profile:void 0,truncated:!0,originalNodeCount:i.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 f());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 f();e.push(a)}t=e}return t[0]??[]}async function sanitizeDiagnosticHeapProfile(e,t,n){let r=e.samples,i=/* @__PURE__ */ new Map,a=[{source:e.head}],o=0,s=0;for(let{source:e,parent:n}of a){++s%1024==0&&await f();let{callFrame:r,redacted:c}=sanitizeDiagnosticProfileFrame(e.callFrame,t);o+=Number(c);let l={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]},u={node:l,parent:n,totalBytes:l.selfSize,count:0,frameId:0};i.set(l.id,u),n?.node.children.push(l);for(let t of e.children)a.push({source:t,parent:u}),++s%1024==0&&await f()}a.length=0;let c=[],l=0,u=0;for(let e of r){++s%1024==0&&await f();let t=i.get(e.nodeId);t?(t.count++,c.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})):(l++,u+=e.size)}let d=[...i.values()];i.clear();for(let e=d.length-1;e>=0;e--){++s%1024==0&&await f();let t=d[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let p={...n,redactedNodeCount:o,unattributedSampleCount:l,unattributedSampleBytes:u},m={...p,truncated:l>0,profile:{head:d[0].node,samples:c}};if(boundedJsonUtf8Bytes(m,1048576).complete)return m;let h=/* @__PURE__ */ new Map,g=/* @__PURE__ */ new Map,_=[];for(let e of d){++s%1024==0&&await f();let t=JSON.stringify(e.node.callFrame),n=h.get(t);n===void 0&&(n=h.size,h.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];_.length=0,_.push(n);for(let t=e.parent;t&&o.length<8;t=t.parent)o.push(t.node.callFrame),_.push(t.frameId);let c=_.join(`,`),l=g.get(c);l?(l.selfBytes+=a,l.totalBytes+=r,l.count+=i):g.set(c,{stack:o,selfBytes:a,totalBytes:r,count:i})}h.clear(),d.length=0;let v={...p,truncated:!0,summary:[]},y=Buffer.byteLength(JSON.stringify(v));for(let e of await sortAllocationSummaries(g.values())){++s%1024==0&&await f();let t=Buffer.byteLength(JSON.stringify(e))+Number(v.summary.length>0);if(y+t>1048576)break;v.summary.push(e),y+=t}return v}const _=5e3,v=262144,y=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let b=Promise.resolve();async function reportWorkerGcStorm(e,t,r){let{profiles:i,...a}=e,o={...a,workerThreadId:t,workerSlot:r},s=n(`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:_,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:v,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:_,effectiveDurationMs:_,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:v,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(t){let n=b.then(async()=>{let n=l.join(e(),`diagnostics`);await c.mkdir(n,{recursive:!0,mode:448});let r=(await c.readdir(n)).filter(e=>y.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-20+2)))await c.unlink(l.join(n,e));let i=`code-mode-gc-${Date.now()}-${s()}`,a=[];for(let[e,r]of[[`heap`,t.heap],[`cpu`,t.cpu]]){let t=`${i}.${e}profile.json`;await m({filePath:l.join(n,t),content:r,mode:384,dirMode:448}),a.push(t)}return a});return b=n.catch(()=>{}),n}export{captureWorkerGcProfiles,reportWorkerGcStorm};