openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
408 lines (407 loc) • 19.3 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { l as isValidEnvSecretRefId } from "./ref-contract-b8L-9DrQ.mjs";
import { o as hasConfiguredSecretInput } from "./types.secrets-BmNLLnHp.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./utils-C8YECn2Q.mjs";
import { b as resolveGatewayPort } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { a as isConfigReadFailure } from "./io.invalid-config-DK-BYZ4Y.mjs";
import "./config-CMA-J084.mjs";
import { i as resolveManifestProviderAuthChoices } from "./provider-auth-choices-BfC_56hU.mjs";
import { t as assertSupportedRuntime } from "./runtime-guard-BiEisZ4L.mjs";
import { r as t } from "./i18n-AiHKCZaZ.mjs";
import { n as resolveProviderInstallCatalogEntries } from "./provider-install-catalog-DH6EFiCw.mjs";
import { o as handleReset, t as DEFAULT_WORKSPACE } from "./onboard-helpers-I6fwzX78.mjs";
import { l as resolveOnboardingSetupTarget } from "./onboard-agent-target-D7VNwjZB.mjs";
import { r as isTerminalInteractive } from "./terminal-interactivity-B_L_vZTP.mjs";
import "./onboard-interactive-runner-DkSapFQL.mjs";
import { i as resolveProviderMatch } from "./provider-auth-choice-helpers-BHHQcecj.mjs";
import { a as GENERIC_PROVIDER_AUTH_CHOICES, r as formatAuthChoiceChoicesForCli } from "./auth-choice-options-BjS5hVuU.mjs";
import { t as resolveLegacyOnboardAuthChoice } from "./auth-choice-legacy-B9SvrCvt.mjs";
import { n as validateGatewayWebSocketUrl } from "./onboard-remote-CH2jFnnK.mjs";
import { u as withSetupMigrationTargetLock } from "./setup.migration-snapshot-Brz-tpao.mjs";
import { n as validateOnboardingChoiceOptions, t as rejectOnboardingOption } from "./onboard-options-CrkNjPND.mjs";
import { t as applyNonInteractiveGatewayConfig } from "./gateway-config-CKjXrNgc.mjs";
import { t as inferAuthChoiceFromFlags } from "./auth-choice-inference-D_FdrIA1.mjs";
import path from "node:path";
//#region src/commands/onboard.ts
/**
* Top-level `openclaw onboard` command entrypoint.
*
* It validates global setup flags, performs optional reset handling, and then
* routes to interactive or non-interactive onboarding.
*/
const VALID_RESET_SCOPES = /* @__PURE__ */ new Set([
"config",
"config+creds+sessions",
"full"
]);
function validatePreflightOptions(e, n) {
const reject = (r) => rejectOnboardingOption(e, n, r);
if (e.mode !== void 0 && e.mode !== "local" && e.mode !== "remote") return reject(`Invalid --mode "${String(e.mode)}". Use "local" or "remote", or run ${formatCliCommand("openclaw onboard")} for interactive setup.`);
const r = [
e.remoteUrl !== void 0 ? "--remote-url" : void 0,
e.remoteToken !== void 0 ? "--remote-token" : void 0,
e.remotePassword !== void 0 ? "--remote-password" : void 0
].filter((e) => e !== void 0);
if (e.nonInteractive && (e.mode ?? "local") === "local" && r.length > 0) return reject(`${r.join(" and ")} ${r.length === 1 ? "requires" : "require"} --mode remote in non-interactive setup.`);
for (const [n, r] of [["--remote-token", e.remoteToken], ["--remote-password", e.remotePassword]]) if (r !== void 0 && !r.trim()) return reject(`Invalid ${n}: value cannot be empty.`);
if (e.remoteToken !== void 0 && e.remotePassword !== void 0) return reject("Use either --remote-token or --remote-password, not both.");
if (e.mode === "remote") {
const n = [
[
"--gateway-password",
e.gatewayPassword,
"--remote-password"
],
[
"--gateway-token",
e.gatewayToken,
"--remote-token"
],
[
"--gateway-token-ref-env",
e.gatewayTokenRefEnv,
"--remote-token with --secret-input-mode ref"
]
];
for (const [e, r, i] of n) if (r !== void 0) return reject(`${e} configures local gateway auth. Use ${i} in remote mode.`);
}
if (e.nonInteractive && e.secretInputMode === "ref") {
const n = [
[
"--gateway-password",
e.gatewayPassword,
"OPENCLAW_GATEWAY_PASSWORD"
],
[
"--remote-token",
e.remoteToken,
"OPENCLAW_GATEWAY_TOKEN"
],
[
"--remote-password",
e.remotePassword,
"OPENCLAW_GATEWAY_PASSWORD"
]
];
for (const [e, r, i] of n) {
if (r === void 0) continue;
const n = process.env[i]?.trim();
if (!n) return reject(`${e} requires ${i} to be set when --secret-input-mode ref is used.`);
if (r.trim() !== n) return reject(`${e} does not match ${i}. Set the environment variable to the same value or omit the flag.`);
}
}
if (!validateOnboardingChoiceOptions(e, n)) return false;
if (e.gatewayTokenRefEnv !== void 0) {
const n = e.gatewayTokenRefEnv.trim();
if (!isValidEnvSecretRefId(n)) return reject("Invalid --gateway-token-ref-env. Use an environment variable name like OPENCLAW_GATEWAY_TOKEN.");
if (e.gatewayToken !== void 0) return reject("Use either --gateway-token or --gateway-token-ref-env, not both. Prefer --gateway-token-ref-env to avoid writing plaintext tokens.");
if (!process.env[n]?.trim()) return reject(`Environment variable "${n}" is missing or empty. Export it first, then rerun ${formatCliCommand("openclaw onboard")}.`);
}
if (e.nonInteractive && e.mode === "remote" && !e.remoteUrl?.trim()) return reject(`Missing --remote-url for remote mode. Example: ${formatCliCommand("openclaw onboard --non-interactive --accept-risk --mode remote --remote-url ws://127.0.0.1:3000")}.`);
if (e.nonInteractive && e.mode === "remote" && e.remoteUrl?.trim()) {
const n = validateGatewayWebSocketUrl(e.remoteUrl);
if (n) return reject(n);
}
if (e.nonInteractive && (e.flow === "import" || e.importSource || e.importSecrets) && !e.importFrom?.trim()) return reject(`--import-from is required for non-interactive migration import. Run ${formatCliCommand("openclaw migrate list")} to choose a provider.`);
return true;
}
async function validateResetAuthChoice(e) {
const reject = (n) => rejectOnboardingOption(e.opts, e.runtime, n);
const n = e.opts.authChoice || e.opts.mode === "remote" || !e.opts.nonInteractive && !wantsClassicInteractiveSetup(e.opts) ? void 0 : inferAuthChoiceFromFlags(e.opts, {
config: e.baseConfig,
workspaceDir: e.workspaceDir,
env: process.env
});
if (n && n.matches.length > 1) return reject([
`Multiple ${e.opts.nonInteractive ? "API key" : "provider credential"} flags were provided for ${e.opts.nonInteractive ? "non-interactive" : "interactive"} setup.`,
"Use a single provider flag or pass --auth-choice explicitly.",
`Flags: ${n.matches.map((e) => e.label).join(", ")}`
].join("\n"));
if (!e.opts.nonInteractive && n) return true;
const r = e.opts.authChoice ?? n?.choice;
if (!r) return true;
if (!new Set(formatAuthChoiceChoicesForCli({
config: e.baseConfig,
workspaceDir: e.workspaceDir,
env: process.env
}).split("|")).has(r)) return reject(`Auth choice "${r}" was not matched to a provider setup flow. Run ${formatCliCommand("openclaw onboard")} to choose interactively.`);
const i = {
config: e.baseConfig,
workspaceDir: e.workspaceDir,
env: process.env,
includeUntrustedWorkspacePlugins: false
};
const a = [...resolveManifestProviderAuthChoices(i), ...resolveProviderInstallCatalogEntries(i)];
const o = GENERIC_PROVIDER_AUTH_CHOICES.includes(r);
const s = normalizeOptionalLowercaseString(e.opts.tokenProvider);
const c = n?.matches[0]?.optionKey;
const l = o ? a.find((e) => {
const n = s ? normalizeOptionalLowercaseString(e.providerId) === s || e.providerAliases?.some((e) => normalizeOptionalLowercaseString(e) === s) : c !== void 0 && e.optionKey === c;
const i = e.methodId.toLowerCase();
const a = r === "apiKey" ? i.includes("api") && i.includes("key") : r === "setup-token" ? i === "setup-token" : i.includes("token");
return n && a;
}) : a.find((e) => e.choiceId === r);
if (e.opts.nonInteractive && o && !s && !c) return reject(`Auth choice "${r}" requires --token-provider in non-interactive setup.`);
if (e.opts.nonInteractive && (r === "token" || r === "setup-token") && !e.opts.token?.trim()) return reject(`Auth choice "${r}" requires --token in non-interactive setup.`);
if (e.opts.nonInteractive && o && !l) return reject(`Auth choice "${r}" was not matched to provider "${e.opts.tokenProvider?.trim()}".`);
if (!e.opts.nonInteractive || r === "skip") return true;
const { resolveNonInteractiveApiKey: u } = await import("./api-keys-Cv4eCffg.mjs");
const d = resolveOnboardingSetupTarget(e.baseConfig, e.opts.agentName || e.opts.team ? {
name: e.opts.agentName ?? "coordinator",
workspaceDir: e.opts.team ? path.join(e.workspaceDir, normalizeAgentId(e.opts.agentName ?? "coordinator")) : e.workspaceDir
} : void 0);
if (r === "custom-api-key") {
const { applyCustomApiConfig: n, CustomApiError: r, parseNonInteractiveCustomApiFlags: i, resolveCustomProviderId: a, resolveCustomProviderNoAuth: o, resolveNonInteractiveCustomApiModelIds: s } = await import("./onboard-custom-config-CxQ5n_CF.mjs");
try {
const r = i({
baseUrl: e.opts.customBaseUrl,
modelId: e.opts.customModelId,
compatibility: e.opts.customCompatibility,
apiKey: e.opts.customApiKey,
noAuth: e.opts.customNoAuth,
providerId: e.opts.customProviderId,
supportsImageInput: e.opts.customImageInput
});
const c = a({
config: e.discoveryConfig,
baseUrl: r.baseUrl,
providerId: r.providerId
}).providerId;
const l = e.discoveryConfig.models?.providers?.[c]?.apiKey;
const f = o({
...r,
config: e.discoveryConfig,
providerId: c,
apiKey: r.apiKey ?? process.env.CUSTOM_API_KEY?.trim()
});
const p = f ? void 0 : await u({
provider: c,
cfg: e.baseConfig,
flagValue: e.opts.customApiKey,
flagName: "--custom-api-key",
envVar: "CUSTOM_API_KEY",
runtime: e.runtime,
agentDir: d.agentDir,
workspaceDir: e.workspaceDir,
allowProfile: e.resetScope === "config" && !hasConfiguredSecretInput(l),
required: false,
secretInputMode: e.opts.secretInputMode,
json: e.opts.json
});
if (e.opts.customApiKey?.trim() && !p) return false;
if (!r.modelId && !f && !p && hasConfiguredSecretInput(l)) return reject("Reset would remove the configured discovery credential. Pass --custom-api-key or rerun without --reset.");
const m = await s({
...r,
config: e.discoveryConfig,
noAuth: f,
apiKey: p?.key,
agentDir: d.agentDir
});
n({
...r,
modelId: m[0] ?? "",
config: e.baseConfig,
noAuth: f,
apiKey: p?.key
});
if (f) e.opts.customNoAuth = true;
e.opts.customModelIds = m;
e.opts.customProviderId = c;
} catch (e) {
return reject(e instanceof r && (e.code === "missing_required" || e.code === "invalid_compatibility" || e.code === "no_auth_conflict" || e.code === "no_auth_unsupported") ? e.message : `Invalid custom provider config: ${formatErrorMessage(e)}`);
}
} else {
const n = (l ? resolveProviderMatch((await import("./provider-auth-choice.runtime.js")).resolvePluginProviders({
config: e.baseConfig,
workspaceDir: e.workspaceDir,
mode: "setup",
includeUntrustedWorkspacePlugins: false,
providerRefs: [l.providerId],
activate: true
}), l.providerId) : null)?.auth.find((e) => e.id === l?.methodId || e.wizard?.choiceId === l?.choiceId);
if (!n?.runNonInteractive || !n.validateNonInteractive) return reject(`Auth choice "${r}" cannot be safely preflighted with --reset (${!n ? "provider unavailable" : !n.runNonInteractive ? "non-interactive setup unsupported" : "reset validation unavailable"}). Choose a provider method that supports non-interactive reset validation, or run setup without --reset.`);
if (!await n.validateNonInteractive({
authChoice: r,
config: e.baseConfig,
baseConfig: e.baseConfig,
opts: e.opts,
runtime: e.runtime,
agentDir: d.agentDir,
workspaceDir: e.workspaceDir,
resolveApiKey: async (n) => await u({
...n,
cfg: e.baseConfig,
runtime: e.runtime,
agentDir: d.agentDir,
workspaceDir: e.workspaceDir,
allowProfile: n.allowProfile === false ? false : e.resetScope === "config",
secretInputMode: e.opts.secretInputMode,
json: e.opts.json
})
})) return false;
}
return true;
}
/**
* Interactive onboarding defaults to guided setup. Any explicit
* setup flag beyond this allowlist keeps the classic wizard — those flags are
* a public automation contract and guided setup does not honor them.
* Most false booleans mean "not passed" because the command layer normalizes
* them with Boolean(). False-valued explicit choices preserve undefined when
* omitted, so daemon, Tailscale-reset, and custom-model input overrides are
* special-cased. `--modern` never reaches this dispatch; the command layer
* routes it through the inference-gated OpenClaw.
*/
const GUIDED_SAFE_ONBOARD_KEYS = /* @__PURE__ */ new Set([
"workspace",
"acceptRisk",
"reset",
"resetScope",
"nonInteractive",
"agentName",
"team",
"tui",
"skipUi",
"suppressGatewayTokenOutput"
]);
function wantsClassicInteractiveSetup(e) {
if (e.classic === true) return true;
if (e.installDaemon !== void 0 || e.customImageInput !== void 0) return true;
return Object.entries(e).some(([e, n]) => !GUIDED_SAFE_ONBOARD_KEYS.has(e) && n !== void 0 && n !== false);
}
async function setupWizardCommand(e, n = defaultRuntime) {
await assertSupportedRuntime(n);
const { authChoice: r, deprecated: i } = resolveLegacyOnboardAuthChoice(e.authChoice, { env: process.env });
if (e.nonInteractive && i) {
rejectOnboardingOption(e, n, i.nonInteractiveError);
return;
}
if (i) n.log(i.message);
const a = e.flow === "manual" ? "advanced" : e.flow;
const o = r === e.authChoice && a === e.flow ? e : {
...e,
authChoice: r,
flow: a
};
const reject = (e) => rejectOnboardingOption(o, n, e);
if (o.agentName !== void 0) {
const { validateFirstOnboardingAgentName: e } = await import("./onboard-agent-GWdAerUe.mjs");
const n = e(o.agentName);
if (n) {
reject(`Invalid --agent-name: ${n}`);
return;
}
}
if (!validatePreflightOptions(o, n)) return;
if (o.workspace?.trim()) {
const { validateSetupWorkspacePath: e } = await import("./setup.workspace-DvB5hq_u.mjs");
const n = e(o.workspace.trim());
if (n) {
reject(`Invalid --workspace: ${n}`);
return;
}
}
if (o.team && (o.mode === "remote" || o.importFrom || o.importSource || o.flow === "import" || !o.nonInteractive && wantsClassicInteractiveSetup(o))) {
reject("--team supports local guided or non-interactive onboarding. Remove classic, remote, or import options.");
return;
}
if (o.classic && o.nonInteractive) {
reject("--classic cannot be combined with --non-interactive. Remove --non-interactive to open the classic wizard, or remove --classic for automated setup.");
return;
}
if (o.tui && o.nonInteractive) {
reject("--tui cannot be combined with --non-interactive. Remove --tui for automation, or remove --non-interactive to open the terminal hatch.");
return;
}
if (o.secretInputMode && o.secretInputMode !== "plaintext" && o.secretInputMode !== "ref") {
reject(`Invalid --secret-input-mode. Use "plaintext" or "ref", or run ${formatCliCommand("openclaw onboard")} for the interactive setup.`);
return;
}
if (o.resetScope && !VALID_RESET_SCOPES.has(o.resetScope)) {
reject(`Invalid --reset-scope. Use "config", "config+creds+sessions", or "full". Run ${formatCliCommand("openclaw onboard --reset --reset-scope config")} for a config-only reset.`);
return;
}
if (o.resetScope && !o.reset) {
reject(`--reset-scope requires --reset. Re-run with ${formatCliCommand(`openclaw onboard --reset --reset-scope ${o.resetScope}`)}.`);
return;
}
if (o.nonInteractive && o.acceptRisk !== true) {
reject([
"Non-interactive setup requires explicit risk acknowledgement.",
"Read: https://docs.openclaw.ai/security",
`Re-run with: ${formatCliCommand("openclaw onboard --non-interactive --accept-risk ...")}`
].join("\n"));
return;
}
if (!o.nonInteractive && !isTerminalInteractive()) {
reject(t("wizard.guided.ttyRequired"));
return;
}
if (process.platform === "win32") n.log([
"Windows detected - OpenClaw runs great on WSL2!",
"Native Windows might be trickier.",
"Quick setup: wsl --install (one command, one reboot)",
"Guide: https://docs.openclaw.ai/windows"
].join("\n"));
const s = o.nonInteractive ? (await import("./onboard-non-interactive-BsSnHtXR.mjs")).runNonInteractiveSetup : wantsClassicInteractiveSetup(o) ? (await import("./onboard-interactive-CJ3psnaV.mjs")).runInteractiveSetup : (await import("./commands/onboard-guided.js")).runGuidedOnboarding;
const runSetupAfterOptionalReset = async () => {
if (o.reset) {
const [{ readConfigSnapshotBeforeEngineSelection: e }, { resolveDatabaseFamilyEngines: r }] = await Promise.all([import("./config-preflight-snapshot-DXY8QhxC.mjs"), import("./registry-CkMGXa4B.mjs")]);
const i = await e(process.env, { isolateEnv: false });
const a = o.resetScope ?? "config+creds+sessions";
if (isConfigReadFailure(i) || i.issues.some((e) => e.errorCode === "CONFIG_SOURCE_INVALID")) {
reject("Cannot determine the source database from an unreadable config. Repair the config before using onboard --reset. For a file-only reset without onboarding, use openclaw reset --scope config.");
return;
}
if (Object.values(r(i.config)).includes("postgres")) {
reject("Onboarding reset retains database state and cannot discard its PostgreSQL routing. Rerun without --reset, or use openclaw database port --to sqlite before resetting.");
return;
}
const s = i.sourceConfig ?? (i.valid ? i.config : {});
const c = {};
const l = resolveUserPath(o.workspace ?? DEFAULT_WORKSPACE);
const u = o.workspace ?? s.agents?.defaults?.workspace;
if (a === "full" && u !== void 0 && (typeof u !== "string" || !u.trim())) {
reject("Configured workspace is invalid. Pass --workspace with the workspace to remove, or use a narrower --reset-scope.");
return;
}
const d = resolveUserPath(typeof u === "string" && u.trim() ? u : DEFAULT_WORKSPACE);
if (!await validateResetAuthChoice({
opts: o,
runtime: n,
baseConfig: c,
discoveryConfig: s,
workspaceDir: l,
resetScope: a
})) return;
if (o.nonInteractive && (o.mode ?? "local") !== "remote" && !await applyNonInteractiveGatewayConfig({
nextConfig: c,
opts: o,
runtime: n,
defaultPort: resolveGatewayPort(c)
})) return;
if (o.importFrom || o.importSource || o.importSecrets || o.flow === "import") {
reject("Migration import cannot be combined with --reset because provider input must be planned before any state is removed. Run the import without --reset.");
return;
}
await handleReset(a, d, n);
const { prepareCliDatabaseEngine: f } = await import("./database-engine-selection-CKQdgAU6.mjs");
await f([
"node",
"openclaw",
"onboard"
]);
}
await s(o, n);
};
await withSetupMigrationTargetLock(resolveStateDir(), runSetupAfterOptionalReset);
}
//#endregion
export { setupWizardCommand };