UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 28.4 kB
import{Cn as e,t,zt as n}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import"./openclaw-state-read-cli-invocation-OtTkpH1g.mjs";import{t as r}from"./openclaw-state-read-node-runtime-env-BdqTfovi.mjs";import{A as i,G as a,Ht as o,I as s,Jt as c,K as l,M as u,Mt as d,O as f,h as p,j as m,k as h,pn as g}from"./openclaw-state-read-src-RL5xtYG2.mjs";import{B as _,I as v,K as y,L as b,M as x,R as S,z as C}from"./openclaw-state-read-sidecar-lock-registration-XTuJQFHg.mjs";import{a as w,t as T}from"./openclaw-state-read-sidecar-lock-DBl8LBF5.mjs";import{t as E}from"./openclaw-state-read-lock-config-CQM_E5H4.mjs";import{t as D}from"./openclaw-state-read-openclaw-root-CbFTRFFl.mjs";import*as O from"node:v8";import k from"node:fs";import A from"node:path";import{getEnvironmentData as j,isMainThread as M,setEnvironmentData as N}from"node:worker_threads";import{fileURLToPath as P}from"node:url";import F from"node:fs/promises";import{randomUUID as I}from"node:crypto";import{setImmediate as L,setTimeout as R}from"node:timers/promises";function*prepareDirectoryMode(e,t){if(t.mode!==`preserve`){t.mutation?.assert(),yield*e.mkdir(t.dirPath,t.mode),yield*S(e,t);return}let inspect=function*(n){let r=h(e,()=>e.lstatExact(t.dirPath),n,!1,e=>{if(e.isSymbolicLink()||!e.isDirectory())throw new g(`not-file`,`Atomic replace parent must be a real directory: ${t.dirPath}`)});return e.asynchronous?yield r:r},n,r=!1;try{n=yield*inspect()}catch(i){if(!v(i,`ENOENT`))throw i;if(!e.asynchronous&&!e.fchmodSync&&process.platform!==`win32`)throw TypeError(`fileSystem.fchmodSync is required to finalize a created directory with dirMode: preserve`);let a=A.dirname(t.dirPath);if(a===t.dirPath)throw i;yield*prepareDirectoryMode(e,{...t,dirPath:a}),t.mutation?.assert();try{yield*e.mkdirExclusive(t.dirPath,448),r=!0}catch(e){if(!v(e,`EEXIST`))throw e}n=yield*inspect()}if(yield*S(e,{...t,mode:r?448:`preserve`,expectedIdentity:n,ignoreChmodError:!r&&t.ignoreChmodError}),r&&process.platform!==`win32`&&((yield*inspect(n)).mode&4095n)!=448n)throw new g(`path-mismatch`,`created directory mode could not be finalized`)}const z=p();function assertSourcePreview(e,t){if(e.isSymbolicLink())throw new g(`symlink`,`Refusing copy fallback from non-file source: ${t}`);if(!e.isFile())throw new g(`not-file`,`Refusing copy fallback from non-file source: ${t}`);if(e.nlink!==1)throw new g(`hardlink`,`Hardlinked copy fallback source not allowed: ${t}`)}function assertOpenedSource(e,t,n){if(!e.isFile()||t.isSymbolicLink())throw new g(`path-mismatch`,`Copy fallback source changed while opening: ${n}`);if(e.nlink!==1n)throw new g(`hardlink`,`Hardlinked copy fallback source not allowed: ${n}`)}function*readOwnedCopySource(e,t){assertSourcePreview(yield*e.lstat(t.src),t.src);let n=yield*openSource(e,t.src);try{let r=h(e,()=>n.statExact(),t.expectedIdentity),i=e.asynchronous?yield r:r,a=h(e,()=>e.lstatExact(t.src),i);return assertOpenedSource(i,e.asynchronous?yield a:a,t.src),{replacement:yield*n.readFile(e.asynchronous?void 0:Number(i.size)),mode:Number(i.mode)}}finally{try{let t=n.close();e.asynchronous&&(yield t)}catch{}}}function*openSource(e,t){try{return yield*e.open(t,z)}catch(e){throw v(e,`ELOOP`)?new g(`symlink`,`Refusing copy fallback from non-file source: ${t}`,{cause:e}):e}}function*writeAtomicDestination(e,t,n,r=!1){n&&(yield*n.beforeWrite(r)),yield*e.truncate(0),n?.writing();let i=0;for(;i<t.length;){n&&(yield*n.beforeWrite(r));let a=e.write(t,i,t.length-i,i);if(e.io.asynchronous){let e=yield a;if(e.bytesWritten===0)throw Error(`Copy fallback write made no progress`);a=e.bytesWritten}i+=a}n&&(yield*n.beforeWrite(r)),yield*e.truncate(t.length)}var AtomicMutation=class{active;#e;#t;#n;#r=!1;constructor(e){this.#e=e.assertBeforeMutation,this.#t=e.onDestinationState,this.active=!!(this.#e||this.#t)}rethrowRefusal(){if(this.#n)throw this.#n.error}refuse(e){throw this.#n??={error:e},this.#n.error}#i(e,t){this.rethrowRefusal();try{let n=e();y(n,t)}catch(e){this.refuse(e)}}assert(){this.#i(()=>this.#e?.(),`assertBeforeMutation`)}destination(e,t,n){if(e===`writing`){if(this.#r)return;this.#r=!0}this.#i(()=>this.#t?.(Object.freeze({state:e,path:t,dev:n.dev,ino:n.ino})),`onDestinationState`)}removed(e){this.#i(()=>this.#t?.(Object.freeze({state:`removed`,path:e})),`onDestinationState`)}};function regular(e,t,n){if(e.isSymbolicLink()||!e.isFile())throw new g(`path-mismatch`,`Atomic replace destination changed: ${t}`);if(n&&e.nlink!==1n)throw new g(`hardlink`,`Hardlinked atomic replace destination not allowed: ${t}`);return e}var AtomicDestination=class{io;file;pathname;mutation;rejectHardlinks;identity;#e=!1;#t=!1;constructor(e,t,n,r,i,a){this.io=e,this.file=t,this.pathname=n,this.mutation=r,this.rejectHardlinks=i,this.identity=a}*verify(e=!1){let t=!1,n=e&&this.#t,r=this;function readFailure(e){throw t=v(e,`EIO`),e}function read(e){try{let t=e?r.io.lstatExact(r.pathname,!1):r.file.statExact();return r.io.asynchronous?Promise.resolve(t).catch(readFailure):t}catch(e){return readFailure(e)}}let admit=e=>regular(e,r.pathname,r.rejectHardlinks);try{let e=h(this.io,()=>read(!1),this.identity,!1,admit);if(this.io.asynchronous&&(yield e),!n){let e=h(this.io,()=>read(!0),this.identity,!1,admit);this.io.asynchronous&&(yield e)}}catch(e){if(!n&&this.#e&&t)throw this.#t=!0,e;this.mutation.refuse(e)}}*beforeWrite(e){this.mutation.assert(),yield*this.verify(e),this.io.asynchronous&&this.mutation.assert()}writing(){this.#e=!0,this.mutation.destination(`writing`,this.pathname,this.identity)}published(){this.mutation.destination(`published`,this.pathname,this.identity)}};function*captureAtomicDestination(e,t,n,r,i){let a=h(e,()=>t.statExact()),o=e.asynchronous?yield a:a;return regular(o,n,i),new AtomicDestination(e,t,n,r,i,o)}const B=process.platform!==`win32`&&`O_NOFOLLOW`in k.constants?k.constants.O_NOFOLLOW:0,V=p(),H=k.constants.O_RDWR|B,U=k.constants.O_WRONLY|k.constants.O_CREAT|k.constants.O_EXCL|B;function admitDestinationKind(e,t,n,r){if(r===`hardlinks`){if(e.isSymbolicLink()||!e.isFile())throw new g(`path-mismatch`,`Atomic replace destination changed while opening: ${n}`)}else if(e.isSymbolicLink())throw new g(`symlink`,`Refusing copy fallback through symlink destination: ${n}`);else if(!e.isFile()||!t.isFile())throw new g(`not-file`,`Copy fallback destination must be a regular file: ${n}`);return e}function*openPinnedDestination(e,t,n,r,i){let a;try{a=yield*e.lstat(t)}catch(e){if(v(e,`ENOENT`))return null;throw e}if(e.asynchronous&&!a||n===`hardlinks`&&(a.isSymbolicLink()||!a.isFile()))return null;if(n===`restore`&&a.isSymbolicLink())throw new g(`symlink`,`Refusing copy fallback through symlink destination: ${t}`);i?.assert();let o=yield*e.open(t,n===`restore`?H:V);try{let i=e.asyncFs===F,a=h(e,()=>o.statExact(),void 0,i),s=e.asynchronous&&!i?yield a:a,c=h(e,()=>e.lstatExact(t),s,i,e=>admitDestinationKind(e,s,t,n));if(e.asynchronous&&!i&&(yield c),(n===`hardlinks`||r===`reject`)&&s.nlink>1n)throw new g(`hardlink`,`Hardlinked ${n===`hardlinks`?`atomic replace`:`copy fallback`} destination not allowed: ${t}`);return o}catch(t){try{let t=o.close();e.asynchronous&&(yield t)}catch{}throw t}}function*assertDestinationHardlinkPolicy(e,t,n){if(n!==`reject`)return;let r=yield*openPinnedDestination(e,t,`hardlinks`);if(r)try{let t=r.close();e.asynchronous&&(yield t)}catch(t){if(!e.asynchronous)throw t}}function*readRestoreSnapshot(e,t,n,r){let o=0;function*read(n,r){let i=t.read(n,0,r,o),a=e.asynchronous?(yield i).bytesRead:i;return o+=a,a}let s={initialSize:Number.isSafeInteger(r.size)&&r.size>=0?r.size:void 0,createLimitError:()=>new g(`too-large`,`Atomic replace restore snapshot exceeds maxRestoreBytes (${n})`)};return e.asynchronous?yield*u(a(n,(e,t)=>i(read(e,t)),s)):l(n,(e,t)=>m(read(e,t)),s)}function restoreFailure(e,t,n){let r=e instanceof Error?e:Error(String(e)),i={cleanup:t},a=t===`restore-failed`?AggregateError([r,n],`copy fallback and original restoration both failed`):r;return new g(`helper-failed`,t===`restored`?`Atomic copy fallback failed; original destination restored: ${r.message}`:`Atomic copy fallback failed and original restoration failed: ${r.message}`,{cause:a,details:i})}function*replacePinnedWithRestore(e,t,n,r,i,a,o){let s=yield*t.stat(),c=s.mode,l=yield*readRestoreSnapshot(e,t,r,s);try{yield*writeAtomicDestination(t,n,a),a&&(yield*a.verify());let r=t.chmod(i);e.asynchronous&&(yield r),yield*t.sync()}catch(n){o.rethrowRefusal();try{yield*writeAtomicDestination(t,l,a,!0),a&&(yield*a.verify(!0));let n=t.chmod(c);e.asynchronous&&(yield n),yield*t.sync()}catch(e){throw o.rethrowRefusal(),restoreFailure(n,`restore-failed`,e)}throw restoreFailure(n,`restored`)}}function*copyFallbackReplace(e,t){let n=t.mutation??new AtomicMutation({}),r=yield*readOwnedCopySource(e,{src:t.src,expectedIdentity:t.expectedSourceIdentity}),{replacement:i}=r,a=null,o=!1,s=!1,c;try{if(t.restore===`restore-original`&&(a=yield*openPinnedDestination(e,t.dest,`restore`,t.destinationHardlinks,n),a&&(n.active&&(c=yield*captureAtomicDestination(e,a,t.dest,n,t.destinationHardlinks===`reject`)),yield*replacePinnedWithRestore(e,a,i,t.maxRestoreBytes,r.mode,c,n))),!a){let s=null;try{s=yield*e.lstat(t.dest)}catch(e){if(!v(e,`ENOENT`))throw e}if(s?.isSymbolicLink())throw new g(`symlink`,`Refusing copy fallback through symlink destination: ${t.dest}`);s&&(yield*assertDestinationHardlinkPolicy(e,t.dest,t.destinationHardlinks),n.assert(),yield*e.remove(t.dest),n.removed(t.dest)),n.assert(),a=yield*e.open(t.dest,U,r.mode&511),n.active&&(c=yield*captureAtomicDestination(e,a,t.dest,n,t.destinationHardlinks===`reject`),c.writing()),c||!e.asynchronous?(yield*writeAtomicDestination(a,i,c),c&&(yield*c.verify())):yield a.writeFile(i);let l=a.chmod(r.mode);e.asynchronous&&(yield l),t.sync&&(yield*a.sync()),o=!t.sync}c&&(yield*c.verify()),c?.published(),s=!0}finally{if(a)try{let t=a.close();e.asynchronous&&(yield t)}catch(e){if(o&&s)throw e}}}function inheritedRegularFileMode(e){if(e.isSymbolicLink())throw new g(`symlink`,`atomic replace destination must not be a symbolic link`);if(!e.isFile())throw new g(`not-file`,`atomic replace destination must be a regular file`);return e.mode&511}function resolveFileLockManagerKey(e,t){return t??`fs-safe.file-lock:${e}`}function withLockDefaults(e){let{managerKey:t,lockPath:n}=e,r={};for(let t of Reflect.ownKeys(e))t!==`managerKey`&&t!==`lockPath`&&Object.getOwnPropertyDescriptor(e,t)?.enumerable&&Object.defineProperty(r,t,{value:Reflect.get(e,t),enumerable:!0,writable:!0,configurable:!0});let i=E();return{...r,retry:r.retry??i.retry,staleMs:r.staleMs??i.staleMs??3e4,staleRecovery:r.staleRecovery??i.staleRecovery,timeoutMs:r.timeoutMs??i.timeoutMs,...n===void 0?{}:{lockPath:n}}}async function withFileLock(e,t,n){return await createFileLockManager(resolveFileLockManagerKey(e,t.managerKey)).withLock(e,t,n)}function createFileLockManager(e){let t=T(e);return{acquire:async(e,n)=>await t.acquire({...withLockDefaults(n),targetPath:e}),withLock:async(e,n,r)=>await t.withLock({...withLockDefaults(n),targetPath:e},r),drain:t.drain,reset:t.reset,heldEntries:t.heldEntries}}function validateRenameIdentity(e){if(e!==void 0&&e!==`strict`&&e!==`verify-content-with-lock`)throw RangeError(`renameIdentity must be strict or verify-content-with-lock`)}function atomicExpectedContentHash(e,t){if(e===`verify-content-with-lock`)return d(typeof t==`string`?t:Buffer.from(t))}function lockOptions(e){let t=A.resolve(e);return{managerKey:`fs-safe.atomic:${t}`,lockPath:A.join(A.dirname(t),`.fs-safe-atomic-${d(t)}.lock`),staleMs:3e4,timeoutMs:5e3,payload:()=>({pid:process.pid,createdAt:(/* @__PURE__ */ new Date()).toISOString()}),retry:{retries:5,minTimeout:100,maxTimeout:2e3,factor:2}}}async function withAtomicRenameIdentityLock(e,t){return await withFileLock(e,lockOptions(e),t)}function*renameWithRetry(e,t,n,r,i){let a=r.renameMaxRetries??0,o=r.renameRetryBaseDelayMs??50,s=r.copyFallbackOnPermissionError===!0,c=r.copyFallbackRestore??`none`,l=r.maxRestoreBytes,u=r.destinationHardlinks,d=t.identity,f=r.syncTempFile===!0;for(let r=0;r<=a;r++){r>0&&(yield*t.assertCurrent());try{return i.assert(),yield*e.rename(t.pathname,n),{method:`rename`}}catch(p){i.rethrowRefusal();let m=b(p);if(m===`EBUSY`&&r<a){yield*e.delay(o*2**r);continue}if(s&&(m===`EPERM`||m===`EEXIST`))return yield*copyFallbackReplace(e,{src:t.pathname,dest:n,destinationHardlinks:u,restore:c,maxRestoreBytes:l,expectedSourceIdentity:d,sync:f,mutation:i}),{method:`copy-fallback`};throw p}}throw Error(`Atomic rename retry loop exhausted.`)}function validateReplaceFilePath(e){if(!e||e.includes(`\0`))throw Error(`Atomic replace file path must be non-empty.`);return c(e,`atomic replace path uses a Windows filesystem namespace alias`)}function validateRestoreOptions(e){if(e.copyFallbackRestore===`restore-original`){if(e.maxRestoreBytes===void 0)throw RangeError(`maxRestoreBytes is required when copyFallbackRestore is restore-original`);if(!Number.isSafeInteger(e.maxRestoreBytes)||e.maxRestoreBytes<0)throw RangeError(`maxRestoreBytes must be a non-negative safe integer`)}}function buildReplaceTempPath(e,t){let n=A.dirname(e),r=o(t??`.fs-safe-replace`,{label:`atomic replace temp prefix`});return A.join(n,`${r}.${process.pid}.${I()}.tmp`)}function*resolveMode(e,t,n){let r=t.mode??384;if(!t.preserveExistingMode)return r;let i;try{i=yield*e.lstat(n)}catch(e){if(!v(e,`ENOENT`))throw e}return i?inheritedRegularFileMode(i):r}async function replaceFileAtomic(e){return await replaceFileAtomicWithDirectorySync(e)}async function replaceFileAtomicWithDirectorySync(e,t){let n=new AtomicMutation(e),r=validateReplaceFilePath(e.filePath);validateRestoreOptions(e);let a=e.renameIdentity;return validateRenameIdentity(a),await w(A.resolve(r),async()=>{if(a!==`verify-content-with-lock`)return await replaceAsync(e,r,a,n,t);let o=e.fileSystem?.promises??F,c=A.dirname(r);n.assert();let l=e.dirMode??448;return l===`preserve`?await i(prepareDirectoryMode(f.async(o),{dirPath:c,mode:`preserve`,mutation:n})):await o.mkdir(o===F?s(c):c,{recursive:!0,mode:l}),n.assert(),await withAtomicRenameIdentityLock(r,()=>replaceAsync(e,r,a,n,t))})}function replaceAsync(e,t,n,r,a){return i(replace(f.async(e.fileSystem?.promises??F),e,t,n,r,a))}function*replace(e,t,n,r,i,a){let o=A.dirname(n),s=t.dirMode??448,c=yield*resolveMode(e,t,n),l=atomicExpectedContentHash(r,t.content);if(!e.asynchronous){let n=t;if(e.fchmodSync=n.fileSystem?.fchmodSync??(n.fileSystem===void 0?k.fchmodSync:void 0),!e.fchmodSync&&(t.mode!==void 0||t.preserveExistingMode===!0||process.platform!==`win32`&&typeof t.dirMode==`number`))throw TypeError(`fileSystem.fchmodSync is required when mode, dirMode, or preserveExistingMode is specified`)}let d=buildReplaceTempPath(n,t.tempPrefix),f=new x(d,e),p;try{if(yield*prepareDirectoryMode(e,{dirPath:o,mode:s,mutation:i}),f.start(),f.adopt(yield*_(e,{tempPath:d,content:t.content,mode:c,sync:t.syncTempFile===!0,onIdentity:f.onIdentity,mutation:i})),yield*f.assertCurrent(),t.beforeRename){let r=t.beforeRename({filePath:n,tempPath:d});e.asynchronous?yield*u(r):y(r,`beforeRename`),yield*f.assertCurrent()}t.destinationHardlinks===`reject`&&(yield*assertDestinationHardlinkPolicy(e,n,t.destinationHardlinks),yield*f.assertCurrent());let r=yield*renameWithRetry(e,f,n,t,i);r.method===`rename`?(f.markRenamed(),yield*f.assertPublished(n,l,e=>i.destination(`published`,n,e))):yield*f.assertCurrent();let p=!1;return a?(yield*u(a(o)),p=!0):t.syncParentDir&&(yield*C(e,o),p=!0),r.method===`rename`&&p&&(yield*f.assertPublished(n,l)),r}catch(e){throw p={error:e},e}finally{yield*f.finish({originalFailure:p,throwOnCleanupError:t.throwOnCleanupError===!0})}}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=j(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return N(e,n),new Int32Array(n)});const W=/* @__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=r(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=P(e)}catch{return}if(!A.isAbsolute(n))return;let r=t?A.relative(t,n).split(A.sep).join(`/`):``,i=(t&&!r.startsWith(`..`)?`/${r}`:A.normalize(n).split(A.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===``&&W.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,r=!1,i,a=!1,o,s,c,l=0,u=0,d=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=!M&&e.workerTracingInactive?()=>void 0:(await import(`node:trace_events`).catch(()=>{throw new ProfileFailure(`unsupported`)})).getEnabledCategories,assertTracingInactive=()=>{if(a())throw new ProfileFailure(`tracing-active`)};if(d=await D({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:O.getHeapSpaceStatistics()};let f=performance.now();n=!0;let p=t.start();u=performance.now()-f,await p,e.durationMs>0&&await R(e.durationMs,void 0,{signal:e.signal}),assertActive(),r=!0;let m=await t.stop();if(!m)throw new ProfileFailure(`capture-failed`);({profile:o}=m),l=performance.now()-f,c={...process.memoryUsage(),heapSpaces:O.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 G=!1,unavailable(i??`cleanup-failed`,a);try{assertActive();let t=await e.sanitize(o,d,{durationMs:l,startBlockedMs:u,before:s,after:c});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 L());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 L();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 L();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 L()}a.length=0;let c=[],l=0,u=0;for(let e of r){++s%1024==0&&await L();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 L();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 L();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:[]},v=Buffer.byteLength(JSON.stringify(_));for(let e of await sortAllocationSummaries(h.values())){++s%1024==0&&await L();let t=Buffer.byteLength(JSON.stringify(e))+Number(_.summary.length>0);if(v+t>1048576)break;_.summary.push(e),v+=t}return _}const K=5e3,q=262144,J=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let Y=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:K,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:q,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:K,effectiveDurationMs:K,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:q,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=Y.then(async()=>{let t=A.join(n(),`diagnostics`);await F.mkdir(t,{recursive:!0,mode:448});let r=(await F.readdir(t)).filter(e=>J.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-20+2)))await F.unlink(A.join(t,e));let i=`code-mode-gc-${Date.now()}-${I()}`,a=[];for(let[n,r]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${i}.${n}profile.json`;await replaceFileAtomic({filePath:A.join(t,e),content:r,mode:384,dirMode:448}),a.push(e)}return a});return Y=t.catch(()=>{}),t}export{captureWorkerGcProfiles,reportWorkerGcStorm};