Files
openclaw/src/commands/onboard-helpers.ts
Peter Steinberger 7acd26a2fc Move provider to a plugin-architecture (#661)
* refactor: introduce provider plugin registry

* refactor: move provider CLI to plugins

* docs: add provider plugin implementation notes

* refactor: shift provider runtime logic into plugins

* refactor: add plugin defaults and summaries

* docs: update provider plugin notes

* feat(commands): add /commands slash list

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* Tests: align google shared expectations

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* refactor: move provider routing into plugins

* test: align agent routing expectations

* docs: update provider plugin notes

* refactor: route replies via provider plugins

* docs: note route-reply plugin hooks

* refactor: extend provider plugin contract

* refactor: derive provider status from plugins

* refactor: unify gateway provider control

* refactor: use plugin metadata in auto-reply

* fix: parenthesize cron target selection

* refactor: derive gateway methods from plugins

* refactor: generalize provider logout

* refactor: route provider logout through plugins

* refactor: move WhatsApp web login methods into plugin

* refactor: generalize provider log prefixes

* refactor: centralize default chat provider

* refactor: derive provider lists from registry

* refactor: move provider reload noops into plugins

* refactor: resolve web login provider via alias

* refactor: derive CLI provider options from plugins

* refactor: derive prompt provider list from plugins

* style: apply biome lint fixes

* fix: resolve provider routing edge cases

* docs: update provider plugin refactor notes

* fix(gateway): harden agent provider routing

* refactor: move provider routing into plugins

* refactor: move provider CLI to plugins

* refactor: derive provider lists from registry

* fix: restore slash command parsing

* refactor: align provider ids for schema

* refactor: unify outbound target resolution

* fix: keep outbound labels stable

* feat: add msteams to cron surfaces

* fix: clean up lint build issues

* refactor: localize chat provider alias normalization

* refactor: drive gateway provider lists from plugins

* docs: update provider plugin notes

* style: format message-provider

* fix: avoid provider registry init cycles

* style: sort message-provider imports

* fix: relax provider alias map typing

* refactor: move provider routing into plugins

* refactor: add plugin pairing/config adapters

* refactor: route pairing and provider removal via plugins

* refactor: align auto-reply provider typing

* test: stabilize telegram media mocks

* docs: update provider plugin refactor notes

* refactor: pluginize outbound targets

* refactor: pluginize provider selection

* refactor: generalize text chunk limits

* docs: update provider plugin notes

* refactor: generalize group session/config

* fix: normalize provider id for room detection

* fix: avoid provider init in system prompt

* style: formatting cleanup

* refactor: normalize agent delivery targets

* test: update outbound delivery labels

* chore: fix lint regressions

* refactor: extend provider plugin adapters

* refactor: move elevated/block streaming defaults to plugins

* refactor: defer outbound send deps to plugins

* docs: note plugin-driven streaming/elevated defaults

* refactor: centralize webchat provider constant

* refactor: add provider setup adapters

* refactor: delegate provider add config to plugins

* docs: document plugin-driven provider add

* refactor: add plugin state/binding metadata

* refactor: build agent provider status from plugins

* docs: note plugin-driven agent bindings

* refactor: centralize internal provider constant usage

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* refactor: centralize default chat provider

* refactor: centralize WhatsApp target normalization

* refactor: move provider routing into plugins

* refactor: normalize agent delivery targets

* chore: fix lint regressions

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* feat: expand provider plugin adapters

* refactor: route auto-reply via provider plugins

* fix: align WhatsApp target normalization

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* refactor: centralize WhatsApp target normalization

* feat: add /config chat config updates

* docs: add /config get alias

* feat(commands): add /commands slash list

* refactor: centralize default chat provider

* style: apply biome lint fixes

* chore: fix lint regressions

* fix: clean up whatsapp allowlist typing

* style: format config command helpers

* refactor: pluginize tool threading context

* refactor: normalize session announce targets

* docs: note new plugin threading and announce hooks

* refactor: pluginize message actions

* docs: update provider plugin actions notes

* fix: align provider action adapters

* refactor: centralize webchat checks

* style: format message provider helpers

* refactor: move provider onboarding into adapters

* docs: note onboarding provider adapters

* feat: add msteams onboarding adapter

* style: organize onboarding imports

* fix: normalize msteams allowFrom types

* feat: add plugin text chunk limits

* refactor: use plugin chunk limit fallbacks

* feat: add provider mention stripping hooks

* style: organize provider plugin type imports

* refactor: generalize health snapshots

* refactor: update macOS health snapshot handling

* docs: refresh health snapshot notes

* style: format health snapshot updates

* refactor: drive security warnings via plugins

* docs: note provider security adapter

* style: format provider security adapters

* refactor: centralize provider account defaults

* refactor: type gateway client identity constants

* chore: regen gateway protocol swift

* fix: degrade health on failed provider probe

* refactor: centralize pairing approve hint

* docs: add plugin CLI command references

* refactor: route auth and tool sends through plugins

* docs: expand provider plugin hooks

* refactor: document provider docking touchpoints

* refactor: normalize internal provider defaults

* refactor: streamline outbound delivery wiring

* refactor: make provider onboarding plugin-owned

* refactor: support provider-owned agent tools

* refactor: move telegram draft chunking into telegram module

* refactor: infer provider tool sends via extractToolSend

* fix: repair plugin onboarding imports

* refactor: de-dup outbound target normalization

* style: tidy plugin and agent imports

* refactor: data-drive provider selection line

* fix: satisfy lint after provider plugin rebase

* test: deflake gateway-cli coverage

* style: format gateway-cli coverage test

* refactor(provider-plugins): simplify provider ids

* test(pairing-cli): avoid provider-specific ternary

* style(macos): swiftformat HealthStore

* refactor(sandbox): derive provider tool denylist

* fix(sandbox): avoid plugin init in defaults

* refactor(provider-plugins): centralize provider aliases

* style(test): satisfy biome

* refactor(protocol): v3 providers.status maps

* refactor(ui): adapt to protocol v3

* refactor(macos): adapt to protocol v3

* test: update providers.status v3 fixtures

* refactor(gateway): map provider runtime snapshot

* test(gateway): update reload runtime snapshot

* refactor(whatsapp): normalize heartbeat provider id

* docs(refactor): update provider plugin notes

* style: satisfy biome after rebase

* fix: describe sandboxed elevated in prompt

* feat(gateway): add agent image attachments + live probe

* refactor: derive CLI provider options from plugins

* fix(gateway): harden agent provider routing

* fix(gateway): harden agent provider routing

* refactor: align provider ids for schema

* fix(protocol): keep agent provider string

* fix(gateway): harden agent provider routing

* fix(protocol): keep agent provider string

* refactor: normalize agent delivery targets

* refactor: support provider-owned agent tools

* refactor(config): provider-keyed elevated allowFrom

* style: satisfy biome

* fix(gateway): appease provider narrowing

* style: satisfy biome

* refactor(reply): move group intro hints into plugin

* fix(reply): avoid plugin registry init cycle

* refactor(providers): add lightweight provider dock

* refactor(gateway): use typed client id in connect

* refactor(providers): document docks and avoid init cycles

* refactor(providers): make media limit helper generic

* fix(providers): break plugin registry import cycles

* style: satisfy biome

* refactor(status-all): build providers table from plugins

* refactor(gateway): delegate web login to provider plugin

* refactor(provider): drop web alias

* refactor(provider): lazy-load monitors

* style: satisfy lint/format

* style: format status-all providers table

* style: swiftformat gateway discovery model

* test: make reload plan plugin-driven

* fix: avoid token stringification in status-all

* refactor: make provider IDs explicit in status

* feat: warn on signal/imessage provider runtime errors

* test: cover gateway provider runtime warnings in status

* fix: add runtime kind to provider status issues

* test: cover health degradation on probe failure

* fix: keep routeReply lightweight

* style: organize routeReply imports

* refactor(web): extract auth-store helpers

* refactor(whatsapp): lazy login imports

* refactor(outbound): route replies via plugin outbound

* docs: update provider plugin notes

* style: format provider status issues

* fix: make sandbox scope warning wrap-safe

* refactor: load outbound adapters from provider plugins

* docs: update provider plugin outbound notes

* style(macos): fix swiftformat lint

* docs: changelog for provider plugins

* fix(macos): satisfy swiftformat

* fix(macos): open settings via menu action

* style: format after rebase

* fix(macos): open Settings via menu action

---------

Co-authored-by: LK <luke@kyohere.com>
Co-authored-by: Luke K (pr-0f3t) <2609441+lc0rp@users.noreply.github.com>
Co-authored-by: Xin <xin@imfing.com>
2026-01-11 11:45:25 +00:00

387 lines
12 KiB
TypeScript

import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { inspect } from "node:util";
import { cancel, isCancel } from "@clack/prompts";
import {
DEFAULT_AGENT_WORKSPACE_DIR,
ensureAgentWorkspace,
} from "../agents/workspace.js";
import type { ClawdbotConfig } from "../config/config.js";
import { CONFIG_PATH_CLAWDBOT } from "../config/config.js";
import { resolveSessionTranscriptsDirForAgent } from "../config/sessions.js";
import { callGateway } from "../gateway/call.js";
import { normalizeControlUiBasePath } from "../gateway/control-ui.js";
import { isSafeExecutableValue } from "../infra/exec-safety.js";
import { pickPrimaryTailnetIPv4 } from "../infra/tailnet.js";
import { runCommandWithTimeout } from "../process/exec.js";
import type { RuntimeEnv } from "../runtime.js";
import { stylePromptTitle } from "../terminal/prompt-style.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { CONFIG_DIR, resolveUserPath } from "../utils.js";
import { VERSION } from "../version.js";
import type {
NodeManagerChoice,
OnboardMode,
ResetScope,
} from "./onboard-types.js";
export function guardCancel<T>(value: T, runtime: RuntimeEnv): T {
if (isCancel(value)) {
cancel(stylePromptTitle("Setup cancelled.") ?? "Setup cancelled.");
runtime.exit(0);
}
return value;
}
export function summarizeExistingConfig(config: ClawdbotConfig): string {
const rows: string[] = [];
const defaults = config.agents?.defaults;
if (defaults?.workspace) rows.push(`workspace: ${defaults.workspace}`);
if (defaults?.model) {
const model =
typeof defaults.model === "string"
? defaults.model
: defaults.model.primary;
if (model) rows.push(`model: ${model}`);
}
if (config.gateway?.mode) rows.push(`gateway.mode: ${config.gateway.mode}`);
if (typeof config.gateway?.port === "number") {
rows.push(`gateway.port: ${config.gateway.port}`);
}
if (config.gateway?.bind) rows.push(`gateway.bind: ${config.gateway.bind}`);
if (config.gateway?.remote?.url) {
rows.push(`gateway.remote.url: ${config.gateway.remote.url}`);
}
if (config.skills?.install?.nodeManager) {
rows.push(`skills.nodeManager: ${config.skills.install.nodeManager}`);
}
return rows.length ? rows.join("\n") : "No key settings detected.";
}
export function randomToken(): string {
return crypto.randomBytes(24).toString("hex");
}
export function printWizardHeader(runtime: RuntimeEnv) {
const header = [
"░████░█░░░░░█████░█░░░█░███░░████░░████░░▀█▀",
"█░░░░░█░░░░░█░░░█░█░█░█░█░░█░█░░░█░█░░░█░░█░",
"█░░░░░█░░░░░█████░█░█░█░█░░█░████░░█░░░█░░█░",
"█░░░░░█░░░░░█░░░█░█░█░█░█░░█░█░░█░░█░░░█░░█░",
"░████░█████░█░░░█░░█░█░░███░░████░░░███░░░█░",
" 🦞 FRESH DAILY 🦞",
].join("\n");
runtime.log(header);
}
export function applyWizardMetadata(
cfg: ClawdbotConfig,
params: { command: string; mode: OnboardMode },
): ClawdbotConfig {
const commit =
process.env.GIT_COMMIT?.trim() || process.env.GIT_SHA?.trim() || undefined;
return {
...cfg,
wizard: {
...cfg.wizard,
lastRunAt: new Date().toISOString(),
lastRunVersion: VERSION,
lastRunCommit: commit,
lastRunCommand: params.command,
lastRunMode: params.mode,
},
};
}
type BrowserOpenSupport = {
ok: boolean;
reason?: string;
command?: string;
};
let wslCached: boolean | null = null;
async function isWSL(): Promise<boolean> {
if (wslCached !== null) return wslCached;
if (process.platform !== "linux") {
wslCached = false;
return wslCached;
}
if (
process.env.WSL_INTEROP ||
process.env.WSL_DISTRO_NAME ||
process.env.WSLENV
) {
wslCached = true;
return wslCached;
}
try {
const release = (await fs.readFile("/proc/version", "utf8")).toLowerCase();
wslCached = release.includes("microsoft") || release.includes("wsl");
} catch {
wslCached = false;
}
return wslCached;
}
type BrowserOpenCommand = {
argv: string[] | null;
reason?: string;
command?: string;
};
async function resolveBrowserOpenCommand(): Promise<BrowserOpenCommand> {
const platform = process.platform;
const hasDisplay = Boolean(
process.env.DISPLAY || process.env.WAYLAND_DISPLAY,
);
const isSsh =
Boolean(process.env.SSH_CLIENT) ||
Boolean(process.env.SSH_TTY) ||
Boolean(process.env.SSH_CONNECTION);
if (isSsh && !hasDisplay && platform !== "win32") {
return { argv: null, reason: "ssh-no-display" };
}
if (platform === "win32") {
return { argv: ["cmd", "/c", "start", ""], command: "cmd" };
}
if (platform === "darwin") {
const hasOpen = await detectBinary("open");
return hasOpen
? { argv: ["open"], command: "open" }
: { argv: null, reason: "missing-open" };
}
if (platform === "linux") {
const wsl = await isWSL();
if (!hasDisplay && !wsl) {
return { argv: null, reason: "no-display" };
}
if (wsl) {
const hasWslview = await detectBinary("wslview");
if (hasWslview) return { argv: ["wslview"], command: "wslview" };
if (!hasDisplay) return { argv: null, reason: "wsl-no-wslview" };
}
const hasXdgOpen = await detectBinary("xdg-open");
return hasXdgOpen
? { argv: ["xdg-open"], command: "xdg-open" }
: { argv: null, reason: "missing-xdg-open" };
}
return { argv: null, reason: "unsupported-platform" };
}
export async function detectBrowserOpenSupport(): Promise<BrowserOpenSupport> {
const resolved = await resolveBrowserOpenCommand();
if (!resolved.argv) return { ok: false, reason: resolved.reason };
return { ok: true, command: resolved.command };
}
export function formatControlUiSshHint(params: {
port: number;
basePath?: string;
token?: string;
}): string {
const basePath = normalizeControlUiBasePath(params.basePath);
const uiPath = basePath ? `${basePath}/` : "/";
const localUrl = `http://localhost:${params.port}${uiPath}`;
const tokenParam = params.token
? `?token=${encodeURIComponent(params.token)}`
: "";
const authedUrl = params.token ? `${localUrl}${tokenParam}` : undefined;
const sshTarget = resolveSshTargetHint();
return [
"No GUI detected. Open from your computer:",
`ssh -N -L ${params.port}:127.0.0.1:${params.port} ${sshTarget}`,
"Then open:",
localUrl,
authedUrl,
"Docs:",
"https://docs.clawd.bot/gateway/remote",
"https://docs.clawd.bot/web/control-ui",
]
.filter(Boolean)
.join("\n");
}
function resolveSshTargetHint(): string {
const user = process.env.USER || process.env.LOGNAME || "user";
const conn = process.env.SSH_CONNECTION?.trim().split(/\s+/);
const host = conn?.[2] ?? "<host>";
return `${user}@${host}`;
}
export async function openUrl(url: string): Promise<boolean> {
const resolved = await resolveBrowserOpenCommand();
if (!resolved.argv) return false;
const command = [...resolved.argv, url];
try {
await runCommandWithTimeout(command, { timeoutMs: 5_000 });
return true;
} catch {
// ignore; we still print the URL for manual open
return false;
}
}
export async function ensureWorkspaceAndSessions(
workspaceDir: string,
runtime: RuntimeEnv,
options?: { skipBootstrap?: boolean; agentId?: string },
) {
const ws = await ensureAgentWorkspace({
dir: workspaceDir,
ensureBootstrapFiles: !options?.skipBootstrap,
});
runtime.log(`Workspace OK: ${ws.dir}`);
const sessionsDir = resolveSessionTranscriptsDirForAgent(options?.agentId);
await fs.mkdir(sessionsDir, { recursive: true });
runtime.log(`Sessions OK: ${sessionsDir}`);
}
export function resolveNodeManagerOptions(): Array<{
value: NodeManagerChoice;
label: string;
}> {
return [
{ value: "npm", label: "npm" },
{ value: "pnpm", label: "pnpm" },
{ value: "bun", label: "bun" },
];
}
export async function moveToTrash(
pathname: string,
runtime: RuntimeEnv,
): Promise<void> {
if (!pathname) return;
try {
await fs.access(pathname);
} catch {
return;
}
try {
await runCommandWithTimeout(["trash", pathname], { timeoutMs: 5000 });
runtime.log(`Moved to Trash: ${pathname}`);
} catch {
runtime.log(`Failed to move to Trash (manual delete): ${pathname}`);
}
}
export async function handleReset(
scope: ResetScope,
workspaceDir: string,
runtime: RuntimeEnv,
) {
await moveToTrash(CONFIG_PATH_CLAWDBOT, runtime);
if (scope === "config") return;
await moveToTrash(path.join(CONFIG_DIR, "credentials"), runtime);
await moveToTrash(resolveSessionTranscriptsDirForAgent(), runtime);
if (scope === "full") {
await moveToTrash(workspaceDir, runtime);
}
}
export async function detectBinary(name: string): Promise<boolean> {
if (!name?.trim()) return false;
if (!isSafeExecutableValue(name)) return false;
const resolved = name.startsWith("~") ? resolveUserPath(name) : name;
if (
path.isAbsolute(resolved) ||
resolved.startsWith(".") ||
resolved.includes("/") ||
resolved.includes("\\")
) {
try {
await fs.access(resolved);
return true;
} catch {
return false;
}
}
const command =
process.platform === "win32"
? ["where", name]
: ["/usr/bin/env", "which", name];
try {
const result = await runCommandWithTimeout(command, { timeoutMs: 2000 });
return result.code === 0 && result.stdout.trim().length > 0;
} catch {
return false;
}
}
export async function probeGatewayReachable(params: {
url: string;
token?: string;
password?: string;
timeoutMs?: number;
}): Promise<{ ok: boolean; detail?: string }> {
const url = params.url.trim();
const timeoutMs = params.timeoutMs ?? 1500;
try {
await callGateway({
url,
token: params.token,
password: params.password,
method: "health",
timeoutMs,
clientName: GATEWAY_CLIENT_NAMES.PROBE,
mode: GATEWAY_CLIENT_MODES.PROBE,
});
return { ok: true };
} catch (err) {
return { ok: false, detail: summarizeError(err) };
}
}
function summarizeError(err: unknown): string {
let raw = "unknown error";
if (err instanceof Error) {
raw = err.message || raw;
} else if (typeof err === "string") {
raw = err || raw;
} else if (err !== undefined) {
raw = inspect(err, { depth: 2 });
}
const line =
raw
.split("\n")
.map((s) => s.trim())
.find(Boolean) ?? raw;
return line.length > 120 ? `${line.slice(0, 119)}` : line;
}
export const DEFAULT_WORKSPACE = DEFAULT_AGENT_WORKSPACE_DIR;
export function resolveControlUiLinks(params: {
port: number;
bind?: "auto" | "lan" | "tailnet" | "loopback";
basePath?: string;
}): { httpUrl: string; wsUrl: string } {
const port = params.port;
const bind = params.bind ?? "loopback";
const tailnetIPv4 = pickPrimaryTailnetIPv4();
const host =
bind === "tailnet" || (bind === "auto" && tailnetIPv4)
? (tailnetIPv4 ?? "127.0.0.1")
: "127.0.0.1";
const basePath = normalizeControlUiBasePath(params.basePath);
const uiPath = basePath ? `${basePath}/` : "/";
const wsPath = basePath ? basePath : "";
return {
httpUrl: `http://${host}:${port}${uiPath}`,
wsUrl: `ws://${host}:${port}${wsPath}`,
};
}