UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 237 kB
import{a as e,c as t,i as n,n as r,o as i,p as a,r as s,u as c}from"./plugin-preparation-record-coerce-CWNcHDAn.mjs";import{a as l,i as u,n as d,o as f,r as p}from"./plugin-preparation-error-graph-internal-3EGECs5H.mjs";import{$ as m,A as h,B as g,C as _,F as v,G as y,H as b,I as x,J as S,L as C,M as w,N as T,P as E,R as D,S as O,T as k,U as A,V as j,W as M,X as N,_ as P,b as F,g as I,j as L,o as R,v as z,w as B,x as V,y as H,z as ee}from"./plugin-preparation-diagnostic-events-C0NITktC.mjs";import{A as te,O as U,T as ne,_ as re,a as W,b as ie,g as ae,i as oe,j as se,o as ce,p as le,r as ue,v as de,w as fe,x as pe,y as me}from"./plugin-preparation-subsystem-D76Sei3m.mjs";import{$t as he,A as ge,Dt as _e,Gt as ve,Ht as ye,Jt as be,Pt as xe,Tt as Se,Xt as Ce,Yt as we,Zt as Te,_t as Ee,an as De,cn as Oe,en as ke,gt as Ae,ht as je,jt as Me,mn as Ne,on as Pe,rn as Fe,st as Ie,t as Le,vt as Re}from"./plugin-preparation-worker-native-lifecycle-D72AWAt5.mjs";import{c as ze,m as Be,p as Ve,r as He,u as Ue}from"./plugin-preparation-sleep-D6xG-JRB.mjs";import"./plugin-preparation-runtime-process-manifest-BlrvoYG_.mjs";import{B as We,R as Ge,a as Ke,c as qe,f as Je,i as Ye,l as Xe,n as Ze,o as Qe,r as $e,s as et,t as G,u as K,v as tt,y as nt}from"./plugin-preparation-result-D34pSHZd.mjs";import{t as rt}from"./plugin-preparation-deferred-B75K7ut7.mjs";import{r as it}from"./plugin-preparation-src-f3atoZzb.mjs";import{n as at}from"./plugin-preparation-cli-invocation-CQPKFT_h.mjs";import{n as ot}from"./plugin-preparation-runtime-process-entrypoints-JtM_i2_8.mjs";import{r as st,t as ct}from"./plugin-preparation-runtime-worker-url-D-YZ5wuH.mjs";import{t as lt}from"./plugin-preparation-errors-8b9QitPs.mjs";import{n as ut,r as dt}from"./plugin-preparation-path-existence-C_m6CcB7.mjs";import*as ft from"node:module";import{createRequire as pt,isBuiltin as mt}from"node:module";import{MessageChannel as ht,MessagePort as gt,isMainThread as _t,parentPort as vt,receiveMessageOnPort as yt,threadId as bt,workerData as xt}from"node:worker_threads";import{AsyncLocalStorage as St}from"node:async_hooks";import Ct,{createHash as wt,hash as Tt,randomUUID as Et}from"node:crypto";import q,{statSync as Dt,default as Ot}from"node:fs";import J,{default as kt}from"node:fs/promises";import At,{tmpdir as jt}from"node:os";import Y from"node:path";import{fileURLToPath as X,pathToFileURL as Z}from"node:url";import{isPathInside as Mt,safeRealpathSync as Nt}from"@openclaw/fs-safe/path";import{isDeepStrictEqual as Pt}from"node:util";import{GCProfiler as Ft,getHeapSpaceStatistics as It,getHeapStatistics as Lt}from"node:v8";import{Session as Rt}from"node:inspector/promises";import{channel as zt}from"node:diagnostics_channel";import"@openclaw/fs-safe/json";import{copyFileDescriptorSync as Bt,copyRootFileSync as Vt,createDirectorySync as Ht,createFileSync as Ut,createRootFileCopyBatchSync as Wt,createRootFileOpenBatchSync as Gt}from"@openclaw/fs-safe/advanced";import{FsSafeError as Kt}from"@openclaw/fs-safe/errors";import"@openclaw/fs-safe/root";import{moduleResolve as qt}from"import-meta-resolve";import{StringDecoder as Jt}from"node:string_decoder";import"@openclaw/fs-safe/durability";import"node:buffer";import"@openclaw/fs-safe/atomic";const Yt=Symbol.for(`openclaw.workerTaskNativeSection`),Xt=globalThis,Zt=Xt[Yt]??=new St;function assertWorkerTaskActive(e,t){if(!t()||e&1)throw Error(`worker task cancelled`)}function acquireWorkerNativeSection(e,t){for(;;){let n=Atomics.load(e,0);if(assertWorkerTaskActive(n,t),Atomics.compareExchange(e,0,n,n+2)===n)break}let n=!1;return()=>{n||(n=!0,Atomics.sub(e,0,2),Atomics.notify(e,0))}}function withWorkerTaskNativeSectionScope(e,t,n){return Zt.run(()=>acquireWorkerNativeSection(e,t),n)}function createWorkerNativeSectionState(){return new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))}function cancelWorkerNativeSections(e){Atomics.or(e,0,1),Atomics.notify(e,0)}function observeWorkerTaskCancellation(e,t,n){let r=!0,i=(async()=>{for(;;){if(!r||!t())return;let i=Atomics.load(e,0);if(i&1){n();return}await Atomics.waitAsync(e,0,i).value}})();return()=>(r=!1,Atomics.notify(e,0),i)}function waitForWorkerNativeSections(e){if(!areWorkerNativeSectionsSettled(e))return(async()=>{for(;;){let t=Atomics.load(e,0);if(t<2)return;await Atomics.waitAsync(e,0,t).value}})()}function areWorkerNativeSectionsSettled(e){return Atomics.load(e,0)<2}function releaseWorkerNativeSectionsOnExit(e){Atomics.store(e,0,1),Atomics.notify(e,0)}function createWorkerTaskControl(e,t,n=new AbortController().signal){let throwIfCancelled=()=>assertWorkerTaskActive(Atomics.load(e,0),t);return{signal:n,throwIfCancelled,runNativeSection:async n=>{let r=acquireWorkerNativeSection(e,t),i;try{i=await n()}finally{r()}return throwIfCancelled(),i}}}function postTaskMessage(e,t,n,r=[]){e.postMessage(t,r),n&&(Atomics.add(n,0,1),Atomics.notify(n,0))}function serveOwnedWorkerTasks$1(e,t,n){if(!vt)return;let r=vt,i=r,a=!1,s=!1;n.initialize(i);let c,l=Promise.resolve(),u=Promise.resolve(),d=0,f,p=typeof e==`function`?void 0:e.synchronousStateless,m=typeof e==`function`?e:e.synchronousStateless,reply=(e,r)=>{postTaskMessage(i,{status:`ok`,value:r,taskId:e.taskId,...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},e.progressSignal,t.transferList?.(r)??[])},fail=(e,r)=>{t.retireOnError?s=!0:postTaskMessage(i,{status:`failed`,taskId:e.taskId,error:r instanceof Error?r.message:String(r),...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},e.progressSignal)},finish=()=>{s?(async()=>{try{await u}finally{try{await n.onRetire?.()}finally{process.exitCode=1;try{i.close()}finally{i!==r&&r.close()}}}})().catch(()=>{process.exitCode=1}):n.onIdle()};i.on(`message`,function receive(e){if(s){e.resourcePort?.close();return}if(!a){a=!0;let t=n.selectStartupPort?.(e);if(t){i.off(`message`,receive),i=t,n.initialize(i),i.on(`message`,receive),n.onReady?.();return}}if(n.onMessage(e.sampleMemory===!0),e.closeResource&&e.resourcePort){let r=e.resourcePort,i=t.closesBesideExecution?.(e.key)?void 0:l;d++,u=u.then(()=>i).then(async()=>{if(s)throw Error(`Worker is retiring after a terminal task failure`);await t.closeResource(e.key),r.postMessage({ok:!0},[])}).catch(e=>{r.postMessage({ok:!1,error:e instanceof Error?e.message:String(e),detail:t.encodeResourceError?.(e)},[])}).finally(()=>{r.close(),d--,!c&&!s&&n.onIdle()});return}if(e.responseId!==void 0){if(e.taskId===f?.taskId&&e.responseId===f.responseId)return;if(!c||e.taskId!==c.taskId||e.responseId!==c.responseId||!c.pending)throw Error(`stale worker task response`);try{c.assertCurrent()}catch(e){c.cancelPending(e);return}let t=c.pending;c.pending=void 0;let n=!1,r=e.taskId,a=e.responseId,s=c.progressSignal;t.resolve({input:e.input,consumed:()=>{n||(n=!0,postTaskMessage(i,{status:`consumed`,taskId:r,id:a},s))}});return}if(c)throw Error(`overlapping worker tasks`);let r=new Int32Array(e.nativeSections),h={taskId:e.taskId,responseId:0,progressSignal:e.progressSignal,assertCurrent:()=>_.throwIfCancelled(),cancelPending:e=>{let t=h.pending;t&&(h.pending=void 0,f={taskId:h.taskId,responseId:h.responseId},t.reject(e))}},g=new AbortController,_=createWorkerTaskControl(r,()=>c===h,g.signal);if(c=h,p&&!e.interactive&&d===0){try{_.throwIfCancelled(),n.installTaskContext(e.taskContext);let t=p(e.input);c=void 0,reply(h,t)}catch(e){c=void 0,fail(h,e)}finally{finish()}return}let v=observeWorkerTaskCancellation(r,()=>c===h,()=>{let e=/* @__PURE__ */ Error(`worker task cancelled`);g.abort(e),h.cancelPending(e)}),y=e.interactive?{notify:e=>{_.throwIfCancelled(),postTaskMessage(i,{status:`notification`,taskId:h.taskId,value:e},h.progressSignal)},consumeInput:()=>postTaskMessage(i,{status:`consumed`,taskId:h.taskId,id:0},h.progressSignal),request:(e,t)=>{if(_.throwIfCancelled(),c!==h||h.pending)throw Error(`closed or busy worker channel`);let n=Promise.withResolvers();h.pending=n;try{let n=t?[...t]:[];_.throwIfCancelled(),postTaskMessage(i,{status:`request`,taskId:h.taskId,id:++h.responseId,value:e},h.progressSignal,n)}catch(e){h.pending=void 0,n.reject(e)}return n.promise}}:void 0,b=u;l=Promise.resolve().then(async()=>{try{return await b,_.throwIfCancelled(),n.installTaskContext(e.taskContext),await withWorkerTaskNativeSectionScope(r,()=>c===h,()=>m(e.input,y,_))}finally{await v?.(),c=void 0}}).then(e=>reply(h,e)).catch(e=>fail(h,e)).finally(finish)}),n.onReady?.()}_t&&process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED===`gateway`&&(delete process.env.NODE_DISABLE_COMPILE_CACHE,delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED);const Qt=36e5,$t=3e4,en=/^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/,sanitize=e=>{let t=e.replace(/[^A-Za-z0-9._-]+/g,`_`).replace(/^_+|_+$/g,``);return t&&t!==`.`&&t!==`..`?t:`unknown`};function scheduleOpenClawCompileCacheFlush(){if(!ft.getCompileCacheDir?.())return;let e=globalThis[Symbol.for(`openclaw.nodeCompileCacheBase`)]??={};e.flush||(e.flush=setImmediate(()=>{e.flush=void 0;try{ft.flushCompileCache()}catch{}}),e.flush.unref())}function resolveSafeNodeCompileCacheDirectory(e){if(process.platform===`win32`&&Y.resolve(e).length>200)process.stderr.write(`[openclaw] Compile cache disabled: Windows cache path exceeds 200 characters.
`);else return e}async function maintain(e){let t=Y.dirname(Y.dirname(e)),n=Y.basename(Y.dirname(e));if(Y.basename(t)!==`openclaw`||sanitize(n)!==n||!en.test(Y.basename(e)))return;let r=Date.now(),i=await J.lstat(t).catch(()=>void 0);for(let n of[t,Y.dirname(e),e]){let e=n===t?i:await J.lstat(n).catch(()=>void 0);if(e&&!e.isDirectory())return}if(i&&r-i.mtimeMs<Qt)return;await J.mkdir(t,{recursive:!0});let a=`${t}.maintenance`,s=await J.lstat(a).catch(()=>void 0);if(s&&r-s.mtimeMs>3e5&&await J.rmdir(a).catch(()=>{}),!await J.mkdir(a).then(()=>!0,()=>!1))return;let c=[],l=0,u=0,d=!1;async function prune(){for(c.sort((e,t)=>t.mtimeMs-e.mtimeMs);c.length;){if(Date.now()-r>$t)return!1;let e=c[c.length-1];if(l<=536870912&&c.length<=4096&&r-e.mtimeMs<=6048e5)break;await J.unlink(e.file).catch(e=>{if(e.code!==`ENOENT`)throw e}),l-=e.size,c.pop()}return!0}async function visit(e){for await(let t of await J.opendir(e)){if(++u>16384||Date.now()-r>$t)return!1;let n=Y.join(e,t.name);if(t.isDirectory()){if(!await visit(n))return!1}else if(t.isFile()){let e=await J.lstat(n).catch(e=>{if(e.code!==`ENOENT`)throw e});if(!e)continue;if(l+=e.size,c.push({file:n,size:e.size,mtimeMs:e.mtimeMs}),c.length%256==0&&!await prune())return!1}}return!0}try{if(r-(await J.lstat(t)).mtimeMs<Qt){d=!0;return}let e=await visit(t);if(await prune()&&e){let e=/* @__PURE__ */ new Date;await J.utimes(t,e,e),d=!0}}finally{d||await J.utimes(t,i?.atime??/* @__PURE__ */ new Date(0),i?.mtime??/* @__PURE__ */ new Date(0)).catch(()=>{}),await J.rmdir(a)}}process.argv[2]===`--maintain`&&process.argv[1]===X(import.meta.url)&&process.argv[3]&&maintain(process.argv[3]).catch(()=>{});const tn=m(Symbol.for(`openclaw.agentDatabaseReaders`),()=>({closers:/* @__PURE__ */ new Set,deleted:/* @__PURE__ */ new Map}));function matchesAgentDatabaseReadCandidatePath(e,t){if(e.path===t)return!0;let n=Y.resolve(e.path),r=Y.resolve(t);if(n===r)return!0;if(e.scope!==`sibling-family`)return!1;let i=Y.parse(n),a=Y.parse(r);return a.dir===i.dir&&a.base.startsWith(`${i.name}.`)&&a.base.endsWith(i.ext)}function registerAgentDatabaseReaderCloser(e){return tn.closers.add(e),()=>{tn.closers.delete(e)}}function captureDeletedAgentDatabaseFences(){return[...tn.deleted]}function installDeletedAgentDatabaseFences(e){tn.deleted.clear();for(let[t,n]of e)tn.deleted.set(t,n)}async function applyAgentDatabaseReaderRequest(e){if(e.kind===`revive`){for(let[t,n]of tn.deleted)e.agentIds.includes(n)&&tn.deleted.delete(t);return}if(e.deleted)for(let t of e.candidates)tn.deleted.set(Y.resolve(t.path),e.agentId);let t=e.deleted?void 0:new Set(e.retainedPaths?.map(e=>Y.resolve(e))),n=await Promise.allSettled([...tn.closers].map(async n=>n(e.candidates,t)));l(n,`Agent database reader cleanup failed`)}function normalizeCandidates(e){if(Array.isArray(e)&&e.every(e=>n(e)&&typeof e.path==`string`&&(e.scope===void 0||e.scope===`sibling-family`)))return e.map(e=>e.scope?{path:e.path,scope:e.scope}:{path:e.path})}function decodeAgentDatabaseReaderRequest(t){if(t===void 0)return;let r;try{r=JSON.parse(t)}catch{return}if(Array.isArray(r)){let e=normalizeCandidates(r);return e?{kind:`close`,candidates:e,deleted:!1}:void 0}if(n(r)){if(`candidates`in r&&!(`deleted`in r)){let t=normalizeCandidates(r.candidates),n=r.retainedPaths;return t&&e(n)?{kind:`close`,candidates:t,retainedPaths:n,deleted:!1}:void 0}if(`deleted`in r){let e=normalizeCandidates(r.deleted);return e&&typeof r.agentId==`string`&&r.agentId.length>0?{kind:`close`,candidates:e,deleted:!0,agentId:r.agentId}:void 0}if(`revive`in r&&e(r.revive))return{kind:`revive`,agentIds:r.revive}}}const nn=m(Symbol.for(`openclaw.databaseEngineSelection`),()=>({})),rn=m(Symbol.for(`openclaw.databaseEngineMaintenanceSelection`),()=>new St);function getDatabaseEngineSelection(){return rn.getStore()??nn.selection}function withDatabaseEngineSelection(e,t){return rn.run(e,t)}const an=xt,Q=m(Symbol.for(`openclaw.postgresIoPool`),()=>({endpoints:an?.postgresPool,workers:void 0,nextStep:void 0,ready:[],refresh:void 0,failure:void 0}));function postgresPoolWorkerFailure(){return Q.failure}function bindPostgresPool(e){if(Q.endpoints){if(Q.endpoints===e)return;for(let{port:t}of e.services)t.close()}else Q.endpoints=e}async function closePostgresPool(){let e=Q.workers;Q.workers=void 0;for(let{port:e}of Q.endpoints?.services??[])e.close();Q.endpoints=void 0,Q.ready=[],Q.refresh=void 0,Q.failure=void 0,await Promise.all(e?.map(e=>e.terminate())??[])}function createGatewayStateProcessOwnerRetiredError(){return/* @__PURE__ */ Error(`OpenClaw state process owner is no longer current`)}const on=m(Symbol.for(`openclaw.stateDatabaseAccessError`),()=>class extends Error{constructor(...e){super(...e),this.name=`StateDatabaseAccessError`}}),sn=m(Symbol.for(`openclaw.gatewayStateOwnerContentionError`),()=>class extends Error{constructor(e,t,n,r){super(`OpenClaw state database is busy at ${e}. ${n?`${n} `:``}Wait for the other OpenClaw process to finish, then retry. If it persists, run \`openclaw gateway status\` and check for other OpenClaw processes using the same state directory. A running Gateway can hold this ownership until it stops; stop it through its service manager or original terminal before retrying.`),this.databasePath=e,this.cause=t,this.holderDetail=n,this.holder=r,this.name=`GatewayStateOwnerContentionError`}}),cn=m(Symbol.for(`openclaw.stateDatabaseMaintenanceScopeError`),()=>class extends on{constructor(e){super(`Internal state ownership error at ${e}: this process holds maintenance ownership without an active schema lease or maintenance scope. Retry the command; if it persists, report this error.`),this.name=`StateDatabaseMaintenanceScopeError`}}),ln=m(Symbol.for(`openclaw.stateDatabaseAdmissionPendingError`),()=>class extends on{constructor(e,t){super(t),this.databasePath=e}}),un=m(Symbol.for(`openclaw.stateDatabaseOfflineMaintenanceError`),()=>class extends on{constructor(e,t){super(t),this.databasePath=e}}),dn=process.hrtime;function readSqliteWorkerMonotonicNs(){return dn.bigint()}const fn=33554432;m(Symbol.for(`openclaw.sqliteWorkerOpenRefusedError`),()=>class extends Error{constructor(e){super(`SQLite worker admission was refused before agent open`,{cause:e}),this.originalError=e,this.name=`SqliteWorkerOpenRefusedError`}});const pn=m(Symbol.for(`openclaw.sqliteWorkerAdmissionTimeoutError`),()=>class extends Error{constructor(){super(`SQLite host admission timed out; retry after transaction rollback`),this.code=`admission-timeout`,this.name=`SqliteWorkerAdmissionTimeoutError`}});function readSqliteWorkerAdmissionDecision(e){if(!n(e)||!(e.decision instanceof SharedArrayBuffer)||e.decision.byteLength!==Int32Array.BYTES_PER_ELEMENT||e.stage!==`open`&&e.stage!==`prepare`&&e.stage!==`transaction`&&e.stage!==`commit`)return;let t=new Int32Array(e.decision),r=typeof e.deadlineMs==`number`&&Number.isFinite(e.deadlineMs)?readSqliteWorkerMonotonicNs()+BigInt(Math.max(0,Math.ceil(e.deadlineMs)))*1000000n:void 0;return{decision:t,expired:()=>{if(r!==void 0&&readSqliteWorkerMonotonicNs()>=r&&Atomics.compareExchange(t,0,0,3)===0&&Atomics.notify(t,0),Atomics.load(t,0)!==3)return!1;if(Array.isArray(e.ports))for(let t of e.ports)t instanceof gt&&t.close();return!0},request:{stage:e.stage,facts:e.facts}}}var SqliteDatabaseAdmissionTimeoutError=class extends ke{constructor(){super(`SQLite admission facts exchange timed out; the host did not reply`,`unavailable`)}};const mn=m(Symbol.for(`openclaw.sqliteDatabaseAdmissionUpstream`),()=>({}));function bindSqliteDatabaseAdmissionUpstream(e){let t=mn.connection;if(t){if(t.port!==e)throw new ke(`SQLite admission upstream changed owner`,`closed`);return}let n={port:e,closed:!1};mn.connection=n,e.once(`close`,()=>{n.closed=!0}),e.unref()}function getSqliteDatabaseAdmissionUpstream(){return mn.connection}function isSqliteDatabaseAdmissionLocation(e){return n(e)&&typeof e.identity==`string`&&typeof e.canonicalPath==`string`}function exchangeSqliteDatabaseAdmissions(e,t,n,r,i){return exchangeDatabaseAdmissions(e,t,n,r,i)}function exchangeDatabaseAdmissions(e,t,n,r,i){let{port1:a,port2:s}=new ht,c=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),l=ve(),u=Date.now(),d=Te(),f=d===void 0?6e5:Math.max(0,d-Date.now()),p=readSqliteWorkerMonotonicNs()+BigInt(Math.ceil(f))*1000000n,remaining=()=>{we();let e=Number(p-readSqliteWorkerMonotonicNs())/1e6;if(e<=0)throw new SqliteDatabaseAdmissionTimeoutError;return e};try{for(remaining(),e.postMessage({kind:`sqlite-database-admissions`,admissions:t,location:n,create:r,observedLocation:i,deadlineAtMs:d,port:s,decision:c.buffer},[s]);Atomics.load(c,0)===0;){let e=remaining();Atomics.wait(c,0,0,Ce()?Math.min(100,e):e)}remaining();let l=Atomics.load(c,0);if(l===4&&n&&r===!0)throw new ln(n,`OpenClaw state at ${n} is undergoing schema admission; retry when it finishes.`);if(l!==1)throw new ke(`SQLite admission facts exchange failed`,`unavailable`);let u=Oe(yt(a)?.message);if(!u)throw new ke(`SQLite admission facts reply is unavailable`,`unavailable`);return u}finally{Atomics.compareExchange(c,0,0,2),l&&(l.databaseAdmissionWaitMs+=Date.now()-u),a.close(),s.close()}}const hn=/* @__PURE__ */ new WeakMap;function bindSqliteWorkerDatabaseAdmissionCursor(e,t,n){hn.set(e,{cursor:t,reset:n})}function isSqliteDatabaseAdmissionMessage(e){return!(!(e.port instanceof gt)||!(e.decision instanceof SharedArrayBuffer)||e.decision.byteLength!==Int32Array.BYTES_PER_ELEMENT||e.location!==void 0&&typeof e.location!=`string`||e.observedLocation!==void 0&&!isSqliteDatabaseAdmissionLocation(e.observedLocation)||e.deadlineAtMs!==void 0&&(typeof e.deadlineAtMs!=`number`||!Number.isFinite(e.deadlineAtMs))||e.create!==void 0&&typeof e.create!=`boolean`&&e.create!==`admitted`)}function createSqliteDatabaseAdmissionReplies(){let e=Pe();return{release(e){hn.delete(e)},receive(t,n,r,i){if(!isSqliteDatabaseAdmissionMessage(t)){i(new ke(`SQLite admission facts request is invalid`,`unavailable`));return}let a=new Int32Array(t.decision),{deadlineAtMs:s,observedLocation:c}=t,assertWaiting=()=>{if(Atomics.load(a,0)!==0||s!==void 0&&Date.now()>=s)throw new ke(`SQLite admission requester stopped waiting`,`unavailable`)},l=t.port,u=t.location;return{message:t,decision:a,deadlineAtMs:s,observedLocation:c,assertWaiting,publishFacts:t=>{assertWaiting();let r=u===void 0&&t.length===0?void 0:{location:u,admissions:t},i=hn.get(n),s=Fe(i?.cursor??e,r);l.postMessage(s,[]),ye(`admission`,`to_worker`),Atomics.compareExchange(a,0,0,1)},failFacts:(t,s)=>{if(Atomics.load(a,0)!==0)return;let c=hn.get(n);c?c.cursor=r?r(()=>c.reset()):c.reset():e=Pe(),t instanceof ln&&t.databasePath===s?Atomics.compareExchange(a,0,0,4):Atomics.compareExchange(a,0,0,2)===0&&i(t)},finishFacts:()=>{l.close(),Atomics.notify(a,0)}}}}}const gn=33554432,_n=typeof Bun==`object`?Bun:void 0;let vn={heapUsed:0,external:0},yn,bn,xn=!1;function hasIdleGarbageGrowth(){let e=process.memoryUsage();return e.heapUsed>vn.heapUsed+gn||e.external>vn.external+gn}async function collectWorkerIdleGarbage(){if(bn=void 0,!hasIdleGarbageGrowth())return;xn=!0;let e=process.memoryUsage(),t=Date.now();try{if(_n)_n.gc(!0);else{if(!yn){let e=new Rt;e.connect(),yn=e}await yn.post(`HeapProfiler.collectGarbage`)}vn=process.memoryUsage();let n=Date.now()-t;if(n>=1e3){let t={elapsedMs:n,threadId:bt,heapUsedBeforeBytes:e.heapUsed,heapUsedAfterBytes:vn.heapUsed,externalBeforeBytes:e.external,externalAfterBytes:vn.external};import(`./plugin-preparation-worker-idle-gc-report.runtime-CujNA8YM.mjs`).then(({reportSlowIdleWorkerGc:e})=>e(t)).catch(e=>{process.emitWarning(e instanceof Error?e:String(e))})}}catch(e){process.emitWarning(e instanceof Error?e:String(e))}finally{xn=!1}}function scheduleWorkerIdleGc(){_t||bn||xn||hasIdleGarbageGrowth()&&(bn=setTimeout(()=>{collectWorkerIdleGarbage()},1e3).unref())}function cancelWorkerIdleGc(){clearTimeout(bn),bn=void 0}const Sn={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},Cn=/* @__PURE__ */ new Set;let wn,Tn,En;function getOldGenerationAfterGcBytes(){return En}function drain(e){let t=wn?.stop();e&&wn?.start();let n=[];for(let e of t?.statistics??[]){let t=Sn[e.gcType];if(!t)continue;let r=e.beforeGC.heapStatistics.usedHeapSize,i={kind:t,reason:`other`,durationMs:e.cost/1e3,heapUsedBeforeBytes:r,reclaimedBytes:Math.max(0,r-e.afterGC.heapStatistics.usedHeapSize)};if(t===`mark_sweep_compact`){i.heapUsedAfterMajorGcBytes=e.afterGC.heapStatistics.usedHeapSize,i.heapUsedAfterMajorGcTimestampSeconds=Date.now()/1e3,En=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(En+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of Cn)e(n)}function flushGcSamples(){wn&&drain(!0)}function observeGcSamples(e){if(!process.versions.bun)return wn?drain(!0):(wn=new Ft,wn.start(),Tn=setInterval(()=>drain(!0),1e3).unref()),Cn.add(e),()=>{if(!Cn.has(e))return;let t=Cn.size===1;drain(!t),Cn.delete(e),t&&(clearInterval(Tn),Tn=void 0,wn=void 0,En=void 0)}}function serveWorkerMemorySamples(e,t){let{port1:n,port2:r}=new ht,i=be(e=>{n.postMessage({sqliteReaderCounter:e})}),a=xe(()=>{n.postMessage({postgresBridgeCounters:Me()})}),s=process.versions.bun?void 0:Lt().heap_size_limit,c,l=!1,flushGc=()=>{c&&=(n.postMessage({gc:c}),void 0)},sample=()=>{let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:a}=process.memoryUsage(),l=process.versions.bun?void 0:It().map(({space_name:e,space_used_size:t})=>({space_name:e,space_used_size:t}));n.postMessage({heapUsed:e,heapTotal:r,external:i,arrayBuffers:a,heapSizeLimitBytes:s,oldGenerationAfterGcBytes:getOldGenerationAfterGcBytes(),heapSpaces:l,retainedData:t?.(),gc:c}),c=void 0},u,setGcEnabled=e=>{e?u??=observeGcSamples(e=>{(c??=[]).push(...e),(l||c.length>=256)&&flushGc()}):(u?.(),u=void 0,c=void 0)};return n.on(`message`,e=>{if(e&&`flush`in e)flushGcSamples(),flushGc(),n.postMessage({flushed:!0,heapUsed:Lt().used_heap_size});else if(e&&`captureGcProfile`in e){let t=e.captureGcProfile;import(`./plugin-preparation-diagnostic-worker-gc-profile-C0CkS2y7.mjs`).then(({captureWorkerGcProfiles:e})=>e()).then(e=>{n.postMessage({gcStorm:e.status===`complete`?{...t,captureStatus:`complete`,profiles:e.result}:{...t,captureStatus:`unavailable`,captureReason:e.reason}})}).catch(()=>{n.postMessage({gcStorm:{...t,captureStatus:`unavailable`,captureReason:`capture-failed`}})})}else e?setGcEnabled(e.gc):sample()}),n.once(`close`,()=>{a(),i(),u?.(),c=void 0}),n.on(`messageerror`,()=>n.close()),n.unref(),sample(),e.postMessage({status:`memory`,port:r,postgresBridgeCounters:Me()},[r]),{setTaskMetrics(e){l=e,setGcEnabled(e)},collectTask(){return l?!0:void 0},close(){a(),i(),u?.(),u=void 0,flushGc(),n.close()}}}function serveOwnedWorkerTasks(e,t={}){let r,i,a,s,c,l,runWithTaskContext=async e=>{let run=async()=>{let t=a;if(!t)return e();let n=!0;try{return await De((e,r,i,a)=>{if(!n)throw Error(`SQLite admission facts outlived their worker task`);return exchangeSqliteDatabaseAdmissions(t,e,r,i,a)},e)}finally{n=!1}};return c?withDatabaseEngineSelection(c,run):run()};serveOwnedWorkerTasks$1(typeof e==`function`?(t,n,r)=>he({deadlineAtMs:s,assertActive:()=>r.throwIfCancelled()},()=>runWithTaskContext(async()=>{let i=await e(t,n,r),a=postgresPoolWorkerFailure();if(a)throw a;return i})):e,{...t,get retireOnError(){return t.retireOnError||postgresPoolWorkerFailure()!==void 0},closesBesideExecution:e=>{let t=decodeAgentDatabaseReaderRequest(e);return t?.kind===`revive`||t?.kind===`close`&&t.deleted},closeResource:e=>runWithTaskContext(async()=>{let n=decodeAgentDatabaseReaderRequest(e);if(!n&&!t.closeResource)throw Error(`Worker does not own retained resources`);n&&await applyAgentDatabaseReaderRequest(n),n&&n.kind!==`close`||await t.closeResource?.(e)})},{selectStartupPort(e){if(n(e)&&e.type===`openclaw.worker-task-port`){if(!(e.port instanceof gt))throw Error(`Retained worker task port is invalid`);return i=e.port,i}},initialize(e){se.forceConsoleToStderr=!0,r=e},onReady(){i?.postMessage({status:`ready`},[])},onMessage(e){e&&!l&&(l=serveWorkerMemorySamples(r,t.retainedData)),cancelWorkerIdleGc()},installTaskContext(e){l?.setTaskMetrics(e.collectWorkerMetrics===!0),s=e.databaseAdmissionDeadlineAtMs,c=e.databaseEngineSelection,e.postgresPool&&bindPostgresPool(e.postgresPool),installDeletedAgentDatabaseFences(e.deletedAgentDatabaseFences),e.databaseAdmissionPort&&bindSqliteDatabaseAdmissionUpstream(e.databaseAdmissionPort),a??=e.databaseAdmissionPort},onIdle(){scheduleOpenClawCompileCacheFlush(),t.idleGc!==!1&&scheduleWorkerIdleGc()},collectTaskDiagnostics:()=>l?.collectTask(),onRetire(){cancelWorkerIdleGc();try{l?.close()}finally{a?.close()}}})}const Dn=m(Symbol.for(`openclaw.pluginInstallRootContext`),()=>new St);function resolvePluginInstallRoots(e=process.env,t=At.homedir){let n=fe(e,t);return Object.freeze({extensionsDir:Y.join(n,`extensions`),gitDir:Y.join(n,`git`),npmDir:Y.join(n,`npm`),stateDir:ne(e,t)})}function resolveActivePluginInstallRoots(e=process.env,t=At.homedir){return Dn.getStore()??resolvePluginInstallRoots(e,t)}function hasActivePluginInstallRoots(){return Dn.getStore()!==void 0}function withPluginInstallRoots(e,t){return Dn.run(e,t)}async function settlesWithin(e,t){return await it(e.then(()=>!0),t,()=>!1,{ref:!1})}const On=m(Symbol.for(`openclaw.asyncWorkScope`),()=>new St),kn=m(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new St),An=m(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}});var jn=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=On.getStore();if(t===this)return e();let n=kn.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return S(On,this,()=>(kn.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new An;if(this.pending.size>0)return this.enter(e);let t=rt();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 An);let t=rt();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(d(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),d(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`}};m(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}});function runOutsideAsyncWorkScope(e){return On.getStore()===void 0?kn.getStore()===void 0?e():kn.exit(e):S(On,void 0,()=>(kn.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}}}const Mn=m(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),Nn=m(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),Pn=m(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap);function releasePluginCacheInstance(e,t){let n=Pn.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&&Pn.delete(e)}function getPluginCacheRetainers(e){let t=Nn.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:rt()},Nn.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},autoEnable:/* @__PURE__ */ new WeakMap,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 Mn.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return L()?.cacheScope?.cache}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function withPluginCache(e,t){let n=L();return n?.cacheScope?.cache===e?t():w(h({...n,cacheScope:{cache:e,parent:n?.cacheScope}},n),t)}function retirePluginCache(e,t,n){let r=getPluginCacheRetainers(e);if(r.retirement)return r.retirement;let i=rt();return r.retirement=i.promise,r.controller.abort(),d(r.controller.signal.reason),runOutsideAsyncWorkScope(async()=>{r.references.size&&await r.settled.promise;let i=new jn;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=rt();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]),s=await Promise.allSettled([...i].map(async e=>({resource:e,result:await e.dispose(void 0,n)}))),c=e.sourceAdmissions;if(c){let e=s.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof T?[e.settled]:[]):[]);e.length>0?Promise.allSettled(e).then(()=>c.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`)):await c.dispose()}e.setupModules.clear();for(let t of e.instances)releasePluginCacheInstance(t,e);let l=[...a.status===`rejected`?[a.reason]:[],...s.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(l.length)throw AggregateError(l,`Plugin cache resources failed to retire`);let u=a.status===`fulfilled`?a.value:void 0,d=[...u?.failures??[]];for(let e of s){if(e.status!==`fulfilled`)continue;let{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(d,t.pluginId,n)}return{cleanupCount:u?.cleanupCount??0,failures:d}})().then(r.resolve,r.reject),r.promise}function getPluginCacheRoot(e){let t=getPluginCache(),n=t.roots.get(t.rootAliases.get(e)??e);if(n)return n;let r=Y.resolve(e),i=t.rootAliases.get(r)??r,a=t.roots.get(i);return a||(a={rootDir:i,files:/* @__PURE__ */ new Map,checkedEntries:/* @__PURE__ */ new Map,paths:/* @__PURE__ */ new Map,artifacts:/* @__PURE__ */ new Map,runtimeArtifacts:/* @__PURE__ */ new Map,entryBoundaries:/* @__PURE__ */ new Map,entryPaths:/* @__PURE__ */ new Map},t.roots.set(i,a)),a}function mergeRootFacts(e,t){for(let[n,r]of t)e.has(n)||e.set(n,r)}function bindPluginCacheRoot(e,t){let n=getPluginCacheRoot(e);if(n.rootDir===t)return n;let r=getPluginCache(),i=Y.resolve(e),a=Y.resolve(t);n.rootDir=a;let s=r.roots.get(a);return s&&s!==n&&(mergeRootFacts(n.files,s.files),mergeRootFacts(n.checkedEntries,s.checkedEntries),mergeRootFacts(n.paths,s.paths),mergeRootFacts(n.artifacts,s.artifacts),mergeRootFacts(n.runtimeArtifacts,s.runtimeArtifacts),mergeRootFacts(n.entryBoundaries,s.entryBoundaries),mergeRootFacts(n.entryPaths,s.entryPaths),n.directory??=s.directory,n.publicSurfaceBoundary??=s.publicSurfaceBoundary,Object.assign(s,n)),r.roots.set(a,n),r.rootAliases.set(i,a),n}const Fn=`pluginCaptureResourcePort`;function isVitestRuntimeEnv(e=process.env){let t=e.VITEST;return t===`true`||t===`1`||e.VITEST_POOL_ID!==void 0||e.VITEST_WORKER_ID!==void 0||e.NODE_ENV===`test`}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var o=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(o===void 0&&(o=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var r=o;if(typeof o!=`function`)throw TypeError(`Object is not disposable.`);r&&(o=function(){try{r.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:o,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}async function reclaimLegacyPluginCapture(e){let t=q.lstatSync(e.directory);t.isDirectory()&&t.dev===e.identity.dev&&t.ino===e.identity.ino&&t.uid===e.identity.uid&&(!process.getuid||t.uid===process.getuid())&&await J.rm(e.directory,{recursive:!0,force:!0})}const In=/* @__PURE__ */ new Set,Ln=/* @__PURE__ */ new Set;function recordPluginNativeLoad(e){In.add(process.platform===`win32`?te(e):e)}function subscribePluginNativeLoads(e){return Ln.add(e),()=>{Ln.delete(e)}}function observePluginNativeLoads(){let e=process.dlopen.bind(process);return process.dlopen=(...t)=>{try{let e=q.realpathSync.native(t[1]);recordPluginNativeLoad(e);for(let t of Ln)t(e)}catch{}return e(...t)},In}function createPluginNativeCaptureCustody(e){let t=observePluginNativeLoads(),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;async function reclaimInstance(t,i,a){let s=Y.join(t,tt[0]),c=tt.map(e=>q.lstatSync(Y.join(t,e),{throwIfNoEntry:!1})),l=c[0],u=Y.join(t,`captures`),d=q.lstatSync(u,{throwIfNoEntry:!1});if(process.getuid&&i.uid!==process.getuid()||!l||c.some(e=>e&&(!e.isFile()||e.nlink!==1||process.getuid&&e.uid!==process.getuid()))||d&&!d.isDirectory())return;let unchanged=()=>{let e=q.lstatSync(t),n=q.lstatSync(s);return e.dev===i.dev&&e.ino===i.ino&&e.isDirectory()&&n.isFile()&&n.nlink===1&&n.dev===l.dev&&n.ino===l.ino},f=nt(t,`reclaim`),p=!1,m=[];e.add(t);try{if(!unchanged())return;let e=Y.join(t,`native`),i=q.lstatSync(e,{throwIfNoEntry:!1});if(await a?.assertCurrent(),!unchanged())return;await J.rm(u,{recursive:!0,force:!0});let s=!!i;if(i?.isDirectory()&&a){for(let t of await J.readdir(e,{withFileTypes:!0})){let i=Y.join(e,t.name);if(!t.isDirectory())continue;if(await a.assertCurrent(),!unchanged())return;let contained=e=>e.startsWith(i+Y.sep);if(!([...a.retainedPaths].some(contained)||[...n.keys()].some(contained))){r.add(i);try{await J.rm(i,{recursive:!0,force:!0}),a.removed.push(i)}finally{r.delete(i)}}}s=(await J.readdir(e)).length>0}if(await a?.assertCurrent(),!unchanged())return;f(!0),p=!0,s||(await a?.assertCurrent(),unchanged()&&await J.rm(t,{recursive:!0,force:!0}))}catch(e){m.push(e)}finally{try{p||f()}catch(e){m.push(e)}finally{e.delete(t)}_e(m,`Plugin source reclamation and cleanup failed`)}}function claimPluginCaptureReclaim(i){let{directory:a}=i,s=i.kind===`managed`?Y.join(a,`captures`):a;if(!(e.has(a)||[...t].some(e=>U(a,e))||[...n.keys()].some(e=>U(s,e))))return e.add(a),r.add(s),()=>{r.delete(s),e.delete(a)}}async function reclaimPluginCaptureSweep(e){if(e.length===0)return{failures:0};let[{deserialize:n},{runCommandBuffersWithTimeout:r},{hasCommandProcessCleanupError:i},{withCommandProcessScope:a},{withChildProcessOperation:s}]=await Promise.all([import(`node:v8`),import(`./plugin-preparation-exec-runner-DfAEf0OY.mjs`),import(`./plugin-preparation-exec-result-DNF4aEWV.mjs`).then(e=>e.a),import(`./plugin-preparation-exec-spawn-BuVpSm1O.mjs`).then(e=>e.r),import(`./plugin-preparation-spawn-diagnostics-BTl-smV2.mjs`).then(e=>e.n)]),c=[],l=[];for(let t of e){let e=claimPluginCaptureReclaim(t);e&&(c.push(t),l.push(e))}if(c.length===0)return{failures:0};let u=!0;try{let e={type:`reclaim-plugin-captures`,candidates:c},i=await a(()=>s(`plugin.capture-reclamation`,()=>r([process.execPath,...ct(st(ot.fsSafeCopy))],{input:JSON.stringify(e),beforeInput:()=>{if(c.some(e=>[...t].some(t=>U(e.directory,t))))throw Error(`Plugin capture became loaded before reclamation`)},killProcessTree:!0,requireProcessTreeExtinction:!0,maxOutputBytes:65536})));if(i.code!==0||i.termination!==`exit`)throw Error(`Plugin capture reclamation failed: ${i.termination}`);let l=n(i.stdout);if(l.type===`failed`)throw Error(l.message);if(l.type!==`captures-reclaimed`)throw Error(`Plugin capture reclamation returned no completion receipt`);return l}catch(e){throw u=!i(e),e}finally{if(u)for(let e of l)e()}}return{reclaimInstance,reclaimPluginCaptureSweep,isPluginSourceCaptureRetained(r){return[...e,...i].some(e=>U(e,r)||U(r,e))||[...n.keys(),...t].some(e=>U(r,e))},retainLoadedPluginSourceCapture(n){if(![...t].some(e=>U(n,e)))return!1;let r=[...e].find(e=>U(e,n))??n;return[...i].some(e=>U(e,r)||U(r,e))||process.emitWarning(`Plugin source capture cleanup: retained-by-loaded-module: ${r}; cleanup deferred until the next startup`),i.add(r),!0},retainPluginNativeCapturePath(e){let t=Y.resolve(e);if([...r].some(e=>t.startsWith(e+Y.sep)))throw Error(`Plugin native capture is being reclaimed`);n.set(t,(n.get(t)??0)+1);let i=!1;return()=>{if(i)return;i=!0;let e=n.get(t);e===1?n.delete(t):n.set(t,e-1)}}}}function createPluginCaptureResourceClient(e,t){let n=/* @__PURE__ */ new Map,r=0,i,receive=e=>{let r=n.get(e.id);r&&(e.ok&&e.retainBrokerUntilProcessExit&&t?.(),r.reply=e,r.completion.resolve(e))},fail=()=>{i??=/* @__PURE__ */ Error(`Plugin capture custody transport is unavailable`);for(let e of n.values())e.completion.reject(i);return i};e.on(`message`,receive),e.on(`close`,fail),e.on(`messageerror`,fail),e.unref();let start=t=>{if(i)throw i;let a=++r,s={completion:rt()};return s.completion.promise.catch(()=>{}),n.set(a,s),e.ref(),e.postMessage({id:a,command:t}),{id:a,call:s}},unwrap=e=>{if(!e.ok){let t=Ae(e.error);throw e.sourceAcquisitionFailure?j(t):t}return e};return{async request(t){let{id:r,call:i}=start(t);try{return unwrap(await i.completion.promise)}finally{n.delete(r),n.size||e.unref()}},requestSync(t){let{id:r,call:i}=start(t),a=new Int32Array(new SharedArrayBuffer(4));try{for(;!i.reply;){let t=yt(e);if(t)receive(t.message);else{if(!je(e))throw fail();Atomics.wait(a,0,0,2)}}return unwrap(i.reply).root}finally{n.delete(r),n.size||e.unref()}}}}async function createPluginCaptureOwner(e,t){let n=Et(),r=Re(`pluginCaptureNativeResource`),i=await e.captureIndependentResource(r,{owner:n,role:`owner`}),a=createPluginCaptureResourceClient(i.port,i.retainBrokerUntilProcessExit),s=/* @__PURE__ */ new Set,c=!1,l,closeWhenReleased=()=>c&&!s.size?(d(),l??=i.close(),l):Promise.resolve(),d=subscribePluginNativeLoads(e=>{a.request({type:`loaded`,filename:e}).catch(e=>process.emitWarning(String(e)))});return{descriptor:e.captureResource(r,Fn,{owner:n,role:`execution`},()=>{let{port1:e,port2:n}=new ht,receive=n=>{let r=n.root.id;s.add(r);let i,c,dispose=()=>i??=(async()=>{let e=[];try{await c}catch(t){e.push(t)}try{await a.request({type:`release-native`,rootId:r}),s.delete(r),await closeWhenReleased()}catch(t){e.push(t)}u(e,`Plugin native capture retirement failed`)})(),l={directory:n.root.directory,commit(){return c??=a.request({type:`commit-native`,rootId:r}).then(()=>{}),c.catch(()=>{}),c},dispose(){dispose().catch(e=>process.emitWarning(String(e)))},disposeAsync:dispose},d;try{if(!t)throw Error(`Plugin capture owner has no native allocation consumer`);d={id:n.id,ok:!0,root:t.native(n.captureId,l)}}catch(e){s.delete(r),d={id:n.id,ok:!1,error:Ee(e)}}e.postMessage(d)};return e.on(`message`,receive),e.unref(),{port:n,service(){for(;;){let t=yt(e);if(!t)return;receive(t.message)}},dispose(){e.close(),n.close()}}}),async createSource(e,t,n){let{root:r}=await a.request({type:`source`,captureId:e,storage:t,prefix:n});if(!r)throw Error(`Plugin capture owner returned no source root`);return r},async copyRecovery(e,t){let{root:n,copiedBytes:r}=await a.request({type:`recovery`,captureId:e,input:t});if(!n||r===void 0)throw Error(`Plugin capture owner returned no recovery source`);return{root:n,copiedBytes:r}},releaseSource:e=>a.request({type:`release-source`,captureId:e}).then(()=>{}),async close(){c=!0,await closeWhenReleased()}}}function resolveBundledSharedModule(e,t,n,r){if(!e||!(r.startsWith(`.`)||r.startsWith(`file:`)||Y.isAbsolute(r)))return;let i=r.startsWith(`file:`)?X(r):Y.resolve(Y.dirname(n),r);if(!U(t,i))return;let a=Y.relative(t,i);if(!(a.split(Y.sep).includes(`node_modules`)||e.ownedPaths.some(e=>U(Y.resolve(t,e),i))))return Y.resolve(e.hostRoot,a)}function bundledSharedModuleResolver(e,t){return e?(n,r)=>resolveBundledSharedModule(e,t,n,r):void 0}let Rn,zn;const createJiti=(...e)=>{if(!Rn){let e=globalThis.openclawStandaloneLoadJitiFactory;if(e)Rn=e();else{let e=qt(`jiti`,new URL(import.meta.url),/* @__PURE__ */ new Set([`node`,`require`]));Rn=pt(import.meta.url)(X(e)).createJiti}}let t=Rn(...e),n=t.options.transform;return n&&!e[1]?.transform&&(t.options.transform=e=>{let t=Error.prepareStackTrace;try{zn&&(Error.prepareStackTrace=zn);let t=n(e);return zn=Error.prepareStackTrace,t.error instanceof Error&&t.error.stack,t}finally{Error.prepareStackTrace=t}}),t},Bn=/\.(c|m)?j(sx?)$/,Vn=/node_modules\/(?:typescript|jiti)\//;function typescriptSibling(e,t,n){if(!(!Y.isAbsolute(t)||!Bn.test(t)||n.tsconfigPaths||Object.keys(n.alias??{}).length||n.nativeModules?.length||Vn.test(t.replaceAll(`\\`,`/`))||q.existsSync(t)))try{let r=t.replace(Bn,`.$1t$2`),i=n.extensions??[],a=i.find(e=>e!==`.js`);if(!a||!q.statSync(r,{throwIfNoEntry:!1})?.isFile())return;let s=pt(e),c=Object.keys(s.extensions);return[...i,...c,...c.map(e=>a+e)].some(e=>q.existsSync(t+e))?void 0:s.resolve(r)}catch{return}}function createPluginCaptureResolver(e){let t,n=/* @__PURE__ */ new Map,get=(r,i=!1)=>{if(t||(t=createJiti(r,{...e,fsCache:!1,moduleCache:!1,tryNative:!1}),n.set(t.options.tsconfigPaths?r:Y.dirname(r),t)),!t.options.tsconfigPaths&&!i)return t;let a=t.options.tsconfigPaths?r:Y.dirname(r),s=n.get(a);return s||(s=createJiti(r,t.options),n.set(a,s)),s};return{get,clear(){t=void 0,n.clear()},resolve(e,t,n){let r=get(e).options,i=!!(r.tsconfigPaths||Object.keys(r.alias??{}).length||r.nativeModules?.length||Vn.test(e.replaceAll(`\\`,`/`))),a=!i&&t.startsWith(`.`)&&!/[?#]/.test(t)?Y.resolve(Y.dirname(e),t):t,s=get(e,i||!Y.isAbsolute(a));return s.esmResolve(typescriptSibling(e,a,s.options)??a,{try:!0,parentURL:Z(e),conditions:[...n]})}}}const Hn=new St;function createPluginGenerationMetrics(){return{captures:0,captureReuse:0,packageFiles:0,dependencyFiles:0,originalBytes:0,copiedBytes:0,receiptPasses:0,receiptFileReads:0,receiptReadBytes:0,hashReadBytes:0,workerMs:0,hostMs:0}}function withPluginGenerationMetrics(e,t){return Hn.run(e,t)}function getPluginGenerationMetrics(){return Hn.getStore()}const Un=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/u;function isGitRuntimeStagingName(e){let t=e.lastIndexOf(`.openclaw-update-`);return t>0&&Un.test(e.slice(t+17))}const isPluginSourceEntry=e=>e!==`node_modules`&&e!==`.git`&&!isGitRuntimeStagingName(e);function readPluginCapturedCode(e,t=!1){try{return q.readFileSync(e,`utf8`)}catch(e){throw t&&Ve(e,`EISDIR`)?j(e):x(e)}}function realpathPluginSource(e,t=!0){return v(()=>q.realpathSync(e),t)}function inspectPluginCaptureSource(e,t,n,r,i){let a=realpathPluginSource(n?.path??e,!n);if(!U(n?.boundary??t,a)&&!r(e,a))throw D(`Standalone plugin input leaves its source directory`,!n);if(!(!n&&i&&U(i,a)))return{real:a,directory:v(()=>q.statSync(a),!n).isDirectory()}}function createPluginSourceDirectoryCapture(e){let t=/* @__PURE__ */ new Set;return function*(n,r,i,a,s){if(a?.has(r))throw D(`Standalone plugin input contains a directory cycle`,s);if(!t.has(i)){let c=a??/* @__PURE__ */ new Set;c.add(r),t.add(i);for(let t of v(()=>q.readdirSync(r),s).toSorted())isPluginSourceEntry(t)&&(yield*e(Y.join(n,t),c));c.delete(r),t.delete(i)}}}const Wn=Buffer.allocUnsafe(65536),pluginSourceStatIdentity=(e,t=e)=>`${t.dev}:${t.ino}:${e.mode}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,pluginSourceIdentityChangedOnlyByCtime=(e,t)=>e.slice(0,e.lastIndexOf(`:`))===t.slice(0,t.lastIndexOf(`:`));function withPluginSourceFile(e,t,n,r=de,i=!1){let a=v(()=>r({absolutePath:e,rootPath:t,boundaryLabel:`plugin build source`,rejectHardlinks:!1}),i);if(!a.ok){let t=Error(`Cannot capture plugin source ${e}`,{cause:a.error});throw i?j(t):t}try{return v(()=>n(a.fd),!1)}finally{v(()=>q.closeSync(a.fd),!1)}}function isPluginNativeExecutable(e,t){return withPluginSourceFile(e,t,isPluginNativeDescriptor)}function isPluginWasmModule(e,t){return withPluginSourceFile(e,t,e=>q.readSync(e,Wn,0,4,0)===4&&Wn.readUInt32BE(0)===6386541)}function isPluginNativeDescriptor(e){if(q.readSync(e,Wn,0,4,0)!==4)return!1;let t=Wn.readUInt32BE(0);return Wn.readUInt16BE(0)===19802||[2135247942,4277009102,4277009103,3472551422,3489328638,3405691582,3199925962].includes(t)}function resolveNativeCopySource(e,t){if(process.platform!==`win32`)return{rootPath:e,absolutePath:t};let n=q.realpathSync.native(e),r=Y.relative(e,t);return n===e||r.startsWith(`..`)||Y.isAbsolute(r)?{rootPath:e,absolutePath:t}:{rootPath:n,absolutePath:Y.join(n,r)}}function copyPluginSourceFile(e,n,r,i={}){return withPluginSourceFile(e,n,s=>{let l=q.fstatSync(s,{bigint:!0}),u=i.expectedSourceIdentity;if(u&&(l.dev!==u.dev||l.ino!==u.ino))throw Error(`Native plugin artifact changed during admission`);try{try{var d=_usingCtx();let t=getPluginGenerationMetrics(),a=i.preserveSourceMode?Number(l.mode&511n):384|Number(l.mode&64n);if(l.size<=BigInt(65536)&&!/\.(?:node|so|dylib|dll)$/iu.test(e)&&!isPluginNativeDescriptor(s)&&q.realpathSync.native(Y.dirname(r))===Y.dirname(r))try{var f=_usingCtx();let e=i.hashCopiedContent,n=f.u(Ut(r,{mode:384})),c=q.fstatSync(n.fd,{bigint:!0}),u=Bt(s,n.fd,{maxBytes:Number(l.size)});if(u!==Number(l.size))throw new Kt(`path-mismatch`,`Plugin source changed while copying`);t&&(t.copiedBytes+=u),q.fchmodSync(n.fd,a);let d=q.lstatSync(r,{bigint:!0}),p=q.fstatSync(n.fd,{bigint:!0});if(!d.isFile()||d.nlink!==1n||d.dev!==c.dev||d.ino!==c.ino||!p.isFile()||p.nlink!==1n||p.dev!==c.dev||p.ino!==c.ino)throw new Kt(`path-mismatch`,`Plugin capture destination changed during copying`);return e?{...hashPluginSourceDescriptor(n.fd),sourceIdentity:pluginSourceStatIdentity(l)}:void 0}catch(e){f.e=e}finally{f.d()}let c=d.u((i.copyFile??Vt)({source:resolveNativeCopySource(n,e),destination:{rootPath:Y.dirname(r),absolutePath:r},expectedSourceIdentity:{dev:l.dev,ino:l.ino},clone:`auto`,maxBytes:Number(l.size),mode:a,sourceHardlinks:`allow`}));return t&&(t.copiedBytes+=c.bytes),i.hashCopiedContent?{...hashPluginSourceDescriptor(c.fd),sourceIdentity:pluginSourceStatIdentity(l,c.sourceIdentity)}:void 0}catch(e){d.e=e}finally{d.d()}}catch(e){throw e instanceof Kt&&t(e,a).some(e=>c(e)===`ENOSPC`)?Object.assign(Error(lt(e),{cause:e}),{code:`ENOSPC`}):e instanceof Kt&&e.code===`too-large`?Error(`Plugin source changed while preparing its reload; retry after the edit finishes.`,{cause:e}):e}},i.openFile,i.preserveSourceMode!==!0)}function linkPluginSourceFile(e,t,n){return withPluginSourceFile(e,t,r=>{let i=q.fstatSync(r,{bigint:!0});q.linkSync(e,n);let a=q.statSync(n,{bigint:!0});return a.dev!==i.dev||a.ino!==i.ino?(q.unlinkSync(n),copyPluginSourceFile(e,t,n,{expectedSourceIdentity:i}),!1):!0})}function hashPluginSourceFile(e,t,n,r,i=de,a){return withPluginSourceFile(e,t,e=>hashPluginSourceDescriptor(e,n,r,a),i)}function hashPluginSourceDescriptor(e,t,n,r){let i=n?void 0:wt(`sha256`),a=n?.sizeBytes??q.fstatSync(e).size;t?.update(String(a)).update(`\0`);let s=0;for(;;){let n=q.readSync(e,Wn,0,Math.min(Wn.length,a-s+1),s);if(s+=n,n===0||s>a)break;let c=Wn.subarray(0,n);i?.update(c),t?.update(c),r?.(c)}let c=getPluginGenerationMetrics();if(c&&(c.hashReadBytes+=s),s!==a)throw Error(`Plugin source changed while preparing its reload; retry after the edit finishes.`);return n??{contentHash:i.digest(`hex`),sizeBytes:a}}function readPluginSourceDirectory(e,t=!0){return v(()=>q.readdirSync(e),t).filter(isPluginSourceEntry).toSorted()}function linkPluginGenerationDependency(e,t,n){let r=q.lstatSync(e,{throwIfNoEntry:!1});if(n&&(r||!q.lstatSync(n).isDirectory()))throw Error(`Pending dependency link does not own an empty destination: ${e}`);if(r&&!r.isSymbolicLink()||r&&Y.resolve(Y.dirname(e),q.readlinkSync(e))===t&&q.statSync(e,{throwIfNoEntry:!1}))return!1;if(v(()=>q.mkdirSync(Y.dirname(e),{recursive:!0,mode:448})),process.platform===`win32`){if(r){if(!q.lstatSync(e).isSymbolicLink())throw Error(`Dependency link became a real entry: ${e}`);v(()=>q.unlinkSync(e))}v(()=>q.symlinkSync(t,e,`junction`))}else{let n=`${e}.${Et()}.tmp`;try{v(()=>{q.symlinkSync(Y.relative(Y.dirname(e),t),n,`junction`),q.renameSync(n,e)})}finally{q.rmSync(n,{force:!0})}}let normalize=e=>process.platform===`win32`?te(e):e;if(!q.lstatSync(e).isSymbolicLink()||(n?normalize(Y.resolve(Y.dirname(e),q.readlinkSync(e)))!==normalize(Y.resolve(t))||normalize(q.realpathSync(n))!==normalize(n):q.realpathSync(e)!==q.realpathSync(t)))throw Error(`Dependency link does not resolve to its captured target: ${e}`);return r&&process.emitWarning(`Replacing plugin dependency link ${e}`),!0}function linkPluginGenerationHostModule(e,t){if(q.lstatSync(e,{throwIfNoEntry:!1}))return!1;q.mkdirSync(Y.dirname(e),{recursive:!0,mode:448});try{return q.symlinkSync(t,e,`file`),!0}catch(e){if(![`EPERM`,`EACCES`,`ENOSYS`,`ENOTSUP`].some(t=>Ve(e,t)))throw e;return!1}}function linkBundledSharedModule(e,t,n,r){linkPluginGenerationHostModule(e,t)&&n.add(e),q.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()&&r.add(e)}function createPluginSourceLinkCapture(){let e=/* @__PURE__ */ new Set;return{defer(t,n,r,i,a=!0){return!i.isSymbolicLink()||U(n,v(()=>q.realpathSync(t),a))?!1:(e.add(r),!0)},contains:t=>[...e].some(e=>U(e,t))}}function createPluginGenerationFileCapture({boundary:e,destination:t,directory:n,packageKind:r,outputRoot:i,capturedPaths:a,capturedDirectories:s,hostModuleLinks:c,originalSources:l,hardlinkedSources:u,sourceCapture:d,sourceLinks:f,deferExternalLinks:p,nativeAdmission:m,sourceOnly:h=!1,retainedSnapshotSource:g=!1,receipt:_,retained:y,sourceFacts:b,executionAliases:x,executionSources:S,onPackageMetadata:C}){let{additions:w}=d,T=/* @__PURE__ */ new Set;function*copy(d,E,O,k,A,j){yield;let M=getPluginGenerationMetrics();if(a.get(Y.resolve(d))===E||c?.has(E))return;let N=m.resolvePreparedSource(d),P=N?.path??d,F=N?.boundary??e,I=!N&&A?j??v(()=>q.lstatSync(P,{bigint:!0})):void 0,L=I&&!I.isSymbolicLink(),R=L?Y.join(A,Y.basename(P)):v(()=>q.realpathSync(P),!N),z=m.isRetainedReference(d,R);if(!U(F,R)&&!z)throw D(`Plugin source link leaves its package: ${Y.relative(e,d)}. Declare shared code as a package dependency.`,!N);if(!N&&i&&U(i,R))return;let B=L?I:v(()=>q.statSync(R,{bigint:!0}),!N),V=a.get(R);if(a.set(Y.resolve(d),E),l.set(E,Y.resolve(d)),a.set(E,E),a.has(R)||a.set(R,E),_.marker(`${B.isDirectory()?`directory`:`file`}\0${Y.relative(t,E)}\0`),B.isDirectory()){if(s.add(E),T.has(R))throw D(`Plugin source contains a directory cycle: ${d}`,!N);T.add(R),q.mkdirSync(E,{recursive:!0,mode:448});for(let e of readPluginSourceDirectory(R,!N)){let t=Y.join(d,e),n=Y.join(P,e),r=p&&!m.isRetainedReference(t)?v(()=>q.lstatSync(n,{bigint:!0}),!N):void 0;!r||!f.defer(n,F,t,r,!N)?yield*copy(t,Y.join(E,e),O,k,R,r):yield}T.delete(R)}else if(B.isFile()){M&&M[r===`package`?`packageFiles`:`dependencyFiles`]++,B.nlink>1n&&u.add(E),A||q.mkdirSync(Y.dirname(E),{recursive:!0,mode:448}),w.add(E);let e=y?.files.get(Y.relative(n,E)),t=y?.source.native?.references.has(E);!M||g||N||V||e&&!t||(M.originalBytes+=Number(B.size)),t&&q.unlinkSync(E);let i=h?void 0:m.materialize(R,F,E,B,d),a;!i&&e&&!t?a=e:i||(a=copyPluginSourceFile(V??R,V?n:F,E,{hashCopiedContent:!0,copyFile:O,openFile:k,...V?{preserveSourceMode:!0}:{}}));let s=Y.relative(n,E),c=!h&&/\.(?:[cm]?tsx?|jsx)$/u.test(E)&&!/\.d\.[cm]?ts$/u.test(E);if(_.file({target:i?.path??E,boundary:i?.boundary??n,sizeBytes:Number(B.size),native:i!==void 0,onSource:c&&!S.has(s)?e=>S.set(s,e):void 0,prepared:i?.content??a,onContent:e=>{i?.record(e),b?.set(Y.relative(n,E),{...e,mode:384|Number(B.mode&64n)})}},k),c&&!x.has(s)){let e=Y.join(`.compiled`,`${s}.js`),t=Y.join(n,e);q.mkdirSync(Y.dirname(t),{recursive:!0,mode:448}),q.writeFileSync(t,``,{flag:`wx`,mode:384}),x.set(s,e)}Y.basename(E)===`package.json`&&C(d,E)}else throw D(`Plugin build input is not a regular file: ${d}`,!N)}return Object.assign((e,t)=>{try{var n=_usingCtx();let r=n.u(Wt()),i=n.u(Gt()),a=copy(e,t,r.copyFile.bind(r),i.openFile.bind(i));for(;!a.next().done;);}catch(e){n.e=e}finally{n.d()}},{*steps(e,t){let n,r,i=copy(e,t,(...e)=>n(...e),(...e)=>r(...e));try{let e=!1;for(;!e;){try{var a=_usingCtx();let t=a.u(Wt()),s=a.u(Gt());n=t.copyFile.bind(t),r=s.openFile.bind(s);for(let t=0;t<32;t++)if(i.next().done){e=!0;break}}catch(e){a.e=e}finally{a.d()}e||(yield)}}finally{i.return()}}})}function drainPluginGenerationSteps(e){let t=e.next();for(;!t.done;)t=e.next();return t.value}function createPluginGenerationReceipt(e){let t=[],n,publishContent=(e,t)=>{if(t.sizeBytes!==e.sizeBytes)throw Error(`Plugin source changed while preparing its reload; retry after the edit finishes.`);e.content||(e.content=t,e.onContent(t))},readContent=(e,t,n=e.content,r)=>{let i=e.onSource?new Jt(`utf8`):void 0,a=``,s=hashPluginSourceFile(e.target,e.boundary,t,e.native?e.content:void 0,r,i?e=>{a+=i.write(e)}:void 0);if(!e.native&&n&&s.contentHash!==n.contentHash)throw Error(`Plugin source changed while preparing its reload; retry after the edit finishes.`);let c=getPluginGenerationMetrics();c&&(c.receiptFileReads++,c.receiptReadBytes+=s.sizeBytes),publishContent(e,s),i&&e.onSource(a+i.end())},inputSignature=()=>{if(t.some(e=>typeof e!=`string`&&!e.content))return;let e=wt(`sha256`);for(let n of t)e.update(JSON.stringify(typeof n==`string`?[`marker`,n]:[`file`,n.sizeBytes,n.content.contentHash]));return e.digest(`hex`)};return{marker(e){n||t.push(e)},file(e,r){let{prepared:i,...a}=e,s=a;i?n&&!s.native?readContent(s,void 0,i,r):publishContent(s,i):(!s.native||n)&&readContent(s,void 0,void 0,r),n||t.push(s)},finish(){return drainPluginGenerationSteps(this.finishSteps())},*finishSteps(){if(n)return n;let r=getPluginGenerationMetrics();r&&r.receiptPasses++;let i=inputSignature(),a=i!==void 0&&e?.signature===i?void 0:wt(`sha256`);for(let e=0;e<t.length;e+=32){try{var s=_usingCtx();let n=s.u(Gt()),r=n.openFile.bind(n);for(let n of t.slice(e,e+32))typeof n==`string`?a?.update(n):!a&&n.content&&n.native||readContent(n,a,n.content,r)}catch(e){s.e=e}finally{s.d()}yield}return n={signature:i??inputSignature(),sourceDigest:a?a.digest(`hex`):e.sourceDigest},t.length=0,n}}}const Gn=new St,Kn=m(Symbol.for(`openclaw.pluginSourceCaptureOwnedRoots`),()=>/* @__PURE__ */ new Set);function retainPluginSourceCaptureRoot(e){let t=q.realpathSync(e);if(Kn.has(t))throw Error(`Plugin source capture root is already owned: ${t}`);Kn.add(t);let n=!1;return()=>{n||(n=!0,Kn.delete(t))}}function getPluginSourceCaptureStorage(){return L()?.sourceCaptureStorage}function resolvePluginSourceCaptureStorage(e,t){let n=e===void 0?getPluginSourceCaptureStorage():void 0;return Object.freeze({stateDir:Y.resolve(e??n?.stateDir??ne()),placement:t??n?.placement??`state`})}function withPluginSourceCaptureStorage(e,t){let n=L();return w(h({...n,sourceCaptureStorage:resolvePluginSourceCaptureStorage(e.stateDir,e.placement)},n),t)}const qn=m(Symbol.for(`openclaw.pluginSourceCaptureMaintenance`),()=>new St);function sha256Hex(e){return Tt(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=Y.resolve(e);for(;;)try{return q.statSync(t).isDirectory()?t:Y.dirname(t)}catch{let e=Y.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=q.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}const Jn=`openclaw-plugin-build-`,Yn=`snapshot-v1-`,Xn=`${Yn}staging-`;function resolvePluginSourceCapturesDirectory(e){return Y.join(e,`tmp`,`plugin-captures`)}function resolvePluginSourceCaptureFallbackPrefix(e){return`openclaw-plugin-captures-${sha256HexPrefixCore(dt(e),32)}-`}async function resolvePluginSourceCaptureFallbackPrefixAsync(e){return`openclaw-plugin-captures-${sha256HexPrefixCore(await ut(e),32)}-`}function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}function assertPluginSourceCaptureDiskSpace(e){let t=tryReadDiskSpace(e);if(t&&t.availableBytes<536870912)throw D(`Plugin source capture refused: ${t.availableBytes} bytes available at ${t.checkedPath}; at least 512 MiB required. Free space on this volume and retry the plugin load.`)}function mkdtempPluginCaptureSync(e){return assertPluginSourceCaptureDiskSpace(Y.dirname(e)),process.platform===`win32`?te(q.mkdtempSync(Y.win32.toNamespacedPath(Y.win32.resolve(e)))):q.mkdtempSync(e)}const Zn=36e5,{instances:Qn,ownedRoots:$n,reclaimInstance:er,reclaimPluginCaptureSweep:tr,isPluginSourceCaptureRetained:nr,retainLoadedPluginSourceCapture:rr,retainPluginNativeCapturePath:ir,sweeps:ar}=m(Symbol.for(`openclaw.pluginSourceCaptureInstances`),()=>{let e=Kn,t=createPluginNativeCaptureCustody(e);return oe(()=>{for(let[e,t]of Qn)retireInstanceForExit(e,t)}),{instances:/* @__PURE__ */ new Map,ownedRoots:e,...t,sweeps:/* @__PURE__ */ new Map}});function retireInstanceForExit(e,t){try{let n=retireInstance(e,t);n&&removeInstanceSync(n,t.pendingNative)}catch(e){process.stderr.write(`Plugin source capture exit cleanup failed: ${String(e)}\n`)}}function retireInstance(e,t){if(t.root&&rr(t.root)){t.references.clear(),scheduleCaptureCleanup(e,t);return}t.closing=!0;let n=t.root;try{t.token?.(!0)}catch(e){Be(e),t.token?.(),n=void 0}return t.root&&$n.delete(t.root),t.references.clear(),Qn.get(e)===t&&Qn.delete(e),t.releaseSignalExit?.(),scheduleCaptureCleanup(e,t),n}function warn(e){process.emitWarning(`Plugin source capture cleanup: ${String(e)}`)}function removeInstanceSync(e,t=[]){if(rr(e))return;q.rmSync(Y.join(e,`captures`),{recursive:!0,force:!0});for(let e of t)q.rmSync(e,{recursive:!0,force:!0});let n=Y.join(e,`native`);q.existsSync(n)&&q.readdirSync(n).length!==0||q.rmSync(e,{recursive:!0,force:!0})}async function reclaimInstances(e,t,n=!1,r,i,a){let s;try{s=await J.readdir(e,{withFileTypes:!0})}catch(e){Be(e);return}if(s.length===0)return;let c=Date.now()-Zn,lstatIfPresent=e=>J.lstat(e).catch(Be);for(let l of s){let s=!n&&!i&&l.name.startsWith(`snapshot-v1-staging-`);if(!l.isDirectory()||l.name.startsWith(`snapshot-v1-`)&&!s||n&&!isLegacyPluginSourceCaptureName(l.name)||i&&!l.name.startsWith(i))continue;let u=Y.join(e,l.name);try{let e=await J.lstat(u),t=n?Math.max(e.mtimeMs,e.ctimeMs,e.birthtimeMs):e.mtimeMs;if(!e.isDirectory()||t>c&&!r?.startup)continue;let l=await J.realpath(u);if($n.has(l)||rr(l))continue;let d=Y.join(l,tt[0]),f=await lstatIfPresent(Y.join(l,`native`)),p=await lstatIfPresent(d);if(n&&p)continue;if(!p){if(s||i||t>c||f)continue;let n={directory:l,identity:{dev:e.dev,ino:e.ino,uid:e.uid},kind:`legacy`};a?a(n):(await r?.assertCurrent(),await reclaimLegacyPluginCapture(n));continue}a?a({directory:l,identity:{dev:e.dev,ino:e.ino,uid:e.uid},kind:`managed`}):await er(l,e,r)}catch(e){!Ve(e,`ENOENT`)&&!Ie(e)&&t(e)}}}function sweepPluginSourceCaptureDirectories(e){let t=Y.resolve(resolvePluginSourceCapturesDirectory(e)),n=ar.get(t);if(!n){let r=0,i,recordFailure=e=>{r++===0&&(i=e)},a=[],collect=e=>a.push(e);n=reclaimInstances(t,recordFailure,!1,void 0,void 0,collect).catch(recordFailure).then(async()=>reclaimInstances(jt(),recordFailure,!1,void 0,await resolvePluginSourceCaptureFallbackPrefixAsync(e),collect)).catch(recordFailure).then(async()=>{let t=/* @__PURE__ */ new Set;for(let n of[Y.join(e,`tmp`),jt()])try{let e=await J.realpath(n);t.has(e)||(t.add(e),await reclaimInstances(e,recordFailure,!0,void 0,void 0,collect))}catch(e){Ve(e,`ENOENT`)||recordFailure(e)}}).then(()=>tr(a)).then(e=>{e.failures>0&&(i??=e.firstFailure,r+=e.failures)}).catch(recordFailure).then(()=>{r!==0&&warn(`${r} cleanup failure(s) in ${t}; will retry. First: ${lt(i)}`)}).finally(()=>ar.delete(t)),ar.set(t,n)}return n}function createCaptureDirectory(e,t,n=`captures`){let{stateDir:r,placement:i}=e.storage;if(e.root){let r=Y.join(e.root,n);try{return mkdtempPluginCaptureSync(Y.join(r,t))}catch(e){return Be(e),q.mkdirSync(r,{mode:448}),mkdtempPluginCaptureSync(Y.join(r,t))}}let prepare=i=>{let a,s;try{if(i)a=mkdtempPluginCaptureSync(Y.join(jt(),resolvePluginSourceCaptureFallbackPrefix(r)));else{let t=resolvePluginSourceCapturesDirectory(r);q.mkdirSync(t,{recursive:!0,mode:448}),e.managedRoot=q.realpathSync.native(t);let n=Y.join(e.managedRoot,Et());q.mkdirSync(n,{mode:448}),a=n}let c=q.realpathSync.native(a);s=nt(c,`create`);let l=Y.join(c,n);q.mkdirSync(l,{mode:448});let u=mkdtempPluginCaptureSync(Y.join(l,t));return e.root=c,e.token=s,$n.add(c),u}catch(t){try{s?.(!0)}catch(n){throw e.root=a,e.token=s,e.closing=!0,a&&$n.add(a),Se([t,n],`Plugin source preparation cleanup failed`,t)}if(a)try{removeInstanceSync(a)}catch(e){warn(e)}throw t}};if(i===`temporary`)return prepare(!0);try{return prepare(!1)}catch(t){if(e.closing)throw t;return warn(t),prepare(!0)}}function scheduleCaptureCleanup(e,t){let n=[...t.references].findLast(e=>e.scheduler&&!e.scheduler.signal.aborted)?.scheduler??void 0;if(t.scheduler===n||(t.scheduler=n,t.cleanupScope?.beginClose(),t.cleanupScope=void 0,!n||t.storage.placement===`temporary`))return;let r=n.scope();t.cleanupScope=r,r.signal.addEventListener(`abort`,()=>scheduleCaptureCleanup(e,t),{once:!0}),N(()=>r.schedule({id:`plugin-source-captures:${e}`,delayMs:Zn,everyMs:Zn,run:()=>sweepPluginSourceCaptureDirectories(t.storage.stateDir)}))}function retainPluginSourceCaptureInstance(e,t,n=`source`){let r=process.env.TMPDIR?.trim(),i=resolvePluginSourceCaptureStorage(e,n===`source`&&process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`&&r&&Y.isAbsolute(r)?`temporary`:t),a=JSON.stringify([i.stateDir,i.placement]),s=qn.getStore(),c=s?.scheduler;c?.signal.throwIfAborted();let l=Qn.get(a);if(l?.closing)throw Error(`Plugin source instance cleanup is incomplete; retry cleanup before creating captures`);if(!l){l={storage:i,references:/* @__PURE__ */ new Set,pendingNative:/* @__PURE__ */ new Set},Qn.set(a,l);let e=l;e.releaseSignalExit=ce(async()=>retireInstanceForExit(a,e)),i.placement===`state`&&(s?s.run(()=>sweepPluginSourceCaptureDirectories(i.stateDir)):sweepPluginSourceCaptureDirectories(i.stateDir))}let u={scheduler:c??null};l.references.add(u),scheduleCaptureCleanup(a,l);let d=l,f=!1,retire=()=>{if(f)return;if(d.references.size>1){d.references.delete(u),scheduleCaptureCleanup(a,d),f=!0;return}let e=retireInstance(a,d);return f=!0,e};return{startMaintenance(e){if(f||d.closing)throw Error(`Plugin source instance has been released`);return e.signal.throwIfAborted(),u.scheduler=e,scheduleCaptureCleanup(a,d),i.placement===`temporary`?Promise.resolve():sweepPluginSourceCaptureDirectories(i.stateDir)},get managedRoot(){return d.managedRoot},createDirectory(e=Jn){if(f||d.closing)throw Error(`Plugin source instance has been released`);return createCaptureDirectory(d,e)},createNativeDirectory(){if(f||d.closing)throw Error(`Plugin source instance has been released`);let e=createCaptureDirectory(d,`admission-`,`native`);return d.pendingNative.add(e),{directory:e,commit:()=>d.pendingNative.delete(e)}},release(){let e=retire();e&&removeInstanceSync(e,d.pendingNative)},async releaseAsync(){let e=d.cleanupScope,t=retire();if(e!==d.cleanupScope&&await e?.stop(),d.references.size===0&&await ar.get(Y.resolve(resolvePluginSourceCapturesDirectory(i.stateDir))),t)try{await J.rm(Y.join(t,`captures`),{recursive:!0,force:!0});for(let e of d.pendingNative)await J.rm(e,{recursive:!0,force:!0});(await J.readdir(Y.join(t,`native`)).catch(e=>(Be(e),[]))).length===0&&await J.rm(t,{recursive:!0,force:!0})}catch(e){warn(e)}}}}const or=ue(()=>import(`./plugin-preparation-temp-artifact-cleanup-qOjvsc_h.mjs`)),prepareTemporaryArtifactCleanup=()=>void or().catch(()=>{});function createPluginNativeCaptureRoot(e,t){let n=retainPluginSourceCaptureInstance(e,t,`native`);try{let e=n.createNativeDirectory();prepareTemporaryArtifactCleanup();let t=!1,r=!1;return{directory:e.directory,commit(){if(r)throw Error(`Plugin native capture has been disposed`);e.commit(),t=!0},dispose(){r||(!t&&!rr(e.directory)&&q.rmSync(e.directory,{recursive:!0,force:!0}),r=!0,n.release())},async disposeAsync(){let{removeTemporaryArtifacts:i}=await or();r||(!t&&!rr(e.directory)&&await i(e.directory,`Plugin native capture`),r=!0,await n.releaseAsync())}}}catch(e){throw n.release(),e}}const sr=/* @__PURE__ */ new Map;m(Symbol.for(`openclaw.bunRuntimeOnResolveProbe`),()=>({tested:!1,supported:!1})),m(Symbol.for(`openclaw.capturedModuleResolvers`),()=>({installed:!1,loaderInstalled:!1,resolving:!1,owners:/* @__PURE__ */ new Set}));function clearPluginSourceCaptureModuleCache(e){let t=Z(e+Y.sep).href,n=pt(import.meta.url).cache;for(let r of Object.keys(n))(r.startsWith(t)||Y.isAbsolute(r)&&U(e,r))&&delete n[r];for(let t of sr.keys())U(e,t)&&sr.delete(t)}function createPluginSourceCaptureState(e){let{directory:t}=e,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=!1,acquire=t=>{if(e.assertAvailable?.(),i)throw Error(`Plugin module capture has been disposed`);try{return{value:t(),additions:[...n]}}catch(e){for(let t of n)r.set(t,e);throw e}finally{n.clear()}},assertModuleAvailable=t=>{if(e.assertAvailable?.(),r.has(t))throw r.get(t)},beginDisposal=()=>{i=!0,clearPluginSourceCaptureModuleCache(t),r.clear()};return{additions:n,capture:acquire,assertModuleAvailable,directory:t,outputRoot:e.outputRoot,linkHost:e=>{let n=Y.join(t,`node_modules`);q.mkdirSync(n,{recursive:!0,mode:448}),q.symlinkSync(e,Y.join(n,`openclaw`),`junction`)},dispose:()=>{beginDisposal(),e.dispose()},disposeAsync:async()=>{beginDisposal(),await e.disposeAsync()}}}const readPackageManifest=(e,t=!1)=>{let n=v(()=>q.readFileSync(e,`utf8`),t);return v(()=>JSON.parse(n))};function createPluginDependencyResolver(e){let t=/* @__PURE__ */ new Map;return(n,r)=>{let i=`${Y.dirname(r)}\0${n}`;if(t.has(i))return t.get(i);for(let a of pt(r).resolve.paths(`${n}/`)??[]){let c=Y.join(a,n);if(q.existsSync(Y.join(c,`package.json`))){if(e&&U(e.root,r)&&!U(e.root,a)){let a=Y.join(resolvePluginModulePackageRoot(r),`package.json`);if(!pluginDependencyNames(q.existsSync(a)?s(readPackageManifest(a,!0)):void 0).has(n)){e.onUnresolvable(n,r),t.set(i,void 0);return}}let l={root:v(()=>q.realpathSync(c)),lookupDirectory:Y.dirname(a)};return t.set(i,l),l}}t.set(i,void 0)}}function createPluginDependencyLookup(e,t,n,r){let i=/* @__PURE__ */ new Map;return a=>{if(!a||a.startsWith(`.`)||Y.isAbsolute(a)||URL.canParse(a)||mt(a))return;let s=packageName(a);if(s===`openclaw`||s===`@openclaw/plugin-sdk`)return;if(a.startsWith(`#`)||t?.exports!=null&&t.name===s)return`package-map`;if(i.has(s))return i.get(s);let c=n(s,e);return c&&r(s,c),i.set(s,c!==void 0),c!==void 0}}function pluginDependencyNames(e){return/* @__PURE__ */ new Set([...Object.keys(e?.dependencies??{}),...Object.keys(e?.optionalDependencies??{}),...Object.keys(e?.peerDependencies??{})])}function createPluginNativeDependencyScopes(e,t){let n=/* @__PURE__ */ new Map;return(r,i)=>{let a=Y.dirname(r),s=n.get(a);if(!s){let c=[...pluginDependencyNames(i)].filter(e=>e!==`openclaw`&&e!==`@openclaw/plugin-sdk`);s={prepareDependencies:c.length?()=>{for(let n of c){let i=e(n,r);i&&t(n,i)}}:void 0},n.set(a,s)}return s}}function createPluginDependencyPlan(e){return{manifest:e,names:[...pluginDependencyNames(e)].toSorted()}}function capturePluginDependencies(e){let t=e.plan??(e.manifestFile?createPluginDependencyPlan(readPackageManifest(e.manifestFile,!0)):void 0),n=t?.manifest,r=[...(t?.names??[]).map(t=>({name:t,importer:Y.join(e.root,`package.json`)})),...[...e.references].flatMap(([e,t])=>[...t].toSorted().map(t=>({name:t,importer:e})))];for(let{name:i,importer:a}of r){if(i===`openclaw`||i===`@openclaw/plugin-sdk`)continue;let r=e.resolve(i,a);if(!r){if(!t||e.incidental||i in(s(n?.optionalDependencies)??{})||i in(s(n?.peerDependencies)??{}))continue;throw j(/* @__PURE__ */ Error(`Plugin dependency ${i} is missing from ${e.root}; install its dependencies and reload.`))}e.capture(i,r)}}function resolvePluginModulePackageRoot(e){let t=Y.dirname(e);for(;Y.basename(t)!==`node_modules`;){if(q.existsSync(Y.join(t,`package.json`)))return t;let e=Y.dirname(t);if(e===t)break;t=e}return Y.dirname(e)}const packageName=e=>e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0],importTargetNames=e=>[...pluginPackageTargets(e)].filter(e=>e&&!e.startsWith(`.`)&&!e.startsWith(`#`)&&!Y.isAbsolute(e)&&!mt(e)).map(packageName);function*pluginPackageTargets(e){if(typeof e==`string`)yield e;else if(e&&typeof e==`object`)for(let t of Object.values(e))yield*pluginPackageTargets(t)}const isPluginPackageFile=(e,t)=>U(e,t)&&!Y.relative(e,t).split(Y.sep).includes(`node_modules`);function isCapturedPathInside(e,t){return process.platform===`win32`?U(e,t):t===e||t.startsWith(e)&&(e.endsWith(`/`)||t.charCodeAt(e.length)===47)}function isCapturedPackageFile(e,t){return process.platform===`win32`?isPluginPackageFile(e,t):isCapturedPathInside(e,t)&&!/(?:^|\/)node_modules(?:\/|$)/u.test(t.slice(e.length))}function findPluginCapturedPackage(e,t,n){let r=process.platform===`win32`?t:Y.resolve(t);if(isCapturedPathInside(n,r))for(let t of e.values()){if(isCapturedPackageFile(t.capturedRoot,r))return{owner:t,root:t.capturedRoot};for(let e of t.links)if(isCapturedPackageFile(e,r))return{owner:t,root:e}}}function createPluginPackageMetadataCapture(e){let t=/* @__PURE__ */ new Map,getManifest=e=>{let n=t.get(e);return n.manifest===void 0&&(n.manifest=s(readPackageManifest(e))??{}),n.manifest??{}},inspectOptionalMetadata=e=>{let n=t.get(e);if(n.manifest===void 0)try{n.manifest=s(readPackageManifest(e))??null}catch(e){if(!(e instanceof SyntaxError))throw e;n.manifest=null}return n},n=/* @__PURE__ */ new Set,prepareNativeScopes=()=>{for(let t of n){n.delete(t);let r=inspectOptionalMetadata(t),i=r.manifest,a=e.packageForFile(t);if(!i||!a||(r.prepareAliases(i),a.state===`body`))continue;let c=e.sourceForCaptured(t),l=i.exports,u=l&&typeof l==`object`&&!Array.isArray(l)&&Object.keys(l).some(e=>e.startsWith(`.`))?s(l)??{}:{".":l},d=[...Object.entries(s(i.imports)??{}),...Object.entries(u)];for(let[n,r]of d)for(let i of pluginPackageTargets(r)){let r=a.sourceRoot,s=n.includes(`*`),{isRetainedReference:l,resolveSource:u}=e;if(!i.startsWith(`./`))continue;let d=Et(),f;try{f=X(new URL(s?i.replaceAll(`*`,d):i,Z(c)))}catch{continue}if(!U(r,f))continue;let p=f.split(d),m=p.length>1?RegExp(`^${He(p[0])}([\\s\\S]*)${p.slice(1).map(He).join(`\\1`)}$`,`i`):void 0,h=/* @__PURE__ */ new Set,visit=e=>{if(Y.relative(r,e).split(Y.sep).some(e=>e===`.git`||e===`node_modules`))return;let n=u?.(e),i=n?.path??e,s=v(()=>q.statSync(i,{throwIfNoEntry:!1}),!n);if(!s)return;let d=v(()=>q.realpathSync(i),!n);if(U(n?.boundary??r,d)||s.isFile()&&l?.(e,d)){if(s.isDirectory()){if(!m)return;if(h.has(d))throw D(`Plugin source contains a directory cycle: ${e}`,!n);h.add(d);for(let t of v(()=>q.readdirSync(i),!n).filter(isPluginSourceEntry).toSorted())visit(Y.join(e,t));h.delete(d)}else s.isFile()&&(!m||m.test(e))&&a.captureTarget(Y.join(Y.dirname(t),Y.relative(Y.dirname(c),e)))}};visit(m?Y.dirname(p[0]+`_`):f)}}};return{capturePackage(t,n,r){let{isRetainedReference:i,resolveSource:a}=e,s=Y.join(n,`package.json`);r(Y.join(t,`package.json`),s);let c=inspectOptionalMetadata(s).manifest;if(c&&c.exports==null){let e=typeof c.main==`string`&&c.main?c.main:void 0,s=e===void 0?[`./index`]:[`./${e}`,`./${e}/index`,`./index`],l=[...e===void 0?[]:[e],...s.flatMap(e=>[`.js`,`.json`,`.node`].map(t=>e+t))];for(let e of l){let s=new URL(e,Z(Y.join(t,`package.json`)));if(s.protocol!==`file:`)continue;let c=X(s),l=a?.(c),u=l?.path??c;if(U(t,c)&&v(()=>q.statSync(u,{throwIfNoEntry:!1}),!l)?.isFile()){let e=v(()=>q.realpathSync(u),!l);if(!U(l?.boundary??t,e)&&!i?.(c,e))continue;r(c,Y.join(n,Y.relative(t,c)));break}}}},record(r,i){if(t.has(r))return;let a=!1;t.set(r,{manifest:e.retainedManifest?.(r),prepareAliases(e){a||=(i(e),!0)}}),n.add(r)},snapshot(e){let n=/* @__PURE__ */ new Map;for(let[r,i]of t)i.manifest!==void 0&&n.set(Y.relative(e,r),i.manifest);return n},dependencyPlan(e){let n=t.get(e);return n.dependencyPlan??=createPluginDependencyPlan(getManifest(e))},get pending(){return n.size>0},prepare(e){e?.prepareDependencies&&(e.prepareDependencies(),delete e.prepareDependencies),prepareNativeScopes()},createScope({root:n,destination:r,boundary:i,copy:a,hasSource:s}){let c=/* @__PURE__ */ new Map,captureScopeMetadata=l=>{if(c.has(l))return c.get(l);let scope,u=Y.join(l,`package.json`);if(s(u)||q.existsSync(e.resolveSource?.(u)?.path??u)){let e=Y.join(r,Y.relative(n,u));a(u,e);let i;scope=()=>{if(!i){let n=t.get(e),r=getManifest(e);n.prepareAliases(r),i={source:u,manifest:r,aliases:new Set(importTargetNames(r.imports))}}return i}}else l!==i&&U(i,Y.dirname(l))&&(scope=captureScopeMetadata(Y.dirname(l)));return c.set(l,scope),scope};return{captureMetadata:captureScopeMetadata,resolve:e=>captureScopeMetadata(e)?.()}},clear(){t.clear(),n.clear()}}}function withPluginSourceCaptureDirectory(e,t,n){return Gn.run({directory:e,managedRoot:n},t)}function createPluginSourceCapture(){let e=Gn.getStore(),t=e===void 0?retainPluginSourceCaptureInstance():void 0,n,r;try{n=e===void 0?t.createDirectory():mkdtempPluginCaptureSync(Y.join(e.directory,Jn)),r=q.realpathSync.native(n),q.chmodSync(r,448)}catch(e){let r=[];try{n&&q.rmSync(n,{recursive:!0,force:!0})}catch(e){r.push(e)}try{t?.release()}catch(e){r.push(e)}throw r.length>0?Se([e,...r],`Plugin source capture setup and cleanup failed`,e):e}return createPluginSourceCaptureState({directory:r,outputRoot:e?.managedRoot??t?.managedRoot,dispose(){rr(r)||q.rmSync(r,{recursive:!0,force:!0}),t?.release()},async disposeAsync(){rr(r)||await J.rm(r,{recursive:!0,force:!0}),await t?.releaseAsync()}})}let cr;function parse(...e){if(!cr){let e=qt(`acorn`,new URL(import.meta.url),/* @__PURE__ */ new Set([`node`,`import`]));cr=pt(import.meta.url)(X(e))}return cr.parse(...e)}function capturedPluginModuleUrl(e,t,n){let r=Z(e);if(!n.includes(`require`)&&(t.startsWith(`.`)||t.startsWith(`file:`)||Y.isAbsolute(t))){let e=new URL(t,r);r.search=e.search,r.hash=e.hash}return r}function isPackageMapError(e,t){return e instanceof Error&&`code`in e&&e.code===t}function resolvePluginPackageMapTarget(e,t,n){let r;try{r=qt(e,Z(t),new Set(n))}catch(e){if(n.includes(`bun`)&&isPackageMapError(e,`ERR_INVALID_PACKAGE_TARGET`))return;if(!isPackageMapError(e,`ERR_MODULE_NOT_FOUND`))throw e;if(typeof e.url!=`string`)return;r=new URL(e.url)}return r.protocol===`file:`?r:void 0}function createPluginPackageMapReferences(){let e=/* @__PURE__ */ new Set,recordMissingTarget=t=>{e.add(Y.resolve(t))};return{recordMissingTarget,hasMissingTarget:t=>e.has(Y.resolve(t)),resolveReference(e,t,n){try{return qt(e,Z(t),new Set(n)).href}catch(e){if(isPackageMapError(e,`ERR_MODULE_NOT_FOUND`)&&typeof e.url==`string`){let t=new URL(e.url);t.protocol===`file:`&&recordMissingTarget(X(t))}return}}}}function staticString(e){if((e?.type===`Literal`||e?.type===`StringLiteral`)&&typeof e.value==`string`)return e.value;if(e?.type===`TemplateLiteral`&&e.expressions?.length===0)return e.quasis?.[0]?.value.cooked??void 0}function isAssignmentTarget(e){let t=e;for(let n=e.parentPath;n?.node;n=n.parentPath){switch(n.node.type){case`AssignmentExpression`:case`AssignmentPattern`:case`ForInStatement`:case`ForOfStatement`:return t.key===`left`;case`UpdateExpression`:return!0;case`ObjectProperty`:if(t.key!==`value`)return!1;break;case`ArrayPattern`:case`ObjectPattern`:case`RestElement`:break;default:return!1}t=n}return!1}function unwrapReferenceArgument(e){let t=e;for(;t?.isTSAsExpression()||t?.isTSTypeAssertion()||t?.isTSNonNullExpression()||t?.isTSSatisfiesExpression()||t?.isTSInstantiationExpression();)t=t.get(`expression`);return t}function isCurrentFileRequire(e){let t=e.get(`callee`),n=t.isMemberExpression()&&!t.node.computed&&t.get(`property`).isIdentifier({name:`resolve`})?t.get(`object`):t,r=n;if(n.isIdentifier()&&n.node.name){let e=n.scope.getBinding(n.node.name);if(!e?.constant||!e.path.isVariableDeclarator())return!1;r=e.path.get(`init`)}if(!r.isCallExpression())return!1;let i=r.get(`arguments`),a=i.length===1?i[0]:void 0;if(!a||!(a.isMemberExpression()&&!a.node.computed&&a.get(`object`).node?.type===`MetaProperty`&&a.matchesPattern(`import.meta.url`)||a.node?.type===`Identifier`&&a.node.name===`__filename`&&!a.scope.getBinding(`__filename`)))return!1;let s=r.get(`callee`);return[`module`,`node:module`].some(e=>s.referencesImport(e,`createRequire`)||s.isMemberExpression()&&!s.node.computed&&s.get(`property`).isIdentifier({name:`createRequire`})&&s.get(`object`).referencesImport(e,`default`))}const lr=/* @__PURE__ */ new Set([`createRequire`,`URL`,`readFile`,`readFileSync`,`createReadStream`,`join`,`resolve`,`require`,`jitiImport`,`jitiESMResolve`,`__dirname`]);function*sourceChildren(e){for(let t of Object.values(e))for(let e of Array.isArray(t)?t:[t])e&&typeof e==`object`&&`type`in e&&(yield e)}function parseNativePluginJavaScript(e,t){if(!/\.[cm]?js$/.test(e))return;let n;try{n=parse(t,{ecmaVersion:`latest`,sourceType:`module`,allowAwaitOutsideFunction:!0})}catch(e){if(e instanceof SyntaxError)return;throw e}let needsTransform=(e,t=!1,n,r)=>{if(e.type===`MetaProperty`)return e.meta.name!==`import`||e.property.name!==`meta`||n?.type!==`MemberExpression`||n.object!==e||n.computed||n.property.type!==`Identifier`||n.property.name!==`url`?!0:!(r?.type===`ArrayExpression`||r?.type===`ReturnStatement`&&r.argument===n||r?.type===`NewExpression`&&r.callee.type===`Identifier`&&r.callee.name===`URL`&&r.arguments.length===2&&r.arguments[1]===n);if(e.type===`VariableDeclaration`&&(e.kind===`using`||e.kind===`await using`)||(e.type===`ForInStatement`||e.type===`ForOfStatement`)&&e.left.type!==`VariableDeclaration`)return!0;let i=e.type===`ExportSpecifier`||e.type===`ExportAllDeclaration`?e.exported:void 0;if((i?.type===`Identifier`?i.name:staticString(i))==="__esModule"||t&&e.type===`Identifier`&&e.name==="__esModule"||e.type===`Identifier`&&(e.name===`require`||e.name===`__dirname`)||e.type===`ImportExpression`&&(e.source.type!==`Literal`||typeof e.source.value!=`string`||e.options!=null))return!0;if(e.type===`ImportDeclaration`){if(e.source.value===`module`||e.source.value===`node:module`)return!0;for(let t of e.specifiers){let e=t.type===`ImportSpecifier`?t.imported.type===`Identifier`?t.imported.name:staticString(t.imported):void 0;if(lr.has(t.local.name)||e!==void 0&&lr.has(e))return!0}}for(let r of sourceChildren(e))if(needsTransform(r,t||e.type===`ExportNamedDeclaration`&&r===e.declaration,e,n))return!0;return!1};return needsTransform(n)?void 0:n}function parseTransformedPluginSource(e,t){try{return parse(t,{ecmaVersion:`latest`,allowImportExportEverywhere:!0,allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0})}catch(t){throw t instanceof SyntaxError?j(SyntaxError(`${e}: could not parse transformed source: ${t.message}`,{cause:t})):t}}function visitPluginSourceReferences(e,t,n,r){let i=/* @__PURE__ */ new Set,visitDirectoryAsset=(e,t)=>{(e===`join`||e===`resolve`)&&t.length>0&&t.every(e=>e!==void 0)&&(e===`join`||!t.some(e=>Y.isAbsolute(e)))&&r(Y.join(`.`,...t),`asset`)},a=parseNativePluginJavaScript(e,t)??parseTransformedPluginSource(e,n().transform({source:t,filename:e,ts:/\.[cm]?tsx?$/.test(e),async:!0,babel:{plugins:[{pre(e){e.path.traverse({"ImportDeclaration|ExportNamedDeclaration"(e){let t=e.node;t.source&&(t.type===`ImportDeclaration`?t.importKind:t.exportKind)!==`type`&&t.specifiers.length>0&&t.specifiers.every(e=>e.type===`ImportSpecifier`&&e.importKind===`type`||e.type===`ExportSpecifier`&&e.exportKind===`type`)&&i.add(t.source.value)},MemberExpression(e){e.get(`object`).node?.type===`MetaProperty`&&isAssignmentTarget(e)&&e.replaceWith({type:`Identifier`,name:`importMetaTarget`})},CallExpression(e){let t=e.get(`arguments`);if(unwrapReferenceArgument(t[0])?.matchesPattern(`import.meta.dirname`)){let n=e.get(`callee`),r=n.isMemberExpression()?n.get(`property`):n,i=[`join`,`resolve`].find(e=>[`path`,`node:path`].some(t=>n.referencesImport(t,e)))??(r.isIdentifier()?r.node.name:void 0)??``;visitDirectoryAsset(i,t.slice(1).map(e=>staticString(unwrapReferenceArgument(e)?.node)))}let n=staticString(unwrapReferenceArgument(t.length===1?t[0]:void 0)?.node);n!==void 0&&isCurrentFileRequire(e)&&r(n,`require`)}})},visitor:{"ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration"(e){e.node.source&&i.add(e.node.source.value)}}}]}})),s=/* @__PURE__ */ new Set;for(let e of a.body)if((e.type===`ImportDeclaration`||e.type===`ExportNamedDeclaration`||e.type===`ExportAllDeclaration`)&&e.source){let t=staticString(e.source);t!==void 0&&(s.add(t),i.add(t))}for(let e of s)r(e,`import`);let visit=(e,t=!1)=>{if(e.type===`ImportExpression`){let t=staticString(e.source);t!==void 0&&r(t,`import`)}if(e.type===`CallExpression`||e.type===`NewExpression`){let{callee:n,arguments:i}=e,a=n.type===`SequenceExpression`?n.expressions.at(-1):n,s=a.type===`MemberExpression`?a.property:a,c=s.type===`Identifier`?s.name:``,l=a.type===`Identifier`?[`require`,`jitiImport`,`jitiESMResolve`].includes(c):a.type===`MemberExpression`&&a.object.type===`Identifier`&&a.object.name===`require`&&c===`resolve`,u=e.type===`NewExpression`&&c===`URL`&&!t||[`readFile`,`readFileSync`,`createReadStream`].includes(c),d=staticString(i[0]);(l||u)&&d!==void 0&&r(d,l?c===`require`||c===`resolve`?`require`:`import`:`asset`),a.type===`MemberExpression`&&i[0]?.type===`Identifier`&&i[0].name===`__dirname`&&visitDirectoryAsset(c,i.slice(1).map(staticString))}for(let n of sourceChildren(e)){let r=e.type===`ExpressionStatement`&&n===e.expression||t&&e.type===`MemberExpression`&&n===e.object;visit(n,r)}};return visit(a),i}function createPluginGenerationReferenceCapture({source:e,rootDir:t,root:n,boundary:r,destination:i,entry:a,executableEntry:s,execute:c,resolveFrozenInput:l,moduleSource:u,originalSources:d,nativeAdmission:f,resolution:p,references:m,inspected:h,scope:g,packageMap:_,capturedPaths:v,resolveDependency:y,captureFile:b,captureExecutableFile:x,owner:S,sourceLinks:C,linkSharedModule:w}){let T,captureFile=e=>{T?.push({kind:`file`,source:e}),b(e)},recordDependency=(e,t)=>{T?.push({kind:`dependency`,importer:e,name:t});let n=m.get(e)??/* @__PURE__ */ new Set;n.add(t),m.set(e,n)},capture=(m,h,b)=>{let T=h!==`asset`,E=h===`import`&&m.startsWith(`.`)?new URL(m,Z(e)):void 0,D=E?`./${Y.relative(Y.dirname(e),X(E))}`:T&&m.startsWith(`file:`)?X(m):m;T&&Y.isAbsolute(D)&&(D=l?.(D)??D);let resolve=t=>{let n=p.resolve(e,t,b??[`node`,`module-sync`,h===`require`?`require`:`import`]);if(!n?.startsWith(`file:`))return n;let r=new URL(n),i=X(r),a=u?.(i)??i;return r.pathname=Z(d.get(a)??f.sourceForPrepared(a)??a).pathname,r.href},addDependency=(t,n=e)=>recordDependency(n,t);if(T&&!D.startsWith(`.`)&&!Y.isAbsolute(D)){if(mt(D))return;let t=packageName(D),n=g?.manifest.exports!=null&&g.manifest.name===t,i=D.startsWith(`#`)||n?_.resolveReference(D,e,b??[`node`,`module-sync`,h]):resolve(D),a=i?.startsWith(`file:`)?X(i):i;if(p.get(e).options.tsconfigPaths&&t!==`openclaw`&&t!==`@openclaw/plugin-sdk`&&i?.startsWith(`file:`)&&a){if(isPluginPackageFile(r,a)&&(v.has(Y.resolve(a))||isPluginPackageFile(r,realpathPluginSource(a))))return captureFile(a),a;if(!U(y(t,e)?.root??r,a))return b&&c?x(a):null}if(!D.startsWith(`#`)&&!n)return b&&!i?void 0:(addDependency(t),i?.startsWith(`file:`)?a:void 0);if(!a||mt(a))return;let s=!1;if(!n&&g)for(let e of g.aliases){let t=y(e,g.source);t&&U(t.root,a)&&((b||!c)&&addDependency(e,g.source),s=!0)}return s||captureFile(a),a}let O=Y.resolve(Y.dirname(e),D),k=a&&!s?Y.resolve(t):n,A=T&&Y.isAbsolute(D)&&U(k,O)?Y.join(r,Y.relative(k,O)):O;if(T&&w?.(e,A,D))return;if(T&&!U(r,A)){if(!b||!c)return null;let e=resolve(A);return e?.startsWith(`file:`)?x(X(e)):void 0}if(!D||!T&&Y.isAbsolute(D)||!U(r,A)||A===r||T&&Y.isAbsolute(D)&&Y.relative(r,A).split(Y.sep).includes(`node_modules`))return;let j=S.state===`body`&&!C.contains(A),M=f.resolvePreparedSource(A)?.path??(j?Y.join(i,Y.relative(n,A)):A),N=T?resolve(M):void 0;if(T&&!N)return;let P=N?.startsWith(`file:`)?X(N):N??A,F=v.has(Y.resolve(P)),I=f.resolvePreparedSource(P);if(F||q.existsSync(I?.path??P))return T&&c&&!F&&!I&&!U(r,realpathPluginSource(P))?b?x(P):null:(captureFile(P),T&&Y.isAbsolute(D)&&v.set(O,v.get(Y.resolve(P))),P)},E=new Map(h?.observed),captureObserved=(e,t,n)=>{let r=`${t}\0${e}`;return(!E.has(r)||n&&c&&E.get(r)===null)&&E.set(r,capture(e,t,n)),E.get(r)??void 0};return{observed:E,capture:captureObserved,*inspect(t,n){if(h){for(let e of h.acquisitions)e.kind===`file`?yield*n(e.source):recordDependency(e.importer,e.name);return h}T=[];let r={staticImports:visitPluginSourceReferences(e,t(),()=>p.get(e),a&&!s?captureObserved:(e,t)=>E.set(`${t}\0${e}`,null)),observed:new Map(E),acquisitions:T};return T=void 0,r}}}function canProbeWindowsPhysicalAlias(e,t){let n=/^(?:[\\/]{2}[?.][\\/])?[A-Za-z]:[\\/]/.exec(t)?.[0];if(n)return Mt(n,t);let r=te(e),i=Mt(e,r)&&Mt(r,e)?Y.win32.parse(r).root||r:e;return Mt(i,t)}function resolvePhysicalPathInsideRootSync(e,t){if(process.platform===`win32`)try{if(!canProbeWindowsPhysicalAlias(e,t)&&!canProbeWindowsPhysicalAlias(q.realpathSync(e),t))return;let n=q.statSync(e,{bigint:!0});if(!n.isDirectory()||n.ino===0n)return;let r=Y.resolve(t);for(;;){let e=q.statSync(r,{bigint:!0});if(e.dev===n.dev&&e.ino===n.ino){let e=q.realpathSync(r);return{rootPath:e,targetPath:Y.resolve(e,Y.relative(r,t)),rootIdentity:Object.freeze({dev:n.dev,ino:n.ino})}}let i=Y.dirname(r);if(i===r)return;r=i}}catch{return}}function isPathInside$1(e,t){return Mt(e,t)||resolvePhysicalPathInsideRootSync(e,t)!==void 0}function relativePluginPathInsideRootSync(e,t){if(Mt(e,t))return process.platform===`win32`?Y.win32.relative(te(e),te(t)):Y.relative(e,t);let n=resolvePhysicalPathInsideRootSync(e,t);return n?Y.relative(n.rootPath,n.targetPath):void 0}function createIdentityBoundRootFileFs(e,t){return{closeSync:q.closeSync,constants:q.constants,fstatSync:q.fstatSync,lstatSync:((...n)=>{let r=Reflect.apply(q.lstatSync,q,n);if(n[0]===e){let n=typeof r.ino==`bigint`?r:q.lstatSync(e,{bigint:!0});if(!r.isDirectory()||n.dev!==t.dev||n.ino!==t.ino)throw new le(`path-mismatch`,`plugin root identity changed during alias reconciliation`)}return r}),openSync:q.openSync,readFileSync:q.readFileSync,realpathSync:q.realpathSync}}function openPluginRootFileSync(e){let t=e.rootRealPath??e.rootPath,n=Mt(t,e.filePath)?void 0:resolvePhysicalPathInsideRootSync(t,e.filePath);return de({absolutePath:n?.targetPath??e.filePath,rootPath:n?.rootPath??e.rootPath,rootRealPath:n?.rootPath??e.rootRealPath,boundaryLabel:e.boundaryLabel??`plugin root`,rejectHardlinks:e.rejectHardlinks,maxBytes:e.maxBytes,skipLexicalRootCheck:n?!0:void 0,ioFs:n?createIdentityBoundRootFileFs(n.rootPath,n.rootIdentity):void 0})}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=Y.join(Y.resolve(e),`package.json`);if(n.has(r))return n.get(r)??null;try{let e=parsePackageName(await kt.readFile(r,{encoding:`utf-8`,signal:t}));return t?.throwIfAborted(),n.set(r,e),e}catch{return t?.throwIfAborted(),n.set(r,null),null}}function readPackageNameSync(e){let t=getPluginCache().sdk.packageNames,n=Y.join(Y.resolve(e),`package.json`);if(t.has(n))return t.get(n)??null;try{let e=parsePackageName(Ot.readFileSync(n,`utf-8`));return t.set(n,e),e}catch{return t.set(n,null),null}}async function findPackageRoot(e,t){for(let n of iterAncestorDirs(e))if(await readPackageName(n,t)===`openclaw`)return n;return null}function findPackageRootSync(e){for(let t of iterAncestorDirs(e))if(readPackageNameSync(t)===`openclaw`)return t;return null}function*iterAncestorDirs(e){let t=Y.resolve(e);for(let e=0;e<12&&(yield t,Y.basename(t)!==`node_modules`);e+=1){let e=Y.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,n=Y.resolve(e),r=t.get(n);if(r)return[...r];let i=n,a=[];try{let e=Ot.realpathSync(i);e!==i&&a.push(Y.dirname(e))}catch{}a.push(Y.dirname(i));let s=i.split(Y.sep),c=s.lastIndexOf(`.bin`);if(c>0&&s[c-1]===`node_modules`){let e=Y.basename(i),t=s.slice(0,c).join(Y.sep);a.push(Y.join(t,e))}let l=dedupeCandidates(a);return t.set(n,l),[...l]}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 resolveOpenClawPackageRootSync(e){let t=preparePackageRootSearch(e,!1);if(t.first!==void 0)return t.first;for(let e of t.candidates){let n=findPackageRootSync(e);if(n)return t.complete(n)}return t.complete(null)}function buildCandidates(e){let t=[];if(e.moduleUrl)try{t.push(Y.dirname(X(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=>Y.resolve(e)))]}function sameFsObject(e,t){return e.dev===t.dev&&e.ino===t.ino}Y.join(`plugins`,`installs.json`);function openClawHostRootsMatch(e,t){let n=Nt(e),r=Nt(t);if(!n||!r)return!1;if(n===r)return!0;try{let e=Dt(n,{bigint:!0});if(e.ino!==0n&&sameFsObject(e,Dt(r,{bigint:!0})))return!0;let t=at(n),i=at(r);return!!(t?.openclaw.commit&&t.executable.sha256&&t.runtime.sha256&&i&&t.openclaw.commit===i.openclaw.commit&&t.openclaw.version===i.openclaw.version&&t.executable.sha256===i.executable.sha256&&t.runtime.sha256===i.runtime.sha256)}catch{return!1}}function createRuntimePathLookup(e){let t=process.platform===`win32`?Y.win32:Y.posix,n=process.platform===`win32`,keyFor=e=>{if(!t.isAbsolute(e))return;let r=t.resolve(e);return n?!/^[a-z]:\\/iu.test(r)&&!/^\\\\[^?.\\][^\\]*\\[^\\]+/u.test(r)||r.includes(`:`,2)?void 0:r.toLowerCase():r},r=Array.from(e,([e,t],n)=>({root:e,value:t,order:n})),i=/* @__PURE__ */ new Map,a=[];for(let e of r){let t=keyFor(e.root);if(t===void 0)a.push(e);else{let n=i.get(t);n?n.push(e):i.set(t,[e])}}return e=>{let n=keyFor(e);if(n===void 0)return r.find(t=>U(t.root,e))?.value;let s,consider=t=>{for(let n of t){if(s&&n.order>=s.order)break;if(U(n.root,e)){s=n;break}}};for(let e=n;;e=t.dirname(e)){let n=i.get(e);if(n&&consider(n),t.dirname(e)===e)break}return consider(a),s?.value}}const ur=[`.ts`,`.mts`,`.js`,`.mjs`,`.cts`,`.cjs`];function isTypeScriptPackageEntry(e){return[`.ts`,`.tsx`,`.mts`,`.cts`].includes(Y.extname(e).toLowerCase())}function listBuiltRuntimeEntryCandidates(e){if(!isTypeScriptPackageEntry(e))return[];let t=e.replace(/\\/g,`/`),n=t.replace(/\.[^.]+$/u,``),r=n.replace(/^\.\//u,``),i=r.startsWith(`src/`)?`./dist/${r.slice(4)}`:`./dist/${r}`,a=Y.extname(t).toLowerCase(),s=a===`.mts`?[`.mjs`,`.js`,`.cjs`]:a===`.cts`?[`.cjs`,`.js`,`.mjs`]:[`.js`,`.mjs`,`.cjs`];return[i,...r.startsWith(`src/`)?[`./dist/${r}`]:[],n].flatMap(e=>s.map(t=>`${e}${t}`))}function rewriteBundledPluginEntryToBuiltPath(e){if(e)return e.replace(/^\.\//u,``).replace(/\.[^.]+$/u,`.js`)}function isTopLevelPublicSurfaceSource(e){return!ur.includes(Y.extname(e))||e.startsWith(`.`)||e.startsWith(`test-`)||e.includes(`.test-`)||e.endsWith(`.d.ts`)||/^config-api(\.[cm]?[jt]s)$/u.test(e)?!1:!/(\.test|\.spec)(\.[cm]?[jt]s)$/u.test(e)}function collectBundledPluginPublicSurfaceArtifacts(e){let t=new Set(H([e.sourceEntry,e.setupEntry]).map(e=>Y.basename(e))),n=q.readdirSync(e.pluginDir,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).filter(isTopLevelPublicSurfaceSource).filter(e=>!t.has(e)).map(e=>rewriteBundledPluginEntryToBuiltPath(e)).filter(e=>typeof e==`string`&&e.length>0).toSorted((e,t)=>e.localeCompare(t));return n.length>0?n:void 0}function isPluginControlUiAssetPath(e){return/^(?:[\w-][\w.-]*\/)*[\w-][\w.-]*\.(?:m?js|css)$/u.test(e)}function normalizeProviderId(e){return A(e)}const dr=[`openai-completions`,`openai-responses`,`openai-chatgpt-responses`,`anthropic-messages`,`google-generative-ai`,`google-interactions`,`google-vertex`,`github-copilot`,`bedrock-converse-stream`,`ollama`,`pi-messages`,`azure-openai-responses`],fr=[`openai`,`openrouter`,`deepseek`,`together`,`qwen`,`qwen-chat-template`,`zai`],pr=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],mr=[...dr],hr=[...fr];function isModelCatalogThinkingFormat(e){return hr.includes(e)}const gr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function normalizeModelFamily(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();return t.length<=64&&gr.test(t)?t:void 0}const _r=[`text`,`image`,`video`,`document`],vr=[...pr],yr=[`available`,`preview`,`deprecated`,`disabled`],br=Xe().int().positive().max(2**53-1),xr=$e([`boolean`,`categorical`,`independent`,`provider-defined`,`none`]),Sr=K({probabilities:xr,abstention:Ke(),minOptions:br.optional(),maxOptions:br.optional(),maxImageOptions:br.optional(),requiresCriteria:Ke().optional()}).refine(e=>e.minOptions===void 0||e.maxOptions===void 0||e.minOptions<=e.maxOptions),Cr=K({boolean:Sr.optional(),choice:Sr.optional(),score:Sr.optional(),sort:Sr.optional(),tags:Sr.optional(),box:Sr.optional()}).refine(e=>Object.values(e).some(Boolean)),wr=K({questions:Cr.optional(),confidence:$e([`provider-specific`,`none`]).optional()}),Tr=Xe().int().positive().max(2**53-1),Er=$e([`boolean`,`choice`,`score`,`sort`,`tags`,`box`]),Dr=Ye(Er).min(1).max(6).refine(e=>new Set(e).size===e.length),Or=$e([`auto`,`off`,`on`]),kr=K({modes:Ye(Or).min(1).max(3).refine(e=>new Set(e).size===e.length),default:Or.optional(),questionTypes:Dr.optional(),metadata:Ke().optional()}).refine(e=>e.default===void 0||e.modes.includes(e.default)),Ar=$e([`provider-docs`,`provider-catalog`,`configured`]),jr=Qe(`unit`,[K({unit:et(`tokens`),source:Ar,usdPerMillion:K({input:Xe().nonnegative().finite().optional(),output:Xe().nonnegative().finite().optional()}).optional()}),K({unit:$e([`decision-units`,`requests`]),source:Ar,usdPerMillion:qe().optional()})]),Mr=wr.extend({protocol:Je().max(64).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/),input:Ye($e([`text`,`image`])).min(1).max(2).refine(e=>new Set(e).size===e.length),reasoning:kr.optional(),grounding:K({webSearch:Ke(),questionTypes:Dr.optional()}).optional(),limits:K({maxQuestions:Tr.optional(),maxRequestTokens:Tr.optional(),maxStateAndQuestionTokens:Tr.optional(),maxInputTokens:Tr.optional(),inputTokenScope:$e([`encoded-question`,`state-plus-each-criterion`]).optional(),image:K({maxBytes:Tr,mimeTypes:Ye($e([`image/png`,`image/jpeg`,`image/webp`])).min(1).max(3),remoteUrls:Ke()}).optional()}).optional(),billing:jr.optional()}).refine(e=>{let supported=t=>e.questions===void 0||e.questions[t]!==void 0;return(e.reasoning?.questionTypes?.every(supported)??!0)&&(e.grounding?.questionTypes?.every(supported)??!0)&&(e.limits?.image===void 0||e.input.includes(`image`))}),Nr=K({chat:Ke(),chatEvidence:et(`unlikely`).optional(),decision:Mr.optional()}),Pr=new Set(_r),Fr=/* @__PURE__ */ new Set([`static`,`refreshable`,`runtime`]),Ir=new Set(yr),Lr=new Set(mr);function isBlockedObjectKey(e){return e===`__proto__`||e===`prototype`||e===`constructor`}function normalizeStringMap(e){return normalizeCatalogRecords(e,(e,t)=>{let n=y(t)??``;return e&&!isBlockedObjectKey(e)&&n?n:void 0},e=>y(e)??``)}function normalizeCatalogFields(e,t,n={}){for(let r of e){let e=t(r);e!==void 0&&(n[r]=e)}return n}function normalizeModelCatalogApi(e){let t=y(e)??``;return Lr.has(t)?t:void 0}function normalizeModelCatalogContextWindows(e){if(!Array.isArray(e))return;let t=/* @__PURE__ */ new Set,r=e.slice(0,16).flatMap(e=>{if(!n(e))return[];let r=y(e.id)??``,i=y(e.label)??``,a=B(e.contextWindow);return!r||!i||a===void 0||t.has(r)?[]:(t.add(r),[{id:r,label:i,contextWindow:a}])});return r.length>0?r.toSorted((e,t)=>e.contextWindow-t.contextWindow||e.id.localeCompare(t.id)):void 0}function normalizeModelCatalogTieredCost(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(!n(r)||!Array.isArray(r.range))continue;let e=O(r.input),i=O(r.output),a=O(r.cacheRead),s=O(r.cacheWrite);if(e===void 0||i===void 0||a===void 0||s===void 0||r.range.length<1||r.range.length>2)continue;let c=r.range.map(e=>O(e));c.some(e=>e===void 0)||t.push({input:e,output:i,cacheRead:a,cacheWrite:s,range:c.length===1?[c[0]]:[c[0],c[1]]})}return t.length>0?t:void 0}function normalizeModelCatalogCost(e){if(!n(e))return;let t=normalizeCatalogFields([`input`,`output`,`cacheRead`,`cacheWrite`],t=>O(e[t])),r=normalizeModelCatalogTieredCost(e.tieredPricing);return r&&(t.tieredPricing=r),Object.keys(t).length>0?t:void 0}function normalizeOpenRouterPrice(e){if(!n(e))return;let t=normalizeCatalogFields([`prompt`,`completion`,`image`,`audio`,`request`],t=>{let n=e[t];return y(n)??V(n)});return Object.keys(t).length>0?t:void 0}function normalizeOpenRouterMetricPreference(e){let t=V(e);if(t!==void 0)return t;if(!n(e))return;let r=normalizeCatalogFields([`p50`,`p75`,`p90`,`p99`],t=>V(e[t]));return Object.keys(r).length>0?r:void 0}function normalizeOpenRouterSort(e){let t=y(e);if(t)return t;if(!n(e))return;let r=y(e.by),i=e.partition===null?null:y(e.partition)??void 0,a={...r?{by:r}:{},...i===void 0?{}:{partition:i}};return Object.keys(a).length>0?a:void 0}function normalizeOpenRouterRouting(e){if(!n(e))return;let t={...typeof e.allow_fallbacks==`boolean`?{allow_fallbacks:e.allow_fallbacks}:{},...typeof e.require_parameters==`boolean`?{require_parameters:e.require_parameters}:{},...e.data_collection===`deny`||e.data_collection===`allow`?{data_collection:e.data_collection}:{},...typeof e.zdr==`boolean`?{zdr:e.zdr}:{},...typeof e.enforce_distillable_text==`boolean`?{enforce_distillable_text:e.enforce_distillable_text}:{}};normalizeCatalogFields([`order`,`only`,`ignore`,`quantizations`],t=>z(e[t]),t);let r=normalizeOpenRouterSort(e.sort);r&&(t.sort=r);let i=normalizeOpenRouterPrice(e.max_price);i&&(t.max_price=i);for(let n of[`preferred_min_throughput`,`preferred_max_latency`]){let r=normalizeOpenRouterMetricPreference(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function normalizeVercelGatewayRouting(e){if(!n(e))return;let t=normalizeCatalogFields([`only`,`order`],t=>z(e[t]));return Object.keys(t).length>0?t:void 0}function normalizeModelCatalogCompat(e){if(!n(e))return;let t={};for(let n of/* @__PURE__ */ `supportsStore.supportsPromptCacheKey.supportsDeveloperRole.supportsReasoningEffort.supportsTemperature.supportsInstructions.cachesInstructions.supportsUsageInStreaming.supportsTools.supportsStrictMode.supportsJsonSchemaResponseFormat.requiresStringContent.strictMessageKeys.requiresToolResultName.requiresAssistantAfterToolResult.requiresThinkingAsText.requiresReasoningContentOnAssistantMessages.zaiToolStream.sendSessionAffinityHeaders.sendSessionIdHeader.supportsEagerToolInputStreaming.supportsLongCacheRetention.supportsResponsesContinuation.requiresOpenAiAnthropicToolPayload.adaptiveThinking.thinkingRequired`.split(`.`))typeof e[n]==`boolean`&&(t[n]=e[n]);normalizeCatalogFields([`toolSchemaProfile`,`toolCallArgumentsEncoding`,`defaultThinkingLevel`],t=>y(e[t]),t);for(let n of[`visibleReasoningDetailTypes`,`supportedReasoningEfforts`,`unsupportedToolSchemaKeywords`,`thinkingLevels`]){let r=H(e[n]);(r.length>0||n===`supportedReasoningEfforts`&&Array.isArray(e[n]))&&(t[n]=r)}if(n(e.reasoningEffortMap)){let n=Object.fromEntries(Object.entries(e.reasoningEffortMap).flatMap(([e,t])=>{let n=e.trim(),r=typeof t==`string`?t.trim():``;return n&&r?[[n,r]]:[]}));Object.keys(n).length>0&&(t.reasoningEffortMap=n)}if(n(e.thinkingLevelLabels)){let n=Object.fromEntries(Object.entries(e.thinkingLevelLabels).flatMap(([e,t])=>typeof t==`string`&&t.trim()?[[e.trim(),t.trim()]]:[]));Object.keys(n).length>0&&(t.thinkingLevelLabels=n)}let r=y(e.codeMode)??``;(r===`preferred`||r===`capable`)&&(t.codeMode=r);let i=y(e.maxTokensField)??``;(i===`max_completion_tokens`||i===`max_tokens`)&&(t.maxTokensField=i);let a=y(e.thinkingFormat)??``;isModelCatalogThinkingFormat(a)&&(t.thinkingFormat=a),e.cacheControlFormat===`anthropic`&&(t.cacheControlFormat=`anthropic`);let s=normalizeOpenRouterRouting(e.openRouterRouting);s&&(t.openRouterRouting=s);let c=normalizeVercelGatewayRouting(e.vercelGatewayRouting);return c&&(t.vercelGatewayRouting=c),Object.keys(t).length>0?t:void 0}function normalizeModelCatalogMediaInput(e){if(!n(e)||!n(e.image))return;let t={};for(let n of[`maxBytes`,`maxPixels`,`maxSidePx`,`preferredSidePx`]){let r=B(e.image[n]);r!==void 0&&(t[n]=r)}let r=y(e.image.tokenMode)??``;return(r===`tile`||r===`detail`||r===`provider`)&&(t.tokenMode=r),Object.keys(t).length>0?{image:t}:void 0}function normalizeModelCatalogModel(e){if(!n(e))return;let t=y(e.id)??``;if(!t)return;let r=e.inference===void 0?void 0:Nr.safeParse(e.inference);if(r&&!r.success)return;let i=y(e.name)??``,a=normalizeModelCatalogApi(e.api),s=y(e.baseUrl)??``,c=normalizeStringMap(e.headers),l=H(e.input).filter(e=>Pr.has(e)),u=l.length>0?l:void 0,d=typeof e.reasoning==`boolean`?e.reasoning:void 0,f=_(e.contextWindow),p=normalizeModelCatalogContextWindows(e.contextWindows),m=y(e.contextWindowDefault),h=m&&p?.some(e=>e.id===m)?{contextWindows:p,contextWindowDefault:m}:{},g=B(e.contextTokens),v=B(e.parameterCount),b=normalizeModelFamily(e.family),x=_(e.maxTokens),S=e.thinkingLevelMap,C=n(S)?normalizeCatalogFields(vr,e=>{let t=S[e];return t===null?null:y(t)}):void 0,w=C&&Object.keys(C).length>0?C:void 0,T=normalizeModelCatalogCost(e.cost),E=normalizeModelCatalogCompat(e.compat),D=normalizeModelCatalogMediaInput(e.mediaInput),O=y(e.status)??``,k=Ir.has(O)?O:void 0,A=y(e.statusReason)??``,j=H(e.replaces),M=y(e.replacedBy)??``,N=H(e.tags);return{id:t,...i?{name:i}:{},...r?.success?{inference:r.data}:{},...a?{api:a}:{},...s?{baseUrl:s}:{},...c?{headers:c}:{},...u?{input:u}:{},...d===void 0?{}:{reasoning:d},...f===void 0?{}:{contextWindow:f},...h,...g===void 0?{}:{contextTokens:g},...v===void 0?{}:{parameterCount:v},...b?{family:b}:{},...x===void 0?{}:{maxTokens:x},...w?{thinkingLevelMap:w}:{},...T?{cost:T}:{},...E?{compat:E}:{},...D?{mediaInput:D}:{},...k?{status:k}:{},...A?{statusReason:A}:{},...j.length>0?{replaces:j}:{},...M?{replacedBy:M}:{},...N.length>0?{tags:N}:{}}}function normalizeModelCatalogProvider(e){if(!n(e))return;if(e.authScope!==void 0&&e.authScope!==`agent`&&e.authScope!==`plugin`)throw Error(`Invalid model catalog credential ownership metadata`);let t=e.authScope,r=Array.isArray(e.models)?e.models.map(e=>normalizeModelCatalogModel(e)).filter(e=>!!e):[];if(r.length===0&&t===void 0)return;let i=y(e.baseUrl)??``,a=normalizeModelCatalogApi(e.api),s=normalizeStringMap(e.headers),c=y(e.defaultModel)??``,l=y(e.defaultUtilityModel)??``,u=normalizeCatalogRecords(e.defaultUtilityModels,(e,t)=>{let n=y(t)??``;return e&&!isBlockedObjectKey(e)&&n?n:void 0},e=>y(e)?.toLowerCase()??``),d=normalizeModelFamily(e.family);return{...t?{authScope:t}:{},...i?{baseUrl:i}:{},...a?{api:a}:{},...s?{headers:s}:{},...d?{family:d}:{},...c?{defaultModel:c}:{},...l?{defaultUtilityModel:l}:{},...u?{defaultUtilityModels:u}:{},models:r}}function normalizeCatalogRecords(e,t,r=normalizeProviderId){if(!n(e))return;let i={};for(let[n,a]of Object.entries(e)){let e=r(n),s=t(e,a);s!==void 0&&(i[e]=s)}return Object.keys(i).length>0?i:void 0}function normalizeModelCatalogSuppressions(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(!n(r))continue;let e=normalizeProviderId(y(r.provider)??``),i=y(r.model)??``;if(!e||!i)continue;let a=y(r.reason)??``,s=n(r.retirement)?y(r.retirement.replacedBy):void 0,c=n(r.retirement)&&(r.retirement.replacedBy===void 0||s)?s?{replacedBy:s}:{}:void 0,l=n(r.when)?r.when:void 0,u=H(l?.baseUrlHosts).map(e=>e.toLowerCase()),d=H(l?.providerConfigApiIn).map(e=>e.toLowerCase()),f=u.length>0||d.length>0?{...u.length>0?{baseUrlHosts:u}:{},...d.length>0?{providerConfigApiIn:d}:{}}:void 0;c&&r.when!==void 0&&(!l||!f||l.baseUrlHosts!==void 0&&u.length===0||l.providerConfigApiIn!==void 0&&d.length===0)||t.push({provider:e,model:i,...a?{reason:a}:{},...c?{retirement:c}:{},...f?{when:f}:{}})}return t.length>0?t:void 0}function normalizeModelCatalog(e,t){if(!n(e))return;let r=new Set([...t.ownedProviders].map(normalizeProviderId).filter(Boolean)),i=Object.fromEntries(Object.entries(normalizeStringMap(e.modelsDev)??{}).flatMap(([e,t])=>{let n=normalizeProviderId(e);return r.has(n)&&!isBlockedObjectKey(n)?[[n,t]]:[]})),a=normalizeCatalogRecords(e.providers,(e,t)=>e&&r.has(e)?normalizeModelCatalogProvider(t):void 0),s=normalizeCatalogRecords(e.aliases,(e,t)=>{if(!e||!n(t))return;let i=normalizeProviderId(y(t.provider)??``);if(!i||!r.has(i))return;let a=normalizeModelCatalogApi(t.api),s=y(t.baseUrl)??``;return{provider:i,...a?{api:a}:{},...s?{baseUrl:s}:{}}}),c=normalizeModelCatalogSuppressions(e.suppressions),l=normalizeCatalogRecords(e.discovery,(e,t)=>{let n=y(t)??``;return e&&r.has(e)&&Fr.has(n)?n:void 0}),u=e.runtimeAugment===!0,d=[...new Set(H(e.configuredEndpointDiscovery).map(normalizeProviderId).filter(e=>l?.[e]===`runtime`))],f={...Object.keys(i).length>0?{modelsDev:i}:{},...a?{providers:a}:{},...s?{aliases:s}:{},...c?{suppressions:c}:{},...l?{discovery:l}:{},...d.length>0?{configuredEndpointDiscovery:d}:{},...u?{runtimeAugment:u}:{}};return Object.keys(f).length>0?f:void 0}const Rr=[`page`,`navigation`,`panel`,`action`,`accessory`,`widget`,`inline`,`replacement`,`link-reader`];function validatePluginUiCapabilities(e){if(e===void 0)return{ok:!0};if(!Array.isArray(e))return{ok:!1,error:`must be an array`};for(let t of e)if(!Rr.some(e=>e===t))return{ok:!1,error:`contains unknown UI capability ${JSON.stringify(t)}`};return{ok:!0,capabilities:Rr.filter(t=>e.includes(t))}}function validatePluginRecommendedPrompts(e){if(e===void 0)return{ok:!0};if(!Array.isArray(e))return{ok:!1,error:`must be an array`};if(e.length>3)return{ok:!1,error:`must contain at most 3 entries`};let t=[];for(let n of e){if(typeof n!=`string`||!n.trim())return{ok:!1,error:`entries must be non-empty strings`};let e=n.replace(/\s+/gu,` `).trim();if(Array.from(e).length>128)return{ok:!1,error:`entries must be at most 128 Unicode code points`};t.push(e)}return{ok:!0,recommendedPrompts:t}}const zr=[`channels`,`models`,`agent-runtimes`,`memory`,`context`,`voice`,`web`,`computer-use`,`media`,`security`,`integrations`,`developer-tools`,`infrastructure`,`documents-files`,`inbox-collaboration`,`productivity`,`scheduling`,`finance-payments`,`sales-marketing`,`data-analytics`,`agent-orchestration`,`research`,`other`],Br=[`tools`,`runtime`,`gateway`],Vr=[...zr,...Br];function validatePluginCategories(e){if(e===void 0)return{ok:!0};if(!Array.isArray(e))return{ok:!1,error:`must be an array`};if(e.length<1||e.length>3)return{ok:!1,error:`must contain between 1 and 3 entries`};let t=[];for(let n of e){let e=Vr.find(e=>e===n);if(!e)return{ok:!1,error:`contains unknown category ${JSON.stringify(n)}`};if(t.includes(e))return{ok:!1,error:`must not contain duplicates`};t.push(e)}return{ok:!0,categories:t}}const Hr=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function normalizeCommandDescriptorName(e){let t=e.trim();return Hr.test(t)?t:null}function sanitizeCommandDescriptorDescription(e){return ae(e).trim()}const Ur=/* @__PURE__ */ `codeModeExecutors.agentToolResultMiddleware.trustedToolPolicies.externalAuthProviders.decisionProviders.embeddingProviders.speechProviders.realtimeTranscriptionProviders.realtimeVoiceProviders.mediaUnderstandingProviders.transcriptSourceProviders.documentExtractors.imageGenerationProviders.videoGenerationProviders.musicGenerationProviders.webContentExtractors.webFetchProviders.webSearchProviders.workerProviders.workerProfileSuggestions.storageProviders.usageProviders.migrationProviders.gatewayMethodDispatch.commandRuntimeCapabilities.sessionScheduledTurns.subagentProfiles.repositoryIntegrations.tools`.split(`.`),Wr=[`accountId`,`guildId`,`channelId`,`meetingUrl`];function normalizeProviderAssistantVisibility(e){return e===`visible`||e===`manual-only`||e===`detected-only`?e:void 0}function isPluginManifestOnboardingScope(e){return e===`text-inference`||e===`image-generation`||e===`music-generation`}function normalizeDecisionCapabilities(e){if(!n(e)||!Array.isArray(e.questionTypes)||e.questionTypes.length===0||e.questionTypes.length>3||!e.questionTypes.every(e=>e===`boolean`||e===`choice`||e===`score`))return;let t={questionTypes:[...new Set(e.questionTypes)]};for(let n of[`maxQuestions`,`maxChoiceAlternatives`,`maxScoreLevels`,`maxInputTokens`]){let r=e[n];typeof r==`number`&&Number.isSafeInteger(r)&&r>0&&(t[n]=r)}return(e.inputTokenScope===`encoded-question`||e.inputTokenScope===`state-plus-each-criterion`)&&(t.inputTokenScope=e.inputTokenScope),typeof e.requiresBooleanCriteria==`boolean`&&(t.requiresBooleanCriteria=e.requiresBooleanCriteria),(e.confidence===`provider-specific`||e.confidence===`none`)&&(t.confidence=e.confidence),t}function normalizeManifestDecisionModels(e,t){let n=/* @__PURE__ */ new Set;return normalizeManifestObjectList(e,e=>{let r=y(e.provider),i=y(e.id),a=y(e.name);if(!r||!i||!a||!t?.includes(r))return;let s=`${r}/${i}`;if(n.has(s))return;let c=normalizeDecisionCapabilities(e.capabilities);return n.add(s),{provider:r,id:i,name:a,...c?{capabilities:c}:{}}})}function normalizeManifestProviderEndpoints(e){return normalizeManifestObjectList(e,e=>{let t=y(e.endpointClass);if(!t)return;let n=z(e.hosts)?.map(e=>e.toLowerCase()),r=z(e.hostSuffixes)?.map(e=>e.toLowerCase()),a=z(e.baseUrls);if(n||r||a)return i({endpointClass:t,hosts:n,hostSuffixes:r,baseUrls:a,googleVertexRegion:y(e.googleVertexRegion),googleVertexRegionHostSuffix:y(e.googleVertexRegionHostSuffix)?.toLowerCase()})})}function normalizeManifestProviderAuthAliases(e){return normalizeManifestRecord(e,e=>{if(typeof e==`string`)return y(e);if(n(e)){let t=y(e.provider),n=H(e.baseUrls);if(t&&n.length>0)return{provider:t,baseUrls:n}}})}function isPluginToolProfile(e){return e===`minimal`||e===`coding`||e===`messaging`||e===`full`}function normalizeStringListRecord(e){return normalizeManifestRecord(e,z)}function normalizeManifestStringRecord(e){return normalizeManifestRecord(e,y)}function normalizeManifestMcpServers(e){return normalizeNamedMetadataRecord(e,e=>({...e}))}function normalizeManifestRecord(e,t){if(!n(e))return;let r=Object.create(null);for(let[n,i]of Object.entries(e)){let e=y(n)??``,a=!e||I(e)?void 0:t(i,e);a&&(r[e]=a)}return Object.keys(r).length>0?r:void 0}function normalizeNamedMetadataRecord(e,t){return normalizeManifestRecord(e,(e,r)=>n(e)?t(e,r):void 0)}function normalizeManifestObjectList(e,t){if(!Array.isArray(e))return;let r=[];for(let i of e){let e=n(i)?t(i):void 0;e!==void 0&&r.push(e)}return r.length>0?r:void 0}function normalizeManifestTranscriptSources(e,t=[]){return normalizeNamedMetadataRecord(e,(e,r)=>{if(!t.includes(r))return;let i=y(e.name),a=e.autoStart,s=n(a)&&Object.entries(a).every(([e,t])=>Wr.some(t=>t===e)&&(t===`optional`||t===`required`))?Object.fromEntries(Object.entries(a)):void 0;return i||s?{...i?{name:i}:{},...s?{autoStart:s}:{}}:void 0})}function isMediaUnderstandingCapability(e){return e===`image`||e===`audio`||e===`video`}function normalizeMediaUnderstandingRecord(e,t){if(!n(e))return;let r={};for(let[n,i]of Object.entries(e)){if(!isMediaUnderstandingCapability(n))continue;let e=t(i);e!==void 0&&(r[n]=e)}return Object.keys(r).length>0?r:void 0}function normalizeMediaUnderstandingCapabilities(e){let t=H(e).filter(isMediaUnderstandingCapability);return t.length>0?t:void 0}function normalizeMediaUnderstandingNativeDocumentInputs(e){let t=H(e).filter(e=>e===`pdf`);return t.length>0?t:void 0}function normalizeMediaUnderstandingDocumentModels(e){if(!n(e))return;let t=e.pdf;if(!n(t))return;let r=optionalManifestFields({textExtraction:y(t.textExtraction),image:t.image!==!1&&y(t.image)});return r?{pdf:r}:void 0}function normalizeMediaUnderstandingProviderMetadata(e){return normalizeNamedMetadataRecord(e,e=>optionalManifestFields({capabilities:normalizeMediaUnderstandingCapabilities(e.capabilities),defaultModels:normalizeMediaUnderstandingRecord(e.defaultModels,y),autoPriority:normalizeMediaUnderstandingRecord(e.autoPriority,e=>typeof e==`number`&&Number.isFinite(e)?e:void 0),nativeDocumentInputs:normalizeMediaUnderstandingNativeDocumentInputs(e.nativeDocumentInputs),documentModels:normalizeMediaUnderstandingDocumentModels(e.documentModels)}))}function normalizeProviderBaseUrlGuard(e){if(!n(e))return;let t=y(e.provider),r=H(e.allowedBaseUrls);if(!t||r.length===0)return;let i=y(e.defaultBaseUrl);return{provider:t,...i?{defaultBaseUrl:i}:{},allowedBaseUrls:r}}function normalizeCapabilityProviderModeConfigSignal(e){if(n(e))return optionalManifestFields({path:y(e.path),default:y(e.default),allowed:z(e.allowed),disallowed:z(e.disallowed)})}function normalizeCapabilityProviderMetadataEntry(e){return optionalManifestFields({aliases:z(e.aliases),authProviders:z(e.authProviders),authSignals:normalizeManifestObjectList(e.authSignals,e=>{let t=y(e.provider);if(t)return i({provider:t,providerBaseUrl:normalizeProviderBaseUrlGuard(e.providerBaseUrl)})}),configSignals:normalizeManifestObjectList(e.configSignals,e=>{let t=y(e.rootPath);if(!t)return;let n=z(e.required),r=z(e.requiredAny),a=normalizeCapabilityProviderModeConfigSignal(e.mode);return n||r||a?i({rootPath:t,overlayPath:y(e.overlayPath),overlayMapPath:y(e.overlayMapPath),required:n,requiredAny:r,mode:a}):void 0}),referenceAudioInputs:e.referenceAudioInputs===!0||void 0})}function normalizeCapabilityProviderMetadata(e){return normalizeNamedMetadataRecord(e,normalizeCapabilityProviderMetadataEntry)}function normalizePluginToolMetadata(e){return normalizeNamedMetadataRecord(e,e=>{let t=normalizeCapabilityProviderMetadataEntry(e),n=H(e.profiles).filter(isPluginToolProfile),r={...t,...e.optional===!0?{optional:!0}:{},...n.length>0?{profiles:n}:{},...e.replaySafe===!0?{replaySafe:!0}:{},...e.sideEffecting===!0?{sideEffecting:!0}:{}};return Object.keys(r).length>0?r:void 0})}function normalizeManifestCatalog(e){if(n(e))return optionalManifestFields({featured:typeof e.featured==`boolean`?e.featured:void 0,order:typeof e.order==`number`&&Number.isFinite(e.order)?e.order:void 0})}function normalizeManifestContracts(e){if(!n(e))return;let t={};for(let n of Ur){let r=H(e[n]);r.length>0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function isManifestConfigLiteral(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function normalizeManifestConfigContracts(e){if(!n(e))return;let t=H(e.compatibilityMigrationPaths),r=H(e.compatibilityRuntimePaths),i=n(e.secretInputs)?e.secretInputs:void 0,a=normalizeManifestObjectList(e.dangerousFlags,e=>{let t=y(e.path)??``;return t&&isManifestConfigLiteral(e.equals)?{path:t,equals:e.equals}:void 0}),s=i?normalizeManifestObjectList(i.paths,e=>{let t=y(e.path)??``;if(!t)return;let n=e.expected===`string`?e.expected:void 0,r=e.ownerKind===`capability`||e.ownerKind===`route`?e.ownerKind:void 0;return{path:t,...n?{expected:n}:{},...r?{ownerKind:r}:{}}}):void 0,c=s?{...typeof i?.bundledDefaultEnabled==`boolean`?{bundledDefaultEnabled:i.bundledDefaultEnabled}:{},paths:s}:void 0,l={...t.length>0?{compatibilityMigrationPaths:t}:{},...r.length>0?{compatibilityRuntimePaths:r}:{},...a?{dangerousFlags:a}:{},...c?{secretInputs:c}:{}};return Object.keys(l).length>0?l:void 0}function optionalManifestFields(e){return i(e),Object.keys(e).length>0?e:void 0}const Gr=/* @__PURE__ */ new Set([`aix`,`android`,`darwin`,`freebsd`,`haiku`,`linux`,`openbsd`,`sunos`,`win32`,`cygwin`,`netbsd`]);function normalizeManifestPlatforms(e){return H(e).filter(e=>Gr.has(e))}function normalizeSetupPresentationHttpsUrl(e){let t=y(e),n=t?URL.parse(t):null;if(!n)return;let r=n.toString();return n.protocol===`https:`&&n.hostname&&!n.username&&!n.password&&r.length<=2048?r:void 0}function controlUiSource(e){let t=n(e.openclaw)?e.openclaw.controlUi:void 0;if(t!==void 0){if(typeof t!=`string`||!t.trim())throw Error(`package.json openclaw.controlUi must name a browser source entrypoint.`);return t}}function normalizeManifestControlUi(e,t=[]){if(e===void 0)return Ze(void 0);if(!n(e)||Object.keys(e).some(e=>![`entry`,`styles`,`panelIcon`,`activation`,`settingsViews`].includes(e)))return G(`controlUi contains an unknown field`);if(e.activation!==void 0&&e.activation!==`settings-only`)return G(`controlUi.activation must be settings-only when specified`);let r=new Set(Array.isArray(t)?t:[]),i=[],a=/* @__PURE__ */ new Set;if(e.settingsViews!==void 0){if(!Array.isArray(e.settingsViews)||e.settingsViews.length===0||e.settingsViews.length>2+r.size)return G(`controlUi.settingsViews must declare unique Settings placements`);for(let t of e.settingsViews){if(!n(t))return G(`invalid Control UI Settings placement`);let e;if(Object.keys(t).length===2&&t.section===`memory`&&(t.panel===`overview`||t.panel===`memories`))e={section:`memory`,panel:t.panel};else if(Object.keys(t).length===3&&t.section===`channels`&&t.panel===`detail`&&typeof t.channelId==`string`&&/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(t.channelId)&&r.has(t.channelId))e={section:`channels`,panel:`detail`,channelId:t.channelId};else return G(`Control UI Settings placement must name Memory or an owned channel detail`);let s=JSON.stringify(e);if(a.has(s))return G(`controlUi.settingsViews must declare unique Settings placements`);a.add(s),i.push(e)}}if(e.activation===`settings-only`&&!e.settingsViews)return G(`settings-only Control UI requires a Settings placement`);let s=typeof e.entry==`string`?e.entry.replace(/^\.\//u,``):``;if(s.length>512||!/^dist\/(?:[\w-][\w.-]*\/)+[\w-][\w.-]*\.m?js$/u.test(s))return G(`controlUi.entry must be a JavaScript file in a dedicated dist subdirectory`);if(e.styles!==void 0&&(!Array.isArray(e.styles)||e.styles.length>16))return G(`controlUi.styles must be an array of at most 16 stylesheets`);let c=s.slice(0,s.lastIndexOf(`/`)+1),l=typeof e.panelIcon==`string`?e.panelIcon.replace(/^\.\//u,``):void 0;if(e.panelIcon!==void 0&&(!l||l.length>512||!/^(?:[\w-][\w.-]*\/)*[\w-][\w.-]*\.svg$/u.test(l)))return G(`controlUi.panelIcon must be a plugin-relative SVG path`);let u=[];for(let t of e.styles??[]){let e=typeof t==`string`?t.replace(/^\.\//u,``):``;if(e.length>512||!e.startsWith(c)||!/^(?:[\w-][\w.-]*\/)+[\w-][\w.-]*\.css$/u.test(e))return G(`controlUi.styles must contain CSS files under the entry's asset directory`);u.includes(e)||u.push(e)}return Ze({entry:s,...l?{panelIcon:l}:{},...u.length>0?{styles:u}:{},...e.activation===`settings-only`?{activation:e.activation}:{},...i.length>0?{settingsViews:i}:{}})}function normalizeManifestActivation(e){if(!n(e))return;let t={};typeof e.onStartup==`boolean`&&(t.onStartup=e.onStartup);for(let n of[`onProviders`,`onAgentHarnesses`,`onCommands`,`onChannels`,`onRoutes`,`onConfigPaths`]){let r=H(e[n]);r.length>0&&(t[n]=r)}let r=H(e.onCapabilities).filter(e=>e===`provider`||e===`channel`||e===`tool`||e===`hook`);return r.length>0&&(t.onCapabilities=r),Object.keys(t).length>0?t:void 0}function normalizeChannelAccountKeyPolicies(e,t){if(!n(e))return;let r=Object.create(null);for(let i of t){if(I(i)||!Object.hasOwn(e,i))continue;let t=e[i],a=n(t)?y(t.canonicalAliasesRequireOwnField):void 0;a&&!I(a)&&(r[i]={canonicalAliasesRequireOwnField:a})}return Object.keys(r).length?r:void 0}function normalizeManifestCliCommands(e){if(!Array.isArray(e))return;let t=/* @__PURE__ */ new Set;return normalizeManifestObjectList(e,e=>{if(typeof e.name!=`string`||typeof e.description!=`string`)return;let n=normalizeCommandDescriptorName(e.name),r=sanitizeCommandDescriptorDescription(e.description);if(n&&r&&typeof e.hasSubcommands==`boolean`&&!t.has(n))return t.add(n),{name:n,description:r,hasSubcommands:e.hasSubcommands}})??[]}function normalizeManifestSetup(e){if(!n(e))return;let t=n(e.nativeSessionCatalog)?i({label:y(e.nativeSessionCatalog.label)??``,legacyDefaultEnabled:e.nativeSessionCatalog.legacyDefaultEnabled===!0||void 0,nodeCommands:z(e.nativeSessionCatalog.nodeCommands),description:y(e.nativeSessionCatalog.description)}):void 0;return optionalManifestFields({providers:normalizeManifestObjectList(e.providers,e=>{let t=y(e.id)??``;if(t)return i({id:t,authMethods:z(e.authMethods),envVars:z(e.envVars),authEvidence:normalizeManifestObjectList(e.authEvidence,e=>{if(e.type!==`local-file-with-env`)return;let t=y(e.credentialMarker);if(!t)return;let n=y(e.fileEnvVar),r=z(e.fallbackPaths);if(n||r)return i({type:`local-file-with-env`,fileEnvVar:n,fallbackPaths:r,requiresAnyEnv:z(e.requiresAnyEnv),requiresAllEnv:z(e.requiresAllEnv),credentialMarker:t,source:y(e.source)})})})}),cliBackends:z(e.cliBackends),configMigrations:z(e.configMigrations),nativeSessionCatalog:t?.label?t:void 0,requiresRuntime:typeof e.requiresRuntime==`boolean`?e.requiresRuntime:void 0})}function normalizeManifestQaRunners(e){return normalizeManifestObjectList(e,e=>{let t=y(e.commandName)??``;if(t)return i({commandName:t,description:y(e.description)})})}function normalizeDashboardCapabilityBase(e,t,r){if(!n(e))return`${t}[${r}] must be an object`;let i=y(e.id),a=y(e.method),s=y(e.description);return!i||!/^[a-z0-9][a-z0-9._-]*$/u.test(i)?`${t}[${r}].id must be a lowercase capability id`:a?s?{id:i,method:a,description:s}:`${t}[${r}].description must be a non-empty string`:`${t}[${r}].method must be a non-empty string`}function normalizeManifestDashboard(e){if(e===void 0)return{ok:!0};if(!n(e))return{ok:!1,error:`dashboard must be an object`};let t=[];for(let n of[`dataBindings`,`actionVerbs`]){let r=e[n];if(r!==void 0&&!Array.isArray(r))return{ok:!1,error:`dashboard.${n} must be an array`};t.push({field:n,entries:r??[]})}let r={};for(let e of t){let{field:t}=e,i=[];for(let[r,a]of e.entries.entries()){let e=normalizeDashboardCapabilityBase(a,`dashboard.${t}`,r);if(typeof e==`string`)return{ok:!1,error:e};let s=t===`actionVerbs`&&n(a)?a.paramShape:void 0;if(s!==void 0&&!n(s))return{ok:!1,error:`dashboard.actionVerbs[${r}].paramShape must be a JSON Schema object`};i.push({...e,...s?{paramShape:s}:{}})}i.length>0&&(r[t]=i)}return Object.keys(r).length>0?{ok:!0,dashboard:r}:{ok:!0}}function normalizeProviderChannelLogin(e){if(!n(e)||Object.keys(e).some(e=>e!==`aliases`)||e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(e=>typeof e!=`string`||!e.trim())))return;let t=F(e.aliases);return t.length>0?{aliases:t}:{}}function normalizeProviderAuthChoices(e){return normalizeManifestObjectList(e,e=>{let t=y(e.provider)??``,n=y(e.method)??``,r=y(e.choiceId)??``;if(!t||!n||!r)return;let a=H(e.onboardingScopes).filter(isPluginManifestOnboardingScope);return i({provider:t,method:n,choiceId:r,modelTarget:e.modelTarget===`utility`?`utility`:void 0,platforms:e.platforms===void 0?void 0:normalizeManifestPlatforms(e.platforms),choiceLabel:y(e.choiceLabel),choiceHint:y(e.choiceHint),icon:normalizeSetupPresentationHttpsUrl(e.icon),website:normalizeSetupPresentationHttpsUrl(e.website),docsUrl:normalizeSetupPresentationHttpsUrl(e.docsUrl),assistantPriority:typeof e.assistantPriority==`number`&&Number.isFinite(e.assistantPriority)?e.assistantPriority:void 0,assistantVisibility:normalizeProviderAssistantVisibility(e.assistantVisibility),deprecatedChoiceIds:z(e.deprecatedChoiceIds),groupId:y(e.groupId),groupLabel:y(e.groupLabel),groupHint:y(e.groupHint),onboardingFeatured:e.onboardingFeatured===!0||void 0,appGuidedDiscovery:e.appGuidedDiscovery===!0||void 0,optionKey:y(e.optionKey),cliFlag:y(e.cliFlag),cliOption:y(e.cliOption),cliDescription:y(e.cliDescription),appGuidedSecret:e.appGuidedSecret===!0||void 0,personalAccount:e.personalAccount===!0||void 0,appGuidedActionLabel:y(e.appGuidedActionLabel),appGuidedAuth:e.appGuidedAuth===`oauth`||e.appGuidedAuth===`device-code`?e.appGuidedAuth:void 0,credentialOnly:e.credentialOnly===!0||void 0,channelLogin:normalizeProviderChannelLogin(e.channelLogin),onboardingScopes:a.length>0?a:void 0})})}function normalizeConfigUiHints(e){if(!n(e))return;let t=Object.create(null);for(let[r,i]of Object.entries(e)){if(!n(i))continue;let e={...i};`presentation`in e&&e.presentation!==`phone-number`&&delete e.presentation,`multiline`in e&&typeof e.multiline!=`boolean`&&delete e.multiline,t[r]=e}return Object.keys(t).length>0?t:void 0}function normalizeChannelConfigs(e){return normalizeNamedMetadataRecord(e,e=>{let t=n(e.schema)?e.schema:null;if(t)return i({schema:t,uiHints:normalizeConfigUiHints(e.uiHints),runtime:n(e.runtime)&&typeof e.runtime.safeParse==`function`?e.runtime:void 0,label:y(e.label),description:y(e.description),preferOver:z(e.preferOver),commands:normalizeManifestChannelCommandDefaults(e.commands)})})}function normalizeManifestChannelCommandDefaults(e){if(!n(e))return;let t={};for(let n of[`nativeCommandsAutoEnabled`,`nativeSkillsAutoEnabled`])typeof e[n]==`boolean`&&(t[n]=e[n]);return Object.keys(t).length>0?t:void 0}const Kr=[`index.ts`,`index.js`,`index.mjs`,`index.cjs`];var CachedFileType=class{constructor(e){this.mode=e}isFile(){return(this.mode&q.constants.S_IFMT)===q.constants.S_IFREG}isDirectory(){return(this.mode&q.constants.S_IFMT)===q.constants.S_IFDIR}isSymbolicLink(){return(this.mode&q.constants.S_IFMT)===q.constants.S_IFLNK}},CachedStat=class extends CachedFileType{constructor(e){super(e.mode),this.uid=e.uid,this.nlink=e.nlink,this.dev=e.dev,this.ino=e.ino,this.size=e.size,this.mtimeMs=e.mtimeMs}};function capturedPluginFile(e,t,n,r){return{ok:!0,path:e,rootRealPath:t,contents:n,hash:Ct.createHash(`sha256`).update(n).digest(`hex`),signature:{size:r.size,mtimeMs:r.mtimeMs,ctimeMs:r.ctimeMs}}}function entryKey(e,t){return JSON.stringify([Y.normalize(e),t])}function enforceFileSize(e,t,n=`validation`,r){return e.ok&&t!==void 0&&Math.max(e.signature.size,e.contents.length)>t?{ok:!1,failure:{ok:!1,reason:n,error:new le(`too-large`,`File exceeds ${t} bytes: ${r??e.path}`)}}:e}function pathFacts(e){let t=Y.resolve(e),n=getPluginCacheRoot(Y.dirname(t)),r=Y.basename(t),i=n.paths.get(r);return i||(i={},n.paths.set(r,i)),i}function resolveRealpath(e){if(Y.resolve(e)===e){if(pathFacts(e).nativeRealpath===e)return e;if(process.platform!==`win32`){let t=Y.dirname(e),n=pluginCacheLstatSync(e);if(t!==e&&n&&!n.isSymbolicLink()){let n=pluginCacheRealpathSync(t);if(n)return Y.join(n,Y.basename(e))}}else if(pluginCacheRealpathSync(e,!0)===e)return e}return q.realpathSync(e)}function pluginCacheRealpathSync(e,t=!1){let n=pathFacts(e),r=t?`nativeRealpath`:`realpath`;if(n[r]===void 0)try{n[r]=t?q.realpathSync.native(e):resolveRealpath(e),pathFacts(n[r])[r]=n[r]}catch{n[r]=null}return n[r]}function pluginCacheLstatSync(e){let t=pathFacts(e);if(t.lstat===void 0)try{t.lstat=new CachedStat(q.lstatSync(e))}catch{t.lstat=null}return t.lstat}function readPluginCacheFile(e){let t=getPluginCacheRoot(e.rootDir),n=e.maxBytes===null?void 0:e.maxBytes??16777216,r=entryKey(e.relativePath,e.rejectHardlinks),i=t.files.get(r)??t.files.get(JSON.stringify([r,n]));if(!i&&!e.rejectHardlinks){let n=t.files.get(entryKey(e.relativePath,!0));i=n?.ok?n:void 0}if(i)return enforceFileSize(i,n);let a=Y.resolve(e.rootDir),s=Y.resolve(a,e.relativePath),c=t.checkedEntries.get(r);if(pathFacts(s).exists===!1||c&&(!c.ok||!c.exists)){let e={ok:!1,failure:c&&!c.ok?c:{ok:!1,reason:`path`}};return t.files.set(r,e),e}let l=e.rootRealPath??pluginCacheRealpathSync(a)??a,u=getPluginCacheRoot(l).files.get(r);if(u?.ok)return bindPluginCacheRoot(a,l),enforceFileSize(u,n);let f=Y.resolve(l,e.relativePath),p=openPluginRootFileSync({filePath:f,rootRealPath:l,rootPath:l,boundaryLabel:`plugin root`,rejectHardlinks:e.rejectHardlinks,maxBytes:n}),m;if(!p.ok)m={ok:!1,failure:p},p.reason===`path`&&p.error&&typeof p.error==`object`&&`code`in p.error&&p.error.code===`ENOENT`&&(pathFacts(s).exists=!1,pathFacts(f).exists=!1);else{t=bindPluginCacheRoot(a,p.rootRealPath);try{let e=n===void 0?q.readFileSync(p.fd):me(p.fd,n);m=capturedPluginFile(p.path,p.rootRealPath,e,p.stat),Object.assign(pathFacts(f),{exists:!0,stat:new CachedStat(p.stat)}),t.checkedEntries.set(r,{ok:!0,path:p.path,rootRealPath:p.rootRealPath,exists:!0})}catch(e){m={ok:!1,failure:{ok:!1,reason:`io`,error:e},failurePhase:`read`}}finally{q.closeSync(p.fd)}}return m.ok||d(m.failure.error),t.files.set(m.ok?r:JSON.stringify([r,n]),m),m}function parsePluginCacheJson(e,t={}){let n=t.json5?`json5`:`json`;if(!e[n])try{let r=e.contents.toString(`utf8`);e[n]={ok:!0,value:t.json5?pe(r):JSON.parse(r)}}catch(t){d(t),e[n]={ok:!1,error:t}}return e[n]}function loadPluginControlUiDeclaration(e){let t=`dist/openclaw.plugin.json`;if(!pluginCacheLstatSync(Y.join(e.rootDir,t))||!pluginCacheLstatSync(Y.join(e.rootDir,`package.json`)))return normalizeManifestControlUi(e.controlUi,e.channels);let r=readPluginCacheFile({...e,relativePath:`package.json`});if(!r.ok)return G(`generated Control UI package metadata could not be safely read`);let i=parsePluginCacheJson(r);if(!i.ok||!n(i.value))return G(`generated Control UI package metadata must be an object`);try{if(!controlUiSource(i.value))return normalizeManifestControlUi(e.controlUi,e.channels)}catch(e){return G(String(e))}let a=readPluginCacheFile({rootDir:e.rootDir,relativePath:t,rejectHardlinks:e.rejectHardlinks,rootRealPath:e.rootRealPath,maxBytes:262144});if(!a.ok)return G(`generated Control UI manifest could not be safely read`);let s=parsePluginCacheJson(a);return!s.ok||!n(s.value)||s.value.controlUi===void 0?G(`generated Control UI manifest must contain controlUi`):normalizeManifestControlUi(s.value.controlUi,e.channels)}function coerceDoctorSessionRouteStateOwners(e){return Array.isArray(e)?e.flatMap(e=>{let t=r(e);if(typeof t?.id!=`string`||typeof t.label!=`string`)return[];let n=t.id.trim(),i=t.label.trim();if(!n||!i)return[];let a={id:n,label:i,providerIds:H(t.providerIds),runtimeIds:H(t.runtimeIds),cliSessionKeys:H(t.cliSessionKeys),authProfilePrefixes:H(t.authProfilePrefixes)};return[`providerIds`,`runtimeIds`,`cliSessionKeys`,`authProfilePrefixes`].every(e=>t[e]===void 0||a[e].length>0)?[a]:[]}):[]}function normalizeManifestCommandAliases(e){if(!Array.isArray(e))return;let t=[];for(let r of e){let e=typeof r==`string`?{name:r}:r;if(!n(e))continue;let i=y(e.name)??``;if(!i)continue;let a=e.kind===`runtime-slash`?e.kind:void 0,s=y(e.cliCommand)??``;t.push({name:i,...a?{kind:a}:{},...s?{cliCommand:s}:{}})}return t.length>0?t:void 0}function normalizeConfigGroups(e,t){if(!Array.isArray(e)||e.length===0||!n(t.properties))return;let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[];for(let s of e){if(!n(s))return;let e=typeof s.id==`string`?s.id.trim():``,c=typeof s.title==`string`?s.title.trim():``;if(!e||!c||r.has(e)||s.order!==void 0&&!Number.isInteger(s.order)||!Array.isArray(s.properties)||s.properties.length===0)return;let l=[];for(let e of s.properties){if(typeof e!=`string`||!e||!Object.hasOwn(t.properties,e)||i.has(e))return;i.add(e),l.push(e)}r.add(e),a.push({id:e,title:c,...typeof s.order==`number`?{order:s.order}:{},properties:l})}return a}const qr=`https://models.opencode.ai/api.json`,Jr=[{id:`openCode`,label:`OpenCode`,url:qr,authoritative:!0},{id:`venice`,label:`Venice`,url:`https://api.venice.ai/api/v1/models`,authoritative:!0},{id:`chutes`,label:`Chutes`,url:`https://llm.chutes.ai/v1/models`,authoritative:!0},{id:`cerebras`,label:`Cerebras`,url:`https://api.cerebras.ai/public/v1/models`,authoritative:!0},{id:`deepinfra`,label:`DeepInfra`,url:`https://api.deepinfra.com/models/list`,authoritative:!0},{id:`modelsDev`,label:`models.dev`,url:qr,authoritative:!1},{id:`openRouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1/models`,authoritative:!1},{id:`liteLLM`,label:`LiteLLM`,url:`https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json`,authoritative:!1}];function normalizeModelPricingProvider(e){let t=s(e);if(!t)return;let n=normalizeProviderId(y(t.priceAs)??``),r={...typeof t.external==`boolean`?{external:t.external}:{},...n?{priceAs:n}:{}};for(let{id:e}of Jr){let n=t[e];if(n===!1){r[e]=!1;continue}let i=s(n),a=normalizeProviderId(y(i?.provider)??``),c=H(i?.modelIdTransforms).filter(e=>e===`version-dots`),l={...a?{provider:a}:{},...i?.passthroughProviderModel===!0?{passthroughProviderModel:!0}:{},...c.length>0?{modelIdTransforms:c}:{}};Object.keys(l).length>0&&(r[e]=l)}return Object.keys(r).length>0?r:void 0}function normalizeManifestProviderRequestProvider(e){if(!n(e))return;let t=y(e.family),r=y(e.compatibilityFamily)===`moonshot`?`moonshot`:void 0,i=n(e.openAICompletions)?e.openAICompletions.supportsStreamingUsage:void 0,a=typeof i==`boolean`?{supportsStreamingUsage:i}:void 0,s={...t?{family:t}:{},...r?{compatibilityFamily:r}:{},...n(e.modelParamsSchema)?{modelParamsSchema:e.modelParamsSchema}:{},...a?{openAICompletions:a}:{}};return Object.keys(s).length>0?s:void 0}const Yr=12e4;function normalizeManifestModelSupport(e){if(n(e))return optionalManifestFields({modelPrefixes:z(e.modelPrefixes),modelPatterns:z(e.modelPatterns)})}function normalizeOwnedProviderMap(e,t,r){if(!n(e)||!n(e.providers))return;let i=new Set([...t].map(e=>normalizeProviderId(e)).filter(Boolean)),a={};for(let[t,n]of Object.entries(e.providers)){let e=normalizeProviderId(t),s=e&&i.has(e)?r(n):null;e&&s&&(a[e]=s)}return Object.keys(a).length>0?a:void 0}function normalizeManifestModelPricing(e,t){let n=normalizeOwnedProviderMap(e,t.ownedProviders,normalizeModelPricingProvider);return n?{providers:n}:void 0}function normalizeManifestModelIdPrefixRules(e){return normalizeManifestObjectList(e,e=>{let t=y(e.modelPrefix),n=y(e.prefix);return t&&n?{modelPrefix:t,prefix:n}:void 0})}function normalizeManifestModelIdNormalizationProvider(e){if(!n(e))return;let t={};if(n(e.aliases))for(let[n,r]of Object.entries(e.aliases)){let e=normalizeProviderId(n),i=y(r);e&&i&&(t[e]=i)}return optionalManifestFields({aliases:Object.keys(t).length>0?t:void 0,stripPrefixes:z(e.stripPrefixes),prefixWhenBare:y(e.prefixWhenBare),prefixWhenBareAfterAliasStartsWith:normalizeManifestModelIdPrefixRules(e.prefixWhenBareAfterAliasStartsWith)})}function normalizeManifestModelIdNormalization(e,t){let n=normalizeOwnedProviderMap(e,t.ownedProviders,normalizeManifestModelIdNormalizationProvider);return n?{providers:n}:void 0}function normalizeManifestProviderRequest(e,t){let n=normalizeOwnedProviderMap(e,t.ownedProviders,normalizeManifestProviderRequestProvider);return n?{providers:n}:void 0}function normalizeManifestPositiveInteger(e,t){return k(e,{min:1,max:t})}function normalizeManifestSecretProviderIntegrations(e){return normalizeNamedMetadataRecord(e,e=>{let t=y(e.command);if(e.source!==`exec`||t!=="${node}")return;let n=[];if(Array.isArray(e.args)){for(let t of e.args)if(!(typeof t!=`string`||t.length>1024)&&(n.push(t),n.length>=128))break}let r=H(e.passEnv).filter(e=>ie.test(e)).slice(0,128);return i({providerAlias:y(e.providerAlias),displayName:y(e.displayName),description:y(e.description),source:`exec`,command:t,args:n.length>0?n:void 0,timeoutMs:normalizeManifestPositiveInteger(e.timeoutMs,Yr),noOutputTimeoutMs:normalizeManifestPositiveInteger(e.noOutputTimeoutMs,Yr),maxOutputBytes:normalizeManifestPositiveInteger(e.maxOutputBytes,20971520),jsonOnly:typeof e.jsonOnly==`boolean`?e.jsonOnly:void 0,env:normalizeManifestStringRecord(e.env),passEnv:r.length>0?r:void 0})})}const Xr=[`claw`,`knot`,`dash`,`absolutely`,`tide`,`beacon`,`phosphor`,`crt`,`manuscript`,`rose`,`miami`],Zr=/* @__PURE__ */ RegExp(`^[a-z0-9][a-z0-9_-]{0,63}$`);function isBuiltinThemeId(e){return Xr.some(t=>t===e)}function isThemeId(e){if(isBuiltinThemeId(e))return!0;if(typeof e!=`string`||e.length>256)return!1;let t=e.lastIndexOf(`/`),n=e.slice(0,t);return t>0&&!n.startsWith(`user/`)&&/^@?[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/i.test(n)&&Zr.test(e.slice(t+1))}const Qr=[`claw`,`mark`],$r=[`penguin`,`fedora`],ei=[`fedora`,`crown`,`santa`,`party`,`pumpkin`],ti=/^[a-z0-9][a-z0-9_-]{0,31}$/,ni=`[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:e[+-]?\\d+)?`,$=`${ni}%?`,ri=`${ni}(?:deg|grad|rad|turn)?`;`${ri}${$}`,`${$}${$}${$}${ri}${$}${$}${$}${$}${ri}${$}`,`${$}${$}${$}${$}`;const ii=`(?:--[a-z0-9_-]*|-?[a-z_][a-z0-9_-]*)`,ai=`(?:"[a-z0-9 ,'._-]*"|'[a-z0-9 ,"._-]*'|${ii}(?: +${ii})*)`;`${ai}${ai}`;function objectProperties(e){return e.type===`ObjectExpression`?e.properties.filter(e=>e.type===`Property`):[]}function propertyName(e){return e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?String(e.key.value):``}function validateArtworkDuplicates(e){let{parseExpressionAt:t}=pt(import.meta.url)(`acorn`),n=t(`(${e}\n)`,0,{ecmaVersion:`latest`});for(let e of objectProperties(n))if(propertyName(e)===`themes`&&e.value.type===`ArrayExpression`){for(let t of e.value.elements)if(t&&t.type===`ObjectExpression`)for(let e of objectProperties(t)){let t=propertyName(e);if(t!==`icons`&&t!==`hats`&&t!==`critters`&&t!==`backgrounds`)continue;let n=/* @__PURE__ */ new Set;for(let r of objectProperties(e.value)){let e=propertyName(r);if(n.has(e))throw Error(`themes.${t} has duplicate artwork ID ${e}`);n.add(e)}}}}function normalizeArtworkEntries(e,t,r,i){if(e===void 0)return;if(!n(e))throw Error(`${t} must be a map with at most 8 entries`);let a=Object.entries(e);if(a.length>8)throw Error(`${t} must be a map with at most 8 entries`);for(let[e]of a)if(!ti.test(e)||r.includes(e))throw Error(`${t}.${e} must use a safe local ID outside the built-in catalog`);return Object.fromEntries(a.map(([e,n])=>[e,i(n,`${t}.${e}`)]))}function normalizeArtworkPath(e,t){let n=typeof e==`string`?e.replace(/^\.\//,``):``;if(!/^(?:[a-z0-9_-][a-z0-9._-]*\/)*[a-z0-9_-][a-z0-9._-]*\.svg$/i.test(n))throw Error(`${t} must be an SVG file inside the plugin root`);return n}function normalizeBackgrounds(e,t){if(e===void 0)return;let r=n(e)?Object.entries(e):[];if(!r.length||r.some(([e])=>e!==`light`&&e!==`dark`))throw Error(`${t} must map light and/or dark to an image`);return Object.fromEntries(r.map(([e,n])=>{let r=typeof n==`string`?n.replace(/^\.\//,``):``;if(!/^(?:[a-z0-9_-][a-z0-9._-]*\/)*[a-z0-9_-][a-z0-9._-]*\.(?:png|jpe?g|webp)$/i.test(r))throw Error(`${t}.${e} must be a PNG, JPEG, or WebP file inside the plugin root`);return[e,r]}))}function normalizeCritter(e,t){if(!n(e))throw Error(`${t} must be an object with an SVG source`);let{source:r,title:a,crossMs:s}=e;if(Object.keys(e).some(e=>![`source`,`title`,`crossMs`].includes(e)))throw Error(`${t} has unsupported fields`);if(a!==void 0&&(typeof a!=`string`||a.length>60||/[\p{Cc}\p{Cf}\p{Cs}]/u.test(a)))throw Error(`${t}.title must be at most 60 printable characters`);if(s!==void 0&&(typeof s!=`number`||!Number.isInteger(s)||s<5e3||s>9e4))throw Error(`${t}.crossMs must be an integer from 5000 to 90000`);return i({source:normalizeArtworkPath(r,`${t}.source`),title:a,crossMs:s})}function normalizeManifestThemes(e,t,r){if(e===void 0)return{ok:!0};if(!Array.isArray(e)||e.length>32)return{ok:!1,error:`themes must be an array with at most 32 entries`};if(e.length&&(t===`user`||!isThemeId(`${t}/x`)))return{ok:!1,error:`themes require a portable plugin ID outside the reserved user namespace`};let a=[],s=/* @__PURE__ */ new Set;for(let[t,r]of e.entries()){if(!n(r))return{ok:!1,error:`themes[${t}] must be an object`};let{id:e,name:c,description:l,source:u,icons:d,hats:f,critters:p,backgrounds:m}=r;if(Object.keys(r).some(e=>![`id`,`name`,`description`,`source`,`icons`,`hats`,`critters`,`backgrounds`].includes(e))||typeof e!=`string`||!Zr.test(e)||s.has(e)||typeof c!=`string`||!c.trim()||c.trim().length>80||typeof l!=`string`||!l.trim()||l.trim().length>320||P(c+l)||typeof u!=`string`)return{ok:!1,error:`themes[${t}] requires a unique safe id, name, description, and JSON source`};let h=u.replace(/^\.\//,``);if(!/^(?:[a-z0-9_-][a-z0-9._-]*\/)*[a-z0-9_-][a-z0-9._-]*\.json$/i.test(h))return{ok:!1,error:`themes[${t}].source must be a JSON file inside the plugin root`};try{a.push({id:e,name:c.trim(),description:l.trim(),source:h,...i({icons:normalizeArtworkEntries(d,`themes[${t}].icons`,Qr,normalizeArtworkPath),hats:normalizeArtworkEntries(f,`themes[${t}].hats`,ei,normalizeArtworkPath),critters:normalizeArtworkEntries(p,`themes[${t}].critters`,$r,normalizeCritter),backgrounds:normalizeBackgrounds(m,`themes[${t}].backgrounds`)})})}catch(e){return{ok:!1,error:e instanceof Error?e.message:`invalid theme artwork`}}s.add(e)}if(r&&a.some(e=>e.icons||e.hats||e.critters||e.backgrounds))try{validateArtworkDuplicates(r)}catch(e){return{ok:!1,error:e instanceof Error?e.message:`invalid theme artwork`}}return{ok:!0,themes:a}}function normalizePluginPolicyId(e){return M(e)??``}const oi=`openclaw.plugin.json`,si=/* @__PURE__ */ new Set([`node-mcp`,`openclaw`]),ci=/* @__PURE__ */ new Set([`memory`,`context-engine`]);function isCoreReservedPluginId(e){return si.has(normalizePluginPolicyId(e))}function parsePluginKind(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:[],n=[];for(let e of t){if(typeof e!=`string`||!ci.has(e))continue;let t=e;n.includes(t)||n.push(t)}return n.length===0?void 0:n.length===1?n[0]:n}function parseDoctorStateMigrationDescriptors(e){if(typeof e==`boolean`)return e;if(!Array.isArray(e))return;let t=/* @__PURE__ */ new Set;return e.flatMap(e=>{if(!n(e))return[];let r=y(e.id);return!r||t.has(r)?[]:(t.add(r),[{id:r,...e.doctorOnly===!0?{doctorOnly:!0}:{},...e.phase===`after-session-repair`?{phase:`after-session-repair`}:{}}])})}function parseManifestBackupResources(e){if(e===void 0)return{ok:!0};if(!Array.isArray(e))return{ok:!1,error:`backupResources must be an array`};let t=/* @__PURE__ */ new Map;for(let[r,i]of e.entries()){if(!n(i)||Object.keys(i).some(e=>![`disposition`,`scope`,`relativePath`,`databaseFamily`,`profile`].includes(e))||!(`disposition`in i)||!(`scope`in i)||!(`relativePath`in i))return{ok:!1,error:`backupResources[${r}] requires disposition, scope, relativePath, and optional databaseFamily or profile`};let{disposition:e,scope:a,relativePath:s,databaseFamily:c,profile:l}=i;if(e!==`include`&&e!==`regenerable`)return{ok:!1,error:`backupResources[${r}].disposition is invalid`};if(l!==void 0&&(l!==`local-companion`||e!==`regenerable`))return{ok:!1,error:`backupResources[${r}].profile requires a local-companion regenerable resource`};if(a!==`state`&&a!==`agent`)return{ok:!1,error:`backupResources[${r}].scope is invalid`};if(c!==void 0&&(e!==`include`||a!==`state`||c!==`state`))return{ok:!1,error:`backupResources[${r}].databaseFamily is invalid`};if(typeof s!=`string`||!s||s.includes(`\\`)||s.includes(`\0`)||Y.posix.isAbsolute(s)||Y.win32.isAbsolute(s)||/^[A-Za-z][A-Za-z\d+.-]*:/.test(s)||s.split(`/`).some(e=>!e||e===`.`||e===`..`))return{ok:!1,error:`backupResources[${r}].relativePath must be a strict relative POSIX path`};let u={disposition:e,scope:a,relativePath:s,...c===void 0?{}:{databaseFamily:c},...l===void 0?{}:{profile:l}};t.set(`${a}\0${s}\0${e}\0${c??``}\0${l??``}`,u)}return{ok:!0,resources:[...t.entries()].toSorted(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>e)}}function loadPluginManifest(e,t=!0,r){let i=readPluginCacheFile({rootDir:e,relativePath:oi,...r===void 0?{}:{rootRealPath:r},maxBytes:262144,rejectHardlinks:t}),a=i.ok?i.path:Y.join(e,oi);if(!i.ok)return re(i.failure,{path:()=>({ok:!1,error:`plugin manifest not found: ${a}`,manifestPath:a}),fallback:e=>({ok:!1,error:`unsafe plugin manifest path: ${a} (${e.reason})`,manifestPath:a})});if(i.manifest)return i.manifest;let cacheResult=e=>i.manifest=e,fail=e=>cacheResult({ok:!1,error:e,manifestPath:a}),s=parsePluginCacheJson(i,{json5:!0});if(!s.ok)return fail(`failed to parse plugin manifest: ${String(s.error)}`);let c=s.value;if(!n(c))return fail(`plugin manifest must be an object`);let l=y(c.id)??``;if(!l)return fail(`plugin manifest requires id`);if(isCoreReservedPluginId(l))return fail(`plugin manifest id "${l}" is reserved by OpenClaw core`);let u=n(c.configSchema)?c.configSchema:null;if(!u)return fail(`plugin manifest requires configSchema`);if(c.generationOverlap!==void 0&&typeof c.generationOverlap!=`boolean`)return fail(`plugin manifest generationOverlap must be a boolean`);let d=parseManifestBackupResources(c.backupResources);if(!d.ok)return cacheResult({ok:!1,error:`invalid plugin manifest backupResources: ${d.error}`,manifestPath:a,diagnosticCode:`backup-resource-declaration-invalid`});let f=validatePluginCategories(c.categories);if(!f.ok)return fail(`invalid plugin manifest categories: ${f.error}`);let p=parsePluginKind(c.kind),m;if(c.contextEngineIds!==void 0){if(!(Array.isArray(p)?p:[p]).includes(`context-engine`)||!Array.isArray(c.contextEngineIds)||c.contextEngineIds.length===0||c.contextEngineIds.some(e=>typeof e!=`string`||!e.trim()||[`legacy`,`none`].includes(e.trim().toLowerCase())))return cacheResult({ok:!1,error:`contextEngineIds requires context-engine kind and a nonempty array of nonreserved engine IDs`,manifestPath:a});m=[...new Set(H(c.contextEngineIds))]}let h=H(c.requiresPlugins),g=normalizeManifestPlatforms(c.enabledByDefaultOnPlatforms),_=H(c.legacyPluginIds),v=H(c.autoEnableWhenConfiguredProviders),b=H(c.providers),x=H(c.channels),S=normalizeManifestContracts(c.contracts),C=H(c.cliBackends),w=n(c.doctorContract)?c.doctorContract:void 0,T=normalizeManifestCliCommands(c.cliCommands),E;if(w?.recoveryCli!==void 0){if(!Array.isArray(w.recoveryCli))return fail(`doctorContract.recoveryCli must be an array of command paths`);E=[];let e=/* @__PURE__ */ new Set;for(let t of w.recoveryCli){if(!Array.isArray(t)||t.length===0||!t.every(e=>typeof e==`string`&&normalizeCommandDescriptorName(e)===e)||!T?.some(({name:e})=>e===t[0]))return fail(`doctorContract.recoveryCli paths must use plain command names beneath a declared cliCommands root`);let n=t.join(` `);e.has(n)||(e.add(n),E.push(t))}}let D=parseDoctorStateMigrationDescriptors(w?.stateMigrations),O=w?{...Object.fromEntries([`configRepair`,`resolveSessionStoreAgentIds`,`sessionRouteStateOwners`].flatMap(e=>typeof w[e]==`boolean`?[[e,w[e]]]:[])),...D===void 0?{}:{stateMigrations:D},...E===void 0?{}:{recoveryCli:E}}:void 0,normalizeManifestModelCatalog=()=>{let e=/* @__PURE__ */ new Set([...b,...C,...S?.decisionProviders??[]]),t=normalizeModelCatalog(c.modelCatalog,{ownedProviders:e}),r=normalizeManifestDecisionModels(c.decisionModels,S?.decisionProviders);if(!r?.length)return t;let i=/* @__PURE__ */ new Map;if(n(c.modelCatalog)&&n(c.modelCatalog.providers))for(let[e,t]of Object.entries(c.modelCatalog.providers)){if(!n(t)||!Array.isArray(t.models))continue;let r=normalizeProviderId(e),a=i.get(r)??/* @__PURE__ */ new Set;for(let e of t.models){let t=n(e)?y(e.id):void 0;t&&a.add(t)}i.set(r,a)}let a={...t?.providers};for(let e of r){let t=normalizeProviderId(e.provider);if(!t||I(t))continue;let n=a[t];if(i.get(t)?.has(e.id))continue;let r=e.capabilities,s={};for(let e of r?.questionTypes??[])s[e]={probabilities:e===`boolean`?`boolean`:`provider-defined`,abstention:!1,...e===`boolean`&&r?.requiresBooleanCriteria!==void 0?{requiresCriteria:r.requiresBooleanCriteria}:{},...e===`choice`&&r?.maxChoiceAlternatives!==void 0?{maxOptions:r.maxChoiceAlternatives}:{},...e===`score`&&r?.maxScoreLevels!==void 0?{maxOptions:r.maxScoreLevels}:{}};let c={id:e.id,name:e.name,inference:{chat:!1,decision:{protocol:`decision-v1`,input:[`text`],...r?{questions:s,...r.confidence?{confidence:r.confidence}:{},limits:{...r.maxQuestions===void 0?{}:{maxQuestions:r.maxQuestions},...r.maxInputTokens===void 0?{}:{maxInputTokens:r.maxInputTokens},...r.inputTokenScope?{inputTokenScope:r.inputTokenScope}:{}}}:{}}}};a[t]={...n,models:[...n?.models??[],c]}}return normalizeModelCatalog({...t,providers:a},{ownedProviders:e})},k;try{k=normalizeManifestModelCatalog()}catch{return cacheResult({ok:!1,error:`invalid plugin manifest modelCatalog ownership metadata`,manifestPath:a})}let A={id:l,configSchema:u,...`categories`in f?{categories:f.categories}:{},...d.resources===void 0?{}:{backupResources:d.resources},...h.length>0?{requiresPlugins:h}:{},...c.enabledByDefault===!0?{enabledByDefault:!0}:{},...c.generationOverlap===void 0?{}:{generationOverlap:c.generationOverlap},...g.length>0?{enabledByDefaultOnPlatforms:g}:{},..._.length>0?{legacyPluginIds:_}:{},...v.length>0?{autoEnableWhenConfiguredProviders:v}:{},kind:p,...m?{contextEngineIds:m}:{},...n(c.reload)&&c.reload.turnHandover===!0?{reload:{turnHandover:!0}}:{},channels:x,channelAccountKeyPolicies:normalizeChannelAccountKeyPolicies(c.channelAccountKeyPolicies,x),providers:b,...c.managesOwnAvailability===!0?{managesOwnAvailability:!0}:{},providerCatalogEntry:y(c.providerCatalogEntry),capabilityCatalogEntry:c.capabilityCatalogEntry===void 0?void 0:y(c.capabilityCatalogEntry)??``,modelSupport:normalizeManifestModelSupport(c.modelSupport),modelCatalog:k,modelPricing:normalizeManifestModelPricing(c.modelPricing,{ownedProviders:/* @__PURE__ */ new Set([...b,...C])}),modelIdNormalization:normalizeManifestModelIdNormalization(c.modelIdNormalization,{ownedProviders:new Set(b)}),providerEndpoints:normalizeManifestProviderEndpoints(c.providerEndpoints),providerRequest:normalizeManifestProviderRequest(c.providerRequest,{ownedProviders:new Set(b)}),secretProviderIntegrations:normalizeManifestSecretProviderIntegrations(c.secretProviderIntegrations),cliBackends:C,syntheticAuthRefs:H(c.syntheticAuthRefs),nonSecretAuthMarkers:H(c.nonSecretAuthMarkers),commandAliases:normalizeManifestCommandAliases(c.commandAliases),cliCommands:T,providerUsageAuthEnvVars:normalizeStringListRecord(c.providerUsageAuthEnvVars),providerAuthAliases:normalizeManifestProviderAuthAliases(c.providerAuthAliases),providerAuthChoices:normalizeProviderAuthChoices(c.providerAuthChoices),activation:normalizeManifestActivation(c.activation),setup:normalizeManifestSetup(c.setup),doctorContract:O,doctorHealthChecks:c.doctorHealthChecks===!0||void 0,sessionRouteStateOwners:c.sessionRouteStateOwners===void 0?void 0:coerceDoctorSessionRouteStateOwners(c.sessionRouteStateOwners),qaRunners:normalizeManifestQaRunners(c.qaRunners)},j=normalizeManifestDashboard(c.dashboard);if(!j.ok)return fail(`invalid plugin manifest dashboard: ${j.error}`);let M=validatePluginUiCapabilities(c.uiCapabilities),N=validatePluginRecommendedPrompts(c.recommendedPrompts),P=loadPluginControlUiDeclaration({rootDir:e,controlUi:c.controlUi,channels:x,rejectHardlinks:t,rootRealPath:r});if(!P.ok)return fail(`invalid plugin manifest controlUi: ${P.error}`);let F=y(c.agentSkillsDir);if(c.agentSkillsDir!==void 0&&(!F||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(F)))return fail(`invalid plugin manifest agentSkillsDir: must be one folder name`);let L=normalizeManifestThemes(c.themes,l,i.contents.toString(`utf8`));return L.ok?cacheResult({ok:!0,...!M.ok||!N.ok?{warnings:[...M.ok?[]:[`ignoring invalid plugin manifest uiCapabilities: ${M.error}`],...N.ok?[]:[`ignoring invalid plugin manifest recommendedPrompts: ${N.error}`]]}:{},manifest:{...A,dashboard:j.dashboard,controlUi:P.value,...M.ok&&M.capabilities!==void 0?{uiCapabilities:M.capabilities}:{},...N.ok&&N.recommendedPrompts!==void 0?{recommendedPrompts:N.recommendedPrompts}:{},themes:L.themes,mcpServers:normalizeManifestMcpServers(c.mcpServers),skills:H(c.skills),...F?{agentSkillsDir:F}:{},name:y(c.name),description:y(c.description),catalog:normalizeManifestCatalog(c.catalog),version:y(c.version),uiHints:normalizeConfigUiHints(c.uiHints),configGroups:normalizeConfigGroups(c.configGroups,u),contracts:S,decisionModels:normalizeManifestDecisionModels(c.decisionModels,S?.decisionProviders),transcriptSources:normalizeManifestTranscriptSources(c.transcriptSources,S?.transcriptSourceProviders),mediaUnderstandingProviderMetadata:normalizeMediaUnderstandingProviderMetadata(c.mediaUnderstandingProviderMetadata),imageGenerationProviderMetadata:normalizeCapabilityProviderMetadata(c.imageGenerationProviderMetadata),videoGenerationProviderMetadata:normalizeCapabilityProviderMetadata(c.videoGenerationProviderMetadata),musicGenerationProviderMetadata:normalizeCapabilityProviderMetadata(c.musicGenerationProviderMetadata),toolMetadata:normalizePluginToolMetadata(c.toolMetadata),configContracts:normalizeManifestConfigContracts(c.configContracts),channelConfigs:normalizeChannelConfigs(c.channelConfigs)},manifestPath:a}):fail(`invalid plugin manifest themes: ${L.error}`)}function isPluginActivityToolName(e){return/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u.test(e)}function collectPluginSafetyInspectedFiles(e){let t=/* @__PURE__ */ new Set,r=new Map(e.map(e=>[e.path,e.kind])),i=[],a=[],s=[];withPluginCache(createPluginCache({kind:`operation`}),()=>{for(let c of e){if(Y.basename(c.path)!==`openclaw.plugin.json`)continue;let e=Y.dirname(c.path),add=n=>{let i=Y.resolve(e,n),a=U(e,i)?pluginCacheRealpathSync(i):null;a&&U(e,a)&&r.get(a)===`file`&&t.add(a)},l=loadPluginManifest(e,!1),u=l.ok?l.manifest:void 0,d=readPluginCacheFile({rootDir:e,relativePath:`package.json`,rejectHardlinks:!1,maxBytes:262144}),f=d.ok?parsePluginCacheJson(d):void 0,p=f?.ok&&n(f.value)&&n(f.value.openclaw)?f.value.openclaw:{},m=H([...Array.isArray(p.extensions)?p.extensions:Kr,...Array.isArray(p.runtimeExtensions)?p.runtimeExtensions:[],p.setupEntry,p.runtimeSetupEntry,u?.providerCatalogEntry,u?.capabilityCatalogEntry]);for(let t of/* @__PURE__ */ new Set([e,Y.join(e,`dist`),...m.map(t=>Y.dirname(Y.resolve(e,t)))]))if(U(e,t)&&r.get(t)===`directory`)for(let n of collectBundledPluginPublicSurfaceArtifacts({pluginDir:t,sourceEntry:``})??[])m.push(...ur.map(r=>Y.relative(e,Y.join(t,n.replace(/\.js$/u,r)))));[`openclaw.plugin.json`,`package.json`,`assets/icon.png`,`assets/activity.svg`].forEach(add);for(let e of m)add(e),listBuiltRuntimeEntryCandidates(e).forEach(add);for(let e of u?.themes??[])[e.source,...Object.values(e.icons??{}),...Object.values(e.hats??{}),...Object.values(e.critters??{}).map(e=>e.source),...Object.values(e.backgrounds??{})].forEach(add);let h=Y.join(e,`assets/activity`),g=u?.controlUi&&Y.resolve(e,Y.dirname(u.controlUi.entry));i.push([h,h]),g&&U(e,g)&&a.push([g,g]);for(let t of u?.skills??[]){let n=Y.resolve(e,t),i=U(e,n)?pluginCacheRealpathSync(n):null;i&&U(e,i)&&r.get(i)===`directory`&&s.push([i,i])}}});let deepestFirst=([e],[t])=>t.length-e.length,c=createRuntimePathLookup(i.toSorted(deepestFirst)),l=createRuntimePathLookup(a.toSorted(deepestFirst)),u=createRuntimePathLookup(s.toSorted(deepestFirst));for(let n of e){if(n.kind!==`file`)continue;let e=c(n.path),r=l(n.path);(Y.basename(n.path)===`package.json`||Y.basename(n.path)===`SKILL.md`&&u(n.path)!==void 0||e&&Y.dirname(n.path)===e&&n.path.endsWith(`.svg`)&&isPluginActivityToolName(Y.basename(n.path,`.svg`))||r&&isPluginControlUiAssetPath(Y.relative(r,n.path).split(Y.sep).join(`/`)))&&t.add(n.path)}return t}const li=/* @__PURE__ */ new WeakMap;function nativeMemberForSource(e,t){let n=Y.relative(e.sourceDirectory,t);if(e.members[n]?.source===t)return n;let r=li.get(e);if(!r){r=/* @__PURE__ */ new Map;for(let[t,{source:n}]of Object.entries(e.members))r.has(n)||r.set(n,t);li.set(e,r)}return r.get(t)}const pluginNativeNamespaceDirectory=e=>e.referenceRoot?e.sourceDirectory:Y.join(e.capturedRoot,`content`),pluginNativeNamespaceBoundary=e=>e.referenceRoot??e.capturedRoot,pluginNativeNamespaceMemberPath=(e,t)=>e.referenceRoot?e.members[t].source:Y.join(e.capturedRoot,`content`,t),pluginNativeNamespaceMemberRelativePath=(e,t)=>e.referenceRoot?Object.entries(e.members).find(([,e])=>e.source===t)[0]:Y.relative(pluginNativeNamespaceDirectory(e),t);function capturePluginNativeDirectoryAliases(e,t){let n=/* @__PURE__ */ new Map,r=Object.keys(t).toSorted((e,t)=>t.length-e.length);for(let[i,{capturedRoot:a}]of e){let e=r.find(e=>U(e,i));e&&n.set(Y.join(t[e],Y.relative(e,i)),a)}return n}function assertPluginNativeNamespaceHost(e,t,n){if(!e.referenceRoot)return;let r=q.realpathSync(n);for(let n of/* @__PURE__ */ new Set([r,q.realpathSync(e.sourceDirectory)])){let i=pt(Y.join(n,`native-host.cjs`)).resolve.paths(`openclaw`)?.map(e=>Y.join(e,`openclaw`)).find(e=>q.existsSync(e)),a=i?q.realpathSync(i):void 0;if(!(a&&openClawHostRootsMatch(a,t)||!i&&n!==r))throw Error(`Retained native directory ${e.sourceDirectory} does not resolve the selected OpenClaw host ${t}: `+(i?`${i} resolves to ${a}`:`no OpenClaw peer resolves from ${n}`)+`. Run openclaw doctor --fix with the selected host to repair the installed plugin's OpenClaw peer link, then reload the plugin.`)}}function inspectDirectory(e,t,n,r=!0){let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Set,c=createPluginDependencyResolver(),visit=(e,l,u,d=!1)=>{let f=q.realpathSync(e);if(n&&U(n,f))return;if(!U(u,f))throw Error(`Native plugin companion leaves its package: ${e}`);let p=q.statSync(f,{bigint:!0});if(!p.isDirectory()&&!p.isFile())throw Error(`Native plugin companion is not a regular file: ${e}`);let m=p.isDirectory()?a.get(f):void 0;if(r&&!d&&s.has(f))throw Error(`Native plugin companions contain a directory cycle: ${e}`);if(i.set(l,{source:f,identity:pluginSourceStatIdentity(p),stat:p,boundary:u,...m===void 0?{}:{linkTo:m}}),p.isDirectory()){if(m!==void 0)return;a.set(f,l),s.add(f);for(let e of q.readdirSync(f).toSorted())isPluginSourceEntry(e)&&visit(Y.join(f,e),Y.join(l,e),u);if(r){let e=l?f:resolvePluginModulePackageRoot(Y.join(f,`native-companion.cjs`)),t=Y.join(e,`package.json`);U(u,e)&&q.existsSync(t)&&capturePluginDependencies({root:e,manifestFile:t,incidental:!!l&&!d,references:/* @__PURE__ */ new Map,resolve:c,capture(e,t){visit(t.root,Y.join(l,`node_modules`,e),t.root,!0)}})}else{let e=Y.join(f,`node_modules`);for(let n of q.existsSync(e)?q.readdirSync(e).toSorted():[]){let r=n.startsWith(`@`)?q.readdirSync(Y.join(e,n)).toSorted().map(e=>`${n}/${e}`):[n];for(let n of r)n!==`openclaw`&&n!==`@openclaw/plugin-sdk`&&visit(Y.join(e,n),Y.join(l,`node_modules`,n),t)}}s.delete(f)}};return visit(e,``,t),i}function pluginNativeNamespaceIsCurrent(e,t,n){let r=inspectDirectory(e.sourceDirectory,t,n),i=inspectDirectory(pluginNativeNamespaceDirectory(e),pluginNativeNamespaceBoundary(e),e.referenceRoot?n:void 0,!!e.referenceRoot);return r.size===Object.keys(e.members).length&&i.size===r.size&&[...r].every(([t,n])=>{let r=e.members[t];return r?.source===n.source&&r.sourceIdentity===n.identity&&r.capturedIdentity===i.get(t)?.identity})}function capturePluginNativeNamespace(e){let{sourceDirectory:t,boundary:n,capturedRoot:r,managed:i,outputRoot:a,previous:s}=e,c=s?pluginNativeNamespaceDirectory(s):t,l=s?pluginNativeNamespaceBoundary(s):n,u=inspectDirectory(c,l,s?void 0:a,!s||!!s.referenceRoot),d=[...u.values()].map(e=>({path:e.source,kind:e.stat.isDirectory()?`directory`:`file`}));for(let t of e.inspectionRoots??[n]){d.push({path:t,kind:`directory`});for(let e of[`openclaw.plugin.json`,`package.json`]){let n=Y.join(t,e);q.statSync(n,{throwIfNoEntry:!1})?.isFile()&&d.push({path:n,kind:`file`})}}let f=s?/* @__PURE__ */ new Set:collectPluginSafetyInspectedFiles(d);for(let t of e.inspectedFiles??[])s||f.add(q.realpathSync(t));let p=Y.join(r,`content`),m=/* @__PURE__ */ new Set,h=q.statSync(r,{bigint:!0}).dev,g;try{for(let[t,r]of u){let a=Y.join(p,t);r.linkTo===void 0?r.stat.isDirectory()?q.mkdirSync(a,{recursive:!0,mode:448}):!e.copyOnly&&r.stat.dev===h&&(s||i&&(e.managedRoots??[n]).some(e=>U(e,r.source)))&&!(s?.members[t]?.boundaryChecked??f.has(r.source))?linkPluginSourceFile(r.source,r.boundary,a)&&m.add(r.source):copyPluginSourceFile(r.source,r.boundary,a):(q.mkdirSync(Y.dirname(a),{recursive:!0,mode:448}),q.symlinkSync(Y.relative(Y.dirname(a),Y.join(p,r.linkTo)),a,`junction`))}}catch(n){if(e.copyOnly||!i||s||!e.retainedRoot||[...u.values()].some(t=>!U(e.retainedRoot,t.source))||![`EXDEV`,`EPERM`,`EACCES`,`ENOTSUP`,`EOPNOTSUPP`,`EMLINK`,`ENOSYS`].some(e=>Ve(n,e)))throw n;q.rmSync(p,{recursive:!0,force:!0}),m.clear(),q.symlinkSync(t,p,`junction`),g=e.retainedRoot}let _=/* @__PURE__ */ new Map;for(let[e,t]of u){if(!t.stat.isFile())continue;if(!s){_.set(e,{sizeBytes:Number(t.stat.size)});continue}let n=Y.join(p,e),i=pluginSourceStatIdentity(q.statSync(n,{bigint:!0})),a=hashPluginSourceFile(n,r),c=s?.members[e];if(!pluginSourceIdentityChangedOnlyByCtime(i,pluginSourceStatIdentity(q.statSync(n,{bigint:!0})))||c&&(a.contentHash!==c.contentHash||a.sizeBytes!==c.sizeBytes))throw Error(`Native plugin companion changed during admission`);_.set(e,a)}let v=inspectDirectory(c,l,s?void 0:a,!s||!!s.referenceRoot),y=inspectDirectory(g?t:p,g??r,g?a:void 0,!!g);if(u.size!==v.size||y.size!==u.size||[...u].some(([e,t])=>{let n=v.get(e);if(!n||n.source!==t.source||!pluginSourceIdentityChangedOnlyByCtime(t.identity,n.identity))return!0;if(!i&&!s&&t.stat.isFile()&&n.identity!==t.identity){let i=y.get(e);if(!i)return!0;let a=hashPluginSourceFile(i.source,r),s=hashPluginSourceFile(t.source,t.boundary),c=pluginSourceStatIdentity(q.statSync(t.source,{bigint:!0})),l=pluginSourceStatIdentity(q.statSync(i.source,{bigint:!0}));if(a.contentHash!==s.contentHash||a.sizeBytes!==s.sizeBytes||!pluginSourceIdentityChangedOnlyByCtime(n.identity,c)||!pluginSourceIdentityChangedOnlyByCtime(i.identity,l))return!0;n.identity=c,i.identity=l,_.set(e,a)}return!1}))throw Error(`Native plugin directory changed during admission`);let b=/* @__PURE__ */ new Map,x={sourceDirectory:t,capturedRoot:r,managed:i,...g?{referenceRoot:g}:{},members:Object.fromEntries([...v].map(([e,t])=>{m.has(t.source)&&t.identity===y.get(e).identity&&b.set(t.source,t.identity);let n=s?.members[e];return n&&(n.capturedIdentity=t.identity),[e,{source:n?.source??t.source,sourceIdentity:n?.sourceIdentity??t.identity,capturedIdentity:y.get(e).identity,boundaryChecked:n?.boundaryChecked??f.has(t.source),..._.get(e)}]}))};if(s?.managed)for(let[e,t]of Object.entries(x.members)){let n=q.statSync(t.source,{bigint:!0,throwIfNoEntry:!1});m.has(v.get(e).source)&&n&&n.dev===v.get(e).stat.dev&&n.ino===v.get(e).stat.ino&&pluginSourceStatIdentity(n)===t.capturedIdentity&&(t.sourceIdentity=pluginSourceStatIdentity(n),s.members[e].sourceIdentity=t.sourceIdentity,b.set(t.source,t.sourceIdentity))}return{fact:x,changed:b}}function finishPluginNativeNamespace(e){for(let[t,n]of Object.entries(e.members)){if(n.sizeBytes===void 0||n.contentHash)continue;let r=pluginNativeNamespaceMemberPath(e,t),i=hashPluginSourceFile(r,pluginNativeNamespaceBoundary(e)),a=pluginSourceStatIdentity(q.statSync(r,{bigint:!0}));if(i.sizeBytes!==n.sizeBytes||!pluginSourceIdentityChangedOnlyByCtime(n.capturedIdentity,a))throw Error(`Native plugin companion changed before admission completed`);n.sourceIdentity===n.capturedIdentity&&(n.sourceIdentity=a),n.capturedIdentity=a,n.contentHash=i.contentHash}}const ui=zt(`openclaw.plugin-native-reference`);let di=0;function linkPluginNativeReference(e,t,n){try{return q.symlinkSync(n.capturedPath,t,`file`),`symlink`}catch(e){if(![`EPERM`,`EACCES`,`ENOSYS`,`ENOTSUP`].some(t=>Ve(e,t)))throw e}let r=Y.dirname(n.capturedPath),i=linkPluginSourceFile(n.capturedPath,r,t);if(n.contentHash){let e=hashPluginSourceFile(n.capturedPath,r);if(e.contentHash!==n.contentHash||e.sizeBytes!==n.sizeBytes)throw Error(`Native plugin artifact changed while linking its generation`)}let a=q.statSync(n.capturedPath,{bigint:!0}),s=q.statSync(e,{bigint:!0}),c=pluginSourceStatIdentity(s);if(c!==n.sourceIdentity&&(!pluginSourceIdentityChangedOnlyByCtime(n.sourceIdentity,c)||(a.dev!==s.dev||a.ino!==s.ino)&&(!n.contentHash||hashPluginSourceFile(e,Y.dirname(e)).contentHash!==n.contentHash)))throw Error(`Plugin source changed while linking its native artifact`);return n.sourceIdentity=c,n.capturedIdentity=pluginSourceStatIdentity(a),i?`hardlink`:`copy`}function resolveNativeHost(e){for(let t of pt(e).resolve.paths(`openclaw`)??[]){let e=Y.join(t,`openclaw`);if(q.existsSync(e))return q.realpathSync(e)}}function createPluginNativeReferenceValidator(e,t){let n=/* @__PURE__ */ new WeakMap;return(r,i,a,s)=>{let c=Y.dirname(pluginNativeNamespaceMemberRelativePath(a,i.capturedPath)),l=`${c}\0${Y.dirname(r)}`,u=n.get(a);try{if(!u?.placements.has(l)){u||(u={placements:/* @__PURE__ */ new Set,members:/* @__PURE__ */ new Set},n.set(a,u));let i=u.members;ui.publish({pluginId:t,completed:di});for(let[n,s]of Object.entries(a.members)){if(!U(c,n||`.`))continue;let l=Y.join(Y.dirname(r),Y.relative(c,n||`.`)),u=`${n}\0${l}`;if(i.has(u))continue;let d=q.realpathSync(l);if(!U(e,d)&&!U(pluginNativeNamespaceBoundary(a),d))throw Error(`Companion ${n} leaves the captured generation`);let f=q.statSync(d,{bigint:!0});if(s.sizeBytes===void 0){if(!f.isDirectory())throw Error(`Companion ${n} is not a directory`)}else{let e=q.statSync(pluginNativeNamespaceMemberPath(a,n),{bigint:!0});if(f.dev!==e.dev||f.ino!==e.ino){let e=hashPluginSourceFile(d,Y.dirname(d));if(e.contentHash!==s.contentHash||e.sizeBytes!==s.sizeBytes)throw Error(`Companion ${n} differs from its captured bytes`)}}i.add(u),ui.publish({pluginId:t,completed:++di})}u.placements.add(l)}if(s){let e=resolveNativeHost(r);if(!e||!openClawHostRootsMatch(e,s))throw Error(`The native companion directory resolves a different OpenClaw host`)}}catch(e){throw Error(`Native plugin companions cannot be preserved without file symlinks. Enable file symlink support for this filesystem, then reload the plugin.`,{cause:e})}}}function admitPluginNativeRecoveryReference(e,t,n=t){if(q.realpathSync(t.capturedPath)!==t.capturedPath)return;let r=q.statSync(t.capturedPath,{bigint:!0}),i=e===t.capturedPath?r:q.statSync(e,{bigint:!0});if(i.dev!==r.dev||i.ino!==r.ino)return;let a=pluginSourceStatIdentity(i);if(a!==n.capturedIdentity||n.contentHash!==t.contentHash||n.sizeBytes!==t.sizeBytes){let e=hashPluginSourceFile(t.capturedPath,Y.dirname(t.capturedPath));if(e.contentHash!==t.contentHash||e.sizeBytes!==t.sizeBytes)return}return{...t,sourceIdentity:a,capturedIdentity:a}}function*copyPluginRecoveryFiles(e,t){let{rootDir:n,boundaryRoot:r,references:i,namespaces:a}=e,s=/* @__PURE__ */ new Map,c=0;yield[r,t,{recursive:!0,verbatimSymlinks:!0,filter:(n,a)=>{let l=i?.get(n);if(!l){let i=q.lstatSync(n);if(e.measureBytes&&i.isFile()&&(c+=i.size),i.isSymbolicLink()){let e=q.readlinkSync(n),i=Y.isAbsolute(e)?relativePluginPathInsideRootSync(r,e):void 0;if(i!==void 0)return q.mkdirSync(Y.dirname(a),{recursive:!0,mode:448}),q.symlinkSync(Y.relative(Y.dirname(a),Y.join(t,i)),a,q.statSync(n).isDirectory()?`junction`:`file`),!1}return!0}return linkPluginNativeReference(l.capturedPath,a,l)!==`symlink`&&s.set(a,l),!1}}];let l=createPluginNativeReferenceValidator(t,n);for(let[e,t]of s)l(e,t,a.get(t.namespace));return c}const fi=/* @__PURE__ */ new WeakSet;function markPluginSourceCaptureOperation(e){return fi.add(e),e}function isPluginSourceCaptureOperation(e){return fi.has(e)}new St;function createPluginSourceFacts(e,t,n,r){let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;return{files:t?i:void 0,recordLink(e,n){t&&q.lstatSync(e).isSymbolicLink()&&a.set(e,n)},snapshot(e,t,n){let relative=t=>Y.relative(e,t),r=new Set([...t].map(relative)),s=new Map([...a].map(([e,t])=>[relative(e),relative(t)]));for(let e of[...i.keys(),...r,...s.keys()]){let t=Y.dirname(e);for(;t!==`.`;)r.add(t),t=Y.dirname(t)}return{files:i,directories:r,links:s,hardlinks:new Set([...n].map(relative))}},resolveDependency:createPluginDependencyResolver(e),captureCustody:e=>({source:e(),files:i,executionAliases:n,executionSources:r})}}function canonicalSource(e,t,n){let r=Y.resolve(n),i=relativePluginPathInsideRootSync(e,r);return i===void 0?r:Y.join(t,i)}function getCapturedSource(e,t,n,r){let i=Y.resolve(r);return e.get(i)??e.get(canonicalSource(t,n,i))}const pi=/* @__PURE__ */ new WeakMap;function snapshotPluginRecoverySourceResolver(e){return pi.get(e)}function restorePluginRecoverySourceResolver(e){return createRecoverySourceResolver(e.rootDir,e.sourceRoot,e.sources)}function createRecoverySourceResolver(e,t,n){let r={rootDir:e,sourceRoot:t,sources:new Map(n)},resolve=n=>{let i=getCapturedSource(r.sources,e,t,n);if(!i)throw Error(`Plugin recovery entry is outside its captured source package`);return i};return pi.set(resolve,r),resolve}function copyRecoverySource(e){let t;try{t=createPluginSourceCapture();let n=getPluginGenerationMetrics(),r=copyPluginRecoveryFiles({rootDir:e.rootDir,boundaryRoot:e.boundaryRoot,references:e.native?.references,namespaces:e.native?.namespaces,measureBytes:n!==void 0},t.directory),i=r.next();for(;!i.done;)q.cpSync(...i.value),i=r.next();return n&&(n.copiedBytes+=i.value),retainRecoverySource(e,t)}catch(n){try{t?.dispose()}finally{e.native?.dispose()}throw Ve(n,`ENOENT`)?new E(n):n}}async function copyRecoverySourceAsync(e){let t,n;try{t=await N(()=>createPluginCaptureOwner(Le({runtimeGeneration:void 0})));let r=getPluginGenerationMetrics(),{root:i,copiedBytes:a}=await t.copyRecovery(1,{rootDir:e.rootDir,boundaryRoot:e.boundaryRoot,references:e.native?.references,namespaces:e.native?.namespaces,measureBytes:r!==void 0,storage:resolvePluginSourceCaptureStorage(),directory:Gn.getStore()}),s=t,c,dispose=()=>c??=p(s.releaseSource(1),()=>s.close(),`Plugin recovery source release and owner close failed`);return n=createPluginSourceCaptureState({directory:i.directory,outputRoot:i.managedRoot,dispose(){dispose().catch(e=>process.emitWarning(String(e)))},disposeAsync:dispose}),r&&(r.copiedBytes+=a),retainRecoverySource(e,n)}catch(r){try{l(await Promise.allSettled([n?n.disposeAsync():t?.close(),e.native?.disposeAsync()]),`Plugin recovery custody cleanup failed`)}catch(e){throw AggregateError([r,e],`Plugin recovery capture and cleanup failed`,{cause:e})}throw Ve(r,`ENOENT`)?new E(r):r}}function retainRecoverySource(e,t){let{rootDir:n,sourceRoot:r,capturedRoot:i,boundaryRoot:a,sources:s,directories:c}=e,l=t.directory,relocate=e=>Y.join(l,Y.relative(a,e)),u=new Map(Array.from(s,([e,t])=>[e,relocate(t)])),d=e.native,f=d?.fork(relocate);e.native=f,d?.dispose();let p=relocate(i),m=new Set([...c].map(relocate)),h=!1;return{rootDir:p,directories:m,sourceCapture:t,resolve:createRecoverySourceResolver(n,r,u),native:f,fork:markPluginSourceCaptureOperation(()=>{if(h)throw Error(`Plugin source recovery has been disposed`);return copyRecoverySource({rootDir:n,sourceRoot:r,capturedRoot:p,boundaryRoot:l,sources:u,directories:m,native:f?.fork()})}),dispose(){if(!h){h=!0;try{t.dispose()}finally{f?.dispose()}}},async disposeAsync(){h||(h=!0,await Promise.all([t.disposeAsync(),f?.disposeAsync()]))}}}function createPluginGenerationSourceLookup({rootDir:e,sourceRoot:t,capturedRoot:n,boundaryRoot:r,capturedPaths:i,capturedDirectories:a,hardlinkedSources:s,assertModuleAvailable:c,captureNativeRecovery:l}){let resolveCaptured=r=>{let a=getCapturedSource(i,e,t,r);return a&&isPathInside$1(n,a)?a:void 0},recoveryInput=()=>{for(let e of new Set(i.values()))c(e);let s=l?.();if(s)for(let[e,t]of s.references)s.references.set(e,{...t,sourceIdentity:t.capturedIdentity});return{rootDir:e,sourceRoot:t,capturedRoot:n,boundaryRoot:r,sources:new Map(i),directories:new Set(a),native:s}};return{hasSource:e=>resolveCaptured(e)!==void 0,resolve:b((e,t=!1)=>{let n=resolveCaptured(e);if(!n)throw j(/* @__PURE__ */ Error(`Plugin entry is outside its captured source package`));if(t&&s.has(n))throw j(/* @__PURE__ */ Error(`Plugin source is hardlinked; use a separate file and reload.`));return c(n),n}),captureRecoverySource:markPluginSourceCaptureOperation(()=>copyRecoverySource(recoveryInput())),captureRecoverySourceAsync:markPluginSourceCaptureOperation(()=>copyRecoverySourceAsync(recoveryInput()))}}function createPluginGenerationModuleLookup({capturedPaths:e,capturedDirectories:t,originalSources:n,moduleCaptures:r,metadataCapture:i,assertModuleAvailable:a,captureAdmitted:s,captureExecutableFile:c,executable:l,packages:u,directory:d}){let packageForFile=e=>findPluginCapturedPackage(u,e,d)?.owner;return{boundaryRoot:d,sourceForCaptured:e=>n.get(Y.resolve(e)),moduleFacts:e=>r.get(e),moduleRoot:e=>n.has(e)?packageForFile(e)?.capturedRoot:void 0,assertModuleAvailable:a,prepareModule:b(e=>{a(e),t.has(e)&&readPluginCapturedCode(e,!0);let i=packageForFile(e),c=n.get(e),u=l&&c&&/\.[cm]?[jt]sx?$/.test(c)&&!r.has(e);return!i||(i.state===`entry`||i.state===`body`)&&!u?[]:s(()=>{i.materialize(i.state===`entry`?c:void 0),u&&i.state!==`entry`&&i.materialize(c)}).additions}),prepareDependency:(e,t)=>s(()=>r.get(e)?.prepareDependency(t)).additions,prepareNativeScopes:e=>{let t=e?r.get(e)?.nativeScope:void 0;return t?.prepareDependencies||i.pending?s(()=>i.prepare(t)):void 0},prepareNativeModule:(e,t)=>s(()=>{let n=r.get(e)?.prepareDependency(t)===`package-map`;return i.prepare(),n}).value,captureModule:(e,t,n)=>{let i=s(()=>r.get(e)?.capture(t,n));return i.value?{...i.value,additions:i.additions}:void 0},captureResolvedModule:t=>{let n=e.get(Y.resolve(t));return n?(a(n),n):s(()=>{let n=findPluginCapturedPackage(u,t,d),r=c(n?Y.join(n.owner.sourceRoot,Y.relative(n.root,t)):t),i=r?e.get(r):void 0;return i&&e.set(Y.resolve(t),i),i}).value}}}Y.join(At.tmpdir(),`openclaw-empty-bundled-plugins`);const mi=`OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR`;function shouldTrustTestBundledPluginsDirOverride(e){let t=e!==process.env;return!R(e[mi])&&!(t&&R(process.env[mi]))?!1:isVitestRuntimeEnv(e)||t&&isVitestRuntimeEnv(process.env)}function hashJson(e){return sha256Hex(JSON.stringify(e))}const hi=[`ANDROID_DATA`,`APPDATA`,`HOME`,`OPENCLAW_BUNDLED_PLUGINS_DIR`,`OPENCLAW_COMPATIBILITY_HOST_VERSION`,`OPENCLAW_CONFIG_PATH`,`OPENCLAW_DEV_SOURCE_ROOT`,`OPENCLAW_DISABLE_BUNDLED_PLUGINS`,`OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS`,`OPENCLAW_HOME`,`OPENCLAW_NIX_MODE`,`OPENCLAW_STATE_DIR`,`PREFIX`,`USERPROFILE`,`XDG_CONFIG_HOME`];function resolvePluginMetadataEnvFingerprint(e=process.env){return hashJson({env:Object.fromEntries(hi.flatMap(t=>{let n=e[t];return n===void 0?[]:[[t,n]]})),installRoots:hasActivePluginInstallRoots()?resolveActivePluginInstallRoots():void 0,trustBundledPluginsDirOverride:shouldTrustTestBundledPluginsDirOverride(e),cwd:Ue()})}const gi=/* @__PURE__ */ new WeakMap,_i=/* @__PURE__ */ new WeakMap,vi=/* @__PURE__ */ new WeakMap;function releaseReplacedNamespaces(e,t){if(e.receiptInventoryComplete)for(let n of Object.keys(t?.nativeArtifacts??{}))[...e.receipts.values()].some(e=>n in e.nativeArtifacts)||e.files.delete(n);for(let n of Object.keys(t?.nativeNamespaces??{}))![...e.receipts.values()].some(e=>n in e.nativeNamespaces)&&![...e.files.values()].some(e=>e.namespace===n)&&e.namespaces.delete(n)}function resolveAdmissionViewKey(e=Ge(),t=resolvePluginSourceCaptureStorage(),n=resolveActivePluginInstallRoots().stateDir){return JSON.stringify([e?`readonly`:`writable`,resolvePluginMetadataEnvFingerprint(),t.stateDir,t.placement,n])}function retainNativePath(e,t){e.pins.has(t)||e.pins.set(t,ir(t))}async function settlePluginNativeAdmissions(e=getPluginCache()){for(let t of gi.get(e)?.values()??[])await settlePluginNativeAdmissionState(t)}async function settlePluginNativeAdmissionState(e){await Promise.all(e.pending);for(let t of e.publications.keys())startNativeAdmissionPublication(e,t);await Promise.all(e.pending)}function queuePluginNativeAdmissionPublication(e,t,n){let r=[...e.roots].filter(e=>t.receipt.nativeNamespaces[e.directory]),i={data:t,run:()=>n(t).then(async n=>{n&&(await Promise.all(r.map(async e=>e.commit())),e.publications.get(t.key)===i&&e.publications.delete(t.key))}).catch(e=>process.emitWarning(`Plugin source receipt was not recorded: ${String(e)}`))};e.publications.set(t.key,i),startNativeAdmissionPublication(e,t.key)}function startNativeAdmissionPublication(e,t){let n=e.publications.get(t);if(!n||e.publishing.has(t))return;e.publishing.add(t);let r=n.run().finally(()=>{e.publishing.delete(t),e.pending.delete(r)});e.pending.add(r)}function bindAdmissionState(e,t){let n=_i.get(e);if(!n){n=/* @__PURE__ */ new Set,_i.set(e,n);let t=n;e.sourceAdmissions={invalidate(){gi.delete(e)},async dispose(){for(let e of t){if(await Promise.all(e.pending),e.borrowers.delete(t),e.borrowers.size>0)continue;await e.inspectionNativeEsm?.dispose?.(),await settlePluginNativeAdmissionState(e);for(let t of e.pins.values())t();e.pins.clear();let n=[...e.roots].filter(t=>{let n=vi.get(t);return n.delete(e),n.size===0});await Promise.all(n.map(e=>e.disposeAsync())),e.roots.clear()}t.clear(),gi.delete(e),_i.delete(e)}}}n.add(t),t.borrowers.add(n);let r=gi.get(e);return r||(r=/* @__PURE__ */ new Map,gi.set(e,r)),r.set(t.viewKey,t),t}function nativeAdmissionStateFor(e=getPluginCache()){let t=Ge(),n=resolvePluginSourceCaptureStorage(),r=resolveActivePluginInstallRoots().stateDir,i=resolveAdmissionViewKey(t,n,r);return gi.get(e)?.get(i)??bindAdmissionState(e,{viewKey:i,captureStorage:n,publicationStateDir:r,artifactPreservingReadOnly:t,createRoot:()=>createPluginNativeCaptureRoot(n.stateDir,n.placement),preparedIndexes:/* @__PURE__ */ new WeakSet,owners:/* @__PURE__ */ new Map,managedRoots:/* @__PURE__ */ new Map,receipts:/* @__PURE__ */ new Map,receiptInventoryComplete:!0,files:/* @__PURE__ */ new Map,namespaces:/* @__PURE__ */ new Map,pins:/* @__PURE__ */ new Map,roots:/* @__PURE__ */ new Set,pending:/* @__PURE__ */ new Set,publications:/* @__PURE__ */ new Map,publishing:/* @__PURE__ */ new Set,borrowers:/* @__PURE__ */ new Set,inspectionNativeEsm:e.inspectionNativeEsmPolicy?.viewKeys.has(i)?{...e.inspectionNativeEsmPolicy}:void 0})}const yi=/* @__PURE__ */ new WeakMap;function snapshotPluginNativeRootLease(e){return yi.get(e)}function retainPluginNativeRoot(e){let t={},n=vi.get(e);n.add(t);let r=!1,release=()=>!r&&(r=!0,n.delete(t),n.size===0),i={directory:e.directory,commit:()=>e.commit(),dispose:()=>{release()&&e.dispose()},disposeAsync:async()=>{release()&&await e.disposeAsync()}};return yi.set(i,{root:yi.get(e)?.root??e,release:i.dispose}),i}const bi=new St;function withPluginSourceAdmissionPublisher(e,t){return bi.run(e,t)}function getPluginSourceAdmissionPublisher(){return bi.getStore()}const xi=/* @__PURE__ */ new WeakMap;function snapshotPluginNativeRecovery(e){let t=xi.get(e);if(!t)throw Error(`Native recovery is not owned by plugin admission`);return t()}function isOwnedPluginNativeRecovery(e){return xi.has(e)}function restorePluginNativeRecovery(e){for(let t of e.roots)vi.has(t)||vi.set(t,/* @__PURE__ */ new Set);return createNativeRecovery(e.receipt,e.references,e.namespaces,e.directories,e.roots)}function createNativeRecovery(e,t,n,r,i){let a={},s=[...t.values()].map(e=>e.capturedPath);s.push(...[...n.keys()].map(e=>Y.join(e,`content`)));let c=[...new Set(s)].map(ir);for(let e of i)vi.get(e).add(a);let l=!1,release=()=>{if(l)return[];l=!0;for(let e of c)e();return i.filter(e=>{let t=vi.get(e);return t.delete(a),t.size===0})},u={receipt:{...e},references:t,namespaces:n,directories:r,fork(a=e=>e){if(l)throw Error(`Plugin native recovery has been disposed`);return createNativeRecovery(e,new Map([...t].map(([e,t])=>[a(e),{...t}])),structuredClone(n),new Map([...r].map(([e,t])=>[a(e),t])),i)},retain(e){if(l)throw Error(`Plugin native recovery has been disposed`);let r=nativeAdmissionStateFor(e);for(let[e,t]of n)r.namespaces.set(e,t),retainNativePath(r,Y.join(e,`content`));for(let e of i)r.roots.add(e),vi.get(e).add(r);for(let e of t.values())retainNativePath(r,e.capturedPath)},dispose(){for(let e of release())e.dispose()},async disposeAsync(){await Promise.all(release().map(e=>e.disposeAsync()))}};return xi.set(u,()=>{if(l)throw Error(`Plugin native recovery has been disposed`);let a=i.map(retainPluginNativeRoot);return{receipt:{...e},references:structuredClone(t),namespaces:structuredClone(n),directories:new Map(r),roots:a}}),u}function isNativeArtifact(e,t,n,r){return/\.(?:node|so(?:\.\d+)*|dylib|dll|exe|bin)$/i.test(e)&&(r||!/\.so(?:\.\d+)*$/i.test(e)||!isPluginWasmModule(e,t))||(n.mode&73n)!=0n&&Y.extname(e)===``&&(r||isPluginNativeExecutable(e,t))}function createPluginNativeAdmission(e,t,n,r,i){r?.retain(getPluginCache());let a=nativeAdmissionStateFor(),s=n?.length===1?Y.resolve(n[0]):n&&JSON.stringify(n.map(e=>Y.resolve(e))),c=`${Y.resolve(e)}\0${s??``}`,l=a.owners.get(Y.resolve(e)),u=l&&!a.artifactPreservingReadOnly?getPluginSourceAdmissionPublisher():void 0,d=r?.receipt??a.receipts.get(c),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=/* @__PURE__ */ new Set,_=/* @__PURE__ */ new Set,v=createPluginNativeReferenceValidator(t,l?.pluginId??e),y=/* @__PURE__ */ new Map,b,x,namespaces=()=>[...new Set(f.values())],S=new Map(r?.namespaces),namespaceById=e=>S.get(e)??a.namespaces.get(e);for(let[e,t]of r?.directories??[]){let n=namespaceById(t);n&&f.set(e,n)}let namespaceFor=e=>[...f].toSorted(([e],[t])=>t.length-e.length).find(([t])=>U(t,e)),resolvePreparedSource=e=>{let t=m.get(Y.resolve(e));if(t)return{path:t.capturedPath,boundary:pluginNativeNamespaceBoundary(namespaceById(t.namespace))};if(!r)for(let t of namespaces()){let n=nativeMemberForSource(t,e);if(n!==void 0)return{path:pluginNativeNamespaceMemberPath(t,n),boundary:pluginNativeNamespaceBoundary(t)}}let n=namespaceFor(Y.resolve(e));return n?{path:Y.join(pluginNativeNamespaceDirectory(n[1]),Y.relative(n[0],Y.resolve(e))),boundary:pluginNativeNamespaceBoundary(n[1])}:void 0},sourceForPrepared=e=>{for(let[t,n]of f){let i=pluginNativeNamespaceDirectory(n);if(U(i,e)){let a=Y.relative(i,e);return!r&&n.members[a]?.source||Y.join(t,a)}}},createNamespace=(e,t,r,s,c)=>{let u=a.createRoot();a.roots.add(u),vi.set(u,/* @__PURE__ */ new Set([a]));let{fact:d,changed:f}=capturePluginNativeNamespace({sourceDirectory:e,boundary:t,managed:r,copyOnly:a.captureStorage.placement===`temporary`,previous:s,retainedRoot:c,managedRoots:[...a.managedRoots.keys()],capturedRoot:u.directory,outputRoot:i,inspectionRoots:[.../* @__PURE__ */ new Set([t,...l?[l.rootDir]:[]])],inspectedFiles:[l?.source,l?.setupSource,...n??[]].filter(e=>!!e)});for(let e of a.namespaces.values())for(let[t,n]of Object.entries(e.members)){let r=f.get(n.source),i=r!==void 0&&pluginSourceIdentityChangedOnlyByCtime(n.sourceIdentity,r),a=r!==void 0&&pluginSourceIdentityChangedOnlyByCtime(n.capturedIdentity,r);if(r&&(i||a)){if(!e.referenceRoot&&e!==s&&!namespaces().includes(e)&&!p.has(e)&&!nr(e.capturedRoot)&&!q.lstatSync(e.capturedRoot,{throwIfNoEntry:!1}))break;if(e!==s||!a){let r=hashPluginSourceFile(pluginNativeNamespaceMemberPath(e,t),pluginNativeNamespaceBoundary(e)).contentHash;if(n.contentHash&&r!==n.contentHash||i&&hashPluginSourceFile(n.source,Y.dirname(n.source)).contentHash!==r)throw Error(`Native plugin companion changed during admission`);n.contentHash??=r}i&&(n.sourceIdentity=r),a&&(n.capturedIdentity=r)}}return a.namespaces.set(u.directory,d),S.set(u.directory,d),d},publish=()=>{if(!x||m.size===0)return;for(let[e,t]of m)a.files.set(e,t),retainNativePath(a,t.capturedPath),retainNativePath(a,Y.join(t.namespace,`content`));let e=new Set([...m.values()].map(e=>e.namespace));for(let t of e)a.namespaces.set(t,namespaceById(t));let t=structuredClone({...x,nativeArtifacts:Object.fromEntries(m),nativeNamespaces:Object.fromEntries([...e].map(e=>[e,namespaceById(e)]))}),n=a.receipts.get(c),r=Pt(n,t);r||(a.receipts.set(c,t),releaseReplacedNamespaces(a,n)),l&&u&&(r?startNativeAdmissionPublication(a,c):queuePluginNativeAdmissionPublication(a,{pluginId:l.pluginId,rootDir:l.rootDir,installRecordHash:l.installRecordHash,key:c,receipt:t},u))},refreshReference=(e,t,n)=>{let r=namespaceById(e.namespace),i=pluginNativeNamespaceMemberRelativePath(r,e.capturedPath),a=r.members[i],s={...e,sourceIdentity:pluginSourceStatIdentity(q.statSync(t,{bigint:!0}))};linkPluginNativeReference(t,n,s)===`symlink`?g.delete(n):g.add(n);let c=a.capturedIdentity;a.capturedIdentity=s.capturedIdentity,a.sourceIdentity===c&&(a.sourceIdentity=s.capturedIdentity),e.sourceIdentity=a.sourceIdentity,e.capturedIdentity=s.capturedIdentity,_.add(n)},assertReferenceNamespaces=(e=_)=>{for(let t of e){if(!g.has(t))continue;let e=m.get(h.get(t));v(t,e,namespaceById(e.namespace),b)}},linkHost=t=>{b=q.realpathSync(t);for(let t of namespaces()){if(t.referenceRoot){assertPluginNativeNamespaceHost(t,b,e);continue}let n=Y.join(t.capturedRoot,`node_modules`,`openclaw`),r=q.lstatSync(n,{throwIfNoEntry:!1}),i;if(r)try{i=q.realpathSync(n)}catch(e){if(!r.isSymbolicLink()||!Ve(e,`ENOENT`))throw e}if(r&&i!==b){let e=createNamespace(t.sourceDirectory,t.sourceDirectory,t.managed,t);p.add(t),q.mkdirSync(Y.join(e.capturedRoot,`node_modules`),{recursive:!0,mode:448}),q.symlinkSync(b,Y.join(e.capturedRoot,`node_modules`,`openclaw`),`junction`);for(let[n,r]of f)r===t&&f.set(n,e);for(let[n,r]of m){if(r.namespace!==t.capturedRoot)continue;let i=pluginNativeNamespaceMemberRelativePath(t,r.capturedPath),a=e.members[i];m.set(n,{...r,namespace:e.capturedRoot,capturedPath:Y.join(pluginNativeNamespaceDirectory(e),i),capturedIdentity:a.capturedIdentity,sourceIdentity:a.sourceIdentity})}for(let[t,n]of h){let r=m.get(n);r.namespace===e.capturedRoot&&(q.unlinkSync(t),refreshReference(r,r.capturedPath,t))}}else if(!r){q.mkdirSync(Y.dirname(n),{recursive:!0,mode:448});try{q.symlinkSync(b,n,`junction`)}catch(e){if(!Ve(e,`EEXIST`))throw e;return linkHost(b)}}}};return{prepared:d,resolvePreparedSource,sourceForPrepared,captureRecovery(e,t){let n=new Map([...h].map(([e,t])=>[e,{...m.get(t)}])),r=new Set([...n.values()].map(e=>e.namespace));return createNativeRecovery(e,n,new Map([...r].map(e=>[e,structuredClone(namespaceById(e))])),capturePluginNativeDirectoryAliases(f,t),[...a.roots].filter(e=>r.has(e.directory)))},isRetainedReference(e,t){let n=r?.references.get(Y.resolve(e));if(!n)return!1;let i=t??q.realpathSync(e),a=admitPluginNativeRecoveryReference(i,n,y.get(i));return a?(y.set(i,a),!0):!1},materialize(e,t,r,s,c=sourceForPrepared(e)??e){let u=y.get(e),d=sourceForPrepared(e)??e,p=m.get(c)??a.files.get(c)??u,g=p&&pluginSourceStatIdentity(s);if(l?.source===c||l?.setupSource===c||n?.includes(c)||!isNativeArtifact(e,t,s,!(!p||p.sourceIdentity!==g&&p.capturedIdentity!==g)))return;let _=namespaceFor(d),v=u?namespaceById(u.namespace):namespaces().find(e=>nativeMemberForSource(e,d)!==void 0)??_?.[1],b=_?.[0]??Y.dirname(d);if(v)u&&(b=[...f].find(([,e])=>e===v)?.[0]??b);else{let e=[...a.managedRoots].find(([e])=>U(e,d)),n=!!e,r=e?.[0]??t,s=resolvePluginModulePackageRoot(d);b=U(r,s)?s:Y.dirname(d);let c=p&&a.namespaces.get(p.namespace);v=[.../* @__PURE__ */ new Set([...c?[c]:[],...[...a.namespaces.values()].toReversed()])].find(t=>{if(!U(t.sourceDirectory,b)||t.managed!==n||t.referenceRoot!==void 0&&(e?.[1]!==`retained-npm`||t.referenceRoot!==e[0]))return!1;try{return pluginNativeNamespaceIsCurrent(t,r,i)}catch{return!1}}),v??=createNamespace(b,r,n,void 0,e?.[1]===`retained-npm`?e[0]:void 0),b=v.sourceDirectory,f.set(b,v)}S.set(v.capturedRoot,v);let x=u?pluginNativeNamespaceMemberRelativePath(v,u.capturedPath):nativeMemberForSource(v,d)??Y.relative(b,d),C=v.members[x];if(!C||C.sizeBytes===void 0)throw Error(`Native plugin artifact is outside its admitted directory`);let w={sourceIdentity:C.sourceIdentity,contentHash:C.contentHash??``,sizeBytes:C.sizeBytes,namespace:v.capturedRoot,capturedPath:pluginNativeNamespaceMemberPath(v,x),capturedIdentity:C.capturedIdentity};return refreshReference(w,e,r),m.set(c,w),h.set(r,c),{fact:w,path:w.capturedPath,boundary:pluginNativeNamespaceBoundary(v),content:w.contentHash?{contentHash:w.contentHash,sizeBytes:w.sizeBytes}:void 0,record(e){Object.assign(w,e),Object.assign(C,e);for(let t of namespaces())for(let n of Object.values(t.members))n.sizeBytes!==e.sizeBytes||n.contentHash||(n.source===C.source&&n.sourceIdentity===C.sourceIdentity||n.capturedIdentity.split(`:`).slice(0,2).join(`:`)===C.capturedIdentity.split(`:`).slice(0,2).join(`:`))&&Object.assign(n,e)}}},finish(e){if(_.size){for(let e of namespaces())finishPluginNativeNamespace(e);x=e,b&&linkHost(b),assertReferenceNamespaces(),publish(),_.clear()}},linkHost(n){v=createPluginNativeReferenceValidator(t,l?.pluginId??e),linkHost(n),assertReferenceNamespaces(g),publish(),_.clear()}}}function createPluginNativeImportPattern(e){let t=e&&typeof e==`object`?Object.keys(e):[];return e=>!t.includes(e)&&t.some(t=>{let n=t.indexOf(`*`);return n>=0&&n<t.length-1&&t.lastIndexOf(`*`)===n&&e.startsWith(t.slice(0,n))&&e.endsWith(t.slice(n+1))})}function capturePluginSourceSnapshot(e,t){return createPluginGenerationArtifact(e,void 0,void 0,void 0,void 0,t,void 0,void 0,!1,!0)}function createPluginGenerationArtifact(...e){return drainPluginGenerationSteps(createPluginGenerationArtifactSteps(...e))}function*createPluginGenerationArtifactSteps(e,t,n,r,i,a,s,c,l=!1,u=!1,d,f=`capture`){let p=getPluginGenerationMetrics();p&&(p.captures++,(c||d)&&p.captureReuse++);let m=typeof t==`string`?[t]:t&&[...t];if(m?.length===0)throw Error(`Selective plugin capture requires at least one entry`);let h=c?.source.sourceCapture??createPluginSourceCapture(),g=h.directory,_=/* @__PURE__ */ new Map,packageForFile=e=>findPluginCapturedPackage(_,e,g)?.owner,y=/* @__PURE__ */ new Map,b=new Set(c?.source.directories),S=/* @__PURE__ */ new Set,w=/* @__PURE__ */ new Map,T=/* @__PURE__ */ new Set,E=createPluginNativeAdmission(e,g,m,i??c?.source.native,h.outputRoot),D=createPluginPackageMetadataCapture({retainedManifest:e=>c?.packageManifests.get(Y.relative(g,e)),sourceForCaptured:e=>w.get(e),packageForFile,isRetainedReference:E.isRetainedReference,resolveSource:E.resolvePreparedSource}),O={},k=new Map(c?.executionAliases),A=new Map(c?.executionSources),j=createPluginSourceFacts(a,l||u,k,A),M=createPluginGenerationReceipt(u?void 0:E.prepared),{additions:N,capture:P,assertModuleAvailable:F}=h,captureAdmitted=e=>{let t=n?n(()=>P(e)):P(e);return E.finish(M.finish()),t},I=/* @__PURE__ */ new Map,L=/* @__PURE__ */ new Map,R=createPluginCaptureResolver(),z=j.resolveDependency,copyPackage=(...e)=>drainPluginGenerationSteps(copyPackageSteps(...e));function*copyPackageSteps(t,i,a=!1,l=!1){let f=d?.(t)??t,p=i?d?.(i)??i:void 0,m=a&&!u&&!d,x=f,P=h.outputRoot&&U(x,h.outputRoot)?h.outputRoot:void 0,B=_.get(f);if(B)return m||(yield*B.materializeSteps(l?p:void 0)),B.capturedRoot;let V=createPluginPackageMapReferences(),H=_.size===0?`package`:`dependency`,ee=`package-${_.size}`,te=Y.join(g,ee,`node_modules`),ne=Y.basename(Y.dirname(x)),re=ne.startsWith(`@`)?Y.dirname(Y.dirname(x)):Y.dirname(x),W=Y.join(te,ne.startsWith(`@`)?ne:``,Y.basename(x));O[f]=W,M.marker(`${ee}\0`);let ie={capturedRoot:W,sourceRoot:x,links:/* @__PURE__ */ new Set,state:`metadata`,captureTarget(e){let t=Y.join(x,Y.relative(W,e));!y.has(t)&&!V.hasMissingTarget(t)&&v(()=>q.statSync(t,{throwIfNoEntry:!1}))?.isFile()&&(U(x,realpathPluginSource(t))||E.isRetainedReference(t))&&(oe(t,e),se.captureMetadata(Y.dirname(t)))},materialize(e){drainPluginGenerationSteps(materializeSteps(e))},materializeSteps};function*materializeSteps(e){if(typeof ie.state==`object`)throw ie.state.error;if(ie.state!==`body`||e){ie.state=e&&ie.state!==`body`?`entry`:`body`;try{e?yield*captureFileSteps(Y.resolve(e)):yield*oe.steps(f,W),yield*captureDependenciesSteps()}catch(e){throw ie.state={error:e},e}}}_.set(f,ie);let ae=createPluginSourceLinkCapture(),oe=createPluginGenerationFileCapture({boundary:x,destination:W,directory:g,packageKind:H,outputRoot:P,capturedPaths:y,capturedDirectories:b,hostModuleLinks:S,originalSources:w,hardlinkedSources:T,sourceCapture:h,sourceLinks:ae,deferExternalLinks:!!n,nativeAdmission:E,sourceOnly:u,retainedSnapshotSource:d!==void 0,receipt:M,retained:c,sourceFacts:j.files,executionAliases:k,executionSources:A,onPackageMetadata(e,t){D.record(t,t=>{for(let n of importTargetNames(t.imports)){if(n===`openclaw`||n===`@openclaw/plugin-sdk`)continue;let t=z(n,e);t&&linkDependency(n,t,!0)}})}}),linkDependency=(e,t,n=!1)=>drainPluginGenerationSteps(linkDependencySteps(e,t,n));function*linkDependencySteps(t,n,r=!1){let i=yield*copyPackageSteps(n.root,void 0,r),a=isPluginPackageFile(x,n.lookupDirectory)?Y.join(W,Y.relative(x,n.lookupDirectory)):Y.join(n.lookupDirectory,`node_modules`)===re?Y.dirname(te):W,s=Y.join(a,`node_modules`,t),c=_.get(n.root);c.links.add(s);try{linkPluginGenerationDependency(s,i)&&N.add(s),j.recordLink(s,i)}catch(n){let r=C(t,e,n);throw c.state={error:r},N.add(s),r}}let se=D.createScope({root:f,destination:W,boundary:x,copy:oe,hasSource:e=>y.has(e)}),ce=/* @__PURE__ */ new Map,le=createPluginNativeDependencyScopes(z,(e,t)=>linkDependency(e,t,!0)),ue=createPluginSourceDirectoryCapture(captureFileSteps),de=0,captureFile=e=>drainPluginGenerationSteps(captureFileSteps(e));function*captureFileSteps(t,i){++de===32&&(de=0,yield);let a=d?.(t)??t,u=y.get(Y.resolve(a));if(u&&(F(u),!/\.[cm]?[jt]sx?$/.test(a)||I.has(u)))return;let m=u??Y.join(W,Y.relative(f,a));if(S.has(m))return;if(!u){let e=E.resolvePreparedSource(a),t=inspectPluginCaptureSource(a,x,e,E.isRetainedReference,P);if(!t)return;let{real:n}=t;if(t.directory){yield*ue(a,n,m,i,!e);return}yield*oe.steps(a,m)}if(!/\.[cm]?[jt]sx?$/.test(a))return;let h=se.resolve(Y.dirname(a)),g=createPluginDependencyLookup(a,h?.manifest,z,linkDependency),_=c?.modules?.get(a);!_&&process.env.JITI_TSCONFIG_PATHS!==void 0&&R.get(a);let v=createPluginGenerationReferenceCapture({source:a,rootDir:e,root:f,boundary:x,destination:W,entry:p,executableEntry:l,execute:!!n,resolveFrozenInput:d,moduleSource:r,originalSources:w,nativeAdmission:E,resolution:R,references:ce,inspected:_,scope:h,packageMap:V,capturedPaths:y,resolveDependency:z,captureFile,captureExecutableFile,owner:ie,sourceLinks:ae,linkSharedModule:s?(t,n,r)=>{let i=resolveBundledSharedModule(s,e,t,n);return i?(r.startsWith(`.`)&&U(x,n)&&linkBundledSharedModule(Y.join(W,Y.relative(x,n)),i,N,S),!0):!1}:void 0}),{observed:C,capture:T}=v,D={isNativeImportPattern:createPluginNativeImportPattern(h?.manifest.imports),isRequireReference:e=>C.has(`require\0${e}`)&&!C.has(`import\0${e}`),prepareDependency:g,nativeScope:le(a,h?.manifest),capture:(e,t)=>{let r=e;if(d&&r.startsWith(`file:`)){let e=new URL(r);e.pathname=Z(d(X(e))).pathname,r=e.href}else d&&Y.isAbsolute(r)&&(r=d(r));let i=r.startsWith(`file:`)?X(r):Y.isAbsolute(r)?r:void 0,s=i&&y.get(Y.resolve(i));if(n&&s)return F(s),{target:capturedPluginModuleUrl(s,r,t)};let c=packageName(r),l=h?.manifest.exports!=null&&h.manifest.name===c;if(!r.startsWith(`.`)&&!Y.isAbsolute(r)&&!r.startsWith(`file:`)&&!l&&!r.startsWith(`#`)&&R.get(a).options.tsconfigPaths){let e=T(r,t.includes(`require`)?`require`:`import`,t),n=e&&y.get(Y.resolve(e));if(n)return captureDependencies(),F(n),{target:Z(n)}}let u=g(r);if(typeof u==`boolean`)return u?{retryNative:!0}:void 0;if(u===`package-map`){let e=resolvePluginPackageMapTarget(r,m,t);if(!e)return;let n=X(e);if(isPluginPackageFile(W,n)){let e=Y.join(x,Y.relative(W,n));if(V.hasMissingTarget(e))return;if(!y.has(e)&&!q.existsSync(e)){V.recordMissingTarget(e);return}captureFile(e)}else packageForFile(n)?.materialize();return captureDependencies(),{retryNative:!0}}let f=T(r,t.includes(`require`)?`require`:`import`,t);captureDependencies();let p=f?y.get(Y.resolve(f)):void 0;if(p)return F(p),{target:capturedPluginModuleUrl(p,r,t)}}};if(I.set(m,D),_||p&&!l||process.versions.bun){let e=yield*v.inspect(()=>readPluginCapturedCode(m,b.has(m)),captureFileSteps);D.staticImports=e.staticImports,s||L.set(a,e)}}let captureDependencies=()=>drainPluginGenerationSteps(captureDependenciesSteps());function*captureDependenciesSteps(){let e=[],t=Y.join(f,`package.json`);if(!p&&!y.has(t))return;let n;try{capturePluginDependencies({root:f,plan:p?void 0:D.dependencyPlan(Y.join(W,`package.json`)),references:ce,resolve:z,capture:(t,n)=>e.push([t,n])})}catch(e){n={error:e}}for(let[t,n]of e)yield*linkDependencySteps(t,n);if(n)throw n.error}return m?D.capturePackage(f,W,oe):yield*materializeSteps(p),W}let captureExecutableFile=e=>n?.(()=>{let t=realpathPluginSource(d?.(e)??e);if(v(()=>q.statSync(t)).isFile())return copyPackage(resolvePluginModulePackageRoot(t),t,!1,!0),t});try{let t=realpathPluginSource(e),r=m?.map(e=>realpathPluginSource(e)),i=yield*copyPackageSteps(t,r?.[0]);for(let e of r?.slice(1)??[])yield*_.get(t).materializeSteps(e);(u||d)&&D.prepare(),O[Y.resolve(e)]=i;for(let[n,i]of r?.entries()??[]){let r=Y.join(t,Y.relative(Y.resolve(e),Y.resolve(m[n]))),a=y.get(i);a&&y.set(r,a)}let a=yield*M.finishSteps();E.finish(a),N.clear();let f=[I,T,D,_,R,L,b],clearCaptures=()=>f.forEach(e=>e.clear()),p=createPluginGenerationSourceLookup({rootDir:e,sourceRoot:t,capturedRoot:i,boundaryRoot:g,capturedPaths:y,capturedDirectories:b,hardlinkedSources:T,assertModuleAvailable:F,captureNativeRecovery:()=>E.captureRecovery(a,O)});return{sourceRoot:t,sharedModule:bundledSharedModuleResolver(s,i),rootDir:i,sourceAliases:O,executionAliases:k,executionSources:A,sourceText:e=>A.get(Y.relative(g,e)),executionAlias:e=>{let t=k.get(Y.relative(g,e));return t===void 0?void 0:Y.join(g,t)},linkHost:e=>{h.linkHost(e),E.linkHost(e)},sourceDigest:a.sourceDigest,...u||l?{sourceSnapshotFacts:j.snapshot(g,b,T)}:{},...p,retainSourceCustody:markPluginSourceCaptureOperation(()=>({...j.captureCustody(p.captureRecoverySource),packageManifests:D.snapshot(g),modules:new Map(L)})),...createPluginGenerationModuleLookup({capturedPaths:y,capturedDirectories:b,originalSources:w,moduleCaptures:I,metadataCapture:D,assertModuleAvailable:F,captureAdmitted,captureExecutableFile,executable:!!n,packages:_,directory:g}),dispose:()=>{(c?.source??h).dispose(),clearCaptures()},disposeAsync:()=>(c?.source??h).disposeAsync().then(clearCaptures)}}catch(e){if(f===`capture`)try{(c?.source??h).dispose()}catch(e){throw x(e)}throw e}}var PluginSnapshotDependencyError=class extends Error{constructor(e){super(`Plugin module ${e} is outside the installed snapshot dependency closure. Declare the dependency and reinstall or update the plugin, or use a local development source.`),this.modulePath=e,this.code=`ERR_PLUGIN_SNAPSHOT_DEPENDENCY`,this.name=`PluginSnapshotDependencyError`}};function capturePluginSnapshotGeneration(e,t,n,r,i){return drainPluginGenerationSteps(createPluginFrozenGenerationSteps(e,t=>createPluginGenerationArtifactSteps(e.rootDir,void 0,n,r,i,void 0,void 0,void 0,!0,!1,t)))}function*createPluginFrozenGenerationSteps(e,t,n=`capture`){let r=Object.entries(e.sourceAliases).toSorted(([e],[t])=>t.length-e.length),i=[...e.sourceLinks].toSorted(([e],[t])=>t.length-e.length),inputFor=e=>{let t=Y.resolve(e),n=r.find(([e])=>U(e,t));n&&(t=Y.join(n[1],Y.relative(n[0],t)));for(let e=0;e<=i.length;e++){let e=i.find(([e])=>U(e,t));if(!e)return t;t=Y.join(e[1],Y.relative(e[0],t))}throw new PluginSnapshotDependencyError(e)},assertInput=t=>{if(!e.sourcePaths.has(inputFor(t)))throw new PluginSnapshotDependencyError(t)},a=yield*t(e=>(assertInput(e),inputFor(e)));if(a.sourceDigest!==e.sourceDigest)throw n===`capture`&&a.dispose(),Error(`Plugin snapshot runtime receipt differs from its immutable source receipt`);let s=Object.entries(a.sourceAliases).toSorted(([,e],[,t])=>t.length-e.length),sourceInputFor=e=>{let t=a.sourceForCaptured(e);if(t)return t;let n=s.find(([,t])=>U(t,e));return n?Y.join(n[0],Y.relative(n[1],e)):e},assertFrozenModule=e=>assertInput(sourceInputFor(e)),originalFor=e=>{let t=r.find(([,t])=>U(t,e));return t?Y.join(t[0],Y.relative(t[1],e)):e},c=Object.fromEntries(r.map(([e,t])=>[e,a.sourceAliases[t]])),runtimeFor=e=>{let t=s.find(([t])=>U(t,e));return t?Y.join(t[1],Y.relative(t[0],e)):e},freezeRecovery=(t,n,r,i,a)=>{let s=t.sourceCapture.directory,relocate=e=>Y.join(s,Y.relative(n,e)),c=snapshotPluginRecoverySourceResolver(t.resolve),l=new Map(c.sources);for(let[e,t]of c.sources)l.set(originalFor(e),t);t.resolve=restorePluginRecoverySourceResolver({...c,sources:l});let u=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,relocate(t)])),d=new Map([...i].map(([e,t])=>[relocate(e),relocate(t)])),f=new Set([...a].map(relocate));t.frozenSource={rootDir:t.rootDir,sourceRoot:e.sourceRoot,sourceAliases:u,sourcePaths:/* @__PURE__ */ new Set([...l.values(),...t.directories]),sourceLinks:d,sourceHardlinks:f,sourceDigest:e.sourceDigest};let p=t.fork;return t.fork=markPluginSourceCaptureOperation(()=>freezeRecovery(p(),s,u,d,f)),t},freezeCapturedRecovery=t=>freezeRecovery(t,a.boundaryRoot,c,new Map([...e.sourceLinks].map(([e,t])=>[runtimeFor(e),runtimeFor(t)])),new Set([...e.sourceHardlinks].map(runtimeFor))),recover=()=>freezeCapturedRecovery(a.captureRecoverySource()),l={...a};return delete l.sourceSnapshotFacts,{...l,sourceRoot:e.sourceRoot,sourceAliases:{...a.sourceAliases,...c},frozenSource:!0,assertFrozenModule,captureRecoverySource:markPluginSourceCaptureOperation(recover),captureRecoverySourceAsync:markPluginSourceCaptureOperation(async()=>freezeCapturedRecovery(await(a.captureRecoverySourceAsync?.()??a.captureRecoverySource()))),retainSourceCustody:markPluginSourceCaptureOperation(()=>{let e=a.retainSourceCustody();return{...e,source:freezeCapturedRecovery(e.source)}}),hasSource:t=>e.sourcePaths.has(inputFor(sourceInputFor(t))),resolve:(t,n)=>{let r=inputFor(sourceInputFor(t));if(assertInput(r),n&&e.sourceHardlinks.has(r))throw j(/* @__PURE__ */ Error(`Plugin source is hardlinked; use a separate file and reload.`));return a.captureResolvedModule(r)??a.resolve(r,n)},sourceForCaptured:e=>{let t=a.sourceForCaptured(e);return t?originalFor(t):void 0}}}var GenerationCodec=class{constructor(e,t){this.invoke=e,this.nativeRoots=t,this.next=0,this.handles=/* @__PURE__ */ new Map,this.identities=/* @__PURE__ */ new WeakMap,this.received=/* @__PURE__ */ new Map,this.remote=/* @__PURE__ */ new WeakMap,this.resources=/* @__PURE__ */ new WeakMap,this.owners=/* @__PURE__ */ new Map,this.released=/* @__PURE__ */ new Set}retainResource(e){this.resources.has(e)||this.resources.set(e,/* @__PURE__ */ new Set)}releaseResource(e){for(let t of this.resources.get(e)??[]){let n=this.owners.get(t);if(n.resources.delete(e),!n.unowned&&!n.resources.size){let e=this.handles.get(t);this.identities.delete(e),this.handles.delete(t),this.owners.delete(t),this.released.add(t)}}this.resources.delete(e)}takeReleasedHandles(){let e=[...this.released];return this.released.clear(),e}isSourcePreparationCall(e){let t=this.handles.get(e);return typeof t==`function`&&g(t)}releaseReceivedHandles(e){for(let t of e){let e=this.received.get(t);e&&(this.remote.delete(e),this.received.delete(t))}}encodeArguments(e){let t=/* @__PURE__ */ new Map;return e.map(e=>this.encode(e,t))}encodeResult(e,t){let n=this.owners.get(t);if(!n||n.unowned)return this.encode(e);let[r,...i]=n.resources,a=this.encode(e,void 0,void 0,r);if(e!==null&&(typeof e==`object`||typeof e==`function`))for(let t of i)this.retainSharedHandles(e,t);return a}encode(e,t=/* @__PURE__ */ new Map,n,r){if(e===null||typeof e!=`object`&&typeof e!=`function`)return{kind:`value`,value:e};let i=this.resources.has(e),a=i?e:r,s=this.remote.get(e);if(s!==void 0)return{kind:`remote`,id:s};let c=t.get(e);if(c!==void 0)return this.retainSharedHandles(e,a),{kind:`reference`,id:c};let l=typeof e==`function`?snapshotPluginRecoverySourceResolver(e):void 0,u=isOwnedPluginNativeRecovery(e),d=u||typeof e==`function`&&!l,f=d?this.identities.get(e):void 0;if(f!==void 0&&u)return this.retainHandle(f,a),{kind:`reference`,id:f};f===void 0&&(f=++this.next,d&&(this.identities.set(e,f),this.handles.set(f,e))),this.retainHandle(f,a),t.set(e,f);let p=snapshotPluginNativeRootLease(e);if(p){let e=this.nativeRoots.exportRoot(p.root);return p.release(),{kind:`native-root`,id:f,rootId:e}}if(typeof e==`function`)return l?{kind:`source-resolver`,id:f,snapshot:this.encode(l,t,void 0,a)}:{kind:`function`,id:f,asynchronous:e.constructor.name===`AsyncFunction`||!!n?.endsWith(`Async`),sourceCapture:isPluginSourceCaptureOperation(e),...n===`dispose`||n===`disposeAsync`?{disposal:!0}:{}};if(u){let n=snapshotPluginNativeRecovery(e);return{kind:`native`,id:f,snapshot:this.encode(n,t,void 0,a)}}if(e instanceof URL)return{kind:`url`,id:f,value:e.href};if(e instanceof Map)return{kind:`map`,id:f,entries:[...e].map(([e,n])=>[this.encode(e,t,void 0,a),this.encode(n,t,void 0,a)])};if(e instanceof Set)return{kind:`set`,id:f,entries:[...e].map(e=>this.encode(e,t,void 0,a))};if(Array.isArray(e))return{kind:`array`,id:f,entries:e.map(e=>this.encode(e,t,void 0,a))};if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw Error(`Unsupported plugin generation transport object`);return{kind:`object`,id:f,...i?{resource:!0}:{},entries:Object.entries(e).map(([e,n])=>[e,this.encode(n,t,e,a)])}}retainHandle(e,t){if(!this.handles.has(e))return;let n=this.owners.get(e);n||(n={resources:/* @__PURE__ */ new Set,unowned:!1},this.owners.set(e,n)),t?(n.resources.add(t),this.resources.get(t).add(e)):n.unowned=!0}retainSharedHandles(e,t,n=/* @__PURE__ */ new Set){if(n.has(e)||e!==t&&this.resources.has(e))return;n.add(e);let r=this.identities.get(e);if(r!==void 0){this.retainHandle(r,t);return}let i=e instanceof Map?[...e].flat():e instanceof Set?[...e]:Object.values(e);for(let e of i)e!==null&&(typeof e==`object`||typeof e==`function`)&&this.retainSharedHandles(e,t,n)}decode(e,t=/* @__PURE__ */ new Map){if(e.kind===`value`)return e.value;if(e.kind===`reference`||e.kind===`remote`){let n=e.kind===`remote`?this.handles.get(e.id):t.get(e.id)??this.received.get(e.id);if(!n)throw Error(`Expired plugin generation handle`);return n}let n=t.get(e.id)??this.received.get(e.id);if(n)return n;let r;if(r=e.kind===`function`?(...t)=>this.invoke(e.id,t,e.asynchronous,e.sourceCapture,e.disposal===!0):e.kind===`source-resolver`?restorePluginRecoverySourceResolver(this.decode(e.snapshot,t)):e.kind===`url`?new URL(e.value):e.kind===`native-root`?this.nativeRoots.importRoot(e.rootId):e.kind===`native`?restorePluginNativeRecovery(this.decode(e.snapshot,t)):e.kind===`map`?/* @__PURE__ */ new Map:e.kind===`set`?/* @__PURE__ */ new Set:e.kind===`array`?[]:{},t.set(e.id,r),(e.kind===`function`||e.kind===`native`)&&(this.received.set(e.id,r),this.remote.set(r,e.id)),e.kind===`object`){for(let[n,i]of e.entries)Object.defineProperty(r,n,{value:this.decode(i,t),enumerable:!0,configurable:!0,writable:!0});let n=Object.getOwnPropertyDescriptor(r,`native`)?.value,i=n&&typeof n==`object`&&isOwnedPluginNativeRecovery(n)?n:void 0;if(e.resource||i){let e=Object.getOwnPropertyDescriptor(r,`dispose`)?.value,t=Object.getOwnPropertyDescriptor(r,`disposeAsync`)?.value;if(typeof e==`function`&&typeof t==`function`){let n=!1,a,s,failNativeCleanup=e=>{throw s=e instanceof Error?e:Error(String(e)),s};Object.defineProperty(r,"dispose",{value:()=>{if(s)throw s;if(!(n||a)){try{Reflect.apply(e,void 0,[])}finally{try{i?.dispose()}catch(e){failNativeCleanup(e)}}n=!0}},enumerable:!0,configurable:!0}),Object.defineProperty(r,"disposeAsync",{value:()=>s?Promise.reject(s):a||(n?Promise.resolve():(a=(async()=>{try{await Reflect.apply(t,void 0,[])}finally{try{await i?.disposeAsync()}catch(e){failNativeCleanup(e)}}n=!0})().finally(()=>{a=void 0}),a)),enumerable:!0,configurable:!0})}}}else if(e.kind===`map`&&r instanceof Map)for(let[n,i]of e.entries)r.set(this.decode(n,t),this.decode(i,t));else if(e.kind===`set`&&r instanceof Set)for(let n of e.entries)r.add(this.decode(n,t));else if(e.kind===`array`&&Array.isArray(r))for(let n of e.entries)r.push(this.decode(n,t));return r}call(e,t){let n=this.handles.get(e);if(typeof n!=`function`)throw Error(`Invalid plugin generation method`);let r=/* @__PURE__ */ new Map;return Reflect.apply(n,void 0,t.map(e=>this.decode(e,r)))}};const Si=/* @__PURE__ */ new WeakSet;function markPrivateDirectoryCreationRefused(e){return typeof e==`object`&&e&&Si.add(e),e}function isPrivateDirectoryCreationRefused(e){return typeof e==`object`&&!!e&&Si.has(e)}var SqliteSnapshotCapacityError=class extends Error{constructor(e,t){super(e,t),this.name=`SqliteSnapshotCapacityError`}};function hasSqliteSnapshotCapacityCode(e){let{code:t,errcode:n}=e;return t===`ENOSPC`||t===`EDQUOT`||n===13}function createPrivateWindowsDirectory(e){let t=!1;try{Ht(Y.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof Kt&&e.code===`already-exists`?markPrivateDirectoryCreationRefused(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&hasSqliteSnapshotCapacityCode(e)?new SqliteSnapshotCapacityError(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&Y.isAbsolute(t))return W({preferredDir:Y.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,r=process.platform===`win32`?`AppData/Local`:`.cache`,i=process.platform===`darwin`?`Library/Caches`:r,a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&Y.isAbsolute(e))??Y.join(ze(e),i),s=ne(e),c=wt(`sha256`).update(s).digest(`hex`).slice(0,24);q.mkdirSync(a,{recursive:!0,mode:448});let l=W({preferredDir:Y.join(a,`openclaw`),tmpdir:()=>a}),[u=``,...d]=Y.relative(l,s).split(Y.sep),f=d.length>0&&/^sqlite-[a-f0-9]{24}$/u.test(u)?u:`sqlite-${c}`,p=Y.join(l,f);q.mkdirSync(p,{recursive:!0,mode:448});let m=q.lstatSync(p);if(!m.isDirectory()||process.getuid&&m.uid!==process.getuid()||process.platform!==`win32`&&m.mode&63)throw Error(`SQLite snapshot namespace must be a private user-owned directory`);return p}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return q.mkdtempSync(Y.join(e,t))}catch(e){throw markPrivateDirectoryCreationRefused(e)}let n=Y.join(e,`${t}${Et()}`);return createPrivateWindowsDirectory(n),n}var PluginSourceSnapshotValidationError=class extends Error{constructor(e,t,n){super(`Installed plugin source snapshot is invalid at ${e}: ${t}`,n),this.artifactPath=e,this.code=`PLUGIN_SOURCE_SNAPSHOT_INVALID`,this.name=`PluginSourceSnapshotValidationError`}};function failPluginSourceSnapshot(e,t){throw new PluginSourceSnapshotValidationError(e,t)}function privatePluginSnapshotEntry(e,t,n){return assertPrivatePluginSnapshotEntry(e,t,n,q.lstatSync(e,{bigint:!0}))}function assertPrivatePluginSnapshotEntry(e,t,n,r){return(!(n===`directory`?r.isDirectory():n===`file`?r.isFile():r.isSymbolicLink())||process.getuid&&r.uid!==BigInt(process.getuid())||n!==`link`&&process.platform!==`win32`&&(r.mode&63n)!=0n||n===`file`&&r.nlink!==1n||process.platform===`win32`&&(r.dev===0n||r.ino===0n))&&failPluginSourceSnapshot(t,`unsafe ${n} ownership, permissions or identity: ${e}`),r}function relativePluginSnapshotMember(e,t){let n=Y.relative(e,t);return n&&U(e,t)||failPluginSourceSnapshot(e,`member leaves its payload: ${t}`),n}function scanPluginSnapshotPayload(e,t,n=e){let r=[],visit=i=>{let a=privatePluginSnapshotEntry(i,e,`directory`);for(let a of q.readdirSync(i).toSorted()){let s=Y.join(i,a),c=q.lstatSync(s,{bigint:!0}),l=relativePluginSnapshotMember(e,s);if(c.isSymbolicLink()){privatePluginSnapshotEntry(s,e,`link`);let t=resolvePluginSnapshotLink(e,s,n,t=>failPluginSourceSnapshot(e,t));pluginSourceStatIdentity(c)!==pluginSourceStatIdentity(privatePluginSnapshotEntry(s,e,`link`))&&failPluginSourceSnapshot(e,`dependency link changed while validating: ${s}`),r.push({path:l,kind:`link`,target:relativePluginSnapshotMember(e,t),identity:pluginSourceStatIdentity(c)})}else if(c.isDirectory())privatePluginSnapshotEntry(s,e,`directory`),r.push({path:l,kind:`directory`,identity:pluginSourceStatIdentity(c)}),visit(s);else{privatePluginSnapshotEntry(s,e,`file`);let n=hashPluginSourceFile(s,e,void 0,void 0,t.openFile.bind(t)),i=privatePluginSnapshotEntry(s,e,`file`);pluginSourceStatIdentity(c)!==pluginSourceStatIdentity(i)&&failPluginSourceSnapshot(e,`file changed while validating: ${s}`),r.push({path:l,kind:`file`,identity:pluginSourceStatIdentity(i),...n,mode:Number(i.mode&511n)})}}pluginSourceStatIdentity(a)!==pluginSourceStatIdentity(privatePluginSnapshotEntry(i,e,`directory`))&&failPluginSourceSnapshot(e,`directory changed while validating: ${i}`)};return visit(e),r}function capturePluginSnapshotPayload(e,t,n,r){let i=[],copy=(n,a)=>{let s=q.lstatSync(n,{bigint:!0});if(s.isSymbolicLink()){let s=Y.resolve(Y.dirname(n),q.readlinkSync(n));U(e.boundaryRoot,s)||r(`capture contains an external link: ${n}`),i.push([a,Y.join(t,Y.relative(e.boundaryRoot,s))])}else if(s.isDirectory()){q.mkdirSync(a,{recursive:!0,mode:448});for(let e of q.readdirSync(n).toSorted())copy(Y.join(n,e),Y.join(a,e))}else s.isFile()?copyPluginSourceFile(n,e.boundaryRoot,a):r(`capture contains a nonregular source: ${n}`)};copy(e.boundaryRoot,t);for(let[e,r]of i)linkPluginGenerationDependency(e,Y.join(n,Y.relative(t,r)),r)}function resolvePluginSnapshotLink(e,t,n,r){let i=Y.resolve(Y.dirname(t),q.readlinkSync(t)),a=process.platform===`win32`?te(i):i,s=Y.resolve(e,Y.relative(n,a));return U(n,a)&&U(e,s)&&q.lstatSync(s).isDirectory()&&U(e,q.realpathSync(s))||r(`dependency link leaves its frozen closure: ${t}`),s}function digestPluginSnapshotClosure(e,t){let n=e.sourceSnapshotFacts;return n||t(`capture does not own complete source facts`),wt(`sha256`).update(JSON.stringify({aliases:Object.entries(e.sourceAliases).map(([t,n])=>[t,Y.relative(e.boundaryRoot,n)]).toSorted(([e],[t])=>e.localeCompare(t)),directories:[...n.directories].toSorted(),links:[...n.links].toSorted(([e],[t])=>e.localeCompare(t)),files:[...n.files].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.contentHash,t.sizeBytes,t.mode]),hardlinks:[...n.hardlinks].toSorted()})).digest(`hex`)}const Ci=`manifest.json`,wi=`payload`,Ti=m(Symbol.for(`openclaw.pluginSourceSnapshotReaders`),()=>/* @__PURE__ */ new Map),digest=e=>wt(`sha256`).update(e).digest(`hex`),ownerIdentity=e=>`${e.dev}:${e.ino}:${e.uid}:${e.gid}:${e.mode}`;function tokenIdentity(e){let t=Y.join(e,tt[0]);return assertTokenIdentity(e,q.lstatSync(t,{bigint:!0}))}function assertTokenIdentity(e,t){let n=Y.join(e,tt[0]);return(!t.isFile()||t.nlink!==1n||process.getuid&&t.uid!==BigInt(process.getuid())||process.platform!==`win32`&&(t.mode&18n)!=0n)&&failPluginSourceSnapshot(e,`unsafe token ownership or permissions: ${n}`),ownerIdentity(t)}function pluginSourceSnapshotClosureDigest(e){return digestPluginSnapshotClosure(e,t=>failPluginSourceSnapshot(e.boundaryRoot,t))}async function stagePluginSourceSnapshot(e){await e.assertCurrent(),(e.binding.contentDigest!==e.capture.sourceDigest||e.binding.dependencyClosureDigest!==pluginSourceSnapshotClosureDigest(e.capture))&&failPluginSourceSnapshot(e.capture.boundaryRoot,`captured content or dependency closure does not match the installation record`);let t=resolvePluginSourceCapturesDirectory(e.stateDir);assertPluginSourceCaptureDiskSpace(t),q.mkdirSync(t,{recursive:!0,mode:448});let n=q.realpathSync.native(t);privatePluginSnapshotEntry(n,n,`directory`);let r=Et(),i=createPrivateSqliteTempDirectorySync(n,Xn),a=Y.join(n,`${Yn}${r}`),s=ownerIdentity(privatePluginSnapshotEntry(i,i,`directory`)),c=!1,l,u=retainPluginSourceCaptureRoot(i),d=!1,f=!1,disposeAsync=async()=>{if(!d){d=!0;try{l?.(!0),l=void 0;let e=c?a:i,t=q.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});t&&ownerIdentity(t)===s&&await J.rm(e,{recursive:!0,force:!0})}finally{u()}}};try{try{var p=_usingCtx();l=nt(i,`create`);let t=tokenIdentity(i),n=Y.join(i,wi),h=Y.join(a,wi);capturePluginSnapshotPayload(e.capture,n,h,e=>failPluginSourceSnapshot(i,e));let g=scanPluginSnapshotPayload(n,p.u(Gt()),h),_=e.capture.sourceSnapshotFacts;(!_||g.length!==_.files.size+_.directories.size+_.links.size||g.some(e=>{if(e.kind===`directory`)return!_.directories.has(e.path);if(e.kind===`link`)return _.links.get(e.path)!==e.target;let t=_.files.get(e.path);return!t||t.contentHash!==e.contentHash||t.sizeBytes!==e.sizeBytes||process.platform!==`win32`&&t.mode!==e.mode}))&&failPluginSourceSnapshot(e.capture.boundaryRoot,`source changed after its installation receipt was captured`);let v={...e.binding,formatVersion:1,generation:r,sourceRoot:e.capture.sourceRoot,root:relativePluginSnapshotMember(e.capture.boundaryRoot,e.capture.rootDir),aliases:Object.fromEntries(Object.entries(e.capture.sourceAliases).map(([t,n])=>[t,relativePluginSnapshotMember(e.capture.boundaryRoot,n)])),sourceDigest:e.capture.sourceDigest,payloadIdentity:pluginSourceStatIdentity(privatePluginSnapshotEntry(n,i,`directory`)),tokenIdentity:t,hardlinks:[..._.hardlinks],platform:process.platform,arch:process.arch,abi:process.versions.modules??``,entries:g},y=JSON.stringify(v);try{var m=_usingCtx();let e=m.u(Ut(Y.join(i,Ci),{mode:384}));q.writeFileSync(e.fd,y),q.fsyncSync(e.fd)}catch(e){m.e=e}finally{m.d()}let b={...e.binding,formatVersion:1,generation:r,platform:v.platform,arch:v.arch,abi:v.abi,artifact:{path:i,identity:s,manifestIdentity:pluginSourceStatIdentity(privatePluginSnapshotEntry(Y.join(i,Ci),i,`file`)),manifestDigest:digest(y),tokenIdentity:t}};return await e.assertCurrent(),assertSnapshotIdentities(b,v,h),{descriptor:{...b,artifact:{...b.artifact,path:a}},async publish(){if(d||f)throw Error(`Plugin source snapshot publication already settled`);f=!0;try{return await e.assertCurrent(),assertSnapshotIdentities(b,v,h),l(),l=void 0,ge(Y.join(i,tt[0])),q.renameSync(i,a),b.artifact.path=a,c=!0,await e.assertCurrent(),assertSnapshotIdentities(b,v),d=!0,u(),b}catch(e){throw await disposeAsync(),e}},dispose:()=>{disposeAsync().catch(()=>{})},disposeAsync}}catch(e){p.e=e}finally{p.d()}}catch(e){throw await disposeAsync(),e}}function assertArtifactPath(e,t){let n=q.realpathSync.native(resolvePluginSourceCapturesDirectory(e));assertArtifactNamespace(t,n),q.realpathSync.native(t)!==t&&failPluginSourceSnapshot(t,`artifact is outside the private capture owner`),privatePluginSnapshotEntry(n,t,`directory`)}function assertArtifactNamespace(e,t){Y.basename(e).startsWith(`snapshot-v1-staging-`)&&failPluginSourceSnapshot(e,`unfinished snapshot staging namespace`),Y.dirname(e)===t&&Y.basename(e).startsWith(`snapshot-v1-`)||failPluginSourceSnapshot(e,`artifact is outside the private capture owner`)}function validateSnapshot(e,t){try{var n=_usingCtx();let r=t.artifact.path;assertArtifactPath(e,r),(t.formatVersion!==1||t.platform!==process.platform||t.arch!==process.arch||t.abi!==(process.versions.modules??``))&&failPluginSourceSnapshot(r,`capture format or platform/ABI is incompatible`),ownerIdentity(privatePluginSnapshotEntry(r,r,`directory`))!==t.artifact.identity&&failPluginSourceSnapshot(r,`artifact root identity changed`),tokenIdentity(r)!==t.artifact.tokenIdentity&&failPluginSourceSnapshot(r,`snapshot token identity changed`);let i=Y.join(r,Ci);pluginSourceStatIdentity(privatePluginSnapshotEntry(i,r,`file`))!==t.artifact.manifestIdentity&&failPluginSourceSnapshot(r,`manifest identity changed`);let a=n.u(Gt()),s=a.openFile({absolutePath:i,rootPath:r,boundaryLabel:`plugin snapshot manifest`,rejectHardlinks:!0});s.ok||failPluginSourceSnapshot(r,`manifest failed guarded open`);let c;try{c=me(s.fd,67108864).toString(`utf8`)}finally{q.closeSync(s.fd)}digest(c)!==t.artifact.manifestDigest&&failPluginSourceSnapshot(r,`manifest content digest changed`);let l=JSON.parse(c);for(let e of[`formatVersion`,`generation`,`installRecordHash`,`contentDigest`,`dependencyClosureDigest`,`buildResolutionDigest`,`packageIntegrity`,`platform`,`arch`,`abi`])l[e]!==t[e]&&failPluginSourceSnapshot(r,`manifest binding changed: ${e}`);l.sourceDigest!==t.contentDigest&&failPluginSourceSnapshot(r,`manifest source receipt does not match installation content`),l.tokenIdentity!==t.artifact.tokenIdentity&&failPluginSourceSnapshot(r,`manifest token identity does not match installation`);let u=scanPluginSnapshotPayload(Y.join(r,wi),a);JSON.stringify(u)!==JSON.stringify(l.entries)&&failPluginSourceSnapshot(r,`payload content, identity or membership changed`);let d=/* @__PURE__ */ new Set([Ci,wi,...tt]);q.readdirSync(r).some(e=>!d.has(e))&&failPluginSourceSnapshot(r,`unexpected artifact member`);for(let e of tt){let t=Y.join(r,e),n=q.lstatSync(t,{bigint:!0,throwIfNoEntry:!1});n&&(!n.isFile()||process.platform!==`win32`&&(n.mode&18n)!=0n)&&failPluginSourceSnapshot(r,`unsafe token permissions or type: ${t}`)}return(ownerIdentity(privatePluginSnapshotEntry(r,r,`directory`))!==t.artifact.identity||pluginSourceStatIdentity(privatePluginSnapshotEntry(i,r,`file`))!==t.artifact.manifestIdentity)&&failPluginSourceSnapshot(r,`artifact changed while validating`),l}catch(e){n.e=e}finally{n.d()}}function assertSnapshotIdentities(e,t,n=Y.join(e.artifact.path,wi)){let r=e.artifact.path;tokenIdentity(r)!==e.artifact.tokenIdentity&&failPluginSourceSnapshot(r,`snapshot token identity changed after source validation`),(ownerIdentity(privatePluginSnapshotEntry(r,r,`directory`))!==e.artifact.identity||pluginSourceStatIdentity(privatePluginSnapshotEntry(Y.join(r,Ci),r,`file`))!==e.artifact.manifestIdentity)&&failPluginSourceSnapshot(r,`artifact changed after source validation`);let i=Y.join(r,wi);pluginSourceStatIdentity(privatePluginSnapshotEntry(i,r,`directory`))!==t.payloadIdentity&&failPluginSourceSnapshot(r,`payload root changed after source validation`);for(let e of t.entries)if(pluginSourceStatIdentity(privatePluginSnapshotEntry(Y.join(i,e.path),r,e.kind))!==e.identity&&failPluginSourceSnapshot(r,`payload member changed after source validation: ${Y.join(i,e.path)}`),e.kind===`link`){let t=resolvePluginSnapshotLink(i,Y.join(i,e.path),n,e=>failPluginSourceSnapshot(r,e));Y.relative(i,t)!==e.target&&failPluginSourceSnapshot(r,`dependency link target changed: ${Y.join(i,e.path)}`),pluginSourceStatIdentity(privatePluginSnapshotEntry(Y.join(i,e.path),r,`link`))!==e.identity&&failPluginSourceSnapshot(r,`dependency link changed while validating: ${Y.join(i,e.path)}`)}}async function acquirePluginSourceSnapshot(e){let t=e.descriptor.artifact.path;await e.assertCurrent();let n=Ti.get(t),r=!1,i=!1;try{if(assertArtifactPath(e.stateDir,t),!n){let r=q.lstatSync(Y.join(t,tt[0]),{bigint:!0}),i=assertTokenIdentity(t,r);i!==e.descriptor.artifact.tokenIdentity&&failPluginSourceSnapshot(t,`snapshot token identity changed`),n={token:nt(t,`read`,{expectedIdentity:{key:`file:${r.dev}:${r.ino}`,birthtime:Ne(r)}}),tokenIdentity:i,references:0},Ti.set(t,n)}n.references++,r=!0;let a=n,assertReader=()=>{tokenIdentity(t)!==a.tokenIdentity&&failPluginSourceSnapshot(t,`snapshot reader token identity changed`)};assertReader();let s=validateSnapshot(e.stateDir,e.descriptor);i=!0,await e.assertCurrent(),i=!1,assertReader(),assertSnapshotIdentities(e.descriptor,s);let c=!1,release=()=>{c||(c=!0,--a.references===0&&(Ti.delete(t),a.token()))},l=Y.join(t,wi);return{rootDir:Y.join(l,s.root),sourceRoot:s.sourceRoot,sourceAliases:Object.fromEntries(Object.entries(s.aliases).map(([e,t])=>[e,Y.join(l,t)])),sourceDigest:s.sourceDigest,assertCurrent:()=>{try{assertReader(),assertSnapshotIdentities(e.descriptor,s)}catch(e){throw e instanceof PluginSourceSnapshotValidationError&&e.artifactPath===t?e:new PluginSourceSnapshotValidationError(t,`snapshot changed after source validation`,{cause:e})}},sourcePaths:new Set(s.entries.map(e=>Y.join(l,e.path))),sourceHardlinks:new Set(s.hardlinks.map(e=>Y.join(l,e))),sourceLinks:new Map(s.entries.flatMap(e=>e.kind===`link`?[[Y.join(l,e.path),Y.join(l,e.target)]]:[])),release,releaseAsync:async()=>release()}}catch(e){throw n&&r&&--n.references===0&&(Ti.delete(t),n.token()),i||e instanceof PluginSourceSnapshotValidationError&&e.artifactPath===t?e:new PluginSourceSnapshotValidationError(t,`snapshot validation failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}const Ei=createPluginCaptureResourceClient(xt[Fn]);function preparationFailure(e,t){let n=e instanceof Error?e:Error(String(e));return{error:{message:n.message,name:n.name,stack:n.stack,...`code`in n&&typeof n.code==`string`?{code:n.code}:{},...`artifactPath`in n&&typeof n.artifactPath==`string`?{artifactPath:n.artifactPath}:{},...`modulePath`in n&&typeof n.modulePath==`string`?{modulePath:n.modulePath}:{}},...t&&ee(e)?{sourceAcquisitionFailure:!0}:{}}}function createPreparationSession(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new WeakSet,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new WeakMap,c=/* @__PURE__ */ new Set,l;function borrowNativeRoot(e){let t=s.get(e);if(t===void 0){let n=requestHost({kind:`native-root-reference`,directory:e.directory}).root;if(!n)throw Error(`Plugin native root is not owned by the preparation host`);t=n.id,s.set(e,t)}return t}function admissionChanges(){let e=nativeAdmissionStateFor(),t=new Map([...e.receipts].filter(([e,t])=>i.get(e)!==t)),n=[...e.publications];if(!t.size&&!n.length)return;let r=new Set([...t.values()].flatMap(e=>Object.keys(e.nativeNamespaces))),s=[...e.roots].filter(e=>r.has(e.directory)&&!a.has(e.directory)).map(e=>(a.add(e.directory),retainPluginNativeRoot(e)));for(let[e,n]of t)i.set(e,n);let c=u.encode({receipts:t,roots:s,publications:n.map(([,e])=>e.data)});for(let[t,r]of n)e.publications.get(t)===r&&e.publications.delete(t);return c}function own(e){if(r.has(e))return e;r.add(e),u.retainResource(e),t.add(e);let i=e.dispose.bind(e),a=e.disposeAsync.bind(e);return e.dispose=()=>{i(),u.releaseResource(e),t.delete(e),n.delete(e)},e.disposeAsync=async()=>{await a(),u.releaseResource(e),t.delete(e),n.delete(e)},e}function ownRecovery(e){if(r.has(e))return e;own(e);let t=e.fork.bind(e);return e.fork=markPluginSourceCaptureOperation(()=>ownRecovery(t())),e}let u=new GenerationCodec(()=>{throw Error(`Host functions cannot enter plugin preparation`)},{exportRoot:borrowNativeRoot,importRoot(){throw Error(`Native root leases cannot enter plugin preparation`)}}),d=createPluginCache(),p=e.callbackPort,m=0;function observe(e){e.kind===`native-load`&&recordPluginNativeLoad(e.filename)}function requestHost(t){if(!p)throw Error(`Plugin preparation host is unavailable`);let n=++m,r=new Int32Array(new SharedArrayBuffer(4));p.postMessage({...t,id:n,signal:r},[]);let i=e?.progressSignal;i&&(Atomics.add(i,0,1),Atomics.notify(i,0));let a=performance.now()+15e3;for(;;){let e=yt(p)?.message;if(e?.kind===`callback-result`&&e.id===n){if(e.error)throw Error(e.error);return e}if(e&&observe(e),performance.now()>a)throw Error(`Plugin preparation callback timed out`);Atomics.wait(r,0,0,2)}}function createNativeRoot(){let t=Ei.requestSync({type:`native`,captureId:e.captureId,storage:e.storage});if(!t)throw Error(`Plugin preparation host did not allocate native custody`);let n={directory:t.directory,commit(){},dispose(){},async disposeAsync(){}};return s.set(n,t.id),n}function scoped(t){let n=e;return withPluginCache(d,()=>withPluginSourceAdmissionPublisher(async()=>!1,()=>withPluginInstallRoots(n.installRoots,()=>withPluginSourceCaptureStorage(n.storage,()=>withPluginSourceCaptureDirectory(n.scratch,()=>n.readOnly?We(t):t(),n.managedRoot)))))}async function close(){await settlePluginNativeAdmissions();let e=await Promise.allSettled([...t].map(e=>e.disposeAsync()));await d.sourceAdmissions?.dispose(),f(e,`Plugin preparation resources failed to close`);for(let e of c)await e.releaseAsync();c.clear()}async function execute(e){let r=createPluginGenerationMetrics(),a=performance.now(),s=await withPluginGenerationMetrics(r,()=>scoped(async()=>{for(let t of e.nativeLoads??[])recordPluginNativeLoad(t);let r,a;try{if(e.operation===`capture`){let t=nativeAdmissionStateFor();t.createRoot=createNativeRoot,t.receiptInventoryComplete=!1;for(let n of[`owners`,`managedRoots`,`receipts`,`files`,`namespaces`]){let r=t[n];e.admission[n].forEach((e,t)=>r.set(t,e)),e.admission[n].clear()}for(let[e,n]of t.receipts)i.set(e,n);if(e.inspection){let{inspectPluginGenerationSources:t,inspectPluginSourceDependencies:n}=await import(`./plugin-preparation-plugin-generation-source-inspection-C7Y-qglN.mjs`),i=e.inspection,a=[];r={inspection:i.kind===`sources`?t(i.entries):n(i.entries,i.dependencyRoot===void 0?void 0:{root:i.dependencyRoot,onUnresolvable:(e,t)=>a.push({name:e,importer:t})}),unresolvedAncestors:a}}else if(e.snapshotPublication){let t=capturePluginSourceSnapshot(e.rootDir),n=e.snapshotPublication,i=own({contentDigest:t.sourceDigest,dependencyClosureDigest:pluginSourceSnapshotClosureDigest(t),stage:markPluginSourceCaptureOperation(async e=>own(await stagePluginSourceSnapshot({stateDir:n.stateDir,capture:t,binding:e,assertCurrent:()=>{}}))),dispose:()=>t.dispose(),disposeAsync:()=>t.disposeAsync()});a=i,r=i}else{let n=e.sourceSnapshot?await acquirePluginSourceSnapshot({...e.sourceSnapshot,assertCurrent:()=>{}}):void 0;n&&c.add(n);let i=e.sourceCustodyId===void 0?void 0:Di.get(e.sourceCustodyId)?.forkSourceCustody();if(e.sourceCustodyId!==void 0&&!i)throw Error(`Plugin preparation source custody has closed`);let s;try{if(i?.source.native?.retain(d),i)for(let e of t.roots)borrowNativeRoot(e);s=own(n?capturePluginSnapshotGeneration(n,e.entryFile,e=>e(),void 0):createPluginGenerationArtifact(e.rootDir,e.entryFile,e=>e(),void 0,void 0,void 0,e.bundledReloadSource,i,!0))}catch(e){throw await i?.source.disposeAsync(),e}if(a=s,n?.assertCurrent(),e.sourceCustodyDigest!==void 0&&s.sourceDigest!==e.sourceCustodyDigest)throw Error(`Plugin source custody digest changed during preparation`);e.retainSourceCustody&&(l=s.retainSourceCustody.bind(s));let u=s.captureRecoverySource.bind(s);s.captureRecoverySource=markPluginSourceCaptureOperation(()=>ownRecovery(u()));let f=s.retainSourceCustody.bind(s);if(s.retainSourceCustody=markPluginSourceCaptureOperation(()=>{let e=f();return ownRecovery(e.source),e}),e.retainSourceCustody)r={sourceDigest:s.sourceDigest};else{let e=s.retainSourceCustody();a=e.source,r=e,await s.disposeAsync()}}}else e.asynchronous&&await settlePluginNativeAdmissions(),r=await u.call(e.handle,e.args);return(e.operation!==`call`||e.asynchronous)&&await settlePluginNativeAdmissions(),{value:e.operation===`call`?u.encodeResult(r,e.handle):u.encode(r),admission:admissionChanges(),resources:t.size-n.size,released:u.takeReleasedHandles()}}catch(r){let i=r;if(a)try{await a.disposeAsync()}catch(e){n.add(a),i=AggregateError([r,e],`Plugin capture and cleanup failed`)}return{...preparationFailure(i,e.operation===`capture`||u.isSourcePreparationCall(e.handle)),resources:t.size-n.size,released:u.takeReleasedHandles()}}}));return r.workerMs=performance.now()-a,{...s,metrics:r}}return p?.on(`message`,observe),p?.unref(),{execute,forkSourceCustody(){if(!l)throw Error(`Plugin preparation source custody is unavailable`);return l()},async close(){await scoped(close),p?.close()}}}const Di=/* @__PURE__ */ new Map;async function closeSession(e){let t=Di.get(e);t&&(await t.close(),Di.delete(e))}serveOwnedWorkerTasks(async e=>{let t=e;if(t.operation===`capture`)try{let{root:e}=await Ei.request({type:`source`,captureId:t.captureId,storage:t.storage,prefix:`plugin-preparation-`});if(!e)throw Error(`Plugin capture owner returned no source root`);Di.set(t.captureId,createPreparationSession({...t,scratch:e.directory,managedRoot:e.managedRoot}))}catch(e){if(!ee(e))throw e;return{...preparationFailure(e,!0),resources:0}}let n=Di.get(t.captureId);return n?n.execute(t):{error:{name:`Error`,message:`Plugin preparation capture has closed`},resources:0}},{async closeResource(e){if(e!==void 0){await closeSession(Number(e));return}let t=await Promise.allSettled([...Di.keys()].map(closeSession));f(t,`Plugin preparation resources failed to close`)},retireOnError:!1});export{closePostgresPool as A,releaseWorkerNativeSectionsOnExit as B,readSqliteWorkerAdmissionDecision as C,cn as D,ln as E,registerAgentDatabaseReaderCloser as F,resolveSafeNodeCompileCacheDirectory as I,areWorkerNativeSectionsSettled as L,getDatabaseEngineSelection as M,captureDeletedAgentDatabaseFences as N,un as O,matchesAgentDatabaseReadCandidatePath as P,cancelWorkerNativeSections as R,pn as S,on as T,waitForWorkerNativeSections as V,bindSqliteWorkerDatabaseAdmissionCursor as _,isPrivateDirectoryCreationRefused as a,getSqliteDatabaseAdmissionUpstream as b,resolveOpenClawPackageRoot as c,isLegacyPluginSourceCaptureName as d,tryReadDiskSpace as f,settlesWithin as g,_usingCtx as h,hasSqliteSnapshotCapacityCode as i,Q as j,createGatewayStateProcessOwnerRetiredError as k,resolveOpenClawPackageRootSync as l,createJiti as m,resolvePrivateSqliteSnapshotStagingRoot as n,markPrivateDirectoryCreationRefused as o,sha256HexPrefixCore as p,SqliteSnapshotCapacityError as r,createPluginGenerationArtifact as s,createPrivateSqliteTempDirectorySync as t,visitPluginSourceReferences as u,createSqliteDatabaseAdmissionReplies as v,sn as w,fn as x,exchangeDatabaseAdmissions as y,createWorkerNativeSectionState as z};