feat: add --dev/--profile CLI profiles
This commit is contained in:
12
package.json
12
package.json
@@ -5,7 +5,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"bin": {
|
"bin": {
|
||||||
"clawdbot": "dist/index.js"
|
"clawdbot": "dist/entry.js"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist/agents/**",
|
"dist/agents/**",
|
||||||
@@ -36,7 +36,7 @@
|
|||||||
"LICENSE"
|
"LICENSE"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tsx src/index.ts",
|
"dev": "tsx src/entry.ts",
|
||||||
"docs:list": "tsx scripts/docs-list.ts",
|
"docs:list": "tsx scripts/docs-list.ts",
|
||||||
"docs:dev": "cd docs && mint dev",
|
"docs:dev": "cd docs && mint dev",
|
||||||
"docs:build": "cd docs && pnpm dlx mint broken-links",
|
"docs:build": "cd docs && pnpm dlx mint broken-links",
|
||||||
@@ -45,10 +45,10 @@
|
|||||||
"ui:install": "pnpm -C ui install",
|
"ui:install": "pnpm -C ui install",
|
||||||
"ui:dev": "pnpm -C ui dev",
|
"ui:dev": "pnpm -C ui dev",
|
||||||
"ui:build": "pnpm -C ui build",
|
"ui:build": "pnpm -C ui build",
|
||||||
"start": "tsx src/index.ts",
|
"start": "tsx src/entry.ts",
|
||||||
"clawdbot": "tsx src/index.ts",
|
"clawdbot": "tsx src/entry.ts",
|
||||||
"gateway:watch": "tsx watch --clear-screen=false --include 'src/**/*.ts' src/index.ts gateway --force",
|
"gateway:watch": "tsx watch --clear-screen=false --include 'src/**/*.ts' src/entry.ts gateway --force",
|
||||||
"clawdbot:rpc": "tsx src/index.ts agent --mode rpc --json",
|
"clawdbot:rpc": "tsx src/entry.ts agent --mode rpc --json",
|
||||||
"lint": "biome check src test && oxlint --type-aware src test --ignore-pattern src/canvas-host/a2ui/a2ui.bundle.js",
|
"lint": "biome check src test && oxlint --type-aware src test --ignore-pattern src/canvas-host/a2ui/a2ui.bundle.js",
|
||||||
"lint:swift": "swiftlint lint --config .swiftlint.yml && (cd apps/ios && swiftlint lint --config .swiftlint.yml)",
|
"lint:swift": "swiftlint lint --config .swiftlint.yml && (cd apps/ios && swiftlint lint --config .swiftlint.yml)",
|
||||||
"lint:fix": "biome check --write --unsafe src && biome format --write src",
|
"lint:fix": "biome check --write --unsafe src && biome format --write src",
|
||||||
|
|||||||
@@ -5,7 +5,18 @@ import { fileURLToPath } from "node:url";
|
|||||||
|
|
||||||
import { resolveUserPath } from "../utils.js";
|
import { resolveUserPath } from "../utils.js";
|
||||||
|
|
||||||
export const DEFAULT_AGENT_WORKSPACE_DIR = path.join(os.homedir(), "clawd");
|
export function resolveDefaultAgentWorkspaceDir(
|
||||||
|
env: NodeJS.ProcessEnv = process.env,
|
||||||
|
homedir: () => string = os.homedir,
|
||||||
|
): string {
|
||||||
|
const profile = env.CLAWDBOT_PROFILE?.trim();
|
||||||
|
if (profile && profile.toLowerCase() !== "default") {
|
||||||
|
return path.join(homedir(), `clawd-${profile}`);
|
||||||
|
}
|
||||||
|
return path.join(homedir(), "clawd");
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_AGENT_WORKSPACE_DIR = resolveDefaultAgentWorkspaceDir();
|
||||||
export const DEFAULT_AGENTS_FILENAME = "AGENTS.md";
|
export const DEFAULT_AGENTS_FILENAME = "AGENTS.md";
|
||||||
export const DEFAULT_SOUL_FILENAME = "SOUL.md";
|
export const DEFAULT_SOUL_FILENAME = "SOUL.md";
|
||||||
export const DEFAULT_TOOLS_FILENAME = "TOOLS.md";
|
export const DEFAULT_TOOLS_FILENAME = "TOOLS.md";
|
||||||
|
|||||||
@@ -19,6 +19,24 @@ describe("browser config", () => {
|
|||||||
expect(profile?.cdpIsLoopback).toBe(true);
|
expect(profile?.cdpIsLoopback).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("derives default ports from CLAWDBOT_GATEWAY_PORT when unset", () => {
|
||||||
|
const prev = process.env.CLAWDBOT_GATEWAY_PORT;
|
||||||
|
process.env.CLAWDBOT_GATEWAY_PORT = "19001";
|
||||||
|
try {
|
||||||
|
const resolved = resolveBrowserConfig(undefined);
|
||||||
|
expect(resolved.controlPort).toBe(19003);
|
||||||
|
const profile = resolveProfile(resolved, resolved.defaultProfile);
|
||||||
|
expect(profile?.cdpPort).toBe(19012);
|
||||||
|
expect(profile?.cdpUrl).toBe("http://127.0.0.1:19012");
|
||||||
|
} finally {
|
||||||
|
if (prev === undefined) {
|
||||||
|
delete process.env.CLAWDBOT_GATEWAY_PORT;
|
||||||
|
} else {
|
||||||
|
process.env.CLAWDBOT_GATEWAY_PORT = prev;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("normalizes hex colors", () => {
|
it("normalizes hex colors", () => {
|
||||||
const resolved = resolveBrowserConfig({
|
const resolved = resolveBrowserConfig({
|
||||||
controlUrl: "http://localhost:18791",
|
controlUrl: "http://localhost:18791",
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import type { BrowserConfig, BrowserProfileConfig } from "../config/config.js";
|
import type { BrowserConfig, BrowserProfileConfig } from "../config/config.js";
|
||||||
|
import {
|
||||||
|
deriveDefaultBrowserCdpPortRange,
|
||||||
|
deriveDefaultBrowserControlPort,
|
||||||
|
} from "../config/port-defaults.js";
|
||||||
import {
|
import {
|
||||||
DEFAULT_CLAWD_BROWSER_COLOR,
|
DEFAULT_CLAWD_BROWSER_COLOR,
|
||||||
DEFAULT_CLAWD_BROWSER_CONTROL_URL,
|
DEFAULT_CLAWD_BROWSER_CONTROL_URL,
|
||||||
@@ -89,11 +93,12 @@ function ensureDefaultProfile(
|
|||||||
profiles: Record<string, BrowserProfileConfig> | undefined,
|
profiles: Record<string, BrowserProfileConfig> | undefined,
|
||||||
defaultColor: string,
|
defaultColor: string,
|
||||||
legacyCdpPort?: number,
|
legacyCdpPort?: number,
|
||||||
|
derivedDefaultCdpPort?: number,
|
||||||
): Record<string, BrowserProfileConfig> {
|
): Record<string, BrowserProfileConfig> {
|
||||||
const result = { ...profiles };
|
const result = { ...profiles };
|
||||||
if (!result[DEFAULT_CLAWD_BROWSER_PROFILE_NAME]) {
|
if (!result[DEFAULT_CLAWD_BROWSER_PROFILE_NAME]) {
|
||||||
result[DEFAULT_CLAWD_BROWSER_PROFILE_NAME] = {
|
result[DEFAULT_CLAWD_BROWSER_PROFILE_NAME] = {
|
||||||
cdpPort: legacyCdpPort ?? CDP_PORT_RANGE_START,
|
cdpPort: legacyCdpPort ?? derivedDefaultCdpPort ?? CDP_PORT_RANGE_START,
|
||||||
color: defaultColor,
|
color: defaultColor,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -103,13 +108,30 @@ export function resolveBrowserConfig(
|
|||||||
cfg: BrowserConfig | undefined,
|
cfg: BrowserConfig | undefined,
|
||||||
): ResolvedBrowserConfig {
|
): ResolvedBrowserConfig {
|
||||||
const enabled = cfg?.enabled ?? DEFAULT_CLAWD_BROWSER_ENABLED;
|
const enabled = cfg?.enabled ?? DEFAULT_CLAWD_BROWSER_ENABLED;
|
||||||
|
const envControlUrl = process.env.CLAWDBOT_BROWSER_CONTROL_URL?.trim();
|
||||||
|
const derivedControlPort = (() => {
|
||||||
|
const raw = process.env.CLAWDBOT_GATEWAY_PORT?.trim();
|
||||||
|
if (!raw) return null;
|
||||||
|
const gatewayPort = Number.parseInt(raw, 10);
|
||||||
|
if (!Number.isFinite(gatewayPort) || gatewayPort <= 0) return null;
|
||||||
|
return deriveDefaultBrowserControlPort(gatewayPort);
|
||||||
|
})();
|
||||||
|
const derivedControlUrl = derivedControlPort
|
||||||
|
? `http://127.0.0.1:${derivedControlPort}`
|
||||||
|
: null;
|
||||||
|
|
||||||
const controlInfo = parseHttpUrl(
|
const controlInfo = parseHttpUrl(
|
||||||
cfg?.controlUrl ?? DEFAULT_CLAWD_BROWSER_CONTROL_URL,
|
cfg?.controlUrl ??
|
||||||
|
envControlUrl ??
|
||||||
|
derivedControlUrl ??
|
||||||
|
DEFAULT_CLAWD_BROWSER_CONTROL_URL,
|
||||||
"browser.controlUrl",
|
"browser.controlUrl",
|
||||||
);
|
);
|
||||||
const controlPort = controlInfo.port;
|
const controlPort = controlInfo.port;
|
||||||
const defaultColor = normalizeHexColor(cfg?.color);
|
const defaultColor = normalizeHexColor(cfg?.color);
|
||||||
|
|
||||||
|
const derivedCdpRange = deriveDefaultBrowserCdpPortRange(controlPort);
|
||||||
|
|
||||||
const rawCdpUrl = (cfg?.cdpUrl ?? "").trim();
|
const rawCdpUrl = (cfg?.cdpUrl ?? "").trim();
|
||||||
let cdpInfo:
|
let cdpInfo:
|
||||||
| {
|
| {
|
||||||
@@ -149,6 +171,7 @@ export function resolveBrowserConfig(
|
|||||||
cfg?.profiles,
|
cfg?.profiles,
|
||||||
defaultColor,
|
defaultColor,
|
||||||
legacyCdpPort,
|
legacyCdpPort,
|
||||||
|
derivedCdpRange.start,
|
||||||
);
|
);
|
||||||
const cdpProtocol = cdpInfo.parsed.protocol === "https:" ? "https" : "http";
|
const cdpProtocol = cdpInfo.parsed.protocol === "https:" ? "https" : "http";
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import path from "node:path";
|
|||||||
|
|
||||||
import type { BrowserProfileConfig, ClawdbotConfig } from "../config/config.js";
|
import type { BrowserProfileConfig, ClawdbotConfig } from "../config/config.js";
|
||||||
import { loadConfig, writeConfigFile } from "../config/config.js";
|
import { loadConfig, writeConfigFile } from "../config/config.js";
|
||||||
|
import { deriveDefaultBrowserCdpPortRange } from "../config/port-defaults.js";
|
||||||
import { resolveClawdUserDataDir } from "./chrome.js";
|
import { resolveClawdUserDataDir } from "./chrome.js";
|
||||||
import { parseHttpUrl, resolveProfile } from "./config.js";
|
import { parseHttpUrl, resolveProfile } from "./config.js";
|
||||||
import {
|
import {
|
||||||
@@ -79,7 +80,10 @@ export function createBrowserProfilesService(ctx: BrowserRouteContext) {
|
|||||||
profileConfig = { cdpUrl: parsed.normalized, color: profileColor };
|
profileConfig = { cdpUrl: parsed.normalized, color: profileColor };
|
||||||
} else {
|
} else {
|
||||||
const usedPorts = getUsedPorts(resolvedProfiles);
|
const usedPorts = getUsedPorts(resolvedProfiles);
|
||||||
const cdpPort = allocateCdpPort(usedPorts);
|
const range = deriveDefaultBrowserCdpPortRange(
|
||||||
|
state.resolved.controlPort,
|
||||||
|
);
|
||||||
|
const cdpPort = allocateCdpPort(usedPorts, range);
|
||||||
if (cdpPort === null) {
|
if (cdpPort === null) {
|
||||||
throw new Error("no available CDP ports in range");
|
throw new Error("no available CDP ports in range");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,6 +64,17 @@ describe("port allocation", () => {
|
|||||||
expect(allocateCdpPort(usedPorts)).toBe(CDP_PORT_RANGE_START);
|
expect(allocateCdpPort(usedPorts)).toBe(CDP_PORT_RANGE_START);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("allocates within an explicit range", () => {
|
||||||
|
const usedPorts = new Set<number>();
|
||||||
|
expect(allocateCdpPort(usedPorts, { start: 20000, end: 20002 })).toBe(
|
||||||
|
20000,
|
||||||
|
);
|
||||||
|
usedPorts.add(20000);
|
||||||
|
expect(allocateCdpPort(usedPorts, { start: 20000, end: 20002 })).toBe(
|
||||||
|
20001,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("skips used ports and returns next available", () => {
|
it("skips used ports and returns next available", () => {
|
||||||
const usedPorts = new Set([CDP_PORT_RANGE_START, CDP_PORT_RANGE_START + 1]);
|
const usedPorts = new Set([CDP_PORT_RANGE_START, CDP_PORT_RANGE_START + 1]);
|
||||||
expect(allocateCdpPort(usedPorts)).toBe(CDP_PORT_RANGE_START + 2);
|
expect(allocateCdpPort(usedPorts)).toBe(CDP_PORT_RANGE_START + 2);
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* CDP port allocation for browser profiles.
|
* CDP port allocation for browser profiles.
|
||||||
*
|
*
|
||||||
* Port range: 18800-18899 (100 profiles max)
|
* Default port range: 18800-18899 (100 profiles max)
|
||||||
* Ports are allocated once at profile creation and persisted in config.
|
* Ports are allocated once at profile creation and persisted in config.
|
||||||
|
* Multi-instance: callers may pass an explicit range to avoid collisions.
|
||||||
*
|
*
|
||||||
* Reserved ports (do not use for CDP):
|
* Reserved ports (do not use for CDP):
|
||||||
* 18789 - Gateway WebSocket
|
* 18789 - Gateway WebSocket
|
||||||
@@ -21,8 +22,22 @@ export function isValidProfileName(name: string): boolean {
|
|||||||
return PROFILE_NAME_REGEX.test(name);
|
return PROFILE_NAME_REGEX.test(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function allocateCdpPort(usedPorts: Set<number>): number | null {
|
export function allocateCdpPort(
|
||||||
for (let port = CDP_PORT_RANGE_START; port <= CDP_PORT_RANGE_END; port++) {
|
usedPorts: Set<number>,
|
||||||
|
range?: { start: number; end: number },
|
||||||
|
): number | null {
|
||||||
|
const start = range?.start ?? CDP_PORT_RANGE_START;
|
||||||
|
const end = range?.end ?? CDP_PORT_RANGE_END;
|
||||||
|
if (
|
||||||
|
!Number.isFinite(start) ||
|
||||||
|
!Number.isFinite(end) ||
|
||||||
|
start <= 0 ||
|
||||||
|
end <= 0
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (start > end) return null;
|
||||||
|
for (let port = start; port <= end; port++) {
|
||||||
if (!usedPorts.has(port)) return port;
|
if (!usedPorts.has(port)) return port;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -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", () => ({
|
vi.mock("../gateway/call.js", () => ({
|
||||||
callGateway: (opts: unknown) => callGateway(opts),
|
callGateway: (opts: unknown) => callGateway(opts),
|
||||||
randomIdempotencyKey: () => randomIdempotencyKey(),
|
randomIdempotencyKey: () => randomIdempotencyKey(),
|
||||||
@@ -205,4 +227,26 @@ describe("gateway-cli coverage", () => {
|
|||||||
process.removeListener("SIGINT", listener);
|
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
|
program
|
||||||
.command("gateway-daemon")
|
.command("gateway-daemon")
|
||||||
.description("Run the WebSocket Gateway as a long-lived 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(
|
.option(
|
||||||
"--bind <mode>",
|
"--bind <mode>",
|
||||||
'Bind mode ("loopback"|"tailnet"|"lan"|"auto"). Defaults to config gateway.bind (or loopback).',
|
'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
|
const gateway = program
|
||||||
.command("gateway")
|
.command("gateway")
|
||||||
.description("Run the WebSocket Gateway")
|
.description("Run the WebSocket Gateway")
|
||||||
.option("--port <port>", "Port for the gateway WebSocket", "18789")
|
.option("--port <port>", "Port for the gateway WebSocket")
|
||||||
.option(
|
.option(
|
||||||
"--bind <mode>",
|
"--bind <mode>",
|
||||||
'Bind mode ("loopback"|"tailnet"|"lan"|"auto"). Defaults to config gateway.bind (or loopback).',
|
'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 =
|
const TAGLINE =
|
||||||
"Send, receive, and auto-reply on WhatsApp (web) and Telegram (bot).";
|
"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 formatIntroLine = (version: string, rich = true) => {
|
||||||
const base = `📡 clawdbot ${version} — ${TAGLINE}`;
|
const base = `📡 clawdbot ${version} — ${TAGLINE}`;
|
||||||
@@ -96,6 +107,10 @@ export function buildProgram() {
|
|||||||
"Send via your web session and print JSON result.",
|
"Send via your web session and print JSON result.",
|
||||||
],
|
],
|
||||||
["clawdbot gateway --port 18789", "Run the WebSocket Gateway locally."],
|
["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",
|
"clawdbot gateway --force",
|
||||||
"Kill anything bound to the default gateway port, then start it.",
|
"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) });
|
||||||
|
}
|
||||||
@@ -330,7 +330,7 @@ export async function setupProviders(
|
|||||||
await prompter.note(
|
await prompter.note(
|
||||||
[
|
[
|
||||||
"Scan the QR with WhatsApp on your phone.",
|
"Scan the QR with WhatsApp on your phone.",
|
||||||
"Credentials are stored under ~/.clawdbot/credentials/ for future runs.",
|
`Credentials are stored under ${resolveWebAuthDir()}/ for future runs.`,
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
"WhatsApp linking",
|
"WhatsApp linking",
|
||||||
);
|
);
|
||||||
|
|||||||
49
src/config/port-defaults.ts
Normal file
49
src/config/port-defaults.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
export type PortRange = { start: number; end: number };
|
||||||
|
|
||||||
|
function isValidPort(port: number): boolean {
|
||||||
|
return Number.isFinite(port) && port > 0 && port <= 65535;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampPort(port: number, fallback: number): number {
|
||||||
|
return isValidPort(port) ? port : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function derivePort(base: number, offset: number, fallback: number): number {
|
||||||
|
return clampPort(base + offset, fallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_BRIDGE_PORT = 18790;
|
||||||
|
export const DEFAULT_BROWSER_CONTROL_PORT = 18791;
|
||||||
|
export const DEFAULT_CANVAS_HOST_PORT = 18793;
|
||||||
|
export const DEFAULT_BROWSER_CDP_PORT_RANGE_START = 18800;
|
||||||
|
export const DEFAULT_BROWSER_CDP_PORT_RANGE_END = 18899;
|
||||||
|
|
||||||
|
export function deriveDefaultBridgePort(gatewayPort: number): number {
|
||||||
|
return derivePort(gatewayPort, 1, DEFAULT_BRIDGE_PORT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveDefaultBrowserControlPort(gatewayPort: number): number {
|
||||||
|
return derivePort(gatewayPort, 2, DEFAULT_BROWSER_CONTROL_PORT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveDefaultCanvasHostPort(gatewayPort: number): number {
|
||||||
|
return derivePort(gatewayPort, 4, DEFAULT_CANVAS_HOST_PORT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveDefaultBrowserCdpPortRange(
|
||||||
|
browserControlPort: number,
|
||||||
|
): PortRange {
|
||||||
|
const start = derivePort(
|
||||||
|
browserControlPort,
|
||||||
|
9,
|
||||||
|
DEFAULT_BROWSER_CDP_PORT_RANGE_START,
|
||||||
|
);
|
||||||
|
const end = clampPort(
|
||||||
|
start +
|
||||||
|
(DEFAULT_BROWSER_CDP_PORT_RANGE_END -
|
||||||
|
DEFAULT_BROWSER_CDP_PORT_RANGE_START),
|
||||||
|
DEFAULT_BROWSER_CDP_PORT_RANGE_END,
|
||||||
|
);
|
||||||
|
if (end < start) return { start, end: start };
|
||||||
|
return { start, end };
|
||||||
|
}
|
||||||
20
src/entry.ts
Normal file
20
src/entry.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import process from "node:process";
|
||||||
|
|
||||||
|
import { applyCliProfileEnv, parseCliProfileArgs } from "./cli/profile.js";
|
||||||
|
|
||||||
|
const parsed = parseCliProfileArgs(process.argv);
|
||||||
|
if (!parsed.ok) {
|
||||||
|
// Keep it simple; Commander will handle rich help/errors after we strip flags.
|
||||||
|
console.error(`[clawdbot] ${parsed.error}`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.profile) {
|
||||||
|
applyCliProfileEnv({ profile: parsed.profile });
|
||||||
|
// Keep Commander and ad-hoc argv checks consistent.
|
||||||
|
process.argv = parsed.argv;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { runCli } = await import("./cli/run-main.js");
|
||||||
|
await runCli(process.argv);
|
||||||
@@ -28,6 +28,10 @@ import {
|
|||||||
STATE_DIR_CLAWDBOT,
|
STATE_DIR_CLAWDBOT,
|
||||||
writeConfigFile,
|
writeConfigFile,
|
||||||
} from "../config/config.js";
|
} from "../config/config.js";
|
||||||
|
import {
|
||||||
|
deriveDefaultBridgePort,
|
||||||
|
deriveDefaultCanvasHostPort,
|
||||||
|
} from "../config/port-defaults.js";
|
||||||
import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
|
import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
|
||||||
import { runCronIsolatedAgentTurn } from "../cron/isolated-agent.js";
|
import { runCronIsolatedAgentTurn } from "../cron/isolated-agent.js";
|
||||||
import { appendCronRunLog, resolveCronRunLogPath } from "../cron/run-log.js";
|
import { appendCronRunLog, resolveCronRunLogPath } from "../cron/run-log.js";
|
||||||
@@ -355,6 +359,9 @@ export async function startGatewayServer(
|
|||||||
port = 18789,
|
port = 18789,
|
||||||
opts: GatewayServerOptions = {},
|
opts: GatewayServerOptions = {},
|
||||||
): Promise<GatewayServer> {
|
): Promise<GatewayServer> {
|
||||||
|
// Ensure all default port derivations (browser/bridge/canvas) see the actual runtime port.
|
||||||
|
process.env.CLAWDBOT_GATEWAY_PORT = String(port);
|
||||||
|
|
||||||
const configSnapshot = await readConfigFileSnapshot();
|
const configSnapshot = await readConfigFileSnapshot();
|
||||||
if (configSnapshot.legacyIssues.length > 0) {
|
if (configSnapshot.legacyIssues.length > 0) {
|
||||||
if (isNixMode) {
|
if (isNixMode) {
|
||||||
@@ -819,9 +826,11 @@ export async function startGatewayServer(
|
|||||||
}
|
}
|
||||||
if (process.env.CLAWDBOT_BRIDGE_PORT !== undefined) {
|
if (process.env.CLAWDBOT_BRIDGE_PORT !== undefined) {
|
||||||
const parsed = Number.parseInt(process.env.CLAWDBOT_BRIDGE_PORT, 10);
|
const parsed = Number.parseInt(process.env.CLAWDBOT_BRIDGE_PORT, 10);
|
||||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 18790;
|
return Number.isFinite(parsed) && parsed > 0
|
||||||
|
? parsed
|
||||||
|
: deriveDefaultBridgePort(port);
|
||||||
}
|
}
|
||||||
return 18790;
|
return deriveDefaultBridgePort(port);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const bridgeHost = (() => {
|
const bridgeHost = (() => {
|
||||||
@@ -848,9 +857,14 @@ export async function startGatewayServer(
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
const canvasHostPort = (() => {
|
const canvasHostPort = (() => {
|
||||||
|
if (process.env.CLAWDBOT_CANVAS_HOST_PORT !== undefined) {
|
||||||
|
const parsed = Number.parseInt(process.env.CLAWDBOT_CANVAS_HOST_PORT, 10);
|
||||||
|
if (Number.isFinite(parsed) && parsed > 0) return parsed;
|
||||||
|
return deriveDefaultCanvasHostPort(port);
|
||||||
|
}
|
||||||
const configured = cfgAtStart.canvasHost?.port;
|
const configured = cfgAtStart.canvasHost?.port;
|
||||||
if (typeof configured === "number" && configured > 0) return configured;
|
if (typeof configured === "number" && configured > 0) return configured;
|
||||||
return 18793;
|
return deriveDefaultCanvasHostPort(port);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
if (canvasHostEnabled && bridgeEnabled && bridgeHost) {
|
if (canvasHostEnabled && bridgeEnabled && bridgeHost) {
|
||||||
|
|||||||
13
src/utils.ts
13
src/utils.ts
@@ -104,6 +104,15 @@ export function resolveUserPath(input: string): string {
|
|||||||
return path.resolve(trimmed);
|
return path.resolve(trimmed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function resolveConfigDir(
|
||||||
|
env: NodeJS.ProcessEnv = process.env,
|
||||||
|
homedir: () => string = os.homedir,
|
||||||
|
): string {
|
||||||
|
const override = env.CLAWDBOT_STATE_DIR?.trim();
|
||||||
|
if (override) return resolveUserPath(override);
|
||||||
|
return path.join(homedir(), ".clawdbot");
|
||||||
|
}
|
||||||
|
|
||||||
export function resolveHomeDir(): string | undefined {
|
export function resolveHomeDir(): string | undefined {
|
||||||
const envHome = process.env.HOME?.trim();
|
const envHome = process.env.HOME?.trim();
|
||||||
if (envHome) return envHome;
|
if (envHome) return envHome;
|
||||||
@@ -133,5 +142,5 @@ export function shortenHomeInString(input: string): string {
|
|||||||
return input.split(home).join("~");
|
return input.split(home).join("~");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fixed configuration root; legacy ~/.clawdbot is no longer used.
|
// Configuration root; can be overridden via CLAWDBOT_STATE_DIR.
|
||||||
export const CONFIG_DIR = path.join(os.homedir(), ".clawdbot");
|
export const CONFIG_DIR = resolveConfigDir();
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import fsSync from "node:fs";
|
import fsSync from "node:fs";
|
||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import {
|
import {
|
||||||
DisconnectReason,
|
DisconnectReason,
|
||||||
@@ -17,11 +16,16 @@ import { danger, info, success } from "../globals.js";
|
|||||||
import { getChildLogger, toPinoLikeLogger } from "../logging.js";
|
import { getChildLogger, toPinoLikeLogger } from "../logging.js";
|
||||||
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
|
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
|
||||||
import type { Provider } from "../utils.js";
|
import type { Provider } from "../utils.js";
|
||||||
import { CONFIG_DIR, ensureDir, jidToE164 } from "../utils.js";
|
import {
|
||||||
|
CONFIG_DIR,
|
||||||
|
ensureDir,
|
||||||
|
jidToE164,
|
||||||
|
resolveConfigDir,
|
||||||
|
} from "../utils.js";
|
||||||
import { VERSION } from "../version.js";
|
import { VERSION } from "../version.js";
|
||||||
|
|
||||||
export function resolveWebAuthDir() {
|
export function resolveWebAuthDir() {
|
||||||
return path.join(os.homedir(), ".clawdbot", "credentials");
|
return path.join(resolveConfigDir(), "credentials");
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveWebCredsPath() {
|
function resolveWebCredsPath() {
|
||||||
|
|||||||
Reference in New Issue
Block a user