UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 30 kB
import"./openclaw-state-read-cli-invocation-fIA_-Tg7.mjs";import{t as e}from"./openclaw-state-read-node-runtime-env-BdqTfovi.mjs";import{v as t}from"./openclaw-state-read-home-dir-BQZX1pD2.mjs";import{a as n}from"./openclaw-state-read-tmp-openclaw-dir-C3Ynn93H.mjs";import{A as r,R as i,a,o,t as s}from"./openclaw-state-read-read-open-flags-CtNL1rJs.mjs";import{T as c,_ as l,b as u,dt as d,ut as f,v as p,x as m,y as h}from"./openclaw-state-read-root-symlink-policy-AldRD6ik.mjs";import{G as g,J as _,K as v,T as y,X as b,Y as x,Z as S,m as C,q as w}from"./openclaw-state-read-fs-safe-CpAHBauR.mjs";import{t as T}from"./openclaw-state-read-lock-config-CQM_E5H4.mjs";import{t as E}from"./openclaw-state-read-subsystem-DSi0tJn8.mjs";import{t as D}from"./openclaw-state-read-openclaw-root-CgRQdXPt.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";const z=s();function assertSourcePreview(e,t){if(e.isSymbolicLink())throw new i(`symlink`,`Refusing copy fallback from non-file source: ${t}`);if(!e.isFile())throw new i(`not-file`,`Refusing copy fallback from non-file source: ${t}`);if(e.nlink!==1)throw new i(`hardlink`,`Hardlinked copy fallback source not allowed: ${t}`)}function assertOpenedSource(e,t,n){if(!e.isFile()||t.isSymbolicLink())throw new i(`path-mismatch`,`Copy fallback source changed while opening: ${n}`);if(e.nlink!==1n)throw new i(`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=p(e,()=>n.statExact(),t.expectedIdentity),i=e.asynchronous?yield r:r,a=p(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 b(e,`ELOOP`)?new i(`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();x(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 i(`path-mismatch`,`Atomic replace destination changed: ${t}`);if(n&&e.nlink!==1n)throw new i(`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=b(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=p(this.io,()=>read(!1),this.identity,!1,admit);if(this.io.asynchronous&&(yield e),!n){let e=p(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=p(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=s(),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 i(`path-mismatch`,`Atomic replace destination changed while opening: ${n}`)}else if(e.isSymbolicLink())throw new i(`symlink`,`Refusing copy fallback through symlink destination: ${n}`);else if(!e.isFile()||!t.isFile())throw new i(`not-file`,`Copy fallback destination must be a regular file: ${n}`);return e}function*openPinnedDestination(e,t,n,r,a){let o;try{o=yield*e.lstat(t)}catch(e){if(b(e,`ENOENT`))return null;throw e}if(e.asynchronous&&!o||n===`hardlinks`&&(o.isSymbolicLink()||!o.isFile()))return null;if(n===`restore`&&o.isSymbolicLink())throw new i(`symlink`,`Refusing copy fallback through symlink destination: ${t}`);a?.assert();let s=yield*e.open(t,n===`restore`?H:V);try{let a=e.asyncFs===F,o=p(e,()=>s.statExact(),void 0,a),c=e.asynchronous&&!a?yield o:o,l=p(e,()=>e.lstatExact(t),c,a,e=>admitDestinationKind(e,c,t,n));if(e.asynchronous&&!a&&(yield l),(n===`hardlinks`||r===`reject`)&&c.nlink>1n)throw new i(`hardlink`,`Hardlinked ${n===`hardlinks`?`atomic replace`:`copy fallback`} destination not allowed: ${t}`);return s}catch(t){try{let t=s.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 s=0;function*read(n,r){let i=t.read(n,0,r,s),a=e.asynchronous?(yield i).bytesRead:i;return s+=a,a}let c={initialSize:Number.isSafeInteger(r.size)&&r.size>=0?r.size:void 0,createLimitError:()=>new i(`too-large`,`Atomic replace restore snapshot exceeds maxRestoreBytes (${n})`)};return e.asynchronous?yield*m(a(n,(e,t)=>h(read(e,t)),c)):o(n,(e,t)=>u(read(e,t)),c)}function restoreFailure(e,t,n){let r=e instanceof Error?e:Error(String(e)),a={cleanup:t},o=t===`restore-failed`?AggregateError([r,n],`copy fallback and original restoration both failed`):r;return new i(`helper-failed`,t===`restored`?`Atomic copy fallback failed; original destination restored: ${r.message}`:`Atomic copy fallback failed and original restoration failed: ${r.message}`,{cause:o,details:a})}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:a}=r,o=null,s=!1,c=!1,l;try{if(t.restore===`restore-original`&&(o=yield*openPinnedDestination(e,t.dest,`restore`,t.destinationHardlinks,n),o&&(n.active&&(l=yield*captureAtomicDestination(e,o,t.dest,n,t.destinationHardlinks===`reject`)),yield*replacePinnedWithRestore(e,o,a,t.maxRestoreBytes,r.mode,l,n))),!o){let c=null;try{c=yield*e.lstat(t.dest)}catch(e){if(!b(e,`ENOENT`))throw e}if(c?.isSymbolicLink())throw new i(`symlink`,`Refusing copy fallback through symlink destination: ${t.dest}`);c&&(yield*assertDestinationHardlinkPolicy(e,t.dest,t.destinationHardlinks),n.assert(),yield*e.remove(t.dest),n.removed(t.dest)),n.assert(),o=yield*e.open(t.dest,U,r.mode&511),n.active&&(l=yield*captureAtomicDestination(e,o,t.dest,n,t.destinationHardlinks===`reject`),l.writing()),l||!e.asynchronous?(yield*writeAtomicDestination(o,a,l),l&&(yield*l.verify())):yield o.writeFile(a);let u=o.chmod(r.mode);e.asynchronous&&(yield u),t.sync&&(yield*o.sync()),s=!t.sync}l&&(yield*l.verify()),l?.published(),c=!0}finally{if(o)try{let t=o.close();e.asynchronous&&(yield t)}catch(e){if(s&&c)throw e}}}function*prepareDirectoryMode(e,t){if(t.mode!==`preserve`){t.mutation?.assert(),yield*e.mkdir(t.dirPath,t.mode),yield*v(e,t);return}let inspect=function*(n){let r=p(e,()=>e.lstatExact(t.dirPath),n,!1,e=>{if(e.isSymbolicLink()||!e.isDirectory())throw new i(`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(!b(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(!b(e,`EEXIST`))throw e}n=yield*inspect()}if(yield*v(e,{...t,mode:r?448:`preserve`,expectedIdentity:n,ignoreChmodError:!r&&t.ignoreChmodError}),r&&process.platform!==`win32`&&((yield*inspect(n)).mode&4095n)!=448n)throw new i(`path-mismatch`,`created directory mode could not be finalized`)}function inheritedRegularFileMode(e){if(e.isSymbolicLink())throw new i(`symlink`,`atomic replace destination must not be a symbolic link`);if(!e.isFile())throw new i(`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=T();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=y(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 f(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-${f(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=S(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 r(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=d(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(!b(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 i=e.renameIdentity;return validateRenameIdentity(i),await C(A.resolve(r),async()=>{if(i!==`verify-content-with-lock`)return await replaceAsync(e,r,i,n,t);let a=e.fileSystem?.promises??F,o=A.dirname(r);n.assert();let s=e.dirMode??448;return s===`preserve`?await h(prepareDirectoryMode(l.async(a),{dirPath:o,mode:`preserve`,mutation:n})):await a.mkdir(a===F?c(o):o,{recursive:!0,mode:s}),n.assert(),await withAtomicRenameIdentityLock(r,()=>replaceAsync(e,r,i,n,t))})}function replaceAsync(e,t,n,r,i){return h(replace(l.async(e.fileSystem?.promises??F),e,t,n,r,i))}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 u=buildReplaceTempPath(n,t.tempPrefix),d=new g(u,e),f;try{if(yield*prepareDirectoryMode(e,{dirPath:o,mode:s,mutation:i}),d.start(),d.adopt(yield*_(e,{tempPath:u,content:t.content,mode:c,sync:t.syncTempFile===!0,onIdentity:d.onIdentity,mutation:i})),yield*d.assertCurrent(),t.beforeRename){let r=t.beforeRename({filePath:n,tempPath:u});e.asynchronous?yield*m(r):x(r,`beforeRename`),yield*d.assertCurrent()}t.destinationHardlinks===`reject`&&(yield*assertDestinationHardlinkPolicy(e,n,t.destinationHardlinks),yield*d.assertCurrent());let r=yield*renameWithRetry(e,d,n,t,i);r.method===`rename`?(d.markRenamed(),yield*d.assertPublished(n,l,e=>i.destination(`published`,n,e))):yield*d.assertCurrent();let f=!1;return a?(yield*m(a(o)),f=!0):t.syncParentDir&&(yield*w(e,o),f=!0),r.method===`rename`&&f&&(yield*d.assertPublished(n,l)),r}catch(e){throw f={error:e},e}finally{yield*d.finish({originalFailure:f,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}}const W=/["\\\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(W)??[]){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=j(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return N(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 K=!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 t=e(process.env.NODE_OPTIONS);return t===null||!!process.env.NODE_V8_COVERAGE||!!(process.versions.bun&&(process.env.BUN_INSPECT||process.env.BUN_INSPECT_CONNECT_TO))||[...process.execArgv,...t??[]].some(e=>/^--(?:inspect|cpu-prof|heap-prof|prof|perf-|.*coverage)/.test(e.replaceAll(`_`,`-`)))}function codePath(e){return A.sep===`/`?e:e.replaceAll(A.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=P(e)}catch{return}if(!A.isAbsolute(n))return;let r=t?codePath(A.relative(t,n)):``,i=(t&&!r.startsWith(`..`)?`/${r}`:codePath(A.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(K)return unavailable(`busy`);K=!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 K=!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{K=!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 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,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 L();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 L()}o.length=0;let l=[],u=0,d=0;for(let e of i){++c%1024==0&&await L();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 f=[...a.values()];a.clear();for(let e=f.length-1;e>=0;e--){++c%1024==0&&await L();let t=f[e];t.parent&&(t.parent.totalBytes+=t.totalBytes)}let p={...n,redactedNodeCount:s,unattributedSampleCount:u,unattributedSampleBytes:d},m={...p,truncated:u>0,profile:{head:f[0].node,samples:l}};if(boundedJsonUtf8Bytes(m,1048576).complete)return m;let h=await r?.(m.profile),g=/* @__PURE__ */ new Map,_=/* @__PURE__ */ new Map,v=[],y=[],b=[];for(let e of f){++c%1024==0&&await L();let t=JSON.stringify(e.node.callFrame),n=g.get(t);n===void 0&&(n=g.size,g.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}}y.length=b.length=v.length=0,y.push(e),b.push(1),v.push(n);let s=e.parent;for(;s&&y.length<32;){let e=s.cycle,t=e&&e.width<=32-y.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;y.push(r),b.push(i?n:1),v.push(i?`${r.frameId}x${n}`:r.frameId),s=r.parent}s=r}if(s){let t=y[29].app,n=t?t===e.owner?[t]:[t,e.owner]:[];y.length=b.length=v.length=29,y.push(void 0,...n),b.push(1,1,1),v.push(`...`,...n.map(e=>e.frameId))}let l=v.join(`,`),u=_.get(l);if(u)u.selfBytes+=a,u.totalBytes+=r,u.count+=i;else{let t=[e.node.callFrame];for(let e=1;e<y.length;e++){let n=y[e]?.node.callFrame;t.push(n?b[e]>1?{...n,functionName:`${n.functionName} ×${b[e]}`}:n:{functionName:`[...]`,url:``,scriptId:`0`,lineNumber:-1,columnNumber:-1})}_.set(l,{stack:t,selfBytes:a,totalBytes:r,count:i})}}g.clear(),y.length=0,f.length=0;let x={...p,...h,truncated:!0,summary:[]},S=Buffer.byteLength(JSON.stringify(x));for(let e of await sortAllocationSummaries(_.values())){++c%1024==0&&await L();let t=Buffer.byteLength(JSON.stringify(e))+Number(x.summary.length>0);if(S+t>1048576)break;x.summary.push(e),S+=t}return x}const q=5e3,J=262144,Y=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let X=Promise.resolve();async function reportWorkerGcStorm(e,t,n){let{profiles:r,...i}=e,a={...i,workerThreadId:t,workerSlot:n},o=E(`agents/code-mode`);if(r)try{let e=await writeWorkerGcProfiles(r);o.warn(`Code Mode worker GC storm`,{...a,profileFiles:e})}catch{o.warn(`Code Mode worker GC storm`,{...a,captureStatus:`unavailable`,captureReason:`profile-write-failed`})}else o.warn(`Code Mode worker GC storm`,a);if(i.captureStatus===`requested`){let{getEnabledCategories:e}=await import(`node:trace_events`);if(e())o.warn(`Code Mode worker GC storm`,{...a,captureStatus:`unavailable`,captureReason:`tracing-active`});else return i}}function captureWorkerGcProfiles(){return captureDiagnosticProfile({hasAuthority:()=>!0,durationMs:q,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:J,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:q,effectiveDurationMs:q,actualDurationMs:r.durationMs,durationLimitReason:null,samplingIntervalBytes:J,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=A.join(n(),`diagnostics`);await F.mkdir(t,{recursive:!0,mode:448});let r=(await F.readdir(t)).filter(e=>Y.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 X=t.catch(()=>{}),t}export{captureWorkerGcProfiles,reportWorkerGcStorm};