openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
560 lines (559 loc) • 21.6 kB
JavaScript
import { c as resolveUserPath } from "../home-dir-EKmgmdPG.mjs";
import { a as displayPath } from "../utils-C8YECn2Q.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 { c as withConsoleSubsystemsSuppressed } from "../console-BkI11Tqj.mjs";
import { n as formatConfigIssueLines } from "../issue-format-WaYQX-7p.mjs";
import { r as hasResolvedRosterBeforeMigrations } from "../agent-roster-provenance-DiT1dDed.mjs";
import { r as t } from "../i18n-AiHKCZaZ.mjs";
import { t as isUnconfiguredConfigSource } from "../fresh-install-config-6qQ4_7BH.mjs";
import { c as resolveOnboardingAgentTarget, u as resolveSystemAgentOnboardingTarget } from "../onboard-agent-target-D7VNwjZB.mjs";
import { n as showSessionMigrationWarnings, t as promptFirstOnboardingAgent } from "../onboard-first-agent-BLJetyiU.mjs";
import { c as requestTelemetryConsent, f as getSecurityNoteTitle, l as requireRiskAcknowledgement } from "../setup.shared-2t79532Q.mjs";
import { t as enableDefaultOnboardingInternalHooks } from "../onboard-hooks-PtiyNF0u.mjs";
import { r as isTerminalInteractive } from "../terminal-interactivity-B_L_vZTP.mjs";
import { n as runInteractiveOnboarding, t as runGuidedOnboardingHandoff } from "../onboard-interactive-runner-DkSapFQL.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
//#region src/commands/onboard-guided-consent.ts
async function persistGuidedAccessMode(e) {
const { mutateConfigFileWithRetry: n } = await import("../config/config.js");
await n({ mutate: (n) => {
if (n.wizard?.accessMode === e) return;
n.wizard = {
...n.wizard,
accessMode: e
};
} });
}
async function persistRiskAcknowledgement(e) {
const n = e.wizard?.securityAcknowledgedAt;
if (!n) return;
const { mutateConfigFileWithRetry: r } = await import("../config/config.js");
return (await r({ mutate: (r) => {
if (!r.wizard?.securityAcknowledgedAt) r.wizard = {
...r.wizard,
securityAcknowledgedAt: n
};
if (e.telemetry?.consentedAt && !r.telemetry?.consentedAt) r.telemetry = e.telemetry;
} })).nextConfig.wizard?.securityAcknowledgedAt;
}
async function requestGuidedOnboardingConsent(e) {
const { opts: n, prompter: r, config: i, offerQuickstart: a } = e;
let o = false;
if (a) {
if (!i.wizard?.securityAcknowledgedAt) await r.note(t("wizard.guided.laneSecurityLine"), getSecurityNoteTitle());
o = await r.select({
message: t("wizard.guided.laneQuestion"),
options: [{
value: "quick",
label: t("wizard.guided.laneQuickLabel"),
hint: t("wizard.guided.laneQuickHint")
}, {
value: "custom",
label: t("wizard.guided.laneCustomLabel"),
hint: t("wizard.guided.laneCustomHint")
}],
initialValue: "quick"
}) === "quick";
}
let s = await requireRiskAcknowledgement({
opts: o ? {
...n,
acceptRisk: true
} : n,
prompter: r,
config: i
});
if (!o) s = await requestTelemetryConsent({
opts: n,
prompter: r,
config: s
});
let c = s.wizard?.securityAcknowledgedAt;
if (!i.wizard?.securityAcknowledgedAt || !i.telemetry?.consentedAt && s.telemetry?.consentedAt) {
const n = await (e.persistRiskAcknowledgement ?? persistRiskAcknowledgement)(s);
if (n) {
c = n;
s = {
...s,
wizard: {
...s.wizard,
securityAcknowledgedAt: c
}
};
}
}
if (!c) throw new Error("Local onboarding requires its persisted security acknowledgement.");
return {
quickstart: o,
config: s,
securityAcknowledgedAt: c
};
}
//#endregion
//#region src/commands/onboard-guided-manual.ts
const SETUP_FAILURE_REASON_KEYS = {
auth: "wizard.guided.failureAuth",
rate_limit: "wizard.guided.failureRateLimit",
billing: "wizard.guided.failureBilling",
timeout: "wizard.guided.failureTimeout",
format: "wizard.guided.failureFormat",
unavailable: "wizard.guided.failureUnavailable",
unknown: "wizard.guided.failureUnknown"
};
async function runManualStage(e) {
const n = e.detection.candidates.map((e) => ({
value: `candidate:${e.kind}`,
label: t("wizard.guided.tryCandidate", {
label: e.label,
detail: e.detail
})
}));
const r = n.length ? [{
value: "detected-ai",
label: t("wizard.guided.detectedGroupLabel"),
hint: e.detection.candidates.map((e) => e.label).join(", "),
methodMessage: t("wizard.guided.detectedGroupPrompt"),
options: n
}] : [];
const { promptAuthChoiceGrouped: i } = await import("../auth-choice-prompt-BrhxsDsz.mjs");
while (true) {
const n = await i({
prompter: e.prompter,
includeSkip: true,
assistantVisibleOnly: false,
additionalGroups: r,
config: e.config,
workspaceDir: e.workspace
});
if (n === "skip") return null;
let a;
if (n.startsWith("candidate:")) {
const r = n.slice(10);
a = e.detection.candidates.find((e) => e.kind === r);
if (!a) continue;
}
const o = [
...e.detection.manualProviders,
...e.detection.authOptions,
...e.detection.prepareOptions ?? []
].find((e) => e.id === n);
const s = a ? a.modelTarget : o ? o.modelTarget : (await import("../provider-flow-DlT4Tpnr.mjs")).resolveProviderSetupFlowContributions({
config: e.config,
workspaceDir: e.workspace
}).find((e) => e.option.value === n)?.option.modelTarget;
const c = await withConsoleSubsystemsSuppressed(() => e.activate({
kind: a?.kind ?? "provider-auth",
...s ? { modelTarget: s } : {},
...a ? { modelRef: a.modelRef } : { authChoice: n },
workspace: e.workspace,
surface: "cli",
runtime: e.runtime,
prompter: e.prompter
}));
if (c.ok) return [...c.lines, t("wizard.guided.repliedIn", { seconds: (c.latencyMs / 1e3).toFixed(1) })];
await e.prompter.note(t("wizard.guided.testFailure", {
label: a?.label ?? n,
reason: t(SETUP_FAILURE_REASON_KEYS[c.status]),
detail: c.error
}), t("wizard.guided.aiAccessTitle"));
if (a?.kind === "existing-model") await e.prompter.note(t("wizard.guided.existingModelKept"), t("wizard.guided.aiAccessTitle"));
}
}
//#endregion
//#region src/commands/onboard-guided.ts
async function runGuidedOnboardingFlow(e, n, r) {
const i = await import("../onboard-helpers-Cy-Vj-Pl.mjs");
const { createClackPrompter: a } = await import("../clack-prompter-190puVWq.mjs");
const o = a();
await i.printWizardHeader(n);
await o.intro(t("wizard.guided.custodianIntro"));
await o.note(t("wizard.guided.escapeHatches"), t("wizard.guided.welcomeTitle"));
const { readConfigFileSnapshot: s } = await import("../config/config.js");
const c = await s();
if (c.exists && !c.valid) {
const e = c.issues.length > 0 ? formatConfigIssueLines(c.issues, "-").join("\n") : t("wizard.guided.invalidConfigUnknown");
await o.note(t("wizard.guided.invalidConfigDetails", {
path: displayPath(c.path),
issues: e
}), t("wizard.setup.invalidConfigTitle"));
await o.outro(t("wizard.guided.invalidConfigRepair", {
fixCommand: formatCliCommand("openclaw doctor --fix"),
inspectCommand: formatCliCommand("openclaw config validate")
}));
n.exit(1);
return null;
}
const l = c.exists && c.valid ? c.sourceConfig ?? c.config : {};
const u = isUnconfiguredConfigSource(c.sourceConfigBeforeMigrations ?? l);
const d = (r.handoffMode ?? "hatch") === "hatch";
const f = d ? await import("../state/local-onboarding-state.js") : void 0;
const p = f?.readLocalOnboardingState(c.path);
const m = d && (!c.exists || u) && l.wizard?.accessMode !== "guarded" && e.nonInteractive !== true && e.skipUi !== true && e.tui !== true;
const h = await requestGuidedOnboardingConsent({
opts: e,
prompter: o,
config: l,
offerQuickstart: m,
persistRiskAcknowledgement: r.persistRiskAcknowledgement
});
const { quickstart: g } = h;
const { config: _, securityAcknowledgedAt: v } = h;
let y = c.exists ? f?.readLocalOnboardingStateForConfig(c.path, l) : void 0;
const b = y?.status === "pending";
const x = hasResolvedRosterBeforeMigrations(c);
if (e.team && x) throw new Error("An agent roster already exists. Use `openclaw agents team create` to add a team.");
const S = b && y?.teamCoordinatorId && !x ? {
name: y.teamCoordinatorId,
team: true
} : await promptFirstOnboardingAgent(x, e.agentName, o, g, {
team: e.team,
offerTeam: e.nonInteractive !== true
});
if (p?.status === "pending" && y === void 0) {
const e = await s();
const n = e.valid ? (e.sourceConfig ?? e.config).wizard?.securityAcknowledgedAt : void 0;
if (n === p.securityAcknowledgedAt || n && n !== v) throw new Error("Another onboarding run already owns this installation. Retry setup.");
}
const C = !c.exists || p?.status === "pending" && y === void 0 || p?.status === "completed" && u;
const w = S?.team ? normalizeAgentId(S.name) : b && x ? y?.teamCoordinatorId ?? resolveSystemAgentOnboardingTarget(l).agentId : void 0;
if (y?.status === "pending" && e.workspace?.trim() && resolveUserPath(e.workspace.trim()) !== resolveUserPath(y.workspace)) throw new Error("Another onboarding run owns a different workspace. Retry onboarding with its approved workspace.");
const assertLocalSetupOwner = (e) => {
if (y?.status === "pending" && f?.readLocalOnboardingStateForConfig(c.path, e)?.runId !== y.runId) throw new Error("Another onboarding run replaced this setup operation. Retry onboarding.");
};
let T = "full";
if (d && !g) T = await o.select({
message: t("wizard.guided.accessQuestion"),
options: [{
value: "full",
label: t("wizard.guided.accessFullLabel"),
hint: t("wizard.guided.accessFullHint")
}, {
value: "guarded",
label: t("wizard.guided.accessGuardedLabel"),
hint: t("wizard.guided.accessGuardedHint")
}],
initialValue: l.wizard?.accessMode === "guarded" ? "guarded" : "full"
}) === "guarded" ? "guarded" : "full";
if (d && l.wizard?.accessMode !== T) await (r.persistAccessMode ?? persistGuidedAccessMode)(T);
const E = resolveUserPath(e.workspace?.trim() || (b ? y?.workspace : void 0) || _.agents?.defaults?.workspace?.trim() || i.DEFAULT_WORKSPACE);
const D = w ? x ? resolveOnboardingAgentTarget(l, w).workspaceDir : path.join(E, w) : E;
let O = (b ? y?.teamCoordinatorId : void 0) ?? (S?.team ? normalizeAgentId(S.name) : void 0);
if (b && x) {
const { matchesLocalSetupWorkspace: e } = await import("../setup-recovery-BiUnF-eU.mjs");
if (y?.teamCoordinatorId && !await e(l, E, y.teamCoordinatorId)) throw new Error("The pending team no longer matches its approved roster and workspace. Inspect `openclaw agents list` and repair the team before retrying setup.");
if (!O && w && await e(l, E, w)) O = w;
}
const k = r.activate ?? (await import("../system-agent/setup-inference.js")).activateSetupInference;
const A = r.detect ?? (await import("../system-agent/setup-inference.js")).detectSetupInference;
let j;
const claimLocalSetup = (e) => {
if (!f) return;
const n = e.wizard?.securityAcknowledgedAt;
if (n !== v) throw new Error("The onboarding configuration changed before inference could be saved. Retry onboarding.");
if (y?.status === "pending") {
assertLocalSetupOwner(e);
return;
}
const r = randomUUID();
const i = f.beginLocalOnboarding({
configPath: c.path,
workspace: E,
...O ? { teamCoordinatorId: O } : {},
securityAcknowledgedAt: n,
runId: r,
...C ? {
replace: true,
...p ? { expectedRunId: p.runId } : {}
} : {}
});
if (i.runId !== r) throw new Error("Another onboarding run already owns this installation. Retry setup.");
y = i;
};
const assertLocalSetupEffects = () => {
if (!y || !f) return;
const e = f.readLocalOnboardingState(c.path);
if (e?.status !== "pending" || e.runId !== y.runId || e.securityAcknowledgedAt !== y.securityAcknowledgedAt) throw new Error("Another onboarding run replaced this setup operation. Retry onboarding.");
};
const activate = async (e) => {
const n = b && x && y?.teamCoordinatorId ? {
...e,
agentId: y.teamCoordinatorId
} : e;
if (!f || !b && (l.gateway || j?.setupComplete === true)) return await k(n);
return await k({
...n,
onCommitStarted: (n) => {
e.onCommitStarted?.(n);
claimLocalSetup(n);
}
});
};
const M = T === "full" || await o.select({
message: t("wizard.guided.lookAroundQuestion"),
options: [{
value: "look",
label: t("wizard.guided.lookAroundYes")
}, {
value: "manual",
label: t("wizard.guided.lookAroundManual")
}],
initialValue: "look"
}) !== "manual";
if (M) {
const e = o.progress(t("wizard.guided.detecting"));
j = await A();
e.stop(t("wizard.guided.detected"));
if (j.candidates.length === 0) {
await o.note(t("wizard.guided.foundNothing"), t("wizard.guided.detectedTitle"));
if (j.recommendedInstalls.length > 0) {
const e = j.recommendedInstalls.map((e) => t("wizard.guided.recommendedInstall", {
label: e.label,
hint: e.hint,
website: e.website
}));
await o.note(e.join("\n"), t("wizard.guided.recommendedInstallsTitle"));
}
} else {
const e = j.candidates.map((e) => t("wizard.guided.detectedCandidate", {
label: e.label,
detail: e.detail,
recommended: ""
}));
await o.note(e.join("\n"), t("wizard.guided.detectedTitle"));
const n = !d ? [] : j.candidates.filter((e) => e.kind === "claude-cli" || e.kind === "codex-cli").map((e) => e.label);
if (n.length > 0) await o.note(t("wizard.guided.codingAgentQuip", { labels: n.join(", ") }), t("wizard.guided.detectedTitle"));
}
if (j.unavailableCandidates.length > 0) {
const e = j.unavailableCandidates.map((e) => t("wizard.guided.unavailableCandidate", {
label: e.label,
detail: e.detail,
reason: e.reason
}));
await o.note(e.join("\n"), t("wizard.guided.unavailableTitle"));
}
} else {
const { listManualSetupInferenceOptions: e } = await import("../system-agent/setup-inference.js");
j = {
candidates: [],
unavailableCandidates: [],
recommendedInstalls: [],
...await e()
};
}
const N = await runManualStage({
detection: j,
config: l,
workspace: E,
runtime: n,
prompter: o,
activate
});
const P = N === null;
if (f && (b || !l.gateway && !j.setupComplete)) {
const { withConfigMutationExclusive: e } = await import("../config/config.js");
await e(async (e) => claimLocalSetup(e));
}
if (N?.length) await o.note(N.join("\n"), t("wizard.guided.appliedTitle"));
const F = await s();
let I = F.valid ? F.sourceConfig ?? F.config : _;
const importMemories = async () => {
await (r.runSetupMemoryImportStep ?? (await import("../setup.memory-import-DvHgkMyZ.mjs")).runSetupMemoryImportStep)({
config: I,
prompter: o,
runtime: n,
...w ? { agentId: w } : {}
});
};
if (!d) {
if (P) {
await o.note(t("wizard.guided.nextStepsWithoutAi", { workspace: E }), t("wizard.guided.nextStepsTitle"));
return null;
}
if (M) await importMemories();
return {
workspace: D,
next: "chat",
...S ? { agentName: S.name } : {}
};
}
const L = y?.status !== "pending" && Boolean(j?.setupComplete || l.gateway);
let R = false;
const { resolveSetupWorkspaceSelection: z } = await import("../setup.workspace-DvB5hq_u.mjs");
const B = await z({
baseConfig: l,
requestedWorkspaceDir: E,
approvedWorkspaceDir: b && O ? y?.workspace : void 0,
prompter: o,
canConfirmMove: !L
});
const { allowWorkspaceChange: V, conflict: H } = B;
const U = B.workspaceDir;
if (y?.status === "pending" && resolveUserPath(U) !== y.workspace) throw new Error("Another onboarding run owns a different workspace. Retry onboarding with its approved workspace.");
if (L) {
if (!P) await o.note(t("wizard.guided.alreadySetUp"), t("wizard.guided.welcomeTitle"));
if (H) await o.note(t("wizard.guided.workspaceConflictClassic", { command: formatCliCommand("openclaw onboard --classic") }), t("wizard.setup.workspaceConflictTitle"));
if (S) {
const { ensureOnboardingAgent: e } = await import("../onboard-agent-GWdAerUe.mjs");
const n = await e({
config: I,
workspace: U,
baseConfig: I,
firstAgent: S
});
I = n.config;
await showSessionMigrationWarnings(o, n.sessionMigrationWarnings);
}
} else {
const r = o.progress(t("wizard.guided.settingUp"));
let i = t("wizard.guided.setupFailed");
try {
if (y?.status === "pending") {
const e = await s();
if (!e.exists || !e.valid || resolveUserPath(e.path) !== y.configPath) throw new Error("Another onboarding run replaced this setup operation. Retry onboarding.");
assertLocalSetupOwner(e.sourceConfig ?? e.config);
}
const { applySystemAgentSetup: a } = await import("../setup-apply-cA4DDEpp.mjs");
const c = await withConsoleSubsystemsSuppressed(() => a({
workspace: E,
...S ? { firstAgent: S } : {},
...O ? { teamCoordinatorId: O } : {},
allowWorkspaceChange: V || y?.status === "pending",
...b ? { resume: true } : {},
...y?.status === "pending" ? { assertCommitPreconditions: assertLocalSetupOwner } : {},
...!e.skipHooks && !P ? { finalizeConfig: enableDefaultOnboardingInternalHooks } : {},
surface: "cli",
...g || P ? { installDaemon: false } : {},
runtime: n
}, y?.status === "pending" ? { beforePersistentApply: assertLocalSetupEffects } : void 0));
if (c.lines.length > 0) await o.note(c.lines.join("\n"), t("wizard.guided.localSetupTitle"));
if (!c.workspaceReady) {
i = t("wizard.guided.workspaceSetupFailed");
throw new Error("The agent workspace could not be prepared. Retry onboarding to finish setup.");
}
const l = c.gateway;
if (l.status === "failed") {
i = t("wizard.guided.gatewaySetupFailed");
throw new Error(l.error);
}
R = c.gateway.status === "skipped" && c.gateway.reason === "external";
const u = y?.status === "pending" ? await (await import("../setup-recovery-BiUnF-eU.mjs")).completeLocalSetupRecovery({
owner: y,
appliedConfigPath: c.configPath,
teamCoordinatorId: O
}) : await s();
if (!u.valid) throw new Error("Setup wrote an invalid OpenClaw config.");
I = u.sourceConfig ?? u.config;
r.stop(t("wizard.guided.setupDone"));
} catch (e) {
r.stop(i);
if (O) throw new Error(`Onboarding did not complete: ${e instanceof Error ? e.message : String(e)} Run \`openclaw agents list\` to inspect the roster, then retry with the same --workspace after resolving the error.`, { cause: e });
await o.note(t("wizard.guided.applyFailedFallback", { detail: e instanceof Error ? e.message : String(e) }), i);
if (P) throw e;
return {
workspace: D,
next: "chat",
...S ? { agentName: S.name } : {}
};
}
}
const W = w ? resolveOnboardingAgentTarget(I, w).workspaceDir : U;
if (P) {
await o.note(t("wizard.guided.nextStepsWithoutAi", { workspace: W }), t("wizard.guided.nextStepsTitle"));
await o.outro(t("wizard.guided.setupDone"));
return null;
}
const { runMemorySetupFlow: G } = await import("../memory-setup-DtjVmk2o.mjs");
const K = await G(I, o, {
agentDir: resolveOnboardingAgentTarget(I, w).agentDir,
secretInputMode: e.secretInputMode
});
if (K !== I) {
const { writeWizardConfigFile: e } = await import("../setup.shared-D5wOOEt0.mjs");
I = (await e(K, {
allowConfigSizeDrop: false,
mergeBase: I
})).nextConfig;
}
const { resolveConfiguredSetupModelForAgent: q } = await import("../utility-model-Bve7jyiB.mjs");
const J = q({
cfg: I,
agentId: w ?? resolveSystemAgentOnboardingTarget(I).agentId
})?.modelTarget === "utility";
if (J) await o.note("Your setup and utility model is ready. It can help finish setup here. Choose a primary model in Model Setup or run openclaw onboard before regular agent chat.", "Setup and utility inference");
if (M && !g && !J) {
await importMemories();
const { setupAppRecommendations: e } = await import("../setup.app-recommendations-D9fQfIKB.mjs");
const r = await e({
config: I,
prompter: o,
runtime: n,
workspaceDir: W,
modelRouteVerified: true
});
const i = r.config;
if (i !== I) {
const { writeWizardConfigFile: e } = await import("../setup.shared-D5wOOEt0.mjs");
I = (await e(i, {
allowConfigSizeDrop: false,
mergeBase: I
})).nextConfig;
}
await r.commitResult();
}
const Y = w ? W : L ? resolveUserPath(l.agents?.defaults?.workspace?.trim() || i.DEFAULT_WORKSPACE) : U;
if (g && !R) {
await o.outro(t("wizard.guided.setupDone"));
return {
next: "foreground-gateway",
...w ? { agentId: w } : {}
};
}
if (e.skipUi === true) {
await o.outro(t("wizard.guided.complete"));
return null;
}
if (e.tui !== true) {
const { runBrowserHatchHandoff: n } = await import("../onboard-browser-handoff-DIaoQVft.mjs");
if (await n({
config: I,
prompter: o,
...w ? { agentId: w } : {},
...e.suppressGatewayTokenOutput ? { suppressTokenOutput: true } : {}
})) {
await o.outro(t("wizard.guided.browserHandoffReady"));
return { next: "browser" };
}
}
if (J) {
await o.outro("Continuing with the OpenClaw setup assistant.");
return {
workspace: Y,
next: "chat"
};
}
await o.note(t("wizard.guided.findMeLater"), t("wizard.guided.welcomeTitle"));
await o.outro(t("wizard.guided.hatchingNow"));
return {
workspace: Y,
next: "hatch",
local: L,
...w ? { agentId: w } : {}
};
}
async function runGuidedOnboarding(e, n, r = {}) {
if (!isTerminalInteractive()) {
n.error(t("wizard.guided.ttyRequired"));
n.exit(1);
return;
}
const i = { handoff: null };
await runInteractiveOnboarding(async () => {
i.handoff = await runGuidedOnboardingFlow(e, n, r);
}, n);
await runGuidedOnboardingHandoff(i.handoff, e, n, r);
}
//#endregion
export { runGuidedOnboarding };