UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

417 lines (416 loc) • 15.8 kB
import { b as resolveNodeSystemdServiceName, v as resolveNodeLaunchAgentLabel, x as resolveNodeWindowsTaskName, y as resolveNodeServiceIdentityEnvironment } from "./constants-BZisy3jr.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as resolveOpenClawPackageRoot } from "./openclaw-root-C-ayo09z.mjs"; import { t as VERSION } from "./version-GlxUMdxI.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs"; import { t as colorize } from "./theme-BOI0xyRZ.mjs"; import { n as loadDeviceIdentityIfPresentAsync } from "./device-identity-async-B1EfjFkw.mjs"; import { i as readPackageVersion } from "./package-json-DXb4lz-W.mjs"; import { s as resolveManagedGatewayServiceCommand } from "./service-types-DdxELPHF.mjs"; import { r as resolveSystemdUserServiceAccount } from "./systemd-user-transport-BwOKajKM.mjs"; import { _ as isSystemdUserServiceAvailable } from "./systemd-busctl-query-BuQgKtLl.mjs"; import { a as resolveNpmGlobalPrefixLayoutFromPrefix } from "./update-npm-prefix-CBfxc8-S.mjs"; import { o as buildPlatformRuntimeLogHints, s as buildPlatformServiceStartHints, t as formatRuntimeStatus } from "./runtime-format-7s5oelVT.mjs"; import { _ as installDaemonServiceAndEmit, d as resolveDaemonInstallBlockMessage, h as buildDaemonServiceSnapshot, l as projectDaemonServiceForJson, n as createDaemonInstallActionContext, p as resolveRuntimeStatusColor, t as createCliStatusTextStyles } from "./shared-cDUnFvXF.mjs"; import { n as collectPackageDistContentInventoryErrors } from "./package-dist-inventory-Cx9cBjwG.mjs"; import { S as createGlobalInstallEnv, f as resolveGlobalInstallTarget, r as collectInstalledGlobalPackageErrors } from "./update-global-EYvKtjUB.mjs"; import { a as runStep } from "./update-runner-command-DcZD6XBi.mjs"; import { s as resolvePinnedDaemonRuntimePath, u as resolveRecordedDaemonRuntime } from "./runtime-paths-xW9-a89Z.mjs"; import { p as resolveNodeProgramArguments } from "./service-hQiIzcTo.mjs"; import { c as withDaemonRuntimePinMigration, o as readDaemonRuntimePinForInstall } from "./runtime-pin-state-DXPlp4E4.mjs"; import { n as readSystemdUserLingerStatus } from "./systemd-k-QLc2ED.mjs"; import { t as runGlobalPackageUpdateSteps } from "./package-update-steps-N6noh5W3.mjs"; import { n as formatInvalidPortOption, t as formatInvalidConfigPort } from "./error-format-O7EzXfiI.mjs"; import { a as loadNodeHostConfig } from "./config-BmUu42pB.mjs"; import { t as canReuseNodeHostDeviceToken } from "./gateway-auth-DyMkGKMU.mjs"; import { n as resolveDaemonInstallRuntimeInputs, r as resolveDaemonRuntimeBinDir, t as emitNodeRuntimeWarning } from "./daemon-install-runtime-warning-0qx7euD-.mjs"; import { i as resolveGatewayDaemonRuntime, r as isGatewayDaemonRuntime } from "./daemon-runtime-agdJw6fb.mjs"; import { t as resolveNodeService } from "./node-service-CJZ08R6H.mjs"; import { n as buildNodeServiceEnvironment } from "./service-env-BbgmtKhw.mjs"; import { n as resolveRestoreServiceCli, t as assertExpectedRuntimePin } from "./install-restore-cli-BRi0_SdX.mjs"; import { a as runServiceUninstall, i as runServiceStop, n as runServiceRestart, r as runServiceStart } from "./lifecycle-core-DaTVXHQN.mjs"; import { n as inspectServiceRuntimeIntent } from "./status.runtime-intent-DpzXaRa6.mjs"; import { t as resolveNodeGatewayOptions } from "./gateway-options-BJTgGucZ.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/daemon/npx-service-install.ts /** npm exec owns its cache, so only a managed npm prefix may own a node service. */ async function resolveDurableNodeEntrypoint(e, t = process.argv[1]) { if (!t) return; const n = await fs.realpath(t).catch(() => path.resolve(t)); if (!n.split(path.sep).includes("_npx")) return; const r = await resolveOpenClawPackageRoot({ argv1: n }); const i = r ? await readPackageVersion(r) : null; if (!i) throw new Error("Cannot determine the npm exec OpenClaw version for node service installation."); const a = resolveNpmGlobalPrefixLayoutFromPrefix(path.join(resolveStateDir(e), "npm")); const o = path.join(a.globalRoot, "openclaw"); if (!((await collectInstalledGlobalPackageErrors({ packageRoot: o, expectedVersion: i })).length === 0 && await collectPackageDistContentInventoryErrors(o).then((e) => e.length === 0, () => false))) { const t = await createGlobalInstallEnv(e, { manager: "npm" }); const n = await resolveGlobalInstallTarget({ manager: "npm", runCommand: runCommandWithTimeout, timeoutMs: 3e4, env: t }); await fs.mkdir(a.globalRoot, { recursive: true }); const r = await runGlobalPackageUpdateSteps({ installTarget: { ...n, globalRoot: a.globalRoot, packageRoot: o }, installSpec: `openclaw@${i}`, requirePackageReplacement: true, packageName: "openclaw", packageRoot: o, runCommand: runCommandWithTimeout, runStep: (e) => runStep({ ...e, cwd: e.cwd ?? process.cwd(), runCommand: runCommandWithTimeout, stepIndex: 0, totalSteps: 0 }), timeoutMs: 3e4, workTimeoutMs: null, env: t }); if (r.failedStep) throw new Error(`Cannot install durable OpenClaw ${i}: ${r.failedStep.stderrTail || r.failedStep.name}`); } return path.join(o, "openclaw.mjs"); } //#endregion //#region src/cli/node-cli/daemon.ts function renderNodeServiceStartHints() { return buildPlatformServiceStartHints({ installHint: formatCliCommand("openclaw node install"), startCommand: formatCliCommand("openclaw node start"), launchAgentPlistPath: `~/Library/LaunchAgents/${resolveNodeLaunchAgentLabel(process.env.OPENCLAW_PROFILE)}.plist`, systemdServiceName: resolveNodeSystemdServiceName(process.env.OPENCLAW_PROFILE), windowsTaskName: resolveNodeWindowsTaskName(process.env.OPENCLAW_PROFILE) }); } /** * User-level node services stop with the last SSH session unless lingering is enabled. * Diagnose this without changing the operator's login policy. */ async function warnIfSystemdUserLingerDisabled(e) { if (process.platform !== "linux") return; if (!await isSystemdUserServiceAvailable()) return; const t = resolveSystemdUserServiceAccount(process.env); if (!t) return; const n = await readSystemdUserLingerStatus({ env: process.env, user: t }); if (!n || n.linger === "yes") return; e(`Systemd lingering is disabled for ${n.user}. The node service will stop when you log out. Run: sudo loginctl enable-linger ${n.user}`); } async function runNodeDaemonInstall(e) { const { json: t, stdout: n, warnings: r, warn: i, emit: a, emitMessage: o, fail: s } = createDaemonInstallActionContext(e.json); const c = resolveDaemonInstallBlockMessage("node"); if (c) { s(c); return; } const l = await loadNodeHostConfig(); let u; try { u = resolveNodeGatewayOptions(e, l); } catch (e) { s(e instanceof Error ? e.message : String(e)); return; } const { host: d, port: f, contextPath: p, tls: m, tlsFingerprint: h, cloudflareAccess: g } = u; if (f === null || !Number.isFinite(f) || f <= 0 || f > 65535) { s(e.port !== void 0 ? formatInvalidPortOption("--port") : formatInvalidConfigPort("node.gateway.port")); return; } if (e.tls === false && e.tlsFingerprint !== void 0) { s("--no-tls cannot be combined with --tls-fingerprint"); return; } if (g && m !== true) { s("Cloudflare Access credentials require --tls for the node Gateway connection"); return; } const _ = resolveNodeService(); let v; try { v = await _.readCommand(process.env); } catch (e) { s(`Node service inspection failed: ${formatErrorMessage(e)}`); return; } const y = resolveManagedGatewayServiceCommand(v); const b = { ...process.env, OPENCLAW_WRAPPER: process.env.OPENCLAW_WRAPPER ?? y?.environment?.OPENCLAW_WRAPPER }; let x; try { x = await withDaemonRuntimePinMigration({ ...b, ...resolveNodeServiceIdentityEnvironment(b) }, () => readDaemonRuntimePinForInstall({ kind: "node", env: b }, v, e.runtime !== void 0 || e.runtimePath !== void 0)); } catch (e) { s(`Runtime pin inspection failed: ${formatErrorMessage(e)}`); return; } let S; let C; try { if (e.expectedRuntimePin !== void 0) assertExpectedRuntimePin(e.expectedRuntimePin, x, "Node"); if (e.restoreServiceCli !== void 0) ({serviceCli: S, runtimePath: C} = await resolveRestoreServiceCli(e.restoreServiceCli, e, b)); } catch (e) { s(e instanceof Error ? e.message : String(e)); return; } let w = e.runtimePath ?? (e.runtime ? void 0 : x.pin?.path); const T = e.runtime || x.pin?.runtime || resolveGatewayDaemonRuntime([w ?? ""]); if (!isGatewayDaemonRuntime(T)) { s("Invalid --runtime (use \"node\", \"bun\", or \"standalone\")"); return; } try { if (!b.OPENCLAW_WRAPPER?.trim() || e.runtimePath !== void 0) w = await resolvePinnedDaemonRuntimePath(w, T, b); } catch (e) { s(`Invalid runtime pin: ${formatErrorMessage(e)}`); return; } let E; try { E = await _.isLoaded({ env: process.env }); } catch (e) { s(`Node service check failed: ${formatErrorMessage(e)}`); return; } if (E && !e.force) { await warnIfSystemdUserLingerDisabled(i); o({ ok: true, result: "already-installed", message: `Node service already ${_.loadedText}.`, service: buildDaemonServiceSnapshot(_, E), warnings: r.length ? r : void 0 }); if (!t) defaultRuntime.log(`Reinstall with: ${formatCliCommand("openclaw node install --force")}`); return; } const D = e.runtime === void 0 && !w && !b.OPENCLAW_WRAPPER?.trim() ? await resolveRecordedDaemonRuntime(y?.programArguments[0], b) : void 0; const O = D?.status === "supported" ? D : void 0; const k = b.OPENCLAW_WRAPPER; const { devMode: A, runtime: j, runtimePath: M } = await resolveDaemonInstallRuntimeInputs({ env: b, runtime: O?.runtime ?? T, runtimeExplicit: e.runtime !== void 0 || e.runtimePath !== void 0, runtimePath: C ?? O?.path, pinnedRuntimePath: w, devMode: S ? false : void 0, wrapperPath: k, warn: i }); const N = S?.entrypoint ?? (!A && !k && j !== "standalone" ? await resolveDurableNodeEntrypoint(b) : void 0); const { programArguments: P, workingDirectory: F } = await resolveNodeProgramArguments({ cliEntrypoint: N, host: d, port: f, contextPath: p, tls: Boolean(m), tlsFingerprint: h, nodeId: e.nodeId, displayName: e.displayName, installedAppsSharing: e.shareInstalledApps, commands: e.commands, allCommands: e.allCommands, dev: A, runtime: j, runtimePath: M, wrapperPath: k }); if (e.authFromEnv) P.push("--auth-from-env"); await emitNodeRuntimeWarning({ env: b, runtime: j, nodeProgram: P[0], warn: i, title: "Node daemon runtime" }); const I = buildNodeServiceEnvironment({ env: b, execPath: S?.executable, runtime: j, extraPathDirs: resolveDaemonRuntimeBinDir(M) }); if (!e.authFromEnv) { const e = (await loadNodeHostConfig(b))?.gateway; const t = e ? await loadDeviceIdentityIfPresentAsync({ env: b }) : null; if (t && await canReuseNodeHostDeviceToken({ savedGateway: e, gatewayCandidates: [{ host: d, port: f, contextPath: p, tls: Boolean(m) }], deviceId: t.deviceId, env: b })) { delete I.OPENCLAW_GATEWAY_TOKEN; delete I.OPENCLAW_GATEWAY_PASSWORD; } } const L = [ `OpenClaw ${VERSION}`, `Runtime: ${j} (${P[0]})`, `Service command: ${P.map(quoteCliArg).join(" ")}`, `Update this node: ${formatCliCommand("openclaw node install --force", b).replace("openclaw", "npx -y openclaw@latest")}` ].join("\n"); if (!t) defaultRuntime.log(L); await installDaemonServiceAndEmit({ serviceNoun: "Node", service: _, warnings: r, emit: (e) => a({ ...e, message: L }), fail: s, install: async () => { await _.install({ runtimePinUpdate: { expected: x, pin: w ? { runtime: T, path: w } : void 0, ...e.expectedRuntimePin !== void 0 ? { requireDefinitionMatch: true, ...!S && x.definition !== void 0 ? { requireRunning: true } : {} } : {} }, env: b, stdout: n, warn: i, programArguments: P, workingDirectory: F, environment: I, environmentValueSources: { OPENCLAW_GATEWAY_TOKEN: "file", OPENCLAW_GATEWAY_PASSWORD: "file", CF_ACCESS_CLIENT_ID: "file", CF_ACCESS_CLIENT_SECRET: "file" }, description: "OpenClaw Node Host", ...S ? { workingDirectory: y?.workingDirectory } : {} }); }, onVerified: () => warnIfSystemdUserLingerDisabled(i) }); } async function runNodeDaemonLifecycle(e, t = {}) { const n = { serviceNoun: "Node", service: resolveNodeService(), renderFailureHints: () => [`Run ${formatCliCommand("openclaw node status")} to inspect the service, then retry.`], opts: t }; if (e === "uninstall") return await runServiceUninstall({ ...n, stopBeforeUninstall: false, assertNotLoadedAfterUninstall: false }); if (e === "stop") return await runServiceStop(n); await (e === "start" ? runServiceStart : runServiceRestart)({ ...n, renderStartHints: renderNodeServiceStartHints }); } async function runNodeDaemonStatus(e = {}) { const t = Boolean(e.json); const n = resolveNodeService(); let r; try { r = await n.isLoaded({ env: process.env }); } catch (e) { const n = `Node service check failed: ${formatErrorMessage(e)}`; if (t) throw new Error(n, { cause: e }); defaultRuntime.error(n); defaultRuntime.exit(1); return; } let i = true; const [a, o] = await Promise.all([n.readCommand(process.env).catch(() => { i = false; return null; }), n.readRuntime(process.env).catch((e) => ({ status: "unknown", detail: formatErrorMessage(e) }))]); if (t) { const e = await inspectServiceRuntimeIntent({ kind: "node", service: n, command: a, env: process.env, serviceEnv: { ...process.env, ...a?.environment }, inspectionKnown: i }); defaultRuntime.writeJson({ service: projectDaemonServiceForJson({ ...buildDaemonServiceSnapshot(n, r), command: a, runtime: o, ...e }, { includeDefinitionPaths: true }) }); return; } const { rich: s, label: c, accent: l, infoText: u, okText: d, warnText: f, errorText: p } = createCliStatusTextStyles(); const m = r ? d(n.loadedText) : f(n.notLoadedText); defaultRuntime.log(`${c("Service:")} ${l(n.label)} (${m})`); if (a?.programArguments?.length) defaultRuntime.log(`${c("Command:")} ${u(a.programArguments.join(" "))}`); if (a?.sourcePath) defaultRuntime.log(`${c("Service file:")} ${u(a.sourcePath)}`); if (a?.workingDirectory) defaultRuntime.log(`${c("Working dir:")} ${u(a.workingDirectory)}`); const h = formatRuntimeStatus(o); if (h) { const e = resolveRuntimeStatusColor(o?.status); defaultRuntime.log(`${c("Runtime:")} ${colorize(s, e, h)}`); } if (!r) { defaultRuntime.log(""); for (const e of renderNodeServiceStartHints()) defaultRuntime.log(`${f("Start with:")} ${u(e)}`); return; } const g = { ...process.env, ...a?.environment }; const _ = { ...g, OPENCLAW_LOG_PREFIX: g.OPENCLAW_LOG_PREFIX ?? "node" }; if (o?.missingUnit || o?.status === "stopped") { defaultRuntime.error(p(o.missingUnit ? "Service unit not found." : "Service is loaded but not running.")); for (const e of buildPlatformRuntimeLogHints({ env: _, systemdServiceName: resolveNodeSystemdServiceName(process.env.OPENCLAW_PROFILE), windowsTaskName: resolveNodeWindowsTaskName(process.env.OPENCLAW_PROFILE) })) defaultRuntime.log(p(e)); } } //#endregion export { runNodeDaemonLifecycle as n, runNodeDaemonStatus as r, runNodeDaemonInstall as t };