UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 24.9 kB
import{spawn as e}from"node:child_process";import{closeSync as t,createWriteStream as n,existsSync as r,readFileSync as i}from"node:fs";import{setTimeout as a}from"node:timers/promises";import o from"node:path";import{fileURLToPath as s,pathToFileURL as c}from"node:url";import{readRootJsonObjectSync as l}from"@openclaw/fs-safe/json";import"@openclaw/fs-safe/advanced";import"@openclaw/proc-safe/errors";import"@openclaw/proc-safe/identity";import"@openclaw/proc-safe/inspect";function parseNodeOptionsEnvVar(e){let t=[],n=``,r=!1,i=e??``;for(let e=0;e<i.length;e+=1){let a=i.charAt(e);if(a===`\\`&&r){if(e+=1,e>=i.length)return null;a=i.charAt(e)}else if(a===` `&&!r){n.length>0&&(t.push(n),n=``);continue}else if(a===`"`){r=!r;continue}n+=a}return r?null:(n.length>0&&t.push(n),t)}function isNodeStartupHook(e){return/^(?:--(?:import|require|(?:experimental-)?loader)(?:=|$)|-r)/u.test(e.replaceAll(`_`,`-`))}function stripNodeStartupHooks(e){let t=parseNodeOptionsEnvVar(e);if(t===null)throw Error(`Invalid NODE_OPTIONS for process owner`);if(!t.some(isNodeStartupHook))return e;let n=[];for(let e=0;e<t.length;e+=1){let r=t[e];isNodeStartupHook(r)?(r===`-r`||r.startsWith(`--`)&&!r.includes(`=`))&&(e+=1):n.push(`"`+r.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)+`"`)}return n.join(` `)}const u=Symbol.for(`openclaw.cliRespawnParent`),d=`OPENCLAW_CLI_RESPAWN_PARENT`,f=process.env[d];delete process.env[d],f===String(process.ppid)&&(globalThis[u]={pid:process.ppid});function readStandaloneRuntimeManifest(e=process.execPath){return readStandaloneManifest({executable:e})}function projectStandaloneBuildInfo(e){let nonBlank=e=>typeof e==`string`&&e.trim().length>0,stringList=e=>Array.isArray(e)&&e.every(nonBlank),t={mode:e.mode,openclaw:{version:e.openclaw.version,...nonBlank(e.openclaw.commit)?{commit:e.openclaw.commit}:{}},bun:{version:e.bun.version}};for(let n of[`revision`,`commit`,`executableSha256`])nonBlank(e.bun[n])&&(t.bun[n]=e.bun[n]);if(e.build!==void 0){let{id:n,flavor:r,pluginSetSha256:i,moduleGraphSha256:a}=e.build;if(!nonBlank(n)||![`standard`,`support`].includes(r)||!/^[a-f0-9]{64}$/.test(i)||!/^[a-f0-9]{64}$/.test(a))throw Error(`Invalid standalone build provenance`);if(t.build={id:n,flavor:r,pluginSetSha256:i,moduleGraphSha256:a},e.build.debugEntry!==void 0){let n=e.build.debugEntry;if(typeof n!=`string`||!n.startsWith(`debug/`)||n.includes(`\\`)||n.split(`/`).some(e=>!e||e===`.`||e===`..`))throw Error(`Invalid standalone debugger entry`);t.build.debugEntry=n}}if(e.target!==void 0){if(!nonBlank(e.target.platform)||!nonBlank(e.target.arch))throw Error(`Invalid standalone build target`);t.target={platform:e.target.platform,arch:e.target.arch}}if(e.plugins!==void 0){if(!stringList(e.plugins.embedded)||!stringList(e.plugins.omitted))throw Error(`Invalid standalone plugin inventory`);t.plugins={embedded:[...e.plugins.embedded],omitted:[...e.plugins.omitted]}}if(e.nativeModules!==void 0){if(!Array.isArray(e.nativeModules)||e.nativeModules.some(e=>!e||!nonBlank(e.name)||!nonBlank(e.version)||!stringList(e.artifacts)||e.qualification!==`unverified`||!nonBlank(e.backend)))throw Error(`Invalid standalone native inventory`);t.nativeModules=e.nativeModules.map(({name:e,version:t,artifacts:n,qualification:r,backend:i})=>({name:e,version:t,artifacts:[...n],qualification:r,backend:i}))}return t}function readStandaloneManifest({executable:e,runtimeRoot:t,includeBuild:n=!1}){let r=e??t;if(!o.isAbsolute(r))return;let a=o.dirname(r),s=o.join(a,`manifest.json`),c;try{c=i(s,`utf8`)}catch(e){if(e?.code===`ENOENT`||e?.code===`ENOTDIR`)return;throw e}let l;try{l=JSON.parse(c)}catch(e){throw Error(`Invalid standalone runtime manifest: ${s}`,{cause:e})}let nonBlank=e=>typeof e==`string`&&e.trim().length>0;if(l?.schemaVersion!==1||![`jit`,`bytecode`,`aot`].includes(l.mode)||!nonBlank(l.executable?.path)||!nonBlank(l.runtime?.path)||!nonBlank(l.openclaw?.version)||!nonBlank(l.bun?.version))throw Error(`Invalid standalone runtime manifest: ${s}`);let u=o.relative(a,o.resolve(a,l.executable.path)),d=o.relative(a,o.resolve(a,l.runtime.path));if(o.isAbsolute(l.executable.path)||!u||u===`..`||u.startsWith(`..${o.sep}`)||e&&o.resolve(a,l.executable.path)!==o.resolve(e)||t&&o.resolve(a,l.runtime.path)!==o.resolve(t)||o.isAbsolute(l.runtime.path)||!d||d===`..`||d.startsWith(`..${o.sep}`))throw Error(`Invalid standalone runtime manifest: ${s}`);return{schemaVersion:1,mode:l.mode,executable:{path:l.executable.path,...nonBlank(l.executable.sha256)?{sha256:l.executable.sha256}:{}},runtime:{path:l.runtime.path,...nonBlank(l.runtime.sha256)?{sha256:l.runtime.sha256}:{}},openclaw:{version:l.openclaw.version,...nonBlank(l.openclaw.commit)?{commit:l.openclaw.commit}:{}},bun:{version:l.bun.version},...n?projectStandaloneBuildInfo(l):{}}}function getEmbeddedStandaloneRuntimeRoot(){let e=globalThis.__openclawStandaloneRootUrl;return typeof e==`string`?s(e):void 0}function isEmbeddedStandaloneModule(e){let t=e.startsWith(`file:`)?s(e):e;return globalThis.__openclawStandaloneIsEmbeddedModule?.(t)===!0}function resolveStandaloneSidecarRoot(e=process.execPath){if(e===process.execPath){let e=getEmbeddedStandaloneRuntimeRoot();if(e!==void 0)return e}let t=readStandaloneRuntimeManifest(e);return t?o.resolve(o.dirname(e),t.runtime.path):void 0}function isStandaloneRuntimeExecutable(e=process.execPath){return resolveStandaloneSidecarRoot(e)!==void 0}function resolveRuntimeScriptEnv(e){return isStandaloneRuntimeExecutable()?{...e,BUN_BE_BUN:`1`}:{...e}}function createRuntimeProcessEntrypoints(e){function runtimeProcessEntrypoint(t,n=t,r=`.js`,i){return{currentModuleUrl:e,sourceModulePath:`src/${t}${i??`.ts`}`,sourceExtension:i,sourceWorkerName:t.startsWith(`infra/`)?t.slice(6):`../${t}`,distWorkerPath:`${n}${r}`}}let loaderFreeEntrypoint=e=>runtimeProcessEntrypoint(e,void 0,void 0,`.mjs`);return{daemonRuntimeProbe:runtimeProcessEntrypoint(`infra/daemon-runtime-probe.entry`),pluginToolsServe:runtimeProcessEntrypoint(`mcp/plugin-tools-serve`),openclawToolsServe:runtimeProcessEntrypoint(`mcp/openclaw-tools-serve`),repositoryPublicationRestore:loaderFreeEntrypoint(`gateway/repository-publication-restore.generated.worker`),nodeWorkspacePublicationSnapshot:loaderFreeEntrypoint(`node-host/node-worker-publication-snapshot.generated.worker`),nodeWorkspaceManifest:loaderFreeEntrypoint(`node-host/node-worker-workspace-manifest.generated.worker`),nodeWorkspaceGitHistory:loaderFreeEntrypoint(`node-host/node-worker-workspace-git-history.generated.worker`),doctorDatabaseEngineInspection:runtimeProcessEntrypoint(`commands/doctor-database-engine-inspection.worker`),backupDatabaseDiscovery:runtimeProcessEntrypoint(`infra/backup-database-discovery.worker`),sqliteHeaderProbe:runtimeProcessEntrypoint(`infra/sqlite-header-probe.worker`),databaseBackup:runtimeProcessEntrypoint(`snapshot/database-backup.worker`),managedHandoffEngine:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-engine.worker`),updatePostgresState:runtimeProcessEntrypoint(`infra/update-candidate-state.postgres.worker`),databasePortCommand:runtimeProcessEntrypoint(`infra/database-engine/port-command.entry.worker`),systemCaWarmup:runtimeProcessEntrypoint(`gateway/system-ca-warmup.worker`),shutdownHardExit:loaderFreeEntrypoint(`cli/gateway-cli/shutdown-hard-exit.worker`),packageIntegrityHasher:runtimeProcessEntrypoint(`infra/package-update-integrity-hasher.worker`),packageLocalOverrides:runtimeProcessEntrypoint(`infra/package-local-overrides.worker`),directoryWatchHost:runtimeProcessEntrypoint(`infra/directory-watch-host.worker`),directoryWatchParent:runtimeProcessEntrypoint(`infra/directory-watch-parent.worker`),workspaceQuiescenceAcquire:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-acquire.generated.worker`),workspaceQuiescenceRenew:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-renew.generated.worker`),workspaceQuiescenceRelease:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-release.generated.worker`),packageActivationRecovery:runtimeProcessEntrypoint(`infra/package-update-activation-sealed`,`package-update-activation-recovery`,`.mjs`),managedHandoffPostgresBridge:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-postgres.worker`,`managed-handoff-postgres-bridge.worker`,`.mjs`),managedHandoffRuntime:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-sealed`,`managed-handoff-runtime`,`.mjs`),sqliteVector:runtimeProcessEntrypoint(`infra/database-engine/sqlite-vector.child`),postgresBridge:runtimeProcessEntrypoint(`infra/postgres-sync/bridge.worker`),secretEgressProxy:runtimeProcessEntrypoint(`secrets/egress-proxy/proxy.worker`),codeModeNode:runtimeProcessEntrypoint(`agents/code-mode-node.worker`),cronReadOnly:runtimeProcessEntrypoint(`cron/store/read-only.worker`),stateRead:runtimeProcessEntrypoint(`state/openclaw-state-read.worker`),workerNativeLifecycle:runtimeProcessEntrypoint(`infra/worker-native-lifecycle.worker`),spawnBroker:runtimeProcessEntrypoint(`process/spawn-broker/worker`),cronStreamMatcher:runtimeProcessEntrypoint(`gateway/cron-stream-matcher.worker`),controlUiFile:runtimeProcessEntrypoint(`gateway/control-ui-file.worker`),publicSessionCard:runtimeProcessEntrypoint(`gateway/control-ui-public-session-card.worker`),nodeBootstrapArtifact:runtimeProcessEntrypoint(`gateway/worker-environments/node-bootstrap-artifact.worker`),nativeHookRelayClient:runtimeProcessEntrypoint(`agents/harness/native-hook-relay-client.worker`),computerHost:runtimeProcessEntrypoint(`gateway/desktop/computer.worker`),imageProcessor:runtimeProcessEntrypoint(`media/image-processor.worker`),fileToolPlanning:runtimeProcessEntrypoint(`agents/sessions/tools/file-tool-planning.worker`),fileToolRead:runtimeProcessEntrypoint(`agents/sessions/tools/read-file.worker`),attachmentProcessor:runtimeProcessEntrypoint(`media/attachment-processor.worker`),widgetScriptSyntax:runtimeProcessEntrypoint(`canvas/widget-script-syntax.worker`),gitOperations:runtimeProcessEntrypoint(`infra/git-operation.worker`),gitPackCleanup:runtimeProcessEntrypoint(`agents/worktrees/git-pack-cleanup.worker`),fsSafeCopy:runtimeProcessEntrypoint(`infra/fs-safe-copy.worker`),sharedStateStore:runtimeProcessEntrypoint(`state/openclaw-state.worker`),clientCredentials:runtimeProcessEntrypoint(`infra/client-credential.worker`),ttsPreferences:runtimeProcessEntrypoint(`tts/tts-settings-write.worker`),authProfileInlineUsage:runtimeProcessEntrypoint(`agents/auth-profiles/inline-usage.worker`),pluginModelCatalogRead:runtimeProcessEntrypoint(`agents/plugin-model-catalog-read.worker`),pluginModelCatalogCredentials:runtimeProcessEntrypoint(`agents/plugin-model-catalog.worker`),pluginCaptureNativeResource:runtimeProcessEntrypoint(`plugins/plugin-capture-native-resource`),pluginGenerationPreparation:runtimeProcessEntrypoint(`plugins/plugin-generation-preparation.worker`),agentDatabaseExecution:runtimeProcessEntrypoint(`state/openclaw-agent-execution.worker`),workspaceMemory:runtimeProcessEntrypoint(`worker/memory-worker-entry`,`agents/workspace-memory.worker`),localAgentAvatar:runtimeProcessEntrypoint(`agents/identity-avatar-file.worker`),identityFile:runtimeProcessEntrypoint(`agents/identity-file.worker`),workspaceSkills:runtimeProcessEntrypoint(`worker/skills-worker-entry`,`agents/workspace-skills.worker`),skillsDiscovery:runtimeProcessEntrypoint(`skills/runtime/discovery.worker`),boardStore:runtimeProcessEntrypoint(`boards/sqlite-board-store.worker`),progressCardStore:runtimeProcessEntrypoint(`session-cards/progress-card-store.worker`),sessionSharingStore:runtimeProcessEntrypoint(`config/sessions/session-sharing-store.worker`),sessionForkDomain:runtimeProcessEntrypoint(`config/sessions/session-fork-domain.worker`),sessionGoalOperations:runtimeProcessEntrypoint(`config/sessions/goals-operations.worker`),sessionLifecyclePlanningDomain:runtimeProcessEntrypoint(`config/sessions/session-lifecycle-projection.worker`),sessionMessageRewriteDomain:runtimeProcessEntrypoint(`config/sessions/session-message-rewrite.worker`),sessionDiskBudget:runtimeProcessEntrypoint(`config/sessions/disk-budget.worker`),contextEngineTurnOutbox:runtimeProcessEntrypoint(`agents/harness/context-engine-turn-outbox.worker`),sqliteStore:runtimeProcessEntrypoint(`infra/sqlite-store.worker`),sqliteWriterAdmission:runtimeProcessEntrypoint(`infra/sqlite-writer-admission.worker`),agentSchemaInspection:runtimeProcessEntrypoint(`state/openclaw-agent-schema-inspection.worker`),stateMigrationSnapshot:runtimeProcessEntrypoint(`infra/state-migrations.snapshot.worker`),githubExec:runtimeProcessEntrypoint(`agents/github-exec-launcher`),shellSnapshotEnvironment:runtimeProcessEntrypoint(`agents/shell-snapshot-env.worker`),sqliteReadOnly:runtimeProcessEntrypoint(`infra/sqlite-readonly-location.worker`),sqliteSnapshotStaging:runtimeProcessEntrypoint(`infra/sqlite-snapshot-staging.worker`),sqliteReadOnlyNativeResource:runtimeProcessEntrypoint(`infra/sqlite-readonly-native-resource`),sqliteSourceRevision:runtimeProcessEntrypoint(`infra/sqlite-source-revision.worker`),sqliteIntegrity:runtimeProcessEntrypoint(`infra/sqlite-integrity.worker`),sqliteCloseProbe:runtimeProcessEntrypoint(`infra/bun-sqlite-close-probe.worker`),preparedModelCatalog:runtimeProcessEntrypoint(`agents/prepared-model-catalog.worker`),providerPromptState:runtimeProcessEntrypoint(`agents/embedded-agent-runner/provider-prompt-state.worker`),retiredWorktreeCleanup:runtimeProcessEntrypoint(`agents/worktrees/retired-worktree-cleanup.worker`),updateNativeGate:runtimeProcessEntrypoint(`cli/update-cli/update-command-native-gate.worker`),updateStateSizes:runtimeProcessEntrypoint(`infra/update-state-sizes.entry`),updateRepair:runtimeProcessEntrypoint(`infra/update-repair.worker`),immutableBuild:runtimeProcessEntrypoint(`infra/update-immutable-build.worker`),updateMigratedFinalize:runtimeProcessEntrypoint(`infra/update-migrated-finalize.worker`),updateAutomaticCleanup:runtimeProcessEntrypoint(`infra/update-automatic-cleanup.worker`),updateCandidateState:runtimeProcessEntrypoint(`infra/update-candidate-state.worker`),doctorLint:runtimeProcessEntrypoint(`commands/doctor-lint.worker`),doctor:runtimeProcessEntrypoint(`commands/doctor.worker`),databaseVerify:runtimeProcessEntrypoint(`state/openclaw-database-verify.worker`),stateOwnership:runtimeProcessEntrypoint(`state/openclaw-state-ownership.worker`),stateLeaseHeartbeat:runtimeProcessEntrypoint(`state/openclaw-state-lease-heartbeat.worker`),gatewayStateOwnerHeartbeat:runtimeProcessEntrypoint(`infra/gateway-state-owner-heartbeat.worker`),sessionTranscriptArchive:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-archive.worker`),sessionTranscript:runtimeProcessEntrypoint(`config/sessions/session-transcript.worker`),usageOverview:runtimeProcessEntrypoint(`infra/session-cost-usage-overview-report.worker`),workerTranscriptCommit:runtimeProcessEntrypoint(`gateway/worker-environments/transcript-commit.worker`),sessionManagerMetadata:runtimeProcessEntrypoint(`agents/sessions/session-manager-metadata.worker`),sessionTranscriptProjectionPublication:runtimeProcessEntrypoint(`config/sessions/session-transcript-projection-publication.worker`),sessionTranscriptReports:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-transcript-reports.worker`),sessionTranscriptReconcile:runtimeProcessEntrypoint(`config/sessions/session-transcript-reconcile.worker`),tailscaleRouteOwner:runtimeProcessEntrypoint(`infra/tailscale-route-owner.worker`),serviceChildRelay:runtimeProcessEntrypoint(`process/supervisor/service-child-relay`),terminalPty:runtimeProcessEntrypoint(`process/terminal-pty-worker`),serviceChildGroupAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-group-anchor`),serviceChildWindowsJobAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-windows-job-anchor`),bunSqliteLibrary:runtimeProcessEntrypoint(`infra/bun-sqlite-library`)}}function pluginRuntimeProcess(e,t,n){return{plugin:e,ownerSource:`extensions/${e}/${t}.ts`,sourceWorkerName:n,distWorkerPath:`extensions/${e}/${n}.js`,package:{name:`@openclaw/${e}`,distWorkerPath:`${n}.js`}}}({...pluginRuntimeProcess(`browser`,`native-host-entry`,`native-host-entry`)}),{...pluginRuntimeProcess(`browser`,`native-host-entry`,`relay-daemon-entry`)},{...pluginRuntimeProcess(`browser`,`setup-entry`,`setup-entry`)},{...pluginRuntimeProcess(`code-mode-quickjs`,`src/executor`,`src/code-mode.worker`)},pluginRuntimeProcess(`codex`,`stdio-worker-entrypoint`,`stdio.worker`),pluginRuntimeProcess(`codex`,`catalog-page-worker-entrypoint`,`catalog-page.worker`),pluginRuntimeProcess(`codex`,`session-history-worker-entrypoint`,`session-history.worker`),{...pluginRuntimeProcess(`discord`,`src/voice/audio-worker-thread`,`src/voice/audio-worker.runtime`)},{...pluginRuntimeProcess(`document-extract`,`document-extractor-worker-entrypoint`,`document-extractor.worker`)},{...pluginRuntimeProcess(`web-readability`,`web-content-extractor-worker.runtime`,`web-content-extractor.worker`)},{...pluginRuntimeProcess(`imessage`,`src/chat-db`,`src/chat-db.worker`)},{...pluginRuntimeProcess(`knowledge`,`src/registry-client`,`src/registry-worker`)},{...pluginRuntimeProcess(`knowledge`,`src/storage-client`,`src/storage-worker`)},{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-search.worker`)},{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-index.worker`)},{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-publication.worker`)},{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/standing-intents.worker`)},{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory-entry-origins.worker`)},pluginRuntimeProcess(`memory-lancedb`,`memory-stats-entrypoint`,`memory-stats.worker`),{...pluginRuntimeProcess(`memory-wiki`,`src/query-reader`,`src/query-reader.worker`)},{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-peer.runtime`,`realtime-quicksilver-audio.worker`)},{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-socket`,`realtime-quicksilver-socket.worker`)},{...pluginRuntimeProcess(`qa-lab`,`src/execution-identity-storage-inspection`,`src/execution-identity-storage-inspection.worker`)},{...pluginRuntimeProcess(`telegram`,`src/telegram-ingress-worker`,`src/telegram-ingress-worker.runtime`)},{...pluginRuntimeProcess(`telegram`,`src/widgets/widget-check`,`src/widgets/widget-check.worker`)},pluginRuntimeProcess(`onnx`,`index`,`src/inference.worker`),pluginRuntimeProcess(`team-reports`,`index`,`src/store.worker`),pluginRuntimeProcess(`team-reports`,`index`,`src/run.worker`),pluginRuntimeProcess(`logbook`,`index`,`src/store.worker`),pluginRuntimeProcess(`workboard`,`index`,`src/sqlite-store.worker`);const p=createRuntimeProcessEntrypoints(import.meta.url);resolveRuntimeProcessDistRoot(s(import.meta.url));function resolveRuntimeProcessDistRoot(e){let t=e.replaceAll(o.sep,`/`).lastIndexOf(`/dist/`);return t>=0?e.slice(0,t+6):void 0}function normalizeRuntimeBasename(e){let t=e.trim().replace(/^["']|["']$/g,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return(n===-1?t:t.slice(n+1)).trim().toLowerCase()}function isBunRuntime(e){let t=normalizeRuntimeBasename(e);return t===`bun`||t===`bun.exe`}[.../* @__PURE__ */ new Set([`-r`,`--preload`,`--require`,`--import`,`--loader`,`--experimental-loader`,`--test-reporter`,`--test-global-setup`])];function resolveRuntimeWorkerUrl(e){if(e.root!==void 0)return c(o.join(e.root,`dist`,e.distWorkerPath));let t=s(e.currentModuleUrl),n=resolveRuntimeProcessDistRoot(t);if(n!==void 0){let t=e.distWorkerPath;if(e.package){let r=o.resolve(n,`..`),i=l({rootDir:r,relativePath:`package.json`,boundaryLabel:`runtime worker package`,rejectHardlinks:!1});if(!i.ok)throw Error(`Cannot resolve runtime worker package: ${r}/package.json`);i.value.name===e.package.name&&(t=e.package.distWorkerPath)}return c(o.join(n,t))}let r=e.sourceExtension??(o.extname(t)||`.js`);return new URL(`./${e.sourceWorkerName}${r}`,e.currentModuleUrl)}function isBunTargetRuntime(e){return e===process.execPath?!!process.versions.bun:isBunRuntime(e)}function resolveRuntimeArgs(e=process.execPath){return isBunTargetRuntime(e)?[`--no-install`]:[]}function runtimeNeedsTypeScriptLoader(e,t=process.execPath){return/\.[cm]?ts$/.test(e)&&!isBunTargetRuntime(t)}function resolveRuntimeWorkerArgv(e,t=process.execPath){let n=s(e);return runtimeNeedsTypeScriptLoader(n,t)?[`--import`,import.meta.resolve(`tsx`),n]:[...resolveRuntimeArgs(t),n]}function resolveRuntimeWorkerEnv(e,t){if(isEmbeddedStandaloneModule(e.href)){let e={...t};return delete e.BUN_BE_BUN,e}return resolveRuntimeScriptEnv(t)}const m=/* @__PURE__ */ new Map;function resolveRuntimeProcessEntrypointUrl(e){return m.get(e)??resolveRuntimeWorkerUrl(p[e])}function expectDefined(e,t){if(e==null)throw Error(`expected `+t+` to be defined`);return e}function stableHomebrewNodePathCandidates(e){let t=e.match(/^(.+?)[\\/]Cellar[\\/]([^\\/]+)[\\/][^\\/]+[\\/]bin[\\/]node$/);if(!t)return[];let n=expectDefined(t[1],`cellar match capture group 1`),r=expectDefined(t[2],`cellar match capture group 2`),i=e.includes(`\\`)?o.win32:o.posix,a=[i.join(n,`opt`,r,`bin`,`node`)];return r===`node`&&a.push(i.join(n,`bin`,`node`)),a}function resolveLaunchableNodePath(e=process.execPath){return r(e)?e:stableHomebrewNodePathCandidates(e).find(r)??e}function readProperty(e,t){try{return e[t]}catch{return}}function extractErrorCode(e){if(!e||typeof e!=`object`)return;let t=readProperty(e,`code`);return typeof t==`string`||typeof t==`number`?String(t):void 0}function isOwnedProcessGroupGone(e){try{return process.kill(-e,0),!1}catch(e){let t=extractErrorCode(e);if(t===`ESRCH`)return!0;if(t===`EPERM`)return!1;throw e}}function setStdioEntry(e,t,n){for(;e.length<=t;)e.push(`ignore`);e[t]=n}function reserveStdioEntry(e,t){let n=3;for(;e[n]!==void 0&&e[n]!==`ignore`;)n+=1;return setStdioEntry(e,n,t),n}function runServiceChildRelay(){let r,i,o=!1,s,c,l=[],u=!1,report=e=>{if(process.connected)try{process.send?.(e,()=>{})}catch{}},settleAnchorExit=()=>{c&&u&&(process.exitCode=c.code===0||c.signal===`SIGKILL`?0:1,process.connected&&process.disconnect?.())},releaseParentLineage=async()=>{if(l.length>0){let e=!1;for(;;){try{if(isOwnedProcessGroupGone(i.pid))break}catch(t){e||(e=!0,report({type:`relay-error`,generation:r,error:t instanceof Error?t.message:String(t)}))}await a(100)}for(let e of l)t(e);l=[]}u=!0,settleAnchorExit()},notifyParentLoss=()=>{o||(o=!0,c?settleAnchorExit():i?.connected&&i.send({type:`parent-loss`,generation:r}))};process.once(`disconnect`,notifyParentLoss),process.on(`SIGTERM`,notifyParentLoss),process.on(`SIGINT`,notifyParentLoss),process.on(`message`,a=>{let u=a;if(u?.type===`cancel`){if(!r||!i||u.generation!==r||u.signal!==`SIGKILL`||!Number.isSafeInteger(u.sequence)||u.sequence<=0||s!==void 0)return;if(s=u.sequence,!c)try{if(!i.kill(`SIGKILL`))throw Error(`retained anchor SIGKILL was not delivered`)}catch(e){report({type:`relay-error`,generation:r,error:e instanceof Error?e.message:String(e)})}return}if(r)return;if(!u||u.type!==`start`&&u.type!==`prepare`||!u.generation){process.exitCode=1;return}if(r=u.generation,u.controlFd===void 0){report({type:`relay-error`,generation:r,error:`service child control fd is missing`}),process.exitCode=1;return}let d=u.nativeProcessOwner?new URL(u.nativeProcessOwner):resolveRuntimeProcessEntrypointUrl(`serviceChildGroupAnchor`),f=[`inherit`,`inherit`,`inherit`];l=u.parentLineageFds??[];for(let e of[u.controlFd,u.lineageFd,...l,u.secretFd])e!==void 0&&setStdioEntry(f,e,e);reserveStdioEntry(f,`ipc`);try{let t=resolveLaunchableNodePath(),n=resolveRuntimeWorkerEnv(d,process.env);n.NODE_OPTIONS!==void 0&&(n.NODE_OPTIONS=stripNodeStartupHooks(n.NODE_OPTIONS)),u.nativeProcessOwner&&delete n.BUN_BE_BUN,i=e(t,resolveRuntimeWorkerArgv(d,t),{stdio:f,detached:!0,windowsHide:!0,env:n})}catch(e){report({type:`relay-error`,generation:r,error:e instanceof Error?e.message:String(e)}),process.exitCode=1;return}i.connected?(i.once(`spawn`,()=>{if(t(u.controlFd),u.lineageFd!==void 0&&t(u.lineageFd),process.versions.bun)for(let e of[1,2]){let t=n(``,{fd:e,autoClose:!0});t.once(`error`,e=>{report({type:`relay-error`,generation:u.generation,error:e.message}),notifyParentLoss()}),t.end()}else process.stdout.destroy(),process.stderr.destroy();i?.send(u),o&&i?.send({type:`parent-loss`,generation:r})}),i.once(`error`,e=>{report({type:`relay-error`,generation:r,error:e.message})}),i.once(`exit`,(e,t)=>{c={code:e,signal:t},releaseParentLineage().catch(e=>{report({type:`relay-error`,generation:r,error:e instanceof Error?e.message:String(e)})})})):(report({type:`relay-error`,generation:r,error:`anchor lifecycle IPC was not created`}),i.kill(`SIGKILL`),process.exitCode=1)})}runServiceChildRelay();export{};