openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
261 lines (260 loc) • 10.5 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as resolveConfigDir } from "./config-dir-DMqvtq2W.mjs";
import { a as displayPath, f as shortenHomeInString } from "./utils-C8YECn2Q.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { a as canonicalPathFromExistingAncestor, c as isPathInside } from "./fs-safe-BbWvmdVn.mjs";
import { u as resolveSessionTranscriptsDirForAgent } from "./paths-DvQ5AJvD.mjs";
import { _ as resolveDefaultAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as DEFAULT_AGENT_WORKSPACE_DIR } from "./workspace-default-DvctYF3A.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs";
import { a as resolveAgentEffectiveModelPrimary } from "./agent-scope-BwB8YH6y.mjs";
import { m as readSourceConfigBestEffort } from "./io.runtime-DsJ2dLCQ.mjs";
import "./config-CMA-J084.mjs";
import { r as isInvalidGatewaySecret } from "./known-weak-gateway-secrets-DrP6ACfl.mjs";
import "./detect-binary-B596fFLF.mjs";
import "./browser-open-3VrAKw25.mjs";
import { t as normalizeControlUiBasePath } from "./control-ui-shared-_tUmz6W8.mjs";
import { t as ensureAgentWorkspace } from "./workspace-DLlXz3VE.mjs";
import { r as stylePromptTitle } from "./prompt-style-CLys-6GQ.mjs";
import { c as removeWorkspaceDirs, i as removeAgentSessions, n as moveToTrash } from "./cleanup-utils-Dk4WWDhW.mjs";
import { t as printClawBanner } from "./claw-banner-B9cabQas.mjs";
import { n as probeGateway } from "./probe-yxDLQFmi.mjs";
import "./control-ui-links-tAtEMm92.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { inspect } from "node:util";
import { cancel } from "@clack/prompts";
//#region src/commands/onboard-helpers.ts
function guardCancel(e, t, n = 0) {
if (typeof e === "symbol") {
cancel(stylePromptTitle("Setup cancelled.") ?? "Setup cancelled.");
t.exit(n);
throw new Error("unreachable");
}
return e;
}
/** Summarizes existing config values before onboarding overwrites or reuses them. */
function summarizeExistingConfig(e) {
const t = [];
const n = e.agents?.defaults;
if (n?.workspace) t.push(terminalText`Workspace: ${shortenHomeInString(n.workspace)}`);
if (n?.model) {
const e = resolveAgentModelPrimaryValue(n.model);
if (e) t.push(terminalText`Model: ${shortenHomeInString(e)}`);
}
const r = summarizeGatewayConfig(e);
if (r) t.push(shortenHomeInString(r));
if (e.skills?.install?.nodeManager) t.push(terminalText`Node manager: ${shortenHomeInString(e.skills.install.nodeManager)}`);
return t.length ? t.join("\n") : "No key settings detected.";
}
function summarizeGatewayConfig(e) {
const t = e.gateway;
if (!t?.mode && typeof t?.port !== "number" && !t?.bind && !t?.remote?.url) return null;
const n = normalizeOptionalString(t.mode);
const r = formatGatewayBind(t.bind);
const i = normalizeOptionalString(t.remote?.url);
const a = i !== void 0 && n !== "local";
const o = a && i ? i : typeof t.port === "number" ? `:${t.port}` : void 0;
const s = [];
if (n) s.push(n);
if (r) s.push(n ? `via ${r}` : r);
if (n === "remote" && !i) {
s.push("(missing remote URL)");
return terminalText`Gateway: ${s.join(" ")}`;
}
if (o) s.push(`${a ? "at" : "on"} ${o}`);
return terminalText`Gateway: ${s.length > 0 ? s.join(" ") : "configured"}`;
}
function formatGatewayBind(e) {
return e === "lan" ? "LAN" : normalizeOptionalString(e);
}
/** Normalizes gateway token prompts while rejecting JS stringification sentinels. */
function normalizeGatewayTokenInput(e) {
if (typeof e !== "string") return "";
const t = e.trim();
if (isInvalidGatewaySecret(t)) return "";
return t;
}
function validateGatewayPasswordInput(e) {
if (typeof e !== "string") return "Required";
const t = e.trim();
if (!t) return "Required";
if (t === "undefined" || t === "null") return "Cannot be the literal string \"undefined\" or \"null\"";
}
async function printWizardHeader(e) {
await printClawBanner(e);
}
/** Records wizard provenance metadata on config writes. */
function applyWizardMetadata(e, t) {
const n = normalizeOptionalString(process.env.GIT_COMMIT) ?? normalizeOptionalString(process.env.GIT_SHA);
return {
...e,
wizard: {
...e.wizard,
lastRunAt: (/* @__PURE__ */ new Date()).toISOString(),
lastRunVersion: VERSION,
lastRunCommit: n,
lastRunCommand: t.command,
lastRunMode: t.mode
}
};
}
function formatControlUiSshHint(e) {
const t = normalizeControlUiBasePath(e.basePath);
const n = t ? `${t}/` : "/";
const r = `${e.tlsEnabled ? "https" : "http"}://localhost:${e.port}${n}`;
return [
"No GUI detected. Open from your computer:",
terminalText`ssh -N -L ${e.port}:127.0.0.1:${e.port} <user>@<host>`,
"Then open:",
terminalText`${r}`,
"BYOH note: lan, tailnet, and custom bind are currently IPv4-only.",
"If your host is IPv6-only, use an IPv4 sidecar or proxy in front of the Gateway.",
"Docs:",
"https://docs.openclaw.ai/gateway/remote",
"https://docs.openclaw.ai/web/control-ui"
].join("\n");
}
/** Ensures workspace bootstrap files and session transcript directories exist. */
async function ensureWorkspaceAndSessions(e, t, n) {
const r = await ensureAgentWorkspace({
dir: e,
ensureBootstrapFiles: !n.skipBootstrap,
skipOptionalBootstrapFiles: n.skipOptionalBootstrapFiles,
guard: n.guard
});
t.log(`Workspace OK: ${displayPath(r.dir)}`);
const i = resolveSessionTranscriptsDirForAgent(n.agentId);
n.guard?.assertHost?.();
await fs.mkdir(i, { recursive: true });
t.log(`Sessions OK: ${displayPath(i)}`);
return { bootstrapPending: r.bootstrapPending === true };
}
async function assertFullResetPreservesOnboardingLock(e) {
const [t, n] = await Promise.all([canonicalPathFromExistingAncestor(path.resolve(e)), canonicalPathFromExistingAncestor(path.join(resolveStateDir(), "migration"))]);
if (t === n || isPathInside(t, n) || isPathInside(n, t)) throw new Error("Full reset workspace overlaps the active onboarding lock directory. Choose a workspace outside the OpenClaw state migration directory or use a narrower reset scope.");
}
/** Deletes onboarding-managed state according to the selected reset scope. */
async function handleReset(e, t, n) {
if (e === "full") await assertFullResetPreservesOnboardingLock(t);
const r = [];
const trashRequiredPath = async (e) => {
if (!await moveToTrash(e, n)) r.push(e);
};
if (e !== "config") await removeAgentSessions({
cfg: await readSourceConfigBestEffort(),
configPath: resolveConfigPath(),
stateDir: resolveStateDir()
}, n);
await trashRequiredPath(resolveConfigPath());
if (e === "config") {
throwIfResetFailed(r);
return;
}
await trashRequiredPath(path.join(resolveConfigDir(), "credentials"));
if (e === "full") r.push(...await removeWorkspaceDirs([t], n, {
removeStateRows: true,
removeWorkspace: (e) => moveToTrash(e, n)
}));
throwIfResetFailed(r);
}
function throwIfResetFailed(e) {
const t = [...new Set(e)];
if (t.length > 0) throw new Error(`Reset failed to remove required state:\n${t.join("\n")}`);
}
function runOnboardingGatewayProbe(e, t) {
const n = e.url.trim();
const r = e.timeoutMs ?? Math.max(1500, e.preauthHandshakeTimeoutMs ?? 0);
return probeGateway({
url: n,
...e.config ? { config: e.config } : {},
...e.originScopedDeviceAuth ? { originScopedDeviceAuth: true } : {},
...e.configuredRemote ? { configuredRemote: true } : {},
timeoutMs: r,
auth: {
token: e.token,
password: e.password
},
...e.tlsFingerprint ? { tlsFingerprint: e.tlsFingerprint } : {},
...e.preauthHandshakeTimeoutMs ? { preauthHandshakeTimeoutMs: e.preauthHandshakeTimeoutMs } : {},
detailLevel: t,
...e.signal ? { signal: e.signal } : {}
});
}
/** Runs a single lightweight gateway probe for onboarding readiness checks. */
async function probeGatewayReachable(e) {
try {
const t = await runOnboardingGatewayProbe(e, "none");
if (!t.ok) return {
ok: false,
detail: t.error ?? void 0
};
return { ok: true };
} catch (e) {
return {
ok: false,
detail: summarizeError(e)
};
}
}
/** Reads only Gateway config and classifies whether its default agent has inference. */
async function probeGatewayConfiguredModel(e) {
let t;
try {
t = await runOnboardingGatewayProbe(e, "config");
} catch {
return "unreachable";
}
if (!t.gatewayReached) return "unreachable";
if (!t.ok) return "reachable-unverified";
const n = t.configSnapshot;
const r = n?.valid === true ? n.runtimeConfig ?? n.config : null;
if (!r || typeof r !== "object" || Array.isArray(r)) return "reachable-unverified";
try {
const e = r;
return resolveAgentEffectiveModelPrimary(e, resolveDefaultAgentId(e)) ? "configured" : "missing-configured-model";
} catch {
return "reachable-unverified";
}
}
async function waitForGatewayReachable(e) {
const { deadlineMs: t = 15e3, pollMs: n = 400, probeTimeoutMs: r = 1500, ...i } = e;
const a = resolveTimerTimeoutMs(n, 400, 0);
const o = Date.now();
let s;
while (Date.now() - o < t) {
e.signal?.throwIfAborted();
const n = await probeGatewayReachable({
...i,
timeoutMs: r
});
e.signal?.throwIfAborted();
if (n.ok) return n;
s = n.detail;
const c = t - (Date.now() - o);
if (c <= 0) break;
await sleep(Math.min(a, c), e.signal);
}
return {
ok: false,
detail: s
};
}
function summarizeError(e) {
let t = "unknown error";
if (e instanceof Error) t = e.message || t;
else if (typeof e === "string") t = e || t;
else if (e !== void 0) t = inspect(e, { depth: 2 });
const n = t.split("\n").map((e) => e.trim()).find(Boolean) ?? t;
return n.length > 120 ? `${truncateUtf16Safe(n, 119)}…` : n;
}
/** Default workspace path shown by onboarding prompts. */
const DEFAULT_WORKSPACE = DEFAULT_AGENT_WORKSPACE_DIR;
//#endregion
export { guardCancel as a, printWizardHeader as c, summarizeExistingConfig as d, validateGatewayPasswordInput as f, formatControlUiSshHint as i, probeGatewayConfiguredModel as l, applyWizardMetadata as n, handleReset as o, waitForGatewayReachable as p, ensureWorkspaceAndSessions as r, normalizeGatewayTokenInput as s, DEFAULT_WORKSPACE as t, probeGatewayReachable as u };