UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 16.8 kB
import{Mt as e,V as t,t as n}from"./sqlite-readonly-subsystem-C-VJT-xk.mjs";import{A as r,J as i,M as a,Mt as o,N as s,P as c,R as l,Rt as u,_ as d,cn as f,j as p,mn as m,q as h}from"./sqlite-readonly-runtime-process-manifest-CLhsN5hb.mjs";import{D as g,F as _,I as v,L as y,N as b,P as x,W as S,k as C,n as w,t as T}from"./sqlite-readonly-lock-config-dZbF0Wy8.mjs";import"./sqlite-readonly-cli-invocation-xwXCxqwu.mjs";import"./sqlite-readonly-openclaw-root-PLr-9gty.mjs";import E from"node:path";import"node:timers/promises";import{randomUUID as D}from"node:crypto";import O from"node:fs";import k from"node:fs/promises";import"node:url";import{getEnvironmentData as A,setEnvironmentData as j}from"node:worker_threads";function*prepareDirectoryMode(e,t){if(t.mode!==`preserve`){t.mutation?.assert(),yield*e.mkdir(t.dirPath,t.mode),yield*_(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 f(`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=E.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*_(e,{...t,mode:r?448:`preserve`,expectedIdentity:n,ignoreChmodError:!r&&t.ignoreChmodError}),r&&process.platform!==`win32`&&((yield*inspect(n)).mode&4095n)!=448n)throw new f(`path-mismatch`,`created directory mode could not be finalized`)}const M=d();function assertSourcePreview(e,t){if(e.isSymbolicLink())throw new f(`symlink`,`Refusing copy fallback from non-file source: ${t}`);if(!e.isFile())throw new f(`not-file`,`Refusing copy fallback from non-file source: ${t}`);if(e.nlink!==1)throw new f(`hardlink`,`Hardlinked copy fallback source not allowed: ${t}`)}function assertOpenedSource(e,t,n){if(!e.isFile()||t.isSymbolicLink())throw new f(`path-mismatch`,`Copy fallback source changed while opening: ${n}`);if(e.nlink!==1n)throw new f(`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,M)}catch(e){throw b(e,`ELOOP`)?new f(`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();S(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 f(`path-mismatch`,`Atomic replace destination changed: ${t}`);if(n&&e.nlink!==1n)throw new f(`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 N=process.platform!==`win32`&&`O_NOFOLLOW`in O.constants?O.constants.O_NOFOLLOW:0,P=d(),F=O.constants.O_RDWR|N,I=O.constants.O_WRONLY|O.constants.O_CREAT|O.constants.O_EXCL|N;function admitDestinationKind(e,t,n,r){if(r===`hardlinks`){if(e.isSymbolicLink()||!e.isFile())throw new f(`path-mismatch`,`Atomic replace destination changed while opening: ${n}`)}else if(e.isSymbolicLink())throw new f(`symlink`,`Refusing copy fallback through symlink destination: ${n}`);else if(!e.isFile()||!t.isFile())throw new f(`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(b(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 f(`symlink`,`Refusing copy fallback through symlink destination: ${t}`);i?.assert();let o=yield*e.open(t,n===`restore`?F:P);try{let i=e.asyncFs===k,a=p(e,()=>o.statExact(),void 0,i),s=e.asynchronous&&!i?yield a:a,c=p(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 f(`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 l={initialSize:Number.isSafeInteger(r.size)&&r.size>=0?r.size:void 0,createLimitError:()=>new f(`too-large`,`Atomic replace restore snapshot exceeds maxRestoreBytes (${n})`)};return e.asynchronous?yield*c(h(n,(e,t)=>a(read(e,t)),l)):i(n,(e,t)=>s(read(e,t)),l)}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 f(`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(!b(e,`ENOENT`))throw e}if(s?.isSymbolicLink())throw new f(`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,I,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 f(`symlink`,`atomic replace destination must not be a symbolic link`);if(!e.isFile())throw new f(`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=w(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 m(typeof t==`string`?t:Buffer.from(t))}function lockOptions(e){let t=E.resolve(e);return{managerKey:`fs-safe.atomic:${t}`,lockPath:E.join(E.dirname(t),`.fs-safe-atomic-${m(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=x(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 u(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=E.dirname(e),r=o(t??`.fs-safe-replace`,{label:`atomic replace temp prefix`});return E.join(n,`${r}.${process.pid}.${D()}.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),i=validateReplaceFilePath(e.filePath);validateRestoreOptions(e);let o=e.renameIdentity;return validateRenameIdentity(o),await g(E.resolve(i),async()=>{if(o!==`verify-content-with-lock`)return await replaceAsync(e,i,o,n,t);let s=e.fileSystem?.promises??k,c=E.dirname(i);n.assert();let u=e.dirMode??448;return u===`preserve`?await a(prepareDirectoryMode(r.async(s),{dirPath:c,mode:`preserve`,mutation:n})):await s.mkdir(s===k?l(c):c,{recursive:!0,mode:u}),n.assert(),await withAtomicRenameIdentityLock(i,()=>replaceAsync(e,i,o,n,t))})}function replaceAsync(e,t,n,i,o){return a(replace(r.async(e.fileSystem?.promises??k),e,t,n,i,o))}function*replace(e,t,n,r,i,a){let o=E.dirname(n),s=t.dirMode??448,l=yield*resolveMode(e,t,n),u=atomicExpectedContentHash(r,t.content);if(!e.asynchronous){let n=t;if(e.fchmodSync=n.fileSystem?.fchmodSync??(n.fileSystem===void 0?O.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 C(d,e),p;try{if(yield*prepareDirectoryMode(e,{dirPath:o,mode:s,mutation:i}),f.start(),f.adopt(yield*y(e,{tempPath:d,content:t.content,mode:l,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*c(r):S(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,u,e=>i.destination(`published`,n,e))):yield*f.assertCurrent();let p=!1;return a?(yield*c(a(o)),p=!0):t.syncParentDir&&(yield*v(e,o),p=!0),r.method===`rename`&&p&&(yield*f.assertPublished(n,u)),r}catch(e){throw p={error:e},e}finally{yield*f.finish({originalFailure:p,throwOnCleanupError:t.throwOnCleanupError===!0})}}e(Symbol.for(`openclaw.runtimeExecutionNotices`),()=>{let e=`openclaw.runtimeExecutionNotices`,t=A(e),n=t instanceof SharedArrayBuffer?t:new SharedArrayBuffer(4);return j(e,n),new Int32Array(n)});const L=/^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;let R=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 writeWorkerGcProfiles(e){let n=R.then(async()=>{let n=E.join(t(),`diagnostics`);await k.mkdir(n,{recursive:!0,mode:448});let r=(await k.readdir(n)).filter(e=>L.test(e)).toSorted();for(let e of r.slice(0,Math.max(0,r.length-20+2)))await k.unlink(E.join(n,e));let i=`code-mode-gc-${Date.now()}-${D()}`,a=[];for(let[t,r]of[[`heap`,e.heap],[`cpu`,e.cpu]]){let e=`${i}.${t}profile.json`;await replaceFileAtomic({filePath:E.join(n,e),content:r,mode:384,dirMode:448}),a.push(e)}return a});return R=n.catch(()=>{}),n}export{reportWorkerGcStorm};