feat: unify onboarding + config schema

This commit is contained in:
Peter Steinberger
2026-01-03 16:04:19 +01:00
parent 0f85080d81
commit 53baba71fa
43 changed files with 3478 additions and 1011 deletions

View File

@@ -180,13 +180,13 @@ function cleanSchemaForGemini(schema: unknown): unknown {
cleaned[key] = cleanSchemaForGemini(value);
} else if (key === "anyOf" && Array.isArray(value)) {
// Clean each anyOf variant
cleaned[key] = value.map((v) => cleanSchemaForGemini(v));
cleaned[key] = value.map((variant) => cleanSchemaForGemini(variant));
} else if (key === "oneOf" && Array.isArray(value)) {
// Clean each oneOf variant
cleaned[key] = value.map((v) => cleanSchemaForGemini(v));
cleaned[key] = value.map((variant) => cleanSchemaForGemini(variant));
} else if (key === "allOf" && Array.isArray(value)) {
// Clean each allOf variant
cleaned[key] = value.map((v) => cleanSchemaForGemini(v));
cleaned[key] = value.map((variant) => cleanSchemaForGemini(variant));
} else if (
key === "additionalProperties" &&
value &&
@@ -265,12 +265,12 @@ function normalizeToolParameters(tool: AnyAgentTool): AnyAgentTool {
.map(([key]) => key)
: undefined;
const { anyOf: _unusedAnyOf, ...restSchema } = schema;
const nextSchema: Record<string, unknown> = { ...schema };
return {
...tool,
parameters: cleanSchemaForGemini({
...restSchema,
type: "object",
...nextSchema,
type: nextSchema.type ?? "object",
properties:
Object.keys(mergedProperties).length > 0
? mergedProperties

View File

@@ -8,6 +8,7 @@ vi.mock("../globals.js", () => ({
isVerbose: () => false,
shouldLogVerbose: () => false,
logVerbose: vi.fn(),
shouldLogVerbose: () => false,
}));
vi.mock("../process/exec.js", () => ({

View File

@@ -24,6 +24,7 @@ import { resolveGatewayService } from "../daemon/service.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { resolveUserPath, sleep } from "../utils.js";
import { createClackPrompter } from "../wizard/clack-prompter.js";
import {
isRemoteEnvironment,
loginAntigravityVpsAware,
@@ -419,6 +420,7 @@ export async function runConfigureWizard(
intro(
opts.command === "update" ? "Clawdis update wizard" : "Clawdis configure",
);
const prompter = createClackPrompter();
const snapshot = await readConfigFileSnapshot();
let baseConfig: ClawdisConfig = snapshot.valid ? snapshot.config : {};
@@ -490,7 +492,7 @@ export async function runConfigureWizard(
) as "local" | "remote";
if (mode === "remote") {
let remoteConfig = await promptRemoteGatewayConfig(baseConfig, runtime);
let remoteConfig = await promptRemoteGatewayConfig(baseConfig, prompter);
remoteConfig = applyWizardMetadata(remoteConfig, {
command: opts.command,
mode,
@@ -565,7 +567,7 @@ export async function runConfigureWizard(
}
if (selected.includes("providers")) {
nextConfig = await setupProviders(nextConfig, runtime, {
nextConfig = await setupProviders(nextConfig, runtime, prompter, {
allowDisable: true,
allowSignalInstall: true,
});
@@ -573,7 +575,7 @@ export async function runConfigureWizard(
if (selected.includes("skills")) {
const wsDir = resolveUserPath(workspaceDir);
nextConfig = await setupSkills(nextConfig, wsDir, runtime);
nextConfig = await setupSkills(nextConfig, wsDir, runtime, prompter);
}
nextConfig = applyWizardMetadata(nextConfig, {

View File

@@ -1,594 +1,22 @@
import path from "node:path";
import {
confirm,
intro,
note,
outro,
select,
spinner,
text,
} from "@clack/prompts";
import { loginAnthropic, type OAuthCredentials } from "@mariozechner/pi-ai";
import type { ClawdisConfig } from "../config/config.js";
import {
CONFIG_PATH_CLAWDIS,
readConfigFileSnapshot,
resolveGatewayPort,
writeConfigFile,
} from "../config/config.js";
import { GATEWAY_LAUNCH_AGENT_LABEL } from "../daemon/constants.js";
import { resolveGatewayProgramArguments } from "../daemon/program-args.js";
import { resolveGatewayService } from "../daemon/service.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { resolveUserPath, sleep } from "../utils.js";
import {
isRemoteEnvironment,
loginAntigravityVpsAware,
} from "./antigravity-oauth.js";
import { healthCommand } from "./health.js";
import {
applyMinimaxConfig,
setAnthropicApiKey,
writeOAuthCredentials,
} from "./onboard-auth.js";
import {
applyWizardMetadata,
DEFAULT_WORKSPACE,
ensureWorkspaceAndSessions,
guardCancel,
handleReset,
openUrl,
printWizardHeader,
probeGatewayReachable,
randomToken,
resolveControlUiLinks,
summarizeExistingConfig,
} from "./onboard-helpers.js";
import { setupProviders } from "./onboard-providers.js";
import { promptRemoteGatewayConfig } from "./onboard-remote.js";
import { setupSkills } from "./onboard-skills.js";
import type {
AuthChoice,
GatewayAuthChoice,
OnboardMode,
OnboardOptions,
ResetScope,
} from "./onboard-types.js";
import { createClackPrompter } from "../wizard/clack-prompter.js";
import { runOnboardingWizard } from "../wizard/onboarding.js";
import { WizardCancelledError } from "../wizard/prompts.js";
import type { OnboardOptions } from "./onboard-types.js";
export async function runInteractiveOnboarding(
opts: OnboardOptions,
runtime: RuntimeEnv = defaultRuntime,
) {
printWizardHeader(runtime);
intro("Clawdis onboarding");
const snapshot = await readConfigFileSnapshot();
let baseConfig: ClawdisConfig = snapshot.valid ? snapshot.config : {};
if (snapshot.exists) {
const title = snapshot.valid
? "Existing config detected"
: "Invalid config";
note(summarizeExistingConfig(baseConfig), title);
if (!snapshot.valid && snapshot.issues.length > 0) {
note(
snapshot.issues
.map((iss) => `- ${iss.path}: ${iss.message}`)
.join("\n"),
"Config issues",
);
}
const action = guardCancel(
await select({
message: "Config handling",
options: [
{ value: "keep", label: "Use existing values" },
{ value: "modify", label: "Update values" },
{ value: "reset", label: "Reset" },
],
}),
runtime,
);
if (action === "reset") {
const workspaceDefault = baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE;
const resetScope = guardCancel(
await select({
message: "Reset scope",
options: [
{ value: "config", label: "Config only" },
{
value: "config+creds+sessions",
label: "Config + creds + sessions",
},
{
value: "full",
label: "Full reset (config + creds + sessions + workspace)",
},
],
}),
runtime,
) as ResetScope;
await handleReset(resetScope, resolveUserPath(workspaceDefault), runtime);
baseConfig = {};
} else if (action === "keep" && !snapshot.valid) {
baseConfig = {};
}
}
const localPort = resolveGatewayPort(baseConfig);
const localUrl = `ws://127.0.0.1:${localPort}`;
const localProbe = await probeGatewayReachable({
url: localUrl,
token: process.env.CLAWDIS_GATEWAY_TOKEN,
password:
baseConfig.gateway?.auth?.password ??
process.env.CLAWDIS_GATEWAY_PASSWORD,
});
const remoteUrl = baseConfig.gateway?.remote?.url?.trim() ?? "";
const remoteProbe = remoteUrl
? await probeGatewayReachable({
url: remoteUrl,
token: baseConfig.gateway?.remote?.token,
})
: null;
const mode =
opts.mode ??
(guardCancel(
await select({
message: "Where will the Gateway run?",
options: [
{
value: "local",
label: "Local (this machine)",
hint: localProbe.ok
? `Gateway reachable (${localUrl})`
: `No gateway detected (${localUrl})`,
},
{
value: "remote",
label: "Remote (info-only)",
hint: !remoteUrl
? "No remote URL configured yet"
: remoteProbe?.ok
? `Gateway reachable (${remoteUrl})`
: `Configured but unreachable (${remoteUrl})`,
},
],
}),
runtime,
) as OnboardMode);
if (mode === "remote") {
let nextConfig = await promptRemoteGatewayConfig(baseConfig, runtime);
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
await writeConfigFile(nextConfig);
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
outro("Remote gateway configured.");
return;
}
const workspaceInput =
opts.workspace ??
(guardCancel(
await text({
message: "Workspace directory",
initialValue: baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE,
}),
runtime,
) as string);
const workspaceDir = resolveUserPath(
workspaceInput.trim() || DEFAULT_WORKSPACE,
);
let nextConfig: ClawdisConfig = {
...baseConfig,
agent: {
...baseConfig.agent,
workspace: workspaceDir,
},
gateway: {
...baseConfig.gateway,
mode: "local",
},
};
const authChoice = guardCancel(
await select({
message: "Model/auth choice",
options: [
{ value: "oauth", label: "Anthropic OAuth (Claude Pro/Max)" },
{
value: "antigravity",
label: "Google Antigravity (Claude Opus 4.5, Gemini 3, etc.)",
},
{ value: "apiKey", label: "Anthropic API key" },
{ value: "minimax", label: "Minimax M2.1 (LM Studio)" },
{ value: "skip", label: "Skip for now" },
],
}),
runtime,
) as AuthChoice;
if (authChoice === "oauth") {
note(
"Browser will open. Paste the code shown after login (code#state).",
"Anthropic OAuth",
);
const spin = spinner();
spin.start("Waiting for authorization…");
let oauthCreds: OAuthCredentials | null = null;
try {
oauthCreds = await loginAnthropic(
async (url) => {
await openUrl(url);
runtime.log(`Open: ${url}`);
},
async () => {
const code = guardCancel(
await text({
message: "Paste authorization code (code#state)",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
return String(code);
},
);
spin.stop("OAuth complete");
if (oauthCreds) {
await writeOAuthCredentials("anthropic", oauthCreds);
}
} catch (err) {
spin.stop("OAuth failed");
runtime.error(String(err));
}
} else if (authChoice === "antigravity") {
const isRemote = isRemoteEnvironment();
note(
isRemote
? [
"You are running in a remote/VPS environment.",
"A URL will be shown for you to open in your LOCAL browser.",
"After signing in, copy the redirect URL and paste it back here.",
].join("\n")
: [
"Browser will open for Google authentication.",
"Sign in with your Google account that has Antigravity access.",
"The callback will be captured automatically on localhost:51121.",
].join("\n"),
"Google Antigravity OAuth",
);
const spin = spinner();
spin.start("Starting OAuth flow…");
let oauthCreds: OAuthCredentials | null = null;
try {
oauthCreds = await loginAntigravityVpsAware(
async (url) => {
if (isRemote) {
spin.stop("OAuth URL ready");
runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${url}\n`);
} else {
spin.message("Complete sign-in in browser…");
await openUrl(url);
runtime.log(`Open: ${url}`);
}
},
(msg) => spin.message(msg),
);
spin.stop("Antigravity OAuth complete");
if (oauthCreds) {
await writeOAuthCredentials("google-antigravity", oauthCreds);
// Set default model to Claude Opus 4.5 via Antigravity
nextConfig = {
...nextConfig,
agent: {
...nextConfig.agent,
model: "google-antigravity/claude-opus-4-5-thinking",
},
};
note(
"Default model set to google-antigravity/claude-opus-4-5-thinking",
"Model configured",
);
}
} catch (err) {
spin.stop("Antigravity OAuth failed");
runtime.error(String(err));
}
} else if (authChoice === "apiKey") {
const key = guardCancel(
await text({
message: "Enter Anthropic API key",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
await setAnthropicApiKey(String(key).trim());
} else if (authChoice === "minimax") {
nextConfig = applyMinimaxConfig(nextConfig);
}
const portRaw = guardCancel(
await text({
message: "Gateway port",
initialValue: String(localPort),
validate: (value) =>
Number.isFinite(Number(value)) ? undefined : "Invalid port",
}),
runtime,
);
const port = Number.parseInt(String(portRaw), 10);
let bind = guardCancel(
await select({
message: "Gateway bind",
options: [
{ value: "loopback", label: "Loopback (127.0.0.1)" },
{ value: "lan", label: "LAN" },
{ value: "tailnet", label: "Tailnet" },
{ value: "auto", label: "Auto" },
],
}),
runtime,
) as "loopback" | "lan" | "tailnet" | "auto";
let authMode = guardCancel(
await select({
message: "Gateway auth",
options: [
{
value: "off",
label: "Off (loopback only)",
hint: "Recommended for single-machine setups",
},
{
value: "token",
label: "Token",
hint: "Use for multi-machine access or non-loopback binds",
},
{ value: "password", label: "Password" },
],
}),
runtime,
) as GatewayAuthChoice;
const tailscaleMode = guardCancel(
await select({
message: "Tailscale exposure",
options: [
{ value: "off", label: "Off", hint: "No Tailscale exposure" },
{
value: "serve",
label: "Serve",
hint: "Private HTTPS for your tailnet (devices on Tailscale)",
},
{
value: "funnel",
label: "Funnel",
hint: "Public HTTPS via Tailscale Funnel (internet)",
},
],
}),
runtime,
) as "off" | "serve" | "funnel";
let tailscaleResetOnExit = false;
if (tailscaleMode !== "off") {
tailscaleResetOnExit = Boolean(
guardCancel(
await confirm({
message: "Reset Tailscale serve/funnel on exit?",
initialValue: false,
}),
runtime,
),
);
}
if (tailscaleMode !== "off" && bind !== "loopback") {
note(
"Tailscale requires bind=loopback. Adjusting bind to loopback.",
"Note",
);
bind = "loopback";
}
if (authMode === "off" && bind !== "loopback") {
note("Non-loopback bind requires auth. Switching to token auth.", "Note");
authMode = "token";
}
if (tailscaleMode === "funnel" && authMode !== "password") {
note("Tailscale funnel requires password auth.", "Note");
authMode = "password";
}
let gatewayToken: string | undefined;
if (authMode === "token") {
const tokenInput = guardCancel(
await text({
message: "Gateway token (blank to generate)",
placeholder: "Needed for multi-machine or non-loopback access",
initialValue: randomToken(),
}),
runtime,
);
gatewayToken = String(tokenInput).trim() || randomToken();
}
if (authMode === "password") {
const password = guardCancel(
await text({
message: "Gateway password",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
auth: {
...nextConfig.gateway?.auth,
mode: "password",
password: String(password).trim(),
},
},
};
} else if (authMode === "token") {
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
auth: {
...nextConfig.gateway?.auth,
mode: "token",
token: gatewayToken,
},
},
};
}
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
port,
bind,
tailscale: {
...nextConfig.gateway?.tailscale,
mode: tailscaleMode,
resetOnExit: tailscaleResetOnExit,
},
},
};
nextConfig = await setupProviders(nextConfig, runtime, {
allowSignalInstall: true,
});
await writeConfigFile(nextConfig);
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
await ensureWorkspaceAndSessions(workspaceDir, runtime);
nextConfig = await setupSkills(nextConfig, workspaceDir, runtime);
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
await writeConfigFile(nextConfig);
const installDaemon = guardCancel(
await confirm({
message: "Install Gateway daemon (recommended)",
initialValue: true,
}),
runtime,
);
if (installDaemon) {
const service = resolveGatewayService();
const loaded = await service.isLoaded({ env: process.env });
if (loaded) {
const action = guardCancel(
await select({
message: "Gateway service already installed",
options: [
{ value: "restart", label: "Restart" },
{ value: "reinstall", label: "Reinstall" },
{ value: "skip", label: "Skip" },
],
}),
runtime,
);
if (action === "restart") {
await service.restart({ stdout: process.stdout });
} else if (action === "reinstall") {
await service.uninstall({ env: process.env, stdout: process.stdout });
}
}
if (
!loaded ||
(loaded && (await service.isLoaded({ env: process.env })) === false)
) {
const devMode =
process.argv[1]?.includes(`${path.sep}src${path.sep}`) &&
process.argv[1]?.endsWith(".ts");
const { programArguments, workingDirectory } =
await resolveGatewayProgramArguments({ port, dev: devMode });
const environment: Record<string, string | undefined> = {
PATH: process.env.PATH,
CLAWDIS_GATEWAY_TOKEN: gatewayToken,
CLAWDIS_LAUNCHD_LABEL:
process.platform === "darwin"
? GATEWAY_LAUNCH_AGENT_LABEL
: undefined,
};
await service.install({
env: process.env,
stdout: process.stdout,
programArguments,
workingDirectory,
environment,
});
}
}
await sleep(1500);
const prompter = createClackPrompter();
try {
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
await runOnboardingWizard(opts, runtime, prompter);
} catch (err) {
runtime.error(`Health check failed: ${String(err)}`);
if (err instanceof WizardCancelledError) {
runtime.exit(0);
return;
}
throw err;
}
note(
[
"Add nodes for extra features:",
"- macOS app (system + notifications)",
"- iOS app (camera/canvas)",
"- Android app (camera/canvas)",
].join("\n"),
"Optional apps",
);
note(
(() => {
const links = resolveControlUiLinks({ bind, port });
const tokenParam =
authMode === "token" && gatewayToken
? `?token=${encodeURIComponent(gatewayToken)}`
: "";
const authedUrl = `${links.httpUrl}${tokenParam}`;
return [
`Web UI: ${links.httpUrl}`,
tokenParam ? `Web UI (with token): ${authedUrl}` : undefined,
`Gateway WS: ${links.wsUrl}`,
]
.filter(Boolean)
.join("\n");
})(),
"Control UI",
);
const wantsOpen = guardCancel(
await confirm({
message: "Open Control UI now?",
initialValue: true,
}),
runtime,
);
if (wantsOpen) {
const links = resolveControlUiLinks({ bind, port });
const tokenParam =
authMode === "token" && gatewayToken
? `?token=${encodeURIComponent(gatewayToken)}`
: "";
await openUrl(`${links.httpUrl}${tokenParam}`);
}
outro("Onboarding complete.");
}

View File

@@ -1,15 +1,12 @@
import fs from "node:fs/promises";
import path from "node:path";
import { confirm, multiselect, note, select, text } from "@clack/prompts";
import chalk from "chalk";
import type { ClawdisConfig } from "../config/config.js";
import { loginWeb } from "../provider-web.js";
import type { RuntimeEnv } from "../runtime.js";
import { normalizeE164 } from "../utils.js";
import { resolveWebAuthDir } from "../web/session.js";
import { detectBinary, guardCancel } from "./onboard-helpers.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { detectBinary } from "./onboard-helpers.js";
import type { ProviderChoice } from "./onboard-types.js";
import { installSignalCli } from "./signal-install.js";
@@ -27,8 +24,8 @@ async function detectWhatsAppLinked(): Promise<boolean> {
return await pathExists(credsPath);
}
function noteProviderPrimer(): void {
note(
async function noteProviderPrimer(prompter: WizardPrompter): Promise<void> {
await prompter.note(
[
"WhatsApp: links via WhatsApp Web (scan QR), stores creds for future sends.",
"Telegram: Bot API (token from @BotFather), replies via your bot.",
@@ -40,8 +37,8 @@ function noteProviderPrimer(): void {
);
}
function noteTelegramTokenHelp(): void {
note(
async function noteTelegramTokenHelp(prompter: WizardPrompter): Promise<void> {
await prompter.note(
[
"1) Open Telegram and chat with @BotFather",
"2) Run /newbot (or /mybots)",
@@ -52,8 +49,8 @@ function noteTelegramTokenHelp(): void {
);
}
function noteDiscordTokenHelp(): void {
note(
async function noteDiscordTokenHelp(prompter: WizardPrompter): Promise<void> {
await prompter.note(
[
"1) Discord Developer Portal → Applications → New Application",
"2) Bot → Add Bot → Reset Token → copy token",
@@ -76,13 +73,14 @@ function setWhatsAppAllowFrom(cfg: ClawdisConfig, allowFrom?: string[]) {
async function promptWhatsAppAllowFrom(
cfg: ClawdisConfig,
runtime: RuntimeEnv,
_runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<ClawdisConfig> {
const existingAllowFrom = cfg.whatsapp?.allowFrom ?? [];
const existingLabel =
existingAllowFrom.length > 0 ? existingAllowFrom.join(", ") : "unset";
note(
await prompter.note(
[
"WhatsApp direct chats are gated by `whatsapp.allowFrom`.",
'Default (unset) = self-chat only; use "*" to allow anyone.',
@@ -105,40 +103,34 @@ async function promptWhatsAppAllowFrom(
{ value: "any", label: "Anyone (*)" },
] as const);
const mode = guardCancel(
await select({
message: "Who can trigger the bot via WhatsApp?",
options: options.map((opt) => ({ value: opt.value, label: opt.label })),
}),
runtime,
) as (typeof options)[number]["value"];
const mode = (await prompter.select({
message: "Who can trigger the bot via WhatsApp?",
options: options.map((opt) => ({ value: opt.value, label: opt.label })),
})) as (typeof options)[number]["value"];
if (mode === "keep") return cfg;
if (mode === "self") return setWhatsAppAllowFrom(cfg, undefined);
if (mode === "any") return setWhatsAppAllowFrom(cfg, ["*"]);
const allowRaw = guardCancel(
await text({
message: "Allowed sender numbers (comma-separated, E.164)",
placeholder: "+15555550123, +447700900123",
validate: (value) => {
const raw = String(value ?? "").trim();
if (!raw) return "Required";
const parts = raw
.split(/[\n,;]+/g)
.map((p) => p.trim())
.filter(Boolean);
if (parts.length === 0) return "Required";
for (const part of parts) {
if (part === "*") continue;
const normalized = normalizeE164(part);
if (!normalized) return `Invalid number: ${part}`;
}
return undefined;
},
}),
runtime,
);
const allowRaw = await prompter.text({
message: "Allowed sender numbers (comma-separated, E.164)",
placeholder: "+15555550123, +447700900123",
validate: (value) => {
const raw = String(value ?? "").trim();
if (!raw) return "Required";
const parts = raw
.split(/[\n,;]+/g)
.map((p) => p.trim())
.filter(Boolean);
if (parts.length === 0) return "Required";
for (const part of parts) {
if (part === "*") continue;
const normalized = normalizeE164(part);
if (!normalized) return `Invalid number: ${part}`;
}
return undefined;
},
});
const parts = String(allowRaw)
.split(/[\n,;]+/g)
@@ -154,6 +146,7 @@ async function promptWhatsAppAllowFrom(
export async function setupProviders(
cfg: ClawdisConfig,
runtime: RuntimeEnv,
prompter: WizardPrompter,
options?: { allowDisable?: boolean; allowSignalInstall?: boolean },
): Promise<ClawdisConfig> {
const whatsappLinked = await detectWhatsAppLinked();
@@ -174,91 +167,63 @@ export async function setupProviders(
const imessageCliPath = cfg.imessage?.cliPath ?? "imsg";
const imessageCliDetected = await detectBinary(imessageCliPath);
note(
await prompter.note(
[
`WhatsApp: ${
whatsappLinked ? chalk.green("linked") : chalk.red("not linked")
}`,
`Telegram: ${
telegramConfigured
? chalk.green("configured")
: chalk.yellow("needs token")
}`,
`Discord: ${
discordConfigured
? chalk.green("configured")
: chalk.yellow("needs token")
}`,
`Signal: ${
signalConfigured
? chalk.green("configured")
: chalk.yellow("needs setup")
}`,
`iMessage: ${
imessageConfigured
? chalk.green("configured")
: chalk.yellow("needs setup")
}`,
`signal-cli: ${
signalCliDetected ? chalk.green("found") : chalk.red("missing")
} (${signalCliPath})`,
`imsg: ${
imessageCliDetected ? chalk.green("found") : chalk.red("missing")
} (${imessageCliPath})`,
`WhatsApp: ${whatsappLinked ? "linked" : "not linked"}`,
`Telegram: ${telegramConfigured ? "configured" : "needs token"}`,
`Discord: ${discordConfigured ? "configured" : "needs token"}`,
`Signal: ${signalConfigured ? "configured" : "needs setup"}`,
`iMessage: ${imessageConfigured ? "configured" : "needs setup"}`,
`signal-cli: ${signalCliDetected ? "found" : "missing"} (${signalCliPath})`,
`imsg: ${imessageCliDetected ? "found" : "missing"} (${imessageCliPath})`,
].join("\n"),
"Provider status",
);
const shouldConfigure = guardCancel(
await confirm({
message: "Configure chat providers now?",
initialValue: true,
}),
runtime,
);
const shouldConfigure = await prompter.confirm({
message: "Configure chat providers now?",
initialValue: true,
});
if (!shouldConfigure) return cfg;
noteProviderPrimer();
await noteProviderPrimer(prompter);
const selection = guardCancel(
await multiselect({
message: "Select providers",
options: [
{
value: "whatsapp",
label: "WhatsApp (QR link)",
hint: whatsappLinked ? "linked" : "not linked",
},
{
value: "telegram",
label: "Telegram (Bot API)",
hint: telegramConfigured ? "configured" : "needs token",
},
{
value: "discord",
label: "Discord (Bot API)",
hint: discordConfigured ? "configured" : "needs token",
},
{
value: "signal",
label: "Signal (signal-cli)",
hint: signalCliDetected ? "signal-cli found" : "signal-cli missing",
},
{
value: "imessage",
label: "iMessage (imsg)",
hint: imessageCliDetected ? "imsg found" : "imsg missing",
},
],
}),
runtime,
) as ProviderChoice[];
const selection = (await prompter.multiselect({
message: "Select providers",
options: [
{
value: "whatsapp",
label: "WhatsApp (QR link)",
hint: whatsappLinked ? "linked" : "not linked",
},
{
value: "telegram",
label: "Telegram (Bot API)",
hint: telegramConfigured ? "configured" : "needs token",
},
{
value: "discord",
label: "Discord (Bot API)",
hint: discordConfigured ? "configured" : "needs token",
},
{
value: "signal",
label: "Signal (signal-cli)",
hint: signalCliDetected ? "signal-cli found" : "signal-cli missing",
},
{
value: "imessage",
label: "iMessage (imsg)",
hint: imessageCliDetected ? "imsg found" : "imsg missing",
},
],
})) as ProviderChoice[];
let next = cfg;
if (selection.includes("whatsapp")) {
if (!whatsappLinked) {
note(
await prompter.note(
[
"Scan the QR with WhatsApp on your phone.",
"Credentials are stored under ~/.clawdis/credentials/ for future runs.",
@@ -266,15 +231,12 @@ export async function setupProviders(
"WhatsApp linking",
);
}
const wantsLink = guardCancel(
await confirm({
message: whatsappLinked
? "WhatsApp already linked. Re-link now?"
: "Link WhatsApp now (QR)?",
initialValue: !whatsappLinked,
}),
runtime,
);
const wantsLink = await prompter.confirm({
message: whatsappLinked
? "WhatsApp already linked. Re-link now?"
: "Link WhatsApp now (QR)?",
initialValue: !whatsappLinked,
});
if (wantsLink) {
try {
await loginWeb(false, "web");
@@ -282,25 +244,25 @@ export async function setupProviders(
runtime.error(`WhatsApp login failed: ${String(err)}`);
}
} else if (!whatsappLinked) {
note("Run `clawdis login` later to link WhatsApp.", "WhatsApp");
await prompter.note(
"Run `clawdis login` later to link WhatsApp.",
"WhatsApp",
);
}
next = await promptWhatsAppAllowFrom(next, runtime);
next = await promptWhatsAppAllowFrom(next, runtime, prompter);
}
if (selection.includes("telegram")) {
let token: string | null = null;
if (!telegramConfigured) {
noteTelegramTokenHelp();
await noteTelegramTokenHelp(prompter);
}
if (telegramEnv && !cfg.telegram?.botToken) {
const keepEnv = guardCancel(
await confirm({
message: "TELEGRAM_BOT_TOKEN detected. Use env var?",
initialValue: true,
}),
runtime,
);
const keepEnv = await prompter.confirm({
message: "TELEGRAM_BOT_TOKEN detected. Use env var?",
initialValue: true,
});
if (keepEnv) {
next = {
...next,
@@ -311,43 +273,31 @@ export async function setupProviders(
};
} else {
token = String(
guardCancel(
await text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else if (cfg.telegram?.botToken) {
const keep = guardCancel(
await confirm({
message: "Telegram token already configured. Keep it?",
initialValue: true,
}),
runtime,
);
const keep = await prompter.confirm({
message: "Telegram token already configured. Keep it?",
initialValue: true,
});
if (!keep) {
token = String(
guardCancel(
await text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else {
token = String(
guardCancel(
await text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
@@ -366,16 +316,13 @@ export async function setupProviders(
if (selection.includes("discord")) {
let token: string | null = null;
if (!discordConfigured) {
noteDiscordTokenHelp();
await noteDiscordTokenHelp(prompter);
}
if (discordEnv && !cfg.discord?.token) {
const keepEnv = guardCancel(
await confirm({
message: "DISCORD_BOT_TOKEN detected. Use env var?",
initialValue: true,
}),
runtime,
);
const keepEnv = await prompter.confirm({
message: "DISCORD_BOT_TOKEN detected. Use env var?",
initialValue: true,
});
if (keepEnv) {
next = {
...next,
@@ -386,43 +333,31 @@ export async function setupProviders(
};
} else {
token = String(
guardCancel(
await text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else if (cfg.discord?.token) {
const keep = guardCancel(
await confirm({
message: "Discord token already configured. Keep it?",
initialValue: true,
}),
runtime,
);
const keep = await prompter.confirm({
message: "Discord token already configured. Keep it?",
initialValue: true,
});
if (!keep) {
token = String(
guardCancel(
await text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else {
token = String(
guardCancel(
await text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
@@ -442,33 +377,39 @@ export async function setupProviders(
let resolvedCliPath = signalCliPath;
let cliDetected = signalCliDetected;
if (options?.allowSignalInstall) {
const wantsInstall = guardCancel(
await confirm({
message: cliDetected
? "signal-cli detected. Reinstall/update now?"
: "signal-cli not found. Install now?",
initialValue: !cliDetected,
}),
runtime,
);
const wantsInstall = await prompter.confirm({
message: cliDetected
? "signal-cli detected. Reinstall/update now?"
: "signal-cli not found. Install now?",
initialValue: !cliDetected,
});
if (wantsInstall) {
try {
const result = await installSignalCli(runtime);
if (result.ok && result.cliPath) {
cliDetected = true;
resolvedCliPath = result.cliPath;
note(`Installed signal-cli at ${result.cliPath}`, "Signal");
await prompter.note(
`Installed signal-cli at ${result.cliPath}`,
"Signal",
);
} else if (!result.ok) {
note(result.error ?? "signal-cli install failed.", "Signal");
await prompter.note(
result.error ?? "signal-cli install failed.",
"Signal",
);
}
} catch (err) {
note(`signal-cli install failed: ${String(err)}`, "Signal");
await prompter.note(
`signal-cli install failed: ${String(err)}`,
"Signal",
);
}
}
}
if (!cliDetected) {
note(
await prompter.note(
"signal-cli not found. Install it, then rerun this step or set signal.cliPath.",
"Signal",
);
@@ -476,25 +417,19 @@ export async function setupProviders(
let account = cfg.signal?.account ?? "";
if (account) {
const keep = guardCancel(
await confirm({
message: `Signal account set (${account}). Keep it?`,
initialValue: true,
}),
runtime,
);
const keep = await prompter.confirm({
message: `Signal account set (${account}). Keep it?`,
initialValue: true,
});
if (!keep) account = "";
}
if (!account) {
account = String(
guardCancel(
await text({
message: "Signal bot number (E.164)",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Signal bot number (E.164)",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
@@ -510,7 +445,7 @@ export async function setupProviders(
};
}
note(
await prompter.note(
[
'Link device with: signal-cli link -n "Clawdis"',
"Scan QR in Signal → Linked Devices",
@@ -523,17 +458,17 @@ export async function setupProviders(
if (selection.includes("imessage")) {
let resolvedCliPath = imessageCliPath;
if (!imessageCliDetected) {
const entered = guardCancel(
await text({
message: "imsg CLI path",
initialValue: resolvedCliPath,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
const entered = await prompter.text({
message: "imsg CLI path",
initialValue: resolvedCliPath,
validate: (value) => (value?.trim() ? undefined : "Required"),
});
resolvedCliPath = String(entered).trim();
if (!resolvedCliPath) {
note("imsg CLI path required to enable iMessage.", "iMessage");
await prompter.note(
"imsg CLI path required to enable iMessage.",
"iMessage",
);
}
}
@@ -548,7 +483,7 @@ export async function setupProviders(
};
}
note(
await prompter.note(
[
"Ensure Clawdis has Full Disk Access to Messages DB.",
"Grant Automation permission for Messages when prompted.",
@@ -560,13 +495,10 @@ export async function setupProviders(
if (options?.allowDisable) {
if (!selection.includes("telegram") && telegramConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable Telegram provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable Telegram provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
@@ -576,13 +508,10 @@ export async function setupProviders(
}
if (!selection.includes("discord") && discordConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable Discord provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable Discord provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
@@ -592,13 +521,10 @@ export async function setupProviders(
}
if (!selection.includes("signal") && signalConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable Signal provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable Signal provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
@@ -608,13 +534,10 @@ export async function setupProviders(
}
if (!selection.includes("imessage") && imessageConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable iMessage provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable iMessage provider?",
initialValue: false,
});
if (disable) {
next = {
...next,

View File

@@ -1,10 +1,8 @@
import { confirm, note, select, spinner, text } from "@clack/prompts";
import type { ClawdisConfig } from "../config/config.js";
import type { GatewayBonjourBeacon } from "../infra/bonjour-discovery.js";
import { discoverGatewayBeacons } from "../infra/bonjour-discovery.js";
import type { RuntimeEnv } from "../runtime.js";
import { detectBinary, guardCancel } from "./onboard-helpers.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { detectBinary } from "./onboard-helpers.js";
const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789";
@@ -28,7 +26,7 @@ function ensureWsUrl(value: string): string {
export async function promptRemoteGatewayConfig(
cfg: ClawdisConfig,
runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<ClawdisConfig> {
let selectedBeacon: GatewayBonjourBeacon | null = null;
let suggestedUrl = cfg.gateway?.remote?.url ?? DEFAULT_GATEWAY_URL;
@@ -36,25 +34,21 @@ export async function promptRemoteGatewayConfig(
const hasBonjourTool =
(await detectBinary("dns-sd")) || (await detectBinary("avahi-browse"));
const wantsDiscover = hasBonjourTool
? guardCancel(
await confirm({
message: "Discover gateway on LAN (Bonjour)?",
initialValue: true,
}),
runtime,
)
? await prompter.confirm({
message: "Discover gateway on LAN (Bonjour)?",
initialValue: true,
})
: false;
if (!hasBonjourTool) {
note(
await prompter.note(
"Bonjour discovery requires dns-sd (macOS) or avahi-browse (Linux).",
"Discovery",
);
}
if (wantsDiscover) {
const spin = spinner();
spin.start("Searching for gateways…");
const spin = prompter.progress("Searching for gateways…");
const beacons = await discoverGatewayBeacons({ timeoutMs: 2000 });
spin.stop(
beacons.length > 0
@@ -63,19 +57,16 @@ export async function promptRemoteGatewayConfig(
);
if (beacons.length > 0) {
const selection = guardCancel(
await select({
message: "Select gateway",
options: [
...beacons.map((beacon, index) => ({
value: String(index),
label: buildLabel(beacon),
})),
{ value: "manual", label: "Enter URL manually" },
],
}),
runtime,
);
const selection = await prompter.select({
message: "Select gateway",
options: [
...beacons.map((beacon, index) => ({
value: String(index),
label: buildLabel(beacon),
})),
{ value: "manual", label: "Enter URL manually" },
],
});
if (selection !== "manual") {
const idx = Number.parseInt(String(selection), 10);
selectedBeacon = Number.isFinite(idx) ? (beacons[idx] ?? null) : null;
@@ -87,24 +78,21 @@ export async function promptRemoteGatewayConfig(
const host = pickHost(selectedBeacon);
const port = selectedBeacon.gatewayPort ?? 18789;
if (host) {
const mode = guardCancel(
await select({
message: "Connection method",
options: [
{
value: "direct",
label: `Direct gateway WS (${host}:${port})`,
},
{ value: "ssh", label: "SSH tunnel (loopback)" },
],
}),
runtime,
);
const mode = await prompter.select({
message: "Connection method",
options: [
{
value: "direct",
label: `Direct gateway WS (${host}:${port})`,
},
{ value: "ssh", label: "SSH tunnel (loopback)" },
],
});
if (mode === "direct") {
suggestedUrl = `ws://${host}:${port}`;
} else {
suggestedUrl = DEFAULT_GATEWAY_URL;
note(
await prompter.note(
[
"Start a tunnel before using the CLI:",
`ssh -N -L 18789:127.0.0.1:18789 <user>@${host}${
@@ -117,42 +105,33 @@ export async function promptRemoteGatewayConfig(
}
}
const urlInput = guardCancel(
await text({
message: "Gateway WebSocket URL",
initialValue: suggestedUrl,
validate: (value) =>
String(value).trim().startsWith("ws://") ||
String(value).trim().startsWith("wss://")
? undefined
: "URL must start with ws:// or wss://",
}),
runtime,
);
const urlInput = await prompter.text({
message: "Gateway WebSocket URL",
initialValue: suggestedUrl,
validate: (value) =>
String(value).trim().startsWith("ws://") ||
String(value).trim().startsWith("wss://")
? undefined
: "URL must start with ws:// or wss://",
});
const url = ensureWsUrl(String(urlInput));
const authChoice = guardCancel(
await select({
message: "Gateway auth",
options: [
{ value: "token", label: "Token (recommended)" },
{ value: "off", label: "No auth" },
],
}),
runtime,
) as "token" | "off";
const authChoice = (await prompter.select({
message: "Gateway auth",
options: [
{ value: "token", label: "Token (recommended)" },
{ value: "off", label: "No auth" },
],
})) as "token" | "off";
let token = cfg.gateway?.remote?.token ?? "";
if (authChoice === "token") {
token = String(
guardCancel(
await text({
message: "Gateway token",
initialValue: token,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Gateway token",
initialValue: token,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
} else {
token = "";

View File

@@ -1,17 +1,9 @@
import {
confirm,
multiselect,
note,
select,
spinner,
text,
} from "@clack/prompts";
import { installSkill } from "../agents/skills-install.js";
import { buildWorkspaceSkillStatus } from "../agents/skills-status.js";
import type { ClawdisConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import { guardCancel, resolveNodeManagerOptions } from "./onboard-helpers.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { resolveNodeManagerOptions } from "./onboard-helpers.js";
function summarizeInstallFailure(message: string): string | undefined {
const cleaned = message
@@ -58,6 +50,7 @@ export async function setupSkills(
cfg: ClawdisConfig,
workspaceDir: string,
runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<ClawdisConfig> {
const report = buildWorkspaceSkillStatus(workspaceDir, { config: cfg });
const eligible = report.skills.filter((s) => s.eligible);
@@ -66,7 +59,7 @@ export async function setupSkills(
);
const blocked = report.skills.filter((s) => s.blockedByAllowlist);
note(
await prompter.note(
[
`Eligible: ${eligible.length}`,
`Missing requirements: ${missing.length}`,
@@ -75,22 +68,16 @@ export async function setupSkills(
"Skills status",
);
const shouldConfigure = guardCancel(
await confirm({
message: "Configure skills now? (recommended)",
initialValue: true,
}),
runtime,
);
const shouldConfigure = await prompter.confirm({
message: "Configure skills now? (recommended)",
initialValue: true,
});
if (!shouldConfigure) return cfg;
const nodeManager = guardCancel(
await select({
message: "Preferred node manager for skill installs",
options: resolveNodeManagerOptions(),
}),
runtime,
) as "npm" | "pnpm" | "bun";
const nodeManager = (await prompter.select({
message: "Preferred node manager for skill installs",
options: resolveNodeManagerOptions(),
})) as "npm" | "pnpm" | "bun";
let next: ClawdisConfig = {
...cfg,
@@ -107,24 +94,21 @@ export async function setupSkills(
(skill) => skill.install.length > 0 && skill.missing.bins.length > 0,
);
if (installable.length > 0) {
const toInstall = guardCancel(
await multiselect({
message: "Install missing skill dependencies",
options: [
{
value: "__skip__",
label: "Skip for now",
hint: "Continue without installing dependencies",
},
...installable.map((skill) => ({
value: skill.name,
label: `${skill.emoji ?? "🧩"} ${skill.name}`,
hint: formatSkillHint(skill),
})),
],
}),
runtime,
);
const toInstall = await prompter.multiselect({
message: "Install missing skill dependencies",
options: [
{
value: "__skip__",
label: "Skip for now",
hint: "Continue without installing dependencies",
},
...installable.map((skill) => ({
value: skill.name,
label: `${skill.emoji ?? "🧩"} ${skill.name}`,
hint: formatSkillHint(skill),
})),
],
});
const selected = (toInstall as string[]).filter(
(name) => name !== "__skip__",
@@ -134,8 +118,7 @@ export async function setupSkills(
if (!target || target.install.length === 0) continue;
const installId = target.install[0]?.id;
if (!installId) continue;
const spin = spinner();
spin.start(`Installing ${name}`);
const spin = prompter.progress(`Installing ${name}`);
const result = await installSkill({
workspaceDir,
skillName: target.name,
@@ -161,22 +144,16 @@ export async function setupSkills(
for (const skill of missing) {
if (!skill.primaryEnv || skill.missing.env.length === 0) continue;
const wantsKey = guardCancel(
await confirm({
message: `Set ${skill.primaryEnv} for ${skill.name}?`,
initialValue: false,
}),
runtime,
);
const wantsKey = await prompter.confirm({
message: `Set ${skill.primaryEnv} for ${skill.name}?`,
initialValue: false,
});
if (!wantsKey) continue;
const apiKey = String(
guardCancel(
await text({
message: `Enter ${skill.primaryEnv}`,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: `Enter ${skill.primaryEnv}`,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
);
next = upsertSkillEntry(next, skill.skillKey, { apiKey: apiKey.trim() });
}

View File

@@ -573,6 +573,12 @@ export type ClawdisConfig = {
* - "message_end": end of the whole assistant message (may include tool blocks)
*/
blockStreamingBreak?: "text_end" | "message_end";
/** Soft block chunking for streamed replies (min/max chars, prefer paragraph/newline). */
blockStreamingChunk?: {
minChars?: number;
maxChars?: number;
breakPreference?: "paragraph" | "newline" | "sentence";
};
timeoutSeconds?: number;
/** Max inbound media size in MB for agent-visible attachments (text note or future image attach). */
mediaMaxMb?: number;
@@ -900,7 +906,7 @@ const HooksGmailSchema = z
})
.optional();
const ClawdisSchema = z.object({
export const ClawdisSchema = z.object({
identity: z
.object({
name: z.string().optional(),
@@ -990,6 +996,19 @@ const ClawdisSchema = z.object({
blockStreamingBreak: z
.union([z.literal("text_end"), z.literal("message_end")])
.optional(),
blockStreamingChunk: z
.object({
minChars: z.number().int().positive().optional(),
maxChars: z.number().int().positive().optional(),
breakPreference: z
.union([
z.literal("paragraph"),
z.literal("newline"),
z.literal("sentence"),
])
.optional(),
})
.optional(),
timeoutSeconds: z.number().int().positive().optional(),
mediaMaxMb: z.number().positive().optional(),
typingIntervalSeconds: z.number().int().positive().optional(),

16
src/config/schema.test.ts Normal file
View File

@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { buildConfigSchema } from "./schema.js";
describe("config schema", () => {
it("exports schema + hints", () => {
const res = buildConfigSchema();
const schema = res.schema as { properties?: Record<string, unknown> };
expect(schema.properties?.gateway).toBeTruthy();
expect(schema.properties?.agent).toBeTruthy();
expect(res.uiHints.gateway?.label).toBe("Gateway");
expect(res.uiHints["gateway.auth.token"]?.sensitive).toBe(true);
expect(res.version).toBeTruthy();
expect(res.generatedAt).toBeTruthy();
});
});

161
src/config/schema.ts Normal file
View File

@@ -0,0 +1,161 @@
import { VERSION } from "../version.js";
import { ClawdisSchema } from "./config.js";
export type ConfigUiHint = {
label?: string;
help?: string;
group?: string;
order?: number;
advanced?: boolean;
sensitive?: boolean;
placeholder?: string;
itemTemplate?: unknown;
};
export type ConfigUiHints = Record<string, ConfigUiHint>;
export type ConfigSchema = ReturnType<typeof ClawdisSchema.toJSONSchema>;
export type ConfigSchemaResponse = {
schema: ConfigSchema;
uiHints: ConfigUiHints;
version: string;
generatedAt: string;
};
const GROUP_LABELS: Record<string, string> = {
identity: "Identity",
wizard: "Wizard",
logging: "Logging",
gateway: "Gateway",
agent: "Agent",
models: "Models",
routing: "Routing",
messages: "Messages",
session: "Session",
cron: "Cron",
hooks: "Hooks",
ui: "UI",
browser: "Browser",
talk: "Talk",
telegram: "Telegram",
discord: "Discord",
signal: "Signal",
imessage: "iMessage",
whatsapp: "WhatsApp",
skills: "Skills",
discovery: "Discovery",
presence: "Presence",
voicewake: "Voice Wake",
};
const GROUP_ORDER: Record<string, number> = {
identity: 10,
wizard: 20,
gateway: 30,
agent: 40,
models: 50,
routing: 60,
messages: 70,
session: 80,
cron: 90,
hooks: 100,
ui: 110,
browser: 120,
talk: 130,
telegram: 140,
discord: 150,
signal: 160,
imessage: 170,
whatsapp: 180,
skills: 190,
discovery: 200,
presence: 210,
voicewake: 220,
logging: 900,
};
const FIELD_LABELS: Record<string, string> = {
"gateway.remote.url": "Remote Gateway URL",
"gateway.remote.token": "Remote Gateway Token",
"gateway.remote.password": "Remote Gateway Password",
"gateway.auth.token": "Gateway Token",
"gateway.auth.password": "Gateway Password",
"agent.workspace": "Workspace",
"agent.model": "Default Model",
"ui.seamColor": "Accent Color",
"browser.controlUrl": "Browser Control URL",
"talk.apiKey": "Talk API Key",
"telegram.botToken": "Telegram Bot Token",
"discord.token": "Discord Bot Token",
"signal.account": "Signal Account",
"imessage.cliPath": "iMessage CLI Path",
};
const FIELD_HELP: Record<string, string> = {
"gateway.remote.url": "Remote Gateway WebSocket URL (ws:// or wss://).",
"gateway.auth.token":
"Required for multi-machine access or non-loopback binds.",
"gateway.auth.password": "Required for Tailscale funnel.",
};
const FIELD_PLACEHOLDERS: Record<string, string> = {
"gateway.remote.url": "ws://host:18789",
};
const SENSITIVE_PATTERNS = [/token/i, /password/i, /secret/i, /api.?key/i];
function isSensitivePath(path: string): boolean {
return SENSITIVE_PATTERNS.some((pattern) => pattern.test(path));
}
function buildBaseHints(): ConfigUiHints {
const hints: ConfigUiHints = {};
for (const [group, label] of Object.entries(GROUP_LABELS)) {
hints[group] = {
label,
group: label,
order: GROUP_ORDER[group],
};
}
for (const [path, label] of Object.entries(FIELD_LABELS)) {
hints[path] = { ...(hints[path] ?? {}), label };
}
for (const [path, help] of Object.entries(FIELD_HELP)) {
hints[path] = { ...(hints[path] ?? {}), help };
}
for (const [path, placeholder] of Object.entries(FIELD_PLACEHOLDERS)) {
hints[path] = { ...(hints[path] ?? {}), placeholder };
}
return hints;
}
function applySensitiveHints(hints: ConfigUiHints): ConfigUiHints {
const next = { ...hints };
for (const key of Object.keys(next)) {
if (isSensitivePath(key)) {
next[key] = { ...next[key], sensitive: true };
}
}
return next;
}
let cached: ConfigSchemaResponse | null = null;
export function buildConfigSchema(): ConfigSchemaResponse {
if (cached) return cached;
const schema = ClawdisSchema.toJSONSchema({
target: "draft-07",
unrepresentable: "any",
});
schema.title = "ClawdisConfig";
const hints = applySensitiveHints(buildBaseHints());
const next = {
schema,
uiHints: hints,
version: VERSION,
generatedAt: new Date().toISOString(),
};
cached = next;
return next;
}

View File

@@ -146,11 +146,8 @@ export class GatewayClient {
const pending = this.pending.get(parsed.id);
if (!pending) return;
// If the payload is an ack with status accepted, keep waiting for final.
const payload = parsed.payload;
const status =
payload && typeof payload === "object" && "status" in payload
? (payload as { status?: unknown }).status
: undefined;
const payload = parsed.payload as { status?: unknown } | undefined;
const status = payload?.status;
if (pending.expectFinal && status === "accepted") {
return;
}

View File

@@ -11,6 +11,10 @@ import {
ChatSendParamsSchema,
type ConfigGetParams,
ConfigGetParamsSchema,
type ConfigSchemaParams,
ConfigSchemaParamsSchema,
type ConfigSchemaResponse,
ConfigSchemaResponseSchema,
type ConfigSetParams,
ConfigSetParamsSchema,
type ConnectParams,
@@ -105,6 +109,22 @@ import {
WebLoginStartParamsSchema,
type WebLoginWaitParams,
WebLoginWaitParamsSchema,
type WizardCancelParams,
WizardCancelParamsSchema,
type WizardNextParams,
WizardNextParamsSchema,
type WizardNextResult,
WizardNextResultSchema,
type WizardStartParams,
WizardStartParamsSchema,
type WizardStartResult,
WizardStartResultSchema,
type WizardStatusParams,
WizardStatusParamsSchema,
type WizardStatusResult,
WizardStatusResultSchema,
type WizardStep,
WizardStepSchema,
} from "./schema.js";
const ajv = new (
@@ -174,6 +194,21 @@ export const validateConfigGetParams = ajv.compile<ConfigGetParams>(
export const validateConfigSetParams = ajv.compile<ConfigSetParams>(
ConfigSetParamsSchema,
);
export const validateConfigSchemaParams = ajv.compile<ConfigSchemaParams>(
ConfigSchemaParamsSchema,
);
export const validateWizardStartParams = ajv.compile<WizardStartParams>(
WizardStartParamsSchema,
);
export const validateWizardNextParams = ajv.compile<WizardNextParams>(
WizardNextParamsSchema,
);
export const validateWizardCancelParams = ajv.compile<WizardCancelParams>(
WizardCancelParamsSchema,
);
export const validateWizardStatusParams = ajv.compile<WizardStatusParams>(
WizardStatusParamsSchema,
);
export const validateTalkModeParams =
ajv.compile<TalkModeParams>(TalkModeParamsSchema);
export const validateProvidersStatusParams = ajv.compile<ProvidersStatusParams>(
@@ -258,6 +293,16 @@ export {
SessionsCompactParamsSchema,
ConfigGetParamsSchema,
ConfigSetParamsSchema,
ConfigSchemaParamsSchema,
ConfigSchemaResponseSchema,
WizardStartParamsSchema,
WizardNextParamsSchema,
WizardCancelParamsSchema,
WizardStatusParamsSchema,
WizardStepSchema,
WizardNextResultSchema,
WizardStartResultSchema,
WizardStatusResultSchema,
ProvidersStatusParamsSchema,
WebLoginStartParamsSchema,
WebLoginWaitParamsSchema,
@@ -304,6 +349,16 @@ export type {
NodePairApproveParams,
ConfigGetParams,
ConfigSetParams,
ConfigSchemaParams,
ConfigSchemaResponse,
WizardStartParams,
WizardNextParams,
WizardCancelParams,
WizardStatusParams,
WizardStep,
WizardNextResult,
WizardStartResult,
WizardStatusResult,
TalkModeParams,
ProvidersStatusParams,
WebLoginStartParams,

View File

@@ -342,6 +342,157 @@ export const ConfigSetParamsSchema = Type.Object(
{ additionalProperties: false },
);
export const ConfigSchemaParamsSchema = Type.Object(
{},
{ additionalProperties: false },
);
export const ConfigUiHintSchema = Type.Object(
{
label: Type.Optional(Type.String()),
help: Type.Optional(Type.String()),
group: Type.Optional(Type.String()),
order: Type.Optional(Type.Integer()),
advanced: Type.Optional(Type.Boolean()),
sensitive: Type.Optional(Type.Boolean()),
placeholder: Type.Optional(Type.String()),
itemTemplate: Type.Optional(Type.Unknown()),
},
{ additionalProperties: false },
);
export const ConfigSchemaResponseSchema = Type.Object(
{
schema: Type.Unknown(),
uiHints: Type.Record(Type.String(), ConfigUiHintSchema),
version: NonEmptyString,
generatedAt: NonEmptyString,
},
{ additionalProperties: false },
);
export const WizardStartParamsSchema = Type.Object(
{
mode: Type.Optional(
Type.Union([Type.Literal("local"), Type.Literal("remote")]),
),
workspace: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardAnswerSchema = Type.Object(
{
stepId: NonEmptyString,
value: Type.Optional(Type.Unknown()),
},
{ additionalProperties: false },
);
export const WizardNextParamsSchema = Type.Object(
{
sessionId: NonEmptyString,
answer: Type.Optional(WizardAnswerSchema),
},
{ additionalProperties: false },
);
export const WizardCancelParamsSchema = Type.Object(
{
sessionId: NonEmptyString,
},
{ additionalProperties: false },
);
export const WizardStatusParamsSchema = Type.Object(
{
sessionId: NonEmptyString,
},
{ additionalProperties: false },
);
export const WizardStepOptionSchema = Type.Object(
{
value: Type.Unknown(),
label: NonEmptyString,
hint: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardStepSchema = Type.Object(
{
id: NonEmptyString,
type: Type.Union([
Type.Literal("note"),
Type.Literal("select"),
Type.Literal("text"),
Type.Literal("confirm"),
Type.Literal("multiselect"),
Type.Literal("progress"),
Type.Literal("action"),
]),
title: Type.Optional(Type.String()),
message: Type.Optional(Type.String()),
options: Type.Optional(Type.Array(WizardStepOptionSchema)),
initialValue: Type.Optional(Type.Unknown()),
placeholder: Type.Optional(Type.String()),
sensitive: Type.Optional(Type.Boolean()),
executor: Type.Optional(
Type.Union([Type.Literal("gateway"), Type.Literal("client")]),
),
},
{ additionalProperties: false },
);
export const WizardNextResultSchema = Type.Object(
{
done: Type.Boolean(),
step: Type.Optional(WizardStepSchema),
status: Type.Optional(
Type.Union([
Type.Literal("running"),
Type.Literal("done"),
Type.Literal("cancelled"),
Type.Literal("error"),
]),
),
error: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardStartResultSchema = Type.Object(
{
sessionId: NonEmptyString,
done: Type.Boolean(),
step: Type.Optional(WizardStepSchema),
status: Type.Optional(
Type.Union([
Type.Literal("running"),
Type.Literal("done"),
Type.Literal("cancelled"),
Type.Literal("error"),
]),
),
error: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardStatusResultSchema = Type.Object(
{
status: Type.Union([
Type.Literal("running"),
Type.Literal("done"),
Type.Literal("cancelled"),
Type.Literal("error"),
]),
error: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const TalkModeParamsSchema = Type.Object(
{
enabled: Type.Boolean(),
@@ -680,6 +831,16 @@ export const ProtocolSchemas: Record<string, TSchema> = {
SessionsCompactParams: SessionsCompactParamsSchema,
ConfigGetParams: ConfigGetParamsSchema,
ConfigSetParams: ConfigSetParamsSchema,
ConfigSchemaParams: ConfigSchemaParamsSchema,
ConfigSchemaResponse: ConfigSchemaResponseSchema,
WizardStartParams: WizardStartParamsSchema,
WizardNextParams: WizardNextParamsSchema,
WizardCancelParams: WizardCancelParamsSchema,
WizardStatusParams: WizardStatusParamsSchema,
WizardStep: WizardStepSchema,
WizardNextResult: WizardNextResultSchema,
WizardStartResult: WizardStartResultSchema,
WizardStatusResult: WizardStatusResultSchema,
TalkModeParams: TalkModeParamsSchema,
ProvidersStatusParams: ProvidersStatusParamsSchema,
WebLoginStartParams: WebLoginStartParamsSchema,
@@ -737,6 +898,16 @@ export type SessionsDeleteParams = Static<typeof SessionsDeleteParamsSchema>;
export type SessionsCompactParams = Static<typeof SessionsCompactParamsSchema>;
export type ConfigGetParams = Static<typeof ConfigGetParamsSchema>;
export type ConfigSetParams = Static<typeof ConfigSetParamsSchema>;
export type ConfigSchemaParams = Static<typeof ConfigSchemaParamsSchema>;
export type ConfigSchemaResponse = Static<typeof ConfigSchemaResponseSchema>;
export type WizardStartParams = Static<typeof WizardStartParamsSchema>;
export type WizardNextParams = Static<typeof WizardNextParamsSchema>;
export type WizardCancelParams = Static<typeof WizardCancelParamsSchema>;
export type WizardStatusParams = Static<typeof WizardStatusParamsSchema>;
export type WizardStep = Static<typeof WizardStepSchema>;
export type WizardNextResult = Static<typeof WizardNextResultSchema>;
export type WizardStartResult = Static<typeof WizardStartResultSchema>;
export type WizardStatusResult = Static<typeof WizardStatusResultSchema>;
export type TalkModeParams = Static<typeof TalkModeParamsSchema>;
export type ProvidersStatusParams = Static<typeof ProvidersStatusParamsSchema>;
export type WebLoginStartParams = Static<typeof WebLoginStartParamsSchema>;

View File

@@ -152,7 +152,10 @@ vi.mock("../config/sessions.js", async () => {
}),
};
});
vi.mock("../config/config.js", () => {
vi.mock("../config/config.js", async () => {
const actual = await vi.importActual<typeof import("../config/config.js")>(
"../config/config.js",
);
const resolveConfigPath = () =>
path.join(os.homedir(), ".clawdis", "clawdis.json");
@@ -222,6 +225,7 @@ vi.mock("../config/config.js", () => {
});
return {
...actual,
CONFIG_PATH_CLAWDIS: resolveConfigPath(),
STATE_DIR_CLAWDIS: path.dirname(resolveConfigPath()),
get isNixMode() {
@@ -381,7 +385,10 @@ function onceMessage<T = unknown>(
});
}
async function startServerWithClient(token?: string) {
async function startServerWithClient(
token?: string,
opts?: Parameters<typeof startGatewayServer>[1],
) {
const port = await getFreePort();
const prev = process.env.CLAWDIS_GATEWAY_TOKEN;
if (token === undefined) {
@@ -389,7 +396,7 @@ async function startServerWithClient(token?: string) {
} else {
process.env.CLAWDIS_GATEWAY_TOKEN = token;
}
const server = await startGatewayServer(port);
const server = await startGatewayServer(port, opts);
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => ws.once("open", resolve));
return { server, ws, port, prevToken: prev };
@@ -2299,6 +2306,110 @@ describe("gateway server", () => {
},
);
test("config.schema returns schema + hints", async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq<{
schema?: { properties?: { gateway?: unknown } };
uiHints?: { gateway?: { label?: string } };
}>(ws, "config.schema", {});
expect(res.ok).toBe(true);
expect(res.payload?.schema?.properties?.gateway).toBeTruthy();
expect(res.payload?.uiHints?.gateway?.label).toBe("Gateway");
ws.close();
await server.close();
});
test("wizard.start and wizard.next drive steps", async () => {
const { server, ws } = await startServerWithClient(undefined, {
wizardRunner: async (_opts, _runtime, prompter) => {
await prompter.note("Welcome");
const name = await prompter.text({ message: "Name" });
await prompter.note(`Hello ${name}`);
},
});
await connectOk(ws);
const startRes = await rpcReq<{
sessionId?: string;
step?: { id?: string; type?: string };
}>(ws, "wizard.start", {});
expect(startRes.ok).toBe(true);
const sessionId = startRes.payload?.sessionId ?? "";
const firstStep = startRes.payload?.step;
expect(sessionId).not.toBe("");
expect(firstStep?.type).toBe("note");
const runningRes = await rpcReq(ws, "wizard.start", {});
expect(runningRes.ok).toBe(false);
expect(runningRes.error?.message).toMatch(/wizard already running/i);
const nextOne = await rpcReq<{
step?: { id?: string; type?: string };
done?: boolean;
}>(ws, "wizard.next", {
sessionId,
answer: { stepId: firstStep?.id, value: null },
});
expect(nextOne.ok).toBe(true);
const textStep = nextOne.payload?.step;
expect(textStep?.type).toBe("text");
const nextTwo = await rpcReq<{
step?: { id?: string; type?: string };
done?: boolean;
}>(ws, "wizard.next", {
sessionId,
answer: { stepId: textStep?.id, value: "Peter" },
});
expect(nextTwo.ok).toBe(true);
const finalStep = nextTwo.payload?.step;
expect(finalStep?.type).toBe("note");
const done = await rpcReq<{
done?: boolean;
status?: string;
}>(ws, "wizard.next", {
sessionId,
answer: { stepId: finalStep?.id, value: null },
});
expect(done.ok).toBe(true);
expect(done.payload?.done).toBe(true);
expect(done.payload?.status).toBe("done");
ws.close();
await server.close();
});
test("wizard.cancel ends the session", async () => {
const { server, ws } = await startServerWithClient(undefined, {
wizardRunner: async (_opts, _runtime, prompter) => {
await prompter.note("Welcome");
await prompter.text({ message: "Name" });
},
});
await connectOk(ws);
const startRes = await rpcReq<{
sessionId?: string;
step?: { id?: string; type?: string };
}>(ws, "wizard.start", {});
expect(startRes.ok).toBe(true);
const sessionId = startRes.payload?.sessionId ?? "";
expect(sessionId).not.toBe("");
const cancelRes = await rpcReq<{ status?: string }>(ws, "wizard.cancel", {
sessionId,
});
expect(cancelRes.ok).toBe(true);
expect(cancelRes.payload?.status).toBe("cancelled");
ws.close();
await server.close();
});
test("providers.status returns snapshot without probe", async () => {
const prevToken = process.env.TELEGRAM_BOT_TOKEN;
delete process.env.TELEGRAM_BOT_TOKEN;

View File

@@ -62,6 +62,7 @@ import {
validateConfigObject,
writeConfigFile,
} from "../config/config.js";
import { buildConfigSchema } from "../config/schema.js";
import {
buildGroupDisplayName,
loadSessionStore,
@@ -170,6 +171,8 @@ import type { WebProviderStatus } from "../web/auto-reply.js";
import { startWebLoginWithQr, waitForWebLogin } from "../web/login-qr.js";
import { sendMessageWhatsApp } from "../web/outbound.js";
import { getWebAuthAgeMs, logoutWeb, readWebSelfId } from "../web/session.js";
import { runOnboardingWizard } from "../wizard/onboarding.js";
import { WizardSession } from "../wizard/session.js";
import {
assertGatewayAuthConfigured,
authorizeGatewayConnect,
@@ -392,6 +395,7 @@ import {
validateChatHistoryParams,
validateChatSendParams,
validateConfigGetParams,
validateConfigSchemaParams,
validateConfigSetParams,
validateConnectParams,
validateCronAddParams,
@@ -426,6 +430,10 @@ import {
validateWakeParams,
validateWebLoginStartParams,
validateWebLoginWaitParams,
validateWizardCancelParams,
validateWizardNextParams,
validateWizardStartParams,
validateWizardStatusParams,
} from "./protocol/index.js";
import { DEFAULT_WS_SLOW_MS, getGatewayWsLogStyle } from "./ws-logging.js";
@@ -504,6 +512,11 @@ const METHODS = [
"status",
"config.get",
"config.set",
"config.schema",
"wizard.start",
"wizard.next",
"wizard.cancel",
"wizard.status",
"talk.mode",
"models.list",
"skills.status",
@@ -602,6 +615,14 @@ export type GatewayServerOptions = {
* Test-only: allow canvas host startup even when NODE_ENV/VITEST would disable it.
*/
allowCanvasHostInTests?: boolean;
/**
* Test-only: override the onboarding wizard runner.
*/
wizardRunner?: (
opts: import("../commands/onboard-types.js").OnboardOptions,
runtime: import("../runtime.js").RuntimeEnv,
prompter: import("../wizard/prompts.js").WizardPrompter,
) => Promise<void>;
};
function isLoopbackAddress(ip: string | undefined): boolean {
@@ -1432,6 +1453,23 @@ export async function startGatewayServer(
);
}
const wizardRunner = opts.wizardRunner ?? runOnboardingWizard;
const wizardSessions = new Map<string, WizardSession>();
const findRunningWizard = (): string | null => {
for (const [id, session] of wizardSessions) {
if (session.getStatus() === "running") return id;
}
return null;
};
const purgeWizardSession = (id: string) => {
const session = wizardSessions.get(id);
if (!session) return;
if (session.getStatus() === "running") return;
wizardSessions.delete(id);
};
const normalizeHookHeaders = (req: IncomingMessage) => {
const headers: Record<string, string> = {};
for (const [key, value] of Object.entries(req.headers)) {
@@ -2801,6 +2839,20 @@ export async function startGatewayServer(
const snapshot = await readConfigFileSnapshot();
return { ok: true, payloadJSON: JSON.stringify(snapshot) };
}
case "config.schema": {
const params = parseParams();
if (!validateConfigSchemaParams(params)) {
return {
ok: false,
error: {
code: ErrorCodes.INVALID_REQUEST,
message: `invalid config.schema params: ${formatValidationErrors(validateConfigSchemaParams.errors)}`,
},
};
}
const schema = buildConfigSchema();
return { ok: true, payloadJSON: JSON.stringify(schema) };
}
case "config.set": {
const params = parseParams();
if (!validateConfigSetParams(params)) {
@@ -5306,6 +5358,23 @@ export async function startGatewayServer(
respond(true, snapshot, undefined);
break;
}
case "config.schema": {
const params = (req.params ?? {}) as Record<string, unknown>;
if (!validateConfigSchemaParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid config.schema params: ${formatValidationErrors(validateConfigSchemaParams.errors)}`,
),
);
break;
}
const schema = buildConfigSchema();
respond(true, schema, undefined);
break;
}
case "config.set": {
const params = (req.params ?? {}) as Record<string, unknown>;
if (!validateConfigSetParams(params)) {
@@ -5363,6 +5432,171 @@ export async function startGatewayServer(
);
break;
}
case "wizard.start": {
const params = (req.params ?? {}) as Record<string, unknown>;
if (!validateWizardStartParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid wizard.start params: ${formatValidationErrors(validateWizardStartParams.errors)}`,
),
);
break;
}
const running = findRunningWizard();
if (running) {
respond(
false,
undefined,
errorShape(ErrorCodes.UNAVAILABLE, "wizard already running"),
);
break;
}
const sessionId = randomUUID();
const opts = {
mode: params.mode as "local" | "remote" | undefined,
workspace:
typeof params.workspace === "string"
? params.workspace
: undefined,
};
const session = new WizardSession((prompter) =>
wizardRunner(opts, defaultRuntime, prompter),
);
wizardSessions.set(sessionId, session);
const result = await session.next();
if (result.done) {
purgeWizardSession(sessionId);
}
respond(true, { sessionId, ...result }, undefined);
break;
}
case "wizard.next": {
const params = (req.params ?? {}) as Record<string, unknown>;
if (!validateWizardNextParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid wizard.next params: ${formatValidationErrors(validateWizardNextParams.errors)}`,
),
);
break;
}
const sessionId = params.sessionId as string;
const session = wizardSessions.get(sessionId);
if (!session) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "wizard not found"),
);
break;
}
const answer = params.answer as
| { stepId?: string; value?: unknown }
| undefined;
if (answer) {
if (session.getStatus() !== "running") {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
"wizard not running",
),
);
break;
}
try {
await session.answer(
String(answer.stepId ?? ""),
answer.value,
);
} catch (err) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(err)),
);
break;
}
}
const result = await session.next();
if (result.done) {
purgeWizardSession(sessionId);
}
respond(true, result, undefined);
break;
}
case "wizard.cancel": {
const params = (req.params ?? {}) as Record<string, unknown>;
if (!validateWizardCancelParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid wizard.cancel params: ${formatValidationErrors(validateWizardCancelParams.errors)}`,
),
);
break;
}
const sessionId = params.sessionId as string;
const session = wizardSessions.get(sessionId);
if (!session) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "wizard not found"),
);
break;
}
session.cancel();
const status = {
status: session.getStatus(),
error: session.getError(),
};
wizardSessions.delete(sessionId);
respond(true, status, undefined);
break;
}
case "wizard.status": {
const params = (req.params ?? {}) as Record<string, unknown>;
if (!validateWizardStatusParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid wizard.status params: ${formatValidationErrors(validateWizardStatusParams.errors)}`,
),
);
break;
}
const sessionId = params.sessionId as string;
const session = wizardSessions.get(sessionId);
if (!session) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "wizard not found"),
);
break;
}
const status = {
status: session.getStatus(),
error: session.getError(),
};
if (status.status !== "running") {
wizardSessions.delete(sessionId);
}
respond(true, status, undefined);
break;
}
case "talk.mode": {
if (
client &&

View File

@@ -0,0 +1,84 @@
import {
cancel,
confirm,
intro,
isCancel,
multiselect,
note,
type Option,
outro,
select,
spinner,
text,
} from "@clack/prompts";
import type { WizardProgress, WizardPrompter } from "./prompts.js";
import { WizardCancelledError } from "./prompts.js";
function guardCancel<T>(value: T | symbol): T {
if (isCancel(value)) {
cancel("Setup cancelled.");
throw new WizardCancelledError();
}
return value as T;
}
export function createClackPrompter(): WizardPrompter {
return {
intro: async (title) => {
intro(title);
},
outro: async (message) => {
outro(message);
},
note: async (message, title) => {
note(message, title);
},
select: async (params) =>
guardCancel(
await select({
message: params.message,
options: params.options.map((opt) => {
const base = { value: opt.value, label: opt.label };
return opt.hint === undefined ? base : { ...base, hint: opt.hint };
}) as Option<(typeof params.options)[number]["value"]>[],
initialValue: params.initialValue,
}),
),
multiselect: async (params) =>
guardCancel(
await multiselect({
message: params.message,
options: params.options.map((opt) => {
const base = { value: opt.value, label: opt.label };
return opt.hint === undefined ? base : { ...base, hint: opt.hint };
}) as Option<(typeof params.options)[number]["value"]>[],
initialValues: params.initialValues,
}),
),
text: async (params) =>
guardCancel(
await text({
message: params.message,
initialValue: params.initialValue,
placeholder: params.placeholder,
validate: params.validate,
}),
),
confirm: async (params) =>
guardCancel(
await confirm({
message: params.message,
initialValue: params.initialValue,
}),
),
progress: (label: string): WizardProgress => {
const spin = spinner();
spin.start(label);
return {
update: (message) => spin.message(message),
stop: (message) => spin.stop(message),
};
},
};
}

535
src/wizard/onboarding.ts Normal file
View File

@@ -0,0 +1,535 @@
import path from "node:path";
import { loginAnthropic, type OAuthCredentials } from "@mariozechner/pi-ai";
import {
isRemoteEnvironment,
loginAntigravityVpsAware,
} from "../commands/antigravity-oauth.js";
import { healthCommand } from "../commands/health.js";
import {
applyMinimaxConfig,
setAnthropicApiKey,
writeOAuthCredentials,
} from "../commands/onboard-auth.js";
import {
applyWizardMetadata,
DEFAULT_WORKSPACE,
ensureWorkspaceAndSessions,
handleReset,
openUrl,
printWizardHeader,
probeGatewayReachable,
randomToken,
resolveControlUiLinks,
summarizeExistingConfig,
} from "../commands/onboard-helpers.js";
import { setupProviders } from "../commands/onboard-providers.js";
import { promptRemoteGatewayConfig } from "../commands/onboard-remote.js";
import { setupSkills } from "../commands/onboard-skills.js";
import type {
AuthChoice,
GatewayAuthChoice,
OnboardMode,
OnboardOptions,
ResetScope,
} from "../commands/onboard-types.js";
import type { ClawdisConfig } from "../config/config.js";
import {
CONFIG_PATH_CLAWDIS,
readConfigFileSnapshot,
resolveGatewayPort,
writeConfigFile,
} from "../config/config.js";
import { GATEWAY_LAUNCH_AGENT_LABEL } from "../daemon/constants.js";
import { resolveGatewayProgramArguments } from "../daemon/program-args.js";
import { resolveGatewayService } from "../daemon/service.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { resolveUserPath, sleep } from "../utils.js";
import type { WizardPrompter } from "./prompts.js";
export async function runOnboardingWizard(
opts: OnboardOptions,
runtime: RuntimeEnv = defaultRuntime,
prompter: WizardPrompter,
) {
printWizardHeader(runtime);
await prompter.intro("Clawdis onboarding");
const snapshot = await readConfigFileSnapshot();
let baseConfig: ClawdisConfig = snapshot.valid ? snapshot.config : {};
if (snapshot.exists) {
const title = snapshot.valid
? "Existing config detected"
: "Invalid config";
await prompter.note(summarizeExistingConfig(baseConfig), title);
if (!snapshot.valid && snapshot.issues.length > 0) {
await prompter.note(
snapshot.issues
.map((iss) => `- ${iss.path}: ${iss.message}`)
.join("\n"),
"Config issues",
);
}
const action = (await prompter.select({
message: "Config handling",
options: [
{ value: "keep", label: "Use existing values" },
{ value: "modify", label: "Update values" },
{ value: "reset", label: "Reset" },
],
})) as "keep" | "modify" | "reset";
if (action === "reset") {
const workspaceDefault = baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE;
const resetScope = (await prompter.select({
message: "Reset scope",
options: [
{ value: "config", label: "Config only" },
{
value: "config+creds+sessions",
label: "Config + creds + sessions",
},
{
value: "full",
label: "Full reset (config + creds + sessions + workspace)",
},
],
})) as ResetScope;
await handleReset(resetScope, resolveUserPath(workspaceDefault), runtime);
baseConfig = {};
} else if (action === "keep" && !snapshot.valid) {
baseConfig = {};
}
}
const localPort = resolveGatewayPort(baseConfig);
const localUrl = `ws://127.0.0.1:${localPort}`;
const localProbe = await probeGatewayReachable({
url: localUrl,
token: process.env.CLAWDIS_GATEWAY_TOKEN,
password:
baseConfig.gateway?.auth?.password ??
process.env.CLAWDIS_GATEWAY_PASSWORD,
});
const remoteUrl = baseConfig.gateway?.remote?.url?.trim() ?? "";
const remoteProbe = remoteUrl
? await probeGatewayReachable({
url: remoteUrl,
token: baseConfig.gateway?.remote?.token,
})
: null;
const mode =
opts.mode ??
((await prompter.select({
message: "Where will the Gateway run?",
options: [
{
value: "local",
label: "Local (this machine)",
hint: localProbe.ok
? `Gateway reachable (${localUrl})`
: `No gateway detected (${localUrl})`,
},
{
value: "remote",
label: "Remote (info-only)",
hint: !remoteUrl
? "No remote URL configured yet"
: remoteProbe?.ok
? `Gateway reachable (${remoteUrl})`
: `Configured but unreachable (${remoteUrl})`,
},
],
})) as OnboardMode);
if (mode === "remote") {
let nextConfig = await promptRemoteGatewayConfig(baseConfig, prompter);
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
await writeConfigFile(nextConfig);
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
await prompter.outro("Remote gateway configured.");
return;
}
const workspaceInput =
opts.workspace ??
(await prompter.text({
message: "Workspace directory",
initialValue: baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE,
}));
const workspaceDir = resolveUserPath(
workspaceInput.trim() || DEFAULT_WORKSPACE,
);
let nextConfig: ClawdisConfig = {
...baseConfig,
agent: {
...baseConfig.agent,
workspace: workspaceDir,
},
gateway: {
...baseConfig.gateway,
mode: "local",
},
};
const authChoice = (await prompter.select({
message: "Model/auth choice",
options: [
{ value: "oauth", label: "Anthropic OAuth (Claude Pro/Max)" },
{
value: "antigravity",
label: "Google Antigravity (Claude Opus 4.5, Gemini 3, etc.)",
},
{ value: "apiKey", label: "Anthropic API key" },
{ value: "minimax", label: "Minimax M2.1 (LM Studio)" },
{ value: "skip", label: "Skip for now" },
],
})) as AuthChoice;
if (authChoice === "oauth") {
await prompter.note(
"Browser will open. Paste the code shown after login (code#state).",
"Anthropic OAuth",
);
const spin = prompter.progress("Waiting for authorization…");
let oauthCreds: OAuthCredentials | null = null;
try {
oauthCreds = await loginAnthropic(
async (url) => {
await openUrl(url);
runtime.log(`Open: ${url}`);
},
async () => {
const code = await prompter.text({
message: "Paste authorization code (code#state)",
validate: (value) => (value?.trim() ? undefined : "Required"),
});
return String(code);
},
);
spin.stop("OAuth complete");
if (oauthCreds) {
await writeOAuthCredentials("anthropic", oauthCreds);
}
} catch (err) {
spin.stop("OAuth failed");
runtime.error(String(err));
}
} else if (authChoice === "antigravity") {
const isRemote = isRemoteEnvironment();
await prompter.note(
isRemote
? [
"You are running in a remote/VPS environment.",
"A URL will be shown for you to open in your LOCAL browser.",
"After signing in, copy the redirect URL and paste it back here.",
].join("\n")
: [
"Browser will open for Google authentication.",
"Sign in with your Google account that has Antigravity access.",
"The callback will be captured automatically on localhost:51121.",
].join("\n"),
"Google Antigravity OAuth",
);
const spin = prompter.progress("Starting OAuth flow…");
let oauthCreds: OAuthCredentials | null = null;
try {
oauthCreds = await loginAntigravityVpsAware(
async (url) => {
if (isRemote) {
spin.stop("OAuth URL ready");
runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${url}\n`);
} else {
spin.update("Complete sign-in in browser…");
await openUrl(url);
runtime.log(`Open: ${url}`);
}
},
(msg) => spin.update(msg),
);
spin.stop("Antigravity OAuth complete");
if (oauthCreds) {
await writeOAuthCredentials("google-antigravity", oauthCreds);
nextConfig = {
...nextConfig,
agent: {
...nextConfig.agent,
model: "google-antigravity/claude-opus-4-5-thinking",
},
};
await prompter.note(
"Default model set to google-antigravity/claude-opus-4-5-thinking",
"Model configured",
);
}
} catch (err) {
spin.stop("Antigravity OAuth failed");
runtime.error(String(err));
}
} else if (authChoice === "apiKey") {
const key = await prompter.text({
message: "Enter Anthropic API key",
validate: (value) => (value?.trim() ? undefined : "Required"),
});
await setAnthropicApiKey(String(key).trim());
} else if (authChoice === "minimax") {
nextConfig = applyMinimaxConfig(nextConfig);
}
const portRaw = await prompter.text({
message: "Gateway port",
initialValue: String(localPort),
validate: (value) =>
Number.isFinite(Number(value)) ? undefined : "Invalid port",
});
const port = Number.parseInt(String(portRaw), 10);
let bind = (await prompter.select({
message: "Gateway bind",
options: [
{ value: "loopback", label: "Loopback (127.0.0.1)" },
{ value: "lan", label: "LAN" },
{ value: "tailnet", label: "Tailnet" },
{ value: "auto", label: "Auto" },
],
})) as "loopback" | "lan" | "tailnet" | "auto";
let authMode = (await prompter.select({
message: "Gateway auth",
options: [
{
value: "off",
label: "Off (loopback only)",
hint: "Recommended for single-machine setups",
},
{
value: "token",
label: "Token",
hint: "Use for multi-machine access or non-loopback binds",
},
{ value: "password", label: "Password" },
],
})) as GatewayAuthChoice;
const tailscaleMode = (await prompter.select({
message: "Tailscale exposure",
options: [
{ value: "off", label: "Off", hint: "No Tailscale exposure" },
{
value: "serve",
label: "Serve",
hint: "Private HTTPS for your tailnet (devices on Tailscale)",
},
{
value: "funnel",
label: "Funnel",
hint: "Public HTTPS via Tailscale Funnel (internet)",
},
],
})) as "off" | "serve" | "funnel";
let tailscaleResetOnExit = false;
if (tailscaleMode !== "off") {
tailscaleResetOnExit = Boolean(
await prompter.confirm({
message: "Reset Tailscale serve/funnel on exit?",
initialValue: false,
}),
);
}
if (tailscaleMode !== "off" && bind !== "loopback") {
await prompter.note(
"Tailscale requires bind=loopback. Adjusting bind to loopback.",
"Note",
);
bind = "loopback";
}
if (authMode === "off" && bind !== "loopback") {
await prompter.note(
"Non-loopback bind requires auth. Switching to token auth.",
"Note",
);
authMode = "token";
}
if (tailscaleMode === "funnel" && authMode !== "password") {
await prompter.note("Tailscale funnel requires password auth.", "Note");
authMode = "password";
}
let gatewayToken: string | undefined;
if (authMode === "token") {
const tokenInput = await prompter.text({
message: "Gateway token (blank to generate)",
placeholder: "Needed for multi-machine or non-loopback access",
initialValue: randomToken(),
});
gatewayToken = String(tokenInput).trim() || randomToken();
}
if (authMode === "password") {
const password = await prompter.text({
message: "Gateway password",
validate: (value) => (value?.trim() ? undefined : "Required"),
});
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
auth: {
...nextConfig.gateway?.auth,
mode: "password",
password: String(password).trim(),
},
},
};
} else if (authMode === "token") {
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
auth: {
...nextConfig.gateway?.auth,
mode: "token",
token: gatewayToken,
},
},
};
}
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
port,
bind,
tailscale: {
...nextConfig.gateway?.tailscale,
mode: tailscaleMode,
resetOnExit: tailscaleResetOnExit,
},
},
};
nextConfig = await setupProviders(nextConfig, runtime, prompter, {
allowSignalInstall: true,
});
await writeConfigFile(nextConfig);
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
await ensureWorkspaceAndSessions(workspaceDir, runtime);
nextConfig = await setupSkills(nextConfig, workspaceDir, runtime, prompter);
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
await writeConfigFile(nextConfig);
const installDaemon = await prompter.confirm({
message: "Install Gateway daemon (recommended)",
initialValue: true,
});
if (installDaemon) {
const service = resolveGatewayService();
const loaded = await service.isLoaded({ env: process.env });
if (loaded) {
const action = (await prompter.select({
message: "Gateway service already installed",
options: [
{ value: "restart", label: "Restart" },
{ value: "reinstall", label: "Reinstall" },
{ value: "skip", label: "Skip" },
],
})) as "restart" | "reinstall" | "skip";
if (action === "restart") {
await service.restart({ stdout: process.stdout });
} else if (action === "reinstall") {
await service.uninstall({ env: process.env, stdout: process.stdout });
}
}
if (
!loaded ||
(loaded && (await service.isLoaded({ env: process.env })) === false)
) {
const devMode =
process.argv[1]?.includes(`${path.sep}src${path.sep}`) &&
process.argv[1]?.endsWith(".ts");
const { programArguments, workingDirectory } =
await resolveGatewayProgramArguments({ port, dev: devMode });
const environment: Record<string, string | undefined> = {
PATH: process.env.PATH,
CLAWDIS_GATEWAY_TOKEN: gatewayToken,
CLAWDIS_LAUNCHD_LABEL:
process.platform === "darwin"
? GATEWAY_LAUNCH_AGENT_LABEL
: undefined,
};
await service.install({
env: process.env,
stdout: process.stdout,
programArguments,
workingDirectory,
environment,
});
}
}
await sleep(1500);
try {
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
} catch (err) {
runtime.error(`Health check failed: ${String(err)}`);
}
await prompter.note(
[
"Add nodes for extra features:",
"- macOS app (system + notifications)",
"- iOS app (camera/canvas)",
"- Android app (camera/canvas)",
].join("\n"),
"Optional apps",
);
await prompter.note(
(() => {
const links = resolveControlUiLinks({ bind, port });
const tokenParam =
authMode === "token" && gatewayToken
? `?token=${encodeURIComponent(gatewayToken)}`
: "";
const authedUrl = `${links.httpUrl}${tokenParam}`;
return [
`Web UI: ${links.httpUrl}`,
tokenParam ? `Web UI (with token): ${authedUrl}` : undefined,
`Gateway WS: ${links.wsUrl}`,
]
.filter(Boolean)
.join("\n");
})(),
"Control UI",
);
const wantsOpen = await prompter.confirm({
message: "Open Control UI now?",
initialValue: true,
});
if (wantsOpen) {
const links = resolveControlUiLinks({ bind, port });
const tokenParam =
authMode === "token" && gatewayToken
? `?token=${encodeURIComponent(gatewayToken)}`
: "";
await openUrl(`${links.httpUrl}${tokenParam}`);
}
await prompter.outro("Onboarding complete.");
}

52
src/wizard/prompts.ts Normal file
View File

@@ -0,0 +1,52 @@
export type WizardSelectOption<T = string> = {
value: T;
label: string;
hint?: string;
};
export type WizardSelectParams<T = string> = {
message: string;
options: Array<WizardSelectOption<T>>;
initialValue?: T;
};
export type WizardMultiSelectParams<T = string> = {
message: string;
options: Array<WizardSelectOption<T>>;
initialValues?: T[];
};
export type WizardTextParams = {
message: string;
initialValue?: string;
placeholder?: string;
validate?: (value: string) => string | undefined;
};
export type WizardConfirmParams = {
message: string;
initialValue?: boolean;
};
export type WizardProgress = {
update: (message: string) => void;
stop: (message?: string) => void;
};
export type WizardPrompter = {
intro: (title: string) => Promise<void>;
outro: (message: string) => Promise<void>;
note: (message: string, title?: string) => Promise<void>;
select: <T>(params: WizardSelectParams<T>) => Promise<T>;
multiselect: <T>(params: WizardMultiSelectParams<T>) => Promise<T[]>;
text: (params: WizardTextParams) => Promise<string>;
confirm: (params: WizardConfirmParams) => Promise<boolean>;
progress: (label: string) => WizardProgress;
};
export class WizardCancelledError extends Error {
constructor(message = "wizard cancelled") {
super(message);
this.name = "WizardCancelledError";
}
}

View File

@@ -0,0 +1,69 @@
import { describe, expect, test } from "vitest";
import { WizardSession } from "./session.js";
function noteRunner() {
return new WizardSession(async (prompter) => {
await prompter.note("Welcome");
const name = await prompter.text({ message: "Name" });
await prompter.note(`Hello ${name}`);
});
}
describe("WizardSession", () => {
test("steps progress in order", async () => {
const session = noteRunner();
const first = await session.next();
expect(first.done).toBe(false);
expect(first.step?.type).toBe("note");
const secondPeek = await session.next();
expect(secondPeek.step?.id).toBe(first.step?.id);
if (!first.step) throw new Error("expected first step");
await session.answer(first.step.id, null);
const second = await session.next();
expect(second.done).toBe(false);
expect(second.step?.type).toBe("text");
if (!second.step) throw new Error("expected second step");
await session.answer(second.step.id, "Peter");
const third = await session.next();
expect(third.step?.type).toBe("note");
if (!third.step) throw new Error("expected third step");
await session.answer(third.step.id, null);
const done = await session.next();
expect(done.done).toBe(true);
expect(done.status).toBe("done");
});
test("invalid answers throw", async () => {
const session = noteRunner();
const first = await session.next();
await expect(session.answer("bad-id", null)).rejects.toThrow(
/wizard: no pending step/i,
);
if (!first.step) throw new Error("expected first step");
await session.answer(first.step.id, null);
});
test("cancel marks session and unblocks", async () => {
const session = new WizardSession(async (prompter) => {
await prompter.text({ message: "Name" });
});
const step = await session.next();
expect(step.step?.type).toBe("text");
session.cancel();
const done = await session.next();
expect(done.done).toBe(true);
expect(done.status).toBe("cancelled");
});
});

268
src/wizard/session.ts Normal file
View File

@@ -0,0 +1,268 @@
import { randomUUID } from "node:crypto";
import {
WizardCancelledError,
type WizardProgress,
type WizardPrompter,
} from "./prompts.js";
export type WizardStepOption = {
value: unknown;
label: string;
hint?: string;
};
export type WizardStep = {
id: string;
type:
| "note"
| "select"
| "text"
| "confirm"
| "multiselect"
| "progress"
| "action";
title?: string;
message?: string;
options?: WizardStepOption[];
initialValue?: unknown;
placeholder?: string;
sensitive?: boolean;
executor?: "gateway" | "client";
};
export type WizardSessionStatus = "running" | "done" | "cancelled" | "error";
export type WizardNextResult = {
done: boolean;
step?: WizardStep;
status: WizardSessionStatus;
error?: string;
};
type Deferred<T> = {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (err: unknown) => void;
};
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (err: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
class WizardSessionPrompter implements WizardPrompter {
constructor(private session: WizardSession) {}
async intro(title: string): Promise<void> {
await this.prompt({
type: "note",
title,
message: "",
executor: "client",
});
}
async outro(message: string): Promise<void> {
await this.prompt({
type: "note",
title: "Done",
message,
executor: "client",
});
}
async note(message: string, title?: string): Promise<void> {
await this.prompt({ type: "note", title, message, executor: "client" });
}
async select<T>(params: {
message: string;
options: Array<{ value: T; label: string; hint?: string }>;
initialValue?: T;
}): Promise<T> {
const res = await this.prompt({
type: "select",
message: params.message,
options: params.options.map((opt) => ({
value: opt.value,
label: opt.label,
hint: opt.hint,
})),
initialValue: params.initialValue,
executor: "client",
});
return res as T;
}
async multiselect<T>(params: {
message: string;
options: Array<{ value: T; label: string; hint?: string }>;
initialValues?: T[];
}): Promise<T[]> {
const res = await this.prompt({
type: "multiselect",
message: params.message,
options: params.options.map((opt) => ({
value: opt.value,
label: opt.label,
hint: opt.hint,
})),
initialValue: params.initialValues,
executor: "client",
});
return (Array.isArray(res) ? res : []) as T[];
}
async text(params: {
message: string;
initialValue?: string;
placeholder?: string;
validate?: (value: string) => string | undefined;
}): Promise<string> {
const res = await this.prompt({
type: "text",
message: params.message,
initialValue: params.initialValue,
placeholder: params.placeholder,
executor: "client",
});
const value = String(res ?? "");
const error = params.validate?.(value);
if (error) {
throw new Error(error);
}
return value;
}
async confirm(params: {
message: string;
initialValue?: boolean;
}): Promise<boolean> {
const res = await this.prompt({
type: "confirm",
message: params.message,
initialValue: params.initialValue,
executor: "client",
});
return Boolean(res);
}
progress(_label: string): WizardProgress {
return {
update: (_message) => {},
stop: (_message) => {},
};
}
private async prompt(step: Omit<WizardStep, "id">): Promise<unknown> {
return await this.session.awaitAnswer({
...step,
id: randomUUID(),
});
}
}
export class WizardSession {
private currentStep: WizardStep | null = null;
private stepDeferred: Deferred<WizardStep | null> | null = null;
private answerDeferred = new Map<string, Deferred<unknown>>();
private status: WizardSessionStatus = "running";
private error: string | undefined;
constructor(private runner: (prompter: WizardPrompter) => Promise<void>) {
const prompter = new WizardSessionPrompter(this);
void this.run(prompter);
}
async next(): Promise<WizardNextResult> {
if (this.currentStep) {
return { done: false, step: this.currentStep, status: this.status };
}
if (this.status !== "running") {
return { done: true, status: this.status, error: this.error };
}
if (!this.stepDeferred) {
this.stepDeferred = createDeferred();
}
const step = await this.stepDeferred.promise;
if (step) {
return { done: false, step, status: this.status };
}
return { done: true, status: this.status, error: this.error };
}
async answer(stepId: string, value: unknown): Promise<void> {
const deferred = this.answerDeferred.get(stepId);
if (!deferred) {
throw new Error("wizard: no pending step");
}
this.answerDeferred.delete(stepId);
this.currentStep = null;
deferred.resolve(value);
}
cancel() {
if (this.status !== "running") return;
this.status = "cancelled";
this.error = "cancelled";
this.currentStep = null;
for (const [, deferred] of this.answerDeferred) {
deferred.reject(new WizardCancelledError());
}
this.answerDeferred.clear();
this.resolveStep(null);
}
pushStep(step: WizardStep) {
this.currentStep = step;
this.resolveStep(step);
}
private async run(prompter: WizardPrompter) {
try {
await this.runner(prompter);
this.status = "done";
} catch (err) {
if (err instanceof WizardCancelledError) {
this.status = "cancelled";
this.error = err.message;
} else {
this.status = "error";
this.error = String(err);
}
} finally {
this.resolveStep(null);
}
}
async awaitAnswer(step: WizardStep): Promise<unknown> {
if (this.status !== "running") {
throw new Error("wizard: session not running");
}
this.pushStep(step);
const deferred = createDeferred<unknown>();
this.answerDeferred.set(step.id, deferred);
return await deferred.promise;
}
private resolveStep(step: WizardStep | null) {
if (!this.stepDeferred) return;
const deferred = this.stepDeferred;
this.stepDeferred = null;
deferred.resolve(step);
}
getStatus(): WizardSessionStatus {
return this.status;
}
getError(): string | undefined {
return this.error;
}
}