openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
411 lines (410 loc) • 17 kB
JavaScript
import { d as resolveGatewayLaunchAgentLabel } from "./constants-BZisy3jr.mjs";
import { _ as resolveSecretInputRef } from "./types.secrets-BmNLLnHp.mjs";
import { i as resolveEnvironmentValue } from "./process-env-DVJdcOcM.mjs";
import { n as isDangerousHostEnvOverrideVarName, o as normalizeEnvVarKey, r as isDangerousHostEnvVarName } from "./host-env-security-BrTYS4pH.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { p as resolveConfigSecretRef, r as collectEnvSecretRefIds } from "./resolution-facts-xaIKuREs.mjs";
import { n as resolveConfigWidePluginManifestRegistry } from "./io.plugin-metadata-CBwzHw3m.mjs";
import { a as createResolverContext } from "./runtime-shared-BVJ4BbUu.mjs";
import { n as discoverConfigSecretTargets } from "./target-registry-query-le6rMGHo.mjs";
import "./target-registry-C0PdHjLu.mjs";
import { n as resolveGatewayStateDir, r as resolveGatewayTaskScriptPath } from "./paths-CNsU_DAo.mjs";
import { r as resolveSecretProviderIntegrationConfig, t as isPluginIntegrationSecretProviderConfig } from "./provider-integrations-YWHLMzFF.mjs";
import { s as resolveManagedGatewayServiceCommand } from "./service-types-DdxELPHF.mjs";
import { t as collectDurableServiceEnvVarSources } from "./state-dir-dotenv-DM9BdByB.mjs";
import { n as resolveLaunchAgentLabel } from "./launchd-label-DdmmL_TH.mjs";
import { r as omitSecretEgressProxyEnvironment } from "./environment-DkQljHwc.mjs";
import { n as mergeServicePath } from "./service-path-policy-BdT8DqoB.mjs";
import { d as OPENCLAW_WRAPPER_ENV_KEY, f as resolveGatewayProgramArguments, h as resolveOpenClawWrapperPath } from "./service-hQiIzcTo.mjs";
import { a as resolveLaunchAgentEnvWrapperPath } from "./launchd-service-files-BgSRMq9s.mjs";
import { c as normalizeServiceEnvKey, d as readManagedServiceEnvKeysFromEnvironment, i as formatManagedServiceEnvKeys, p as writeManagedServiceEnvKeysToEnvironment, u as readEnvironmentValueSource } from "./service-managed-env-BculT5iw.mjs";
import { t as evaluateGatewayAuthSurfaceStates } from "./runtime-gateway-auth-surfaces-Bwh_ghBD.mjs";
import { t as collectPluginConfigAssignments } from "./runtime-config-collectors-plugins-B77S_ham.mjs";
import { n as hasSecretRefCandidate } from "./runtime-secret-scan-COeHTBgF.mjs";
import { i as resolveDaemonServicePathDirs, n as resolveDaemonInstallRuntimeInputs, t as emitNodeRuntimeWarning } from "./daemon-install-runtime-warning-0qx7euD-.mjs";
import { r as buildServiceEnvironment } from "./service-env-BbgmtKhw.mjs";
import path from "node:path";
//#region src/commands/daemon-install-helpers.ts
const NON_PERSISTED_CONFIG_SECRET_ENV_TARGET_IDS = /* @__PURE__ */ new Set(["gateway.auth.password", "gateway.auth.token"]);
function collectAuthProfileSecretRefs(e) {
if (!e) return [];
return Object.values(e.profiles).flatMap((e) => {
const t = e.type === "api_key" ? e.keyRef : e.type === "token" ? e.tokenRef : void 0;
return t ? [t] : [];
});
}
function* configSecretRefsForService(e) {
for (const t of discoverConfigSecretTargets(e)) {
if (!t.entry.includeInPlan) continue;
const { ref: n } = resolveSecretInputRef({
value: resolveConfigSecretRef({
config: e,
path: t.path,
value: t.value,
defaults: e.secrets?.defaults,
includeResolved: true
}),
refValue: t.refValue,
defaults: e.secrets?.defaults
});
if (n) yield {
target: t,
ref: n
};
}
}
const PRESERVED_OPENCLAW_OPERATOR_OPT_IN_ENV_KEYS = /* @__PURE__ */ new Set([
"OPENCLAW_CLI_CONTAINER_BYPASS",
"OPENCLAW_CONFIG_READONLY",
"OPENCLAW_CONFIG_READONLY_NOTICE",
"OPENCLAW_CONTAINER_HINT",
"OPENCLAW_GATEWAY_STARTUP_TRACE"
]);
function collectExistingServiceEnvVars(e, t) {
const n = {};
for (const [r, i] of Object.entries(e ?? {})) {
const e = normalizeEnvVarKey(r, { portable: true });
if (!e || !t(e.toUpperCase()) || isDangerousHostEnvVarName(e) || isDangerousHostEnvOverrideVarName(e)) continue;
const a = i?.trim();
if (!a) continue;
n[e] = a;
}
return n;
}
function omitEnvironmentEntriesShadowedBy(e, t) {
const n = new Set(t.flatMap((e) => Object.keys(e).flatMap((e) => {
const t = normalizeEnvVarKey(e, { portable: true })?.toUpperCase();
return t ? [t] : [];
})));
return Object.fromEntries(Object.entries(e).filter(([e]) => {
const t = normalizeEnvVarKey(e, { portable: true })?.toUpperCase();
return !t || !n.has(t);
}));
}
async function buildGatewayInstallEnvironment(e) {
const { stateDirDotEnvEnvironment: t, configEnvironment: n, durableEnvironment: r } = collectDurableServiceEnvVarSources({
env: e.env,
config: e.config
});
const i = hasSecretRefCandidate(e.config, e.config?.secrets?.defaults) || collectEnvSecretRefIds(e.config).size > 0;
const a = /* @__PURE__ */ new Set();
const o = {};
{
const { env: n, config: r, warn: s } = e;
if (r && i) {
const e = evaluateGatewayAuthSurfaceStates({
config: r,
env: n,
defaults: r.secrets?.defaults
});
for (const { target: i, ref: c } of configSecretRefsForService(r)) {
if (c.source !== "env") continue;
const r = normalizeEnvVarKey(c.id, { portable: true });
if (!r) {
s?.(`Config SecretRef env id "${c.id}" is not portable and was not added to the service environment`, "Config SecretRef");
continue;
}
if (isDangerousHostEnvVarName(r) || isDangerousHostEnvOverrideVarName(r)) {
s?.(`Config SecretRef env ref "${r}" blocked by host-env security policy`, "Config SecretRef");
continue;
}
if (NON_PERSISTED_CONFIG_SECRET_ENV_TARGET_IDS.has(i.entry.id)) {
if (e[i.entry.id]?.active) a.add(r.toUpperCase());
continue;
}
a.add(r.toUpperCase());
if (Object.hasOwn(t, r)) continue;
const l = n[r]?.trim();
if (!l) continue;
o[r] = l;
}
}
}
let s = e.authStore;
if (!s) {
const { hasAnyAuthProfileStoreSourceAsync: e } = await import("./daemon-install-auth-profiles-source.runtime.js");
if (await e()) {
const { loadAuthProfileStoreForSecretsRuntimeAsync: e } = await import("./daemon-install-auth-profiles-store.runtime.js");
s = await e();
}
}
const c = {};
{
const { env: t, config: n, warn: a } = e;
if (n) {
let e;
const o = [];
if (i) {
for (const { ref: e } of configSecretRefsForService(n)) if (e.source === "exec") o.push({
ref: e,
warningTitle: "Config SecretRef"
});
}
for (const e of collectAuthProfileSecretRefs(s)) if (e.source === "exec") o.push({
ref: e,
warningTitle: "Auth profile"
});
if (i) {
const e = createResolverContext({
sourceConfig: n,
env: t
});
collectPluginConfigAssignments({
config: n,
defaults: n.secrets?.defaults,
context: e
});
for (const t of e.assignments.map((e) => e.ref)) if (t.source === "exec") o.push({
ref: t,
warningTitle: "Plugin config SecretRef"
});
}
for (const { ref: i, warningTitle: s } of o) {
const o = n.secrets?.providers?.[i.provider];
if (!o || o.source !== "exec") continue;
const l = isPluginIntegrationSecretProviderConfig(o) ? (() => {
e ??= resolveConfigWidePluginManifestRegistry({
config: n,
env: t
});
const r = resolveSecretProviderIntegrationConfig({
manifestRegistry: e,
providerAlias: i.provider,
providerConfig: o,
config: n,
env: t
});
if (!r.ok) {
a?.(`Exec SecretRef plugin provider "${i.provider}" could not be resolved for service environment planning: ${r.reason}`, s);
return;
}
return r.providerConfig;
})() : o;
if (!l) continue;
for (const e of l.passEnv ?? []) {
const n = normalizeEnvVarKey(e, { portable: true });
if (!n) {
a?.(`Exec SecretRef passEnv id "${e}" is not portable and was not added to the service environment`, s);
continue;
}
const i = Object.hasOwn(t, n) ? t[n]?.trim() : void 0;
if (!i) continue;
if (isDangerousHostEnvVarName(n) || isDangerousHostEnvOverrideVarName(n) && n.toUpperCase() !== "HOME") {
a?.(`Exec SecretRef passEnv ref "${n}" blocked by host-env security policy`, s);
continue;
}
if (Object.hasOwn(r, n)) continue;
c[n] = i;
}
}
}
}
const l = {};
for (const t of collectAuthProfileSecretRefs(s)) {
if (t.source !== "env") continue;
const n = normalizeEnvVarKey(t.id, { portable: true });
if (!n) continue;
if (isDangerousHostEnvVarName(n) || isDangerousHostEnvOverrideVarName(n)) {
e.warn?.(`Auth profile env ref "${n}" blocked by host-env security policy`, "Auth profile");
continue;
}
if (e.platform === "linux") a.add(n.toUpperCase());
const r = e.env[n]?.trim();
if (!r) continue;
l[n] = r;
}
let u = {};
{
const { env: t, config: n, existingEnvironment: i, platform: a } = e;
if (a === "linux") {
const e = readManagedServiceEnvKeysFromEnvironment(i);
const a = new Set([
...Object.keys(r),
...Object.keys(l),
...Object.entries(i ?? {}).flatMap(([n, r]) => e.has(n.toUpperCase()) && t[n]?.trim() !== r?.trim() ? [] : [n])
].map((e) => e.toUpperCase()));
const o = new Map(Object.entries(t).flatMap(([e, t]) => {
const n = normalizeEnvVarKey(e, { portable: true })?.toUpperCase();
const r = t?.trim();
return n && n.endsWith("_API_KEY") && !n.endsWith("_ADMIN_API_KEY") && !a.has(n) && r && !isDangerousHostEnvVarName(n) && !isDangerousHostEnvOverrideVarName(n) ? [[n, r]] : [];
}));
if (o.size > 0) {
const { isManifestPluginAvailableForControlPlane: e, loadManifestMetadataSnapshot: r } = await import("./manifest-contract-eligibility-D8Uu36ng.mjs");
const i = n ?? {};
const a = r({
config: i,
env: t
});
u = Object.fromEntries(a.plugins.flatMap((t) => {
if (t.origin !== "bundled" && t.trustedOfficialInstall !== true || !e({
snapshot: a,
plugin: t,
config: i
})) return [];
const n = new Set((t.providerAuthChoices ?? []).filter(({ method: e, appGuidedSecret: t, onboardingScopes: n }) => e === "api-key" && t === true && (!n || n.includes("text-inference"))).map(({ provider: e }) => e));
return (t.setup?.providers ?? []).filter(({ id: e }) => n.has(e)).flatMap(({ envVars: e = [] }) => e.flatMap((e) => {
const t = normalizeEnvVarKey(e, { portable: true })?.toUpperCase();
const n = t ? o.get(t) : void 0;
return t && n ? [[t, n]] : [];
}));
}));
}
}
}
const d = omitEnvironmentEntriesShadowedBy(t, [
n,
o,
c,
l
]);
const f = readManagedServiceEnvKeysFromEnvironment(e.existingEnvironment);
const p = collectExistingServiceEnvVars(e.existingEnvironment, (e) => e !== "HOME" && e !== "PATH" && e !== "TMPDIR" && e !== "HOMEBREW_PREFIX" && (!e.startsWith("OPENCLAW_") || PRESERVED_OPENCLAW_OPERATOR_OPT_IN_ENV_KEYS.has(e)) && !f.has(e));
const m = {};
const h = {};
function addServiceEnvPlanEntries(e, t) {
for (const [n, r] of Object.entries(e)) {
if (typeof r !== "string" || !r.trim()) {
if (t.includeRawKeys) {
m[n] = r;
h[n] = "inline";
}
continue;
}
const e = normalizeServiceEnvKey(n);
if (!e || t.includeKeys && !t.includeKeys.has(e)) continue;
m[n] = r;
const i = typeof t.valueSource === "function" ? t.valueSource({ normalizedKey: e }) : t.valueSource;
h[n] = i ?? "inline";
}
}
addServiceEnvPlanEntries(p, { valueSource: ({ normalizedKey: t }) => readEnvironmentValueSource(e.existingEnvironmentValueSources, t) ?? "inline" });
addServiceEnvPlanEntries(u, { valueSource: "file" });
addServiceEnvPlanEntries(t, {});
addServiceEnvPlanEntries(n, {});
addServiceEnvPlanEntries(c, {});
const g = Object.fromEntries([...a].map((e) => [e, "1"]));
const _ = formatManagedServiceEnvKeys({
...r,
...g
}, { omitKeys: Object.keys(e.serviceEnvironment) });
const v = omitEnvironmentEntriesShadowedBy(collectExistingServiceEnvVars(e.existingEnvironment, (e) => a.has(e)), [
d,
o,
c,
l
]);
const { serviceEnvironment: y, platform: b } = e;
const x = b === "darwin" && Boolean(y.OPENCLAW_LAUNCHD_LABEL?.trim());
writeManagedServiceEnvKeysToEnvironment(m, _);
if (m.OPENCLAW_SERVICE_MANAGED_ENV_KEYS) h.OPENCLAW_SERVICE_MANAGED_ENV_KEYS = "inline";
addServiceEnvPlanEntries(l, { valueSource: b === "linux" ? "file" : "inline" });
const S = readManagedServiceEnvKeysFromEnvironment({ OPENCLAW_SERVICE_MANAGED_ENV_KEYS: _ });
if (S.size > 0) {
if (x || b === "linux") addServiceEnvPlanEntries(v, {
includeKeys: S,
valueSource: "file"
});
if (x) addServiceEnvPlanEntries(d, {
includeKeys: S,
valueSource: "inline"
});
addServiceEnvPlanEntries(o, {
includeKeys: S,
valueSource: b === "linux" ? "file" : "inline"
});
}
addServiceEnvPlanEntries(e.serviceEnvironment, { includeRawKeys: true });
const C = mergeServicePath(e.serviceEnvironment.PATH, e.existingEnvironment?.PATH, e.serviceEnvironment.TMPDIR, e.platform);
if (C) {
m.PATH = C;
h.PATH = "inline";
}
for (const e of Object.keys(h)) if (!Object.hasOwn(m, e)) delete h[e];
return {
environment: m,
environmentValueSources: h
};
}
async function buildGatewayInstallPlan(e) {
const t = e.platform ?? process.platform;
const n = omitSecretEgressProxyEnvironment(e.env, t);
const r = omitSecretEgressProxyEnvironment(e.existingEnvironment ?? {}, t);
n.NODE_EXTRA_CA_CERTS = resolveEnvironmentValue(n, "NODE_EXTRA_CA_CERTS", t) ?? resolveEnvironmentValue(r, "NODE_EXTRA_CA_CERTS", t);
const i = e.wrapperPath ?? n["OPENCLAW_WRAPPER"];
const a = t === "win32" ? resolveGatewayTaskScriptPath(n) : t === "darwin" ? resolveLaunchAgentEnvWrapperPath(n, resolveLaunchAgentLabel(n)) : void 0;
const o = a !== void 0 && normalizeServicePathForCompare(i, t) === normalizeServicePathForCompare(a, t);
if (o) e.warn?.(t === "win32" ? `Ignoring ${OPENCLAW_WRAPPER_ENV_KEY} because it points to the Windows task script; using the OpenClaw gateway entrypoint directly to avoid a recursive gateway.cmd wrapper.` : `Ignoring ${OPENCLAW_WRAPPER_ENV_KEY} because it points to the generated LaunchAgent environment wrapper; using the OpenClaw gateway entrypoint directly to avoid a self-referencing wrapper.`);
const s = o ? void 0 : await resolveOpenClawWrapperPath(i);
const { devMode: c, runtime: l, runtimePath: u } = await resolveDaemonInstallRuntimeInputs({
env: n,
runtime: e.runtime,
runtimeExplicit: e.runtimeExplicit,
devMode: e.serviceCli ? false : e.devMode,
runtimePath: e.runtimePath,
pinnedRuntimePath: e.pinnedRuntimePath,
wrapperPath: s,
warn: e.warn
});
const d = { ...n };
if (s) d[OPENCLAW_WRAPPER_ENV_KEY] = s;
else if (o) delete d[OPENCLAW_WRAPPER_ENV_KEY];
const { programArguments: f, workingDirectory: p } = await resolveGatewayProgramArguments({
port: e.port,
allowUnconfigured: e.allowUnconfigured ?? (e.config?.gateway?.mode === "remote" && resolveManagedGatewayServiceCommand(e.existingCommand)?.programArguments.includes("--allow-unconfigured") === true),
dev: c,
runtime: l,
runtimePath: u,
wrapperPath: s,
cliEntrypoint: e.serviceCli?.entrypoint ?? void 0,
...e.existingCommand ? { existingCommand: e.existingCommand } : {}
});
await emitNodeRuntimeWarning({
env: n,
runtime: l,
nodeProgram: f[0],
warn: e.warn,
title: "Gateway runtime"
});
const m = buildServiceEnvironment({
env: d,
execPath: e.serviceCli?.executable,
port: e.port,
runtime: l,
existingNodeOptions: resolveManagedGatewayServiceCommand(e.existingCommand)?.environment?.NODE_OPTIONS,
launchdLabel: t === "darwin" ? resolveGatewayLaunchAgentLabel(d.OPENCLAW_PROFILE) : void 0,
platform: t,
extraPathDirs: resolveDaemonServicePathDirs({
runtimePath: u,
argv: e.serviceCli && [e.serviceCli.executable, ...e.serviceCli.entrypoint ? [e.serviceCli.entrypoint] : []],
env: d,
platform: t
})
});
const { environment: h, environmentValueSources: g } = await buildGatewayInstallEnvironment({
env: d,
config: e.config,
authStore: e.authStore,
warn: e.warn,
serviceEnvironment: m,
existingEnvironment: r,
existingEnvironmentValueSources: e.existingEnvironmentValueSources,
platform: t
});
return {
runtime: l,
programArguments: f,
workingDirectory: p || (t === "darwin" ? resolveGatewayStateDir(d) : void 0),
environment: h,
...Object.keys(g).length > 0 ? { environmentValueSources: g } : {}
};
}
function normalizeServicePathForCompare(e, t) {
const n = e?.trim();
if (!n) return;
return t === "win32" ? path.win32.resolve(n).toLowerCase() : path.resolve(n);
}
function gatewayInstallErrorHint(e = process.platform) {
return e === "win32" ? "Tip: native Windows now falls back to a per-user Startup-folder login item when Scheduled Task creation is denied; if install still fails, rerun from an elevated PowerShell or skip service install." : `Tip: rerun \`${formatCliCommand("openclaw gateway install")}\` after fixing the error.`;
}
//#endregion
export { gatewayInstallErrorHint as n, buildGatewayInstallPlan as t };