UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 15.1 kB
import{A as e,J as t,t as n}from"./read-only.worker-subsystem-UGB_-INE.mjs";import{t as r}from"./read-only.worker-openclaw-root-bzhbMXdO.mjs";import"./read-only.worker-cli-invocation-fIA_-Tg7.mjs";import{randomUUID as i}from"node:crypto";import a from"node:fs/promises";import o from"node:path";import{fileURLToPath as s}from"node:url";import*as c from"node:v8";import{getEnvironmentData as l,isMainThread as u,setEnvironmentData as d}from"node:worker_threads";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}}const h=/["\\\u0000-\u001f\ud800-\udfff]/gu;function jsonStringByteLengthUpToLimit(e,t){if(e.length+2>t)return t+1;let n=Buffer.byteLength(e,`utf8`)+2;if(n>t)return t+1;for(let t of e.match(h)??[]){let e=t.charCodeAt(0);n+=e>=55296?3:e<32&&!`\b \f\r`.includes(t)?5:1}return n}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=l(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return d(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 o.sep===`/`?e:e.replaceAll(o.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=s(e)}catch{return}if(!o.isAbsolute(n))return;let r=t?codePath(o.relative(t,n)):``,i=(t&&!r.startsWith(`..`)?`/${r}`:codePath(o.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,a,o=!1,s,l,d,f=0,m=0,h=null,assertActive=()=>{if(e.signal?.aborted||!e.hasAuthority())throw new ProfileFailure(`cancelled`)};try{assertActive();let a=await import(`node:inspector/promises`).catch(()=>{throw new ProfileFailure(`unsupported`)}),o=!u&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(o())throw new ProfileFailure(`tracing-active`)};if(h=await r({moduleUrl:import.meta.url}),assertActive(),a.url()||hasProfilerConflict())throw new ProfileFailure(`conflict`);assertTracingInactive(),t=e.create(a),await t.setup?.(),assertActive(),assertTracingInactive(),l={...process.memoryUsage(),heapSpaces:c.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:s}=v),f=performance.now()-g,d={...process.memoryUsage(),heapSpaces:c.getHeapSpaceStatistics()}}catch(t){a=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{o=!0}try{await t.close()}catch{o=!0}}}if(a||o)return _=!1,unavailable(a??`cleanup-failed`,o);try{assertActive();let t=await e.sanitize(s,h,{durationMs:f,startBlockedMs:m,before:l,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:i}=r.profile;if(boundedJsonUtf8Bytes(r,1048576).complete)return r;let a=new Map(i.map(e=>[e.id,e])),o=/* @__PURE__ */ new Map;for(let e of i)for(let t of e.children??[])o.set(t,e.id);let s=/* @__PURE__ */ new Map;for(let t of e.samples)s.set(t,(s.get(t)??0)+1);let c=/* @__PURE__ */ new Map;for(let[e,t]of s){let n=[],r=a.get(e);for(;r&&n.length<8;)n.push(r.callFrame),r=a.get(o.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=a.get(o.get(r.id));r&&(n.push(r.callFrame),i=e)}let s=JSON.stringify({stack:n,elidedFrameCount:i}),l=c.get(s);l?l.sampleCount+=t:c.set(s,{stack:n,elidedFrameCount:i,sampleCount:t})}let l=[],u={...r,profile:void 0,truncated:!0,originalNodeCount:i.length,sampleCount:e.samples.length,omittedSampleCount:e.samples.length,summary:l},d=Buffer.byteLength(JSON.stringify(u));for(let e of[...c.values()].toSorted((e,t)=>t.sampleCount-e.sampleCount)){let t=Buffer.byteLength(JSON.stringify(e))+Number(u.summary.length>0);if(u.summary.length===128||d+t>1048576)break;u.summary.push(e),u.omittedSampleCount-=e.sampleCount,d+=t}return u}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,r){let i=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 f();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 f()}o.length=0;let l=[],u=0,d=0;for(let e of i){++c%1024==0&&await f();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 p=[...a.values()];a.clear();for(let e=p.length-1;e>=0;e--){++c%1024==0&&await f();let t=p[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let m={...n,redactedNodeCount:s,unattributedSampleCount:u,unattributedSampleBytes:d},h={...m,truncated:u>0,profile:{head:p[0].node,samples:l}};if(boundedJsonUtf8Bytes(h,1048576).complete)return h;let g=await r?.(h.profile),_=/* @__PURE__ */ new Map,v=/* @__PURE__ */ new Map,y=[],b=[],x=[];for(let e of p){++c%1024==0&&await f();let t=JSON.stringify(e.node.callFrame),n=_.get(t);n===void 0&&(n=_.size,_.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}}b.length=x.length=y.length=0,b.push(e),x.push(1),y.push(n);let s=e.parent;for(;s&&b.length<32;){let e=s.cycle,t=e&&e.width<=32-b.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;b.push(r),x.push(i?n:1),y.push(i?`${r.frameId}x${n}`:r.frameId),s=r.parent}s=r}if(s){let t=b[29].app,n=t?t===e.owner?[t]:[t,e.owner]:[];b.length=x.length=y.length=29,b.push(void 0,...n),x.push(1,1,1),y.push(`...`,...n.map(e=>e.frameId))}let l=y.join(`,`),u=v.get(l);if(u)u.selfBytes+=a,u.totalBytes+=r,u.count+=i;else{let t=[e.node.callFrame];for(let e=1;e<b.length;e++){let n=b[e]?.node.callFrame;t.push(n?x[e]>1?{...n,functionName:`${n.functionName} ×${x[e]}`}:n:{functionName:`[...]`,url:``,scriptId:`0`,lineNumber:-1,columnNumber:-1})}v.set(l,{stack:t,selfBytes:a,totalBytes:r,count:i})}}_.clear(),b.length=0,p.length=0;let S={...m,...g,truncated:!0,summary:[]},C=Buffer.byteLength(JSON.stringify(S));for(let e of await sortAllocationSummaries(v.values())){++c%1024==0&&await f();let t=Buffer.byteLength(JSON.stringify(e))+Number(S.summary.length>0);if(C+t>1048576)break;S.summary.push(e),C+=t}return S}const v=5e3,y=262144,b=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let x=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: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(t){let n=x.then(async()=>{let n=o.join(e(),`diagnostics`);await a.mkdir(n,{recursive:!0,mode:448});let r=(await a.readdir(n)).filter(e=>b.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-20+2)))await a.unlink(o.join(n,e));let s=`code-mode-gc-${Date.now()}-${i()}`,c=[];for(let[e,r]of[[`heap`,t.heap],[`cpu`,t.cpu]]){let t=`${s}.${e}profile.json`;await m({filePath:o.join(n,t),content:r,mode:384,dirMode:448}),c.push(t)}return c});return x=n.catch(()=>{}),n}export{captureWorkerGcProfiles,reportWorkerGcStorm};