refactor: rename to openclaw

This commit is contained in:
Peter Steinberger committed 2026-01-30 03:16:21 +01:00
1 parent 4583f88626
commit 9a7160786a
2357 files changed
+16688 -16788

No files matched your search

+5 -5
View File
@@ -12,7 +12,7 @@ vi.mock("./agent.js", () => ({
agentCommand: vi.fn(),
}));
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import * as configModule from "../config/config.js";
import { callGateway } from "../gateway/call.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -27,7 +27,7 @@ const runtime: RuntimeEnv = {
const configSpy = vi.spyOn(configModule, "loadConfig");
function mockConfig(storePath: string, overrides?: Partial<MoltbotConfig>) {
function mockConfig(storePath: string, overrides?: Partial<OpenClawConfig>) {
configSpy.mockReturnValue({
agents: {
defaults: {
@@ -50,7 +50,7 @@ beforeEach(() => {
describe("agentCliCommand", () => {
it("uses gateway by default", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-agent-cli-"));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-cli-"));
const store = path.join(dir, "sessions.json");
mockConfig(store);
@@ -75,7 +75,7 @@ describe("agentCliCommand", () => {
});
it("falls back to embedded agent when gateway fails", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-agent-cli-"));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-cli-"));
const store = path.join(dir, "sessions.json");
mockConfig(store);
@@ -97,7 +97,7 @@ describe("agentCliCommand", () => {
});
it("skips gateway when --local is set", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-agent-cli-"));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-cli-"));
const store = path.join(dir, "sessions.json");
mockConfig(store);
+1 -1
View File
@@ -93,7 +93,7 @@ export async function agentViaGatewayCommand(opts: AgentCliOpts, runtime: Runtim
const knownAgents = listAgentIds(cfg);
if (!knownAgents.includes(agentId)) {
throw new Error(
`Unknown agent id "${agentIdRaw}". Use "${formatCliCommand("moltbot agents list")}" to see configured agents.`,
`Unknown agent id "${agentIdRaw}". Use "${formatCliCommand("openclaw agents list")}" to see configured agents.`,
);
}
}
+8 -8
View File
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { CliDeps } from "../cli/deps.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import type { SessionEntry } from "../config/sessions.js";
@@ -37,7 +37,7 @@ describe("deliverAgentCommandResult", () => {
});
it("prefers explicit accountId for outbound delivery", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
@@ -74,7 +74,7 @@ describe("deliverAgentCommandResult", () => {
});
it("falls back to session accountId for implicit delivery", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
@@ -110,7 +110,7 @@ describe("deliverAgentCommandResult", () => {
});
it("does not infer accountId for explicit delivery targets", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
@@ -150,7 +150,7 @@ describe("deliverAgentCommandResult", () => {
});
it("skips session accountId when channel differs", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
@@ -186,7 +186,7 @@ describe("deliverAgentCommandResult", () => {
});
it("uses session last channel when none is provided", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
@@ -221,7 +221,7 @@ describe("deliverAgentCommandResult", () => {
});
it("uses reply overrides for delivery routing", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
@@ -261,7 +261,7 @@ describe("deliverAgentCommandResult", () => {
});
it("prefixes nested agent outputs with context", async () => {
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
const deps = {} as CliDeps;
const runtime = {
log: vi.fn(),
+5 -5
View File
@@ -16,7 +16,7 @@ vi.mock("../agents/model-catalog.js", () => ({
import { loadModelCatalog } from "../agents/model-catalog.js";
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import * as configModule from "../config/config.js";
import { emitAgentEvent, onAgentEvent } from "../infra/agent-events.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -38,14 +38,14 @@ const runtime: RuntimeEnv = {
const configSpy = vi.spyOn(configModule, "loadConfig");
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
return withTempHomeBase(fn, { prefix: "moltbot-agent-" });
return withTempHomeBase(fn, { prefix: "openclaw-agent-" });
}
function mockConfig(
home: string,
storePath: string,
agentOverrides?: Partial<NonNullable<NonNullable<MoltbotConfig["agents"]>["defaults"]>>,
telegramOverrides?: Partial<NonNullable<MoltbotConfig["telegram"]>>,
agentOverrides?: Partial<NonNullable<NonNullable<OpenClawConfig["agents"]>["defaults"]>>,
telegramOverrides?: Partial<NonNullable<OpenClawConfig["telegram"]>>,
agentsList?: Array<{ id: string; default?: boolean }>,
) {
configSpy.mockReturnValue({
@@ -53,7 +53,7 @@ function mockConfig(
defaults: {
model: { primary: "anthropic/claude-opus-4-5" },
models: { "anthropic/claude-opus-4-5": {} },
workspace: path.join(home, "clawd"),
workspace: path.join(home, "openclaw"),
...agentOverrides,
},
list: agentsList,
+1 -1
View File
@@ -78,7 +78,7 @@ export async function agentCommand(
const knownAgents = listAgentIds(cfg);
if (!knownAgents.includes(agentIdOverride)) {
throw new Error(
`Unknown agent id "${agentIdOverrideRaw}". Use "${formatCliCommand("moltbot agents list")}" to see configured agents.`,
`Unknown agent id "${agentIdOverrideRaw}". Use "${formatCliCommand("openclaw agents list")}" to see configured agents.`,
);
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { AGENT_LANE_NESTED } from "../../agents/lanes.js";
import { getChannelPlugin, normalizeChannelId } from "../../channels/plugins/index.js";
import { createOutboundSendDeps, type CliDeps } from "../../cli/outbound-send-deps.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import type { SessionEntry } from "../../config/sessions.js";
import { deliverOutboundPayloads } from "../../infra/outbound/deliver.js";
import { buildOutboundResultEnvelope } from "../../infra/outbound/envelope.js";
@@ -46,7 +46,7 @@ function logNestedOutput(runtime: RuntimeEnv, opts: AgentCommandOpts, output: st
}
export async function deliverAgentCommandResult(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
deps: CliDeps;
runtime: RuntimeEnv;
opts: AgentCommandOpts;
+2 -2
View File
@@ -3,7 +3,7 @@ import { lookupContextTokens } from "../../agents/context.js";
import { DEFAULT_CONTEXT_TOKENS } from "../../agents/defaults.js";
import { isCliProvider } from "../../agents/model-selection.js";
import { hasNonzeroUsage } from "../../agents/usage.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import { type SessionEntry, updateSessionStore } from "../../config/sessions.js";
type RunResult = Awaited<
@@ -11,7 +11,7 @@ type RunResult = Awaited<
>;
export async function updateSessionStoreAfterAgentRun(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
contextTokensOverride?: number;
sessionId: string;
sessionKey: string;
+3 -3
View File
@@ -7,7 +7,7 @@ import {
type ThinkLevel,
type VerboseLevel,
} from "../../auto-reply/thinking.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import {
evaluateSessionFreshness,
loadSessionStore,
@@ -40,7 +40,7 @@ type SessionKeyResolution = {
};
export function resolveSessionKeyForRequest(opts: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
to?: string;
sessionId?: string;
sessionKey?: string;
@@ -81,7 +81,7 @@ export function resolveSessionKeyForRequest(opts: {
}
export function resolveSession(opts: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
to?: string;
sessionId?: string;
sessionKey?: string;
+1 -1
View File
@@ -25,7 +25,7 @@ const runtime: RuntimeEnv = {
};
const baseSnapshot = {
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
+6 -6
View File
@@ -1,7 +1,7 @@
import { resolveChannelDefaultAccountId } from "../channels/plugins/helpers.js";
import { getChannelPlugin, normalizeChannelId } from "../channels/plugins/index.js";
import type { ChannelId } from "../channels/plugins/types.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { AgentBinding } from "../config/types.js";
import { DEFAULT_ACCOUNT_ID, normalizeAgentId } from "../routing/session-key.js";
import type { ChannelChoice } from "./onboard-types.js";
@@ -29,10 +29,10 @@ export function describeBinding(binding: AgentBinding) {
}
export function applyAgentBindings(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
bindings: AgentBinding[],
): {
config: MoltbotConfig;
config: OpenClawConfig;
added: AgentBinding[];
skipped: AgentBinding[];
conflicts: Array<{ binding: AgentBinding; existingAgentId: string }>;
@@ -81,7 +81,7 @@ export function applyAgentBindings(
};
}
function resolveDefaultAccountId(cfg: MoltbotConfig, provider: ChannelId): string {
function resolveDefaultAccountId(cfg: OpenClawConfig, provider: ChannelId): string {
const plugin = getChannelPlugin(provider);
if (!plugin) return DEFAULT_ACCOUNT_ID;
return resolveChannelDefaultAccountId({ plugin, cfg });
@@ -90,7 +90,7 @@ function resolveDefaultAccountId(cfg: MoltbotConfig, provider: ChannelId): strin
export function buildChannelBindings(params: {
agentId: string;
selection: ChannelChoice[];
config: MoltbotConfig;
config: OpenClawConfig;
accountIds?: Partial<Record<ChannelChoice, string>>;
}): AgentBinding[] {
const bindings: AgentBinding[] = [];
@@ -114,7 +114,7 @@ export function buildChannelBindings(params: {
export function parseBindingSpecs(params: {
agentId: string;
specs?: string[];
config: MoltbotConfig;
config: OpenClawConfig;
}): { bindings: AgentBinding[]; errors: string[] } {
const bindings: AgentBinding[] = [];
const errors: string[] = [];
+3 -3
View File
@@ -1,5 +1,5 @@
import { formatCliCommand } from "../cli/command-format.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { readConfigFileSnapshot } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -7,7 +7,7 @@ export function createQuietRuntime(runtime: RuntimeEnv): RuntimeEnv {
return { ...runtime, log: () => {} };
}
export async function requireValidConfig(runtime: RuntimeEnv): Promise<MoltbotConfig | null> {
export async function requireValidConfig(runtime: RuntimeEnv): Promise<OpenClawConfig | null> {
const snapshot = await readConfigFileSnapshot();
if (snapshot.exists && !snapshot.valid) {
const issues =
@@ -15,7 +15,7 @@ export async function requireValidConfig(runtime: RuntimeEnv): Promise<MoltbotCo
? snapshot.issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")
: "Unknown validation issue.";
runtime.error(`Config invalid:\n${issues}`);
runtime.error(`Fix the config or run ${formatCliCommand("moltbot doctor")}.`);
runtime.error(`Fix the config or run ${formatCliCommand("openclaw doctor")}.`);
runtime.exit(1);
return null;
}
+2 -2
View File
@@ -172,7 +172,7 @@ export async function agentsAddCommand(
const prompter = createClackPrompter();
try {
await prompter.intro("Add Moltbot agent");
await prompter.intro("Add OpenClaw agent");
const name =
nameInput ??
(await prompter.text({
@@ -326,7 +326,7 @@ export async function agentsAddCommand(
await prompter.note(
[
"Routing unchanged. Add bindings when you're ready.",
"Docs: https://docs.molt.bot/concepts/multi-agent",
"Docs: https://docs.openclaw.ai/concepts/multi-agent",
].join("\n"),
"Routing",
);
+1 -1
View File
@@ -118,7 +118,7 @@ export async function agentsListCommand(
const lines = ["Agents:", ...summaries.map(formatSummary)];
lines.push("Routing rules map channel/account/peer to an agent. Use --bindings for full rules.");
lines.push(
`Channel status reflects local config/creds. For live health: ${formatCliCommand("moltbot channels status --probe")}.`,
`Channel status reflects local config/creds. For live health: ${formatCliCommand("openclaw channels status --probe")}.`,
);
runtime.log(lines.join("\n"));
}
+10 -10
View File
@@ -9,7 +9,7 @@ import {
loadAgentIdentityFromWorkspace,
parseIdentityMarkdown as parseIdentityMarkdownFile,
} from "../agents/identity-file.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { normalizeAgentId } from "../routing/session-key.js";
export type AgentSummary = {
@@ -28,11 +28,11 @@ export type AgentSummary = {
isDefault: boolean;
};
type AgentEntry = NonNullable<NonNullable<MoltbotConfig["agents"]>["list"]>[number];
type AgentEntry = NonNullable<NonNullable<OpenClawConfig["agents"]>["list"]>[number];
export type AgentIdentity = AgentIdentityFile;
export function listAgentEntries(cfg: MoltbotConfig): AgentEntry[] {
export function listAgentEntries(cfg: OpenClawConfig): AgentEntry[] {
const list = cfg.agents?.list;
if (!Array.isArray(list)) return [];
return list.filter((entry): entry is AgentEntry => Boolean(entry && typeof entry === "object"));
@@ -43,14 +43,14 @@ export function findAgentEntryIndex(list: AgentEntry[], agentId: string): number
return list.findIndex((entry) => normalizeAgentId(entry.id) === id);
}
function resolveAgentName(cfg: MoltbotConfig, agentId: string) {
function resolveAgentName(cfg: OpenClawConfig, agentId: string) {
const entry = listAgentEntries(cfg).find(
(agent) => normalizeAgentId(agent.id) === normalizeAgentId(agentId),
);
return entry?.name?.trim() || undefined;
}
function resolveAgentModel(cfg: MoltbotConfig, agentId: string) {
function resolveAgentModel(cfg: OpenClawConfig, agentId: string) {
const entry = listAgentEntries(cfg).find(
(agent) => normalizeAgentId(agent.id) === normalizeAgentId(agentId),
);
@@ -78,7 +78,7 @@ export function loadAgentIdentity(workspace: string): AgentIdentity | null {
return identityHasValues(parsed) ? parsed : null;
}
export function buildAgentSummaries(cfg: MoltbotConfig): AgentSummary[] {
export function buildAgentSummaries(cfg: OpenClawConfig): AgentSummary[] {
const defaultAgentId = normalizeAgentId(resolveDefaultAgentId(cfg));
const configuredAgents = listAgentEntries(cfg);
const orderedIds =
@@ -122,7 +122,7 @@ export function buildAgentSummaries(cfg: MoltbotConfig): AgentSummary[] {
}
export function applyAgentConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
params: {
agentId: string;
name?: string;
@@ -130,7 +130,7 @@ export function applyAgentConfig(
agentDir?: string;
model?: string;
},
): MoltbotConfig {
): OpenClawConfig {
const agentId = normalizeAgentId(params.agentId);
const name = params.name?.trim();
const list = listAgentEntries(cfg);
@@ -162,10 +162,10 @@ export function applyAgentConfig(
}
export function pruneAgentConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
agentId: string,
): {
config: MoltbotConfig;
config: OpenClawConfig;
removedBindings: number;
removedAllow: number;
} {
+13 -13
View File
@@ -29,7 +29,7 @@ const runtime: RuntimeEnv = {
};
const baseSnapshot = {
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -49,16 +49,16 @@ describe("agents set-identity command", () => {
});
it("sets identity from workspace IDENTITY.md", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-identity-"));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-identity-"));
const workspace = path.join(root, "work");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(
path.join(workspace, "IDENTITY.md"),
[
"- Name: Clawd",
"- Name: OpenClaw",
"- Creature: helpful sloth",
"- Emoji: :)",
"- Avatar: avatars/clawd.png",
"- Avatar: avatars/openclaw.png",
"",
].join("\n"),
"utf-8",
@@ -84,15 +84,15 @@ describe("agents set-identity command", () => {
};
const main = written.agents?.list?.find((entry) => entry.id === "main");
expect(main?.identity).toEqual({
name: "Clawd",
name: "OpenClaw",
theme: "helpful sloth",
emoji: ":)",
avatar: "avatars/clawd.png",
avatar: "avatars/openclaw.png",
});
});
it("errors when multiple agents match the same workspace", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-identity-"));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-identity-"));
const workspace = path.join(root, "shared");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(path.join(workspace, "IDENTITY.md"), "- Name: Echo\n", "utf-8");
@@ -117,16 +117,16 @@ describe("agents set-identity command", () => {
});
it("overrides identity file values with explicit flags", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-identity-"));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-identity-"));
const workspace = path.join(root, "work");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(
path.join(workspace, "IDENTITY.md"),
[
"- Name: Clawd",
"- Name: OpenClaw",
"- Theme: space lobster",
"- Emoji: :)",
"- Avatar: avatars/clawd.png",
"- Avatar: avatars/openclaw.png",
"",
].join("\n"),
"utf-8",
@@ -161,7 +161,7 @@ describe("agents set-identity command", () => {
});
it("reads identity from an explicit IDENTITY.md path", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-identity-"));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-identity-"));
const workspace = path.join(root, "work");
const identityPath = path.join(workspace, "IDENTITY.md");
await fs.mkdir(workspace, { recursive: true });
@@ -197,7 +197,7 @@ describe("agents set-identity command", () => {
});
it("accepts avatar-only identity from IDENTITY.md", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-identity-"));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-identity-"));
const workspace = path.join(root, "work");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(
@@ -243,7 +243,7 @@ describe("agents set-identity command", () => {
});
it("errors when identity data is missing", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-identity-"));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-identity-"));
const workspace = path.join(root, "work");
await fs.mkdir(workspace, { recursive: true });
+6 -6
View File
@@ -5,7 +5,7 @@ import {
normalizeChannelId,
} from "../channels/plugins/index.js";
import type { ChannelId } from "../channels/plugins/types.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { AgentBinding } from "../config/types.js";
import { DEFAULT_ACCOUNT_ID } from "../routing/session-key.js";
@@ -43,7 +43,7 @@ function formatProviderState(entry: ProviderAccountStatus): string {
}
export async function buildProviderStatusIndex(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
): Promise<Map<string, ProviderAccountStatus>> {
const map = new Map<string, ProviderAccountStatus>();
@@ -91,13 +91,13 @@ export async function buildProviderStatusIndex(
return map;
}
function resolveDefaultAccountId(cfg: MoltbotConfig, provider: ChannelId): string {
function resolveDefaultAccountId(cfg: OpenClawConfig, provider: ChannelId): string {
const plugin = getChannelPlugin(provider);
if (!plugin) return DEFAULT_ACCOUNT_ID;
return resolveChannelDefaultAccountId({ plugin, cfg });
}
function shouldShowProviderEntry(entry: ProviderAccountStatus, cfg: MoltbotConfig): boolean {
function shouldShowProviderEntry(entry: ProviderAccountStatus, cfg: OpenClawConfig): boolean {
const plugin = getChannelPlugin(entry.provider);
if (!plugin) return Boolean(entry.configured);
if (plugin.meta.showConfigured === false) {
@@ -116,7 +116,7 @@ function formatProviderEntry(entry: ProviderAccountStatus): string {
return `${label}: ${formatProviderState(entry)}`;
}
export function summarizeBindings(cfg: MoltbotConfig, bindings: AgentBinding[]): string[] {
export function summarizeBindings(cfg: OpenClawConfig, bindings: AgentBinding[]): string[] {
if (bindings.length === 0) return [];
const seen = new Map<string, string>();
for (const binding of bindings) {
@@ -137,7 +137,7 @@ export function summarizeBindings(cfg: MoltbotConfig, bindings: AgentBinding[]):
export function listProvidersForAgent(params: {
summaryIsDefault: boolean;
cfg: MoltbotConfig;
cfg: OpenClawConfig;
bindings: AgentBinding[];
providerStatus: Map<string, ProviderAccountStatus>;
}): string[] {
+6 -6
View File
@@ -3,7 +3,7 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import {
applyAgentBindings,
applyAgentConfig,
@@ -13,7 +13,7 @@ import {
describe("agents helpers", () => {
it("buildAgentSummaries includes default + configured agents", () => {
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
agents: {
defaults: {
workspace: "/main-ws",
@@ -45,7 +45,7 @@ describe("agents helpers", () => {
const work = summaries.find((summary) => summary.id === "work");
expect(main).toBeTruthy();
expect(main?.workspace).toBe(path.join(os.homedir(), "clawd-main"));
expect(main?.workspace).toBe(path.join(os.homedir(), ".openclaw", "workspace-main"));
expect(main?.bindings).toBe(1);
expect(main?.model).toBe("anthropic/claude");
expect(main?.agentDir.endsWith(path.join("agents", "main", "agent"))).toBe(true);
@@ -59,7 +59,7 @@ describe("agents helpers", () => {
});
it("applyAgentConfig merges updates", () => {
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
agents: {
list: [{ id: "work", workspace: "/old-ws", model: "anthropic/claude" }],
},
@@ -80,7 +80,7 @@ describe("agents helpers", () => {
});
it("applyAgentBindings skips duplicates and reports conflicts", () => {
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
bindings: [
{
agentId: "main",
@@ -111,7 +111,7 @@ describe("agents helpers", () => {
});
it("pruneAgentConfig removes agent, bindings, and allowlist entries", () => {
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
agents: {
list: [
{ id: "work", default: true, workspace: "/work-ws" },
+1 -1
View File
@@ -138,7 +138,7 @@ export async function applyAuthChoiceOpenAI(
spin.stop("OpenAI OAuth failed");
params.runtime.error(String(err));
await params.prompter.note(
"Trouble with OAuth? See https://docs.molt.bot/start/faq",
"Trouble with OAuth? See https://docs.openclaw.ai/start/faq",
"OAuth help",
);
}
@@ -1,4 +1,4 @@
import { resolveMoltbotAgentDir } from "../agents/agent-paths.js";
import { resolveOpenClawAgentDir } from "../agents/agent-paths.js";
import {
resolveDefaultAgentId,
resolveAgentDir,
@@ -7,7 +7,7 @@ import {
import { upsertAuthProfile } from "../agents/auth-profiles.js";
import { normalizeProviderId } from "../agents/model-selection.js";
import { resolveDefaultAgentWorkspaceDir } from "../agents/workspace.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { enablePluginInConfig } from "../plugins/enable.js";
import { resolvePluginProviders } from "../plugins/providers.js";
import type { ProviderAuthMethod, ProviderPlugin } from "../plugins/types.js";
@@ -72,7 +72,7 @@ function mergeConfigPatch<T>(base: T, patch: unknown): T {
return next as T;
}
function applyDefaultModel(cfg: MoltbotConfig, model: string): MoltbotConfig {
function applyDefaultModel(cfg: OpenClawConfig, model: string): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[model] = models[model] ?? {};
@@ -115,7 +115,7 @@ export async function applyAuthChoicePluginProvider(
const defaultAgentId = resolveDefaultAgentId(nextConfig);
const agentDir =
params.agentDir ??
(agentId === defaultAgentId ? resolveMoltbotAgentDir() : resolveAgentDir(nextConfig, agentId));
(agentId === defaultAgentId ? resolveOpenClawAgentDir() : resolveAgentDir(nextConfig, agentId));
const workspaceDir =
resolveAgentWorkspaceDir(nextConfig, agentId) ?? resolveDefaultAgentWorkspaceDir();
+3 -3
View File
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { applyAuthChoiceAnthropic } from "./auth-choice.apply.anthropic.js";
@@ -15,7 +15,7 @@ import type { AuthChoice } from "./onboard-types.js";
export type ApplyAuthChoiceParams = {
authChoice: AuthChoice;
config: MoltbotConfig;
config: OpenClawConfig;
prompter: WizardPrompter;
runtime: RuntimeEnv;
agentDir?: string;
@@ -28,7 +28,7 @@ export type ApplyAuthChoiceParams = {
};
export type ApplyAuthChoiceResult = {
config: MoltbotConfig;
config: OpenClawConfig;
agentModelOverride?: string;
};
+5 -5
View File
@@ -1,16 +1,16 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { WizardPrompter } from "../wizard/prompts.js";
export async function applyDefaultModelChoice(params: {
config: MoltbotConfig;
config: OpenClawConfig;
setDefaultModel: boolean;
defaultModel: string;
applyDefaultConfig: (config: MoltbotConfig) => MoltbotConfig;
applyProviderConfig: (config: MoltbotConfig) => MoltbotConfig;
applyDefaultConfig: (config: OpenClawConfig) => OpenClawConfig;
applyProviderConfig: (config: OpenClawConfig) => OpenClawConfig;
noteDefault?: string;
noteAgentModel: (model: string) => Promise<void>;
prompter: WizardPrompter;
}): Promise<{ config: MoltbotConfig; agentModelOverride?: string }> {
}): Promise<{ config: OpenClawConfig; agentModelOverride?: string }> {
if (params.setDefaultModel) {
const next = params.applyDefaultConfig(params.config);
if (params.noteDefault) {
+2 -2
View File
@@ -4,12 +4,12 @@ import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "../agents/defaults.js";
import { getCustomProviderApiKey, resolveEnvApiKey } from "../agents/model-auth.js";
import { loadModelCatalog } from "../agents/model-catalog.js";
import { resolveConfiguredModelRef } from "../agents/model-selection.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { OPENAI_CODEX_DEFAULT_MODEL } from "./openai-codex-model-default.js";
export async function warnIfModelConfigLooksOff(
config: MoltbotConfig,
config: OpenClawConfig,
prompter: WizardPrompter,
options?: { agentId?: string; agentDir?: string },
) {
+40 -40
View File
@@ -22,14 +22,14 @@ const noopAsync = async () => {};
const noop = () => {};
const authProfilePathFor = (agentDir: string) => path.join(agentDir, "auth-profiles.json");
const requireAgentDir = () => {
const agentDir = process.env.CLAWDBOT_AGENT_DIR;
if (!agentDir) throw new Error("CLAWDBOT_AGENT_DIR not set");
const agentDir = process.env.OPENCLAW_AGENT_DIR;
if (!agentDir) throw new Error("OPENCLAW_AGENT_DIR not set");
return agentDir;
};
describe("applyAuthChoice", () => {
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
const previousStateDir = process.env.OPENCLAW_STATE_DIR;
const previousAgentDir = process.env.OPENCLAW_AGENT_DIR;
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
const previousOpenrouterKey = process.env.OPENROUTER_API_KEY;
const previousAiGatewayKey = process.env.AI_GATEWAY_API_KEY;
@@ -45,14 +45,14 @@ describe("applyAuthChoice", () => {
tempStateDir = null;
}
if (previousStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = previousStateDir;
process.env.OPENCLAW_STATE_DIR = previousStateDir;
}
if (previousAgentDir === undefined) {
delete process.env.CLAWDBOT_AGENT_DIR;
delete process.env.OPENCLAW_AGENT_DIR;
} else {
process.env.CLAWDBOT_AGENT_DIR = previousAgentDir;
process.env.OPENCLAW_AGENT_DIR = previousAgentDir;
}
if (previousPiAgentDir === undefined) {
delete process.env.PI_CODING_AGENT_DIR;
@@ -82,10 +82,10 @@ describe("applyAuthChoice", () => {
});
it("prompts and writes MiniMax API key when selecting minimax-api", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
const text = vi.fn().mockResolvedValue("sk-minimax-test");
const select: WizardPrompter["select"] = vi.fn(
@@ -135,10 +135,10 @@ describe("applyAuthChoice", () => {
});
it("prompts and writes Synthetic API key when selecting synthetic-api-key", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
const text = vi.fn().mockResolvedValue("sk-synthetic-test");
const select: WizardPrompter["select"] = vi.fn(
@@ -188,10 +188,10 @@ describe("applyAuthChoice", () => {
});
it("sets default model when selecting github-copilot", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
const prompter: WizardPrompter = {
intro: vi.fn(noopAsync),
@@ -231,10 +231,10 @@ describe("applyAuthChoice", () => {
});
it("does not override the default model when selecting opencode-zen without setDefaultModel", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
const text = vi.fn().mockResolvedValue("sk-opencode-zen-test");
const select: WizardPrompter["select"] = vi.fn(
@@ -282,10 +282,10 @@ describe("applyAuthChoice", () => {
});
it("uses existing OPENROUTER_API_KEY when selecting openrouter-api-key", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
process.env.OPENROUTER_API_KEY = "sk-openrouter-test";
const text = vi.fn();
@@ -343,10 +343,10 @@ describe("applyAuthChoice", () => {
});
it("uses existing AI_GATEWAY_API_KEY when selecting ai-gateway-api-key", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
process.env.AI_GATEWAY_API_KEY = "gateway-test-key";
const text = vi.fn();
@@ -406,10 +406,10 @@ describe("applyAuthChoice", () => {
});
it("writes Chutes OAuth credentials when selecting chutes (remote/manual)", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
process.env.SSH_TTY = "1";
process.env.CHUTES_CLIENT_ID = "cid_test";
@@ -493,10 +493,10 @@ describe("applyAuthChoice", () => {
});
it("writes Qwen credentials when selecting qwen-portal", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
resolvePluginProviders.mockReturnValue([
{
@@ -50,7 +50,7 @@ const runtime: RuntimeEnv = {
};
const baseSnapshot = {
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -370,7 +370,7 @@ describe("channels command", () => {
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/Message Content Intent is disabled/i);
expect(lines.join("\n")).toMatch(/Run: (?:moltbot|moltbot)( --profile isolated)? doctor/);
expect(lines.join("\n")).toMatch(/Run: (?:openclaw|openclaw)( --profile isolated)? doctor/);
});
it("surfaces Discord permission audit issues in channels status output", () => {
@@ -425,12 +425,12 @@ describe("channels command", () => {
accountId: "default",
enabled: true,
configured: true,
probe: { ok: true, bot: { username: "moltbot_bot" } },
probe: { ok: true, bot: { username: "openclaw_bot" } },
},
],
},
});
expect(lines.join("\n")).toMatch(/bot:@moltbot_bot/);
expect(lines.join("\n")).toMatch(/bot:@openclaw_bot/);
});
it("surfaces Telegram group membership audit issues in channels status output", () => {
@@ -40,7 +40,7 @@ const runtime: RuntimeEnv = {
};
const _baseSnapshot = {
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
+5 -5
View File
@@ -1,16 +1,16 @@
import { getChannelPlugin } from "../../channels/plugins/index.js";
import type { ChannelId, ChannelSetupInput } from "../../channels/plugins/types.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import { normalizeAccountId } from "../../routing/session-key.js";
type ChatChannel = ChannelId;
export function applyAccountName(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
channel: ChatChannel;
accountId: string;
name?: string;
}): MoltbotConfig {
}): OpenClawConfig {
const accountId = normalizeAccountId(params.accountId);
const plugin = getChannelPlugin(params.channel);
const apply = plugin?.setup?.applyAccountName;
@@ -18,7 +18,7 @@ export function applyAccountName(params: {
}
export function applyChannelAccountConfig(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
channel: ChatChannel;
accountId: string;
name?: string;
@@ -52,7 +52,7 @@ export function applyChannelAccountConfig(params: {
groupChannels?: string[];
dmAllowlist?: string[];
autoDiscoverChannels?: boolean;
}): MoltbotConfig {
}): OpenClawConfig {
const accountId = normalizeAccountId(params.accountId);
const plugin = getChannelPlugin(params.channel);
const apply = plugin?.setup?.applyAccountConfig;
+2 -2
View File
@@ -2,7 +2,7 @@ import { resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../../agents/ag
import { listChannelPluginCatalogEntries } from "../../channels/plugins/catalog.js";
import { getChannelPlugin, normalizeChannelId } from "../../channels/plugins/index.js";
import type { ChannelId } from "../../channels/plugins/types.js";
import { writeConfigFile, type MoltbotConfig } from "../../config/config.js";
import { writeConfigFile, type OpenClawConfig } from "../../config/config.js";
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import { createClackPrompter } from "../../wizard/clack-prompter.js";
@@ -60,7 +60,7 @@ function parseList(value: string | undefined): string[] | undefined {
return parsed.length > 0 ? parsed : undefined;
}
function resolveCatalogChannelEntry(raw: string, cfg: MoltbotConfig | null) {
function resolveCatalogChannelEntry(raw: string, cfg: OpenClawConfig | null) {
const trimmed = raw.trim().toLowerCase();
if (!trimmed) return undefined;
const workspaceDir = cfg ? resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg)) : undefined;
+1 -1
View File
@@ -89,7 +89,7 @@ describe("channelsCapabilitiesCommand", () => {
botToken: "xoxb-bot",
config: { userToken: "xoxp-user" },
},
probe: { ok: true, bot: { name: "moltbot" }, team: { name: "team" } },
probe: { ok: true, bot: { name: "openclaw" }, team: { name: "team" } },
});
vi.mocked(listChannelPlugins).mockReturnValue([plugin]);
vi.mocked(getChannelPlugin).mockReturnValue(plugin);
+2 -2
View File
@@ -4,7 +4,7 @@ import type { ChannelCapabilities, ChannelPlugin } from "../../channels/plugins/
import { fetchChannelPermissionsDiscord } from "../../discord/send.js";
import { parseDiscordTarget } from "../../discord/targets.js";
import { danger } from "../../globals.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import { fetchSlackScopes, type SlackScopesResult } from "../../slack/scopes.js";
import { theme } from "../../terminal/theme.js";
@@ -291,7 +291,7 @@ async function buildDiscordPermissions(params: {
async function resolveChannelReports(params: {
plugin: ChannelPlugin;
cfg: MoltbotConfig;
cfg: OpenClawConfig;
timeoutMs: number;
accountOverride?: string;
target?: string;
+2 -2
View File
@@ -4,7 +4,7 @@ import {
listChannelPlugins,
normalizeChannelId,
} from "../../channels/plugins/index.js";
import { type MoltbotConfig, writeConfigFile } from "../../config/config.js";
import { type OpenClawConfig, writeConfigFile } from "../../config/config.js";
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import { createClackPrompter } from "../../wizard/clack-prompter.js";
@@ -16,7 +16,7 @@ export type ChannelsRemoveOptions = {
delete?: boolean;
};
function listAccountIds(cfg: MoltbotConfig, channel: ChatChannel): string[] {
function listAccountIds(cfg: OpenClawConfig, channel: ChatChannel): string[] {
const plugin = getChannelPlugin(channel);
if (!plugin) return [];
return plugin.config.listAccountIds(cfg);
+3 -3
View File
@@ -1,6 +1,6 @@
import { type ChannelId, getChannelPlugin } from "../../channels/plugins/index.js";
import { formatCliCommand } from "../../cli/command-format.js";
import { type MoltbotConfig, readConfigFileSnapshot } from "../../config/config.js";
import { type OpenClawConfig, readConfigFileSnapshot } from "../../config/config.js";
import { DEFAULT_ACCOUNT_ID } from "../../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
@@ -8,7 +8,7 @@ export type ChatChannel = ChannelId;
export async function requireValidConfig(
runtime: RuntimeEnv = defaultRuntime,
): Promise<MoltbotConfig | null> {
): Promise<OpenClawConfig | null> {
const snapshot = await readConfigFileSnapshot();
if (snapshot.exists && !snapshot.valid) {
const issues =
@@ -16,7 +16,7 @@ export async function requireValidConfig(
? snapshot.issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")
: "Unknown validation issue.";
runtime.error(`Config invalid:\n${issues}`);
runtime.error(`Fix the config or run ${formatCliCommand("moltbot doctor")}.`);
runtime.error(`Fix the config or run ${formatCliCommand("openclaw doctor")}.`);
runtime.exit(1);
return null;
}
+3 -3
View File
@@ -2,7 +2,7 @@ import { listChannelPlugins } from "../../channels/plugins/index.js";
import { buildChannelAccountSnapshot } from "../../channels/plugins/status.js";
import type { ChannelAccountSnapshot } from "../../channels/plugins/types.js";
import { withProgress } from "../../cli/progress.js";
import { type MoltbotConfig, readConfigFileSnapshot } from "../../config/config.js";
import { type OpenClawConfig, readConfigFileSnapshot } from "../../config/config.js";
import { callGateway } from "../../gateway/call.js";
import { formatAge } from "../../infra/channel-summary.js";
import { collectChannelStatusIssues } from "../../infra/channels-status-issues.js";
@@ -143,7 +143,7 @@ export function formatGatewayChannelsStatusLines(payload: Record<string, unknown
`- ${issue.channel} ${issue.accountId}: ${issue.message}${issue.fix ? ` (${issue.fix})` : ""}`,
);
}
lines.push(`- Run: ${formatCliCommand("moltbot doctor")}`);
lines.push(`- Run: ${formatCliCommand("openclaw doctor")}`);
lines.push("");
}
lines.push(
@@ -153,7 +153,7 @@ export function formatGatewayChannelsStatusLines(payload: Record<string, unknown
}
async function formatConfigChannelsStatusLines(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
meta: { path?: string; mode?: "local" | "remote" },
): Promise<string[]> {
const lines: string[] = [];
+1 -1
View File
@@ -84,7 +84,7 @@ async function waitForLocalCallback(params: {
"<!doctype html>",
"<html><head><meta charset='utf-8' /></head>",
"<body><h2>Chutes OAuth complete</h2>",
"<p>You can close this window and return to moltbot.</p></body></html>",
"<p>You can close this window and return to OpenClaw.</p></body></html>",
].join(""),
);
if (timeout) clearTimeout(timeout);
+2 -2
View File
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { resolveDefaultAgentWorkspaceDir } from "../agents/workspace.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import { resolveHomeDir, resolveUserPath, shortenHomeInString } from "../utils.js";
@@ -11,7 +11,7 @@ export type RemovalResult = {
skipped?: boolean;
};
export function collectWorkspaceDirs(cfg: MoltbotConfig | undefined): string[] {
export function collectWorkspaceDirs(cfg: OpenClawConfig | undefined): string[] {
const dirs = new Set<string>();
const defaults = cfg?.agents?.defaults;
if (typeof defaults?.workspace === "string" && defaults.workspace.trim()) {
+6 -6
View File
@@ -1,6 +1,6 @@
import { getChannelPlugin, listChannelPlugins } from "../channels/plugins/index.js";
import { formatCliCommand } from "../cli/command-format.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { CONFIG_PATH } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import { note } from "../terminal/note.js";
@@ -9,9 +9,9 @@ import { confirm, select } from "./configure.shared.js";
import { guardCancel } from "./onboard-helpers.js";
export async function removeChannelConfigWizard(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
runtime: RuntimeEnv,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
let next = { ...cfg };
const listConfiguredChannels = () =>
@@ -24,8 +24,8 @@ export async function removeChannelConfigWizard(
if (configured.length === 0) {
note(
[
"No channel config found in moltbot.json.",
`Tip: \`${formatCliCommand("moltbot channels status")}\` shows what is configured and enabled.`,
"No channel config found in openclaw.json.",
`Tip: \`${formatCliCommand("openclaw channels status")}\` shows what is configured and enabled.`,
].join("\n"),
"Remove channel",
);
@@ -64,7 +64,7 @@ export async function removeChannelConfigWizard(
next = {
...next,
channels: Object.keys(nextChannels).length
? (nextChannels as MoltbotConfig["channels"])
? (nextChannels as OpenClawConfig["channels"])
: undefined,
};
+3 -3
View File
@@ -1,5 +1,5 @@
import { ensureAuthProfileStore } from "../agents/auth-profiles.js";
import type { MoltbotConfig, GatewayAuthConfig } from "../config/config.js";
import type { OpenClawConfig, GatewayAuthConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { applyAuthChoice, resolvePreferredProviderForAuthChoice } from "./auth-choice.js";
@@ -37,10 +37,10 @@ export function buildGatewayAuthConfig(params: {
}
export async function promptAuthConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
const authChoice = await promptAuthChoiceGrouped({
prompter,
store: ensureAuthProfileStore(undefined, {
+6 -4
View File
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { resolveGatewayPort } from "../config/config.js";
import { findTailscaleBinary } from "../infra/tailscale.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -10,10 +10,10 @@ import { guardCancel, randomToken } from "./onboard-helpers.js";
type GatewayAuthChoice = "token" | "password";
export async function promptGatewayConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
runtime: RuntimeEnv,
): Promise<{
config: MoltbotConfig;
config: OpenClawConfig;
port: number;
token?: string;
}> {
@@ -139,7 +139,9 @@ export async function promptGatewayConfig(
let tailscaleResetOnExit = false;
if (tailscaleMode !== "off") {
note(
["Docs:", "https://docs.molt.bot/gateway/tailscale", "https://docs.molt.bot/web"].join("\n"),
["Docs:", "https://docs.openclaw.ai/gateway/tailscale", "https://docs.openclaw.ai/web"].join(
"\n",
),
"Tailscale",
);
tailscaleResetOnExit = Boolean(
+4 -4
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
const mocks = vi.hoisted(() => ({
clackIntro: vi.fn(),
@@ -30,7 +30,7 @@ vi.mock("@clack/prompts", () => ({
}));
vi.mock("../config/config.js", () => ({
CONFIG_PATH: "~/.clawdbot/moltbot.json",
CONFIG_PATH: "~/.openclaw/openclaw.json",
readConfigFileSnapshot: mocks.readConfigFileSnapshot,
writeConfigFile: mocks.writeConfigFile,
resolveGatewayPort: mocks.resolveGatewayPort,
@@ -49,8 +49,8 @@ vi.mock("../terminal/note.js", () => ({
}));
vi.mock("./onboard-helpers.js", () => ({
DEFAULT_WORKSPACE: "~/.clawdbot/workspace",
applyWizardMetadata: (cfg: MoltbotConfig) => cfg,
DEFAULT_WORKSPACE: "~/.openclaw/workspace",
applyWizardMetadata: (cfg: OpenClawConfig) => cfg,
ensureWorkspaceAndSessions: vi.fn(),
guardCancel: <T>(value: T) => value,
printWizardHeader: mocks.printWizardHeader,
+25 -25
View File
@@ -1,5 +1,5 @@
import { formatCliCommand } from "../cli/command-format.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { readConfigFileSnapshot, resolveGatewayPort, writeConfigFile } from "../config/config.js";
import { logConfigUpdated } from "../config/logging.js";
import { ensureControlUiAssetsBuilt } from "../infra/control-ui-assets.js";
@@ -79,7 +79,7 @@ async function promptChannelMode(runtime: RuntimeEnv): Promise<ChannelsWizardMod
{
value: "remove",
label: "Remove channel config",
hint: "Delete channel tokens/settings from moltbot.json",
hint: "Delete channel tokens/settings from openclaw.json",
},
],
initialValue: "configure",
@@ -89,9 +89,9 @@ async function promptChannelMode(runtime: RuntimeEnv): Promise<ChannelsWizardMod
}
async function promptWebToolsConfig(
nextConfig: MoltbotConfig,
nextConfig: OpenClawConfig,
runtime: RuntimeEnv,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
const existingSearch = nextConfig.tools?.web?.search;
const existingFetch = nextConfig.tools?.web?.fetch;
const hasSearchKey = Boolean(existingSearch?.apiKey);
@@ -100,7 +100,7 @@ async function promptWebToolsConfig(
[
"Web search lets your agent look things up online using the `web_search` tool.",
"It requires a Brave Search API key (you can store it in the config or set BRAVE_API_KEY in the Gateway environment).",
"Docs: https://docs.molt.bot/tools/web",
"Docs: https://docs.openclaw.ai/tools/web",
].join("\n"),
"Web search",
);
@@ -136,7 +136,7 @@ async function promptWebToolsConfig(
[
"No key stored yet, so web_search will stay unavailable.",
"Store a key here or set BRAVE_API_KEY in the Gateway environment.",
"Docs: https://docs.molt.bot/tools/web",
"Docs: https://docs.openclaw.ai/tools/web",
].join("\n"),
"Web search",
);
@@ -175,11 +175,11 @@ export async function runConfigureWizard(
) {
try {
printWizardHeader(runtime);
intro(opts.command === "update" ? "Moltbot update wizard" : "Moltbot configure");
intro(opts.command === "update" ? "OpenClaw update wizard" : "OpenClaw configure");
const prompter = createClackPrompter();
const snapshot = await readConfigFileSnapshot();
const baseConfig: MoltbotConfig = snapshot.valid ? snapshot.config : {};
const baseConfig: OpenClawConfig = snapshot.valid ? snapshot.config : {};
if (snapshot.exists) {
const title = snapshot.valid ? "Existing config detected" : "Invalid config";
@@ -189,14 +189,14 @@ export async function runConfigureWizard(
[
...snapshot.issues.map((iss) => `- ${iss.path}: ${iss.message}`),
"",
"Docs: https://docs.molt.bot/gateway/configuration",
"Docs: https://docs.openclaw.ai/gateway/configuration",
].join("\n"),
"Config issues",
);
}
if (!snapshot.valid) {
outro(
`Config invalid. Run \`${formatCliCommand("moltbot doctor")}\` to repair it, then re-run configure.`,
`Config invalid. Run \`${formatCliCommand("openclaw doctor")}\` to repair it, then re-run configure.`,
);
runtime.exit(1);
return;
@@ -206,8 +206,8 @@ export async function runConfigureWizard(
const localUrl = "ws://127.0.0.1:18789";
const localProbe = await probeGatewayReachable({
url: localUrl,
token: baseConfig.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN,
password: baseConfig.gateway?.auth?.password ?? process.env.CLAWDBOT_GATEWAY_PASSWORD,
token: baseConfig.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN,
password: baseConfig.gateway?.auth?.password ?? process.env.OPENCLAW_GATEWAY_PASSWORD,
});
const remoteUrl = baseConfig.gateway?.remote?.url?.trim() ?? "";
const remoteProbe = remoteUrl
@@ -274,7 +274,7 @@ export async function runConfigureWizard(
let gatewayToken: string | undefined =
nextConfig.gateway?.auth?.token ??
baseConfig.gateway?.auth?.token ??
process.env.CLAWDBOT_GATEWAY_TOKEN;
process.env.OPENCLAW_GATEWAY_TOKEN;
const persistConfig = async () => {
nextConfig = applyWizardMetadata(nextConfig, {
@@ -377,9 +377,9 @@ export async function runConfigureWizard(
const remoteUrl = nextConfig.gateway?.remote?.url?.trim();
const wsUrl =
nextConfig.gateway?.mode === "remote" && remoteUrl ? remoteUrl : localLinks.wsUrl;
const token = nextConfig.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN;
const token = nextConfig.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN;
const password =
nextConfig.gateway?.auth?.password ?? process.env.CLAWDBOT_GATEWAY_PASSWORD;
nextConfig.gateway?.auth?.password ?? process.env.OPENCLAW_GATEWAY_PASSWORD;
await waitForGatewayReachable({
url: wsUrl,
token,
@@ -393,8 +393,8 @@ export async function runConfigureWizard(
note(
[
"Docs:",
"https://docs.molt.bot/gateway/health",
"https://docs.molt.bot/gateway/troubleshooting",
"https://docs.openclaw.ai/gateway/health",
"https://docs.openclaw.ai/gateway/troubleshooting",
].join("\n"),
"Health check help",
);
@@ -502,9 +502,9 @@ export async function runConfigureWizard(
const remoteUrl = nextConfig.gateway?.remote?.url?.trim();
const wsUrl =
nextConfig.gateway?.mode === "remote" && remoteUrl ? remoteUrl : localLinks.wsUrl;
const token = nextConfig.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN;
const token = nextConfig.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN;
const password =
nextConfig.gateway?.auth?.password ?? process.env.CLAWDBOT_GATEWAY_PASSWORD;
nextConfig.gateway?.auth?.password ?? process.env.OPENCLAW_GATEWAY_PASSWORD;
await waitForGatewayReachable({
url: wsUrl,
token,
@@ -518,8 +518,8 @@ export async function runConfigureWizard(
note(
[
"Docs:",
"https://docs.molt.bot/gateway/health",
"https://docs.molt.bot/gateway/troubleshooting",
"https://docs.openclaw.ai/gateway/health",
"https://docs.openclaw.ai/gateway/troubleshooting",
].join("\n"),
"Health check help",
);
@@ -551,9 +551,9 @@ export async function runConfigureWizard(
basePath: nextConfig.gateway?.controlUi?.basePath,
});
// Try both new and old passwords since gateway may still have old config.
const newPassword = nextConfig.gateway?.auth?.password ?? process.env.CLAWDBOT_GATEWAY_PASSWORD;
const oldPassword = baseConfig.gateway?.auth?.password ?? process.env.CLAWDBOT_GATEWAY_PASSWORD;
const token = nextConfig.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN;
const newPassword = nextConfig.gateway?.auth?.password ?? process.env.OPENCLAW_GATEWAY_PASSWORD;
const oldPassword = baseConfig.gateway?.auth?.password ?? process.env.OPENCLAW_GATEWAY_PASSWORD;
const token = nextConfig.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN;
let gatewayProbe = await probeGatewayReachable({
url: links.wsUrl,
@@ -577,7 +577,7 @@ export async function runConfigureWizard(
`Web UI: ${links.httpUrl}`,
`Gateway WS: ${links.wsUrl}`,
gatewayStatusLine,
"Docs: https://docs.molt.bot/web/control-ui",
"Docs: https://docs.openclaw.ai/web/control-ui",
].join("\n"),
"Control UI",
);
+12 -12
View File
@@ -34,11 +34,11 @@ afterEach(() => {
describe("resolveGatewayDevMode", () => {
it("detects dev mode for src ts entrypoints", () => {
expect(resolveGatewayDevMode(["node", "/Users/me/moltbot/src/cli/index.ts"])).toBe(true);
expect(resolveGatewayDevMode(["node", "C:\\Users\\me\\moltbot\\src\\cli\\index.ts"])).toBe(
expect(resolveGatewayDevMode(["node", "/Users/me/openclaw/src/cli/index.ts"])).toBe(true);
expect(resolveGatewayDevMode(["node", "C:\\Users\\me\\openclaw\\src\\cli\\index.ts"])).toBe(
true,
);
expect(resolveGatewayDevMode(["node", "/Users/me/moltbot/dist/cli/index.js"])).toBe(false);
expect(resolveGatewayDevMode(["node", "/Users/me/openclaw/dist/cli/index.js"])).toBe(false);
});
});
@@ -55,7 +55,7 @@ describe("buildGatewayInstallPlan", () => {
supported: true,
});
mocks.renderSystemNodeWarning.mockReturnValue(undefined);
mocks.buildServiceEnvironment.mockReturnValue({ CLAWDBOT_PORT: "3000" });
mocks.buildServiceEnvironment.mockReturnValue({ OPENCLAW_PORT: "3000" });
const plan = await buildGatewayInstallPlan({
env: {},
@@ -66,7 +66,7 @@ describe("buildGatewayInstallPlan", () => {
expect(plan.programArguments).toEqual(["node", "gateway"]);
expect(plan.workingDirectory).toBe("/Users/me");
expect(plan.environment).toEqual({ CLAWDBOT_PORT: "3000" });
expect(plan.environment).toEqual({ OPENCLAW_PORT: "3000" });
expect(mocks.resolvePreferredNodePath).not.toHaveBeenCalled();
});
@@ -108,7 +108,7 @@ describe("buildGatewayInstallPlan", () => {
supported: true,
});
mocks.buildServiceEnvironment.mockReturnValue({
CLAWDBOT_PORT: "3000",
OPENCLAW_PORT: "3000",
HOME: "/Users/me",
});
@@ -130,7 +130,7 @@ describe("buildGatewayInstallPlan", () => {
expect(plan.environment.GOOGLE_API_KEY).toBe("test-key");
expect(plan.environment.CUSTOM_VAR).toBe("custom-value");
// Service environment vars should take precedence
expect(plan.environment.CLAWDBOT_PORT).toBe("3000");
expect(plan.environment.OPENCLAW_PORT).toBe("3000");
expect(plan.environment.HOME).toBe("/Users/me");
});
@@ -145,7 +145,7 @@ describe("buildGatewayInstallPlan", () => {
version: "22.0.0",
supported: true,
});
mocks.buildServiceEnvironment.mockReturnValue({ CLAWDBOT_PORT: "3000" });
mocks.buildServiceEnvironment.mockReturnValue({ OPENCLAW_PORT: "3000" });
const plan = await buildGatewayInstallPlan({
env: {},
@@ -209,7 +209,7 @@ describe("buildGatewayInstallPlan", () => {
});
mocks.buildServiceEnvironment.mockReturnValue({
HOME: "/Users/service",
CLAWDBOT_PORT: "3000",
OPENCLAW_PORT: "3000",
});
const plan = await buildGatewayInstallPlan({
@@ -220,14 +220,14 @@ describe("buildGatewayInstallPlan", () => {
env: {
HOME: "/Users/config",
vars: {
CLAWDBOT_PORT: "9999",
OPENCLAW_PORT: "9999",
},
},
},
});
expect(plan.environment.HOME).toBe("/Users/service");
expect(plan.environment.CLAWDBOT_PORT).toBe("3000");
expect(plan.environment.OPENCLAW_PORT).toBe("3000");
});
});
@@ -235,7 +235,7 @@ describe("gatewayInstallErrorHint", () => {
it("returns platform-specific hints", () => {
expect(gatewayInstallErrorHint("win32")).toContain("Run as administrator");
expect(gatewayInstallErrorHint("linux")).toMatch(
/(?:moltbot|moltbot)( --profile isolated)? gateway install/,
/(?:openclaw|openclaw)( --profile isolated)? gateway install/,
);
});
});
+4 -4
View File
@@ -8,7 +8,7 @@ import {
import { buildServiceEnvironment } from "../daemon/service-env.js";
import { formatCliCommand } from "../cli/command-format.js";
import { collectConfigEnvVars } from "../config/env-vars.js";
import type { MoltbotConfig } from "../config/types.js";
import type { OpenClawConfig } from "../config/types.js";
import type { GatewayDaemonRuntime } from "./daemon-runtime.js";
type WarnFn = (message: string, title?: string) => void;
@@ -34,7 +34,7 @@ export async function buildGatewayInstallPlan(params: {
nodePath?: string;
warn?: WarnFn;
/** Full config to extract env vars from (env vars + inline env keys). */
config?: MoltbotConfig;
config?: OpenClawConfig;
}): Promise<GatewayInstallPlan> {
const devMode = params.devMode ?? resolveGatewayDevMode();
const nodePath =
@@ -60,7 +60,7 @@ export async function buildGatewayInstallPlan(params: {
token: params.token,
launchdLabel:
process.platform === "darwin"
? resolveGatewayLaunchAgentLabel(params.env.CLAWDBOT_PROFILE)
? resolveGatewayLaunchAgentLabel(params.env.OPENCLAW_PROFILE)
: undefined,
});
@@ -77,5 +77,5 @@ export async function buildGatewayInstallPlan(params: {
export function gatewayInstallErrorHint(platform = process.platform): string {
return platform === "win32"
? "Tip: rerun from an elevated PowerShell (Start → type PowerShell → right-click → Run as administrator) or skip service install."
: `Tip: rerun \`${formatCliCommand("moltbot gateway install")}\` after fixing the error.`;
: `Tip: rerun \`${formatCliCommand("openclaw gateway install")}\` after fixing the error.`;
}
+2 -2
View File
@@ -42,7 +42,7 @@ function resetRuntime() {
function mockSnapshot(token = "abc") {
mocks.readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -87,7 +87,7 @@ describe("dashboardCommand", () => {
expect(mocks.copyToClipboard).toHaveBeenCalledWith("http://127.0.0.1:18789/?token=abc123");
expect(mocks.openUrl).toHaveBeenCalledWith("http://127.0.0.1:18789/?token=abc123");
expect(runtime.log).toHaveBeenCalledWith(
"Opened in your browser. Keep that tab to control Moltbot.",
"Opened in your browser. Keep that tab to control OpenClaw.",
);
});
+2 -2
View File
@@ -23,7 +23,7 @@ export async function dashboardCommand(
const bind = cfg.gateway?.bind ?? "loopback";
const basePath = cfg.gateway?.controlUi?.basePath;
const customBindHost = cfg.gateway?.customBindHost;
const token = cfg.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN ?? "";
const token = cfg.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN ?? "";
const links = resolveControlUiLinks({
port,
@@ -57,7 +57,7 @@ export async function dashboardCommand(
}
if (opened) {
runtime.log("Opened in your browser. Keep that tab to control Moltbot.");
runtime.log("Opened in your browser. Keep that tab to control OpenClaw.");
} else if (hint) {
runtime.log(hint);
}
+5 -5
View File
@@ -5,7 +5,7 @@ import { formatDocsLink } from "../terminal/links.js";
import { isRich, theme } from "../terminal/theme.js";
import { formatCliCommand } from "../cli/command-format.js";
const SEARCH_TOOL = "https://docs.molt.bot/mcp.SearchMoltbot";
const SEARCH_TOOL = "https://docs.openclaw.ai/mcp.SearchOpenClaw";
const SEARCH_TIMEOUT_MS = 30_000;
const DEFAULT_SNIPPET_MAX = 220;
@@ -148,13 +148,13 @@ async function renderMarkdown(markdown: string, runtime: RuntimeEnv) {
export async function docsSearchCommand(queryParts: string[], runtime: RuntimeEnv) {
const query = queryParts.join(" ").trim();
if (!query) {
const docs = formatDocsLink("/", "docs.molt.bot");
const docs = formatDocsLink("/", "docs.openclaw.ai");
if (isRich()) {
runtime.log(`${theme.muted("Docs:")} ${docs}`);
runtime.log(`${theme.muted("Search:")} ${formatCliCommand('moltbot docs "your query"')}`);
runtime.log(`${theme.muted("Search:")} ${formatCliCommand('openclaw docs "your query"')}`);
} else {
runtime.log("Docs: https://docs.molt.bot/");
runtime.log(`Search: ${formatCliCommand('moltbot docs "your query"')}`);
runtime.log("Docs: https://docs.openclaw.ai/");
runtime.log(`Search: ${formatCliCommand('openclaw docs "your query"')}`);
}
return;
}
@@ -24,18 +24,18 @@ function makePrompter(confirmValue: boolean): DoctorPrompter {
}
beforeEach(() => {
originalAgentDir = process.env.CLAWDBOT_AGENT_DIR;
originalAgentDir = process.env.OPENCLAW_AGENT_DIR;
originalPiAgentDir = process.env.PI_CODING_AGENT_DIR;
tempAgentDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-auth-"));
process.env.CLAWDBOT_AGENT_DIR = tempAgentDir;
tempAgentDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_AGENT_DIR = tempAgentDir;
process.env.PI_CODING_AGENT_DIR = tempAgentDir;
});
afterEach(() => {
if (originalAgentDir === undefined) {
delete process.env.CLAWDBOT_AGENT_DIR;
delete process.env.OPENCLAW_AGENT_DIR;
} else {
process.env.CLAWDBOT_AGENT_DIR = originalAgentDir;
process.env.OPENCLAW_AGENT_DIR = originalAgentDir;
}
if (originalPiAgentDir === undefined) {
delete process.env.PI_CODING_AGENT_DIR;
+15 -15
View File
@@ -12,15 +12,15 @@ import {
resolveProfileUnusableUntilForDisplay,
} from "../agents/auth-profiles.js";
import { updateAuthProfileStoreWithLock } from "../agents/auth-profiles/store.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { note } from "../terminal/note.js";
import { formatCliCommand } from "../cli/command-format.js";
import type { DoctorPrompter } from "./doctor-prompter.js";
export async function maybeRepairAnthropicOAuthProfileId(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
prompter: DoctorPrompter,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
const store = ensureAuthProfileStore();
const repair = repairOAuthProfileIdMismatch({
cfg,
@@ -55,9 +55,9 @@ function pruneAuthOrder(
}
function pruneAuthProfiles(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
profileIds: Set<string>,
): { next: MoltbotConfig; changed: boolean } {
): { next: OpenClawConfig; changed: boolean } {
const profiles = cfg.auth?.profiles;
const order = cfg.auth?.order;
const nextProfiles = profiles ? { ...profiles } : undefined;
@@ -96,9 +96,9 @@ function pruneAuthProfiles(
}
export async function maybeRemoveDeprecatedCliAuthProfiles(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
prompter: DoctorPrompter,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
const store = ensureAuthProfileStore(undefined, { allowKeychainPrompt: false });
const deprecated = new Set<string>();
if (store.profiles[CLAUDE_CLI_PROFILE_ID] || cfg.auth?.profiles?.[CLAUDE_CLI_PROFILE_ID]) {
@@ -113,13 +113,13 @@ export async function maybeRemoveDeprecatedCliAuthProfiles(
const lines = ["Deprecated external CLI auth profiles detected (no longer supported):"];
if (deprecated.has(CLAUDE_CLI_PROFILE_ID)) {
lines.push(
`- ${CLAUDE_CLI_PROFILE_ID} (Anthropic): use setup-token → ${formatCliCommand("moltbot models auth setup-token")}`,
`- ${CLAUDE_CLI_PROFILE_ID} (Anthropic): use setup-token → ${formatCliCommand("openclaw models auth setup-token")}`,
);
}
if (deprecated.has(CODEX_CLI_PROFILE_ID)) {
lines.push(
`- ${CODEX_CLI_PROFILE_ID} (OpenAI Codex): use OAuth → ${formatCliCommand(
"moltbot models auth login --provider openai-codex",
"openclaw models auth login --provider openai-codex",
)}`,
);
}
@@ -190,16 +190,16 @@ type AuthIssue = {
function formatAuthIssueHint(issue: AuthIssue): string | null {
if (issue.provider === "anthropic" && issue.profileId === CLAUDE_CLI_PROFILE_ID) {
return `Deprecated profile. Use ${formatCliCommand("moltbot models auth setup-token")} or ${formatCliCommand(
"moltbot configure",
return `Deprecated profile. Use ${formatCliCommand("openclaw models auth setup-token")} or ${formatCliCommand(
"openclaw configure",
)}.`;
}
if (issue.provider === "openai-codex" && issue.profileId === CODEX_CLI_PROFILE_ID) {
return `Deprecated profile. Use ${formatCliCommand(
"moltbot models auth login --provider openai-codex",
)} or ${formatCliCommand("moltbot configure")}.`;
"openclaw models auth login --provider openai-codex",
)} or ${formatCliCommand("openclaw configure")}.`;
}
return `Re-auth via \`${formatCliCommand("moltbot configure")}\` or \`${formatCliCommand("moltbot onboard")}\`.`;
return `Re-auth via \`${formatCliCommand("openclaw configure")}\` or \`${formatCliCommand("openclaw onboard")}\`.`;
}
function formatAuthIssueLine(issue: AuthIssue): string {
@@ -210,7 +210,7 @@ function formatAuthIssueLine(issue: AuthIssue): string {
}
export async function noteAuthProfileHealth(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
prompter: DoctorPrompter;
allowKeychainPrompt: boolean;
}): Promise<void> {
+4 -4
View File
@@ -9,10 +9,10 @@ import { loadAndMaybeMigrateDoctorConfig } from "./doctor-config-flow.js";
describe("doctor config flow", () => {
it("preserves invalid config for doctor repairs", async () => {
await withTempHome(async (home) => {
const configDir = path.join(home, ".clawdbot");
const configDir = path.join(home, ".openclaw");
await fs.mkdir(configDir, { recursive: true });
await fs.writeFile(
path.join(configDir, "moltbot.json"),
path.join(configDir, "openclaw.json"),
JSON.stringify(
{
gateway: { auth: { mode: "token", token: 123 } },
@@ -37,10 +37,10 @@ describe("doctor config flow", () => {
it("drops unknown keys on repair", async () => {
await withTempHome(async (home) => {
const configDir = path.join(home, ".clawdbot");
const configDir = path.join(home, ".openclaw");
await fs.mkdir(configDir, { recursive: true });
await fs.writeFile(
path.join(configDir, "moltbot.json"),
path.join(configDir, "openclaw.json"),
JSON.stringify(
{
bridge: { bind: "auto" },
+13 -45
View File
@@ -1,10 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import type { ZodIssue } from "zod";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import {
MoltbotSchema,
OpenClawSchema,
CONFIG_PATH,
migrateLegacyConfig,
readConfigFileSnapshot,
@@ -63,16 +61,16 @@ function resolvePathTarget(root: unknown, path: Array<string | number>): unknown
return current;
}
function stripUnknownConfigKeys(config: MoltbotConfig): {
config: MoltbotConfig;
function stripUnknownConfigKeys(config: OpenClawConfig): {
config: OpenClawConfig;
removed: string[];
} {
const parsed = MoltbotSchema.safeParse(config);
const parsed = OpenClawSchema.safeParse(config);
if (parsed.success) {
return { config, removed: [] };
}
const next = structuredClone(config) as MoltbotConfig;
const next = structuredClone(config) as OpenClawConfig;
const removed: string[] = [];
for (const issue of parsed.error.issues) {
if (!isUnrecognizedKeysIssue(issue)) continue;
@@ -91,7 +89,7 @@ function stripUnknownConfigKeys(config: MoltbotConfig): {
return { config: next, removed };
}
function noteOpencodeProviderOverrides(cfg: MoltbotConfig) {
function noteOpencodeProviderOverrides(cfg: OpenClawConfig) {
const providers = cfg.models?.providers;
if (!providers) return;
@@ -120,25 +118,6 @@ function noteOpencodeProviderOverrides(cfg: MoltbotConfig) {
note(lines.join("\n"), "OpenCode Zen");
}
function hasExplicitConfigPath(env: NodeJS.ProcessEnv): boolean {
return Boolean(env.MOLTBOT_CONFIG_PATH?.trim() || env.CLAWDBOT_CONFIG_PATH?.trim());
}
function moveLegacyConfigFile(legacyPath: string, canonicalPath: string) {
fs.mkdirSync(path.dirname(canonicalPath), { recursive: true, mode: 0o700 });
try {
fs.renameSync(legacyPath, canonicalPath);
} catch {
fs.copyFileSync(legacyPath, canonicalPath);
fs.chmodSync(canonicalPath, 0o600);
try {
fs.unlinkSync(legacyPath);
} catch {
// Best-effort cleanup; we'll warn later if both files exist.
}
}
}
export async function loadAndMaybeMigrateDoctorConfig(params: {
options: DoctorOptions;
confirm: (p: { message: string; initialValue: boolean }) => Promise<boolean>;
@@ -153,20 +132,9 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
}
let snapshot = await readConfigFileSnapshot();
if (!hasExplicitConfigPath(process.env) && snapshot.exists) {
const basename = path.basename(snapshot.path);
if (basename === "clawdbot.json") {
const canonicalPath = path.join(path.dirname(snapshot.path), "moltbot.json");
if (!fs.existsSync(canonicalPath)) {
moveLegacyConfigFile(snapshot.path, canonicalPath);
note(`- Config: ${snapshot.path} → ${canonicalPath}`, "Doctor changes");
snapshot = await readConfigFileSnapshot();
}
}
}
const baseCfg = snapshot.config ?? {};
let cfg: MoltbotConfig = baseCfg;
let candidate = structuredClone(baseCfg) as MoltbotConfig;
let cfg: OpenClawConfig = baseCfg;
let candidate = structuredClone(baseCfg) as OpenClawConfig;
let pendingChanges = false;
let shouldWriteConfig = false;
const fixHints: string[] = [];
@@ -197,7 +165,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
if (migrated) cfg = migrated;
} else {
fixHints.push(
`Run "${formatCliCommand("moltbot doctor --fix")}" to apply legacy migrations.`,
`Run "${formatCliCommand("openclaw doctor --fix")}" to apply legacy migrations.`,
);
}
}
@@ -210,7 +178,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
if (shouldRepair) {
cfg = normalized.config;
} else {
fixHints.push(`Run "${formatCliCommand("moltbot doctor --fix")}" to apply these changes.`);
fixHints.push(`Run "${formatCliCommand("openclaw doctor --fix")}" to apply these changes.`);
}
}
@@ -222,7 +190,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
if (shouldRepair) {
cfg = autoEnable.config;
} else {
fixHints.push(`Run "${formatCliCommand("moltbot doctor --fix")}" to apply these changes.`);
fixHints.push(`Run "${formatCliCommand("openclaw doctor --fix")}" to apply these changes.`);
}
}
@@ -236,7 +204,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
note(lines, "Doctor changes");
} else {
note(lines, "Unknown config keys");
fixHints.push('Run "moltbot doctor --fix" to remove these keys.');
fixHints.push('Run "openclaw doctor --fix" to remove these keys.');
}
}
+5 -5
View File
@@ -66,14 +66,14 @@ export function buildGatewayRuntimeHints(
return hints;
}
if (runtime.cachedLabel && platform === "darwin") {
const label = resolveGatewayLaunchAgentLabel(env.CLAWDBOT_PROFILE);
const label = resolveGatewayLaunchAgentLabel(env.OPENCLAW_PROFILE);
hints.push(
`LaunchAgent label cached but plist missing. Clear with: launchctl bootout gui/$UID/${label}`,
);
hints.push(`Then reinstall: ${formatCliCommand("moltbot gateway install", env)}`);
hints.push(`Then reinstall: ${formatCliCommand("openclaw gateway install", env)}`);
}
if (runtime.missingUnit) {
hints.push(`Service not installed. Run: ${formatCliCommand("moltbot gateway install", env)}`);
hints.push(`Service not installed. Run: ${formatCliCommand("openclaw gateway install", env)}`);
if (fileLog) hints.push(`File logs: ${fileLog}`);
return hints;
}
@@ -85,10 +85,10 @@ export function buildGatewayRuntimeHints(
hints.push(`Launchd stdout (if installed): ${logs.stdoutPath}`);
hints.push(`Launchd stderr (if installed): ${logs.stderrPath}`);
} else if (platform === "linux") {
const unit = resolveGatewaySystemdServiceName(env.CLAWDBOT_PROFILE);
const unit = resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE);
hints.push(`Logs: journalctl --user -u ${unit}.service -n 200 --no-pager`);
} else if (platform === "win32") {
const task = resolveGatewayWindowsTaskName(env.CLAWDBOT_PROFILE);
const task = resolveGatewayWindowsTaskName(env.OPENCLAW_PROFILE);
hints.push(`Logs: schtasks /Query /TN "${task}" /V /FO LIST`);
}
}
+9 -6
View File
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { resolveGatewayPort } from "../config/config.js";
import {
resolveGatewayLaunchAgentLabel,
@@ -76,7 +76,7 @@ async function maybeRepairLaunchAgentBootstrap(params: {
}
export async function maybeRepairGatewayDaemon(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
runtime: RuntimeEnv;
prompter: DoctorPrompter;
options: DoctorOptions;
@@ -106,7 +106,10 @@ export async function maybeRepairGatewayDaemon(params: {
prompter: params.prompter,
});
await maybeRepairLaunchAgentBootstrap({
env: { ...process.env, CLAWDBOT_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel() },
env: {
...process.env,
OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(),
},
title: "Node",
runtime: params.runtime,
prompter: params.prompter,
@@ -158,7 +161,7 @@ export async function maybeRepairGatewayDaemon(params: {
const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
env: process.env,
port,
token: params.cfg.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN,
token: params.cfg.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN,
runtime: daemonRuntime,
warn: (message, title) => note(message, title),
config: params.cfg,
@@ -207,9 +210,9 @@ export async function maybeRepairGatewayDaemon(params: {
}
if (process.platform === "darwin") {
const label = resolveGatewayLaunchAgentLabel(process.env.CLAWDBOT_PROFILE);
const label = resolveGatewayLaunchAgentLabel(process.env.OPENCLAW_PROFILE);
note(
`LaunchAgent loaded; stopping requires "${formatCliCommand("moltbot gateway stop")}" or launchctl bootout gui/$UID/${label}.`,
`LaunchAgent loaded; stopping requires "${formatCliCommand("openclaw gateway stop")}" or launchctl bootout gui/$UID/${label}.`,
"Gateway",
);
}
+2 -2
View File
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { buildGatewayConnectionDetails, callGateway } from "../gateway/call.js";
import { collectChannelStatusIssues } from "../infra/channels-status-issues.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -8,7 +8,7 @@ import { formatHealthCheckFailure } from "./health-format.js";
export async function checkGatewayHealth(params: {
runtime: RuntimeEnv;
cfg: MoltbotConfig;
cfg: OpenClawConfig;
timeoutMs?: number;
}) {
const gatewayDetails = buildGatewayConnectionDetails({ config: params.cfg });
+5 -94
View File
@@ -1,9 +1,8 @@
import path from "node:path";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { resolveGatewayPort, resolveIsNixMode } from "../config/paths.js";
import { findExtraGatewayServices, renderGatewayServiceCleanupHints } from "../daemon/inspect.js";
import { findLegacyGatewayServices, uninstallLegacyGatewayServices } from "../daemon/legacy.js";
import { renderSystemNodeWarning, resolveSystemNodeInfo } from "../daemon/runtime-paths.js";
import { resolveGatewayService } from "../daemon/service.js";
import {
@@ -13,12 +12,8 @@ import {
} from "../daemon/service-audit.js";
import type { RuntimeEnv } from "../runtime.js";
import { note } from "../terminal/note.js";
import { buildGatewayInstallPlan, gatewayInstallErrorHint } from "./daemon-install-helpers.js";
import {
DEFAULT_GATEWAY_DAEMON_RUNTIME,
GATEWAY_DAEMON_RUNTIME_OPTIONS,
type GatewayDaemonRuntime,
} from "./daemon-runtime.js";
import { buildGatewayInstallPlan } from "./daemon-install-helpers.js";
import { DEFAULT_GATEWAY_DAEMON_RUNTIME, type GatewayDaemonRuntime } from "./daemon-runtime.js";
import type { DoctorOptions, DoctorPrompter } from "./doctor-prompter.js";
function detectGatewayRuntime(programArguments: string[] | undefined): GatewayDaemonRuntime {
@@ -42,92 +37,8 @@ function normalizeExecutablePath(value: string): string {
return path.resolve(value);
}
export async function maybeMigrateLegacyGatewayService(
cfg: MoltbotConfig,
mode: "local" | "remote",
runtime: RuntimeEnv,
prompter: DoctorPrompter,
) {
const legacyServices = await findLegacyGatewayServices(process.env);
if (legacyServices.length === 0) return;
note(
legacyServices.map((svc) => `- ${svc.label} (${svc.platform}, ${svc.detail})`).join("\n"),
"Legacy gateway services detected",
);
const migrate = await prompter.confirmSkipInNonInteractive({
message: "Migrate legacy gateway services to Moltbot now?",
initialValue: true,
});
if (!migrate) return;
try {
await uninstallLegacyGatewayServices({
env: process.env,
stdout: process.stdout,
});
} catch (err) {
runtime.error(`Legacy service cleanup failed: ${String(err)}`);
return;
}
if (resolveIsNixMode(process.env)) {
note("Nix mode detected; skip installing services.", "Gateway");
return;
}
if (mode === "remote") {
note("Gateway mode is remote; skipped local service install.", "Gateway");
return;
}
const service = resolveGatewayService();
const loaded = await service.isLoaded({ env: process.env });
if (loaded) {
note(`Moltbot ${service.label} already ${service.loadedText}.`, "Gateway");
return;
}
const install = await prompter.confirmSkipInNonInteractive({
message: "Install Moltbot gateway service now?",
initialValue: true,
});
if (!install) return;
const daemonRuntime = await prompter.select<GatewayDaemonRuntime>(
{
message: "Gateway service runtime",
options: GATEWAY_DAEMON_RUNTIME_OPTIONS,
initialValue: DEFAULT_GATEWAY_DAEMON_RUNTIME,
},
DEFAULT_GATEWAY_DAEMON_RUNTIME,
);
const port = resolveGatewayPort(cfg, process.env);
const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
env: process.env,
port,
token: cfg.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN,
runtime: daemonRuntime,
warn: (message, title) => note(message, title),
config: cfg,
});
try {
await service.install({
env: process.env,
stdout: process.stdout,
programArguments,
workingDirectory,
environment,
});
} catch (err) {
runtime.error(`Gateway service install failed: ${String(err)}`);
note(gatewayInstallErrorHint(), "Gateway");
}
}
export async function maybeRepairGatewayServiceConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
mode: "local" | "remote",
runtime: RuntimeEnv,
prompter: DoctorPrompter,
@@ -174,7 +85,7 @@ export async function maybeRepairGatewayServiceConfig(
const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
env: process.env,
port,
token: cfg.gateway?.auth?.token ?? process.env.CLAWDBOT_GATEWAY_TOKEN,
token: cfg.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN,
runtime: needsNodeRuntime && systemNodePath ? "node" : runtimeChoice,
nodePath: systemNodePath ?? undefined,
warn: (message, title) => note(message, title),
+6 -6
View File
@@ -15,16 +15,16 @@ describe("normalizeLegacyConfigValues", () => {
};
beforeEach(() => {
previousOauthDir = process.env.CLAWDBOT_OAUTH_DIR;
tempOauthDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-oauth-"));
process.env.CLAWDBOT_OAUTH_DIR = tempOauthDir;
previousOauthDir = process.env.OPENCLAW_OAUTH_DIR;
tempOauthDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-oauth-"));
process.env.OPENCLAW_OAUTH_DIR = tempOauthDir;
});
afterEach(() => {
if (previousOauthDir === undefined) {
delete process.env.CLAWDBOT_OAUTH_DIR;
delete process.env.OPENCLAW_OAUTH_DIR;
} else {
process.env.CLAWDBOT_OAUTH_DIR = previousOauthDir;
process.env.OPENCLAW_OAUTH_DIR = previousOauthDir;
}
if (tempOauthDir) {
fs.rmSync(tempOauthDir, { recursive: true, force: true });
@@ -94,7 +94,7 @@ describe("normalizeLegacyConfigValues", () => {
});
it("copies legacy ack reaction when authDir override exists", () => {
const customDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-wa-auth-"));
const customDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-wa-auth-"));
try {
writeCreds(customDir);
+4 -4
View File
@@ -1,10 +1,10 @@
import type { MoltbotConfig } from "../config/config.js";
export function normalizeLegacyConfigValues(cfg: MoltbotConfig): {
config: MoltbotConfig;
import type { OpenClawConfig } from "../config/config.js";
export function normalizeLegacyConfigValues(cfg: OpenClawConfig): {
config: OpenClawConfig;
changes: string[];
} {
const changes: string[] = [];
let next: MoltbotConfig = cfg;
let next: OpenClawConfig = cfg;
const legacyAckReaction = cfg.messages?.ackReaction?.trim();
const hasWhatsAppConfig = cfg.channels?.whatsapp !== undefined;
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { describe, expect, it, vi } from "vitest";
@@ -8,7 +8,7 @@ describe("noteMacLaunchctlGatewayEnvOverrides", () => {
it("prints clear unsetenv instructions for token override", async () => {
const noteFn = vi.fn();
const getenv = vi.fn(async (name: string) =>
name === "CLAWDBOT_GATEWAY_TOKEN" ? "launchctl-token" : undefined,
name === "OPENCLAW_GATEWAY_TOKEN" ? "launchctl-token" : undefined,
);
const cfg = {
gateway: {
@@ -16,25 +16,25 @@ describe("noteMacLaunchctlGatewayEnvOverrides", () => {
token: "config-token",
},
},
} as MoltbotConfig;
} as OpenClawConfig;
await noteMacLaunchctlGatewayEnvOverrides(cfg, { platform: "darwin", getenv, noteFn });
expect(noteFn).toHaveBeenCalledTimes(1);
expect(getenv).toHaveBeenCalledTimes(2);
expect(getenv).toHaveBeenCalledTimes(6);
const [message, title] = noteFn.mock.calls[0] ?? [];
expect(title).toBe("Gateway (macOS)");
expect(message).toContain("launchctl environment overrides detected");
expect(message).toContain("CLAWDBOT_GATEWAY_TOKEN");
expect(message).toContain("launchctl unsetenv CLAWDBOT_GATEWAY_TOKEN");
expect(message).not.toContain("CLAWDBOT_GATEWAY_PASSWORD");
expect(message).toContain("OPENCLAW_GATEWAY_TOKEN");
expect(message).toContain("launchctl unsetenv OPENCLAW_GATEWAY_TOKEN");
expect(message).not.toContain("OPENCLAW_GATEWAY_PASSWORD");
});
it("does nothing when config has no gateway credentials", async () => {
const noteFn = vi.fn();
const getenv = vi.fn(async () => "launchctl-token");
const cfg = {} as MoltbotConfig;
const cfg = {} as OpenClawConfig;
await noteMacLaunchctlGatewayEnvOverrides(cfg, { platform: "darwin", getenv, noteFn });
@@ -51,7 +51,7 @@ describe("noteMacLaunchctlGatewayEnvOverrides", () => {
token: "config-token",
},
},
} as MoltbotConfig;
} as OpenClawConfig;
await noteMacLaunchctlGatewayEnvOverrides(cfg, { platform: "linux", getenv, noteFn });
+65 -12
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { note } from "../terminal/note.js";
import { shortenHomePath } from "../utils.js";
@@ -16,9 +16,10 @@ function resolveHomeDir(): string {
export async function noteMacLaunchAgentOverrides() {
if (process.platform !== "darwin") return;
const markerPath = path.join(resolveHomeDir(), ".clawdbot", "disable-launchagent");
const hasMarker = fs.existsSync(markerPath);
if (!hasMarker) return;
const home = resolveHomeDir();
const markerCandidates = [path.join(home, ".openclaw", "disable-launchagent")];
const markerPath = markerCandidates.find((candidate) => fs.existsSync(candidate));
if (!markerPath) return;
const displayMarkerPath = shortenHomePath(markerPath);
const lines = [
@@ -39,7 +40,7 @@ async function launchctlGetenv(name: string): Promise<string | undefined> {
}
}
function hasConfigGatewayCreds(cfg: MoltbotConfig): boolean {
function hasConfigGatewayCreds(cfg: OpenClawConfig): boolean {
const localToken =
typeof cfg.gateway?.auth?.token === "string" ? cfg.gateway?.auth?.token.trim() : "";
const localPassword =
@@ -52,7 +53,7 @@ function hasConfigGatewayCreds(cfg: MoltbotConfig): boolean {
}
export async function noteMacLaunchctlGatewayEnvOverrides(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
deps?: {
platform?: NodeJS.Platform;
getenv?: (name: string) => Promise<string | undefined>;
@@ -64,20 +65,72 @@ export async function noteMacLaunchctlGatewayEnvOverrides(
if (!hasConfigGatewayCreds(cfg)) return;
const getenv = deps?.getenv ?? launchctlGetenv;
const envToken = await getenv("CLAWDBOT_GATEWAY_TOKEN");
const envPassword = await getenv("CLAWDBOT_GATEWAY_PASSWORD");
const deprecatedLaunchctlEntries = [
["MOLTBOT_GATEWAY_TOKEN", await getenv("MOLTBOT_GATEWAY_TOKEN")],
["MOLTBOT_GATEWAY_PASSWORD", await getenv("MOLTBOT_GATEWAY_PASSWORD")],
["CLAWDBOT_GATEWAY_TOKEN", await getenv("CLAWDBOT_GATEWAY_TOKEN")],
["CLAWDBOT_GATEWAY_PASSWORD", await getenv("CLAWDBOT_GATEWAY_PASSWORD")],
].filter((entry): entry is [string, string] => Boolean(entry[1]?.trim()));
if (deprecatedLaunchctlEntries.length > 0) {
const lines = [
"- Deprecated launchctl environment variables detected (ignored).",
...deprecatedLaunchctlEntries.map(
([key]) =>
`- \`${key}\` is set; use \`OPENCLAW_${key.slice(key.indexOf("_") + 1)}\` instead.`,
),
];
(deps?.noteFn ?? note)(lines.join("\n"), "Gateway (macOS)");
}
const tokenEntries = [
["OPENCLAW_GATEWAY_TOKEN", await getenv("OPENCLAW_GATEWAY_TOKEN")],
] as const;
const passwordEntries = [
["OPENCLAW_GATEWAY_PASSWORD", await getenv("OPENCLAW_GATEWAY_PASSWORD")],
] as const;
const tokenEntry = tokenEntries.find(([, value]) => value?.trim());
const passwordEntry = passwordEntries.find(([, value]) => value?.trim());
const envToken = tokenEntry?.[1]?.trim() ?? "";
const envPassword = passwordEntry?.[1]?.trim() ?? "";
const envTokenKey = tokenEntry?.[0];
const envPasswordKey = passwordEntry?.[0];
if (!envToken && !envPassword) return;
const lines = [
"- launchctl environment overrides detected (can cause confusing unauthorized errors).",
envToken ? "- `CLAWDBOT_GATEWAY_TOKEN` is set; it overrides config tokens." : undefined,
envToken && envTokenKey
? `- \`${envTokenKey}\` is set; it overrides config tokens.`
: undefined,
envPassword
? "- `CLAWDBOT_GATEWAY_PASSWORD` is set; it overrides config passwords."
? `- \`${envPasswordKey ?? "OPENCLAW_GATEWAY_PASSWORD"}\` is set; it overrides config passwords.`
: undefined,
"- Clear overrides and restart the app/gateway:",
envToken ? " launchctl unsetenv CLAWDBOT_GATEWAY_TOKEN" : undefined,
envPassword ? " launchctl unsetenv CLAWDBOT_GATEWAY_PASSWORD" : undefined,
envTokenKey ? ` launchctl unsetenv ${envTokenKey}` : undefined,
envPasswordKey ? ` launchctl unsetenv ${envPasswordKey}` : undefined,
].filter((line): line is string => Boolean(line));
(deps?.noteFn ?? note)(lines.join("\n"), "Gateway (macOS)");
}
export function noteDeprecatedLegacyEnvVars(
env: NodeJS.ProcessEnv = process.env,
deps?: { noteFn?: typeof note },
) {
const entries = Object.entries(env)
.filter(
([key, value]) =>
(key.startsWith("MOLTBOT_") || key.startsWith("CLAWDBOT_")) && value?.trim(),
)
.map(([key]) => key);
if (entries.length === 0) return;
const lines = [
"- Deprecated legacy environment variables detected (ignored).",
"- Use OPENCLAW_* equivalents instead:",
...entries.map((key) => {
const suffix = key.slice(key.indexOf("_") + 1);
return ` ${key} -> OPENCLAW_${suffix}`;
}),
];
(deps?.noteFn ?? note)(lines.join("\n"), "Environment");
}
+13 -13
View File
@@ -7,7 +7,7 @@ import {
DEFAULT_SANDBOX_IMAGE,
resolveSandboxScope,
} from "../agents/sandbox.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { runCommandWithTimeout, runExec } from "../process/exec.js";
import type { RuntimeEnv } from "../runtime.js";
import { note } from "../terminal/note.js";
@@ -87,17 +87,17 @@ async function dockerImageExists(image: string): Promise<boolean> {
}
}
function resolveSandboxDockerImage(cfg: MoltbotConfig): string {
function resolveSandboxDockerImage(cfg: OpenClawConfig): string {
const image = cfg.agents?.defaults?.sandbox?.docker?.image?.trim();
return image ? image : DEFAULT_SANDBOX_IMAGE;
}
function resolveSandboxBrowserImage(cfg: MoltbotConfig): string {
function resolveSandboxBrowserImage(cfg: OpenClawConfig): string {
const image = cfg.agents?.defaults?.sandbox?.browser?.image?.trim();
return image ? image : DEFAULT_SANDBOX_BROWSER_IMAGE;
}
function updateSandboxDockerImage(cfg: MoltbotConfig, image: string): MoltbotConfig {
function updateSandboxDockerImage(cfg: OpenClawConfig, image: string): OpenClawConfig {
return {
...cfg,
agents: {
@@ -116,7 +116,7 @@ function updateSandboxDockerImage(cfg: MoltbotConfig, image: string): MoltbotCon
};
}
function updateSandboxBrowserImage(cfg: MoltbotConfig, image: string): MoltbotConfig {
function updateSandboxBrowserImage(cfg: OpenClawConfig, image: string): OpenClawConfig {
return {
...cfg,
agents: {
@@ -136,7 +136,7 @@ function updateSandboxBrowserImage(cfg: MoltbotConfig, image: string): MoltbotCo
}
type SandboxImageCheck = {
label: string;
kind: string;
image: string;
buildScript?: string;
updateConfig: (image: string) => void;
@@ -153,12 +153,12 @@ async function handleMissingSandboxImage(
const buildHint = params.buildScript
? `Build it with ${params.buildScript}.`
: "Build or pull it first.";
note(`Sandbox ${params.label} image missing: ${params.image}. ${buildHint}`, "Sandbox");
note(`Sandbox ${params.kind} image missing: ${params.image}. ${buildHint}`, "Sandbox");
let built = false;
if (params.buildScript) {
const build = await prompter.confirmSkipInNonInteractive({
message: `Build ${params.label} sandbox image now?`,
message: `Build ${params.kind} sandbox image now?`,
initialValue: true,
});
if (build) {
@@ -170,10 +170,10 @@ async function handleMissingSandboxImage(
}
export async function maybeRepairSandboxImages(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
runtime: RuntimeEnv,
prompter: DoctorPrompter,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
const sandbox = cfg.agents?.defaults?.sandbox;
const mode = sandbox?.mode ?? "off";
if (!sandbox || mode === "off") return cfg;
@@ -190,7 +190,7 @@ export async function maybeRepairSandboxImages(
const dockerImage = resolveSandboxDockerImage(cfg);
await handleMissingSandboxImage(
{
label: "base",
kind: "base",
image: dockerImage,
buildScript:
dockerImage === DEFAULT_SANDBOX_COMMON_IMAGE
@@ -210,7 +210,7 @@ export async function maybeRepairSandboxImages(
if (sandbox.browser?.enabled) {
await handleMissingSandboxImage(
{
label: "browser",
kind: "browser",
image: resolveSandboxBrowserImage(cfg),
buildScript: "scripts/sandbox-browser-setup.sh",
updateConfig: (image) => {
@@ -230,7 +230,7 @@ export async function maybeRepairSandboxImages(
return next;
}
export function noteSandboxScopeWarnings(cfg: MoltbotConfig) {
export function noteSandboxScopeWarnings(cfg: OpenClawConfig) {
const globalSandbox = cfg.agents?.defaults?.sandbox;
const agents = Array.isArray(cfg.agents?.list) ? cfg.agents.list : [];
const warnings: string[] = [];
+14 -14
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
const note = vi.hoisted(() => vi.fn());
@@ -20,23 +20,23 @@ describe("noteSecurityWarnings gateway exposure", () => {
beforeEach(() => {
note.mockClear();
prevToken = process.env.CLAWDBOT_GATEWAY_TOKEN;
prevPassword = process.env.CLAWDBOT_GATEWAY_PASSWORD;
delete process.env.CLAWDBOT_GATEWAY_TOKEN;
delete process.env.CLAWDBOT_GATEWAY_PASSWORD;
prevToken = process.env.OPENCLAW_GATEWAY_TOKEN;
prevPassword = process.env.OPENCLAW_GATEWAY_PASSWORD;
delete process.env.OPENCLAW_GATEWAY_TOKEN;
delete process.env.OPENCLAW_GATEWAY_PASSWORD;
});
afterEach(() => {
if (prevToken === undefined) delete process.env.CLAWDBOT_GATEWAY_TOKEN;
else process.env.CLAWDBOT_GATEWAY_TOKEN = prevToken;
if (prevPassword === undefined) delete process.env.CLAWDBOT_GATEWAY_PASSWORD;
else process.env.CLAWDBOT_GATEWAY_PASSWORD = prevPassword;
if (prevToken === undefined) delete process.env.OPENCLAW_GATEWAY_TOKEN;
else process.env.OPENCLAW_GATEWAY_TOKEN = prevToken;
if (prevPassword === undefined) delete process.env.OPENCLAW_GATEWAY_PASSWORD;
else process.env.OPENCLAW_GATEWAY_PASSWORD = prevPassword;
});
const lastMessage = () => String(note.mock.calls.at(-1)?.[0] ?? "");
it("warns when exposed without auth", async () => {
const cfg = { gateway: { bind: "lan" } } as MoltbotConfig;
const cfg = { gateway: { bind: "lan" } } as OpenClawConfig;
await noteSecurityWarnings(cfg);
const message = lastMessage();
expect(message).toContain("CRITICAL");
@@ -44,8 +44,8 @@ describe("noteSecurityWarnings gateway exposure", () => {
});
it("uses env token to avoid critical warning", async () => {
process.env.CLAWDBOT_GATEWAY_TOKEN = "token-123";
const cfg = { gateway: { bind: "lan" } } as MoltbotConfig;
process.env.OPENCLAW_GATEWAY_TOKEN = "token-123";
const cfg = { gateway: { bind: "lan" } } as OpenClawConfig;
await noteSecurityWarnings(cfg);
const message = lastMessage();
expect(message).toContain("WARNING");
@@ -55,14 +55,14 @@ describe("noteSecurityWarnings gateway exposure", () => {
it("treats whitespace token as missing", async () => {
const cfg = {
gateway: { bind: "lan", auth: { mode: "token", token: " " } },
} as MoltbotConfig;
} as OpenClawConfig;
await noteSecurityWarnings(cfg);
const message = lastMessage();
expect(message).toContain("CRITICAL");
});
it("skips warning for loopback bind", async () => {
const cfg = { gateway: { bind: "loopback" } } as MoltbotConfig;
const cfg = { gateway: { bind: "loopback" } } as OpenClawConfig;
await noteSecurityWarnings(cfg);
const message = lastMessage();
expect(message).toContain("No channel security warnings detected");
+8 -8
View File
@@ -1,16 +1,16 @@
import { resolveChannelDefaultAccountId } from "../channels/plugins/helpers.js";
import { listChannelPlugins } from "../channels/plugins/index.js";
import type { ChannelId } from "../channels/plugins/types.js";
import type { MoltbotConfig, GatewayBindMode } from "../config/config.js";
import type { OpenClawConfig, GatewayBindMode } from "../config/config.js";
import { readChannelAllowFromStore } from "../pairing/pairing-store.js";
import { note } from "../terminal/note.js";
import { formatCliCommand } from "../cli/command-format.js";
import { resolveGatewayAuth } from "../gateway/auth.js";
import { isLoopbackHost, resolveGatewayBindHost } from "../gateway/net.js";
export async function noteSecurityWarnings(cfg: MoltbotConfig) {
export async function noteSecurityWarnings(cfg: OpenClawConfig) {
const warnings: string[] = [];
const auditHint = `- Run: ${formatCliCommand("moltbot security audit --deep")}`;
const auditHint = `- Run: ${formatCliCommand("openclaw security audit --deep")}`;
// ===========================================
// GATEWAY NETWORK EXPOSURE CHECK
@@ -48,19 +48,19 @@ export async function noteSecurityWarnings(cfg: MoltbotConfig) {
const authFixLines =
resolvedAuth.mode === "password"
? [
` Fix: ${formatCliCommand("moltbot configure")} to set a password`,
` Or switch to token: ${formatCliCommand("moltbot config set gateway.auth.mode token")}`,
` Fix: ${formatCliCommand("openclaw configure")} to set a password`,
` Or switch to token: ${formatCliCommand("openclaw config set gateway.auth.mode token")}`,
]
: [
` Fix: ${formatCliCommand("moltbot doctor --fix")} to generate a token`,
` Fix: ${formatCliCommand("openclaw doctor --fix")} to generate a token`,
` Or set token directly: ${formatCliCommand(
"moltbot config set gateway.auth.mode token",
"openclaw config set gateway.auth.mode token",
)}`,
];
warnings.push(
`- CRITICAL: Gateway bound to ${bindDescriptor} without authentication.`,
` Anyone on your network (or internet if port-forwarded) can fully control your agent.`,
` Fix: ${formatCliCommand("moltbot config set gateway.bind loopback")}`,
` Fix: ${formatCliCommand("openclaw config set gateway.bind loopback")}`,
...authFixLines,
);
} else {
+9 -7
View File
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { resolveDefaultAgentId } from "../agents/agent-scope.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { resolveOAuthDir, resolveStateDir } from "../config/paths.js";
import {
loadSessionStore,
@@ -108,16 +108,18 @@ function findOtherStateDirs(stateDir: string): string[] {
for (const entry of entries) {
if (!entry.isDirectory()) continue;
if (entry.name.startsWith(".")) continue;
const candidate = path.resolve(root, entry.name, ".clawdbot");
if (candidate === resolvedState) continue;
if (existsDir(candidate)) found.push(candidate);
const candidates = [".openclaw"].map((dir) => path.resolve(root, entry.name, dir));
for (const candidate of candidates) {
if (candidate === resolvedState) continue;
if (existsDir(candidate)) found.push(candidate);
}
}
}
return found;
}
export async function noteStateIntegrity(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
prompter: DoctorPrompterLike,
configPath?: string,
) {
@@ -126,7 +128,7 @@ export async function noteStateIntegrity(
const env = process.env;
const homedir = os.homedir;
const stateDir = resolveStateDir(env, homedir);
const defaultStateDir = path.join(homedir(), ".clawdbot");
const defaultStateDir = path.join(homedir(), ".openclaw");
const oauthDir = resolveOAuthDir(env, stateDir);
const agentId = resolveDefaultAgentId(cfg);
const sessionsDir = resolveSessionTranscriptsDirForAgent(agentId, env, homedir);
@@ -354,7 +356,7 @@ export function noteWorkspaceBackupTip(workspaceDir: string) {
note(
[
"- Tip: back up the workspace in a private git repo (GitHub or GitLab).",
"- Keep ~/.clawdbot out of git; it contains credentials and session history.",
"- Keep ~/.openclaw out of git; it contains credentials and session history.",
"- Details: /concepts/agent-workspace#git-backup-recommended",
].join("\n"),
"Workspace",
+31 -54
View File
@@ -4,7 +4,7 @@ import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import {
autoMigrateLegacyStateDir,
autoMigrateLegacyState,
@@ -17,7 +17,7 @@ import {
let tempRoot: string | null = null;
async function makeTempRoot() {
const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), "moltbot-doctor-"));
const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), "openclaw-doctor-"));
tempRoot = root;
return root;
}
@@ -38,7 +38,7 @@ function writeJson5(filePath: string, value: unknown) {
describe("doctor legacy state migrations", () => {
it("migrates legacy sessions into agents/<id>/sessions", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const legacySessionsDir = path.join(root, "sessions");
fs.mkdirSync(legacySessionsDir, { recursive: true });
@@ -54,7 +54,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
const result = await runLegacyStateMigrations({
detected,
@@ -82,7 +82,7 @@ describe("doctor legacy state migrations", () => {
it("migrates legacy agent dir with conflict fallback", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const legacyAgentDir = path.join(root, "agent");
fs.mkdirSync(legacyAgentDir, { recursive: true });
@@ -95,7 +95,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -106,7 +106,7 @@ describe("doctor legacy state migrations", () => {
it("auto-migrates legacy agent dir on startup", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const legacyAgentDir = path.join(root, "agent");
fs.mkdirSync(legacyAgentDir, { recursive: true });
@@ -116,7 +116,7 @@ describe("doctor legacy state migrations", () => {
const result = await autoMigrateLegacyState({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
log,
});
@@ -128,7 +128,7 @@ describe("doctor legacy state migrations", () => {
it("auto-migrates legacy sessions on startup", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const legacySessionsDir = path.join(root, "sessions");
fs.mkdirSync(legacySessionsDir, { recursive: true });
@@ -141,7 +141,7 @@ describe("doctor legacy state migrations", () => {
const result = await autoMigrateLegacyState({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
log,
now: () => 123,
});
@@ -157,7 +157,7 @@ describe("doctor legacy state migrations", () => {
it("migrates legacy WhatsApp auth files without touching oauth.json", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const oauthDir = path.join(root, "credentials");
fs.mkdirSync(oauthDir, { recursive: true });
@@ -167,7 +167,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -180,10 +180,10 @@ describe("doctor legacy state migrations", () => {
it("no-ops when nothing detected", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
const result = await runLegacyStateMigrations({ detected });
expect(result.changes).toEqual([]);
@@ -191,7 +191,7 @@ describe("doctor legacy state migrations", () => {
it("routes legacy state to the default agent entry", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
agents: { list: [{ id: "alpha", default: true }] },
};
const legacySessionsDir = path.join(root, "sessions");
@@ -202,7 +202,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -215,7 +215,7 @@ describe("doctor legacy state migrations", () => {
it("honors session.mainKey when seeding the direct-chat bucket", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = { session: { mainKey: "work" } };
const cfg: OpenClawConfig = { session: { mainKey: "work" } };
const legacySessionsDir = path.join(root, "sessions");
fs.mkdirSync(legacySessionsDir, { recursive: true });
writeJson5(path.join(legacySessionsDir, "sessions.json"), {
@@ -225,7 +225,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -239,7 +239,7 @@ describe("doctor legacy state migrations", () => {
it("canonicalizes legacy main keys inside the target sessions store", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const targetDir = path.join(root, "agents", "main", "sessions");
writeJson5(path.join(targetDir, "sessions.json"), {
main: { sessionId: "legacy", updatedAt: 10 },
@@ -248,7 +248,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -261,7 +261,7 @@ describe("doctor legacy state migrations", () => {
it("prefers the newest entry when collapsing main aliases", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = { session: { mainKey: "work" } };
const cfg: OpenClawConfig = { session: { mainKey: "work" } };
const targetDir = path.join(root, "agents", "main", "sessions");
writeJson5(path.join(targetDir, "sessions.json"), {
"agent:main:main": { sessionId: "legacy", updatedAt: 50 },
@@ -270,7 +270,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -283,7 +283,7 @@ describe("doctor legacy state migrations", () => {
it("lowercases agent session keys during canonicalization", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const targetDir = path.join(root, "agents", "main", "sessions");
writeJson5(path.join(targetDir, "sessions.json"), {
"agent:main:slack:channel:C123": { sessionId: "legacy", updatedAt: 10 },
@@ -291,7 +291,7 @@ describe("doctor legacy state migrations", () => {
const detected = await detectLegacyStateMigrations({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
});
await runLegacyStateMigrations({ detected, now: () => 123 });
@@ -304,7 +304,7 @@ describe("doctor legacy state migrations", () => {
it("auto-migrates when only target sessions contain legacy keys", async () => {
const root = await makeTempRoot();
const cfg: MoltbotConfig = {};
const cfg: OpenClawConfig = {};
const targetDir = path.join(root, "agents", "main", "sessions");
writeJson5(path.join(targetDir, "sessions.json"), {
main: { sessionId: "legacy", updatedAt: 10 },
@@ -314,7 +314,7 @@ describe("doctor legacy state migrations", () => {
const result = await autoMigrateLegacyState({
cfg,
env: { CLAWDBOT_STATE_DIR: root } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
log,
});
@@ -327,48 +327,25 @@ describe("doctor legacy state migrations", () => {
expect(store["agent:main:main"]?.sessionId).toBe("legacy");
});
it("auto-migrates legacy state dir to ~/.moltbot", async () => {
it("does nothing when no legacy state dir exists", async () => {
const root = await makeTempRoot();
const legacyDir = path.join(root, ".clawdbot");
fs.mkdirSync(legacyDir, { recursive: true });
fs.writeFileSync(path.join(legacyDir, "foo.txt"), "legacy", "utf-8");
const result = await autoMigrateLegacyStateDir({
env: {} as NodeJS.ProcessEnv,
homedir: () => root,
});
const targetDir = path.join(root, ".moltbot");
expect(fs.existsSync(path.join(targetDir, "foo.txt"))).toBe(true);
const legacyStat = fs.lstatSync(legacyDir);
expect(legacyStat.isSymbolicLink()).toBe(true);
expect(fs.realpathSync(legacyDir)).toBe(fs.realpathSync(targetDir));
expect(result.migrated).toBe(true);
});
it("skips state dir migration when target exists", async () => {
const root = await makeTempRoot();
const legacyDir = path.join(root, ".clawdbot");
const targetDir = path.join(root, ".moltbot");
fs.mkdirSync(legacyDir, { recursive: true });
fs.mkdirSync(targetDir, { recursive: true });
const result = await autoMigrateLegacyStateDir({
env: {} as NodeJS.ProcessEnv,
homedir: () => root,
});
expect(result.migrated).toBe(false);
expect(result.warnings.length).toBeGreaterThan(0);
expect(result.skipped).toBe(false);
expect(result.warnings).toHaveLength(0);
});
it("skips state dir migration when env override is set", async () => {
const root = await makeTempRoot();
const legacyDir = path.join(root, ".clawdbot");
const legacyDir = path.join(root, ".openclaw");
fs.mkdirSync(legacyDir, { recursive: true });
const result = await autoMigrateLegacyStateDir({
env: { MOLTBOT_STATE_DIR: "/custom/state" } as NodeJS.ProcessEnv,
env: { OPENCLAW_STATE_DIR: "/custom/state" } as NodeJS.ProcessEnv,
homedir: () => root,
});
+2 -2
View File
@@ -1,6 +1,6 @@
import fs from "node:fs/promises";
import path from "node:path";
import { resolveMoltbotPackageRoot } from "../infra/moltbot-root.js";
import { resolveOpenClawPackageRoot } from "../infra/openclaw-root.js";
import { runCommandWithTimeout } from "../process/exec.js";
import type { RuntimeEnv } from "../runtime.js";
import { note } from "../terminal/note.js";
@@ -10,7 +10,7 @@ export async function maybeRepairUiProtocolFreshness(
_runtime: RuntimeEnv,
prompter: DoctorPrompter,
) {
const root = await resolveMoltbotPackageRoot({
const root = await resolveOpenClawPackageRoot({
moduleUrl: import.meta.url,
argv1: process.argv[1],
cwd: process.cwd(),
+5 -5
View File
@@ -6,7 +6,7 @@ import { note } from "../terminal/note.js";
import { formatCliCommand } from "../cli/command-format.js";
import type { DoctorOptions } from "./doctor-prompter.js";
async function detectMoltbotGitCheckout(root: string): Promise<"git" | "not-git" | "unknown"> {
async function detectOpenClawGitCheckout(root: string): Promise<"git" | "not-git" | "unknown"> {
const res = await runCommandWithTimeout(["git", "-C", root, "rev-parse", "--show-toplevel"], {
timeoutMs: 5000,
}).catch(() => null);
@@ -29,7 +29,7 @@ export async function maybeOfferUpdateBeforeDoctor(params: {
confirm: (p: { message: string; initialValue: boolean }) => Promise<boolean>;
outro: (message: string) => void;
}) {
const updateInProgress = isTruthyEnvValue(process.env.CLAWDBOT_UPDATE_IN_PROGRESS);
const updateInProgress = isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS);
const canOfferUpdate =
!updateInProgress &&
params.options.nonInteractive !== true &&
@@ -38,10 +38,10 @@ export async function maybeOfferUpdateBeforeDoctor(params: {
Boolean(process.stdin.isTTY);
if (!canOfferUpdate || !params.root) return { updated: false };
const git = await detectMoltbotGitCheckout(params.root);
const git = await detectOpenClawGitCheckout(params.root);
if (git === "git") {
const shouldUpdate = await params.confirm({
message: "Update Moltbot from git before running doctor?",
message: "Update OpenClaw from git before running doctor?",
initialValue: true,
});
if (!shouldUpdate) return { updated: false };
@@ -72,7 +72,7 @@ export async function maybeOfferUpdateBeforeDoctor(params: {
note(
[
"This install is not a git checkout.",
`Run \`${formatCliCommand("moltbot update")}\` to update via your package manager (npm/pnpm), then rerun doctor.`,
`Run \`${formatCliCommand("openclaw update")}\` to update via your package manager (npm/pnpm), then rerun doctor.`,
].join("\n"),
"Update",
);
+4 -4
View File
@@ -1,11 +1,11 @@
import { resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../agents/agent-scope.js";
import { buildWorkspaceSkillStatus } from "../agents/skills-status.js";
import type { MoltbotConfig } from "../config/config.js";
import { loadMoltbotPlugins } from "../plugins/loader.js";
import type { OpenClawConfig } from "../config/config.js";
import { loadOpenClawPlugins } from "../plugins/loader.js";
import { note } from "../terminal/note.js";
import { detectLegacyWorkspaceDirs, formatLegacyWorkspaceWarning } from "./doctor-workspace.js";
export function noteWorkspaceStatus(cfg: MoltbotConfig) {
export function noteWorkspaceStatus(cfg: OpenClawConfig) {
const workspaceDir = resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg));
const legacyWorkspace = detectLegacyWorkspaceDirs({ workspaceDir });
if (legacyWorkspace.legacyDirs.length > 0) {
@@ -25,7 +25,7 @@ export function noteWorkspaceStatus(cfg: MoltbotConfig) {
"Skills status",
);
const pluginRegistry = loadMoltbotPlugins({
const pluginRegistry = loadOpenClawPlugins({
config: cfg,
workspaceDir,
logger: {
+3 -27
View File
@@ -1,37 +1,13 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { detectLegacyWorkspaceDirs } from "./doctor-workspace.js";
describe("detectLegacyWorkspaceDirs", () => {
it("ignores ~/moltbot when it doesn't look like a workspace (e.g. install dir)", () => {
const home = "/home/user";
const workspaceDir = "/home/user/clawd";
const candidate = path.join(home, "moltbot");
const detection = detectLegacyWorkspaceDirs({
workspaceDir,
homedir: () => home,
exists: (value) => value === candidate,
});
it("returns active workspace and no legacy dirs", () => {
const workspaceDir = "/home/user/openclaw";
const detection = detectLegacyWorkspaceDirs({ workspaceDir });
expect(detection.activeWorkspace).toBe(path.resolve(workspaceDir));
expect(detection.legacyDirs).toEqual([]);
});
it("flags ~/moltbot when it contains workspace markers", () => {
const home = "/home/user";
const workspaceDir = "/home/user/clawd";
const candidate = path.join(home, "moltbot");
const agentsPath = path.join(candidate, "AGENTS.md");
const detection = detectLegacyWorkspaceDirs({
workspaceDir,
homedir: () => home,
exists: (value) => value === candidate || value === agentsPath,
});
expect(detection.legacyDirs).toEqual([candidate]);
});
});
+5 -34
View File
@@ -1,13 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
DEFAULT_AGENTS_FILENAME,
DEFAULT_IDENTITY_FILENAME,
DEFAULT_SOUL_FILENAME,
DEFAULT_USER_FILENAME,
} from "../agents/workspace.js";
import { DEFAULT_AGENTS_FILENAME } from "../agents/workspace.js";
import { shortenHomePath } from "../utils.js";
export const MEMORY_SYSTEM_PROMPT = [
@@ -15,8 +9,8 @@ export const MEMORY_SYSTEM_PROMPT = [
"Paste this into your agent:",
"",
"Install the memory system by applying:",
"https://github.com/moltbot/moltbot/commit/9ffea23f31ca1df5183b25668f8f814bee0fb34e",
"https://github.com/moltbot/moltbot/commit/7d1fee70e76f2f634f1b41fca927ee663914183a",
"https://github.com/openclaw/openclaw/commit/9ffea23f31ca1df5183b25668f8f814bee0fb34e",
"https://github.com/openclaw/openclaw/commit/7d1fee70e76f2f634f1b41fca927ee663914183a",
].join("\n");
export async function shouldSuggestMemorySystem(workspaceDir: string): Promise<boolean> {
@@ -47,34 +41,11 @@ export type LegacyWorkspaceDetection = {
legacyDirs: string[];
};
function looksLikeWorkspaceDir(dir: string, exists: (value: string) => boolean) {
const markers = [
DEFAULT_AGENTS_FILENAME,
DEFAULT_SOUL_FILENAME,
DEFAULT_USER_FILENAME,
DEFAULT_IDENTITY_FILENAME,
];
return markers.some((name) => exists(path.join(dir, name)));
}
export function detectLegacyWorkspaceDirs(params: {
workspaceDir: string;
homedir?: () => string;
exists?: (value: string) => boolean;
}): LegacyWorkspaceDetection {
const homedir = params.homedir ?? os.homedir;
const exists = params.exists ?? fs.existsSync;
const home = homedir();
const activeWorkspace = path.resolve(params.workspaceDir);
const candidates = [path.join(home, "moltbot")];
const legacyDirs = candidates
.filter((candidate) => {
if (!exists(candidate)) return false;
return path.resolve(candidate) !== activeWorkspace;
})
.filter((candidate) => {
return looksLikeWorkspaceDir(candidate, exists);
});
const legacyDirs: string[] = [];
return { activeWorkspace, legacyDirs };
}
@@ -83,6 +54,6 @@ export function formatLegacyWorkspaceWarning(detection: LegacyWorkspaceDetection
"Extra workspace directories detected (may contain old agent files):",
...detection.legacyDirs.map((dir) => `- ${shortenHomePath(dir)}`),
`Active workspace: ${shortenHomePath(detection.activeWorkspace)}`,
"If unused, archive or move to Trash (e.g. trash ~/moltbot).",
"If unused, archive or move to Trash.",
].join("\n");
}
@@ -26,7 +26,7 @@ beforeEach(() => {
readConfigFileSnapshot.mockReset();
writeConfigFile.mockReset().mockResolvedValue(undefined);
resolveMoltbotPackageRoot.mockReset().mockResolvedValue(null);
resolveOpenClawPackageRoot.mockReset().mockResolvedValue(null);
runGatewayUpdate.mockReset().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -34,7 +34,7 @@ beforeEach(() => {
durationMs: 0,
});
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -55,7 +55,7 @@ beforeEach(() => {
killed: false,
});
ensureAuthProfileStore.mockReset().mockReturnValue({ version: 1, profiles: {} });
loadMoltbotPlugins.mockReset().mockReturnValue({ plugins: [], diagnostics: [] });
loadOpenClawPlugins.mockReset().mockReturnValue({ plugins: [], diagnostics: [] });
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
config: raw as Record<string, unknown>,
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
@@ -76,11 +76,11 @@ beforeEach(() => {
originalIsTTY = process.stdin.isTTY;
setStdinTty(true);
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-doctor-state-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
originalStateDir = process.env.OPENCLAW_STATE_DIR;
originalUpdateInProgress = process.env.OPENCLAW_UPDATE_IN_PROGRESS;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-state-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
recursive: true,
});
@@ -90,14 +90,14 @@ beforeEach(() => {
afterEach(() => {
setStdinTty(originalIsTTY);
if (originalStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
process.env.OPENCLAW_STATE_DIR = originalStateDir;
}
if (originalUpdateInProgress === undefined) {
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
} else {
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = originalUpdateInProgress;
}
if (tempStateDir) {
fs.rmSync(tempStateDir, { recursive: true, force: true });
@@ -110,7 +110,7 @@ const confirm = vi.fn().mockResolvedValue(true);
const select = vi.fn().mockResolvedValue("node");
const note = vi.fn();
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
const resolveMoltbotPackageRoot = vi.fn().mockResolvedValue(null);
const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null);
const runGatewayUpdate = vi.fn().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -132,10 +132,10 @@ const runCommandWithTimeout = vi.fn().mockResolvedValue({
});
const ensureAuthProfileStore = vi.fn().mockReturnValue({ version: 1, profiles: {} });
const loadMoltbotPlugins = vi.fn().mockReturnValue({ plugins: [], diagnostics: [] });
const loadOpenClawPlugins = vi.fn().mockReturnValue({ plugins: [], diagnostics: [] });
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -175,13 +175,13 @@ vi.mock("../agents/skills-status.js", () => ({
}));
vi.mock("../plugins/loader.js", () => ({
loadMoltbotPlugins,
loadOpenClawPlugins,
}));
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
CONFIG_PATH: "/tmp/moltbot.json",
CONFIG_PATH: "/tmp/openclaw.json",
createConfigIO,
readConfigFileSnapshot,
writeConfigFile,
@@ -216,8 +216,8 @@ vi.mock("../process/exec.js", () => ({
runCommandWithTimeout,
}));
vi.mock("../infra/moltbot-root.js", () => ({
resolveMoltbotPackageRoot,
vi.mock("../infra/openclaw-root.js", () => ({
resolveOpenClawPackageRoot,
}));
vi.mock("../infra/update-runner.js", () => ({
@@ -333,7 +333,7 @@ vi.mock("./doctor-state-migrations.js", () => ({
describe("doctor command", () => {
it("runs legacy state migrations in non-interactive mode without prompting", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -26,7 +26,7 @@ beforeEach(() => {
readConfigFileSnapshot.mockReset();
writeConfigFile.mockReset().mockResolvedValue(undefined);
resolveMoltbotPackageRoot.mockReset().mockResolvedValue(null);
resolveOpenClawPackageRoot.mockReset().mockResolvedValue(null);
runGatewayUpdate.mockReset().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -34,7 +34,7 @@ beforeEach(() => {
durationMs: 0,
});
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -75,11 +75,11 @@ beforeEach(() => {
originalIsTTY = process.stdin.isTTY;
setStdinTty(true);
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-doctor-state-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
originalStateDir = process.env.OPENCLAW_STATE_DIR;
originalUpdateInProgress = process.env.OPENCLAW_UPDATE_IN_PROGRESS;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-state-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
recursive: true,
});
@@ -89,14 +89,14 @@ beforeEach(() => {
afterEach(() => {
setStdinTty(originalIsTTY);
if (originalStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
process.env.OPENCLAW_STATE_DIR = originalStateDir;
}
if (originalUpdateInProgress === undefined) {
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
} else {
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = originalUpdateInProgress;
}
if (tempStateDir) {
fs.rmSync(tempStateDir, { recursive: true, force: true });
@@ -109,7 +109,7 @@ const confirm = vi.fn().mockResolvedValue(true);
const select = vi.fn().mockResolvedValue("node");
const note = vi.fn();
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
const resolveMoltbotPackageRoot = vi.fn().mockResolvedValue(null);
const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null);
const runGatewayUpdate = vi.fn().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -133,7 +133,7 @@ const runCommandWithTimeout = vi.fn().mockResolvedValue({
const ensureAuthProfileStore = vi.fn().mockReturnValue({ version: 1, profiles: {} });
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -173,14 +173,14 @@ vi.mock("../agents/skills-status.js", () => ({
}));
vi.mock("../plugins/loader.js", () => ({
loadMoltbotPlugins: () => ({ plugins: [], diagnostics: [] }),
loadOpenClawPlugins: () => ({ plugins: [], diagnostics: [] }),
}));
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
CONFIG_PATH: "/tmp/moltbot.json",
CONFIG_PATH: "/tmp/openclaw.json",
createConfigIO,
readConfigFileSnapshot,
writeConfigFile,
@@ -215,8 +215,8 @@ vi.mock("../process/exec.js", () => ({
runCommandWithTimeout,
}));
vi.mock("../infra/moltbot-root.js", () => ({
resolveMoltbotPackageRoot,
vi.mock("../infra/openclaw-root.js", () => ({
resolveOpenClawPackageRoot,
}));
vi.mock("../infra/update-runner.js", () => ({
@@ -332,7 +332,7 @@ vi.mock("./doctor-state-migrations.js", () => ({
describe("doctor command", () => {
it("migrates routing.allowFrom to channels.whatsapp.allowFrom", { timeout: 60_000 }, async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: { routing: { allowFrom: ["+15555550123"] } },
@@ -374,9 +374,9 @@ describe("doctor command", () => {
expect(written.routing).toBeUndefined();
});
it("migrates legacy gateway services", { timeout: 60_000 }, async () => {
it("skips legacy gateway services migration", { timeout: 60_000 }, async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -389,7 +389,7 @@ describe("doctor command", () => {
findLegacyGatewayServices.mockResolvedValueOnce([
{
platform: "darwin",
label: "com.steipete.clawdbot.gateway",
label: "com.steipete.openclaw.gateway",
detail: "loaded",
},
]);
@@ -405,15 +405,15 @@ describe("doctor command", () => {
await doctorCommand(runtime);
expect(uninstallLegacyGatewayServices).toHaveBeenCalledTimes(1);
expect(serviceInstall).toHaveBeenCalledTimes(1);
expect(uninstallLegacyGatewayServices).not.toHaveBeenCalled();
expect(serviceInstall).not.toHaveBeenCalled();
});
it("offers to update first for git checkouts", async () => {
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
const root = "/tmp/moltbot";
resolveMoltbotPackageRoot.mockResolvedValueOnce(root);
const root = "/tmp/openclaw";
resolveOpenClawPackageRoot.mockResolvedValueOnce(root);
runCommandWithTimeout.mockResolvedValueOnce({
stdout: `${root}\n`,
stderr: "",
@@ -430,7 +430,7 @@ describe("doctor command", () => {
});
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -26,7 +26,7 @@ beforeEach(() => {
readConfigFileSnapshot.mockReset();
writeConfigFile.mockReset().mockResolvedValue(undefined);
resolveMoltbotPackageRoot.mockReset().mockResolvedValue(null);
resolveOpenClawPackageRoot.mockReset().mockResolvedValue(null);
runGatewayUpdate.mockReset().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -34,7 +34,7 @@ beforeEach(() => {
durationMs: 0,
});
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -75,11 +75,11 @@ beforeEach(() => {
originalIsTTY = process.stdin.isTTY;
setStdinTty(true);
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-doctor-state-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
originalStateDir = process.env.OPENCLAW_STATE_DIR;
originalUpdateInProgress = process.env.OPENCLAW_UPDATE_IN_PROGRESS;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-state-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
recursive: true,
});
@@ -89,14 +89,14 @@ beforeEach(() => {
afterEach(() => {
setStdinTty(originalIsTTY);
if (originalStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
process.env.OPENCLAW_STATE_DIR = originalStateDir;
}
if (originalUpdateInProgress === undefined) {
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
} else {
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = originalUpdateInProgress;
}
if (tempStateDir) {
fs.rmSync(tempStateDir, { recursive: true, force: true });
@@ -109,7 +109,7 @@ const confirm = vi.fn().mockResolvedValue(true);
const select = vi.fn().mockResolvedValue("node");
const note = vi.fn();
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
const resolveMoltbotPackageRoot = vi.fn().mockResolvedValue(null);
const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null);
const runGatewayUpdate = vi.fn().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -133,7 +133,7 @@ const runCommandWithTimeout = vi.fn().mockResolvedValue({
const ensureAuthProfileStore = vi.fn().mockReturnValue({ version: 1, profiles: {} });
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -173,14 +173,14 @@ vi.mock("../agents/skills-status.js", () => ({
}));
vi.mock("../plugins/loader.js", () => ({
loadMoltbotPlugins: () => ({ plugins: [], diagnostics: [] }),
loadOpenClawPlugins: () => ({ plugins: [], diagnostics: [] }),
}));
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
CONFIG_PATH: "/tmp/moltbot.json",
CONFIG_PATH: "/tmp/openclaw.json",
createConfigIO,
readConfigFileSnapshot,
writeConfigFile,
@@ -215,8 +215,8 @@ vi.mock("../process/exec.js", () => ({
runCommandWithTimeout,
}));
vi.mock("../infra/moltbot-root.js", () => ({
resolveMoltbotPackageRoot,
vi.mock("../infra/openclaw-root.js", () => ({
resolveOpenClawPackageRoot,
}));
vi.mock("../infra/update-runner.js", () => ({
@@ -332,7 +332,7 @@ vi.mock("./doctor-state-migrations.js", () => ({
describe("doctor command", () => {
it("runs legacy state migrations in yes mode without prompting", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -391,7 +391,7 @@ describe("doctor command", () => {
it("skips gateway restarts in non-interactive mode", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -423,7 +423,7 @@ describe("doctor command", () => {
it("migrates anthropic oauth config profile id when only email profile exists", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
+12 -12
View File
@@ -10,13 +10,13 @@ import {
resolveHooksGmailModel,
} from "../agents/model-selection.js";
import { formatCliCommand } from "../cli/command-format.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { CONFIG_PATH, readConfigFileSnapshot, writeConfigFile } from "../config/config.js";
import { logConfigUpdated } from "../config/logging.js";
import { resolveGatewayService } from "../daemon/service.js";
import { resolveGatewayAuth } from "../gateway/auth.js";
import { buildGatewayConnectionDetails } from "../gateway/call.js";
import { resolveMoltbotPackageRoot } from "../infra/moltbot-root.js";
import { resolveOpenClawPackageRoot } from "../infra/openclaw-root.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { note } from "../terminal/note.js";
@@ -31,7 +31,6 @@ import { loadAndMaybeMigrateDoctorConfig } from "./doctor-config-flow.js";
import { maybeRepairGatewayDaemon } from "./doctor-gateway-daemon-flow.js";
import { checkGatewayHealth } from "./doctor-gateway-health.js";
import {
maybeMigrateLegacyGatewayService,
maybeRepairGatewayServiceConfig,
maybeScanExtraGatewayServices,
} from "./doctor-gateway-services.js";
@@ -39,6 +38,7 @@ import { noteSourceInstallIssues } from "./doctor-install.js";
import {
noteMacLaunchAgentOverrides,
noteMacLaunchctlGatewayEnvOverrides,
noteDeprecatedLegacyEnvVars,
} from "./doctor-platform-notes.js";
import { createDoctorPrompter, type DoctorOptions } from "./doctor-prompter.js";
import { maybeRepairSandboxImages, noteSandboxScopeWarnings } from "./doctor-sandbox.js";
@@ -58,7 +58,7 @@ import { ensureSystemdUserLingerInteractive } from "./systemd-linger.js";
const intro = (message: string) => clackIntro(stylePromptTitle(message) ?? message);
const outro = (message: string) => clackOutro(stylePromptTitle(message) ?? message);
function resolveMode(cfg: MoltbotConfig): "local" | "remote" {
function resolveMode(cfg: OpenClawConfig): "local" | "remote" {
return cfg.gateway?.mode === "remote" ? "remote" : "local";
}
@@ -68,9 +68,9 @@ export async function doctorCommand(
) {
const prompter = createDoctorPrompter({ runtime, options });
printWizardHeader(runtime);
intro("Moltbot doctor");
intro("OpenClaw doctor");
const root = await resolveMoltbotPackageRoot({
const root = await resolveOpenClawPackageRoot({
moduleUrl: import.meta.url,
argv1: process.argv[1],
cwd: process.cwd(),
@@ -87,22 +87,23 @@ export async function doctorCommand(
await maybeRepairUiProtocolFreshness(runtime, prompter);
noteSourceInstallIssues(root);
noteDeprecatedLegacyEnvVars();
const configResult = await loadAndMaybeMigrateDoctorConfig({
options,
confirm: (p) => prompter.confirm(p),
});
let cfg: MoltbotConfig = configResult.cfg;
let cfg: OpenClawConfig = configResult.cfg;
const configPath = configResult.path ?? CONFIG_PATH;
if (!cfg.gateway?.mode) {
const lines = [
"gateway.mode is unset; gateway start will be blocked.",
`Fix: run ${formatCliCommand("moltbot configure")} and set Gateway mode (local/remote).`,
`Or set directly: ${formatCliCommand("moltbot config set gateway.mode local")}`,
`Fix: run ${formatCliCommand("openclaw configure")} and set Gateway mode (local/remote).`,
`Or set directly: ${formatCliCommand("openclaw config set gateway.mode local")}`,
];
if (!fs.existsSync(configPath)) {
lines.push(`Missing config: run ${formatCliCommand("moltbot setup")} first.`);
lines.push(`Missing config: run ${formatCliCommand("openclaw setup")} first.`);
}
note(lines.join("\n"), "Gateway");
}
@@ -184,7 +185,6 @@ export async function doctorCommand(
cfg = await maybeRepairSandboxImages(cfg, runtime, prompter);
noteSandboxScopeWarnings(cfg);
await maybeMigrateLegacyGatewayService(cfg, resolveMode(cfg), runtime, prompter);
await maybeScanExtraGatewayServices(options);
await maybeRepairGatewayServiceConfig(cfg, resolveMode(cfg), runtime, prompter);
await noteMacLaunchAgentOverrides();
@@ -282,7 +282,7 @@ export async function doctorCommand(
runtime.log(`Backup: ${shortenHomePath(backupPath)}`);
}
} else {
runtime.log(`Run "${formatCliCommand("moltbot doctor --fix")}" to apply changes.`);
runtime.log(`Run "${formatCliCommand("openclaw doctor --fix")}" to apply changes.`);
}
if (options.workspaceSuggestions !== false) {
@@ -26,7 +26,7 @@ beforeEach(() => {
readConfigFileSnapshot.mockReset();
writeConfigFile.mockReset().mockResolvedValue(undefined);
resolveMoltbotPackageRoot.mockReset().mockResolvedValue(null);
resolveOpenClawPackageRoot.mockReset().mockResolvedValue(null);
runGatewayUpdate.mockReset().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -34,7 +34,7 @@ beforeEach(() => {
durationMs: 0,
});
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -75,11 +75,11 @@ beforeEach(() => {
originalIsTTY = process.stdin.isTTY;
setStdinTty(true);
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-doctor-state-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
originalStateDir = process.env.OPENCLAW_STATE_DIR;
originalUpdateInProgress = process.env.OPENCLAW_UPDATE_IN_PROGRESS;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-state-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
recursive: true,
});
@@ -89,14 +89,14 @@ beforeEach(() => {
afterEach(() => {
setStdinTty(originalIsTTY);
if (originalStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
process.env.OPENCLAW_STATE_DIR = originalStateDir;
}
if (originalUpdateInProgress === undefined) {
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
} else {
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = originalUpdateInProgress;
}
if (tempStateDir) {
fs.rmSync(tempStateDir, { recursive: true, force: true });
@@ -109,7 +109,7 @@ const confirm = vi.fn().mockResolvedValue(true);
const select = vi.fn().mockResolvedValue("node");
const note = vi.fn();
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
const resolveMoltbotPackageRoot = vi.fn().mockResolvedValue(null);
const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null);
const runGatewayUpdate = vi.fn().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -133,7 +133,7 @@ const runCommandWithTimeout = vi.fn().mockResolvedValue({
const ensureAuthProfileStore = vi.fn().mockReturnValue({ version: 1, profiles: {} });
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -173,14 +173,14 @@ vi.mock("../agents/skills-status.js", () => ({
}));
vi.mock("../plugins/loader.js", () => ({
loadMoltbotPlugins: () => ({ plugins: [], diagnostics: [] }),
loadOpenClawPlugins: () => ({ plugins: [], diagnostics: [] }),
}));
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
CONFIG_PATH: "/tmp/moltbot.json",
CONFIG_PATH: "/tmp/openclaw.json",
createConfigIO,
readConfigFileSnapshot,
writeConfigFile,
@@ -215,8 +215,8 @@ vi.mock("../process/exec.js", () => ({
runCommandWithTimeout,
}));
vi.mock("../infra/moltbot-root.js", () => ({
resolveMoltbotPackageRoot,
vi.mock("../infra/openclaw-root.js", () => ({
resolveOpenClawPackageRoot,
}));
vi.mock("../infra/update-runner.js", () => ({
@@ -332,7 +332,7 @@ vi.mock("./doctor-state-migrations.js", () => ({
describe("doctor command", () => {
it("warns when per-agent sandbox docker/browser/prune overrides are ignored under shared scope", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -348,7 +348,7 @@ describe("doctor command", () => {
list: [
{
id: "work",
workspace: "~/clawd-work",
workspace: "~/openclaw-work",
sandbox: {
mode: "all",
scope: "shared",
@@ -387,15 +387,15 @@ describe("doctor command", () => {
).toBe(true);
}, 30_000);
it("warns when extra workspace directories exist", async () => {
it("does not warn when only the active workspace is present", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
valid: true,
config: {
agents: { defaults: { workspace: "/Users/steipete/clawd" } },
agents: { defaults: { workspace: "/Users/steipete/openclaw" } },
},
issues: [],
legacyIssues: [],
@@ -404,10 +404,14 @@ describe("doctor command", () => {
note.mockClear();
const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue("/Users/steipete");
const realExists = fs.existsSync;
const legacyPath = path.join("/Users/steipete", "moltbot");
const legacyPath = path.join("/Users/steipete", "openclaw");
const legacyAgentsPath = path.join(legacyPath, "AGENTS.md");
const existsSpy = vi.spyOn(fs, "existsSync").mockImplementation((value) => {
if (value === "/Users/steipete/moltbot" || value === legacyPath || value === legacyAgentsPath)
if (
value === "/Users/steipete/openclaw" ||
value === legacyPath ||
value === legacyAgentsPath
)
return true;
return realExists(value as never);
});
@@ -421,12 +425,7 @@ describe("doctor command", () => {
await doctorCommand(runtime, { nonInteractive: true });
expect(
note.mock.calls.some(
([message, title]) =>
title === "Extra workspace" && typeof message === "string" && message.includes("moltbot"),
),
).toBe(true);
expect(note.mock.calls.some(([_, title]) => title === "Extra workspace")).toBe(false);
homedirSpy.mockRestore();
existsSpy.mockRestore();
@@ -26,7 +26,7 @@ beforeEach(() => {
readConfigFileSnapshot.mockReset();
writeConfigFile.mockReset().mockResolvedValue(undefined);
resolveMoltbotPackageRoot.mockReset().mockResolvedValue(null);
resolveOpenClawPackageRoot.mockReset().mockResolvedValue(null);
runGatewayUpdate.mockReset().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -34,7 +34,7 @@ beforeEach(() => {
durationMs: 0,
});
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -75,11 +75,11 @@ beforeEach(() => {
originalIsTTY = process.stdin.isTTY;
setStdinTty(true);
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-doctor-state-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
originalStateDir = process.env.OPENCLAW_STATE_DIR;
originalUpdateInProgress = process.env.OPENCLAW_UPDATE_IN_PROGRESS;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
tempStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-state-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
recursive: true,
});
@@ -89,14 +89,14 @@ beforeEach(() => {
afterEach(() => {
setStdinTty(originalIsTTY);
if (originalStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
process.env.OPENCLAW_STATE_DIR = originalStateDir;
}
if (originalUpdateInProgress === undefined) {
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
} else {
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
process.env.OPENCLAW_UPDATE_IN_PROGRESS = originalUpdateInProgress;
}
if (tempStateDir) {
fs.rmSync(tempStateDir, { recursive: true, force: true });
@@ -109,7 +109,7 @@ const confirm = vi.fn().mockResolvedValue(true);
const select = vi.fn().mockResolvedValue("node");
const note = vi.fn();
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
const resolveMoltbotPackageRoot = vi.fn().mockResolvedValue(null);
const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null);
const runGatewayUpdate = vi.fn().mockResolvedValue({
status: "skipped",
mode: "unknown",
@@ -133,7 +133,7 @@ const runCommandWithTimeout = vi.fn().mockResolvedValue({
const ensureAuthProfileStore = vi.fn().mockReturnValue({ version: 1, profiles: {} });
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: false,
raw: null,
parsed: {},
@@ -173,14 +173,14 @@ vi.mock("../agents/skills-status.js", () => ({
}));
vi.mock("../plugins/loader.js", () => ({
loadMoltbotPlugins: () => ({ plugins: [], diagnostics: [] }),
loadOpenClawPlugins: () => ({ plugins: [], diagnostics: [] }),
}));
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
CONFIG_PATH: "/tmp/moltbot.json",
CONFIG_PATH: "/tmp/openclaw.json",
createConfigIO,
readConfigFileSnapshot,
writeConfigFile,
@@ -215,8 +215,8 @@ vi.mock("../process/exec.js", () => ({
runCommandWithTimeout,
}));
vi.mock("../infra/moltbot-root.js", () => ({
resolveMoltbotPackageRoot,
vi.mock("../infra/openclaw-root.js", () => ({
resolveOpenClawPackageRoot,
}));
vi.mock("../infra/update-runner.js", () => ({
@@ -336,7 +336,7 @@ vi.mock("./doctor-update.js", () => ({
describe("doctor command", () => {
it("warns when the state directory is missing", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -346,9 +346,9 @@ describe("doctor command", () => {
legacyIssues: [],
});
const missingDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-missing-state-"));
const missingDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-missing-state-"));
fs.rmSync(missingDir, { recursive: true, force: true });
process.env.CLAWDBOT_STATE_DIR = missingDir;
process.env.OPENCLAW_STATE_DIR = missingDir;
note.mockClear();
const { doctorCommand } = await import("./doctor.js");
@@ -364,7 +364,7 @@ describe("doctor command", () => {
it("warns about opencode provider overrides", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -396,9 +396,9 @@ describe("doctor command", () => {
expect(warned).toBe(true);
});
it("skips gateway auth warning when CLAWDBOT_GATEWAY_TOKEN is set", async () => {
it("skips gateway auth warning when OPENCLAW_GATEWAY_TOKEN is set", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -410,8 +410,8 @@ describe("doctor command", () => {
legacyIssues: [],
});
const prevToken = process.env.CLAWDBOT_GATEWAY_TOKEN;
process.env.CLAWDBOT_GATEWAY_TOKEN = "env-token-1234567890";
const prevToken = process.env.OPENCLAW_GATEWAY_TOKEN;
process.env.OPENCLAW_GATEWAY_TOKEN = "env-token-1234567890";
note.mockClear();
try {
@@ -421,8 +421,8 @@ describe("doctor command", () => {
{ nonInteractive: true, workspaceSuggestions: false },
);
} finally {
if (prevToken === undefined) delete process.env.CLAWDBOT_GATEWAY_TOKEN;
else process.env.CLAWDBOT_GATEWAY_TOKEN = prevToken;
if (prevToken === undefined) delete process.env.OPENCLAW_GATEWAY_TOKEN;
else process.env.OPENCLAW_GATEWAY_TOKEN = prevToken;
}
const warned = note.mock.calls.some(([message]) =>
+8 -2
View File
@@ -2,6 +2,7 @@ import { withProgress } from "../cli/progress.js";
import { loadConfig, resolveGatewayPort } from "../config/config.js";
import { probeGateway } from "../gateway/probe.js";
import { discoverGatewayBeacons } from "../infra/bonjour-discovery.js";
import { resolveWideAreaDiscoveryDomain } from "../infra/widearea-dns.js";
import { resolveSshConfig } from "../infra/ssh-config.js";
import { parseSshTarget, startSshPortForward } from "../infra/ssh-tunnel.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -38,6 +39,9 @@ export async function gatewayStatusCommand(
const cfg = loadConfig();
const rich = isRich() && opts.json !== true;
const overallTimeoutMs = parseTimeoutMs(opts.timeout, 3000);
const wideAreaDomain = resolveWideAreaDiscoveryDomain({
configDomain: cfg.discovery?.wideArea?.domain,
});
const baseTargets = resolveTargets(cfg, opts.url);
const network = buildNetworkHints(cfg);
@@ -45,6 +49,7 @@ export async function gatewayStatusCommand(
const discoveryTimeoutMs = Math.min(1200, overallTimeoutMs);
const discoveryPromise = discoverGatewayBeacons({
timeoutMs: discoveryTimeoutMs,
wideAreaDomain,
});
let sshTarget = sanitizeSshTarget(opts.ssh) ?? sanitizeSshTarget(cfg.gateway?.remote?.sshTarget);
@@ -276,10 +281,11 @@ export async function gatewayStatusCommand(
runtime.log("");
runtime.log(colorize(rich, theme.heading, "Discovery (this machine)"));
const discoveryDomains = wideAreaDomain ? `local. + ${wideAreaDomain}` : "local.";
runtime.log(
discovery.length > 0
? `Found ${discovery.length} gateway(s) via Bonjour (local. + moltbot.internal.)`
: "Found 0 gateways via Bonjour (local. + moltbot.internal.)",
? `Found ${discovery.length} gateway(s) via Bonjour (${discoveryDomains})`
: `Found 0 gateways via Bonjour (${discoveryDomains})`,
);
if (discovery.length === 0) {
runtime.log(
+6 -6
View File
@@ -1,5 +1,5 @@
import { resolveGatewayPort } from "../../config/config.js";
import type { MoltbotConfig, ConfigFileSnapshot } from "../../config/types.js";
import type { OpenClawConfig, ConfigFileSnapshot } from "../../config/types.js";
import type { GatewayProbeResult } from "../../gateway/probe.js";
import { pickPrimaryTailnetIPv4 } from "../../infra/tailnet.js";
import { colorize, theme } from "../../terminal/theme.js";
@@ -79,7 +79,7 @@ function normalizeWsUrl(value: string): string | null {
return trimmed;
}
export function resolveTargets(cfg: MoltbotConfig, explicitUrl?: string): GatewayStatusTarget[] {
export function resolveTargets(cfg: OpenClawConfig, explicitUrl?: string): GatewayStatusTarget[] {
const targets: GatewayStatusTarget[] = [];
const add = (t: GatewayStatusTarget) => {
if (!targets.some((x) => x.url === t.url)) targets.push(t);
@@ -124,7 +124,7 @@ export function sanitizeSshTarget(value: unknown): string | null {
}
export function resolveAuthForTarget(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
target: GatewayStatusTarget,
overrides: { token?: string; password?: string },
): { token?: string; password?: string } {
@@ -145,8 +145,8 @@ export function resolveAuthForTarget(
};
}
const envToken = process.env.CLAWDBOT_GATEWAY_TOKEN?.trim() || "";
const envPassword = process.env.CLAWDBOT_GATEWAY_PASSWORD?.trim() || "";
const envToken = process.env.OPENCLAW_GATEWAY_TOKEN?.trim() || "";
const envPassword = process.env.OPENCLAW_GATEWAY_PASSWORD?.trim() || "";
const cfgToken =
typeof cfg.gateway?.auth?.token === "string" ? cfg.gateway.auth.token.trim() : "";
const cfgPassword =
@@ -239,7 +239,7 @@ export function extractConfigSummary(snapshotUnknown: unknown): GatewayConfigSum
};
}
export function buildNetworkHints(cfg: MoltbotConfig) {
export function buildNetworkHints(cfg: OpenClawConfig) {
const tailnetIPv4 = pickPrimaryTailnetIPv4();
const port = resolveGatewayPort(cfg);
return {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import {
applyGoogleGeminiModelDefault,
GOOGLE_GEMINI_DEFAULT_MODEL,
@@ -8,7 +8,7 @@ import {
describe("applyGoogleGeminiModelDefault", () => {
it("sets gemini default when model is unset", () => {
const cfg: MoltbotConfig = { agents: { defaults: {} } };
const cfg: OpenClawConfig = { agents: { defaults: {} } };
const applied = applyGoogleGeminiModelDefault(cfg);
expect(applied.changed).toBe(true);
expect(applied.next.agents?.defaults?.model).toEqual({
@@ -17,7 +17,7 @@ describe("applyGoogleGeminiModelDefault", () => {
});
it("overrides existing model", () => {
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
agents: { defaults: { model: "anthropic/claude-opus-4-5" } },
};
const applied = applyGoogleGeminiModelDefault(cfg);
@@ -28,7 +28,7 @@ describe("applyGoogleGeminiModelDefault", () => {
});
it("no-ops when already gemini default", () => {
const cfg: MoltbotConfig = {
const cfg: OpenClawConfig = {
agents: { defaults: { model: GOOGLE_GEMINI_DEFAULT_MODEL } },
};
const applied = applyGoogleGeminiModelDefault(cfg);
+3 -3
View File
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { AgentModelListConfig } from "../config/types.js";
export const GOOGLE_GEMINI_DEFAULT_MODEL = "google/gemini-3-pro-preview";
@@ -11,8 +11,8 @@ function resolvePrimaryModel(model?: AgentModelListConfig | string): string | un
return undefined;
}
export function applyGoogleGeminiModelDefault(cfg: MoltbotConfig): {
next: MoltbotConfig;
export function applyGoogleGeminiModelDefault(cfg: OpenClawConfig): {
next: OpenClawConfig;
changed: boolean;
} {
const current = resolvePrimaryModel(cfg.agents?.defaults?.model)?.trim();
+2 -2
View File
@@ -20,7 +20,7 @@ describe("formatHealthCheckFailure", () => {
"gateway closed (1006 abnormal closure (no close frame)): no close reason",
"Gateway target: ws://127.0.0.1:19001",
"Source: local loopback",
"Config: /Users/steipete/.clawdbot-dev/moltbot.json",
"Config: /Users/steipete/.openclaw-dev/openclaw.json",
"Bind: loopback",
].join("\n"),
);
@@ -30,7 +30,7 @@ describe("formatHealthCheckFailure", () => {
"Health check failed: gateway closed (1006 abnormal closure (no close frame)): no close reason",
" Gateway target: ws://127.0.0.1:19001",
" Source: local loopback",
" Config: /Users/steipete/.clawdbot-dev/moltbot.json",
" Config: /Users/steipete/.openclaw-dev/openclaw.json",
" Bind: loopback",
].join("\n"),
);
+1 -1
View File
@@ -135,7 +135,7 @@ describe("getHealthSnapshot", () => {
});
it("treats telegram.tokenFile as configured", async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-health-"));
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-health-"));
const tokenFile = path.join(tmpDir, "telegram-token");
fs.writeFileSync(tokenFile, "t-file\n", "utf-8");
testConfig = { channels: { telegram: { tokenFile } } };
+4 -4
View File
@@ -3,7 +3,7 @@ import { resolveChannelDefaultAccountId } from "../channels/plugins/helpers.js";
import { getChannelPlugin, listChannelPlugins } from "../channels/plugins/index.js";
import type { ChannelAccountSnapshot } from "../channels/plugins/types.js";
import { withProgress } from "../cli/progress.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { loadConfig } from "../config/config.js";
import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
import { buildGatewayConnectionDetails, callGateway } from "../gateway/call.js";
@@ -73,7 +73,7 @@ export type HealthSummary = {
const DEFAULT_TIMEOUT_MS = 10_000;
const debugHealth = (...args: unknown[]) => {
if (isTruthyEnvValue(process.env.CLAWDBOT_DEBUG_HEALTH)) {
if (isTruthyEnvValue(process.env.OPENCLAW_DEBUG_HEALTH)) {
console.warn("[health:debug]", ...args);
}
};
@@ -502,7 +502,7 @@ export async function getHealthSnapshot(params?: {
}
export async function healthCommand(
opts: { json?: boolean; timeoutMs?: number; verbose?: boolean; config?: MoltbotConfig },
opts: { json?: boolean; timeoutMs?: number; verbose?: boolean; config?: OpenClawConfig },
runtime: RuntimeEnv,
) {
const cfg = opts.config ?? loadConfig();
@@ -527,7 +527,7 @@ export async function healthCommand(
if (opts.json) {
runtime.log(JSON.stringify(summary, null, 2));
} else {
const debugEnabled = isTruthyEnvValue(process.env.CLAWDBOT_DEBUG_HEALTH);
const debugEnabled = isTruthyEnvValue(process.env.OPENCLAW_DEBUG_HEALTH);
if (opts.verbose) {
const details = buildGatewayConnectionDetails({ config: cfg });
runtime.log(info("Gateway connection:"));
+8 -8
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { makePrompter } from "./onboarding/__tests__/test-utils.js";
import {
applyModelAllowlist,
@@ -53,7 +53,7 @@ describe("promptDefaultModel", () => {
return first?.value ?? "";
});
const prompter = makePrompter({ select });
const config = { agents: { defaults: {} } } as MoltbotConfig;
const config = { agents: { defaults: {} } } as OpenClawConfig;
await promptDefaultModel({
config,
@@ -90,7 +90,7 @@ describe("promptModelAllowlist", () => {
params.options.map((option: { value: string }) => option.value),
);
const prompter = makePrompter({ multiselect });
const config = { agents: { defaults: {} } } as MoltbotConfig;
const config = { agents: { defaults: {} } } as OpenClawConfig;
await promptModelAllowlist({ config, prompter });
@@ -126,7 +126,7 @@ describe("promptModelAllowlist", () => {
params.options.map((option: { value: string }) => option.value),
);
const prompter = makePrompter({ multiselect });
const config = { agents: { defaults: {} } } as MoltbotConfig;
const config = { agents: { defaults: {} } } as OpenClawConfig;
await promptModelAllowlist({
config,
@@ -152,7 +152,7 @@ describe("applyModelAllowlist", () => {
},
},
},
} as MoltbotConfig;
} as OpenClawConfig;
const next = applyModelAllowlist(config, ["openai/gpt-5.2"]);
expect(next.agents?.defaults?.models).toEqual({
@@ -169,7 +169,7 @@ describe("applyModelAllowlist", () => {
},
},
},
} as MoltbotConfig;
} as OpenClawConfig;
const next = applyModelAllowlist(config, []);
expect(next.agents?.defaults?.models).toBeUndefined();
@@ -184,7 +184,7 @@ describe("applyModelFallbacksFromSelection", () => {
model: { primary: "anthropic/claude-opus-4-5" },
},
},
} as MoltbotConfig;
} as OpenClawConfig;
const next = applyModelFallbacksFromSelection(config, [
"anthropic/claude-opus-4-5",
@@ -203,7 +203,7 @@ describe("applyModelFallbacksFromSelection", () => {
model: { primary: "anthropic/claude-opus-4-5", fallbacks: ["openai/gpt-5.2"] },
},
},
} as MoltbotConfig;
} as OpenClawConfig;
const next = applyModelFallbacksFromSelection(config, ["openai/gpt-5.2"]);
expect(next.agents?.defaults?.model).toEqual({
+10 -10
View File
@@ -9,7 +9,7 @@ import {
normalizeProviderId,
resolveConfiguredModelRef,
} from "../agents/model-selection.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { WizardPrompter, WizardSelectOption } from "../wizard/prompts.js";
import { formatTokenK } from "./models/shared.js";
@@ -23,7 +23,7 @@ const PROVIDER_FILTER_THRESHOLD = 30;
const HIDDEN_ROUTER_MODELS = new Set(["openrouter/auto"]);
type PromptDefaultModelParams = {
config: MoltbotConfig;
config: OpenClawConfig;
prompter: WizardPrompter;
allowKeep?: boolean;
includeManual?: boolean;
@@ -38,7 +38,7 @@ type PromptModelAllowlistResult = { models?: string[] };
function hasAuthForProvider(
provider: string,
cfg: MoltbotConfig,
cfg: OpenClawConfig,
store: ReturnType<typeof ensureAuthProfileStore>,
) {
if (listProfilesForProvider(store, provider).length > 0) return true;
@@ -47,13 +47,13 @@ function hasAuthForProvider(
return false;
}
function resolveConfiguredModelRaw(cfg: MoltbotConfig): string {
function resolveConfiguredModelRaw(cfg: OpenClawConfig): string {
const raw = cfg.agents?.defaults?.model as { primary?: string } | string | undefined;
if (typeof raw === "string") return raw.trim();
return raw?.primary?.trim() ?? "";
}
function resolveConfiguredModelKeys(cfg: MoltbotConfig): string[] {
function resolveConfiguredModelKeys(cfg: OpenClawConfig): string[] {
const models = cfg.agents?.defaults?.models ?? {};
return Object.keys(models)
.map((key) => String(key ?? "").trim())
@@ -266,7 +266,7 @@ export async function promptDefaultModel(
}
export async function promptModelAllowlist(params: {
config: MoltbotConfig;
config: OpenClawConfig;
prompter: WizardPrompter;
message?: string;
agentDir?: string;
@@ -387,7 +387,7 @@ export async function promptModelAllowlist(params: {
return { models: [] };
}
export function applyPrimaryModel(cfg: MoltbotConfig, model: string): MoltbotConfig {
export function applyPrimaryModel(cfg: OpenClawConfig, model: string): OpenClawConfig {
const defaults = cfg.agents?.defaults;
const existingModel = defaults?.model;
const existingModels = defaults?.models;
@@ -414,7 +414,7 @@ export function applyPrimaryModel(cfg: MoltbotConfig, model: string): MoltbotCon
};
}
export function applyModelAllowlist(cfg: MoltbotConfig, models: string[]): MoltbotConfig {
export function applyModelAllowlist(cfg: OpenClawConfig, models: string[]): OpenClawConfig {
const defaults = cfg.agents?.defaults;
const normalized = normalizeModelKeys(models);
if (normalized.length === 0) {
@@ -448,9 +448,9 @@ export function applyModelAllowlist(cfg: MoltbotConfig, models: string[]): Moltb
}
export function applyModelFallbacksFromSelection(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
selection: string[],
): MoltbotConfig {
): OpenClawConfig {
const normalized = normalizeModelKeys(selection);
if (normalized.length <= 1) return cfg;
+7 -7
View File
@@ -1,14 +1,14 @@
import { describe, expect, it, vi } from "vitest";
const loadConfig = vi.fn();
const ensureMoltbotModelsJson = vi.fn().mockResolvedValue(undefined);
const resolveMoltbotAgentDir = vi.fn().mockReturnValue("/tmp/moltbot-agent");
const ensureOpenClawModelsJson = vi.fn().mockResolvedValue(undefined);
const resolveOpenClawAgentDir = vi.fn().mockReturnValue("/tmp/openclaw-agent");
const ensureAuthProfileStore = vi.fn().mockReturnValue({ version: 1, profiles: {} });
const listProfilesForProvider = vi.fn().mockReturnValue([]);
const resolveAuthProfileDisplayLabel = vi.fn(({ profileId }: { profileId: string }) => profileId);
const resolveAuthStorePathForDisplay = vi
.fn()
.mockReturnValue("/tmp/moltbot-agent/auth-profiles.json");
.mockReturnValue("/tmp/openclaw-agent/auth-profiles.json");
const resolveProfileUnusableUntilForDisplay = vi.fn().mockReturnValue(null);
const resolveEnvApiKey = vi.fn().mockReturnValue(undefined);
const resolveAwsSdkEnvVarName = vi.fn().mockReturnValue(undefined);
@@ -17,17 +17,17 @@ const discoverAuthStorage = vi.fn().mockReturnValue({});
const discoverModels = vi.fn();
vi.mock("../config/config.js", () => ({
CONFIG_PATH: "/tmp/moltbot.json",
STATE_DIR: "/tmp/moltbot-state",
CONFIG_PATH: "/tmp/openclaw.json",
STATE_DIR: "/tmp/openclaw-state",
loadConfig,
}));
vi.mock("../agents/models-config.js", () => ({
ensureMoltbotModelsJson,
ensureOpenClawModelsJson,
}));
vi.mock("../agents/agent-paths.js", () => ({
resolveMoltbotAgentDir,
resolveOpenClawAgentDir,
}));
vi.mock("../agents/auth-profiles.js", () => ({
+4 -4
View File
@@ -5,7 +5,7 @@ const writeConfigFile = vi.fn().mockResolvedValue(undefined);
const loadConfig = vi.fn().mockReturnValue({});
vi.mock("../config/config.js", () => ({
CONFIG_PATH: "/tmp/moltbot.json",
CONFIG_PATH: "/tmp/openclaw.json",
readConfigFileSnapshot,
writeConfigFile,
loadConfig,
@@ -19,7 +19,7 @@ describe("models set + fallbacks", () => {
it("normalizes z.ai provider in models set", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -46,7 +46,7 @@ describe("models set + fallbacks", () => {
it("normalizes z-ai provider in models fallbacks add", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
@@ -73,7 +73,7 @@ describe("models set + fallbacks", () => {
it("normalizes provider casing in models set", async () => {
readConfigFileSnapshot.mockResolvedValue({
path: "/tmp/moltbot.json",
path: "/tmp/openclaw.json",
exists: true,
raw: "{}",
parsed: {},
+3 -3
View File
@@ -10,7 +10,7 @@ import {
import { resolveDefaultAgentWorkspaceDir } from "../../agents/workspace.js";
import { parseDurationMs } from "../../cli/parse-duration.js";
import { formatCliCommand } from "../../cli/command-format.js";
import { readConfigFileSnapshot, type MoltbotConfig } from "../../config/config.js";
import { readConfigFileSnapshot, type OpenClawConfig } from "../../config/config.js";
import { logConfigUpdated } from "../../config/logging.js";
import type { RuntimeEnv } from "../../runtime.js";
import { stylePromptHint, stylePromptMessage } from "../../terminal/prompt-style.js";
@@ -283,7 +283,7 @@ function mergeConfigPatch<T>(base: T, patch: unknown): T {
return next as T;
}
function applyDefaultModel(cfg: MoltbotConfig, model: string): MoltbotConfig {
function applyDefaultModel(cfg: OpenClawConfig, model: string): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[model] = models[model] ?? {};
@@ -332,7 +332,7 @@ export async function modelsAuthLoginCommand(opts: LoginOptions, runtime: Runtim
const providers = resolvePluginProviders({ config, workspaceDir });
if (providers.length === 0) {
throw new Error(
`No provider plugins found. Install one via \`${formatCliCommand("moltbot plugins install")}\`.`,
`No provider plugins found. Install one via \`${formatCliCommand("openclaw plugins install")}\`.`,
);
}
+2 -2
View File
@@ -7,14 +7,14 @@ import {
resolveProfileUnusableUntilForDisplay,
} from "../../agents/auth-profiles.js";
import { getCustomProviderApiKey, resolveEnvApiKey } from "../../agents/model-auth.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import { shortenHomePath } from "../../utils.js";
import { maskApiKey } from "./list.format.js";
import type { ProviderAuthOverview } from "./list.types.js";
export function resolveProviderAuthOverview(params: {
provider: string;
cfg: MoltbotConfig;
cfg: OpenClawConfig;
store: AuthProfileStore;
modelsPath: string;
}): ProviderAuthOverview {
+2 -2
View File
@@ -4,11 +4,11 @@ import {
resolveConfiguredModelRef,
resolveModelRefFromString,
} from "../../agents/model-selection.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import type { ConfiguredEntry } from "./list.types.js";
import { DEFAULT_MODEL, DEFAULT_PROVIDER, modelKey } from "./shared.js";
export function resolveConfiguredEntries(cfg: MoltbotConfig) {
export function resolveConfiguredEntries(cfg: OpenClawConfig) {
const resolvedDefault = resolveConfiguredModelRef({
cfg,
defaultProvider: DEFAULT_PROVIDER,
+7 -7
View File
@@ -1,7 +1,7 @@
import crypto from "node:crypto";
import fs from "node:fs/promises";
import { resolveMoltbotAgentDir } from "../../agents/agent-paths.js";
import { resolveOpenClawAgentDir } from "../../agents/agent-paths.js";
import {
ensureAuthProfileStore,
listProfilesForProvider,
@@ -15,7 +15,7 @@ import { getCustomProviderApiKey, resolveEnvApiKey } from "../../agents/model-au
import { normalizeProviderId, parseModelRef } from "../../agents/model-selection.js";
import { resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../../agents/agent-scope.js";
import { resolveDefaultAgentWorkspaceDir } from "../../agents/workspace.js";
import type { MoltbotConfig } from "../../config/config.js";
import type { OpenClawConfig } from "../../config/config.js";
import {
resolveSessionTranscriptPath,
resolveSessionTranscriptsDirForAgent,
@@ -117,7 +117,7 @@ function selectProbeModel(params: {
}
function buildProbeTargets(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
providers: string[];
modelCandidates: string[];
options: AuthProbeOptions;
@@ -260,7 +260,7 @@ function buildProbeTargets(params: {
}
async function probeTarget(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
agentId: string;
agentDir: string;
workspaceDir: string;
@@ -335,7 +335,7 @@ async function probeTarget(params: {
}
async function runTargetsWithConcurrency(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
targets: AuthProbeTarget[];
timeoutMs: number;
maxTokens: number;
@@ -346,7 +346,7 @@ async function runTargetsWithConcurrency(params: {
const concurrency = Math.max(1, Math.min(targets.length || 1, params.concurrency));
const agentId = resolveDefaultAgentId(cfg);
const agentDir = resolveMoltbotAgentDir();
const agentDir = resolveOpenClawAgentDir();
const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId) ?? resolveDefaultAgentWorkspaceDir();
const sessionDir = resolveSessionTranscriptsDirForAgent(agentId);
@@ -389,7 +389,7 @@ async function runTargetsWithConcurrency(params: {
}
export async function runAuthProbes(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
providers: string[];
modelCandidates: string[];
options: AuthProbeOptions;
+8 -8
View File
@@ -1,7 +1,7 @@
import type { Api, Model } from "@mariozechner/pi-ai";
import { discoverAuthStorage, discoverModels } from "@mariozechner/pi-coding-agent";
import { resolveMoltbotAgentDir } from "../../agents/agent-paths.js";
import { resolveOpenClawAgentDir } from "../../agents/agent-paths.js";
import type { AuthProfileStore } from "../../agents/auth-profiles.js";
import { listProfilesForProvider } from "../../agents/auth-profiles.js";
import {
@@ -9,8 +9,8 @@ import {
resolveAwsSdkEnvVarName,
resolveEnvApiKey,
} from "../../agents/model-auth.js";
import { ensureMoltbotModelsJson } from "../../agents/models-config.js";
import type { MoltbotConfig } from "../../config/config.js";
import { ensureOpenClawModelsJson } from "../../agents/models-config.js";
import type { OpenClawConfig } from "../../config/config.js";
import type { ModelRow } from "./list.types.js";
import { modelKey } from "./shared.js";
@@ -30,7 +30,7 @@ const isLocalBaseUrl = (baseUrl: string) => {
}
};
const hasAuthForProvider = (provider: string, cfg: MoltbotConfig, authStore: AuthProfileStore) => {
const hasAuthForProvider = (provider: string, cfg: OpenClawConfig, authStore: AuthProfileStore) => {
if (listProfilesForProvider(authStore, provider).length > 0) return true;
if (provider === "amazon-bedrock" && resolveAwsSdkEnvVarName()) return true;
if (resolveEnvApiKey(provider)) return true;
@@ -38,9 +38,9 @@ const hasAuthForProvider = (provider: string, cfg: MoltbotConfig, authStore: Aut
return false;
};
export async function loadModelRegistry(cfg: MoltbotConfig) {
await ensureMoltbotModelsJson(cfg);
const agentDir = resolveMoltbotAgentDir();
export async function loadModelRegistry(cfg: OpenClawConfig) {
await ensureOpenClawModelsJson(cfg);
const agentDir = resolveOpenClawAgentDir();
const authStorage = discoverAuthStorage(agentDir);
const registry = discoverModels(authStorage, agentDir);
const models = registry.getAll() as Model<Api>[];
@@ -55,7 +55,7 @@ export function toModelRow(params: {
tags: string[];
aliases?: string[];
availableKeys?: Set<string>;
cfg?: MoltbotConfig;
cfg?: OpenClawConfig;
authStore?: AuthProfileStore;
}): ModelRow {
const { model, key, tags, aliases = [], availableKeys, cfg, authStore } = params;
+4 -4
View File
@@ -1,5 +1,5 @@
import path from "node:path";
import { resolveMoltbotAgentDir } from "../../agents/agent-paths.js";
import { resolveOpenClawAgentDir } from "../../agents/agent-paths.js";
import {
buildAuthHealthSummary,
DEFAULT_OAUTH_WARN_MS,
@@ -93,7 +93,7 @@ export async function modelsStatusCommand(
);
const allowed = Object.keys(cfg.agents?.defaults?.models ?? {});
const agentDir = resolveMoltbotAgentDir();
const agentDir = resolveOpenClawAgentDir();
const store = ensureAuthProfileStore();
const modelsPath = path.join(agentDir, "models.json");
@@ -487,8 +487,8 @@ export async function modelsStatusCommand(
for (const provider of missingProvidersInUse) {
const hint =
provider === "anthropic"
? `Run \`claude setup-token\`, then \`${formatCliCommand("moltbot models auth setup-token")}\` or \`${formatCliCommand("moltbot configure")}\`.`
: `Run \`${formatCliCommand("moltbot configure")}\` or set an API key env var.`;
? `Run \`claude setup-token\`, then \`${formatCliCommand("openclaw models auth setup-token")}\` or \`${formatCliCommand("openclaw configure")}\`.`
: `Run \`${formatCliCommand("openclaw configure")}\` or set an API key env var.`;
runtime.log(`- ${theme.heading(provider)} ${hint}`);
}
}
+4 -4
View File
@@ -29,7 +29,7 @@ const mocks = vi.hoisted(() => {
return {
store,
resolveMoltbotAgentDir: vi.fn().mockReturnValue("/tmp/moltbot-agent"),
resolveOpenClawAgentDir: vi.fn().mockReturnValue("/tmp/openclaw-agent"),
ensureAuthProfileStore: vi.fn().mockReturnValue(store),
listProfilesForProvider: vi.fn((s: typeof store, provider: string) => {
return Object.entries(s.profiles)
@@ -39,7 +39,7 @@ const mocks = vi.hoisted(() => {
resolveAuthProfileDisplayLabel: vi.fn(({ profileId }: { profileId: string }) => profileId),
resolveAuthStorePathForDisplay: vi
.fn()
.mockReturnValue("/tmp/moltbot-agent/auth-profiles.json"),
.mockReturnValue("/tmp/openclaw-agent/auth-profiles.json"),
resolveEnvApiKey: vi.fn((provider: string) => {
if (provider === "openai") {
return {
@@ -72,7 +72,7 @@ const mocks = vi.hoisted(() => {
});
vi.mock("../../agents/agent-paths.js", () => ({
resolveMoltbotAgentDir: mocks.resolveMoltbotAgentDir,
resolveOpenClawAgentDir: mocks.resolveOpenClawAgentDir,
}));
vi.mock("../../agents/auth-profiles.js", async (importOriginal) => {
@@ -118,7 +118,7 @@ describe("modelsStatusCommand auth overview", () => {
const payload = JSON.parse(String((runtime.log as vi.Mock).mock.calls[0][0]));
expect(payload.defaultModel).toBe("anthropic/claude-opus-4-5");
expect(payload.auth.storePath).toBe("/tmp/moltbot-agent/auth-profiles.json");
expect(payload.auth.storePath).toBe("/tmp/openclaw-agent/auth-profiles.json");
expect(payload.auth.shellEnvFallback.enabled).toBe(true);
expect(payload.auth.shellEnvFallback.appliedKeys).toContain("OPENAI_API_KEY");
expect(payload.auth.missingProvidersInUse).toEqual([]);
+5 -5
View File
@@ -6,7 +6,7 @@ import {
resolveModelRefFromString,
} from "../../agents/model-selection.js";
import {
type MoltbotConfig,
type OpenClawConfig,
readConfigFileSnapshot,
writeConfigFile,
} from "../../config/config.js";
@@ -31,8 +31,8 @@ export const formatMs = (value?: number | null) => {
};
export async function updateConfig(
mutator: (cfg: MoltbotConfig) => MoltbotConfig,
): Promise<MoltbotConfig> {
mutator: (cfg: OpenClawConfig) => OpenClawConfig,
): Promise<OpenClawConfig> {
const snapshot = await readConfigFileSnapshot();
if (!snapshot.valid) {
const issues = snapshot.issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n");
@@ -43,7 +43,7 @@ export async function updateConfig(
return next;
}
export function resolveModelTarget(params: { raw: string; cfg: MoltbotConfig }): {
export function resolveModelTarget(params: { raw: string; cfg: OpenClawConfig }): {
provider: string;
model: string;
} {
@@ -62,7 +62,7 @@ export function resolveModelTarget(params: { raw: string; cfg: MoltbotConfig }):
return resolved.ref;
}
export function buildAllowlistSet(cfg: MoltbotConfig): Set<string> {
export function buildAllowlistSet(cfg: OpenClawConfig): Set<string> {
const allowed = new Set<string>();
const models = cfg.agents?.defaults?.models ?? {};
for (const raw of Object.keys(models)) {
+1 -1
View File
@@ -58,7 +58,7 @@ export async function buildNodeInstallPlan(params: {
const environment = buildNodeServiceEnvironment({ env: params.env });
const description = formatNodeServiceDescription({
version: environment.CLAWDBOT_SERVICE_VERSION,
version: environment.OPENCLAW_SERVICE_VERSION,
});
return { programArguments, workingDirectory, environment, description };
+16 -16
View File
@@ -11,7 +11,7 @@ import {
VENICE_DEFAULT_MODEL_REF,
VENICE_MODEL_CATALOG,
} from "../agents/venice-models.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import {
OPENROUTER_DEFAULT_MODEL_REF,
VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF,
@@ -29,7 +29,7 @@ import {
MOONSHOT_DEFAULT_MODEL_REF,
} from "./onboard-auth.models.js";
export function applyZaiConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyZaiConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[ZAI_DEFAULT_MODEL_REF] = {
...models[ZAI_DEFAULT_MODEL_REF],
@@ -57,7 +57,7 @@ export function applyZaiConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applyOpenrouterProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyOpenrouterProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[OPENROUTER_DEFAULT_MODEL_REF] = {
...models[OPENROUTER_DEFAULT_MODEL_REF],
@@ -76,7 +76,7 @@ export function applyOpenrouterProviderConfig(cfg: MoltbotConfig): MoltbotConfig
};
}
export function applyVercelAiGatewayProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyVercelAiGatewayProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF] = {
...models[VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF],
@@ -95,7 +95,7 @@ export function applyVercelAiGatewayProviderConfig(cfg: MoltbotConfig): MoltbotC
};
}
export function applyVercelAiGatewayConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyVercelAiGatewayConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyVercelAiGatewayProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
@@ -117,7 +117,7 @@ export function applyVercelAiGatewayConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applyOpenrouterConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyOpenrouterConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyOpenrouterProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
@@ -139,7 +139,7 @@ export function applyOpenrouterConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applyMoonshotProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyMoonshotProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[MOONSHOT_DEFAULT_MODEL_REF] = {
...models[MOONSHOT_DEFAULT_MODEL_REF],
@@ -182,7 +182,7 @@ export function applyMoonshotProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applyMoonshotConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyMoonshotConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyMoonshotProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
@@ -204,7 +204,7 @@ export function applyMoonshotConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applyKimiCodeProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyKimiCodeProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[KIMI_CODE_MODEL_REF] = {
...models[KIMI_CODE_MODEL_REF],
@@ -247,7 +247,7 @@ export function applyKimiCodeProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applyKimiCodeConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyKimiCodeConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyKimiCodeProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
@@ -269,7 +269,7 @@ export function applyKimiCodeConfig(cfg: MoltbotConfig): MoltbotConfig {
};
}
export function applySyntheticProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applySyntheticProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[SYNTHETIC_DEFAULT_MODEL_REF] = {
...models[SYNTHETIC_DEFAULT_MODEL_REF],
@@ -316,7 +316,7 @@ export function applySyntheticProviderConfig(cfg: MoltbotConfig): MoltbotConfig
};
}
export function applySyntheticConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applySyntheticConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applySyntheticProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
@@ -413,7 +413,7 @@ export function applyXiaomiConfig(cfg: MoltbotConfig): MoltbotConfig {
* Apply Venice provider configuration without changing the default model.
* Registers Venice models and sets up the provider, but preserves existing model selection.
*/
export function applyVeniceProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyVeniceProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[VENICE_DEFAULT_MODEL_REF] = {
...models[VENICE_DEFAULT_MODEL_REF],
@@ -462,7 +462,7 @@ export function applyVeniceProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
* Apply Venice provider configuration AND set Venice as the default model.
* Use this when Venice is the primary provider choice during onboarding.
*/
export function applyVeniceConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyVeniceConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyVeniceProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
@@ -485,7 +485,7 @@ export function applyVeniceConfig(cfg: MoltbotConfig): MoltbotConfig {
}
export function applyAuthProfileConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
params: {
profileId: string;
provider: string;
@@ -493,7 +493,7 @@ export function applyAuthProfileConfig(
email?: string;
preferProfileFirst?: boolean;
},
): MoltbotConfig {
): OpenClawConfig {
const profiles = {
...cfg.auth?.profiles,
[params.profileId]: {
+11 -11
View File
@@ -1,4 +1,4 @@
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import {
buildMinimaxApiModelDefinition,
buildMinimaxModelDefinition,
@@ -12,7 +12,7 @@ import {
MINIMAX_LM_STUDIO_COST,
} from "./onboard-auth.models.js";
export function applyMinimaxProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyMinimaxProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models["anthropic/claude-opus-4-5"] = {
...models["anthropic/claude-opus-4-5"],
@@ -59,9 +59,9 @@ export function applyMinimaxProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
}
export function applyMinimaxHostedProviderConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
params?: { baseUrl?: string },
): MoltbotConfig {
): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[MINIMAX_HOSTED_MODEL_REF] = {
...models[MINIMAX_HOSTED_MODEL_REF],
@@ -103,7 +103,7 @@ export function applyMinimaxHostedProviderConfig(
};
}
export function applyMinimaxConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyMinimaxConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyMinimaxProviderConfig(cfg);
return {
...next,
@@ -126,9 +126,9 @@ export function applyMinimaxConfig(cfg: MoltbotConfig): MoltbotConfig {
}
export function applyMinimaxHostedConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
params?: { baseUrl?: string },
): MoltbotConfig {
): OpenClawConfig {
const next = applyMinimaxHostedProviderConfig(cfg, params);
return {
...next,
@@ -147,9 +147,9 @@ export function applyMinimaxHostedConfig(
// MiniMax Anthropic-compatible API (platform.minimax.io/anthropic)
export function applyMinimaxApiProviderConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
modelId: string = "MiniMax-M2.1",
): MoltbotConfig {
): OpenClawConfig {
const providers = { ...cfg.models?.providers };
const existingProvider = providers.minimax;
const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
@@ -190,9 +190,9 @@ export function applyMinimaxApiProviderConfig(
}
export function applyMinimaxApiConfig(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
modelId: string = "MiniMax-M2.1",
): MoltbotConfig {
): OpenClawConfig {
const next = applyMinimaxApiProviderConfig(cfg, modelId);
return {
...next,
+3 -3
View File
@@ -1,7 +1,7 @@
import { OPENCODE_ZEN_DEFAULT_MODEL_REF } from "../agents/opencode-zen-models.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
export function applyOpencodeZenProviderConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyOpencodeZenProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
// Use the built-in opencode provider from pi-ai; only seed the allowlist alias.
const models = { ...cfg.agents?.defaults?.models };
models[OPENCODE_ZEN_DEFAULT_MODEL_REF] = {
@@ -21,7 +21,7 @@ export function applyOpencodeZenProviderConfig(cfg: MoltbotConfig): MoltbotConfi
};
}
export function applyOpencodeZenConfig(cfg: MoltbotConfig): MoltbotConfig {
export function applyOpencodeZenConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyOpencodeZenProviderConfig(cfg);
return {
...next,
+2 -2
View File
@@ -1,8 +1,8 @@
import type { OAuthCredentials } from "@mariozechner/pi-ai";
import { resolveMoltbotAgentDir } from "../agents/agent-paths.js";
import { resolveOpenClawAgentDir } from "../agents/agent-paths.js";
import { upsertAuthProfile } from "../agents/auth-profiles.js";
const resolveAuthAgentDir = (agentDir?: string) => agentDir ?? resolveMoltbotAgentDir();
const resolveAuthAgentDir = (agentDir?: string) => agentDir ?? resolveOpenClawAgentDir();
export async function writeOAuthCredentials(
provider: string,
+25 -25
View File
@@ -26,14 +26,14 @@ import {
const authProfilePathFor = (agentDir: string) => path.join(agentDir, "auth-profiles.json");
const requireAgentDir = () => {
const agentDir = process.env.CLAWDBOT_AGENT_DIR;
if (!agentDir) throw new Error("CLAWDBOT_AGENT_DIR not set");
const agentDir = process.env.OPENCLAW_AGENT_DIR;
if (!agentDir) throw new Error("OPENCLAW_AGENT_DIR not set");
return agentDir;
};
describe("writeOAuthCredentials", () => {
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
const previousStateDir = process.env.OPENCLAW_STATE_DIR;
const previousAgentDir = process.env.OPENCLAW_AGENT_DIR;
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
let tempStateDir: string | null = null;
@@ -43,28 +43,28 @@ describe("writeOAuthCredentials", () => {
tempStateDir = null;
}
if (previousStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = previousStateDir;
process.env.OPENCLAW_STATE_DIR = previousStateDir;
}
if (previousAgentDir === undefined) {
delete process.env.CLAWDBOT_AGENT_DIR;
delete process.env.OPENCLAW_AGENT_DIR;
} else {
process.env.CLAWDBOT_AGENT_DIR = previousAgentDir;
process.env.OPENCLAW_AGENT_DIR = previousAgentDir;
}
if (previousPiAgentDir === undefined) {
delete process.env.PI_CODING_AGENT_DIR;
} else {
process.env.PI_CODING_AGENT_DIR = previousPiAgentDir;
}
delete process.env.CLAWDBOT_OAUTH_DIR;
delete process.env.OPENCLAW_OAUTH_DIR;
});
it("writes auth-profiles.json under CLAWDBOT_AGENT_DIR when set", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-oauth-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
it("writes auth-profiles.json under OPENCLAW_AGENT_DIR when set", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-oauth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
const creds = {
refresh: "refresh-token",
@@ -92,8 +92,8 @@ describe("writeOAuthCredentials", () => {
});
describe("setMinimaxApiKey", () => {
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
const previousStateDir = process.env.OPENCLAW_STATE_DIR;
const previousAgentDir = process.env.OPENCLAW_AGENT_DIR;
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
let tempStateDir: string | null = null;
@@ -103,14 +103,14 @@ describe("setMinimaxApiKey", () => {
tempStateDir = null;
}
if (previousStateDir === undefined) {
delete process.env.CLAWDBOT_STATE_DIR;
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.CLAWDBOT_STATE_DIR = previousStateDir;
process.env.OPENCLAW_STATE_DIR = previousStateDir;
}
if (previousAgentDir === undefined) {
delete process.env.CLAWDBOT_AGENT_DIR;
delete process.env.OPENCLAW_AGENT_DIR;
} else {
process.env.CLAWDBOT_AGENT_DIR = previousAgentDir;
process.env.OPENCLAW_AGENT_DIR = previousAgentDir;
}
if (previousPiAgentDir === undefined) {
delete process.env.PI_CODING_AGENT_DIR;
@@ -119,11 +119,11 @@ describe("setMinimaxApiKey", () => {
}
});
it("writes to CLAWDBOT_AGENT_DIR when set", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-minimax-"));
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
process.env.CLAWDBOT_AGENT_DIR = path.join(tempStateDir, "custom-agent");
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
it("writes to OPENCLAW_AGENT_DIR when set", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-minimax-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "custom-agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
await setMinimaxApiKey("sk-minimax-test");
+4 -4
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { setupChannels } from "./onboard-channels.js";
@@ -76,7 +76,7 @@ describe("setupChannels", () => {
}),
};
await setupChannels({} as MoltbotConfig, runtime, prompter, {
await setupChannels({} as OpenClawConfig, runtime, prompter, {
skipConfirm: true,
quickstartDefaults: true,
forceAllowFromChannels: ["whatsapp"],
@@ -127,7 +127,7 @@ describe("setupChannels", () => {
botToken: "token",
},
},
} as MoltbotConfig,
} as OpenClawConfig,
runtime,
prompter,
{
@@ -189,7 +189,7 @@ describe("setupChannels", () => {
enabled: false,
},
},
} as MoltbotConfig,
} as OpenClawConfig,
runtime,
prompter,
{
+11 -11
View File
@@ -7,7 +7,7 @@ import {
formatChannelSelectionLine,
listChatChannels,
} from "../channels/registry.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { isChannelConfigured } from "../config/plugin-auto-enable.js";
import type { DmPolicy } from "../config/types.js";
import { resolveChannelDefaultAccountId } from "../channels/plugins/helpers.js";
@@ -82,7 +82,7 @@ async function promptConfiguredAction(params: {
}
async function promptRemovalAccountId(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
prompter: WizardPrompter;
label: string;
channel: ChannelChoice;
@@ -105,7 +105,7 @@ async function promptRemovalAccountId(params: {
}
async function collectChannelStatus(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
options?: SetupChannelsOptions;
accountOverrides: Partial<Record<ChannelChoice, string>>;
}): Promise<ChannelStatusSummary> {
@@ -157,7 +157,7 @@ async function collectChannelStatus(params: {
}
export async function noteChannelStatus(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
prompter: WizardPrompter;
options?: SetupChannelsOptions;
accountOverrides?: Partial<Record<ChannelChoice, string>>;
@@ -188,7 +188,7 @@ async function noteChannelPrimer(
await prompter.note(
[
"DM security: default is pairing; unknown DMs get a pairing code.",
`Approve with: ${formatCliCommand("moltbot pairing approve <channel> <code>")}`,
`Approve with: ${formatCliCommand("openclaw pairing approve <channel> <code>")}`,
'Public DMs require dmPolicy="open" + allowFrom=["*"].',
'Multi-user DMs: set session.dmScope="per-channel-peer" (or "per-account-channel-peer" for multi-account channels) to isolate sessions.',
`Docs: ${formatDocsLink("/start/pairing", "start/pairing")}`,
@@ -213,11 +213,11 @@ function resolveQuickstartDefault(
}
async function maybeConfigureDmPolicies(params: {
cfg: MoltbotConfig;
cfg: OpenClawConfig;
selection: ChannelChoice[];
prompter: WizardPrompter;
accountIdsByChannel?: Map<ChannelChoice, string>;
}): Promise<MoltbotConfig> {
}): Promise<OpenClawConfig> {
const { selection, prompter, accountIdsByChannel } = params;
const dmPolicies = selection
.map((channel) => getChannelOnboardingAdapter(channel)?.dmPolicy)
@@ -235,7 +235,7 @@ async function maybeConfigureDmPolicies(params: {
await prompter.note(
[
"Default: pairing (unknown DMs get a pairing code).",
`Approve: ${formatCliCommand(`moltbot pairing approve ${policy.channel} <code>`)}`,
`Approve: ${formatCliCommand(`openclaw pairing approve ${policy.channel} <code>`)}`,
`Allowlist DMs: ${policy.policyKey}="allowlist" + ${policy.allowFromKey} entries.`,
`Public DMs: ${policy.policyKey}="open" + ${policy.allowFromKey} includes "*".`,
'Multi-user DMs: set session.dmScope="per-channel-peer" (or "per-account-channel-peer" for multi-account channels) to isolate sessions.',
@@ -275,11 +275,11 @@ async function maybeConfigureDmPolicies(params: {
// Channel-specific prompts moved into onboarding adapters.
export async function setupChannels(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
runtime: RuntimeEnv,
prompter: WizardPrompter,
options?: SetupChannelsOptions,
): Promise<MoltbotConfig> {
): Promise<OpenClawConfig> {
let next = cfg;
const forceAllowFromChannels = new Set(options?.forceAllowFromChannels ?? []);
const accountOverrides: Partial<Record<ChannelChoice, string>> = {
@@ -584,7 +584,7 @@ export async function setupChannels(
{
value: "__skip__",
label: "Skip for now",
hint: `You can add channels later via \`${formatCliCommand("moltbot channels add")}\``,
hint: `You can add channels later via \`${formatCliCommand("openclaw channels add")}\``,
},
],
initialValue: quickstartDefault,
+9 -9
View File
@@ -6,7 +6,7 @@ import { inspect } from "node:util";
import { cancel, isCancel } from "@clack/prompts";
import { DEFAULT_AGENT_WORKSPACE_DIR, ensureAgentWorkspace } from "../agents/workspace.js";
import type { MoltbotConfig } from "../config/config.js";
import type { OpenClawConfig } from "../config/config.js";
import { CONFIG_PATH } from "../config/config.js";
import { resolveSessionTranscriptsDirForAgent } from "../config/sessions.js";
import { callGateway } from "../gateway/call.js";
@@ -36,7 +36,7 @@ export function guardCancel<T>(value: T | symbol, runtime: RuntimeEnv): T {
return value as T;
}
export function summarizeExistingConfig(config: MoltbotConfig): string {
export function summarizeExistingConfig(config: OpenClawConfig): string {
const rows: string[] = [];
const defaults = config.agents?.defaults;
if (defaults?.workspace) rows.push(shortenHomeInString(`workspace: ${defaults.workspace}`));
@@ -65,9 +65,9 @@ export function randomToken(): string {
export function printWizardHeader(runtime: RuntimeEnv) {
const header = [
"▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄",
"██░▄▀▄░██░▄▄▄░██░████▄▄░▄▄██░▄▄▀██░▄▄▄░█▄▄░▄▄██",
"██░█░█░██░███░██░██████░████░▄▄▀██░███░███░████",
"██░███░██░▀▀▀░██░▀▀░███░████░▀▀░██░▀▀▀░███░████",
"█████░█████░█████░█░░░█░█████░█░░░░░░███░░█░░░█",
"█░░░█░█░░░█░███░░░██░░█░█░░░░░█░░░░░█░░░█░█░█░█",
"█████░████░░█████░█░░██░█████░█████░█████░██░██",
"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀",
" 🦞 FRESH DAILY 🦞 ",
" ",
@@ -76,9 +76,9 @@ export function printWizardHeader(runtime: RuntimeEnv) {
}
export function applyWizardMetadata(
cfg: MoltbotConfig,
cfg: OpenClawConfig,
params: { command: string; mode: OnboardMode },
): MoltbotConfig {
): OpenClawConfig {
const commit = process.env.GIT_COMMIT?.trim() || process.env.GIT_SHA?.trim() || undefined;
return {
...cfg,
@@ -178,8 +178,8 @@ export function formatControlUiSshHint(params: {
localUrl,
authedUrl,
"Docs:",
"https://docs.molt.bot/gateway/remote",
"https://docs.molt.bot/web/control-ui",
"https://docs.openclaw.ai/gateway/remote",
"https://docs.openclaw.ai/web/control-ui",
]
.filter(Boolean)
.join("\n");
Loaded 100 of 2357 files, more files were not shown because too many files have changed in this diff. Show more