feat: add --dev/--profile CLI profiles
This commit is contained in:
@@ -24,6 +24,28 @@ const defaultRuntime = {
|
||||
},
|
||||
};
|
||||
|
||||
async function withEnvOverride<T>(
|
||||
overrides: Record<string, string | undefined>,
|
||||
fn: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
for (const key of Object.keys(overrides)) {
|
||||
saved[key] = process.env[key];
|
||||
if (overrides[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = overrides[key];
|
||||
}
|
||||
vi.resetModules();
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
for (const key of Object.keys(saved)) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
vi.resetModules();
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock("../gateway/call.js", () => ({
|
||||
callGateway: (opts: unknown) => callGateway(opts),
|
||||
randomIdempotencyKey: () => randomIdempotencyKey(),
|
||||
@@ -205,4 +227,26 @@ describe("gateway-cli coverage", () => {
|
||||
process.removeListener("SIGINT", listener);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses env/config port when --port is omitted", async () => {
|
||||
await withEnvOverride({ CLAWDBOT_GATEWAY_PORT: "19001" }, async () => {
|
||||
runtimeLogs.length = 0;
|
||||
runtimeErrors.length = 0;
|
||||
startGatewayServer.mockClear();
|
||||
|
||||
const { registerGatewayCli } = await import("./gateway-cli.js");
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
registerGatewayCli(program);
|
||||
|
||||
startGatewayServer.mockRejectedValueOnce(new Error("nope"));
|
||||
await expect(
|
||||
program.parseAsync(["gateway", "--allow-unconfigured"], {
|
||||
from: "user",
|
||||
}),
|
||||
).rejects.toThrow("__exit__:1");
|
||||
|
||||
expect(startGatewayServer).toHaveBeenCalledWith(19001, expect.anything());
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -153,7 +153,7 @@ export function registerGatewayCli(program: Command) {
|
||||
program
|
||||
.command("gateway-daemon")
|
||||
.description("Run the WebSocket Gateway as a long-lived daemon")
|
||||
.option("--port <port>", "Port for the gateway WebSocket", "18789")
|
||||
.option("--port <port>", "Port for the gateway WebSocket")
|
||||
.option(
|
||||
"--bind <mode>",
|
||||
'Bind mode ("loopback"|"tailnet"|"lan"|"auto"). Defaults to config gateway.bind (or loopback).',
|
||||
@@ -298,7 +298,7 @@ export function registerGatewayCli(program: Command) {
|
||||
const gateway = program
|
||||
.command("gateway")
|
||||
.description("Run the WebSocket Gateway")
|
||||
.option("--port <port>", "Port for the gateway WebSocket", "18789")
|
||||
.option("--port <port>", "Port for the gateway WebSocket")
|
||||
.option(
|
||||
"--bind <mode>",
|
||||
'Bind mode ("loopback"|"tailnet"|"lan"|"auto"). Defaults to config gateway.bind (or loopback).',
|
||||
|
||||
99
src/cli/profile.test.ts
Normal file
99
src/cli/profile.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyCliProfileEnv, parseCliProfileArgs } from "./profile.js";
|
||||
|
||||
describe("parseCliProfileArgs", () => {
|
||||
it("strips --dev anywhere in argv", () => {
|
||||
const res = parseCliProfileArgs([
|
||||
"node",
|
||||
"clawdbot",
|
||||
"gateway",
|
||||
"--dev",
|
||||
"--allow-unconfigured",
|
||||
]);
|
||||
if (!res.ok) throw new Error(res.error);
|
||||
expect(res.profile).toBe("dev");
|
||||
expect(res.argv).toEqual([
|
||||
"node",
|
||||
"clawdbot",
|
||||
"gateway",
|
||||
"--allow-unconfigured",
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses --profile value and strips it", () => {
|
||||
const res = parseCliProfileArgs([
|
||||
"node",
|
||||
"clawdbot",
|
||||
"--profile",
|
||||
"work",
|
||||
"status",
|
||||
]);
|
||||
if (!res.ok) throw new Error(res.error);
|
||||
expect(res.profile).toBe("work");
|
||||
expect(res.argv).toEqual(["node", "clawdbot", "status"]);
|
||||
});
|
||||
|
||||
it("rejects missing profile value", () => {
|
||||
const res = parseCliProfileArgs(["node", "clawdbot", "--profile"]);
|
||||
expect(res.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects combining --dev with --profile (dev first)", () => {
|
||||
const res = parseCliProfileArgs([
|
||||
"node",
|
||||
"clawdbot",
|
||||
"--dev",
|
||||
"--profile",
|
||||
"work",
|
||||
"status",
|
||||
]);
|
||||
expect(res.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects combining --dev with --profile (profile first)", () => {
|
||||
const res = parseCliProfileArgs([
|
||||
"node",
|
||||
"clawdbot",
|
||||
"--profile",
|
||||
"work",
|
||||
"--dev",
|
||||
"status",
|
||||
]);
|
||||
expect(res.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyCliProfileEnv", () => {
|
||||
it("fills env defaults for dev profile", () => {
|
||||
const env: Record<string, string | undefined> = {};
|
||||
applyCliProfileEnv({
|
||||
profile: "dev",
|
||||
env,
|
||||
homedir: () => "/home/peter",
|
||||
});
|
||||
expect(env.CLAWDBOT_PROFILE).toBe("dev");
|
||||
expect(env.CLAWDBOT_STATE_DIR).toBe("/home/peter/.clawdbot-dev");
|
||||
expect(env.CLAWDBOT_CONFIG_PATH).toBe(
|
||||
path.join("/home/peter/.clawdbot-dev", "clawdbot.json"),
|
||||
);
|
||||
expect(env.CLAWDBOT_GATEWAY_PORT).toBe("19001");
|
||||
});
|
||||
|
||||
it("does not override explicit env values", () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
CLAWDBOT_STATE_DIR: "/custom",
|
||||
CLAWDBOT_GATEWAY_PORT: "19099",
|
||||
};
|
||||
applyCliProfileEnv({
|
||||
profile: "dev",
|
||||
env,
|
||||
homedir: () => "/home/peter",
|
||||
});
|
||||
expect(env.CLAWDBOT_STATE_DIR).toBe("/custom");
|
||||
expect(env.CLAWDBOT_GATEWAY_PORT).toBe("19099");
|
||||
expect(env.CLAWDBOT_CONFIG_PATH).toBe(
|
||||
path.join("/custom", "clawdbot.json"),
|
||||
);
|
||||
});
|
||||
});
|
||||
107
src/cli/profile.ts
Normal file
107
src/cli/profile.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
export type CliProfileParseResult =
|
||||
| { ok: true; profile: string | null; argv: string[] }
|
||||
| { ok: false; error: string };
|
||||
|
||||
function takeValue(
|
||||
raw: string,
|
||||
next: string | undefined,
|
||||
): {
|
||||
value: string | null;
|
||||
consumedNext: boolean;
|
||||
} {
|
||||
if (raw.includes("=")) {
|
||||
const [, value] = raw.split("=", 2);
|
||||
const trimmed = (value ?? "").trim();
|
||||
return { value: trimmed || null, consumedNext: false };
|
||||
}
|
||||
const trimmed = (next ?? "").trim();
|
||||
return { value: trimmed || null, consumedNext: Boolean(next) };
|
||||
}
|
||||
|
||||
function isValidProfileName(value: string): boolean {
|
||||
if (!value) return false;
|
||||
// Keep it path-safe + shell-friendly.
|
||||
return /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(value);
|
||||
}
|
||||
|
||||
export function parseCliProfileArgs(argv: string[]): CliProfileParseResult {
|
||||
if (argv.length < 2) return { ok: true, profile: null, argv };
|
||||
|
||||
const out: string[] = argv.slice(0, 2);
|
||||
let profile: string | null = null;
|
||||
let sawDev = false;
|
||||
|
||||
const args = argv.slice(2);
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
const arg = args[i];
|
||||
if (arg === undefined) continue;
|
||||
|
||||
if (arg === "--dev") {
|
||||
if (profile && profile !== "dev") {
|
||||
return { ok: false, error: "Cannot combine --dev with --profile" };
|
||||
}
|
||||
sawDev = true;
|
||||
profile = "dev";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--profile" || arg.startsWith("--profile=")) {
|
||||
if (sawDev) {
|
||||
return { ok: false, error: "Cannot combine --dev with --profile" };
|
||||
}
|
||||
const next = args[i + 1];
|
||||
const { value, consumedNext } = takeValue(arg, next);
|
||||
if (consumedNext) i += 1;
|
||||
if (!value) return { ok: false, error: "--profile requires a value" };
|
||||
if (!isValidProfileName(value)) {
|
||||
return {
|
||||
ok: false,
|
||||
error: 'Invalid --profile (use letters, numbers, "_", "-" only)',
|
||||
};
|
||||
}
|
||||
profile = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
out.push(arg);
|
||||
}
|
||||
|
||||
return { ok: true, profile, argv: out };
|
||||
}
|
||||
|
||||
function resolveProfileStateDir(
|
||||
profile: string,
|
||||
homedir: () => string,
|
||||
): string {
|
||||
const suffix = profile.toLowerCase() === "default" ? "" : `-${profile}`;
|
||||
return path.join(homedir(), `.clawdbot${suffix}`);
|
||||
}
|
||||
|
||||
export function applyCliProfileEnv(params: {
|
||||
profile: string;
|
||||
env?: Record<string, string | undefined>;
|
||||
homedir?: () => string;
|
||||
}) {
|
||||
const env = params.env ?? (process.env as Record<string, string | undefined>);
|
||||
const homedir = params.homedir ?? os.homedir;
|
||||
const profile = params.profile.trim();
|
||||
if (!profile) return;
|
||||
|
||||
// Convenience only: fill defaults, never override explicit env values.
|
||||
env.CLAWDBOT_PROFILE = profile;
|
||||
|
||||
const stateDir =
|
||||
env.CLAWDBOT_STATE_DIR?.trim() || resolveProfileStateDir(profile, homedir);
|
||||
if (!env.CLAWDBOT_STATE_DIR?.trim()) env.CLAWDBOT_STATE_DIR = stateDir;
|
||||
|
||||
if (!env.CLAWDBOT_CONFIG_PATH?.trim()) {
|
||||
env.CLAWDBOT_CONFIG_PATH = path.join(stateDir, "clawdbot.json");
|
||||
}
|
||||
|
||||
if (profile === "dev" && !env.CLAWDBOT_GATEWAY_PORT?.trim()) {
|
||||
env.CLAWDBOT_GATEWAY_PORT = "19001";
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,18 @@ export function buildProgram() {
|
||||
const TAGLINE =
|
||||
"Send, receive, and auto-reply on WhatsApp (web) and Telegram (bot).";
|
||||
|
||||
program.name("clawdbot").description("").version(PROGRAM_VERSION);
|
||||
program
|
||||
.name("clawdbot")
|
||||
.description("")
|
||||
.version(PROGRAM_VERSION)
|
||||
.option(
|
||||
"--dev",
|
||||
"Dev profile: isolate config/state under ~/.clawdbot-dev and default gateway port 19001",
|
||||
)
|
||||
.option(
|
||||
"--profile <name>",
|
||||
"Use a named profile (isolates CLAWDBOT_STATE_DIR/CLAWDBOT_CONFIG_PATH under ~/.clawdbot-<name>)",
|
||||
);
|
||||
|
||||
const formatIntroLine = (version: string, rich = true) => {
|
||||
const base = `📡 clawdbot ${version} — ${TAGLINE}`;
|
||||
@@ -96,6 +107,10 @@ export function buildProgram() {
|
||||
"Send via your web session and print JSON result.",
|
||||
],
|
||||
["clawdbot gateway --port 18789", "Run the WebSocket Gateway locally."],
|
||||
[
|
||||
"clawdbot --dev gateway",
|
||||
"Run a dev Gateway (isolated state/config) on ws://127.0.0.1:19001.",
|
||||
],
|
||||
[
|
||||
"clawdbot gateway --force",
|
||||
"Kill anything bound to the default gateway port, then start it.",
|
||||
|
||||
48
src/cli/run-main.ts
Normal file
48
src/cli/run-main.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import process from "node:process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { loadDotEnv } from "../infra/dotenv.js";
|
||||
import { normalizeEnv } from "../infra/env.js";
|
||||
import { isMainModule } from "../infra/is-main.js";
|
||||
import { ensureClawdbotCliOnPath } from "../infra/path-env.js";
|
||||
import { assertSupportedRuntime } from "../infra/runtime-guard.js";
|
||||
import { enableConsoleCapture } from "../logging.js";
|
||||
|
||||
export async function runCli(argv: string[] = process.argv) {
|
||||
loadDotEnv({ quiet: true });
|
||||
normalizeEnv();
|
||||
ensureClawdbotCliOnPath();
|
||||
|
||||
// Capture all console output into structured logs while keeping stdout/stderr behavior.
|
||||
enableConsoleCapture();
|
||||
|
||||
// Enforce the minimum supported runtime before doing any work.
|
||||
assertSupportedRuntime();
|
||||
|
||||
const { buildProgram } = await import("./program.js");
|
||||
const program = buildProgram();
|
||||
|
||||
// Global error handlers to prevent silent crashes from unhandled rejections/exceptions.
|
||||
// These log the error and exit gracefully instead of crashing without trace.
|
||||
process.on("unhandledRejection", (reason, _promise) => {
|
||||
console.error(
|
||||
"[clawdbot] Unhandled promise rejection:",
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : reason,
|
||||
);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
process.on("uncaughtException", (error) => {
|
||||
console.error(
|
||||
"[clawdbot] Uncaught exception:",
|
||||
error.stack ?? error.message,
|
||||
);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
await program.parseAsync(argv);
|
||||
}
|
||||
|
||||
export function isCliMainModule(): boolean {
|
||||
return isMainModule({ currentFile: fileURLToPath(import.meta.url) });
|
||||
}
|
||||
Reference in New Issue
Block a user