openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
32 lines • 50.4 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{c as sha256File}from"./directory-durability-o_aQCRBZ.mjs";import{T as walkDirectory,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{o as compareWorkerBundlePaths,s as hashWorkerBundleManifest}from"./worker-bundle-hash-BjW-uz8I.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as readRuntimeDependencyOwnership}from"./runtime-dependency-ownership-BFbNEbn1.mjs";import{n as MAX_WORKER_BUNDLE_ARCHIVE_BYTES,t as DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS}from"./worker-bundle-limits-CR6eh8-9.mjs";import{r as PACKAGE_LIFECYCLE_PENDING_RELATIVE_PATH,t as LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH}from"./package-lifecycle-marker-CyZ9jU7h.mjs";import{o as PACKAGE_DIST_CONTENT_INVENTORY_RELATIVE_PATH,r as collectPackageDistInventory,s as PACKAGE_DIST_INVENTORY_RELATIVE_PATH}from"./package-dist-inventory-BgxkmdN9.mjs";import{g as ReadEntry,s as Pack,v as Header}from"./esm-Ch36GTgp.mjs";import{t as isRecord$1}from"./record-shared-BiZn2HTQ.mjs";import{n as readWorkerBundleArchiveManifest}from"./worker-bundle-archive-Dsq_4ki1.mjs";import{createRequire}from"node:module";import fs,{constants,createWriteStream}from"node:fs";import path,{isAbsolute,win32}from"node:path";import{createHash}from"node:crypto";import fs$1 from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{once}from"node:events";import{satisfies,valid}from"semver";import{StringDecoder}from"node:string_decoder";import{finished,pipeline}from"node:stream/promises";import{Parser}from"acorn";
//!scripts/lib/package-bundle-dependencies.mts
function listBundleDependencies(e){if(!isRecord$1(e))return[];if(e.bundleDependencies===true||e.bundledDependencies===true)return Object.keys(isRecord$1(e.dependencies)?e.dependencies:{});const t=Array.isArray(e.bundleDependencies)?e.bundleDependencies:e.bundledDependencies;return Array.isArray(t)?t.filter(e=>typeof e===`string`):[]}
//!scripts/lib/package-bundled-mcp.mts
const PATCHED_MCP_NAME=`chrome-devtools-mcp`;const PATCHED_MCP_CLI=`build/src/bin/chrome-devtools-mcp.js`;function mcpFileHashes(e){return/* @__PURE__ */ new Map([[PATCHED_MCP_CLI,e.cli],[`build/src/bin/chrome-devtools-mcp-main.js`,e.main],[`LICENSE`,`58d1e17ffe5109a7ae296caafcadfdbe6a7d176f0bc4ab01e12a689b0499d8bd`],[`build/src/third_party/THIRD_PARTY_NOTICES`,e.notices],[`build/src/TextSnapshot.js`,e.snapshot],[`build/src/McpPage.js`,e.page],[`build/src/third_party/index.js`,e.thirdParty],[`build/src/OPENCLAW_PATCH_NOTICE.md`,e.patchNotice]])}const MCP_FILE_HASHES=/* @__PURE__ */ new Map([[`1.8.0`,mcpFileHashes({cli:`9f380d06e1ac05b257e27e708c0cc4b4ba190e285ed6eb6c8aa50978d98a12c5`,snapshot:`299833ad0e4cfc171a417afaec41df594e4862fe53a7ada6ba160409f979788b`,main:`fc383cb3e5db5f18cf1e8c49221212c669825248874ba91c90ba9035e175f5b4`,notices:`8f10277934fe6888173f41f7cbbd9112d208c8c931bf163db59110f69f119e53`,page:`b9e791d758e4d28589525e2d427600e24b271d365a5879893a392043a11cf426`,thirdParty:`a8f5cb1e02405d347117114141b58572f71c083861fb50ab31a27511e3a279bf`,patchNotice:`8f5a32aaedf4bb6f8ad39f226bd343bf804132c11ebc6c3c19f667669856287c`})],[`1.9.0`,mcpFileHashes({cli:`9f380d06e1ac05b257e27e708c0cc4b4ba190e285ed6eb6c8aa50978d98a12c5`,snapshot:`299833ad0e4cfc171a417afaec41df594e4862fe53a7ada6ba160409f979788b`,main:`5ca0e81196ab6b6e1481629a2dcae7f416b3b38f74555e3138ad5cdbb055e809`,notices:`975febf536bb1c83c031a7888b90bdf1ffe8dc46000e0698eac364491dca8ac4`,page:`6d83dbd4d79c913664fbfa428d138b22fe4246612ab4dfcd93e9d8e62d5d6b51`,thirdParty:`7609bb6c575c7c1152b3f4233ad4b98d97885c62ccff7bd9ee29257ca8ffc83f`,patchNotice:`0e53a04f337a3760f2f1adab9c20e3b4f07019795f503266c0b68e0f46d55a6c`})],[`1.10.1`,mcpFileHashes({cli:`9f380d06e1ac05b257e27e708c0cc4b4ba190e285ed6eb6c8aa50978d98a12c5`,snapshot:`299833ad0e4cfc171a417afaec41df594e4862fe53a7ada6ba160409f979788b`,main:`10603ea8c2ac9f69a42791100701795018ebfaa522a7c93d783ed583cce5cce4`,notices:`6ae0ce181dbc9ba4217b6aad679d7503ed3ab56c45e6f3647e9ab753aa97b67b`,page:`47aa13c6b28cc11e1b0883532edea97cfde7563d78d143035850852d09809975`,thirdParty:`c988e0684584b75e87ae04b768c4f8ae7064401afe5187ec0d4878b2c6833f12`,patchNotice:`4bf44b52a80b5860b2160bc83407a5f0dd09f1801c85d0a2b6e4fec26bd7045d`})],[`1.11.0`,mcpFileHashes({cli:`e8b0290a8fe9a1edc31d595ccc870df926bfaaafe19fb14cd4d8d47bf6194979`,main:`68bffbf26cf0e8840409079456a7681c03e737cd977935c2e0c424c1b8a0700a`,snapshot:`5c647c3d0b416bdfc1bcaf1b1136f6a7682db05cf59982e3ab6f17d00d2d17ac`,notices:`6476ce17667202e92ea191d166050a3ab74f465f2f7a2b6b01dcb4e9477b6a0a`,page:`4044a30df6292a5d4517f718c32818e9c85f8051c318ec88bef7aa127d883a36`,thirdParty:`b047499006b0027bd37165fa8197fa6fa5caa9b8c07d938992857659270ec493`,patchNotice:`41aada055258ec8754581f6cee1e3ed505499be8373969e6267031ebabc00594`})],[`1.12.0`,mcpFileHashes({cli:`e8b0290a8fe9a1edc31d595ccc870df926bfaaafe19fb14cd4d8d47bf6194979`,main:`fc7e2ca9f850a71a015d42f771a4c96f7ee81e21fbcdbd5e1559ccdbac800a96`,snapshot:`21be06826da0dafaadf712b1dc689f6f07c63042a0b6ee30c4afca9a0d616963`,notices:`79e0eeaebdc9a605a3a2a51ecfe8da1e0f68df37416e405ba96dd4376a488e64`,page:`313ce4bfaaea85ab3c57a0bb8f4ad23c093ad33f25407170b2bef6f1654b30b8`,thirdParty:`e1752f75684b672362dc3ae77a399407c509b76471fca08f967fc44fe2cb267b`,patchNotice:`c490fb032360cf26141c4a8d72c6ab4587613051619aa88c346662eaaa6daee5`})]]);const REQUIRED_MCP_FILES=[`build/src/third_party/devtools-formatter-worker.js`,`build/src/third_party/devtools-heap-snapshot-worker.js`,`build/src/third_party/lighthouse-devtools-mcp-bundle.js`,`build/src/third_party/bundled-packages.json`];function collectPatchedMcpArtifactErrors({declaredVersion:e=`1.12.0`,manifest:t,files:n,sha256:r}){const i=typeof e===`string`?MCP_FILE_HASHES.get(e):void 0;if(typeof e!==`string`||!i)return[`package.json dependencies.${PATCHED_MCP_NAME} must be pinned to a supported patched version`];const a=[];if(!isRecord$1(t)||t.version!==e||t.type!==`module`)a.push(`bundled ${PATCHED_MCP_NAME} must be ESM version ${e}`);if(!isRecord$1(t)||!isRecord$1(t.bin)||t.bin[`chrome-devtools-mcp`]!==`./${`build/src/bin/chrome-devtools-mcp.js`}`)a.push(`bundled ${PATCHED_MCP_NAME} must expose CLI ${PATCHED_MCP_CLI}`);for(const e of[...REQUIRED_MCP_FILES,...i.keys()]){if(!n.has(e)){a.push(`bundled ${PATCHED_MCP_NAME} is missing required runtime entry ${e}`);continue}const t=i.get(e);if(t&&r(e)!==t)a.push(`bundled ${PATCHED_MCP_NAME} has unpatched or changed runtime entry ${e}`)}if(![...n].some(e=>e.startsWith(`build/src/third_party/issue-descriptions/`)&&e.endsWith(`.md`)))a.push(`bundled ${PATCHED_MCP_NAME} is missing third-party issue descriptions`);return a}
//!scripts/lib/javascript-statements.mjs
var AppendOnlyScopeNames=class extends Array{firstIndices=/* @__PURE__ */ new Map;push(...e){const t=this.length;const n=super.push(...e);for(let n=0;n<e.length;n+=1){const r=e[n];if(!this.firstIndices.has(r))this.firstIndices.set(r,t+n)}return n}indexOf(e,t=0){return t===0?this.firstIndices.get(e)??-1:super.indexOf(e,t)}};const ArtifactParser=Parser.extend(e=>class extends e{enterScope(e){super.enterScope(e);const t=this.currentScope();t.lexical=new AppendOnlyScopeNames;t.var=new AppendOnlyScopeNames;t.functions=new AppendOnlyScopeNames}});function visitJavaScriptStatements(e,t,n){const r={type:`Program`,start:0,end:0,sourceType:t.sourceType,body:[]};const visitCompletedStatements=()=>{if(r.body.length>0)n(r.body.splice(0))};ArtifactParser.parse(e,{ecmaVersion:`latest`,...t,program:r,onToken:visitCompletedStatements});visitCompletedStatements()}
//!scripts/lib/package-dist-imports.mjs
const JS_FILE_RE=/\.(?:cjs|js|mjs)$/u;const TS_FILE_RE=/\.(?:cts|ts|mts)$/u;const CONTROL_UI_ROOT=`dist/control-ui/`;const require$1=createRequire(import.meta.url);function preparePackageDistJavaScript(e,t){return TS_FILE_RE.test(e)?require$1(`esbuild`).transformSync(t,{loader:`ts`,target:`esnext`,sourcefile:e,tsconfigRaw:{compilerOptions:{verbatimModuleSyntax:true}}}).code:t}function normalizePackagePath(e){return e.replace(/\\/gu,`/`).replace(/^package\//u,``)}function stripSpecifierSuffix(e){return e.replace(/[?#].*$/u,``)}function hasRuntimeFileExtension(e,t){const n=path.posix.basename(stripSpecifierSuffix(e));return/\.(?:cjs|js|mjs|exe)$/u.test(n)||t&&TS_FILE_RE.test(n)}function literal(e){if(e?.type===`Literal`&&typeof e.value===`string`)return e.value;return e?.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0].value.cooked:void 0}function packageJsonsFor(e,t){return e.packageJsons??new Map(t.filter(t=>e.readText&&path.posix.basename(t)===`package.json`).map(t=>[t,e.readText(t)]))}function sourceTypeFor(e,t){if(/\.(?:cjs|cts)$/u.test(e))return`script`;if(/\.(?:mjs|mts)$/u.test(e))return`module`;let n=path.posix.dirname(e);while(true){const e=t.get(path.posix.join(n,`package.json`));if(e!==void 0){const t=JSON.parse(e).type;return t===`module`?`module`:t===`commonjs`?`script`:void 0}if(n===`.`||n===`/`)return;n=path.posix.dirname(n)}}function resolvePackageDistCommonJs(e,t,n){const r=[``,`.js`,`.json`,`.node`];const loadFile=e=>r.map(t=>e+t).find(e=>t.has(e));const loadIndex=e=>r.slice(1).map(t=>path.posix.join(e,`index`+t)).find(e=>t.has(e));const i=!e.endsWith(`/`)&&loadFile(e);if(i)return i;const a=n.get(path.posix.join(e,`package.json`));const o=a===void 0?void 0:JSON.parse(a).main;if(typeof o===`string`&&o){const t=path.posix.join(e,o);const n=loadFile(t)??loadIndex(t);if(n)return n}return loadIndex(e)}function appendImportEdges(e,t,n,r,i,a,o,s,c){const l=s?[]:void 0;function visit(e){if(e.type===`Identifier`||e.type===`Literal`||e.type===`TemplateElement`)return;if(o&&e.type===`CallExpression`){const t=literal(e.arguments[0]);if(t?.startsWith(`.`))o(t)}let r;let s;let u;if(e.type===`ImportDeclaration`||e.type===`ExportNamedDeclaration`||e.type===`ExportAllDeclaration`||e.type===`ImportExpression`){s=literal(e.source);if(e.source)u=e.type===`ImportExpression`?`dynamic-import`:e.type===`ImportDeclaration`?`static-import`:`static-export`;if(e.source?.type===`Literal`&&typeof e.source.value===`string`)a?.(e.source.value)}else if(e.type===`CallExpression`&&e.callee.type===`Identifier`&&e.callee.name===`require`){r=`require`;u=`require`;s=literal(e.arguments[0])}else if(e.type===`NewExpression`&&e.callee.type===`Identifier`&&e.callee.name===`URL`&&e.arguments.length>=2){const t=e.arguments[1];if(t.type===`MemberExpression`&&!t.computed&&t.property.type===`Identifier`&&t.property.name===`url`&&t.object.type===`MetaProperty`&&t.object.meta.name===`import`&&t.object.property.name===`meta`){r=`import-meta-url`;u=`import-meta-url`;s=literal(e.arguments[0])}}let d;if(s?.startsWith(`.`)&&(r!==`import-meta-url`||hasRuntimeFileExtension(s,i))){let e=path.posix.normalize(path.posix.join(path.posix.dirname(t),r===`require`?s:stripSpecifierSuffix(s)));if(r===void 0&&t.startsWith(CONTROL_UI_ROOT))e=c.get(e)??e;if(!(r===`import-meta-url`&&t===`dist/managed-handoff-runtime.mjs`&&e===`dist/node_modules/@openclaw/proc-safe/dist/identity.js`)&&(r!==`import-meta-url`||e.startsWith(`dist/`))){n.push({importerPath:t,importedPath:e,...r===`require`?{kind:r}:{}});d=e}}if(u&&l)l.push({importerPath:t,kind:u,start:e.start,end:e.end,...s===void 0?{}:{specifier:s},...d===void 0?{}:{importedPath:d}});for(const t in e){const n=e[t];if(!n||typeof n!==`object`)continue;if(Array.isArray(n)){for(const e of n)if(e&&typeof e.type===`string`)visit(e)}else if(typeof n.type===`string`)visit(n)}}const scan=t=>visitJavaScriptStatements(e,{sourceType:t,allowReturnOutsideFunction:true},e=>{for(const t of e)visit(t)});if(r)scan(r);else{const e=n.length;try{scan(`script`)}catch(t){if(!(t instanceof SyntaxError))throw t;n.length=e;if(l)l.length=0;scan(`module`)}}for(const e of l??[])s(e)}function collectPackageDistImportErrors(e){const t=[...new Set(e.files.map(normalizePackagePath))];const n=new Set(t);const r=[];const i=packageJsonsFor(e,t);const a=e.imports??collectPackageDistImports({files:t,readText:e.readText,packageJsons:i});for(const{importerPath:e,importedPath:t,kind:o}of a)if(!(o===`require`?resolvePackageDistCommonJs(t,n,i)!==void 0:n.has(t)))r.push(`${e} imports missing ${t}`);return r}function collectPackageDistImports(e){const t=e.files.length===1?[normalizePackagePath(e.files[0])]:[...new Set(e.files.map(normalizePackagePath))].toSorted((e,t)=>e.localeCompare(t));const n=[];const r=packageJsonsFor(e,t);const i=/* @__PURE__ */ new Map;const a=`${CONTROL_UI_ROOT}index.html`;if(t.includes(a)){const t=/<script\b[^>]*\btype="importmap"[^>]*>([\s\S]*?)<\/script>/iu.exec(e.readText(a));for(const[e,r]of Object.entries(JSON.parse(t?.[1]??`{}`).imports??{})){if(!e.startsWith(`./`)||typeof r!==`string`||!r.startsWith(`./`))throw new Error(`Unsupported Control UI package import-map entry`);const t=path.posix.join(CONTROL_UI_ROOT,r);i.set(path.posix.join(CONTROL_UI_ROOT,e),t);n.push({importerPath:a,importedPath:t})}}for(const a of t){if(!JS_FILE_RE.test(a)&&!(e.includeTypeScript&&TS_FILE_RE.test(a))||/(?:^|\/)node_modules\//u.test(a))continue;appendImportEdges(preparePackageDistJavaScript(a,e.readText(a)),a,n,sourceTypeFor(a,r),e.includeTypeScript,e.onStaticImport,e.onLiteralCall,e.onImportOccurrence,i)}return n}
//!scripts/lib/package-installed-dependencies.mts
function validateBundledPackageName(e){if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/u.test(e))throw new Error(`Invalid bundled dependency name: ${e}`)}async function installedPackagePath(e,t){validateBundledPackageName(t);const n=createRequire(path.join(e,`package.json`)).resolve.paths(`${t}/`)??[];for(const e of n){const n=path.join(e,t);try{await fs$1.access(path.join(n,`package.json`));return n}catch(e){if(!isRecord$1(e)||e.code!==`ENOENT`)throw e}}}async function installedPackageDependencies(e,t){const n=isRecord$1(t.dependencies)?t.dependencies:{};const r=isRecord$1(t.optionalDependencies)?t.optionalDependencies:{};const i=isRecord$1(t.peerDependencies)?t.peerDependencies:{};const a=isRecord$1(t.peerDependenciesMeta)?t.peerDependenciesMeta:{};const o=[];for(const t of Object.keys({...i,...n,...r})){const i=await installedPackagePath(e,t);const s=a[t];const c=Object.hasOwn(r,t)||!Object.hasOwn(n,t)&&isRecord$1(s)&&s.optional===true;if(!i){if(c)continue;throw new Error(`Linked bundle requires dependency-closure staging: ${e} is missing ${t}`)}o.push({name:t,path:i,root:await fs$1.realpath(i)})}return o}function hasInstalledPackageAncestor(e,t,n){const r=createRequire(path.join(e,`package.json`)).resolve.paths(`${t.name}/`)??[];for(const e of r){const r=n.get(path.join(e,t.name));if(r!==void 0)return r===t.root}return false}
//!scripts/package-source-dependencies.mjs
const PRIVATE_WORKSPACE_VERSION=`0.0.0-private`;function dependenciesRecord(e,t){if(e===void 0)return{};if(typeof e!==`object`||e===null||Array.isArray(e))throw new Error(`${t} dependencies must be an object when present`);return e}function validateBundledPackageDependencyAlignment({bundledDependencies:e,bundledPackageLabel:t,rootDependencies:n,rootPackageLabel:r=`root package.json`}){const i=dependenciesRecord(e,t);const a=dependenciesRecord(n,r);const o=[];for(const[e,n]of Object.entries(i)){if(typeof n!==`string`)throw new Error(`${t} dependency ${e} must declare a string version`);if(n===PRIVATE_WORKSPACE_VERSION)continue;const i=a[e];if(i!==void 0&&typeof i!==`string`)throw new Error(`${r} dependency ${e} must declare a string version`);if(i!==n&&i!==`workspace:${n}`)throw new Error(`${r} must declare ${e}@${n} to bundle ${t} without duplicate dependencies`);o.push([e,n])}return o}
//!src/infra/package-plugin-composition.ts
function composePackagePlugins(e,t){const n=structuredClone(e);const r=/* @__PURE__ */ new Set;for(const{id:e,packageJson:i}of t){for(const e of listBundleDependencies(i))r.add(e);for(const t of[`dependencies`,`optionalDependencies`]){const r=i[t]??{};for(const[t,n]of Object.entries(r))if(valid(n)!==n)throw new Error(`Selected plugin ${e} requires an exact dependency pin: ${t}@${n}`);for(const t of[n.dependencies,n.optionalDependencies])validateBundledPackageDependencyAlignment({bundledDependencies:r,bundledPackageLabel:`selected plugin ${e}`,rootDependencies:{...r,...t}});n[t]={...n[t],...r}}}for(const e of listBundleDependencies(n))r.add(e);if(r.size>0){n.bundleDependencies=[...r].toSorted();delete n.bundledDependencies}for(const e of Object.keys(n.dependencies??{}))delete n.optionalDependencies?.[e];for(const{id:e,packageJson:r}of t)for(const[t,i]of Object.entries(r.peerDependencies??{})){const a=t===n.name?n.version:n.dependencies?.[t]??n.optionalDependencies?.[t];if(!a&&!r.peerDependenciesMeta?.[t]?.optional||a&&!satisfies(a,i))throw new Error(`Selected plugin ${e} requires peer ${t}@${i} in the distribution`)}const i=new Set(t.map(({id:e})=>`!dist/extensions/${e}/**`));if(n.files)n.files=n.files.filter(e=>!i.has(e));return n}
//!src/gateway/worker-environments/node-bootstrap-package.ts
const IGNORED_PLUGIN_DIRECTORIES=/* @__PURE__ */ new Set([`node_modules`,`src`,`test`,`tests`]);const PLUGIN_DIST_SHARED_CHUNK_PREFIX=`dist/.setup`;const METADATA_KEYS=[`name`,`version`,`dependencies`,`optionalDependencies`,`peerDependencies`,`peerDependenciesMeta`];function bootstrapPath(e){if(!e||e.includes(`\\`)||e.includes(`\0`)||/[\r\n]/u.test(e)||e.startsWith(`/`)||e.split(`/`).some(e=>!e||e===`.`||e===`..`))throw new Error(`Unsafe node distribution path: ${e}`);return e}async function readPackageManifest(e){const t=JSON.parse(await fs$1.readFile(path.join(e,`package.json`),`utf8`));if(!t.name||valid(t.version)!==t.version)throw new Error(`Node distribution requires a named package with an exact version`);return t}async function collectBootstrapFiles(e,t=false){const included=({name:e,relativePath:n})=>t&&n.split(path.sep).join(`/`)===PLUGIN_DIST_SHARED_CHUNK_PREFIX||!e.startsWith(`.`)&&!(t?IGNORED_PLUGIN_DIRECTORIES.has(e):n===`node_modules`);const{entries:n,failedDirs:r,truncated:i}=await walkDirectory(e,{maxEntries:DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxEntries,symlinks:`include`,include:included,descend:e=>{if(e.depth>=64)throw new Error(`Node bootstrap ${t?`plugin`:`dependency`} exceeds its directory depth limit`);return included(e)}});if(r.length>0)throw r[0].error;if(i)throw new Error(`Node bootstrap distribution exceeds its artifact limits`);return n.flatMap(e=>{if(e.kind===`directory`||(t?!/\.(?:[cm]?js|json|wasm)$/u.test(e.name):e.relativePath===`package.json`))return[];if(e.kind!==`file`)throw new Error(`Unsafe bundled node distribution path: ${e.relativePath}`);return[e.relativePath.split(path.sep).join(`/`)]})}async function resolvePlugins(e,t){const n=/* @__PURE__ */ new Set;return await Promise.all(e.plugins.map(async({id:e,root:r})=>{if(!/^[a-z0-9][a-z0-9_-]*$/u.test(e)||n.has(e))throw new Error(`Invalid or duplicate node bootstrap plugin: ${e}`);n.add(e);const i=await fs$1.realpath(r);const a=path.join(t,`extensions`,e);const o=path.join(t,`dist`,`extensions`,e);const s=i===a?o:i;const c=await readPackageManifest(s);const l=s===o?await readPackageManifest(a).catch(e=>{if(i===o&&hasErrnoCode(e,`ENOENT`))return;throw e}):void 0;if(l&&METADATA_KEYS.some(e=>!isDeepStrictEqual(c[e],l[e])))throw new Error(`Built plugin ${e} does not match source metadata; rebuild and restart the Gateway`);if(JSON.parse(await fs$1.readFile(path.join(s,`openclaw.plugin.json`),`utf8`)).id!==e)throw new Error(`Node bootstrap plugin identity does not match ${e}`);const u=c.openclaw?.runtimeExtensions??c.openclaw?.extensions;if(!u?.length)throw new Error(`Node bootstrap plugin ${e} has no runtime entry`);for(const e of u){const t=bootstrapPath(e.replace(/^\.\//u,``).replace(/\.ts$/u,`.js`));await fs$1.access(path.join(s,t))}return{id:e,root:s,installationRoot:l?a:i,packageJson:c,bundled:s===o}}))}function requireRunningBuild(e,t,n){const r=JSON.parse(t);if(!e.runningBuildId||r.buildId!==e.runningBuildId||r.version!==n)throw new Error(`Cloud bootstrap requires the running Gateway build; run pnpm build and restart the Gateway before provisioning`);return e.runningBuildId}
//!src/gateway/worker-environments/node-bootstrap-dependencies.ts
async function collectNodeBootstrapDependencies(e,t,n,r=/* @__PURE__ */ new Map){const i=[];const a=/* @__PURE__ */ new Map;const visit=async(e,o,s,c)=>{const l={...o.peerDependencies,...o.dependencies,...o.optionalDependencies};const u=[];const d=/* @__PURE__ */ new Map;for(const[f,p]of Object.entries(l).toSorted(([e],[t])=>e.localeCompare(t))){if(f===t.name)continue;const l=f in(o.optionalDependencies??{})||!Object.hasOwn(o.dependencies??{},f)&&o.peerDependenciesMeta?.[f]?.optional===true;const m=!s?r.get(f)??e:e;let h=await installedPackagePath(m,f);if(!h){if(l)continue;throw new Error(`Node runtime dependency is not installed: ${o.name} requires ${f}`)}h=await fs$1.realpath(h);const g=await readPackageManifest(h);const _=p.startsWith(`npm:`)?p.slice(4,p.lastIndexOf(`@`)):f;if(!s&&g.name!==_||!s&&valid(p)===p&&g.version!==p)throw new Error(`Node runtime dependency identity mismatch: ${f}@${p}`);const supports=(e,t)=>!e||!e.includes(`!${t}`)&&(!e.some(e=>!e.startsWith(`!`))||e.includes(t));if(!supports(g.os,n.platform)||!supports(g.cpu,n.arch)){if(l)continue;throw new Error(`Node runtime dependency ${f} does not support ${n.platform}/${n.arch}`)}if(c.find(e=>e.has(f))?.get(f)===h)continue;const v=!a.has(f);const y=`${v?``:s}node_modules/${f}/`;if(y.split(`/`).length>64)throw new Error(`Node runtime dependency nesting exceeds the archive depth limit`);if(v)a.set(f,h);else d.set(f,h);const b={requestedName:f,root:h,prefix:y,manifest:g};i.push(b);u.push({...b,ancestors:v?[a]:[d,...c]})}for(const e of u)await visit(e.root,e.manifest,e.prefix,e.ancestors)};await visit(e,t,``,[]);return i}async function collectNodeBootstrapDependencyTargets(e,t){const n=[{platform:process.platform,arch:process.arch,root:e,prefix:``}];const r=path.join(e,`node-runtime-dependencies`);for(const i of await fs$1.readdir(r,{withFileTypes:true}).then(e=>e.toSorted((e,t)=>e.name.localeCompare(t.name))).catch(e=>{if(hasErrnoCode(e,`ENOENT`))return[];throw e})){if(!i.isDirectory()||!/^(linux|darwin|win32)-(x64|arm64)$/u.test(i.name))throw new Error(`Invalid node runtime dependency target input`);const a=i.name.indexOf(`-`);const o=i.name.slice(0,a);const s=i.name.slice(a+1);if(o===process.platform&&s===process.arch)continue;const c=await fs$1.realpath(path.join(r,i.name));if(c!==path.join(r,i.name))throw new Error(`Node runtime target input path is unsafe`);const l=await readPackageManifest(c);const u=JSON.parse(await fs$1.readFile(path.join(c,`runtime-input.json`),`utf8`));if(!isRecord(u)||u.platform!==o||u.arch!==s||u.packageJsonSha256!==(await sha256File(path.join(e,`package.json`))).digest||u.lockfileSha256!==(await sha256File(path.join(e,`pnpm-lock.yaml`))).digest||l.name!==t.name||l.version!==t.version||!isDeepStrictEqual(l.dependencies,t.dependencies)||!isDeepStrictEqual(l.optionalDependencies,t.optionalDependencies))throw new Error(`Node runtime target ${i.name} does not match the running source/dependencies`);n.push({platform:o,arch:s,root:c,prefix:`runtime-dependencies/${i.name}/`})}return n}
//!src/gateway/worker-environments/node-bootstrap-prebuilt.ts
const NODE_BOOTSTRAP_PREBUILT_ARCHIVE=`node-runtime.tgz`;async function copyNodeBootstrapPrebuiltArchive(e,t){if(process.platform===`win32`)return;const n=path.join(t,NODE_BOOTSTRAP_PREBUILT_ARCHIVE);const r=await root(e,{symlinks:`reject`,hardlinks:`allow`});const i=await root(t);try{await i.copyIn(NODE_BOOTSTRAP_PREBUILT_ARCHIVE,{root:r,relativePath:NODE_BOOTSTRAP_PREBUILT_ARCHIVE},{maxBytes:MAX_WORKER_BUNDLE_ARCHIVE_BYTES,overwrite:false,durable:false,mode:384});return await readWorkerBundleArchiveManifest(n,DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS)}catch{await fs$1.rm(n,{force:true});return}}
//!scripts/lib/root-package-bundled-plugin-excludes.mjs
function collectRootPackageExcludedExtensionDirs(e={}){const t=/* @__PURE__ */ new Set;let n=e.files;if(!n){const r=path.join(e.cwd??process.cwd(),`package.json`);if(!fs.existsSync(r))return t;n=JSON.parse(fs.readFileSync(r,`utf8`)).files??[]}for(const e of n){if(typeof e!==`string`)continue;const n=/^!dist\/extensions\/([^/]+)\/\*\*$/u.exec(e);if(n?.[1]&&n[1]!==`node_modules`)t.add(n[1])}return t}
//!src/infra/package-root-imports.ts
const require=createRequire(import.meta.url);const namespaces=/* @__PURE__ */ new Map([[`node:module`,`module`],[`module`,`module`],[`node:process`,`process`],[`process`,`process`],[`node:path`,`path`],[`path`,`path`],[`node:fs`,`fs`],[`fs`,`fs`],[`node:fs/promises`,`fs-promises`],[`fs/promises`,`fs-promises`]]);const members=/* @__PURE__ */ new Map([[`module`,/* @__PURE__ */ new Map([[`createRequire`,`factory`]])],[`process`,/* @__PURE__ */ new Map([[`getBuiltinModule`,`builtin`],[`cwd`,`cwd`],[`chdir`,`chdir`]])],[`path`,/* @__PURE__ */ new Map([[`join`,`join`],[`resolve`,`resolve`]])],[`fs`,/* @__PURE__ */ new Map([[`realpathSync`,`realpath`],[`promises`,`fs-promises`]])],[`fs-promises`,/* @__PURE__ */ new Map([[`realpath`,`realpath-async`]])]]);const ambient=/* @__PURE__ */ new Map([[`require`,`root`],[`__filename`,`location`],[`process`,`process`]]);const loaders=/* @__PURE__ */ new Set([`root`,`caller`,`unlocated`]);const snapshotsKinds=/* @__PURE__ */ new Set([`caller-path`,`caller-string`,`caller`,`root`]);const callerValues=/* @__PURE__ */ new Set([`input`,`caller-path`,`caller-string`]);const pathValues=/* @__PURE__ */ new Set([...callerValues,`literal`,`relative`]);const readableValues=/* @__PURE__ */ new Set([...pathValues,`module`,`process`,`path`,`fs`,`fs-promises`,`scalar`]);const pureCalls=/* @__PURE__ */ new Set([`factory`,`builtin`,`join`,`resolve`,`realpath`,`realpath-async`,`cwd`]);function union(...e){const t=[...new Set(e.flat())];return t.length?t:[`unknown`]}function collectPackageRootImports(e,t){const{parse:n}=require("@babel/parser");const{default:r}=require("@babel/traverse");const i=n(e,{sourceType:`unambiguous`,allowUndeclaredExports:true,allowReturnOutsideFunction:true,createImportExpressions:true});const a=[];const recordImport=(e,n,r=`runtime`)=>{a.push(e);if(t){if(n.start==null)throw new Error(`Parsed package import is missing its source position`);t(e,n.start,r)}};const o=/* @__PURE__ */ new Map;const s=[];const c=[i.program];const l=/* @__PURE__ */ new Map;const u=[];const d=[];const f=/* @__PURE__ */ new Map;let p=false;function symbolAt(e){return o.get(e)?.scope.getBinding(e.name)}function literal(e){return e?.type===`StringLiteral`?e.value:void 0}function property(e){return e.type===`Identifier`?e.name:literal(e)}function memberName(e){return e.computed?literal(e.property):property(e.property)}function register(e,t,n){for(const r of Object.values(e.getBindingIdentifiers())){const i=e.scope.getBinding(r.name);if(i){const a=l.get(i)??[];a.push({node:e.node,name:r,constant:t,inputScope:n});l.set(i,a)}}}function recordWrite(e,t){switch(e.type){case`Identifier`:u.push([e,t]);break;case`AssignmentPattern`:recordWrite(e.left);break;case`ObjectPattern`:for(const t of e.properties)recordWrite(t.type===`ObjectProperty`?t.value:t.argument);break;case`ArrayPattern`:for(const t of e.elements)if(t)recordWrite(t);break;case`RestElement`:recordWrite(e.argument)}}r(i,{enter(e){o.set(e.node,e)},ImportDeclaration(e){recordImport(e.node.source.value,e.node,`static`);for(const t of e.get(`specifiers`))register(t,true)},ExportNamedDeclaration(e){if(e.node.source)recordImport(e.node.source.value,e.node,`static`)},ExportAllDeclaration(e){recordImport(e.node.source.value,e.node,`static`)},ImportExpression(e){const t=literal(e.node.source);if(t!==void 0)recordImport(t,e.node)},"CallExpression|OptionalCallExpression"(e){if(e.isCallExpression()||e.isOptionalCallExpression())s.push(e.node)},Function(e){c.push(e.node);for(const t of e.get(`params`))register(t,false,e.node)},VariableDeclarator(e){register(e,e.parentPath.isVariableDeclaration({kind:`const`}))},AssignmentExpression(e){recordWrite(e.node.left,e.node.right)},"ForOfStatement|ForInStatement"(e){if(e.isForOfStatement()||e.isForInStatement()){if(e.node.left.type!==`VariableDeclaration`)recordWrite(e.node.left)}},"MemberExpression|OptionalMemberExpression"(e){if(e.isMemberExpression()||e.isOptionalMemberExpression()){if(memberName(e.node)===`chdir`)d.push(e.node)}}});const m=/* @__PURE__ */ new Map;for(const[e,t]of u){const n=symbolAt(e);if(n)m.set(n,[...m.get(n)??[],t])}function memberOrigins(e,t){return union(e.map(e=>e===`input`?`input`:t===void 0?`unknown`:members.get(e)?.get(t)??`unknown`))}function origins(e,t=/* @__PURE__ */ new Set,n,r=false){if(e.type===`AwaitExpression`)return origins(e.argument,t,n,true);if(e.type===`StringLiteral`||e.type===`TemplateLiteral`&&e.expressions.length===0){const t=e.type===`StringLiteral`?e.value:e.quasis[0]?.value.cooked??``;return[isAbsolute(t)||win32.isAbsolute(t)||URL.canParse(t)?`literal`:`relative`]}if([`NumericLiteral`,`BooleanLiteral`,`NullLiteral`].includes(e.type))return[`literal`];if(e.type===`ConditionalExpression`)return union(origins(e.consequent,new Set(t),n),origins(e.alternate,new Set(t),n));if(e.type===`SequenceExpression`){const r=e.expressions.at(-1);return r?origins(r,t,n):[`unknown`]}if(e.type===`BinaryExpression`||e.type===`LogicalExpression`||e.type===`AssignmentExpression`){if(e.operator===`=`)return origins(e.right,t,n);const r=union(origins(e.left,new Set(t),n),origins(e.right,new Set(t),n));if([`||`,`&&`,`??`,`||=`,`&&=`,`??=`].includes(e.operator))return r;if(e.operator===`+`&&r.some(e=>callerValues.has(e))&&r.every(e=>pathValues.has(e)))return[`caller-string`];return[`scalar`]}if(e.type===`Identifier`){const r=symbolAt(e);if(!r)return[ambient.get(e.name)??`unknown`];const i=f.get(r);if(i)return i;if(t.has(r))return[`unknown`];t.add(r);const a=l.get(r)??[];const o=n&&a.some(e=>e.inputScope===n);return union(...a.map(e=>declarationOrigins(e,new Set(t),n)),...(o?[]:m.get(r)??[]).map(e=>e?origins(e,new Set(t),n):[`unknown`]))}if(e.type===`MemberExpression`||e.type===`OptionalMemberExpression`){const r=memberName(e);if(r===`url`&&e.object.type===`MetaProperty`&&e.object.meta.name===`import`&&e.object.property.name===`meta`)return[`location`];return memberOrigins(origins(e.object,t,n),r)}if(e.type===`ImportExpression`)return[namespaces.get(literal(e.source)??``)??`unknown`];if(e.type===`CallExpression`||e.type===`OptionalCallExpression`){const i=literal(e.arguments[0]);const a=i===void 0?void 0:namespaces.get(i);const o=origins(e.callee,new Set(t),n);const s=o.some(e=>[`factory`,`resolve`,`realpath`,`realpath-async`,`join`].includes(e))?e.arguments.map(e=>origins(e,new Set(t),n)):[];return union(...o.map(t=>{if(t===`factory`)return(s[0]??[`unknown`]).map(e=>e===`location`?`root`:callerValues.has(e)?`caller`:`unlocated`);if(loaders.has(t)||t===`builtin`)return[a??`unknown`];if(t===`cwd`)return[n&&!p?`caller-path`:`scalar`];if(t===`realpath-async`&&!r)return[`unknown`];if(t===`resolve`||(t===`realpath`||t===`realpath-async`)&&e.arguments.length===1){const e=t===`resolve`?s.flat():s[0]??[`unknown`];return[!p&&e.every(e=>[`input`,`caller-path`,`caller-string`,`relative`].includes(e))&&(n||e.includes(`caller-path`))&&(n||!e.includes(`caller-string`))?`caller-path`:`scalar`]}if(t===`join`){const e=s.flat();if(e.every(e=>pathValues.has(e))&&e.some(e=>callerValues.has(e)))return[s[0]?.every(e=>e===`caller-path`)?`caller-path`:`caller-string`];return[`scalar`]}return[`unknown`]}))}return[`unknown`]}function declarationOrigins(e,t,n){const{node:r,name:i}=e;if(r.type===`ImportSpecifier`||r.type===`ImportNamespaceSpecifier`||r.type===`ImportDefaultSpecifier`){const e=o.get(r)?.parent;const t=e?.type===`ImportDeclaration`?namespaces.get(e.source.value):void 0;return t?r.type===`ImportSpecifier`?memberOrigins([t],property(r.imported)):[t]:[`unknown`]}if(r.type!==`VariableDeclarator`&&!e.inputScope)return[`unknown`];const a=r.type===`VariableDeclarator`?r.id:r;const s=r.type===`VariableDeclarator`?r.init:r.type===`AssignmentPattern`?r.right:void 0;const c=e.inputScope?union([n===e.inputScope?`input`:`unknown`],s?a.type===`AssignmentPattern`&&a.left.type!==`Identifier`?[`unknown`]:origins(s,new Set(t),n):[]):s?origins(s,new Set(t),n):[`unknown`];if(a===i||a.type===`AssignmentPattern`&&a.left===i)return union(c,!e.inputScope&&!e.constant?[`unknown`]:[]);const l=[];let u=i;let d=o.get(u)?.parent;let f;while(d&&u!==a){if(d.type===`AssignmentPattern`)l.push(d.left===i?origins(d.right,new Set(t),n):[`unknown`]);if(d.type===`ObjectProperty`&&o.get(d)?.parent===a&&(d.value===i||d.value.type===`AssignmentPattern`&&d.value.left===i))f=d.computed?literal(d.key):property(d.key);u=d;d=o.get(u)?.parent}return union(e.inputScope?c:f===void 0?[`unknown`]:memberOrigins(c,f),...l,!e.inputScope&&!e.constant?[`unknown`]:[])}function pure(e,t){if(e.type===`Identifier`)return Boolean(symbolAt(e))||ambient.has(e.name)||e.name===`undefined`;if([`StringLiteral`,`NumericLiteral`,`BooleanLiteral`,`NullLiteral`].includes(e.type)||e.type===`TemplateLiteral`&&e.expressions.length===0)return true;if(e.type===`LogicalExpression`)return pure(e.left,t)&&pure(e.right,t);if(e.type===`ConditionalExpression`)return pure(e.test,t)&&pure(e.consequent,t)&&pure(e.alternate,t);if(e.type===`AwaitExpression`){const n=e.argument;if(n.type===`ImportExpression`)return namespaces.has(literal(n.source)??``)&&pure(n,t);if(n.type!==`CallExpression`&&n.type!==`OptionalCallExpression`)return false;return origins(n.callee,/* @__PURE__ */ new Set,t).every(e=>e===`realpath-async`)&&pure(n,t)}if(e.type===`MemberExpression`||e.type===`OptionalMemberExpression`){if(origins(e,/* @__PURE__ */ new Set,t).includes(`location`))return true;return origins(e.object,/* @__PURE__ */ new Set,t).every(e=>readableValues.has(e))&&pure(e.object,t)&&(!e.computed||literal(e.property)!==void 0)}if(e.type===`ImportExpression`)return!e.options&&namespaces.has(literal(e.source)??``);if(e.type!==`CallExpression`&&e.type!==`OptionalCallExpression`)return false;const n=namespaces.has(literal(e.arguments[0])??``)&&e.arguments.length===1;return origins(e.callee,/* @__PURE__ */ new Set,t).every(t=>pureCalls.has(t)&&(t===`join`||t===`resolve`||e.arguments.length===(t===`cwd`?0:1))||loaders.has(t)&&n)&&pure(e.callee,t)&&e.arguments.every(e=>pure(e,t))}p=d.some(e=>origins(e).includes(`chdir`))||[...l.values()].some(e=>e.some(e=>declarationOrigins(e,/* @__PURE__ */ new Set).includes(`chdir`)));for(const e of c.toSorted((e,t)=>(e.start??0)-(t.start??0))){const t=e.type===`Program`?e:e.body;if(t.type!==`Program`&&t.type!==`BlockStatement`)continue;if(e.type!==`Program`&&e.params.some(e=>e.type!==`Identifier`))continue;prefix:for(const n of t.body){const t=n.type===`ExportNamedDeclaration`||n.type===`ExportDefaultDeclaration`?n.declaration:n;if(!t||t.type===`ImportDeclaration`||t.type===`ExportAllDeclaration`||t.type===`FunctionDeclaration`||t.type===`EmptyStatement`||t.type===`ExpressionStatement`&&t.expression.type===`StringLiteral`)continue;if(t.type!==`VariableDeclaration`||t.kind!==`const`)break;for(const n of t.declarations){if(n.id.type!==`Identifier`||!n.init||!pure(n.init,e))break prefix;const t=origins(n.init,/* @__PURE__ */ new Set,e);if(!t.every(e=>snapshotsKinds.has(e)||[`literal`,`relative`,...namespaces.values(),...pureCalls].includes(e)))break prefix;const r=symbolAt(n.id);if(r&&t.every(e=>snapshotsKinds.has(e)))f.set(r,t)}}}for(const e of s){const t=literal(e.arguments[0]);if(e.arguments.length!==1||t===void 0)continue;const n=origins(e.callee);if(n.includes(`root`)||e.callee.type===`Identifier`&&e.callee.name===`require`&&!n.every(e=>e===`caller`))recordImport(t,e)}return a}
//!src/shared/non-packaged-plugin-dirs.ts
const NON_PACKAGED_BUNDLED_PLUGIN_DIRS=/* @__PURE__ */ new Set([`qa-channel`,`qa-lab`]);
//!src/gateway/worker-environments/node-bootstrap-runtime-chunks.ts
async function resolveNodeBootstrapRuntimeChunks(e,t,n,r){const i=readRuntimeDependencyOwnership(e);const a=r??/* @__PURE__ */ new Set([...NON_PACKAGED_BUNDLED_PLUGIN_DIRS,...collectRootPackageExcludedExtensionDirs({files:n})]);const o=new Map(t.flatMap(e=>{if(!e.startsWith(`dist/`)||!/\.[cm]?js$/u.test(e)||e.startsWith(`dist/extensions/`))return[];const t=i?.chunks[e.slice(5)];return t?.extensions.every(e=>a.has(e))?[[e,t]]:[]}));const s=/* @__PURE__ */ new Map;if(o.size===0)return{files:t,sourceFacts:s};const c=await root(e,{hardlinks:`allow`,symlinks:`reject`});const l=new Set(t);const u=new Set(n);const read=async e=>{const{buffer:t}=await c.read(e,{hardlinks:`allow`,symlinks:`reject`,maxBytes:DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxExpandedBytes});const n=o.get(e);if(n&&createHash(`sha256`).update(t).digest(`hex`)!==n.sha256)throw new Error(`Runtime dependency ownership does not match ${e}; rebuild the Gateway`);return t};const d=/* @__PURE__ */ new Map;for(const e of t)if(path.posix.basename(e)===`package.json`)d.set(e,(await read(e)).toString(`utf8`));const f=new Set(t.filter(e=>!o.has(e)));for(const e of f){const t=u.has(e)&&/\.[cm]?ts$/u.test(e);if(!/\.[cm]?js$/u.test(e)&&!t)continue;const n=(await read(e)).toString(`utf8`);const r=/* @__PURE__ */ new Set;const i=[];const a=collectPackageDistImports({files:[e],includeTypeScript:t,readText:()=>n,onLiteralCall:e=>r.add(e),onStaticImport:e=>{i.push(e)}});s.set(e,{imports:a});const c=new Set(a.map(({importedPath:e})=>e));const p=/(?:^|\/)node_modules\//u.test(e)?collectPackageRootImports(preparePackageDistJavaScript(e,n)):/* @__PURE__ */ new Set([...i,...r]);for(const t of p){if(!t.startsWith(`.`))continue;const n=t.replace(/[?#].*$/u,``);const r=path.posix.normalize(path.posix.join(path.posix.dirname(e),n));const i=resolvePackageDistCommonJs(r,l,d);if(i)c.add(i)}for(const e of c)if(o.has(e))f.add(e)}for(const e of o.keys())if(!f.has(e))await read(e);return{files:t.filter(e=>f.has(e)),sourceFacts:s}}
//!src/gateway/worker-environments/node-bootstrap-artifact-build.ts
async function observeBootstrapModes(e){const t=[];for(const n of[420,493]){const r=path.join(e,`.mode-${n.toString(8)}`);const i=await fs$1.open(r,`wx`,n);try{t.push((await i.stat()).mode&511)}finally{await i.close();await fs$1.rm(r)}}return t}async function prepareNodeBootstrapArtifact(e,t,n=true){const r=await fs$1.realpath(e.packageRoot);const i=await readPackageManifest(r);if(i.name!==`openclaw`)throw new Error(`Node bootstrap requires the running OpenClaw package root`);const a=path.join(r,`dist`,`build-info.json`);const o=await fs$1.readFile(a,`utf8`).catch(e=>{throw new Error(`Cloud bootstrap requires a built Gateway; run pnpm build and restart the Gateway before provisioning`,{cause:e})});const s=requireRunningBuild(e,o,i.version);const c=await resolvePlugins(e,r);const l=composePackagePlugins(i,c);const u=e.install??`bundle`;const d=await observeBootstrapModes(t);const f={inspectImports:true,label:l.name,prefix:``,files:[],imports:[],packageJsons:/* @__PURE__ */ new Map};const p=[];const m=/* @__PURE__ */ new Map;const planEntry=(e,t)=>{bootstrapPath(e);m.set(e,t);if(m.size>DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxEntries)throw new Error(`Node bootstrap distribution exceeds its artifact limits`)};let h=0;let g=0;const reserveFile=e=>{h+=e;g+=1;if(g>DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxEntries||h>DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxExpandedBytes)throw new Error(`Node bootstrap distribution exceeds its artifact limits`)};const addGeneratedFile=(e,t,n=f)=>{reserveFile(Buffer.byteLength(t));planEntry(e,{contents:Buffer.from(t),scope:n})};const addFiles=(e,t,n=``,r=f)=>{for(const i of new Set(t))planEntry(`${n}${i}`,{source:{root:e,relative:i},scope:r})};const readEntry=async(e,t)=>{if(`contents`in e){await t([e.contents],e.contents.byteLength,d[0]);return}const{root:n,relative:r}=e.source;const i=path.join(n,r);if(await fs$1.realpath(i)!==i)throw new Error(`Node distribution cannot contain symbolic links: ${r}`);const a=await fs$1.open(i,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{const e=await a.stat();if(!e.isFile())throw new Error(`Invalid node distribution file: ${r}`);reserveFile(e.size);async function*chunks(){let t=e.size;while(t>=0){const e=Buffer.allocUnsafe(Math.min(t+1,65536));const{bytesRead:n}=await a.read(e,0,e.length,null);if(!n)return;t-=n;yield e.subarray(0,n)}}await t(chunks(),e.size,d[(e.mode&73)!==0?1:0]);const n=await fs$1.lstat(i);if(n.isSymbolicLink()||n.dev!==e.dev||n.ino!==e.ino||await fs$1.realpath(i)!==i)throw new Error(`Node distribution changed while packaging: ${r}`)}finally{await a.close()}};const _=c.filter(e=>!e.bundled).map(({id:e})=>`dist/extensions/${e}/`);const v=(await collectPackageDistInventory(r,{packageManifest:l})).filter(e=>e!==`dist/postinstall-content-inventory.json`&&!e.startsWith(`dist/worker/`)&&!e.startsWith(`dist/worker-artifacts/`)&&!e.startsWith(`dist/control-ui/`)&&!_.some(t=>e.startsWith(t)));const y=(i.files??[]).filter(e=>(e.startsWith(`scripts/`)||/\.[cm]?[jt]s$/u.test(e))&&!e.startsWith(`!`)&&!e.includes(`*`)&&!e.endsWith(`/`));const{files:b,sourceFacts:x}=await resolveNodeBootstrapRuntimeChunks(r,[...y,...v].filter(e=>e!==LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH),l.files??[]);if(!b.includes(`dist/entry.js`)&&!b.includes(`dist/entry.mjs`))throw new Error(`Cloud bootstrap is missing its built CLI entry; run pnpm build and restart the Gateway`);addFiles(r,b);if(u===`npm`)l.scripts=Object.fromEntries(Object.entries(l.scripts??{}).filter(([e])=>[`preinstall`,`install`,`postinstall`].includes(e)));else delete l.scripts;delete l.devDependencies;for(const e of c){if(e.bundled)continue;const t=await collectBootstrapFiles(e.root,true);addFiles(e.root,t,`dist/extensions/${e.id}/`)}let S=[];if(u===`npm`){const addBundledPackage=async(e,t,n,r=false)=>{const i=r?await collectPackageDistInventory(e):await collectBootstrapFiles(e);if(i.length===0)throw new Error(`Bundled node dependency ${t.name} needs its compiled distribution; rebuild the Gateway`);const a={inspectImports:true,label:t.name,prefix:n,files:[],imports:[],packageJsons:/* @__PURE__ */ new Map,...t.name===`chrome-devtools-mcp`?{patchedMcp:{manifest:t,hashes:/* @__PURE__ */ new Map}}:{}};p.push(a);addFiles(e,i,n,a);delete t.devDependencies;delete t.scripts;addGeneratedFile(`${n}package.json`,`${JSON.stringify(t,null,2)}\n`,a)};const addRegistryClosure=async(e,n,r,i)=>{if(r.split(`/`).length>64)throw new Error(`Node bootstrap dependency exceeds its directory depth limit`);await addBundledPackage(e,n,r);const a=path.resolve(t,`package`,r);const o=new Map(i).set(a,e);for(const t of await installedPackageDependencies(e,n)){if(hasInstalledPackageAncestor(a,t,o))continue;await addRegistryClosure(t.root,await readPackageManifest(t.root),`${r}node_modules/${t.name}/`,o)}};const e=/* @__PURE__ */ new Set([...listBundleDependencies(i),...Object.entries(i.dependencies??{}).filter(([,e])=>e.startsWith(`workspace:`)).map(([e])=>e)]);const n=/* @__PURE__ */ new Set([...e,...listBundleDependencies(l)]);for(const t of[...n].toSorted()){bootstrapPath(t);const n=(e.has(t)?void 0:c.find(({packageJson:e})=>listBundleDependencies(e).includes(t))??c.find(({packageJson:e})=>Object.hasOwn(e.dependencies??{},t)||Object.hasOwn(e.optionalDependencies??{},t)))?.installationRoot??r;const a=await installedPackagePath(n,t);if(!a)throw new Error(`Bundled node dependency ${t} is missing from ${n}; install its dependencies and rebuild the Gateway`);const o=await fs$1.realpath(a);const s=await readPackageManifest(o);if(s.name!==t)throw new Error(`Bundled node distribution dependency identity does not match ${t}`);const u=i.dependencies?.[t]?.startsWith(`workspace:`)||!o.endsWith(`${path.sep}node_modules${path.sep}${t.split(`/`).join(path.sep)}`);if(u){const e=validateBundledPackageDependencyAlignment({bundledDependencies:s.dependencies,bundledPackageLabel:`bundled ${t}`,rootDependencies:l.dependencies});for(const[t,n]of e)l.dependencies[t]=n;delete s.dependencies}const d=`node_modules/${t}/`;if(u)await addBundledPackage(o,s,d,true);else await addRegistryClosure(o,s,d,/* @__PURE__ */ new Map);l.dependencies[t]=s.version}l.bundleDependencies=[...n].toSorted();delete l.bundledDependencies;for(const[e,t]of Object.entries({...l.optionalDependencies,...l.dependencies}))if(valid(t)!==t)throw new Error(`Node distribution requires an exact dependency pin: ${e}@${t}`)}else{const e=/* @__PURE__ */ new Set([...listBundleDependencies(i),...Object.entries(i.dependencies??{}).filter(([,e])=>e.startsWith(`workspace:`)).map(([e])=>e)]);S=await collectNodeBootstrapDependencyTargets(r,i);for(const t of S){const n=/* @__PURE__ */ new Map;for(const e of c)for(const r of Object.keys({...e.packageJson.dependencies,...e.packageJson.optionalDependencies}))if(!Object.hasOwn(i.dependencies??{},r)&&!Object.hasOwn(i.optionalDependencies??{},r))n.set(r,t.prefix?path.join(t.root,`extensions`,e.id):e.installationRoot);for(const r of await collectNodeBootstrapDependencies(t.root,l,t,n)){const{root:n,requestedName:a,manifest:o}=r;if(!t.prefix&&r.prefix===`node_modules/${o.name}/`&&l.dependencies?.[o.name])l.dependencies[o.name]=o.version;const s=o.name;const c=path.relative(t.root,n);if(t.prefix&&(c===`..`||c.startsWith(`..${path.sep}`)||path.isAbsolute(c)))throw new Error(`Node runtime target dependency escapes its prepared input: ${s}`);const u=i.dependencies?.[a]?.startsWith(`workspace:`)||![a,s].some(e=>n.endsWith(`${path.sep}node_modules${path.sep}${e.split(`/`).join(path.sep)}`))?await collectPackageDistInventory(n):await collectBootstrapFiles(n);if(!u.length)throw new Error(`Node runtime dependency ${s} has no executable distribution`);const d={inspectImports:e.has(s),label:s,prefix:`${t.prefix}${r.prefix}`,files:[],imports:[],packageJsons:/* @__PURE__ */ new Map,...s===`chrome-devtools-mcp`?{patchedMcp:{manifest:o,hashes:/* @__PURE__ */ new Map}}:{}};p.push(d);addFiles(n,u,d.prefix,d);const f={...o};delete f.scripts;delete f.devDependencies;addGeneratedFile(`${d.prefix}package.json`,`${JSON.stringify(f,null,2)}\n`,d)}}delete l.bundleDependencies;delete l.bundledDependencies}addGeneratedFile(`node-runtime.json`,`${JSON.stringify({buildId:s,install:u,openclawVersion:l.version,platforms:u===`bundle`?S.map(({platform:e,arch:t,prefix:n})=>({platform:e,arch:t,prefix:n})):[]})}\n`);addGeneratedFile(`package.json`,`${JSON.stringify(l,null,2)}\n`);const C=[...m.keys()].filter(e=>e.startsWith(`dist/`)).toSorted();addGeneratedFile(PACKAGE_DIST_INVENTORY_RELATIVE_PATH,`${JSON.stringify(C)}\n`);if(u===`npm`)addGeneratedFile(PACKAGE_LIFECYCLE_PENDING_RELATIVE_PATH,`pending
`);const w=[...m].toSorted(([e],[t])=>Number(path.posix.basename(t)===`package.json`)-Number(path.posix.basename(e)===`package.json`)||compareWorkerBundlePaths(e,t));f.files=w.map(([e])=>e);for(const e of p)e.files=w.flatMap(([t])=>t.startsWith(e.prefix)?[t.slice(e.prefix.length)]:[]);const T=path.join(t,NODE_BOOTSTRAP_PREBUILT_ARCHIVE);const E=n?await copyNodeBootstrapPrebuiltArchive(r,t):void 0;let D=Promise.resolve();const O=E?void 0:new Pack({gzip:true,noMtime:true,portable:true,strict:true,onWriteEntry(e){D=finished(e,{readable:true,writable:false,cleanup:true});D.catch(()=>void 0)}});const k=createHash(`sha256`);const A=O?pipeline(O,async function*(e){for await(const t of e){k.update(t);yield t}},createWriteStream(T,{flags:`wx`})):Promise.resolve();const j=new AbortController;A.catch(e=>j.abort(e));const M=[];try{for(const[e,t]of w)await readEntry(t,async(n,r,i)=>{const a=e.slice(t.scope.prefix.length);const o=x.get(e);const s=path.posix.basename(e)===`package.json`;const c=t.scope===f&&y.includes(e);const l=s||!o&&!t.scope.patchedMcp&&(/\.[cm]?js$/u.test(a)||c&&/\.[cm]?ts$/u.test(a))?new StringDecoder(`utf8`):void 0;let u=``;const d=O?new ReadEntry(new Header({path:`package/${e}`,size:r,mode:i,type:`File`})):void 0;if(d&&O)O.add(d);const p=createHash(`sha256`);let m=0;for await(const t of n){j.signal.throwIfAborted();m+=t.byteLength;if(m>r)throw new Error(`Node distribution changed while packaging: ${e}`);p.update(t);if(l)u+=l.write(t);if(d&&!d.write(t))await once(d,`drain`,{signal:j.signal})}if(m!==r)throw new Error(`Node distribution changed while packaging: ${e}`);d?.end();u+=l?.end()??``;if(s){f.packageJsons.set(e,u);t.scope.packageJsons.set(a,u)}const h={path:`package/${e}`,size:r,mode:process.platform===`win32`?448:i,sha256:p.digest(`hex`)};if(t.scope.patchedMcp)t.scope.patchedMcp.hashes.set(a,h.sha256);else if(t.scope.inspectImports)t.scope.imports.push(...o?.imports??collectPackageDistImports({files:[a],includeTypeScript:c,packageJsons:t.scope.packageJsons,readText:()=>u}));M.push(h);if(O)await Promise.race([D,A])});for(const e of p)for(const[t,n]of f.packageJsons)if(t.startsWith(e.prefix))e.packageJsons.set(t.slice(e.prefix.length),n);for(const e of[...p,f]){if(!e.inspectImports)continue;const t=e.patchedMcp?collectPatchedMcpArtifactErrors({manifest:e.patchedMcp.manifest,files:new Set(e.files),sha256:t=>e.patchedMcp?.hashes.get(t)}):collectPackageDistImportErrors(e);if(t.length>0)throw new Error(`Node distribution ${e.label} ${e.patchedMcp?`has an invalid patched dependency`:`has an incomplete built import closure`}; rebuild and restart the Gateway: ${t.slice(0,5).join(`; `)}`)}const e=Buffer.from(`${JSON.stringify(M)}\n`);reserveFile(e.byteLength);const t={path:`package/node-runtime.manifest.json`,size:e.byteLength,mode:process.platform===`win32`?448:d[0],sha256:createHash(`sha256`).update(e).digest(`hex`)};M.push(t);if(O){const n=new ReadEntry(new Header({path:t.path,size:t.size,mode:d[0],type:`File`}));O.add(n);n.end(e);await Promise.race([D,A])}O?.end();await A}catch(e){O?.destroy(e instanceof Error?e:new Error(`Node bootstrap archive failed`,{cause:e}));O?.zip?.destroy();await A.catch(()=>void 0);throw e}const N=(await fs$1.stat(T)).size;if(N>536870912)throw new Error(`Node bootstrap archive exceeds the transfer limit`);M.sort((e,t)=>compareWorkerBundlePaths(e.path,t.path));if(E){if(hashWorkerBundleManifest(M)!==hashWorkerBundleManifest(E)){await fs$1.rm(T);return await prepareNodeBootstrapArtifact(e,t,false)}}let P;if(O)P=k.digest(`hex`);else try{var F=_usingCtx();const e=F.a(await fs$1.open(T,`r`));P=(await sha256File(e)).digest}catch(e){F.e=e}finally{await F.d()}return{tarballPath:T,tarballSha256:P,tarballBytes:N,openclawVersion:l.version,buildId:s,install:u,manifestSha256:M.find(e=>e.path===`package/node-runtime.manifest.json`).sha256,enabledPluginIds:c.map(({id:e})=>e).toSorted()}}export{prepareNodeBootstrapArtifact};