openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
665 lines (664 loc) • 22.6 kB
JavaScript
import { r as defaultRuntime, t as ExitError } from "./runtime-B-SLYP-m.mjs";
import { C as resolveIsNixMode } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { y as resolveFutureConfigActionBlock } from "./config-env-vars-ByeGN-9N.mjs";
import { r as isPluginPackagingRuntimeOutputInvalidConfigSnapshot } from "./recovery-policy-CixJJb9O.mjs";
import { a as readBestEffortConfig, s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs";
import "./config-CMA-J084.mjs";
import { t as createGatewayCredentialPlan } from "./credential-planner-DCQbkiQO.mjs";
import { n as isGatewaySecretRefUnavailableError, t as GatewaySecretRefUnavailableError } from "./credentials-UDpmcQCV.mjs";
import { t as isWSL } from "./wsl-I_VtUW9p.mjs";
import { i as assertGatewayServiceUpdateCurrent } from "./service-update-authority-wlK0pAdP.mjs";
import { _ as isSystemdUserServiceAvailable } from "./systemd-busctl-query-BuQgKtLl.mjs";
import { c as resolveSystemdServiceName } from "./systemd-service-files-kK4fW2O4.mjs";
import { a as writeGatewayServiceRestartIntentSync, i as writeGatewayRestartIntentSync, r as prepareGatewayRestartIntentLegacyProcess, s as GatewayRestartPreparationError, t as clearGatewayRestartIntentSync } from "./restart-intent-D5xKHHxG.mjs";
import { t as appendGatewayLifecycleAuditLog } from "./restart-logs-zLeNdzsY.mjs";
import { t as mergeGatewayServiceEnv } from "./service-env-merge-994N__ny.mjs";
import { i as renderSystemdUnavailableHints } from "./runtime-format-7s5oelVT.mjs";
import { d as resolveDaemonInstallBlockMessage, g as createDaemonActionContext, h as buildDaemonServiceSnapshot, r as filterContainerGenericHints } from "./shared-cDUnFvXF.mjs";
import { n as resolveLaunchAgentLabel } from "./launchd-label-DdmmL_TH.mjs";
import { a as formatGatewayServiceStartRepairIssues, i as collectGatewayServiceStartRepairIssues, r as startGatewayService, t as describeGatewayServiceRestart } from "./service-hQiIzcTo.mjs";
import { t as createGatewayLifecycleMutationReporter } from "./service-mutation-DD9C-blM.mjs";
import { r as readGatewayServiceLoadState, t as readGatewayServiceState } from "./service-state-uYnG1mTd.mjs";
import "./systemd-k-QLc2ED.mjs";
import { r as isTerminalInteractive } from "./terminal-interactivity-B_L_vZTP.mjs";
import { r as formatPluginPackagingRuntimeOutputRecoveryHint, t as formatInvalidConfigRecoveryHint } from "./config-recovery-hints-DL4KuQ2q.mjs";
import { t as renderConfigValidationIssueLines } from "./issue-location-B-4mXR06.mjs";
import { i as checkTokenDrift, r as checkManagedServiceEnvDrift } from "./service-audit-BfaswvZi.mjs";
import { t as resolveGatewayAuthToken } from "./auth-token-resolution-CUaXbu3r.mjs";
//#region src/cli/daemon-cli/gateway-token-drift.ts
/** Resolve the expected Gateway token for service drift checks, or undefined when token auth is inactive. */
async function resolveGatewayTokenForDriftCheck(e) {
const t = e.env ?? process.env;
const n = e.cfg.gateway?.auth?.mode;
if (n === "password" || n === "none" || n === "trusted-proxy") return;
const r = createGatewayCredentialPlan({
config: e.cfg,
env: t
});
if (r.authMode === void 0 && r.passwordCanWin && !r.tokenCanWin) return;
const i = await resolveGatewayAuthToken({
cfg: e.cfg,
env: t,
envFallback: "never",
unresolvedReasonStyle: "detailed"
});
if (i.token) return i.token;
if (!i.secretRefConfigured) return;
throw new GatewaySecretRefUnavailableError("gateway.auth.token");
}
//#endregion
//#region src/cli/daemon-cli/lifecycle-action-preflight.ts
/** Startup admission, or a diagnostic to report after recovery actions. */
async function getServiceActionPreflightFailure(e) {
let t;
try {
if (e === "restart") {
const { readConfigSnapshotForEngineSelection: e } = await import("./config-preflight-snapshot-DXY8QhxC.mjs");
t = await e(process.env, { isolateEnv: false });
if (t.valid) t = await readConfigFileSnapshot({ observe: false });
} else t = await readConfigFileSnapshot({
observe: false,
...e === "stop" || e === "uninstall" ? { pluginValidation: "core-only" } : {}
});
if (!t.valid) return {
message: t.issues.length > 0 ? renderConfigValidationIssueLines(t, "").join("\n") : "Unknown validation issue.",
...isPluginPackagingRuntimeOutputInvalidConfigSnapshot(t) ? { hints: formatPluginPackagingRuntimeOutputRecoveryHint().split("\n") } : {}
};
} catch (t) {
return e === "restart" ? { message: formatErrorMessage(t) } : null;
}
const n = resolveFutureConfigActionBlock({
action: `${e} the gateway service`,
snapshot: t
});
if (n) return {
message: e === "start" ? n.message : `Config was last written by OpenClaw ${n.touchedVersion}; this binary is ${n.currentVersion}.`,
hints: n.hints
};
return null;
}
//#endregion
//#region src/cli/daemon-cli/lifecycle-audit.ts
function appendGatewayLifecycleAudit(e) {
appendGatewayLifecycleAuditLog(e.env ?? process.env, {
action: e.action,
source: e.source,
mode: e.mode,
...e.pid === void 0 ? {} : { pid: e.pid },
interactive: isTerminalInteractive()
});
}
function createGatewayLifecycleMutationAudit(e) {
const t = createGatewayLifecycleMutationReporter((t) => {
appendGatewayLifecycleAudit({
action: e.action,
source: e.source ?? "cli",
mode: t.mode,
...e.env === void 0 ? {} : { env: e.env }
});
});
return (e) => t(e.mode);
}
function createServiceLifecycleMutationAudit(e) {
return e.serviceNoun === "Gateway" ? createGatewayLifecycleMutationAudit({ action: e.action }) : void 0;
}
function appendServiceLifecycleRepairAudit(e) {
if (e.serviceNoun !== "Gateway") return;
appendGatewayLifecycleAudit({
action: e.action,
source: "cli",
mode: "service-repair",
...e.pid === void 0 ? {} : { pid: e.pid }
});
}
//#endregion
//#region src/cli/daemon-cli/lifecycle-restart-intent.ts
function createServiceRestartIntent(e) {
let t = false;
let n = process.env;
return {
prepare: async () => {
if (e.serviceNoun !== "Gateway" || t) return;
const r = await e.service.readRuntime(process.env).catch(() => null);
assertGatewayServiceUpdateCurrent();
const i = process.platform === "linux" || process.platform === "darwin";
let a;
let o;
if (i) try {
const t = await e.service.readCommand(process.env, { requireEffective: true });
assertGatewayServiceUpdateCurrent();
if (!t) throw new GatewayRestartPreparationError("service-command");
n = mergeGatewayServiceEnv(process.env, t);
a = process.platform === "linux" ? {
kind: "systemd",
name: r?.systemd?.unit ?? resolveSystemdServiceName(process.env)
} : {
kind: "launchd",
name: resolveLaunchAgentLabel(process.env)
};
o = await prepareGatewayRestartIntentLegacyProcess({
env: n,
command: t,
runtimePid: r?.pid,
readRuntime: () => e.service.readRuntime(process.env),
assertCurrent: assertGatewayServiceUpdateCurrent
});
} catch {
assertGatewayServiceUpdateCurrent();
throw new GatewayRestartPreparationError("service-command");
}
assertGatewayServiceUpdateCurrent();
const s = {
env: n,
reason: "gateway.restart",
...e.intent ? { intent: e.intent } : {}
};
t = a ? writeGatewayServiceRestartIntentSync({
...s,
service: a,
legacyProcess: o,
nativeStopped: r?.status === "stopped" && r.pid === void 0,
assertCurrent: assertGatewayServiceUpdateCurrent
}) : writeGatewayRestartIntentSync({
...s,
targetPid: r?.pid
});
},
clear: () => {
if (t) {
assertGatewayServiceUpdateCurrent();
clearGatewayRestartIntentSync(n);
t = false;
}
}
};
}
//#endregion
//#region src/cli/daemon-cli/lifecycle-core.ts
function mergeWarnings(e, t) {
const n = [...e, ...t ?? []];
return n.length > 0 ? n : void 0;
}
async function failServiceNotLoaded(e, t) {
let n = e.renderStartHints();
if (process.platform === "linux" && !await isSystemdUserServiceAvailable().catch(() => false)) n = [...n, ...renderSystemdUnavailableHints({
wsl: await isWSL(),
kind: "generic_unavailable"
})];
t(`${e.serviceNoun} service ${e.service.notLoadedText}.`, filterContainerGenericHints(n));
}
async function resolveServiceLoadedOrFail(e, t, n = {}) {
const hasInstalledDefinition = async () => e.service.hasInstalledDefinition ? await e.service.hasInstalledDefinition({ env: process.env }).catch(() => false) : Boolean(await e.service.readCommand(process.env).catch(() => null));
const r = await readGatewayServiceLoadState(e.service, { env: process.env });
if (r.status === "unknown") {
t(`${n.inspectionFailureMessage ?? `${e.serviceNoun} service check failed`}: ${r.detail}`);
return null;
}
return r.status === "loaded" || Boolean(n.acceptInstalledDefinition) && await hasInstalledDefinition();
}
/** Only observer cancellation belongs to the root; concurrent service failures still report. */
function commandInterrupted(e) {
const t = getAsyncWorkSignal();
return t?.aborted === true && (e === t.reason || e instanceof Error && e.cause === t.reason);
}
function warnServiceConfig(e, t) {
if (!e) return;
const n = [
`Config needs repair: ${e.message}`,
...e.hints ?? [],
formatCliCommand("openclaw doctor --fix")
].join("\n");
t.warnings.push(n);
if (!t.json) defaultRuntime.error(`WARNING: ${n}`);
}
async function runServiceUninstall(e) {
const t = Boolean(e.opts?.json);
const { stdout: n, warnings: r, emit: i, fail: a } = createDaemonActionContext({
action: "uninstall",
json: t
});
if (resolveIsNixMode(process.env)) {
a("Nix mode detected; service uninstall is disabled.");
return;
}
let o = await resolveServiceLoadedOrFail(e, a, { inspectionFailureMessage: `${e.serviceNoun} uninstall aborted because service status is unknown; resolve the inspection error before retrying` });
if (o === null) return;
if (o && e.stopBeforeUninstall) try {
await e.service.stop({
env: process.env,
stdout: n
});
} catch {}
try {
await e.service.uninstall({
env: process.env,
stdout: n
});
} catch (t) {
a(`${e.serviceNoun} uninstall failed: ${String(t)}`, e.renderFailureHints());
return;
}
o = await resolveServiceLoadedOrFail(e, a, { inspectionFailureMessage: `${e.serviceNoun} uninstall verification failed because service status is unknown` });
if (o === null) return;
if (o && e.assertNotLoadedAfterUninstall) {
a(`${e.serviceNoun} service still loaded after uninstall.`, e.renderFailureHints());
return;
}
warnServiceConfig(await getServiceActionPreflightFailure("uninstall"), {
json: t,
warnings: r
});
i({
ok: true,
result: "uninstalled",
service: buildDaemonServiceSnapshot(e.service, o)
});
}
async function runServiceStart(e) {
const t = Boolean(e.opts?.json);
const n = formatCliCommand(`openclaw ${e.serviceNoun.toLowerCase()}`);
const { stdout: r, warnings: i, emitMessage: a, fail: o } = createDaemonActionContext({
action: "start",
json: t
});
const s = t ? (e) => i.push(e) : void 0;
let c = false;
const checkReadiness = async () => {
await e.postStartCheck?.({
json: t,
stdout: r,
warnings: i,
warn: s,
fail: (e, t, n) => {
c = true;
o(e, t, n);
}
});
return !c;
};
const emitStarted = async (t) => {
if (!await checkReadiness()) return;
a({
ok: true,
result: "started",
message: t.message,
warnings: mergeWarnings(i, t.reportedWarnings),
service: buildDaemonServiceSnapshot(e.service, t.loaded)
});
};
const l = await resolveServiceLoadedOrFail(e, o);
if (l === null) return;
const u = await getServiceActionPreflightFailure("start");
if (u) {
o(!u.hints ? `${e.serviceNoun} aborted: config is invalid.\n${u.message}\n${formatInvalidConfigRecoveryHint()}` : `${e.serviceNoun} start blocked: ${u.message}`, u.hints);
return;
}
if (!l) try {
const n = await e.onNotLoaded?.({
json: t,
stdout: r,
warn: s,
fail: o
});
if (n) {
await emitStarted({
loaded: n.loaded ?? false,
message: n.message,
reportedWarnings: n.warnings
});
return;
}
} catch (t) {
if (c || t instanceof ExitError) throw t;
if (commandInterrupted(t)) return;
o(`${e.serviceNoun} start failed: ${String(t)}`, e.renderStartHints());
return;
}
try {
const l = await startGatewayService(e.service, {
env: process.env,
stdout: r,
warn: s,
onMutation: createServiceLifecycleMutationAudit({
serviceNoun: e.serviceNoun,
action: "start"
})
}, e.expectedPort);
if (l.outcome === "missing-install") {
await failServiceNotLoaded(e, o);
return;
}
if (l.outcome === "already-running") {
if (l.issues.length > 0) {
const r = e.repairLoadedService ? "restart" : "install --force";
const a = `${e.serviceNoun} service already running, but its installed service definition needs repair: ${formatGatewayServiceStartRepairIssues(l.issues)}; run \`${n} ${r}\` to apply.`;
i.push(a);
if (!t) defaultRuntime.log(a);
}
if (!await checkReadiness()) return;
const r = l.state.runtime?.pid;
a({
ok: true,
result: "already-running",
message: `${e.serviceNoun} service already running${r === void 0 ? "" : ` (pid ${r})`}.`,
service: buildDaemonServiceSnapshot(e.service, true),
warnings: i.length ? i : void 0
});
return;
}
if (l.outcome === "repair-required") {
try {
const n = await e.repairLoadedService?.({
json: t,
stdout: r,
warn: s,
fail: o,
state: l.state,
issues: l.issues
});
if (n) {
appendServiceLifecycleRepairAudit({
serviceNoun: e.serviceNoun,
action: "start"
});
await emitStarted({
loaded: n.loaded ?? true,
message: n.message,
reportedWarnings: n.warnings
});
return;
}
} catch (t) {
if (c || t instanceof ExitError) throw t;
if (commandInterrupted(t)) return;
o(`${e.serviceNoun} repair failed: ${String(t)}`, e.renderStartHints());
return;
}
o(`${e.serviceNoun} service needs repair before it can start: ${formatGatewayServiceStartRepairIssues(l.issues)}`, [`${n} install --force`]);
return;
}
await emitStarted({ loaded: l.state.loadState.status === "loaded" });
} catch (t) {
if (c || t instanceof ExitError) throw t;
if (commandInterrupted(t)) return;
o(`${e.serviceNoun} start failed: ${String(t)}`, e.renderStartHints());
}
}
async function runServiceStop(e) {
const t = Boolean(e.opts?.json);
const { stdout: n, warnings: r, emit: i, emitMessage: a, fail: o } = createDaemonActionContext({
action: "stop",
json: t
});
const s = createServiceLifecycleMutationAudit({
serviceNoun: e.serviceNoun,
action: "stop"
});
const c = await resolveServiceLoadedOrFail(e, o);
if (c === null) return;
if (!c && !e.stopWhenNotLoaded) {
try {
const i = await e.onNotLoaded?.({
json: t,
stdout: n,
fail: o
});
if (i) {
warnServiceConfig(await getServiceActionPreflightFailure("stop"), {
json: t,
warnings: r
});
a({
ok: true,
result: i.result,
message: i.message,
warnings: mergeWarnings(r, i.warnings),
service: buildDaemonServiceSnapshot(e.service, false)
});
return;
}
} catch (t) {
if (t instanceof ExitError) throw t;
o(`${e.serviceNoun} stop failed: ${String(t)}`, e.renderFailureHints());
return;
}
warnServiceConfig(await getServiceActionPreflightFailure("stop"), {
json: t,
warnings: r
});
a({
ok: true,
result: "not-loaded",
message: `${e.serviceNoun} service ${e.service.notLoadedText}.`,
service: buildDaemonServiceSnapshot(e.service, c)
});
return;
}
try {
await e.service.stop({
env: process.env,
stdout: n,
disable: e.opts?.disable,
onMutation: s
});
} catch (t) {
o(`${e.serviceNoun} stop failed: ${String(t)}`, e.renderFailureHints());
return;
}
const l = c ? await resolveServiceLoadedOrFail(e, o, { inspectionFailureMessage: `${e.serviceNoun} stop verification failed because service status is unknown` }) : false;
if (l === null) return;
warnServiceConfig(await getServiceActionPreflightFailure("stop"), {
json: t,
warnings: r
});
i({
ok: true,
result: "stopped",
service: buildDaemonServiceSnapshot(e.service, l)
});
}
async function runServiceRestart(e) {
const t = Boolean(e.opts?.json);
const { stdout: n, warnings: r, emitMessage: i, fail: a } = createDaemonActionContext({
action: "restart",
json: t
});
const o = t ? (e) => r.push(e) : void 0;
const renderRestartFailureHints = (t) => t instanceof GatewayRestartPreparationError && t.reason === "serving-owner" ? [formatCliCommand("openclaw gateway status --deep"), `Fix the reported startup failure, then run \`${formatCliCommand("openclaw gateway start")}\` to wait for readiness without restarting the process.`] : e.renderStartHints();
const s = e.opts?.restartIntent;
const c = createServiceLifecycleMutationAudit({
serviceNoun: e.serviceNoun,
action: "restart"
});
let l = null;
let u = null;
let d = null;
const { prepare: f, clear: p } = createServiceRestartIntent({
...e,
intent: s
});
const emitScheduledRestart = (t, n) => {
i({
ok: true,
result: t.daemonActionResult,
message: t.message,
service: buildDaemonServiceSnapshot(e.service, n),
warnings: r.length ? r : void 0
});
return true;
};
const m = await resolveServiceLoadedOrFail(e, a, { acceptInstalledDefinition: true });
if (m === null) return false;
const h = await getServiceActionPreflightFailure("restart");
if (e.restartOwnedProcess) try {
l = await e.restartOwnedProcess({
json: t,
stdout: n,
warn: o,
fail: a
});
} catch (t) {
if (t instanceof ExitError) throw t;
if (commandInterrupted(t)) return false;
a(`${e.serviceNoun} restart failed: ${String(t)}`);
return false;
}
if (m && !l) e.beforeServiceMutation?.();
if (!m && !l) {
try {
l = await e.onNotLoaded?.({
json: t,
stdout: n,
warn: o,
fail: a
}) ?? null;
} catch (t) {
if (t instanceof ExitError) throw t;
if (commandInterrupted(t)) return false;
a(`${e.serviceNoun} restart failed: ${String(t)}`);
return false;
}
if (!l) {
await failServiceNotLoaded(e, a);
return false;
}
if (l.warnings?.length) r.push(...l.warnings);
d = l.loaded ?? null;
}
if (m && !l && !h && e.repairLoadedService) try {
const i = await readGatewayServiceState(e.service, { env: process.env });
const s = collectGatewayServiceStartRepairIssues(i, e.expectedPort);
if (s.length > 0) {
await f();
u = await e.repairLoadedService({
json: t,
stdout: n,
warn: o,
fail: a,
state: i,
issues: s
});
if (!u) {
p();
a(`${e.serviceNoun} service needs repair before restart: ${formatGatewayServiceStartRepairIssues(s)}`, [formatCliCommand("openclaw gateway install --force")]);
return false;
}
appendServiceLifecycleRepairAudit({
serviceNoun: e.serviceNoun,
action: "restart",
pid: i.runtime?.pid
});
if (u.warnings?.length) r.push(...u.warnings);
}
} catch (t) {
p();
if (t instanceof ExitError) throw t;
if (commandInterrupted(t)) return false;
const n = renderRestartFailureHints(t);
a(`${e.serviceNoun} repair failed: ${String(t)}`, n);
return false;
}
if (m && !l && !h && e.checkTokenDrift) {
const warnDrift = (e, n) => {
const i = n ? resolveDaemonInstallBlockMessage("gateway") ?? `Run \`${formatCliCommand("openclaw gateway install --force")}\` to refresh the service ${n}.` : void 0;
const a = i ? `${e} ${i}` : e;
r.push(a);
if (!t) defaultRuntime.log(`\n⚠️ ${a}\n`);
};
try {
const t = await e.service.readCommand(process.env);
const n = await readBestEffortConfig();
const r = {
...process.env,
...t?.environment
};
try {
const e = await resolveGatewayTokenForDriftCheck({
cfg: n,
env: r
});
const i = checkTokenDrift({
serviceToken: t?.environment?.OPENCLAW_GATEWAY_TOKEN,
configToken: e
});
if (i) warnDrift(i.message, "token source");
} catch (e) {
if (isGatewaySecretRefUnavailableError(e, "gateway.auth.token")) warnDrift("Unable to verify gateway token drift: gateway.auth.token SecretRef is configured but unavailable in this command path.");
}
const { collectDurableServiceEnvVars: i } = await import("./state-dir-dotenv-_lXSPAf9.mjs");
const { collectEnvSecretRefIds: a } = await import("./resolution-facts-DHQgJtdf.mjs");
const o = checkManagedServiceEnvDrift({
command: t,
durableEnvironment: i({
env: r,
config: n
}),
secretRefKeys: a(n)
});
if (o) warnDrift(o.message, "environment");
} catch {}
}
let g = false;
try {
let s;
if (m && !u && !l) {
if (!e.opts?.preserveDefinition) await f();
try {
s = await e.service.restart({
prepareRestart: e.opts?.preserveDefinition ? f : void 0,
preserveDefinition: h ? true : e.opts?.preserveDefinition,
env: process.env,
stdout: n,
warn: o,
onMutation: c
});
} catch (e) {
p();
throw e;
}
}
warnServiceConfig(h, {
json: t,
warnings: r
});
let _ = describeGatewayServiceRestart(e.serviceNoun, s ?? { outcome: "completed" });
if (_.scheduled) return emitScheduledRestart(_, m || d === true);
if (e.postRestartCheck) {
const i = await e.postRestartCheck({
json: t,
stdout: n,
warnings: r,
warn: o,
activationAccepted: s?.outcome === "completed" || Boolean(l),
preserveDefinition: h ? true : e.opts?.preserveDefinition,
fail: (e, t, n) => {
g = true;
a(e, t, n);
}
});
if (i) {
_ = describeGatewayServiceRestart(e.serviceNoun, i);
if (_.scheduled) return emitScheduledRestart(_, m || d === true);
}
}
i({
ok: true,
result: "restarted",
message: l?.message ?? u?.message,
service: buildDaemonServiceSnapshot(e.service, m || d === true),
warnings: r.length ? r : void 0
});
return true;
} catch (t) {
if (g || t instanceof ExitError) throw t;
if (commandInterrupted(t)) return false;
const n = renderRestartFailureHints(t);
a(`${e.serviceNoun} restart failed: ${String(t)}`, n);
return false;
}
}
//#endregion
export { runServiceUninstall as a, runServiceStop as i, runServiceRestart as n, appendGatewayLifecycleAudit as o, runServiceStart as r, createGatewayLifecycleMutationAudit as s, commandInterrupted as t };