feat: expand wizard setup flow
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
import chalk from "chalk";
|
||||
import { Command } from "commander";
|
||||
import { agentCommand } from "../commands/agent.js";
|
||||
import { configureCommand } from "../commands/configure.js";
|
||||
import { doctorCommand } from "../commands/doctor.js";
|
||||
import { healthCommand } from "../commands/health.js";
|
||||
import { onboardCommand } from "../commands/onboard.js";
|
||||
import { sendCommand } from "../commands/send.js";
|
||||
import { sessionsCommand } from "../commands/sessions.js";
|
||||
import { setupCommand } from "../commands/setup.js";
|
||||
import { statusCommand } from "../commands/status.js";
|
||||
import { updateCommand } from "../commands/update.js";
|
||||
import { danger, setVerbose } from "../globals.js";
|
||||
import { loginWeb, logoutWeb } from "../provider-web.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
@@ -201,6 +204,44 @@ export function buildProgram() {
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("configure")
|
||||
.description(
|
||||
"Interactive wizard to update models, providers, skills, and gateway",
|
||||
)
|
||||
.action(async () => {
|
||||
try {
|
||||
await configureCommand(defaultRuntime);
|
||||
} catch (err) {
|
||||
defaultRuntime.error(String(err));
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("doctor")
|
||||
.description("Health checks + quick fixes for the gateway and providers")
|
||||
.action(async () => {
|
||||
try {
|
||||
await doctorCommand(defaultRuntime);
|
||||
} catch (err) {
|
||||
defaultRuntime.error(String(err));
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("update")
|
||||
.description("Audit and modernize the local configuration")
|
||||
.action(async () => {
|
||||
try {
|
||||
await updateCommand(defaultRuntime);
|
||||
} catch (err) {
|
||||
defaultRuntime.error(String(err));
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("login")
|
||||
.description("Link your personal WhatsApp via QR (web provider)")
|
||||
|
||||
521
src/commands/configure.ts
Normal file
521
src/commands/configure.ts
Normal file
@@ -0,0 +1,521 @@
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
confirm,
|
||||
intro,
|
||||
multiselect,
|
||||
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,
|
||||
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 { healthCommand } from "./health.js";
|
||||
import {
|
||||
applyMinimaxConfig,
|
||||
setAnthropicApiKey,
|
||||
writeOAuthCredentials,
|
||||
} from "./onboard-auth.js";
|
||||
import {
|
||||
applyWizardMetadata,
|
||||
DEFAULT_WORKSPACE,
|
||||
ensureWorkspaceAndSessions,
|
||||
guardCancel,
|
||||
openUrl,
|
||||
printWizardHeader,
|
||||
randomToken,
|
||||
summarizeExistingConfig,
|
||||
} from "./onboard-helpers.js";
|
||||
import { setupProviders } from "./onboard-providers.js";
|
||||
import { setupSkills } from "./onboard-skills.js";
|
||||
|
||||
type WizardSection =
|
||||
| "model"
|
||||
| "providers"
|
||||
| "gateway"
|
||||
| "daemon"
|
||||
| "workspace"
|
||||
| "skills"
|
||||
| "health";
|
||||
|
||||
type ConfigureWizardParams = {
|
||||
command: "configure" | "update";
|
||||
sections?: WizardSection[];
|
||||
};
|
||||
|
||||
async function promptGatewayConfig(
|
||||
cfg: ClawdisConfig,
|
||||
runtime: RuntimeEnv,
|
||||
): Promise<{
|
||||
config: ClawdisConfig;
|
||||
port: number;
|
||||
token?: string;
|
||||
}> {
|
||||
const portRaw = guardCancel(
|
||||
await text({
|
||||
message: "Gateway port",
|
||||
initialValue: "18789",
|
||||
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)" },
|
||||
{ value: "token", label: "Token" },
|
||||
{ value: "password", label: "Password" },
|
||||
],
|
||||
}),
|
||||
runtime,
|
||||
) as "off" | "token" | "password";
|
||||
|
||||
const tailscaleMode = guardCancel(
|
||||
await select({
|
||||
message: "Tailscale exposure",
|
||||
options: [
|
||||
{ value: "off", label: "Off" },
|
||||
{ value: "serve", label: "Serve" },
|
||||
{ value: "funnel", label: "Funnel" },
|
||||
],
|
||||
}),
|
||||
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;
|
||||
let next = cfg;
|
||||
|
||||
if (authMode === "token") {
|
||||
const tokenInput = guardCancel(
|
||||
await text({
|
||||
message: "Gateway token (blank to generate)",
|
||||
initialValue: randomToken(),
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
gatewayToken = String(tokenInput).trim() || randomToken();
|
||||
next = {
|
||||
...next,
|
||||
gateway: {
|
||||
...next.gateway,
|
||||
auth: { ...next.gateway?.auth, mode: "token" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (authMode === "password") {
|
||||
const password = guardCancel(
|
||||
await text({
|
||||
message: "Gateway password",
|
||||
validate: (value) => (value?.trim() ? undefined : "Required"),
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
next = {
|
||||
...next,
|
||||
gateway: {
|
||||
...next.gateway,
|
||||
auth: {
|
||||
...next.gateway?.auth,
|
||||
mode: "password",
|
||||
password: String(password).trim(),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
next = {
|
||||
...next,
|
||||
gateway: {
|
||||
...next.gateway,
|
||||
mode: "local",
|
||||
bind,
|
||||
tailscale: {
|
||||
...next.gateway?.tailscale,
|
||||
mode: tailscaleMode,
|
||||
resetOnExit: tailscaleResetOnExit,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return { config: next, port, token: gatewayToken };
|
||||
}
|
||||
|
||||
async function promptAuthConfig(
|
||||
cfg: ClawdisConfig,
|
||||
runtime: RuntimeEnv,
|
||||
): Promise<ClawdisConfig> {
|
||||
const authChoice = guardCancel(
|
||||
await select({
|
||||
message: "Model/auth choice",
|
||||
options: [
|
||||
{ value: "oauth", label: "Anthropic OAuth (Claude Pro/Max)" },
|
||||
{ value: "apiKey", label: "Anthropic API key" },
|
||||
{ value: "minimax", label: "Minimax M2.1 (LM Studio)" },
|
||||
{ value: "skip", label: "Skip for now" },
|
||||
],
|
||||
}),
|
||||
runtime,
|
||||
) as "oauth" | "apiKey" | "minimax" | "skip";
|
||||
|
||||
let next = cfg;
|
||||
|
||||
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 === "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") {
|
||||
next = applyMinimaxConfig(next);
|
||||
}
|
||||
|
||||
const modelInput = guardCancel(
|
||||
await text({
|
||||
message: "Default model (blank to keep)",
|
||||
initialValue: next.agent?.model ?? "",
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
const model = String(modelInput ?? "").trim();
|
||||
if (model) {
|
||||
next = {
|
||||
...next,
|
||||
agent: {
|
||||
...next.agent,
|
||||
model,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
async function maybeInstallDaemon(params: {
|
||||
runtime: RuntimeEnv;
|
||||
port: number;
|
||||
gatewayToken?: string;
|
||||
}) {
|
||||
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" },
|
||||
],
|
||||
}),
|
||||
params.runtime,
|
||||
);
|
||||
if (action === "restart") {
|
||||
await service.restart({ stdout: process.stdout });
|
||||
return;
|
||||
}
|
||||
if (action === "skip") return;
|
||||
if (action === "reinstall") {
|
||||
await service.uninstall({ env: process.env, stdout: process.stdout });
|
||||
}
|
||||
}
|
||||
|
||||
const devMode =
|
||||
process.argv[1]?.includes(`${path.sep}src${path.sep}`) &&
|
||||
process.argv[1]?.endsWith(".ts");
|
||||
const { programArguments, workingDirectory } =
|
||||
await resolveGatewayProgramArguments({ port: params.port, dev: devMode });
|
||||
const environment: Record<string, string | undefined> = {
|
||||
PATH: process.env.PATH,
|
||||
CLAWDIS_GATEWAY_TOKEN: params.gatewayToken,
|
||||
CLAWDIS_LAUNCHD_LABEL:
|
||||
process.platform === "darwin" ? GATEWAY_LAUNCH_AGENT_LABEL : undefined,
|
||||
};
|
||||
await service.install({
|
||||
env: process.env,
|
||||
stdout: process.stdout,
|
||||
programArguments,
|
||||
workingDirectory,
|
||||
environment,
|
||||
});
|
||||
}
|
||||
|
||||
export async function runConfigureWizard(
|
||||
opts: ConfigureWizardParams,
|
||||
runtime: RuntimeEnv = defaultRuntime,
|
||||
) {
|
||||
printWizardHeader(runtime);
|
||||
intro(
|
||||
opts.command === "update" ? "Clawdis update wizard" : "Clawdis configure",
|
||||
);
|
||||
|
||||
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",
|
||||
);
|
||||
}
|
||||
if (!snapshot.valid) {
|
||||
const reset = guardCancel(
|
||||
await confirm({
|
||||
message: "Config invalid. Start fresh?",
|
||||
initialValue: true,
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
if (reset) baseConfig = {};
|
||||
}
|
||||
}
|
||||
|
||||
const mode = guardCancel(
|
||||
await select({
|
||||
message: "Where will the Gateway run?",
|
||||
options: [
|
||||
{ value: "local", label: "Local (this machine)" },
|
||||
{ value: "remote", label: "Remote (info-only)" },
|
||||
],
|
||||
}),
|
||||
runtime,
|
||||
) as "local" | "remote";
|
||||
|
||||
if (mode === "remote") {
|
||||
note(
|
||||
[
|
||||
"Run on the gateway host:",
|
||||
"- clawdis setup",
|
||||
"- clawdis gateway-daemon --port 18789",
|
||||
"- OAuth creds: ~/.clawdis/credentials/oauth.json",
|
||||
"- Workspace: ~/clawd",
|
||||
].join("\n"),
|
||||
"Remote setup",
|
||||
);
|
||||
outro("Done. Local config unchanged.");
|
||||
return;
|
||||
}
|
||||
|
||||
const selected = opts.sections
|
||||
? opts.sections
|
||||
: (guardCancel(
|
||||
await multiselect({
|
||||
message: "Select sections to configure",
|
||||
options: [
|
||||
{ value: "workspace", label: "Workspace" },
|
||||
{ value: "model", label: "Model/auth" },
|
||||
{ value: "gateway", label: "Gateway config" },
|
||||
{ value: "daemon", label: "Gateway daemon" },
|
||||
{ value: "providers", label: "Providers" },
|
||||
{ value: "skills", label: "Skills" },
|
||||
{ value: "health", label: "Health check" },
|
||||
],
|
||||
}),
|
||||
runtime,
|
||||
) as WizardSection[]);
|
||||
|
||||
if (!selected || selected.length === 0) {
|
||||
outro("No changes selected.");
|
||||
return;
|
||||
}
|
||||
|
||||
let nextConfig = { ...baseConfig };
|
||||
let workspaceDir =
|
||||
nextConfig.agent?.workspace ??
|
||||
baseConfig.agent?.workspace ??
|
||||
DEFAULT_WORKSPACE;
|
||||
let gatewayPort = 18789;
|
||||
let gatewayToken: string | undefined;
|
||||
|
||||
if (selected.includes("workspace")) {
|
||||
const workspaceInput = guardCancel(
|
||||
await text({
|
||||
message: "Workspace directory",
|
||||
initialValue: workspaceDir,
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
workspaceDir = resolveUserPath(
|
||||
String(workspaceInput ?? "").trim() || DEFAULT_WORKSPACE,
|
||||
);
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
agent: {
|
||||
...nextConfig.agent,
|
||||
workspace: workspaceDir,
|
||||
},
|
||||
};
|
||||
await ensureWorkspaceAndSessions(workspaceDir, runtime);
|
||||
}
|
||||
|
||||
if (selected.includes("model")) {
|
||||
nextConfig = await promptAuthConfig(nextConfig, runtime);
|
||||
}
|
||||
|
||||
if (selected.includes("gateway")) {
|
||||
const gateway = await promptGatewayConfig(nextConfig, runtime);
|
||||
nextConfig = gateway.config;
|
||||
gatewayPort = gateway.port;
|
||||
gatewayToken = gateway.token;
|
||||
}
|
||||
|
||||
if (selected.includes("providers")) {
|
||||
nextConfig = await setupProviders(nextConfig, runtime, {
|
||||
allowDisable: true,
|
||||
allowSignalInstall: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (selected.includes("skills")) {
|
||||
const wsDir = resolveUserPath(workspaceDir);
|
||||
nextConfig = await setupSkills(nextConfig, wsDir, runtime);
|
||||
}
|
||||
|
||||
nextConfig = applyWizardMetadata(nextConfig, {
|
||||
command: opts.command,
|
||||
mode,
|
||||
});
|
||||
await writeConfigFile(nextConfig);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
|
||||
|
||||
if (selected.includes("daemon")) {
|
||||
if (!selected.includes("gateway")) {
|
||||
const portInput = guardCancel(
|
||||
await text({
|
||||
message: "Gateway port for daemon install",
|
||||
initialValue: String(gatewayPort),
|
||||
validate: (value) =>
|
||||
Number.isFinite(Number(value)) ? undefined : "Invalid port",
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
gatewayPort = Number.parseInt(String(portInput), 10);
|
||||
}
|
||||
|
||||
await maybeInstallDaemon({
|
||||
runtime,
|
||||
port: gatewayPort,
|
||||
gatewayToken,
|
||||
});
|
||||
}
|
||||
|
||||
if (selected.includes("health")) {
|
||||
await sleep(1000);
|
||||
try {
|
||||
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
|
||||
} catch (err) {
|
||||
runtime.error(`Health check failed: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
outro("Configure complete.");
|
||||
}
|
||||
|
||||
export async function configureCommand(runtime: RuntimeEnv = defaultRuntime) {
|
||||
await runConfigureWizard({ command: "configure" }, runtime);
|
||||
}
|
||||
93
src/commands/doctor.ts
Normal file
93
src/commands/doctor.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { confirm, intro, note, outro } from "@clack/prompts";
|
||||
|
||||
import { buildWorkspaceSkillStatus } from "../agents/skills-status.js";
|
||||
import type { ClawdisConfig } from "../config/config.js";
|
||||
import {
|
||||
CONFIG_PATH_CLAWDIS,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
} from "../config/config.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 { healthCommand } from "./health.js";
|
||||
import {
|
||||
applyWizardMetadata,
|
||||
DEFAULT_WORKSPACE,
|
||||
guardCancel,
|
||||
printWizardHeader,
|
||||
} from "./onboard-helpers.js";
|
||||
|
||||
function resolveMode(cfg: ClawdisConfig): "local" | "remote" {
|
||||
return cfg.gateway?.mode === "remote" ? "remote" : "local";
|
||||
}
|
||||
|
||||
export async function doctorCommand(runtime: RuntimeEnv = defaultRuntime) {
|
||||
printWizardHeader(runtime);
|
||||
intro("Clawdis doctor");
|
||||
|
||||
const snapshot = await readConfigFileSnapshot();
|
||||
let cfg: ClawdisConfig = snapshot.valid ? snapshot.config : {};
|
||||
if (snapshot.exists && !snapshot.valid) {
|
||||
note("Config invalid; doctor will run with defaults.", "Config");
|
||||
}
|
||||
|
||||
const workspaceDir = resolveUserPath(
|
||||
cfg.agent?.workspace ?? DEFAULT_WORKSPACE,
|
||||
);
|
||||
const skillsReport = buildWorkspaceSkillStatus(workspaceDir, { config: cfg });
|
||||
note(
|
||||
[
|
||||
`Eligible: ${skillsReport.skills.filter((s) => s.eligible).length}`,
|
||||
`Missing requirements: ${
|
||||
skillsReport.skills.filter(
|
||||
(s) => !s.eligible && !s.disabled && !s.blockedByAllowlist,
|
||||
).length
|
||||
}`,
|
||||
`Blocked by allowlist: ${
|
||||
skillsReport.skills.filter((s) => s.blockedByAllowlist).length
|
||||
}`,
|
||||
].join("\n"),
|
||||
"Skills status",
|
||||
);
|
||||
|
||||
let healthOk = false;
|
||||
try {
|
||||
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
|
||||
healthOk = true;
|
||||
} catch (err) {
|
||||
runtime.error(`Health check failed: ${String(err)}`);
|
||||
}
|
||||
|
||||
if (!healthOk) {
|
||||
const service = resolveGatewayService();
|
||||
const loaded = await service.isLoaded({ env: process.env });
|
||||
if (!loaded) {
|
||||
note("Gateway daemon not installed.", "Gateway");
|
||||
} else {
|
||||
const restart = guardCancel(
|
||||
await confirm({
|
||||
message: "Restart gateway daemon now?",
|
||||
initialValue: true,
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
if (restart) {
|
||||
await service.restart({ stdout: process.stdout });
|
||||
await sleep(1500);
|
||||
try {
|
||||
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
|
||||
} catch (err) {
|
||||
runtime.error(`Health check failed: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfg = applyWizardMetadata(cfg, { command: "doctor", mode: resolveMode(cfg) });
|
||||
await writeConfigFile(cfg);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
|
||||
|
||||
outro("Doctor complete.");
|
||||
}
|
||||
@@ -13,7 +13,8 @@ import { CONFIG_PATH_CLAWDIS } from "../config/config.js";
|
||||
import { resolveSessionTranscriptsDir } from "../config/sessions.js";
|
||||
import { runCommandWithTimeout } from "../process/exec.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { CONFIG_DIR } from "../utils.js";
|
||||
import { CONFIG_DIR, resolveUserPath } from "../utils.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import type { NodeManagerChoice, ResetScope } from "./onboard-types.js";
|
||||
|
||||
export function guardCancel<T>(value: T, runtime: RuntimeEnv): T {
|
||||
@@ -41,6 +42,36 @@ export function randomToken(): string {
|
||||
return crypto.randomBytes(24).toString("hex");
|
||||
}
|
||||
|
||||
export function printWizardHeader(runtime: RuntimeEnv) {
|
||||
const header = [
|
||||
"##### # ### # # #### ##### ####",
|
||||
"# # # # # # # # # # ",
|
||||
"# # ##### # # # # # # ### ",
|
||||
"# # # # ## ## # # # #",
|
||||
"##### ##### # # # # #### ##### #### ",
|
||||
].join("\n");
|
||||
runtime.log(header);
|
||||
}
|
||||
|
||||
export function applyWizardMetadata(
|
||||
cfg: ClawdisConfig,
|
||||
params: { command: string; mode: "local" | "remote" },
|
||||
): ClawdisConfig {
|
||||
const commit =
|
||||
process.env.GIT_COMMIT?.trim() || process.env.GIT_SHA?.trim() || undefined;
|
||||
return {
|
||||
...cfg,
|
||||
wizard: {
|
||||
...cfg.wizard,
|
||||
lastRunAt: new Date().toISOString(),
|
||||
lastRunVersion: VERSION,
|
||||
lastRunCommit: commit,
|
||||
lastRunCommand: params.command,
|
||||
lastRunMode: params.mode,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function openUrl(url: string): Promise<void> {
|
||||
const platform = process.platform;
|
||||
const command =
|
||||
@@ -114,6 +145,17 @@ export async function handleReset(
|
||||
}
|
||||
|
||||
export async function detectBinary(name: string): Promise<boolean> {
|
||||
if (!name?.trim()) return false;
|
||||
const resolved = name.startsWith("~") ? resolveUserPath(name) : name;
|
||||
if (path.isAbsolute(resolved) || resolved.startsWith(".")) {
|
||||
try {
|
||||
await fs.access(resolved);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const command =
|
||||
process.platform === "win32"
|
||||
? ["where", name]
|
||||
|
||||
@@ -30,11 +30,13 @@ import {
|
||||
writeOAuthCredentials,
|
||||
} from "./onboard-auth.js";
|
||||
import {
|
||||
applyWizardMetadata,
|
||||
DEFAULT_WORKSPACE,
|
||||
ensureWorkspaceAndSessions,
|
||||
guardCancel,
|
||||
handleReset,
|
||||
openUrl,
|
||||
printWizardHeader,
|
||||
randomToken,
|
||||
summarizeExistingConfig,
|
||||
} from "./onboard-helpers.js";
|
||||
@@ -52,14 +54,7 @@ export async function runInteractiveOnboarding(
|
||||
opts: OnboardOptions,
|
||||
runtime: RuntimeEnv = defaultRuntime,
|
||||
) {
|
||||
const header = [
|
||||
" _____ _ ___ _ _ ____ ___ ____ ",
|
||||
" / ____| | / _ \\ | | | | | _ \\_ _/ __|",
|
||||
"| | | | | | | | | | | | | | | | |\\__ \\",
|
||||
"| |___ | |___| |_| | | |__| |___ | |_| | |___) |",
|
||||
" \\_____|_____|\\___/ \\____/_____|____/___/____/ ",
|
||||
].join("\n");
|
||||
runtime.log(header);
|
||||
printWizardHeader(runtime);
|
||||
intro("Clawdis onboarding");
|
||||
|
||||
const snapshot = await readConfigFileSnapshot();
|
||||
@@ -363,13 +358,16 @@ export async function runInteractiveOnboarding(
|
||||
},
|
||||
};
|
||||
|
||||
nextConfig = await setupProviders(nextConfig, runtime);
|
||||
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(
|
||||
|
||||
@@ -15,6 +15,7 @@ import { resolveUserPath, sleep } from "../utils.js";
|
||||
import { healthCommand } from "./health.js";
|
||||
import { applyMinimaxConfig, setAnthropicApiKey } from "./onboard-auth.js";
|
||||
import {
|
||||
applyWizardMetadata,
|
||||
DEFAULT_WORKSPACE,
|
||||
ensureWorkspaceAndSessions,
|
||||
randomToken,
|
||||
@@ -168,6 +169,7 @@ export async function runNonInteractiveOnboarding(
|
||||
};
|
||||
}
|
||||
|
||||
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
|
||||
await writeConfigFile(nextConfig);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
|
||||
await ensureWorkspaceAndSessions(workspaceDir, runtime);
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { RuntimeEnv } from "../runtime.js";
|
||||
import { resolveWebAuthDir } from "../web/session.js";
|
||||
import { detectBinary, guardCancel } from "./onboard-helpers.js";
|
||||
import type { ProviderChoice } from "./onboard-types.js";
|
||||
import { installSignalCli } from "./signal-install.js";
|
||||
|
||||
async function pathExists(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
@@ -27,6 +28,7 @@ async function detectWhatsAppLinked(): Promise<boolean> {
|
||||
export async function setupProviders(
|
||||
cfg: ClawdisConfig,
|
||||
runtime: RuntimeEnv,
|
||||
options?: { allowDisable?: boolean; allowSignalInstall?: boolean },
|
||||
): Promise<ClawdisConfig> {
|
||||
const whatsappLinked = await detectWhatsAppLinked();
|
||||
const telegramEnv = Boolean(process.env.TELEGRAM_BOT_TOKEN?.trim());
|
||||
@@ -38,7 +40,8 @@ export async function setupProviders(
|
||||
const signalConfigured = Boolean(
|
||||
cfg.signal?.account || cfg.signal?.httpUrl || cfg.signal?.httpPort,
|
||||
);
|
||||
const signalCliDetected = await detectBinary("signal-cli");
|
||||
const signalCliPath = cfg.signal?.cliPath ?? "signal-cli";
|
||||
const signalCliDetected = await detectBinary(signalCliPath);
|
||||
|
||||
note(
|
||||
[
|
||||
@@ -46,7 +49,7 @@ export async function setupProviders(
|
||||
`Telegram: ${telegramConfigured ? "configured" : "needs token"}`,
|
||||
`Discord: ${discordConfigured ? "configured" : "needs token"}`,
|
||||
`Signal: ${signalConfigured ? "configured" : "needs setup"}`,
|
||||
`signal-cli: ${signalCliDetected ? "found" : "missing"}`,
|
||||
`signal-cli: ${signalCliDetected ? "found" : "missing"} (${signalCliPath})`,
|
||||
].join("\n"),
|
||||
"Provider status",
|
||||
);
|
||||
@@ -241,7 +244,35 @@ export async function setupProviders(
|
||||
}
|
||||
|
||||
if (selection.includes("signal")) {
|
||||
if (!signalCliDetected) {
|
||||
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,
|
||||
);
|
||||
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");
|
||||
} else if (!result.ok) {
|
||||
note(result.error ?? "signal-cli install failed.", "Signal");
|
||||
}
|
||||
} catch (err) {
|
||||
note(`signal-cli install failed: ${String(err)}`, "Signal");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!cliDetected) {
|
||||
note(
|
||||
"signal-cli not found. Install it, then rerun this step or set signal.cliPath.",
|
||||
"Signal",
|
||||
@@ -279,7 +310,7 @@ export async function setupProviders(
|
||||
...next.signal,
|
||||
enabled: true,
|
||||
account,
|
||||
cliPath: next.signal?.cliPath ?? "signal-cli",
|
||||
cliPath: resolvedCliPath ?? "signal-cli",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -294,5 +325,55 @@ export async function setupProviders(
|
||||
);
|
||||
}
|
||||
|
||||
if (options?.allowDisable) {
|
||||
if (!selection.includes("telegram") && telegramConfigured) {
|
||||
const disable = guardCancel(
|
||||
await confirm({
|
||||
message: "Disable Telegram provider?",
|
||||
initialValue: false,
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
if (disable) {
|
||||
next = {
|
||||
...next,
|
||||
telegram: { ...next.telegram, enabled: false },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!selection.includes("discord") && discordConfigured) {
|
||||
const disable = guardCancel(
|
||||
await confirm({
|
||||
message: "Disable Discord provider?",
|
||||
initialValue: false,
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
if (disable) {
|
||||
next = {
|
||||
...next,
|
||||
discord: { ...next.discord, enabled: false },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!selection.includes("signal") && signalConfigured) {
|
||||
const disable = guardCancel(
|
||||
await confirm({
|
||||
message: "Disable Signal provider?",
|
||||
initialValue: false,
|
||||
}),
|
||||
runtime,
|
||||
);
|
||||
if (disable) {
|
||||
next = {
|
||||
...next,
|
||||
signal: { ...next.signal, enabled: false },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
199
src/commands/signal-install.ts
Normal file
199
src/commands/signal-install.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import { createWriteStream } from "node:fs";
|
||||
import fs from "node:fs/promises";
|
||||
import { request } from "node:https";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
|
||||
import { runCommandWithTimeout } from "../process/exec.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { CONFIG_DIR } from "../utils.js";
|
||||
|
||||
type ReleaseAsset = {
|
||||
name?: string;
|
||||
browser_download_url?: string;
|
||||
};
|
||||
|
||||
type NamedAsset = {
|
||||
name: string;
|
||||
browser_download_url: string;
|
||||
};
|
||||
|
||||
type ReleaseResponse = {
|
||||
tag_name?: string;
|
||||
assets?: ReleaseAsset[];
|
||||
};
|
||||
|
||||
export type SignalInstallResult = {
|
||||
ok: boolean;
|
||||
cliPath?: string;
|
||||
version?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function looksLikeArchive(name: string): boolean {
|
||||
return (
|
||||
name.endsWith(".tar.gz") || name.endsWith(".tgz") || name.endsWith(".zip")
|
||||
);
|
||||
}
|
||||
|
||||
function pickAsset(assets: ReleaseAsset[], platform: NodeJS.Platform) {
|
||||
const withName = assets.filter((asset): asset is NamedAsset =>
|
||||
Boolean(asset.name && asset.browser_download_url),
|
||||
);
|
||||
const byName = (pattern: RegExp) =>
|
||||
withName.find((asset) => pattern.test(asset.name.toLowerCase()));
|
||||
|
||||
if (platform === "linux") {
|
||||
return (
|
||||
byName(/linux-native/) ||
|
||||
byName(/linux/) ||
|
||||
withName.find((asset) => looksLikeArchive(asset.name.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
return (
|
||||
byName(/macos|osx|darwin/) ||
|
||||
withName.find((asset) => looksLikeArchive(asset.name.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === "win32") {
|
||||
return (
|
||||
byName(/windows|win/) ||
|
||||
withName.find((asset) => looksLikeArchive(asset.name.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
return withName.find((asset) => looksLikeArchive(asset.name.toLowerCase()));
|
||||
}
|
||||
|
||||
async function downloadToFile(
|
||||
url: string,
|
||||
dest: string,
|
||||
maxRedirects = 5,
|
||||
): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const req = request(url, (res) => {
|
||||
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400) {
|
||||
const location = res.headers.location;
|
||||
if (!location || maxRedirects <= 0) {
|
||||
reject(new Error("Redirect loop or missing Location header"));
|
||||
return;
|
||||
}
|
||||
const redirectUrl = new URL(location, url).href;
|
||||
resolve(downloadToFile(redirectUrl, dest, maxRedirects - 1));
|
||||
return;
|
||||
}
|
||||
if (!res.statusCode || res.statusCode >= 400) {
|
||||
reject(new Error(`HTTP ${res.statusCode ?? "?"} downloading file`));
|
||||
return;
|
||||
}
|
||||
const out = createWriteStream(dest);
|
||||
pipeline(res, out).then(resolve).catch(reject);
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function findSignalCliBinary(root: string): Promise<string | null> {
|
||||
const candidates: string[] = [];
|
||||
const enqueue = async (dir: string, depth: number) => {
|
||||
if (depth > 3) return;
|
||||
const entries = await fs
|
||||
.readdir(dir, { withFileTypes: true })
|
||||
.catch(() => []);
|
||||
for (const entry of entries) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await enqueue(full, depth + 1);
|
||||
} else if (entry.isFile() && entry.name === "signal-cli") {
|
||||
candidates.push(full);
|
||||
}
|
||||
}
|
||||
};
|
||||
await enqueue(root, 0);
|
||||
return candidates[0] ?? null;
|
||||
}
|
||||
|
||||
export async function installSignalCli(
|
||||
runtime: RuntimeEnv,
|
||||
): Promise<SignalInstallResult> {
|
||||
if (process.platform === "win32") {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Signal CLI auto-install is not supported on Windows yet.",
|
||||
};
|
||||
}
|
||||
|
||||
const apiUrl =
|
||||
"https://api.github.com/repos/AsamK/signal-cli/releases/latest";
|
||||
const response = await fetch(apiUrl, {
|
||||
headers: {
|
||||
"User-Agent": "clawdis",
|
||||
Accept: "application/vnd.github+json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Failed to fetch release info (${response.status})`,
|
||||
};
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as ReleaseResponse;
|
||||
const version = payload.tag_name?.replace(/^v/, "") ?? "unknown";
|
||||
const assets = payload.assets ?? [];
|
||||
const asset = pickAsset(assets, process.platform);
|
||||
const assetName = asset?.name ?? "";
|
||||
const assetUrl = asset?.browser_download_url ?? "";
|
||||
|
||||
if (!assetName || !assetUrl) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "No compatible release asset found for this platform.",
|
||||
};
|
||||
}
|
||||
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-signal-"));
|
||||
const archivePath = path.join(tmpDir, assetName);
|
||||
|
||||
runtime.log(`Downloading signal-cli ${version} (${assetName})…`);
|
||||
await downloadToFile(assetUrl, archivePath);
|
||||
|
||||
const installRoot = path.join(CONFIG_DIR, "tools", "signal-cli", version);
|
||||
await fs.mkdir(installRoot, { recursive: true });
|
||||
|
||||
if (assetName.endsWith(".zip")) {
|
||||
await runCommandWithTimeout(
|
||||
["unzip", "-q", archivePath, "-d", installRoot],
|
||||
{
|
||||
timeoutMs: 60_000,
|
||||
},
|
||||
);
|
||||
} else if (assetName.endsWith(".tar.gz") || assetName.endsWith(".tgz")) {
|
||||
await runCommandWithTimeout(
|
||||
["tar", "-xzf", archivePath, "-C", installRoot],
|
||||
{
|
||||
timeoutMs: 60_000,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
return { ok: false, error: `Unsupported archive type: ${assetName}` };
|
||||
}
|
||||
|
||||
const cliPath = await findSignalCliBinary(installRoot);
|
||||
if (!cliPath) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `signal-cli binary not found after extracting ${assetName}`,
|
||||
};
|
||||
}
|
||||
|
||||
await fs.chmod(cliPath, 0o755).catch(() => {});
|
||||
|
||||
return { ok: true, cliPath, version };
|
||||
}
|
||||
21
src/commands/update.ts
Normal file
21
src/commands/update.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
import { runConfigureWizard } from "./configure.js";
|
||||
|
||||
export async function updateCommand(runtime: RuntimeEnv = defaultRuntime) {
|
||||
await runConfigureWizard(
|
||||
{
|
||||
command: "update",
|
||||
sections: [
|
||||
"workspace",
|
||||
"model",
|
||||
"gateway",
|
||||
"daemon",
|
||||
"providers",
|
||||
"skills",
|
||||
"health",
|
||||
],
|
||||
},
|
||||
runtime,
|
||||
);
|
||||
}
|
||||
@@ -390,6 +390,13 @@ export type ClawdisConfig = {
|
||||
theme?: string;
|
||||
emoji?: string;
|
||||
};
|
||||
wizard?: {
|
||||
lastRunAt?: string;
|
||||
lastRunVersion?: string;
|
||||
lastRunCommit?: string;
|
||||
lastRunCommand?: string;
|
||||
lastRunMode?: "local" | "remote";
|
||||
};
|
||||
logging?: LoggingConfig;
|
||||
browser?: BrowserConfig;
|
||||
ui?: {
|
||||
@@ -699,6 +706,17 @@ const ClawdisSchema = z.object({
|
||||
emoji: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
wizard: z
|
||||
.object({
|
||||
lastRunAt: z.string().optional(),
|
||||
lastRunVersion: z.string().optional(),
|
||||
lastRunCommit: z.string().optional(),
|
||||
lastRunCommand: z.string().optional(),
|
||||
lastRunMode: z
|
||||
.union([z.literal("local"), z.literal("remote")])
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
logging: z
|
||||
.object({
|
||||
level: z
|
||||
|
||||
Reference in New Issue
Block a user