Repository navigation
Expand file tree
/
Copy pathruntime-process-scripts.generated.mjs
More file actions
64 lines (64 loc) 路 29.6 KB
/
Copy pathruntime-process-scripts.generated.mjs
File metadata and controls
64 lines (64 loc) 路 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Generated by scripts/generate-runtime-script-assets.mjs; do not edit.
/* oxlint-disable no-var -- esbuild owns variable declarations in this generated bundle. */
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
function materializeRuntimeProcessScriptFile(entry, options = {}) {
const directory = fs.mkdtempSync(
path.join(options.parentDirectory ?? os.tmpdir(), "openclaw-script-"),
);
const filename = path.join(directory, entry.fileName);
let disposed = false;
const dispose = () => {
if (disposed) {
return;
}
try {
fs.rmSync(directory, { recursive: true, force: true });
disposed = true;
} catch (error) {
process.emitWarning(
`Runtime script cleanup failed at ${directory}: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
try {
fs.writeFileSync(filename, entry.source, { mode: 384, flag: "wx" });
return { url: pathToFileURL(filename), dispose };
} catch (error) {
dispose();
throw error;
}
}
var scripts = {
bunSqliteLibraryProbe: {
fileName: "bun-sqlite-library-probe.mjs",
source: `import{createRequire}from"node:module";try{const candidate=process.argv[2];if(!candidate||process.argv.length!==3){throw new Error("Expected one SQLite library path")}const require2=createRequire(import.meta.url);const{Database}=require2("bun:sqlite");Database.setCustomSQLite(candidate);const database=new Database(":memory:");let facts;try{facts=database.query("SELECT sqlite_version() AS version, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted").get()}finally{database.close()}process.stdout.write(JSON.stringify({protocol:1,version:facts.version,extensionLoadingSupported:facts.omitted===0}))}catch(error){process.stdout.write(JSON.stringify({protocol:1,error:(error instanceof Error?error.message:String(error)).slice(0,512)}));process.exitCode=1}
`,
},
packageCliNodeProbe: {
fileName: "package-cli-node-probe.mjs",
source:
"process.stdout.write(JSON.stringify({version:process.versions.node??null,bunVersion:process.versions.bun??null,execPath:process.execPath??null}));\n",
},
nodeRuntimeProbe: {
fileName: "node-runtime-probe.mjs",
source:
'import process from"node:process";var requiredFlag=process.argv[2];process.stdout.write(!process.versions.bun&&(!requiredFlag||process.allowedNodeEnvironmentFlags.has(requiredFlag))?process.execPath:"");\n',
},
daemonRuntimeProbe: {
fileName: "daemon-runtime-probe.mjs",
source:
'var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res,err)=>function __init(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var GATEWAY_SHUTDOWN_DRAIN_TIMEOUT_MS,GATEWAY_SHUTDOWN_RESERVE_MS,GATEWAY_SUPERVISOR_EXIT_MARGIN_MS,GATEWAY_SHUTDOWN_TIMEOUT_MS,GATEWAY_SERVICE_STOP_TIMEOUT_MS,LAUNCH_AGENT_EXIT_TIMEOUT_SECONDS;var init_gateway_shutdown_budget=__esm({"gateway-shutdown-budget.mjs"(){"use strict";GATEWAY_SHUTDOWN_DRAIN_TIMEOUT_MS=315e3;GATEWAY_SHUTDOWN_RESERVE_MS=1e4;GATEWAY_SUPERVISOR_EXIT_MARGIN_MS=5e3;GATEWAY_SHUTDOWN_TIMEOUT_MS=GATEWAY_SHUTDOWN_DRAIN_TIMEOUT_MS+GATEWAY_SHUTDOWN_RESERVE_MS;GATEWAY_SERVICE_STOP_TIMEOUT_MS=GATEWAY_SHUTDOWN_TIMEOUT_MS+GATEWAY_SUPERVISOR_EXIT_MARGIN_MS;LAUNCH_AGENT_EXIT_TIMEOUT_SECONDS=GATEWAY_SERVICE_STOP_TIMEOUT_MS/1e3}});var parentKey,CLI_RESPAWN_PARENT_ENV,inheritedParent,CLI_PARENT_BOUND_PRELOAD;var init_cli_parent_lifetime=__esm({"cli-parent-lifetime.mjs"(){"use strict";init_gateway_shutdown_budget();parentKey=Symbol.for("openclaw.cliRespawnParent");CLI_RESPAWN_PARENT_ENV="OPENCLAW_CLI_RESPAWN_PARENT";inheritedParent=process.env[CLI_RESPAWN_PARENT_ENV];delete process.env[CLI_RESPAWN_PARENT_ENV];if(inheritedParent===String(process.ppid)){globalThis[parentKey]={pid:process.ppid}}CLI_PARENT_BOUND_PRELOAD=`data:text/javascript,${encodeURIComponent(`\n globalThis[Symbol.for("openclaw.cliRespawnParent")] = { pid: process.ppid };\n process.execArgv = process.execArgv.filter((arg, index, args) =>\n arg !== import.meta.url && !(arg === "--import" && args[index + 1] === import.meta.url));\n`)}`}});var init_node_runtime_env=__esm({"node-runtime-env.mjs"(){"use strict"}});import{readFileSync}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";function readStandaloneRuntimeManifest(executable=process.execPath){return readStandaloneManifest({executable})}function projectStandaloneBuildInfo(value){const nonBlank=text=>typeof text==="string"&&text.trim().length>0;const stringList=items=>Array.isArray(items)&&items.every(nonBlank);const result={mode:value.mode,openclaw:{version:value.openclaw.version,...nonBlank(value.openclaw.commit)?{commit:value.openclaw.commit}:{}},bun:{version:value.bun.version}};for(const key of["revision","commit","executableSha256"]){if(nonBlank(value.bun[key])){result.bun[key]=value.bun[key]}}if(value.build!==void 0){const{id,flavor,pluginSetSha256,moduleGraphSha256}=value.build;if(!nonBlank(id)||!["standard","support"].includes(flavor)||!/^[a-f0-9]{64}$/.test(pluginSetSha256)||!/^[a-f0-9]{64}$/.test(moduleGraphSha256)){throw new Error("Invalid standalone build provenance")}result.build={id,flavor,pluginSetSha256,moduleGraphSha256};if(value.build.debugEntry!==void 0){const entry=value.build.debugEntry;if(typeof entry!=="string"||!entry.startsWith("debug/")||entry.includes("\\\\")||entry.split("/").some(part=>!part||part==="."||part==="..")){throw new Error("Invalid standalone debugger entry")}result.build.debugEntry=entry}}if(value.target!==void 0){if(!nonBlank(value.target.platform)||!nonBlank(value.target.arch)){throw new Error("Invalid standalone build target")}result.target={platform:value.target.platform,arch:value.target.arch}}if(value.plugins!==void 0){if(!stringList(value.plugins.embedded)||!stringList(value.plugins.omitted)){throw new Error("Invalid standalone plugin inventory")}result.plugins={embedded:[...value.plugins.embedded],omitted:[...value.plugins.omitted]}}if(value.nativeModules!==void 0){if(!Array.isArray(value.nativeModules)||value.nativeModules.some(item=>!item||!nonBlank(item.name)||!nonBlank(item.version)||!stringList(item.artifacts)||item.qualification!=="unverified"||!nonBlank(item.backend))){throw new Error("Invalid standalone native inventory")}result.nativeModules=value.nativeModules.map(({name,version,artifacts,qualification,backend})=>({name,version,artifacts:[...artifacts],qualification,backend}))}return result}function readStandaloneManifest({executable,runtimeRoot,includeBuild=false}){const location=executable??runtimeRoot;if(!path.isAbsolute(location)){return void 0}const root=path.dirname(location);const manifestPath=path.join(root,"manifest.json");let raw;try{raw=readFileSync(manifestPath,"utf8")}catch(error){if(error?.code==="ENOENT"||error?.code==="ENOTDIR"){return void 0}throw error}let manifest;try{manifest=JSON.parse(raw)}catch(cause){throw new Error(`Invalid standalone runtime manifest: ${manifestPath}`,{cause})}const nonBlank=value=>typeof value==="string"&&value.trim().length>0;if(manifest?.schemaVersion!==1||!["jit","bytecode","aot"].includes(manifest.mode)||!nonBlank(manifest.executable?.path)||!nonBlank(manifest.runtime?.path)||!nonBlank(manifest.openclaw?.version)||!nonBlank(manifest.bun?.version)){throw new Error(`Invalid standalone runtime manifest: ${manifestPath}`)}const executableRelative=path.relative(root,path.resolve(root,manifest.executable.path));const sidecarRelative=path.relative(root,path.resolve(root,manifest.runtime.path));if(path.isAbsolute(manifest.executable.path)||!executableRelative||executableRelative===".."||executableRelative.startsWith(`..${path.sep}`)||executable&&path.resolve(root,manifest.executable.path)!==path.resolve(executable)||runtimeRoot&&path.resolve(root,manifest.runtime.path)!==path.resolve(runtimeRoot)||path.isAbsolute(manifest.runtime.path)||!sidecarRelative||sidecarRelative===".."||sidecarRelative.startsWith(`..${path.sep}`)){throw new Error(`Invalid standalone runtime manifest: ${manifestPath}`)}return{schemaVersion:1,mode:manifest.mode,executable:{path:manifest.executable.path,...nonBlank(manifest.executable.sha256)?{sha256:manifest.executable.sha256}:{}},runtime:{path:manifest.runtime.path,...nonBlank(manifest.runtime.sha256)?{sha256:manifest.runtime.sha256}:{}},openclaw:{version:manifest.openclaw.version,...nonBlank(manifest.openclaw.commit)?{commit:manifest.openclaw.commit}:{}},bun:{version:manifest.bun.version},...includeBuild?projectStandaloneBuildInfo(manifest):{}}}function getEmbeddedStandaloneRuntimeRoot(){const rootUrl=globalThis.__openclawStandaloneRootUrl;return typeof rootUrl==="string"?fileURLToPath(rootUrl):void 0}function resolveStandaloneSidecarRoot(executable=process.execPath){if(executable===process.execPath){const embeddedRoot=getEmbeddedStandaloneRuntimeRoot();if(embeddedRoot!==void 0){return embeddedRoot}}const manifest=readStandaloneRuntimeManifest(executable);return manifest?path.resolve(path.dirname(executable),manifest.runtime.path):void 0}function isStandaloneRuntimeExecutable(executable=process.execPath){return resolveStandaloneSidecarRoot(executable)!==void 0}function resolveRuntimeScriptEnv(env){return isStandaloneRuntimeExecutable()?{...env,BUN_BE_BUN:"1"}:{...env}}var init_cli_invocation=__esm({"cli-invocation.mjs"(){"use strict";init_cli_parent_lifetime();init_node_runtime_env()}});function pluginRuntimeProcess(plugin,owner,worker){return{plugin,ownerSource:`extensions/${plugin}/${owner}.ts`,sourceWorkerName:worker,distWorkerPath:`extensions/${plugin}/${worker}.js`,package:{name:`@openclaw/${plugin}`,distWorkerPath:`${worker}.js`}}}var pluginRuntimeProcessManifest,runtimeProcessScriptEntrypoints;var init_runtime_process_manifest=__esm({"src/infra/runtime-process-manifest.ts"(){"use strict";pluginRuntimeProcessManifest={browserNativeHost:{...pluginRuntimeProcess("browser","native-host-entry","native-host-entry"),package:{name:"@openclaw/browser-plugin",distWorkerPath:"native-host-entry.js"}},browserRelayDaemon:{...pluginRuntimeProcess("browser","native-host-entry","relay-daemon-entry"),package:{name:"@openclaw/browser-plugin",distWorkerPath:"relay-daemon-entry.js"}},browserSetup:{...pluginRuntimeProcess("browser","setup-entry","setup-entry"),package:{name:"@openclaw/browser-plugin",distWorkerPath:"setup-entry.js"}},quickJsCodeMode:{...pluginRuntimeProcess("code-mode-quickjs","src/executor","src/code-mode.worker"),sourceWorkerName:"code-mode.worker"},codexCatalogPage:pluginRuntimeProcess("codex","catalog-page-worker-entrypoint","catalog-page.worker"),codexSessionHistory:pluginRuntimeProcess("codex","session-history-worker-entrypoint","session-history.worker"),discordAudio:{...pluginRuntimeProcess("discord","src/voice/audio-worker-thread","src/voice/audio-worker.runtime"),sourceWorkerName:"audio-worker.runtime"},documentExtractor:{...pluginRuntimeProcess("document-extract","document-extractor-worker-entrypoint","document-extractor.worker"),package:{name:"@openclaw/document-extract-plugin",distWorkerPath:"document-extractor.worker.js"}},fileTransferDirFetch:{plugin:"file-transfer",ownerSource:"extensions/file-transfer/src/node-host/dir-fetch-archive.ts",sourceWorkerName:"dir-fetch-archive.worker",distWorkerPath:"extensions/file-transfer/src/node-host/dir-fetch-archive.worker.js",package:{name:"@openclaw/file-transfer",distWorkerPath:"src/node-host/dir-fetch-archive.worker.js"}},fileTransferDirList:{plugin:"file-transfer",ownerSource:"extensions/file-transfer/src/node-host/dir-list-worker-command.ts",sourceWorkerName:"dir-list.worker",distWorkerPath:"extensions/file-transfer/src/node-host/dir-list.worker.js",package:{name:"@openclaw/file-transfer",distWorkerPath:"src/node-host/dir-list.worker.js"}},iMessageChatDb:{...pluginRuntimeProcess("imessage","src/chat-db","src/chat-db.worker"),sourceWorkerName:"chat-db.worker"},knowledgeRegistry:{...pluginRuntimeProcess("knowledge","src/registry-client","src/registry-worker"),sourceWorkerName:"registry-worker"},knowledgeStorage:{...pluginRuntimeProcess("knowledge","src/storage-client","src/storage-worker"),sourceWorkerName:"storage-worker"},mxcLauncher:{plugin:"mxc",ownerSource:"extensions/mxc/src/plugin-root.ts",sourceWorkerName:"mxc-spawn-launcher",sourceExtension:".mjs",build:"static-asset",distWorkerPath:"extensions/mxc/mxc-spawn-launcher.mjs",package:{name:"@openclaw/mxc-sandbox",distWorkerPath:"mxc-spawn-launcher.mjs"}},onePasswordSecretResolver:{plugin:"onepassword",ownerSource:"extensions/onepassword/onepassword-secret-ref-resolver.js",sourceWorkerName:"onepassword-secret-ref-resolver",sourceExtension:".js",build:"static-asset",distWorkerPath:"extensions/onepassword/onepassword-secret-ref-resolver.js",package:{name:"@openclaw/onepassword",distWorkerPath:"onepassword-secret-ref-resolver.js"}},vaultSecretResolver:{plugin:"vault",ownerSource:"extensions/vault/vault-secret-ref-resolver.js",sourceWorkerName:"vault-secret-ref-resolver",sourceExtension:".js",build:"static-asset",distWorkerPath:"extensions/vault/vault-secret-ref-resolver.js",package:{name:"@openclaw/vault",distWorkerPath:"vault-secret-ref-resolver.js"}},memorySearch:{...pluginRuntimeProcess("memory-core","src/memory/manager-cpu-entrypoints","src/memory/manager-search.worker"),sourceWorkerName:"manager-search.worker",distWorkerPath:"extensions/memory-core/memory-search.worker.js"},memoryIndex:{...pluginRuntimeProcess("memory-core","src/memory/manager-cpu-entrypoints","src/memory/manager-index.worker"),sourceWorkerName:"manager-index.worker",distWorkerPath:"extensions/memory-core/memory-index.worker.js"},memoryPublication:{...pluginRuntimeProcess("memory-core","src/memory/manager-cpu-entrypoints","src/memory/manager-publication.worker"),sourceWorkerName:"manager-publication.worker",distWorkerPath:"extensions/memory-core/memory-publication.worker.js"},memoryStandingIntents:{...pluginRuntimeProcess("memory-core","src/memory/manager-cpu-entrypoints","src/standing-intents.worker"),sourceWorkerName:"../standing-intents.worker",distWorkerPath:"extensions/memory-core/standing-intents.worker.js"},memoryEntryOrigins:{...pluginRuntimeProcess("memory-core","src/memory/manager-cpu-entrypoints","src/memory-entry-origins.worker"),sourceWorkerName:"../memory-entry-origins.worker",distWorkerPath:"extensions/memory-core/memory-entry-origins.worker.js"},memoryStatsRuntime:pluginRuntimeProcess("memory-lancedb","memory-stats-entrypoint","memory-stats.worker"),memoryWikiQuery:{...pluginRuntimeProcess("memory-wiki","src/query-reader","src/query-reader.worker"),sourceWorkerName:"query-reader.worker"},openAiRealtimeAudio:{...pluginRuntimeProcess("openai","realtime-quicksilver-peer.runtime","realtime-quicksilver-audio.worker"),package:{name:"@openclaw/openai-provider",distWorkerPath:"realtime-quicksilver-audio.worker.js"}},openAiRealtimeSocket:{...pluginRuntimeProcess("openai","realtime-quicksilver-socket","realtime-quicksilver-socket.worker"),package:{name:"@openclaw/openai-provider",distWorkerPath:"realtime-quicksilver-socket.worker.js"}},qaExecutionIdentityInspection:{...pluginRuntimeProcess("qa-lab","src/execution-identity-storage-inspection","src/execution-identity-storage-inspection.worker"),sourceWorkerName:"execution-identity-storage-inspection.worker"},telegramIngress:{...pluginRuntimeProcess("telegram","src/telegram-ingress-worker","src/telegram-ingress-worker.runtime"),sourceWorkerName:"telegram-ingress-worker.runtime",distWorkerPath:"telegram-ingress-worker.runtime.js"},onnxInference:pluginRuntimeProcess("onnx","index","src/inference.worker"),teamReportsStore:pluginRuntimeProcess("team-reports","index","src/store.worker"),teamReportsRun:pluginRuntimeProcess("team-reports","index","src/run.worker"),logbookStore:pluginRuntimeProcess("logbook","index","src/store.worker"),workboardSqlite:pluginRuntimeProcess("workboard","index","src/sqlite-store.worker")};runtimeProcessScriptEntrypoints={bunSqliteLibraryProbe:{buildSource:"src/infra/bun-sqlite-library-probe.entry.ts",sourceModule:"src/infra/bun-sqlite-library-probe.generated.ts",sourceBinding:"BUN_SQLITE_LIBRARY_PROBE_SOURCE",kind:"file",fileName:"bun-sqlite-library-probe.mjs",materialize:true},packageCliNodeProbe:{buildSource:"scripts/lib/package-cli-node-probe.entry.mjs",sourceModule:"scripts/lib/package-cli-node-probe.generated.mjs",sourceBinding:"PACKAGE_CLI_NODE_PROBE_SOURCE",kind:"file",fileName:"package-cli-node-probe.mjs",materialize:true},fsSafeNpmCliPreload:{buildSource:"scripts/lib/fs-safe-npm-cli-preload.entry.mjs",sourceModule:"scripts/lib/fs-safe-npm-cli-preload.generated.mjs",sourceBinding:"FS_SAFE_NPM_CLI_PRELOAD_DATA_URL",kind:"data-url"},repositoryPublicationRestoreRemote:{sourceModule:"src/gateway/github-repository-publication-restore.ts",sourceBinding:"RESTORE_PUBLICATION_INDEX_JS",kind:"source"},nodeRuntimeProbe:{buildSource:"src/infra/node-runtime-probe.entry.ts",sourceModule:"src/infra/node-runtime-probe.generated.mjs",sourceBinding:"NODE_RUNTIME_PROBE_SOURCE",kind:"file",fileName:"node-runtime-probe.mjs",materialize:true},daemonRuntimeProbe:{buildSource:"src/infra/daemon-runtime-probe.entry.ts",sourceModule:"src/infra/daemon-runtime-probe.generated.mjs",sourceBinding:"DAEMON_RUNTIME_PROBE_SOURCE",kind:"file",fileName:"daemon-runtime-probe.mjs",materialize:true,runtimeEntrypoint:"daemonRuntimeProbe"},updateStateSizes:{sourceModule:"src/infra/update-state-sizes.generated.mjs",sourceBinding:"UPDATE_STATE_SIZES_SOURCE",kind:"file",fileName:"update-state-sizes.mjs",materialize:true,runtimeEntrypoint:"updateStateSizes"},updateNativeGate:{sourceModule:"src/cli/update-cli/update-command-native-gate.generated.ts",sourceBinding:"UPDATE_NATIVE_GATE_SOURCE",kind:"file",fileName:"update-native-gate.mjs"},managedUpdateHandoff:{sourceModule:"src/infra/update-managed-service-handoff.ts",sourceBinding:"HANDOFF_SCRIPT",kind:"file",fileName:"handoff.cjs"},workspaceQuiescence:{sourceModule:"src/gateway/worker-environments/workspace-quiescence-scripts.ts",export:"workspaceQuiescenceArgv",kind:"argv"}}}});import path4 from"node:path";function probeSqlite(DatabaseSync){const result={available:false,version:null,text:false,blob:false,json:false};let database;try{database=new DatabaseSync(":memory:");result.available=true;const text="a\\0b\\0";const bytes=Buffer.from(text,"utf8");const json=JSON.stringify({value:text});database.exec("CREATE TABLE probe (text_value TEXT, blob_value BLOB, json_value TEXT)");database.prepare("INSERT INTO probe VALUES (?, ?, ?)").run(text,bytes,json);const row=database.prepare("SELECT sqlite_version() AS version, text_value, blob_value, json_value FROM probe").get();result.version=typeof row?.version==="string"?row.version:null;result.text=typeof row?.text_value==="string"&&row.text_value.length===text.length&&Buffer.from(row.text_value,"utf8").equals(bytes);result.blob=row?.blob_value instanceof Uint8Array&&Buffer.from(row.blob_value).equals(bytes);result.json=row?.json_value===json&&JSON.parse(row.json_value).value===text}catch(error){let failure=error;if(database&&result.version===null){try{const version=database.prepare("SELECT sqlite_version() AS version").get()?.version;result.version=typeof version==="string"?version:null}catch(versionError){failure=versionError}}result.error=failure instanceof Error?failure.message:String(failure)}finally{database?.close()}return result}function isSqliteWalResetSafeVersion(value){const match=/^(\\d+)\\.(\\d+)\\.(\\d+)$/u.exec(value.trim());if(!match){return false}const[major,minor,patch]=match.slice(1).map(Number);if(![major,minor,patch].every(Number.isSafeInteger)){return false}return major>3||major===3&&(minor>51||minor===51&&patch>=3||minor===50&&patch>=7||minor===44&&patch>=6)}init_cli_invocation();import{existsSync}from"node:fs";import{createRequire}from"node:module";import{posix}from"node:path";import{getEnvironmentData,isMainThread,setEnvironmentData}from"node:worker_threads";var GLOBAL_SINGLETON_RESETS_KEY=Symbol.for("openclaw.globalSingletonLifecycleResets");function resolveGlobalSingletonResetRegistry(){const globalStore=globalThis;const existing=globalStore[GLOBAL_SINGLETON_RESETS_KEY];if(existing instanceof Map){return existing}const created=new Map;globalStore[GLOBAL_SINGLETON_RESETS_KEY]=created;return created}function resolveGlobalSingleton(key,create,reset,lifecycle="close-and-restart"){const globalStore=globalThis;let value;if(Object.hasOwn(globalStore,key)){value=globalStore[key]}else{value=create();globalStore[key]=value}if(reset){resolveGlobalSingletonResetRegistry().set(key,{lifecycle,reset:()=>reset(value)})}return value}init_cli_invocation();import{spawnSync}from"node:child_process";import fs2 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var BUN_SQLITE_LIBRARY_PROBE_SOURCE=`import{createRequire}from"node:module";try{const candidate=process.argv[2];if(!candidate||process.argv.length!==3){throw new Error("Expected one SQLite library path")}const require2=createRequire(import.meta.url);const{Database}=require2("bun:sqlite");Database.setCustomSQLite(candidate);const database=new Database(":memory:");let facts;try{facts=database.query("SELECT sqlite_version() AS version, sqlite_compileoption_used(\'OMIT_LOAD_EXTENSION\') AS omitted").get()}finally{database.close()}process.stdout.write(JSON.stringify({protocol:1,version:facts.version,extensionLoadingSupported:facts.omitted===0}))}catch(error){process.stdout.write(JSON.stringify({protocol:1,error:(error instanceof Error?error.message:String(error)).slice(0,512)}));process.exitCode=1}\n`;init_runtime_process_manifest();import fs from"node:fs";import os from"node:os";import path2 from"node:path";import{pathToFileURL}from"node:url";function materializeRuntimeProcessScriptFile(entry,options={}){const directory=fs.mkdtempSync(path2.join(options.parentDirectory??os.tmpdir(),"openclaw-script-"));const filename=path2.join(directory,entry.fileName);let disposed=false;const dispose=()=>{if(disposed){return}try{fs.rmSync(directory,{recursive:true,force:true});disposed=true}catch(error){process.emitWarning(`Runtime script cleanup failed at ${directory}: ${error instanceof Error?error.message:String(error)}`)}};try{fs.writeFileSync(filename,entry.source,{mode:384,flag:"wx"});return{url:pathToFileURL(filename),dispose}}catch(error){dispose();throw error}}function probeBunSqliteLibrary(candidate){const script=materializeRuntimeProcessScriptFile({fileName:runtimeProcessScriptEntrypoints.bunSqliteLibraryProbe.fileName,source:BUN_SQLITE_LIBRARY_PROBE_SOURCE});try{const scriptPath=fileURLToPath2(script.url);const directory=path3.dirname(scriptPath);const configPath=path3.join(directory,"bunfig.toml");fs2.writeFileSync(configPath,"",{mode:384,flag:"wx"});const env={};for(const key of["SystemRoot","SYSTEMROOT","WINDIR","TEMP","TMP","TMPDIR"]){if(process.env[key]){env[key]=process.env[key]}}const result=spawnSync(process.execPath,["--no-install","--no-env-file",`--config=${configPath}`,scriptPath,path3.resolve(candidate)],{cwd:directory,env:resolveRuntimeScriptEnv(env),encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:5e3,killSignal:"SIGKILL",maxBuffer:4096});if(result.error){throw result.error}let facts;try{facts=JSON.parse(result.stdout)}catch{throw new Error("SQLite library probe returned invalid output")}if(typeof facts!=="object"||facts===null||Array.isArray(facts)||!("protocol"in facts)||facts.protocol!==1){throw new Error("SQLite library probe returned invalid output")}if(result.status!==0){throw new Error("error"in facts&&typeof facts.error==="string"?facts.error.slice(0,512):`SQLite library probe failed (${result.signal??result.status})`)}if(!("version"in facts)||typeof facts.version!=="string"||facts.version.length>64||!("extensionLoadingSupported"in facts)||typeof facts.extensionLoadingSupported!=="boolean"){throw new Error("SQLite library probe returned invalid output")}return{version:facts.version,extensionLoadingSupported:facts.extensionLoadingSupported}}finally{script.dispose()}}var WORKER_SELECTION_KEY="openclaw.bunSqliteLibrarySelection";function selectLibrary(path5){const require2=createRequire(import.meta.url);const{Database}=require2("bun:sqlite");Database.setCustomSQLite(path5)}function createSelector(){let selection;let failure;return(options={})=>{if(failure){throw failure}if(selection){return selection}const override=options.explicitPath??(process.env.OPENCLAW_SQLITE_LIBRARY?.trim()||void 0);if(!process.versions.bun||process.platform!=="darwin"){selection=override?{source:"runtime",ignoredOverride:"OPENCLAW_SQLITE_LIBRARY requires Bun on macOS"}:{source:"runtime"};return selection}const standaloneRoot=options.standaloneRoot??resolveStandaloneSidecarRoot();const bundled=override===void 0&&standaloneRoot!==void 0?posix.join(standaloneRoot,"lib/libsqlite3.dylib"):void 0;const prefix=process.env.HOMEBREW_PREFIX?.trim();const candidates=override!==void 0?[override]:[...new Set([...bundled?[bundled]:[],...prefix?[posix.join(prefix,"opt/sqlite/lib/libsqlite3.dylib")]:[],"/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/opt/local/lib/libsqlite3.dylib"])];const unusable=[];for(const path5 of candidates){const source=override!==void 0?"env":path5===bundled?"bundled":"discovered";let probe;let present=true;try{try{probe=probeBunSqliteLibrary(path5)}catch(error){present=existsSync(path5);throw present?error:new Error("missing file",{cause:error})}if(!isSqliteWalResetSafeVersion(probe.version)){throw new Error(`SQLite version ${probe.version} below the WAL safety floor`)}if(!probe.extensionLoadingSupported){throw new Error("built with SQLITE_OMIT_LOAD_EXTENSION")}}catch(error){if(override===void 0){if(present||path5===bundled){unusable.push(`${path5} (${error instanceof Error?error.message:String(error)})`)}continue}failure=selectionError(path5,error,source==="bundled");throw failure}try{selectLibrary(path5)}catch(error){failure=selectionError(path5,error,source==="bundled");throw failure}selection={source,path:path5,version:probe.version,extensionLoadingSupported:true};return selection}failure=new Error(`No supported SQLite library for Bun on macOS (${process.arch})`+(unusable.length>0?`; unusable: ${unusable.join(", ")}`:"")+". Apple\'s system SQLite fails OpenClaw\'s read-only database connections. "+(bundled?"Rebuild or replace the complete standalone artifact to restore its bundled SQLite library. ":"")+`Install one with brew install sqlite, or set OPENCLAW_SQLITE_LIBRARY to a libsqlite3.dylib built for ${process.arch}.`);throw failure}}function selectionError(path5,error,bundled=false){const guidance=bundled?"Rebuild or replace the complete standalone artifact (openclaw and runtime/), or set OPENCLAW_SQLITE_LIBRARY to a supported library.":"Fix or unset OPENCLAW_SQLITE_LIBRARY; install a supported library with brew install sqlite.";return new Error(`Cannot use ${bundled?"bundled ":""}SQLite library ${path5}: ${error instanceof Error?error.message:String(error)}. ${guidance}`,{cause:error})}function createRuntimeSelector(){const isBun=Boolean(process.versions.bun);const sharedLibrary=isBun&&process.platform==="darwin";let inherited;if(sharedLibrary&&!isMainThread){inherited=getEnvironmentData(WORKER_SELECTION_KEY)}const select=createSelector();let published=false;return options=>{const selection=inherited??select(options);if(sharedLibrary&&isMainThread&&!published){setEnvironmentData(WORKER_SELECTION_KEY,Object.freeze({...selection}));published=true}return selection}}function runtimeSelector(){return resolveGlobalSingleton(Symbol.for("openclaw.bunSqliteLibrarySelection"),createRuntimeSelector)}function ensureSqliteLibrarySelected(options){return runtimeSelector()(options)}async function readRuntimeProbeInfo(runtime,standaloneRoot){let sqliteVersion=null;let sqliteSelectionError=null;let sqliteLibraryPath=null;let sqliteProbe={available:false,version:null,text:false,blob:false,json:false};if(runtime==="bun"){try{const selection=ensureSqliteLibrarySelected({standaloneRoot});if("path"in selection){sqliteLibraryPath=path4.resolve(selection.path)}}catch(error){sqliteSelectionError=error instanceof Error?error.message:String(error)}}if(sqliteSelectionError===null){try{const{DatabaseSync}=await import("node:sqlite");sqliteProbe=probeSqlite(DatabaseSync);sqliteVersion=sqliteProbe.version}catch{}}const variables=process.config?.variables;const sharedSqlite=variables?.node_shared_sqlite;const nodeSharedSqlite=sharedSqlite===true||sharedSqlite==="true";return{nodeVersion:process.versions.node,bunVersion:process.versions.bun??null,sqliteVersion,sqliteProbe,sqliteSelectionError,sqliteLibraryPath,nodeSharedSqlite}}process.stdout.write(JSON.stringify(await readRuntimeProbeInfo(process.argv[2]==="bun"?"bun":"node",process.argv[3]||void 0)));\n',
},
updateStateSizes: {
fileName: "update-state-sizes.mjs",
source:
'import fs from"node:fs";function isNodeError(value){return Boolean(value&&typeof value==="object"&&"code"in value)}function hasNodeErrorCode(value,code){return isNodeError(value)&&value.code===code}var UPDATE_STATE_INSPECTION_PROGRESS_PREFIX="State schema progress: ";var input="";process.stdin.setEncoding("utf8");process.stdin.on("data",chunk=>{input+=chunk});process.stdin.on("end",()=>{const{files}=JSON.parse(input);const result=[];const progress=pathname=>{try{fs.writeSync(2,UPDATE_STATE_INSPECTION_PROGRESS_PREFIX+JSON.stringify({phase:"metadata inventory",path:pathname})+"\\n")}catch(error){if(!hasNodeErrorCode(error,"EAGAIN")&&!hasNodeErrorCode(error,"EWOULDBLOCK")){throw error}}};for(const file of files){let size;progress(file);try{size=fs.statSync(file,{bigint:true}).size}catch(error){if(!hasNodeErrorCode(error,"ENOENT")){result.push({path:file})}continue}for(const suffix of["-wal","-shm","-journal"]){progress(file+suffix);try{size+=fs.statSync(file+suffix,{bigint:true}).size}catch(error){if(!hasNodeErrorCode(error,"ENOENT")){size=void 0;break}}}result.push({path:file,sizeBytes:size?.toString()})}process.stdout.write(JSON.stringify(result))});\n',
},
};
function createRuntimeProcessScriptFile(name, options) {
return materializeRuntimeProcessScriptFile(scripts[name], options);
}
export { createRuntimeProcessScriptFile };