openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
369 lines (368 loc) • 14.9 kB
JavaScript
#!/usr/bin/env node
import { c as resolveOpenClawCliRespawn, h as watchCliRespawnParent, s as resolveOpenClawCliInvocation } from "./cli-invocation-ZSPsKRWa.mjs";
import { n as resolveOpenClawCompileCacheDirectory, r as resolveOpenClawCompileCacheRespawnEnv, t as enableOpenClawCompileCache$1 } from "./node-compile-cache-BodUgF6I.mjs";
import { u as isRootHelpInvocation } from "./argv-CbnKpH-r.mjs";
import { r as isForegroundGatewayRunArgv } from "./gateway-run-argv-DfcBAs2-.mjs";
import { t as resolveCliArgvInvocation } from "./argv-invocation-C9SmXUsh.mjs";
import { t as resolveCliDatabaseProcessRole } from "./database-process-role-MptgTPr9.mjs";
import { i as shouldKeepNativeHookRelayInProcess, n as isNativeHookRelayArgv, r as isTerminalInteractiveRespawnArgv, t as isForegroundGmailRunArgv } from "./respawn-policy-LFXoiOm5.mjs";
import { l as fsSafeEnvInput, r as normalizeEnv } from "./env-HehwidXj.mjs";
import { n as parseCliProfileArgs, t as applyCliProfileEnv } from "./profile-TAKKDhQt.mjs";
import { n as tryRunUpdateAdmissionBeforeStartup, t as isUpdateAdmissionInvocation } from "./run-main-update-admission-2cBv_sw3.mjs";
import "./detached-async-context-D_mi-wUl.mjs";
import { i as createGatewayDispatchStartupTrace, n as configureGatewayStartupTraceConsoleFormatting, s as prepareGatewayStartupTraceConsoleFormatting } from "./startup-trace-DWZsuODq.mjs";
import { t as normalizeWindowsArgv } from "./windows-argv-Co4garuq.mjs";
import { r as installDatabaseProcessRole } from "./admission-scope-DmxaPNhm.mjs";
import { t as isMainModule } from "./is-main-DHs8alyJ.mjs";
import { c as formatErrorStackWithMessage } from "./error-coercion-hDrHOSGy.mjs";
import "./node-runtime-recovery-BDQPyLO8.mjs";
import { n as parseCliContainerArgs, r as resolveCliContainerTarget } from "./container-target-Gm4i9O54.mjs";
import { t as tryOutputPrecomputedCommandHelp } from "./precomputed-help-ENbS88WM.mjs";
import { n as runCliRespawnPlan, r as runRespawnChildWithSignalBridge, t as buildCliRespawnPlan } from "./entry.respawn-_JCiXQZs.mjs";
import { t as tryHandleRootVersionFastPath } from "./entry.version-fast-path-BXwwJjrt.mjs";
import { i as ensureOpenClawExecMarkerOnProcess } from "./openclaw-exec-env-BPYcT7Dr.mjs";
import { t as installProcessWarningFilter } from "./warning-filter-DRoUNq4c.mjs";
import { i as requestNodeHostLauncherBootstrap, n as isNodeHostLauncherChild, t as getManagedNodeHostStatePath } from "./launcher-client-DcylVxuB.mjs";
import { r as defaultRuntime, t as ExitError } from "./runtime-B-SLYP-m.mjs";
import { getCompileCacheDir } from "node:module";
import process from "node:process";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { format as format$1 } from "node:util";
//#region src/entry.compile-cache.ts
const COMPILE_CACHE_DISABLED_RESPAWNED_ENV = "OPENCLAW_COMPILE_CACHE_DISABLED_RESPAWNED";
function resolveEntryInstallRoot(e) {
const t = path.dirname(e);
const n = path.basename(t);
return n === "dist" || n === "src" ? path.dirname(t) : t;
}
function isSourceEntry(e) {
return path.extname(e) === ".ts";
}
function isNodeCompileCacheRequested(e) {
return e.NODE_COMPILE_CACHE !== void 0 && e.NODE_DISABLE_COMPILE_CACHE === void 0;
}
async function respawnWithoutOpenClawCompileCacheIfNeeded(e) {
if (!isSourceEntry(e.currentFile) && isForegroundGatewayRunArgv(process.argv)) {
const t = resolveOpenClawCompileCacheRespawnEnv({
directory: resolveOpenClawCompileCacheDirectory({
installRoot: resolveEntryInstallRoot(e.currentFile),
env: e.env,
foregroundGateway: true
}),
env: e.env,
foregroundGateway: true
});
if (t) {
const { command: n, args: r } = resolveOpenClawCliInvocation({ entryPath: e.currentFile });
if (process.platform !== "win32" && process.execve) process.execve(n, [n, ...r], t);
const { runRespawnedChild: i } = await import("./node-runtime-recovery-DkL1Uw9l.mjs");
return i(resolveOpenClawCliRespawn({
entryPath: e.currentFile,
env: t
}));
}
}
const t = getCompileCacheDir?.();
const n = e.env ?? process.env;
const r = process.argv;
const i = process.platform;
if (i !== "win32" && isForegroundGatewayRunArgv(r)) return false;
if (isForegroundGmailRunArgv(r) || shouldKeepNativeHookRelayInProcess(r, i)) return false;
if (!isSourceEntry(e.currentFile)) return false;
if (n[COMPILE_CACHE_DISABLED_RESPAWNED_ENV] === "1") return false;
if (!t && !isNodeCompileCacheRequested(n)) return false;
const a = {
...n,
NODE_DISABLE_COMPILE_CACHE: "1",
[COMPILE_CACHE_DISABLED_RESPAWNED_ENV]: "1"
};
delete a.NODE_COMPILE_CACHE;
const o = {
...resolveOpenClawCliRespawn({
entryPath: e.currentFile,
args: r.slice(2),
env: a
}),
detachForProcessTree: i !== "win32" && !isTerminalInteractiveRespawnArgv(r)
};
const s = await e.prepareWriteError?.() ?? ((e) => {
process.stderr.write(e);
});
process.exitCode = await runRespawnChildWithSignalBridge({
command: o.command,
args: o.args,
env: o.env,
detachForProcessTree: o.detachForProcessTree,
onError: (e) => s(`[openclaw] Failed to respawn CLI without compile cache: ${e instanceof Error ? formatErrorStackWithMessage(e) : String(e)}\n`)
});
return true;
}
function enableOpenClawCompileCache(e) {
if (!isSourceEntry(e.currentFile)) enableOpenClawCompileCache$1({
directory: resolveOpenClawCompileCacheDirectory({
...e,
foregroundGateway: isForegroundGatewayRunArgv(process.argv)
}),
foregroundGateway: isForegroundGatewayRunArgv(process.argv)
});
}
//#endregion
//#region src/entry.ts
const inheritedRuntimeEnv = { ...process.env };
const ENTRY_WRAPPER_PAIRS = [
{
wrapperBasename: "openclaw.mjs",
entryBasename: "entry.js"
},
{
wrapperBasename: "openclaw.mjs",
entryBasename: "entry.mjs"
},
{
wrapperBasename: "openclaw.js",
entryBasename: "entry.js"
}
];
async function writeCapturedCliArgumentError(e) {
const { loadCliDotEnv: t } = await import("./dotenv-BqC7eRgR.mjs");
t();
await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
const { enableConsoleCapture: n } = await import("./logging-DjenjrNY.mjs");
n();
const [{ formatCliJsonFailure: r }, { isJsonOutputModeActive: i }] = await Promise.all([import("./failure-output-DKniP608.mjs"), import("./json-output-mode-hTr0tmcB.mjs")]);
if (i(process.argv)) defaultRuntime.writeJson(r(e));
console.error(`[openclaw] ${e}`);
}
async function prepareCliDiagnosticBlockWriter() {
const loadWriter = async () => {
const { loadCliDotEnv: e } = await import("./dotenv-BqC7eRgR.mjs");
e();
await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
const { formatConsoleDiagnosticBlock: t } = await import("./json-console-line-CjjM6-5-.mjs");
return (e, n) => {
const r = n === void 0 ? e : format$1(e, n);
process.stderr.write(t({ message: r.endsWith("\n") ? r : `${r}\n` }));
};
};
return gatewayEntryStartupTrace.enabled ? loadWriter() : async (e, t) => (await loadWriter())(e, t);
}
async function flushEntryStartupTraceForEarlyReturn(e) {
if (!gatewayEntryStartupTrace.enabled) return;
const { loadCliDotEnvForEarlyDiagnostic: t } = await import("./dotenv-BqC7eRgR.mjs");
await t(e);
await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
}
function shouldForceReadOnlyAuthStore(e) {
const t = e.slice(2).filter((e) => e.length > 0 && !e.startsWith("-"));
for (let e = 0; e < t.length - 1; e += 1) if (t[e] === "secrets" && t[e + 1] === "audit") return true;
return false;
}
const gatewayEntryStartupTrace = createGatewayDispatchStartupTrace(process.argv, "entry");
if (isMainModule({
currentFile: fileURLToPath(import.meta.url),
wrapperEntryPairs: [...ENTRY_WRAPPER_PAIRS]
})) try {
await runEntryMain();
} catch (e) {
if (!(e instanceof ExitError)) throw e;
process.exitCode = e.code;
}
async function runEntryMain() {
installDatabaseProcessRole(resolveCliDatabaseProcessRole(normalizeWindowsArgv(process.argv)));
watchCliRespawnParent();
if (isUpdateAdmissionInvocation(resolveCliArgvInvocation(process.argv))) {
await tryRunUpdateAdmissionBeforeStartup(resolveCliArgvInvocation(process.argv));
return;
}
const e = fileURLToPath(import.meta.url);
const t = resolveEntryInstallRoot(e);
ensureOpenClawExecMarkerOnProcess();
installProcessWarningFilter();
normalizeEnv();
process.argv = normalizeWindowsArgv(process.argv);
const n = parseCliProfileArgs(process.argv);
if (n.ok && n.profile) applyCliProfileEnv({ profile: n.profile });
const r = { ...fsSafeEnvInput(process.env) };
const { assertSupportedRuntime: i, isCurrentRuntimeSupported: a } = await import("./runtime-guard-Cecap7VY.mjs");
if (!await a()) {
const { loadCliDotEnv: e } = await import("./dotenv-BqC7eRgR.mjs");
e();
await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
}
await i(void 0, void 0, process.argv, false, inheritedRuntimeEnv);
const { runNodeHostLauncher: o } = await import(new URL("../node-host-launcher.mjs", import.meta.url).href);
if (await o({
entryPath: e,
packageRoot: t
})) {
process.exitCode ??= 0;
return;
}
gatewayEntryStartupTrace.mark("bootstrap");
if (!(!isNodeHostLauncherChild() && await respawnWithoutOpenClawCompileCacheIfNeeded({
currentFile: e,
env: r,
prepareWriteError: async () => {
const e = await prepareCliDiagnosticBlockWriter();
return (t) => e(t);
}
}))) {
enableOpenClawCompileCache({
currentFile: e,
installRoot: t
});
if (shouldForceReadOnlyAuthStore(process.argv)) process.env.OPENCLAW_AUTH_STORE_READONLY = "1";
if (process.argv.includes("--no-color")) {
process.env.NO_COLOR = "1";
process.env.FORCE_COLOR = "0";
}
async function ensureCliRespawnReady() {
const e = buildCliRespawnPlan({ env: r });
if (!e) return false;
if (isNodeHostLauncherChild()) {
await requestNodeHostLauncherBootstrap({
execArgv: e.argv.slice(0, e.argv.length - process.argv.length + 1),
env: e.env
});
process.exitCode = 0;
return true;
}
const t = await prepareCliDiagnosticBlockWriter();
await runCliRespawnPlan(e, t);
return true;
}
if (!await ensureCliRespawnReady()) {
await i(void 0, void 0, process.argv, true, inheritedRuntimeEnv);
process.title = "openclaw";
const e = parseCliContainerArgs(process.argv);
if (!e.ok) {
await writeCapturedCliArgumentError(e.error);
process.exitCode = 2;
return;
}
const t = parseCliProfileArgs(e.argv);
if (!t.ok) {
await writeCapturedCliArgumentError(t.error);
process.exitCode = 2;
return;
}
const n = resolveCliContainerTarget(process.argv);
if (t.profile) {
applyCliProfileEnv({ profile: t.profile });
process.argv = t.argv;
}
if (n && t.profile) {
await writeCapturedCliArgumentError("--container cannot be combined with --profile/--dev");
process.exitCode = 2;
return;
}
gatewayEntryStartupTrace.mark("argv");
if (!tryHandleRootVersionFastPath(process.argv)) {
const run = async (e) => {
const { withCliProcessScope: t } = await import("./runtime-cleanup-scope-CYOx21nX.mjs");
return t(() => runMainOrRootHelp(process.argv, { finalize: e }));
};
const e = getManagedNodeHostStatePath();
if (e) {
const { withExistingOpenClawStateSchema: t } = await import("./openclaw-state-db-schema-policy-C90D12Il.mjs");
await t({ path: e }, async () => {
const { openOpenClawStateDatabase: t, closeOpenClawStateDatabaseByPathAsync: n } = await import("./openclaw-state-db-Ds4jcYSd.mjs");
t({ path: e });
await run(async () => {
await n(e);
});
});
} else await run();
}
}
}
}
async function tryHandleRootHelpFastPath(e) {
const t = process.env;
if (t.OPENCLAW_DISABLE_CLI_STARTUP_HELP_FAST_PATH === "1" || resolveCliContainerTarget(e, t)) return false;
if (!isRootHelpInvocation(e)) return false;
try {
const { loadRootHelpRenderOptionsForConfigSensitivePlugins: e } = await import("./root-help-live-config-DxvS2fIz.mjs");
const n = await e(t);
if (!n) {
const { outputPrecomputedRootHelpText: e } = await import("./root-help-metadata-BOmAFAGo.mjs");
if (e()) return true;
}
const { outputRootHelp: r } = await import("./root-help-C86Bx-Rp.mjs");
await r(n ?? void 0);
return true;
} catch (e) {
const t = e instanceof Error ? formatErrorStackWithMessage(e) : String(e);
await (await prepareCliDiagnosticBlockWriter())(`[openclaw] Failed to display help: ${t}\n`);
process.exitCode = 1;
return true;
}
}
async function tryHandlePrecomputedCommandHelpFastPath(e) {
if (resolveCliContainerTarget(e)) return false;
try {
return await tryOutputPrecomputedCommandHelp(e);
} catch {
return false;
}
}
async function prepareCliFailureHandler(e, t) {
const [{ loadCliDotEnvForEarlyDiagnostic: n }, { enableConsoleCapture: r, writeRootConsoleLine: i }, { formatCliFailureLines: a, formatCliJsonFailure: o }, { isJsonOutputModeActive: s }, c] = await Promise.all([
import("./dotenv-BqC7eRgR.mjs"),
import("./console-DzWOOvYF.mjs"),
import("./failure-output-DKniP608.mjs"),
import("./json-output-mode-hTr0tmcB.mjs"),
prepareGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace)
]);
return async (l) => {
await n(e);
c();
r();
if (s(e)) defaultRuntime.writeJson(o(l));
for (const n of a({
title: t() ? "The CLI command failed." : "Could not start the CLI.",
error: l,
argv: e
})) if (!i("error", n)) console.error(n);
process.exitCode = 1;
};
}
async function runMainOrRootHelp(e, t = {}) {
let n = false;
let r;
const { runCliWithExitFinalization: i, requestExitAfterOneShotOutput: a } = await import("./one-shot-exit-DGkIdz5q.mjs");
await i({
finalize: t.finalize,
run: async () => {
if (isNativeHookRelayArgv(e) && !e.includes("--help") && !e.includes("-h")) {
const { runNativeHookRelayCliFromArgv: t } = await import("./native-hook-relay-cli-O946UYTD.mjs");
const n = await t(e);
process.exitCode = n;
a(defaultRuntime, n);
return;
}
if (await tryHandleRootHelpFastPath(e)) {
await flushEntryStartupTraceForEarlyReturn(e);
a(defaultRuntime);
return;
}
if (await tryHandlePrecomputedCommandHelpFastPath(e)) {
await flushEntryStartupTraceForEarlyReturn(e);
a(defaultRuntime);
return;
}
const { runCli: t } = await gatewayEntryStartupTrace.measure("run-main-import", () => import("./cli/run-main.js"));
r = await prepareCliFailureHandler(e, () => n);
n = true;
await t(e, {
additionalStartupTrace: gatewayEntryStartupTrace,
runtimeRecoveryEnv: inheritedRuntimeEnv,
retainConsoleRoutingUntilProcessExit: true
});
},
onError: async (t) => (r ?? await prepareCliFailureHandler(e, () => n))(t)
});
}
//#endregion
export { runMainOrRootHelp, tryHandlePrecomputedCommandHelpFastPath, tryHandleRootHelpFastPath };