UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 23.6 kB
import{P as e,d as t,h as n,t as r,x as i}from"./attachment-processor.worker-subsystem-DWWW8u45.mjs";import"./attachment-processor.worker-src-Bd661ObH.mjs";import"./attachment-processor.worker-cli-invocation-DL76jDxC.mjs";import{a,l as o}from"./attachment-processor.worker.js";import{getEnvironmentData as s,isMainThread as c,setEnvironmentData as l}from"node:worker_threads";import{AsyncLocalStorage as u}from"node:async_hooks";import{randomUUID as d}from"node:crypto";import f from"node:fs";import p,{default as m}from"node:fs/promises";import h from"node:path";import{fileURLToPath as g}from"node:url";import*as _ from"node:v8";import{setImmediate as v,setTimeout as y}from"node:timers/promises";import{replaceFileAtomic as b}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}}}e(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=s(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return l(e,n),new Int32Array(n)});const x=e(Symbol.for(`openclaw.asyncWorkScope`),()=>new u),S=e(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new u),C=e(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}});var w=class AsyncWorkScope{constructor(e){this.failures=e,this.pending=/* @__PURE__ */ new Set,this.controller=new AbortController,this.phase=`open`}get signal(){return this.controller.signal}get hasPendingWork(){return this.pending.size>0}get isClosing(){return this.phase!==`open`}enter(e){let t=x.getStore();if(t===this)return e();let n=S.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return i(x,this,()=>(S.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new C;if(this.pending.size>0)return this.enter(e);let t=a();this.pending.add(t.promise);try{return this.enter(e)}finally{t.resolve(),this.pending.delete(t.promise)}}track(e){if(this.phase===`closed`)return Promise.reject(new C);let t=a();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(o(e),this.failures.add(e))});try{t.resolve(this.enter(e))}catch(e){t.reject(e)}return t.promise}beginClose(e){this.phase===`open`&&(this.phase=`closing`,this.controller.abort(e),o(this.controller.signal.reason))}runWhenIdle(e){return AsyncWorkScope.runWhenAllIdle(()=>[this],()=>this.track(e))}static async runWhenAllIdle(e,t){let n=e();for(;n.some(e=>e.pending.size>0);)await Promise.allSettled(n.flatMap(e=>Array.from(e.pending))),n=e();return t()}async drain(){for(this.beginClose();this.pending.size>0;)await Promise.allSettled(this.pending);this.phase=`closed`}};e(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}});function runOutsideAsyncWorkScope(e){return x.getStore()===void 0?S.getStore()===void 0?e():S.exit(e):i(x,void 0,()=>(S.enterWith(void 0),e()))}function appendPluginInstanceCleanupFailures(e,t,n){for(let r of n.errors)e.some(e=>e.pluginId===t&&e.error===r)||e.push({pluginId:t,hookId:`instance`,error:r})}function createPluginCacheSdk(){return{hosts:/* @__PURE__ */ new Map,contexts:/* @__PURE__ */ new Map,roots:/* @__PURE__ */ new Set,packageNames:/* @__PURE__ */ new Map,packageSearches:/* @__PURE__ */ new Map,argvDirectories:/* @__PURE__ */ new Map,devSourceRoots:/* @__PURE__ */ new Map,runtimeModules:/* @__PURE__ */ new Map,normalizedJitiAliases:/* @__PURE__ */ new Map,aliasFacts:/* @__PURE__ */ new WeakMap,native:{sdkProviders:/* @__PURE__ */ new Map,nextSdkProviderOrder:0,parents:/* @__PURE__ */ new Map,aliases:/* @__PURE__ */ new Map,registeredHosts:/* @__PURE__ */ new Set,hostRoots:/* @__PURE__ */ new Map,nearestPackageRoots:/* @__PURE__ */ new Map,loaderPackageRoots:/* @__PURE__ */ new Map,allowedParentRoots:/* @__PURE__ */ new Map}}}e(Symbol.for(`openclaw.pluginInventoryRetiredError`),()=>class extends Error{constructor(){super(`Plugin inventory has retired; begin a new plugin operation.`),this.name=`PluginInventoryRetiredError`}}),e(Symbol.for(`openclaw.pluginSourceRecoveryUnavailableError`),()=>class extends Error{constructor(e){super(`Captured plugin source is missing; its previous code cannot be recovered.`,{cause:e}),this.name=`PluginSourceRecoveryUnavailableError`}});const T=e(Symbol.for(`openclaw.pluginInstanceDrainTimeoutError`),()=>class extends Error{constructor(e,t,n,r){super(e,n),this.settled=t,this.forcedRetirement=r,this.name=`PluginInstanceDrainTimeoutError`}}),E=e(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),D=e(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),O=e(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap);function releasePluginCacheInstance(e,t){let n=O.get(e);if(t)t.instances.delete(e),n?.delete(t);else{for(let t of n??[])t.instances.delete(e);n?.clear()}n?.size===0&&O.delete(e)}function getPluginCacheRetainers(e){let t=D.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:a()},D.set(e,t)),t}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:!1,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},snapshots:/* @__PURE__ */ new Map,derivedIndexes:/* @__PURE__ */ new WeakMap,preparedManifests:/* @__PURE__ */ new WeakMap,snapshotManifestFacts:/* @__PURE__ */ new WeakMap,discovery:/* @__PURE__ */ new Map,sharedDiscovery:/* @__PURE__ */ new Map,projections:/* @__PURE__ */ new WeakMap,projectionSources:/* @__PURE__ */ new WeakMap,completions:/* @__PURE__ */ new WeakMap,indexFacts:/* @__PURE__ */ new WeakMap,providerPolicyOwners:/* @__PURE__ */ new WeakMap,channelAdapters:/* @__PURE__ */ new WeakMap,bundledChannelCatalogs:/* @__PURE__ */ new Map,bundledProviderPolicySurfaces:/* @__PURE__ */ new WeakMap,staticCatalogStates:/* @__PURE__ */ new WeakMap,modelSuppressionResolvers:/* @__PURE__ */ new WeakMap,mcpAuthDeclarations:/* @__PURE__ */ new WeakMap}}function createPluginCache(e={}){return{async[Symbol.asyncDispose](){await retirePluginCache(this)},kind:e.kind??`operation`,roots:/* @__PURE__ */ new Map,rootAliases:/* @__PURE__ */ new Map,sdk:createPluginCacheSdk(),setupModules:/* @__PURE__ */ new Map,instances:/* @__PURE__ */ new Set,metadata:createPluginMetadataCache(),installRecords:/* @__PURE__ */ new Map,persistedInstalledIndex:/* @__PURE__ */ new Map,preparedBundledDiscoveryModes:/* @__PURE__ */ new Map,dependencyStatus:/* @__PURE__ */ new WeakMap,moduleLoaders:/* @__PURE__ */ new Map,sources:/* @__PURE__ */ new Map,sourceAliases:/* @__PURE__ */ new Map,runtimeRecordRoots:/* @__PURE__ */ new WeakMap}}function getProcessPluginCache(){return E.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return t()?.cacheScope?.cache}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function retirePluginCache(e,t,n){let r=getPluginCacheRetainers(e);if(r.retirement)return r.retirement;let i=a();return r.retirement=i.promise,r.controller.abort(),o(r.controller.signal.reason),runOutsideAsyncWorkScope(async()=>{r.references.size&&await r.settled.promise;let i=new w;try{return await i.track(()=>beginPluginCacheRetirement(e,t,n))}finally{await i.drain()}}).then(i.resolve,i.reject),i.promise}function beginPluginCacheRetirement(e,t,n){if(e.retirement)return e.retirement;let r=a();return e.retirement=r.promise,(async()=>{t?.();let r=e.retireRegistryLoads?.(),i=/* @__PURE__ */ new Set([...e.setupModules.values(),...e.instances]);for(let e of i)e.quiesce();let[a]=await Promise.allSettled([r]),o=await Promise.allSettled([...i].map(async e=>({resource:e,result:await e.dispose(void 0,n)}))),s=e.sourceAdmissions;if(s){let e=o.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof T?[e.settled]:[]):[]);e.length>0?Promise.allSettled(e).then(()=>s.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`)):await s.dispose()}e.setupModules.clear();for(let t of e.instances)releasePluginCacheInstance(t,e);let c=[...a.status===`rejected`?[a.reason]:[],...o.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(c.length)throw AggregateError(c,`Plugin cache resources failed to retire`);let l=a.status===`fulfilled`?a.value:void 0,u=[...l?.failures??[]];for(let e of o){if(e.status!==`fulfilled`)continue;let{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(u,t.pluginId,n)}return{cleanupCount:l?.cleanupCount??0,failures:u}})().then(r.resolve,r.reject),r.promise}function parsePackageName(e){let t=JSON.parse(e);return typeof t.name==`string`?t.name:null}async function readPackageName(e,t){t?.throwIfAborted();let n=getPluginCache().sdk.packageNames,r=h.join(h.resolve(e),`package.json`);if(n.has(r))return n.get(r)??null;try{let e=parsePackageName(await m.readFile(r,{encoding:`utf-8`,signal:t}));return t?.throwIfAborted(),n.set(r,e),e}catch{return t?.throwIfAborted(),n.set(r,null),null}}async function findPackageRoot(e,t){for(let n of iterAncestorDirs(e))if(await readPackageName(n,t)===`openclaw`)return n;return null}function*iterAncestorDirs(e){let t=h.resolve(e);for(let e=0;e<12&&(yield t,h.basename(t)!==`node_modules`);e+=1){let e=h.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,n=h.resolve(e),r=t.get(n);if(r)return[...r];let i=n,a=[];try{let e=f.realpathSync(i);e!==i&&a.push(h.dirname(e))}catch{}a.push(h.dirname(i));let o=i.split(h.sep),s=o.lastIndexOf(`.bin`);if(s>0&&o[s-1]===`node_modules`){let e=h.basename(i),t=o.slice(0,s).join(h.sep);a.push(h.join(t,e))}let c=dedupeCandidates(a);return t.set(n,c),[...c]}function preparePackageRootSearch(e,t){let n=buildCandidates(e),r=n.join(`\0`),i=getPluginCache().sdk.packageSearches,a=i.get(r);return{candidates:n,first:a?.all?a.all[0]??null:a?.first,complete(e){return i.set(r,t?{...i.get(r),first:e}:{first:e}),e}}}async function resolveOpenClawPackageRoot(e){e.signal?.throwIfAborted();let t=preparePackageRootSearch(e,!0);if(t.first!==void 0)return t.first;for(let n of t.candidates){let r=await findPackageRoot(n,e.signal);if(r)return t.complete(r)}return t.complete(null)}function buildCandidates(e){let t=[];if(e.moduleUrl)try{t.push(h.dirname(g(e.moduleUrl)))}catch{}return e.argv1&&t.push(...candidateDirsFromArgv1(e.argv1)),e.cwd&&t.push(e.cwd),dedupeCandidates(t)}function dedupeCandidates(e){return[...new Set(e.map(e=>h.resolve(e)))]}const k=/* @__PURE__ */ new Set([`(root)`,`(program)`,`(idle)`,`(garbage collector)`,`(GC)`,`(PARSER)`,`(COMPILER)`,`(BYTECODE_COMPILER)`,`(V8 API)`,`(EXTERNAL)`,`(LOGGING)`,`(IDLE_EXTERNAL)`,`(IDLE)`,`(JS)`,`(deopt)`]);let A=!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=g(e)}catch{return}if(!h.isAbsolute(n))return;let r=t?h.relative(t,n).split(h.sep).join(`/`):``,i=(t&&!r.startsWith(`..`)?`/${r}`:h.normalize(n).split(h.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===``&&k.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(A)return unavailable(`busy`);A=!0;let t,n=!1,r=!1,i,a=!1,o,s,l,u=0,d=0,f=null,assertActive=()=>{if(e.signal?.aborted||!e.hasAuthority())throw new ProfileFailure(`cancelled`)};try{assertActive();let i=await import(`node:inspector/promises`).catch(()=>{throw new ProfileFailure(`unsupported`)}),a=!c&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(a())throw new ProfileFailure(`tracing-active`)};if(f=await resolveOpenClawPackageRoot({moduleUrl:import.meta.url}),assertActive(),i.url()||hasProfilerConflict())throw new ProfileFailure(`conflict`);assertTracingInactive(),t=e.create(i),await t.setup?.(),assertActive(),assertTracingInactive(),s={...process.memoryUsage(),heapSpaces:_.getHeapSpaceStatistics()};let p=performance.now();n=!0;let m=t.start();d=performance.now()-p,await m,e.durationMs>0&&await y(e.durationMs,void 0,{signal:e.signal}),assertActive(),r=!0;let h=await t.stop();if(!h)throw new ProfileFailure(`capture-failed`);({profile:o}=h),u=performance.now()-p,l={...process.memoryUsage(),heapSpaces:_.getHeapSpaceStatistics()}}catch(t){i=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&&!r)try{await t.stop()}catch{a=!0}try{await t.close()}catch{a=!0}}}if(i||a)return A=!1,unavailable(i??`cleanup-failed`,a);try{assertActive();let t=await e.sanitize(o,f,{durationMs:u,startBlockedMs:d,before:s,after:l});return assertActive(),{status:`complete`,result:t}}catch(e){return unavailable(e instanceof ProfileFailure?e.reason:`invalid-profile`)}finally{A=!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 v());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 v();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 v();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 v()}a.length=0;let c=[],l=0,u=0;for(let e of r){++s%1024==0&&await v();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 v();let t=d[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let f={...n,redactedNodeCount:o,unattributedSampleCount:l,unattributedSampleBytes:u},p={...f,truncated:l>0,profile:{head:d[0].node,samples:c}};if(boundedJsonUtf8Bytes(p,1048576).complete)return p;let m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=[];for(let e of d){++s%1024==0&&await v();let t=JSON.stringify(e.node.callFrame),n=m.get(t);n===void 0&&(n=m.size,m.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];g.length=0,g.push(n);for(let t=e.parent;t&&o.length<8;t=t.parent)o.push(t.node.callFrame),g.push(t.frameId);let c=g.join(`,`),l=h.get(c);l?(l.selfBytes+=a,l.totalBytes+=r,l.count+=i):h.set(c,{stack:o,selfBytes:a,totalBytes:r,count:i})}m.clear(),d.length=0;let _={...f,truncated:!0,summary:[]},y=Buffer.byteLength(JSON.stringify(_));for(let e of await sortAllocationSummaries(h.values())){++s%1024==0&&await v();let t=Buffer.byteLength(JSON.stringify(e))+Number(_.summary.length>0);if(y+t>1048576)break;_.summary.push(e),y+=t}return _}const j=5e3,M=262144,N=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let P=Promise.resolve();async function reportWorkerGcStorm(e,t,n){let{profiles:i,...a}=e,o={...a,workerThreadId:t,workerSlot:n},s=r(`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:j,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:M,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:j,effectiveDurationMs:j,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:M,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=P.then(async()=>{let t=h.join(n(),`diagnostics`);await p.mkdir(t,{recursive:!0,mode:448});let r=(await p.readdir(t)).filter(e=>N.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-20+2)))await p.unlink(h.join(t,e));let i=`code-mode-gc-${Date.now()}-${d()}`,a=[];for(let[n,r]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${i}.${n}profile.json`;await b({filePath:h.join(t,e),content:r,mode:384,dirMode:448}),a.push(e)}return a});return P=t.catch(()=>{}),t}export{captureWorkerGcProfiles,reportWorkerGcStorm};