Merge upstream/main - sync 332 commits (resolved conflicts using upstream)
This commit is contained in:
commit
42acfb9313
2406 files changed
+39156
-38009
No files matched your search
+5
-5
@@ -10,7 +10,7 @@ import {
|
||||
type SessionNotification,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
|
||||
import { ensureClawdbotCliOnPath } from "../infra/path-env.js";
|
||||
import { ensureMoltbotCliOnPath } from "../infra/path-env.js";
|
||||
|
||||
export type AcpClientOptions = {
|
||||
cwd?: string;
|
||||
@@ -75,8 +75,8 @@ export async function createAcpClient(opts: AcpClientOptions = {}): Promise<AcpC
|
||||
const verbose = Boolean(opts.verbose);
|
||||
const log = verbose ? (msg: string) => console.error(`[acp-client] ${msg}`) : () => {};
|
||||
|
||||
ensureClawdbotCliOnPath({ cwd });
|
||||
const serverCommand = opts.serverCommand ?? "clawdbot";
|
||||
ensureMoltbotCliOnPath({ cwd });
|
||||
const serverCommand = opts.serverCommand ?? "moltbot";
|
||||
const serverArgs = buildServerArgs(opts);
|
||||
|
||||
log(`spawning: ${serverCommand} ${serverArgs.join(" ")}`);
|
||||
@@ -122,7 +122,7 @@ export async function createAcpClient(opts: AcpClientOptions = {}): Promise<AcpC
|
||||
fs: { readTextFile: true, writeTextFile: true },
|
||||
terminal: true,
|
||||
},
|
||||
clientInfo: { name: "clawdbot-acp-client", version: "1.0.0" },
|
||||
clientInfo: { name: "moltbot-acp-client", version: "1.0.0" },
|
||||
});
|
||||
|
||||
log("creating session");
|
||||
@@ -146,7 +146,7 @@ export async function runAcpClientInteractive(opts: AcpClientOptions = {}): Prom
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
console.log("Clawdbot ACP client");
|
||||
console.log("Moltbot ACP client");
|
||||
console.log(`Session: ${sessionId}`);
|
||||
console.log('Type a prompt, or "exit" to quit.\n');
|
||||
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ function parseArgs(args: string[]): AcpServerOptions {
|
||||
}
|
||||
|
||||
function printHelp(): void {
|
||||
console.log(`Usage: clawdbot acp [options]
|
||||
console.log(`Usage: moltbot acp [options]
|
||||
|
||||
Gateway-backed ACP server for IDE integration.
|
||||
|
||||
|
||||
+2
-2
@@ -24,7 +24,7 @@ export type AcpServerOptions = {
|
||||
};
|
||||
|
||||
export const ACP_AGENT_INFO = {
|
||||
name: "clawdbot-acp",
|
||||
title: "Clawdbot ACP Gateway",
|
||||
name: "moltbot-acp",
|
||||
title: "Moltbot ACP Gateway",
|
||||
version: VERSION,
|
||||
};
|
||||
@@ -4,9 +4,9 @@ import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveClawdbotAgentDir } from "./agent-paths.js";
|
||||
import { resolveMoltbotAgentDir } from "./agent-paths.js";
|
||||
|
||||
describe("resolveClawdbotAgentDir", () => {
|
||||
describe("resolveMoltbotAgentDir", () => {
|
||||
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
|
||||
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
@@ -35,23 +35,23 @@ describe("resolveClawdbotAgentDir", () => {
|
||||
});
|
||||
|
||||
it("defaults to the multi-agent path when no overrides are set", async () => {
|
||||
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-agent-"));
|
||||
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-agent-"));
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
delete process.env.CLAWDBOT_AGENT_DIR;
|
||||
delete process.env.PI_CODING_AGENT_DIR;
|
||||
|
||||
const resolved = resolveClawdbotAgentDir();
|
||||
const resolved = resolveMoltbotAgentDir();
|
||||
|
||||
expect(resolved).toBe(path.join(tempStateDir, "agents", "main", "agent"));
|
||||
});
|
||||
|
||||
it("honors CLAWDBOT_AGENT_DIR overrides", async () => {
|
||||
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-agent-"));
|
||||
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-agent-"));
|
||||
const override = path.join(tempStateDir, "agent");
|
||||
process.env.CLAWDBOT_AGENT_DIR = override;
|
||||
delete process.env.PI_CODING_AGENT_DIR;
|
||||
|
||||
const resolved = resolveClawdbotAgentDir();
|
||||
const resolved = resolveMoltbotAgentDir();
|
||||
|
||||
expect(resolved).toBe(path.resolve(override));
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { resolveStateDir } from "../config/paths.js";
|
||||
import { DEFAULT_AGENT_ID } from "../routing/session-key.js";
|
||||
import { resolveUserPath } from "../utils.js";
|
||||
|
||||
export function resolveClawdbotAgentDir(): string {
|
||||
export function resolveMoltbotAgentDir(): string {
|
||||
const override =
|
||||
process.env.CLAWDBOT_AGENT_DIR?.trim() || process.env.PI_CODING_AGENT_DIR?.trim();
|
||||
if (override) return resolveUserPath(override);
|
||||
@@ -12,8 +12,8 @@ export function resolveClawdbotAgentDir(): string {
|
||||
return resolveUserPath(defaultAgentDir);
|
||||
}
|
||||
|
||||
export function ensureClawdbotAgentEnv(): string {
|
||||
const dir = resolveClawdbotAgentDir();
|
||||
export function ensureMoltbotAgentEnv(): string {
|
||||
const dir = resolveMoltbotAgentDir();
|
||||
if (!process.env.CLAWDBOT_AGENT_DIR) process.env.CLAWDBOT_AGENT_DIR = dir;
|
||||
if (!process.env.PI_CODING_AGENT_DIR) process.env.PI_CODING_AGENT_DIR = dir;
|
||||
return dir;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import {
|
||||
resolveAgentConfig,
|
||||
resolveAgentModelFallbacksOverride,
|
||||
@@ -8,13 +8,13 @@ import {
|
||||
|
||||
describe("resolveAgentConfig", () => {
|
||||
it("should return undefined when no agents config exists", () => {
|
||||
const cfg: ClawdbotConfig = {};
|
||||
const cfg: MoltbotConfig = {};
|
||||
const result = resolveAgentConfig(cfg, "main");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined when agent id does not exist", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [{ id: "main", workspace: "~/clawd" }],
|
||||
},
|
||||
@@ -24,7 +24,7 @@ describe("resolveAgentConfig", () => {
|
||||
});
|
||||
|
||||
it("should return basic agent config", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -52,7 +52,7 @@ describe("resolveAgentConfig", () => {
|
||||
});
|
||||
|
||||
it("supports per-agent model primary+fallbacks", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
@@ -76,7 +76,7 @@ describe("resolveAgentConfig", () => {
|
||||
expect(resolveAgentModelFallbacksOverride(cfg, "linus")).toEqual(["openai/gpt-5.2"]);
|
||||
|
||||
// If fallbacks isn't present, we don't override the global fallbacks.
|
||||
const cfgNoOverride: ClawdbotConfig = {
|
||||
const cfgNoOverride: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -91,7 +91,7 @@ describe("resolveAgentConfig", () => {
|
||||
expect(resolveAgentModelFallbacksOverride(cfgNoOverride, "linus")).toBe(undefined);
|
||||
|
||||
// Explicit empty list disables global fallbacks for that agent.
|
||||
const cfgDisable: ClawdbotConfig = {
|
||||
const cfgDisable: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -108,7 +108,7 @@ describe("resolveAgentConfig", () => {
|
||||
});
|
||||
|
||||
it("should return agent-specific sandbox config", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -136,7 +136,7 @@ describe("resolveAgentConfig", () => {
|
||||
});
|
||||
|
||||
it("should return agent-specific tools config", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -166,7 +166,7 @@ describe("resolveAgentConfig", () => {
|
||||
});
|
||||
|
||||
it("should return both sandbox and tools config", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -190,7 +190,7 @@ describe("resolveAgentConfig", () => {
|
||||
});
|
||||
|
||||
it("should normalize agent id", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [{ id: "main", workspace: "~/clawd" }],
|
||||
},
|
||||
|
||||
+13
-13
@@ -1,7 +1,7 @@
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolveStateDir } from "../config/paths.js";
|
||||
import {
|
||||
DEFAULT_AGENT_ID,
|
||||
@@ -13,7 +13,7 @@ import { DEFAULT_AGENT_WORKSPACE_DIR } from "./workspace.js";
|
||||
|
||||
export { resolveAgentIdFromSessionKey } from "../routing/session-key.js";
|
||||
|
||||
type AgentEntry = NonNullable<NonNullable<ClawdbotConfig["agents"]>["list"]>[number];
|
||||
type AgentEntry = NonNullable<NonNullable<MoltbotConfig["agents"]>["list"]>[number];
|
||||
|
||||
type ResolvedAgentConfig = {
|
||||
name?: string;
|
||||
@@ -32,13 +32,13 @@ type ResolvedAgentConfig = {
|
||||
|
||||
let defaultAgentWarned = false;
|
||||
|
||||
function listAgents(cfg: ClawdbotConfig): AgentEntry[] {
|
||||
function listAgents(cfg: MoltbotConfig): AgentEntry[] {
|
||||
const list = cfg.agents?.list;
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list.filter((entry): entry is AgentEntry => Boolean(entry && typeof entry === "object"));
|
||||
}
|
||||
|
||||
export function listAgentIds(cfg: ClawdbotConfig): string[] {
|
||||
export function listAgentIds(cfg: MoltbotConfig): string[] {
|
||||
const agents = listAgents(cfg);
|
||||
if (agents.length === 0) return [DEFAULT_AGENT_ID];
|
||||
const seen = new Set<string>();
|
||||
@@ -52,7 +52,7 @@ export function listAgentIds(cfg: ClawdbotConfig): string[] {
|
||||
return ids.length > 0 ? ids : [DEFAULT_AGENT_ID];
|
||||
}
|
||||
|
||||
export function resolveDefaultAgentId(cfg: ClawdbotConfig): string {
|
||||
export function resolveDefaultAgentId(cfg: MoltbotConfig): string {
|
||||
const agents = listAgents(cfg);
|
||||
if (agents.length === 0) return DEFAULT_AGENT_ID;
|
||||
const defaults = agents.filter((agent) => agent?.default);
|
||||
@@ -64,7 +64,7 @@ export function resolveDefaultAgentId(cfg: ClawdbotConfig): string {
|
||||
return normalizeAgentId(chosen || DEFAULT_AGENT_ID);
|
||||
}
|
||||
|
||||
export function resolveSessionAgentIds(params: { sessionKey?: string; config?: ClawdbotConfig }): {
|
||||
export function resolveSessionAgentIds(params: { sessionKey?: string; config?: MoltbotConfig }): {
|
||||
defaultAgentId: string;
|
||||
sessionAgentId: string;
|
||||
} {
|
||||
@@ -78,18 +78,18 @@ export function resolveSessionAgentIds(params: { sessionKey?: string; config?: C
|
||||
|
||||
export function resolveSessionAgentId(params: {
|
||||
sessionKey?: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
}): string {
|
||||
return resolveSessionAgentIds(params).sessionAgentId;
|
||||
}
|
||||
|
||||
function resolveAgentEntry(cfg: ClawdbotConfig, agentId: string): AgentEntry | undefined {
|
||||
function resolveAgentEntry(cfg: MoltbotConfig, agentId: string): AgentEntry | undefined {
|
||||
const id = normalizeAgentId(agentId);
|
||||
return listAgents(cfg).find((entry) => normalizeAgentId(entry.id) === id);
|
||||
}
|
||||
|
||||
export function resolveAgentConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
): ResolvedAgentConfig | undefined {
|
||||
const id = normalizeAgentId(agentId);
|
||||
@@ -114,7 +114,7 @@ export function resolveAgentConfig(
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAgentModelPrimary(cfg: ClawdbotConfig, agentId: string): string | undefined {
|
||||
export function resolveAgentModelPrimary(cfg: MoltbotConfig, agentId: string): string | undefined {
|
||||
const raw = resolveAgentConfig(cfg, agentId)?.model;
|
||||
if (!raw) return undefined;
|
||||
if (typeof raw === "string") return raw.trim() || undefined;
|
||||
@@ -123,7 +123,7 @@ export function resolveAgentModelPrimary(cfg: ClawdbotConfig, agentId: string):
|
||||
}
|
||||
|
||||
export function resolveAgentModelFallbacksOverride(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
): string[] | undefined {
|
||||
const raw = resolveAgentConfig(cfg, agentId)?.model;
|
||||
@@ -133,7 +133,7 @@ export function resolveAgentModelFallbacksOverride(
|
||||
return Array.isArray(raw.fallbacks) ? raw.fallbacks : undefined;
|
||||
}
|
||||
|
||||
export function resolveAgentWorkspaceDir(cfg: ClawdbotConfig, agentId: string) {
|
||||
export function resolveAgentWorkspaceDir(cfg: MoltbotConfig, agentId: string) {
|
||||
const id = normalizeAgentId(agentId);
|
||||
const configured = resolveAgentConfig(cfg, id)?.workspace?.trim();
|
||||
if (configured) return resolveUserPath(configured);
|
||||
@@ -146,7 +146,7 @@ export function resolveAgentWorkspaceDir(cfg: ClawdbotConfig, agentId: string) {
|
||||
return path.join(os.homedir(), `clawd-${id}`);
|
||||
}
|
||||
|
||||
export function resolveAgentDir(cfg: ClawdbotConfig, agentId: string) {
|
||||
export function resolveAgentDir(cfg: MoltbotConfig, agentId: string) {
|
||||
const id = normalizeAgentId(agentId);
|
||||
const configured = resolveAgentConfig(cfg, id)?.agentDir?.trim();
|
||||
if (configured) return resolveUserPath(configured);
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
validateAnthropicSetupToken,
|
||||
} from "../commands/auth-token.js";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import { resolveClawdbotAgentDir } from "./agent-paths.js";
|
||||
import { resolveMoltbotAgentDir } from "./agent-paths.js";
|
||||
import {
|
||||
type AuthProfileCredential,
|
||||
ensureAuthProfileStore,
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from "./auth-profiles.js";
|
||||
import { getApiKeyForModel, requireApiKey } from "./model-auth.js";
|
||||
import { normalizeProviderId, parseModelRef } from "./model-selection.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
|
||||
const LIVE = isTruthyEnvValue(process.env.LIVE) || isTruthyEnvValue(process.env.CLAWDBOT_LIVE_TEST);
|
||||
const SETUP_TOKEN_RAW = process.env.CLAWDBOT_LIVE_SETUP_TOKEN?.trim() ?? "";
|
||||
@@ -70,7 +70,7 @@ async function resolveTokenSource(): Promise<TokenSource> {
|
||||
if (error) {
|
||||
throw new Error(`Invalid setup-token: ${error}`);
|
||||
}
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-setup-token-"));
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-setup-token-"));
|
||||
const profileId = `anthropic:setup-token-live-${randomUUID()}`;
|
||||
const store = ensureAuthProfileStore(tempDir, {
|
||||
allowKeychainPrompt: false,
|
||||
@@ -90,7 +90,7 @@ async function resolveTokenSource(): Promise<TokenSource> {
|
||||
};
|
||||
}
|
||||
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
const store = ensureAuthProfileStore(agentDir, {
|
||||
allowKeychainPrompt: false,
|
||||
});
|
||||
@@ -153,7 +153,7 @@ describeLive("live anthropic setup-token", () => {
|
||||
const tokenSource = await resolveTokenSource();
|
||||
try {
|
||||
const cfg = loadConfig();
|
||||
await ensureClawdbotModelsJson(cfg, tokenSource.agentDir);
|
||||
await ensureMoltbotModelsJson(cfg, tokenSource.agentDir);
|
||||
|
||||
const authStorage = discoverAuthStorage(tokenSource.agentDir);
|
||||
const modelRegistry = discoverModels(authStorage, tokenSource.agentDir);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { applyPatch } from "./apply-patch.js";
|
||||
|
||||
async function withTempDir<T>(fn: (dir: string) => Promise<T>) {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-patch-"));
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-patch-"));
|
||||
try {
|
||||
return await fn(dir);
|
||||
} finally {
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import {
|
||||
type AuthProfileCredential,
|
||||
type AuthProfileStore,
|
||||
CLAUDE_CLI_PROFILE_ID,
|
||||
CODEX_CLI_PROFILE_ID,
|
||||
resolveAuthProfileDisplayLabel,
|
||||
} from "./auth-profiles.js";
|
||||
|
||||
export type AuthProfileSource = "claude-cli" | "codex-cli" | "store";
|
||||
export type AuthProfileSource = "store";
|
||||
|
||||
export type AuthProfileHealthStatus = "ok" | "expiring" | "expired" | "missing" | "static";
|
||||
|
||||
@@ -41,9 +39,7 @@ export type AuthHealthSummary = {
|
||||
|
||||
export const DEFAULT_OAUTH_WARN_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export function resolveAuthProfileSource(profileId: string): AuthProfileSource {
|
||||
if (profileId === CLAUDE_CLI_PROFILE_ID) return "claude-cli";
|
||||
if (profileId === CODEX_CLI_PROFILE_ID) return "codex-cli";
|
||||
export function resolveAuthProfileSource(_profileId: string): AuthProfileSource {
|
||||
return "store";
|
||||
}
|
||||
|
||||
@@ -80,7 +76,7 @@ function buildProfileHealth(params: {
|
||||
profileId: string;
|
||||
credential: AuthProfileCredential;
|
||||
store: AuthProfileStore;
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
now: number;
|
||||
warnAfterMs: number;
|
||||
}): AuthProfileHealth {
|
||||
@@ -142,7 +138,7 @@ function buildProfileHealth(params: {
|
||||
|
||||
export function buildAuthHealthSummary(params: {
|
||||
store: AuthProfileStore;
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
warnAfterMs?: number;
|
||||
providers?: string[];
|
||||
}): AuthHealthSummary {
|
||||
|
||||
@@ -34,7 +34,7 @@ describe("auth-profiles (chutes)", () => {
|
||||
});
|
||||
|
||||
it("refreshes expired Chutes OAuth credentials", async () => {
|
||||
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-chutes-"));
|
||||
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-chutes-"));
|
||||
process.env.CLAWDBOT_STATE_DIR = tempDir;
|
||||
process.env.CLAWDBOT_AGENT_DIR = path.join(tempDir, "agents", "main", "agent");
|
||||
process.env.PI_CODING_AGENT_DIR = process.env.CLAWDBOT_AGENT_DIR;
|
||||
|
||||
@@ -3,12 +3,11 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ensureAuthProfileStore } from "./auth-profiles.js";
|
||||
import { AUTH_STORE_VERSION, CODEX_CLI_PROFILE_ID } from "./auth-profiles/constants.js";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import { AUTH_STORE_VERSION } from "./auth-profiles/constants.js";
|
||||
|
||||
describe("ensureAuthProfileStore", () => {
|
||||
it("migrates legacy auth.json and deletes it (PR #368)", () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-auth-profiles-"));
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-auth-profiles-"));
|
||||
try {
|
||||
const legacyPath = path.join(agentDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
@@ -49,7 +48,7 @@ describe("ensureAuthProfileStore", () => {
|
||||
});
|
||||
|
||||
it("merges main auth profiles into agent store and keeps agent overrides", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-auth-merge-"));
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-auth-merge-"));
|
||||
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
|
||||
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
try {
|
||||
@@ -123,80 +122,4 @@ describe("ensureAuthProfileStore", () => {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("drops codex-cli from merged store when a custom openai-codex profile matches", async () => {
|
||||
await withTempHome(async (tempHome) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-auth-dedup-merge-"));
|
||||
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
|
||||
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
try {
|
||||
const mainDir = path.join(root, "main-agent");
|
||||
const agentDir = path.join(root, "agent-x");
|
||||
fs.mkdirSync(mainDir, { recursive: true });
|
||||
fs.mkdirSync(agentDir, { recursive: true });
|
||||
|
||||
process.env.CLAWDBOT_AGENT_DIR = mainDir;
|
||||
process.env.PI_CODING_AGENT_DIR = mainDir;
|
||||
process.env.HOME = tempHome;
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(mainDir, "auth-profiles.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version: AUTH_STORE_VERSION,
|
||||
profiles: {
|
||||
[CODEX_CLI_PROFILE_ID]: {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "shared-access-token",
|
||||
refresh: "shared-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(agentDir, "auth-profiles.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version: AUTH_STORE_VERSION,
|
||||
profiles: {
|
||||
"openai-codex:my-custom-profile": {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "shared-access-token",
|
||||
refresh: "shared-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
expect(store.profiles[CODEX_CLI_PROFILE_ID]).toBeUndefined();
|
||||
expect(store.profiles["openai-codex:my-custom-profile"]).toBeDefined();
|
||||
} finally {
|
||||
if (previousAgentDir === undefined) {
|
||||
delete process.env.CLAWDBOT_AGENT_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_AGENT_DIR = previousAgentDir;
|
||||
}
|
||||
if (previousPiAgentDir === undefined) {
|
||||
delete process.env.PI_CODING_AGENT_DIR;
|
||||
} else {
|
||||
process.env.PI_CODING_AGENT_DIR = previousPiAgentDir;
|
||||
}
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import { CLAUDE_CLI_PROFILE_ID, ensureAuthProfileStore } from "./auth-profiles.js";
|
||||
|
||||
describe("external CLI credential sync", () => {
|
||||
it("does not overwrite API keys when syncing external CLI creds", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-no-overwrite-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
// Create Claude Code CLI credentials
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
const claudeCreds = {
|
||||
claudeAiOauth: {
|
||||
accessToken: "cli-access",
|
||||
refreshToken: "cli-refresh",
|
||||
expiresAt: Date.now() + 30 * 60 * 1000,
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(path.join(claudeDir, ".credentials.json"), JSON.stringify(claudeCreds));
|
||||
|
||||
// Create auth-profiles.json with an API key
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
"anthropic:default": {
|
||||
type: "api_key",
|
||||
provider: "anthropic",
|
||||
key: "sk-store",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
// Should keep the store's API key and still add the CLI profile.
|
||||
expect((store.profiles["anthropic:default"] as { key: string }).key).toBe("sk-store");
|
||||
expect(store.profiles[CLAUDE_CLI_PROFILE_ID]).toBeDefined();
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
it("prefers oauth over token even if token has later expiry (oauth enables auto-refresh)", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-cli-oauth-preferred-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
// CLI has OAuth credentials (with refresh token) expiring in 30 min
|
||||
fs.writeFileSync(
|
||||
path.join(claudeDir, ".credentials.json"),
|
||||
JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
accessToken: "cli-oauth-access",
|
||||
refreshToken: "cli-refresh",
|
||||
expiresAt: Date.now() + 30 * 60 * 1000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
// Store has token credentials expiring in 60 min (later than CLI)
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
[CLAUDE_CLI_PROFILE_ID]: {
|
||||
type: "token",
|
||||
provider: "anthropic",
|
||||
token: "store-token-access",
|
||||
expires: Date.now() + 60 * 60 * 1000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
// OAuth should be preferred over token because it can auto-refresh
|
||||
const cliProfile = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
expect(cliProfile.type).toBe("oauth");
|
||||
expect((cliProfile as { access: string }).access).toBe("cli-oauth-access");
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import { CLAUDE_CLI_PROFILE_ID, ensureAuthProfileStore } from "./auth-profiles.js";
|
||||
|
||||
describe("external CLI credential sync", () => {
|
||||
it("does not overwrite fresher store oauth with older CLI oauth", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-cli-oauth-no-downgrade-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
// CLI has OAuth credentials expiring in 30 min
|
||||
fs.writeFileSync(
|
||||
path.join(claudeDir, ".credentials.json"),
|
||||
JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
accessToken: "cli-oauth-access",
|
||||
refreshToken: "cli-refresh",
|
||||
expiresAt: Date.now() + 30 * 60 * 1000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
// Store has OAuth credentials expiring in 60 min (later than CLI)
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
[CLAUDE_CLI_PROFILE_ID]: {
|
||||
type: "oauth",
|
||||
provider: "anthropic",
|
||||
access: "store-oauth-access",
|
||||
refresh: "store-refresh",
|
||||
expires: Date.now() + 60 * 60 * 1000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
// Fresher store oauth should be kept
|
||||
const cliProfile = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
expect(cliProfile.type).toBe("oauth");
|
||||
expect((cliProfile as { access: string }).access).toBe("store-oauth-access");
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
it("does not downgrade store oauth to token when CLI lacks refresh token", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-cli-no-downgrade-oauth-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
// CLI has token-only credentials (no refresh token)
|
||||
fs.writeFileSync(
|
||||
path.join(claudeDir, ".credentials.json"),
|
||||
JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
accessToken: "cli-token-access",
|
||||
expiresAt: Date.now() + 30 * 60 * 1000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
// Store already has OAuth credentials with refresh token
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
[CLAUDE_CLI_PROFILE_ID]: {
|
||||
type: "oauth",
|
||||
provider: "anthropic",
|
||||
access: "store-oauth-access",
|
||||
refresh: "store-refresh",
|
||||
expires: Date.now() + 60 * 60 * 1000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
// Keep oauth to preserve auto-refresh capability
|
||||
const cliProfile = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
expect(cliProfile.type).toBe("oauth");
|
||||
expect((cliProfile as { access: string }).access).toBe("store-oauth-access");
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
-166
@@ -1,166 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import { CODEX_CLI_PROFILE_ID, ensureAuthProfileStore } from "./auth-profiles.js";
|
||||
|
||||
describe("external CLI credential sync", () => {
|
||||
it("skips codex-cli sync when credentials already exist in another openai-codex profile", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-dedup-skip-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const codexDir = path.join(tempHome, ".codex");
|
||||
fs.mkdirSync(codexDir, { recursive: true });
|
||||
const codexAuthPath = path.join(codexDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
codexAuthPath,
|
||||
JSON.stringify({
|
||||
tokens: {
|
||||
access_token: "shared-access-token",
|
||||
refresh_token: "shared-refresh-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
fs.utimesSync(codexAuthPath, new Date(), new Date());
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
"openai-codex:my-custom-profile": {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "shared-access-token",
|
||||
refresh: "shared-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
expect(store.profiles[CODEX_CLI_PROFILE_ID]).toBeUndefined();
|
||||
expect(store.profiles["openai-codex:my-custom-profile"]).toBeDefined();
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("creates codex-cli profile when credentials differ from existing openai-codex profiles", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-dedup-create-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const codexDir = path.join(tempHome, ".codex");
|
||||
fs.mkdirSync(codexDir, { recursive: true });
|
||||
const codexAuthPath = path.join(codexDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
codexAuthPath,
|
||||
JSON.stringify({
|
||||
tokens: {
|
||||
access_token: "unique-access-token",
|
||||
refresh_token: "unique-refresh-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
fs.utimesSync(codexAuthPath, new Date(), new Date());
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
"openai-codex:my-custom-profile": {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "different-access-token",
|
||||
refresh: "different-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
expect(store.profiles[CODEX_CLI_PROFILE_ID]).toBeDefined();
|
||||
expect((store.profiles[CODEX_CLI_PROFILE_ID] as { access: string }).access).toBe(
|
||||
"unique-access-token",
|
||||
);
|
||||
expect(store.profiles["openai-codex:my-custom-profile"]).toBeDefined();
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("removes codex-cli profile when it duplicates another openai-codex profile", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-dedup-remove-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const codexDir = path.join(tempHome, ".codex");
|
||||
fs.mkdirSync(codexDir, { recursive: true });
|
||||
const codexAuthPath = path.join(codexDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
codexAuthPath,
|
||||
JSON.stringify({
|
||||
tokens: {
|
||||
access_token: "shared-access-token",
|
||||
refresh_token: "shared-refresh-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
fs.utimesSync(codexAuthPath, new Date(), new Date());
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
[CODEX_CLI_PROFILE_ID]: {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "shared-access-token",
|
||||
refresh: "shared-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
},
|
||||
"openai-codex:my-custom-profile": {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "shared-access-token",
|
||||
refresh: "shared-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
expect(store.profiles[CODEX_CLI_PROFILE_ID]).toBeUndefined();
|
||||
const saved = JSON.parse(fs.readFileSync(authPath, "utf8")) as {
|
||||
profiles?: Record<string, unknown>;
|
||||
};
|
||||
expect(saved.profiles?.[CODEX_CLI_PROFILE_ID]).toBeUndefined();
|
||||
expect(saved.profiles?.["openai-codex:my-custom-profile"]).toBeDefined();
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import { CLAUDE_CLI_PROFILE_ID, ensureAuthProfileStore } from "./auth-profiles.js";
|
||||
|
||||
describe("external CLI credential sync", () => {
|
||||
it("syncs Claude Code CLI OAuth credentials into anthropic:claude-cli", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-cli-sync-"));
|
||||
try {
|
||||
// Create a temp home with Claude Code CLI credentials
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
// Create Claude Code CLI credentials with refreshToken (OAuth)
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
const claudeCreds = {
|
||||
claudeAiOauth: {
|
||||
accessToken: "fresh-access-token",
|
||||
refreshToken: "fresh-refresh-token",
|
||||
expiresAt: Date.now() + 60 * 60 * 1000, // 1 hour from now
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(path.join(claudeDir, ".credentials.json"), JSON.stringify(claudeCreds));
|
||||
|
||||
// Create empty auth-profiles.json
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
"anthropic:default": {
|
||||
type: "api_key",
|
||||
provider: "anthropic",
|
||||
key: "sk-default",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Load the store - should sync from CLI as OAuth credential
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
expect(store.profiles["anthropic:default"]).toBeDefined();
|
||||
expect((store.profiles["anthropic:default"] as { key: string }).key).toBe("sk-default");
|
||||
expect(store.profiles[CLAUDE_CLI_PROFILE_ID]).toBeDefined();
|
||||
// Should be stored as OAuth credential (type: "oauth") for auto-refresh
|
||||
const cliProfile = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
expect(cliProfile.type).toBe("oauth");
|
||||
expect((cliProfile as { access: string }).access).toBe("fresh-access-token");
|
||||
expect((cliProfile as { refresh: string }).refresh).toBe("fresh-refresh-token");
|
||||
expect((cliProfile as { expires: number }).expires).toBeGreaterThan(Date.now());
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
it("syncs Claude Code CLI credentials without refreshToken as token type", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-cli-token-sync-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
// Create Claude Code CLI credentials WITHOUT refreshToken (fallback to token type)
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
const claudeCreds = {
|
||||
claudeAiOauth: {
|
||||
accessToken: "access-only-token",
|
||||
// No refreshToken - backward compatibility scenario
|
||||
expiresAt: Date.now() + 60 * 60 * 1000,
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(path.join(claudeDir, ".credentials.json"), JSON.stringify(claudeCreds));
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(authPath, JSON.stringify({ version: 1, profiles: {} }));
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
expect(store.profiles[CLAUDE_CLI_PROFILE_ID]).toBeDefined();
|
||||
// Should be stored as token type (no refresh capability)
|
||||
const cliProfile = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
expect(cliProfile.type).toBe("token");
|
||||
expect((cliProfile as { token: string }).token).toBe("access-only-token");
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import { CODEX_CLI_PROFILE_ID, ensureAuthProfileStore } from "./auth-profiles.js";
|
||||
|
||||
describe("external CLI credential sync", () => {
|
||||
it("updates codex-cli profile when Codex CLI refresh token changes", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-refresh-sync-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
const codexDir = path.join(tempHome, ".codex");
|
||||
fs.mkdirSync(codexDir, { recursive: true });
|
||||
const codexAuthPath = path.join(codexDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
codexAuthPath,
|
||||
JSON.stringify({
|
||||
tokens: {
|
||||
access_token: "same-access",
|
||||
refresh_token: "new-refresh",
|
||||
},
|
||||
}),
|
||||
);
|
||||
fs.utimesSync(codexAuthPath, new Date(), new Date());
|
||||
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
[CODEX_CLI_PROFILE_ID]: {
|
||||
type: "oauth",
|
||||
provider: "openai-codex",
|
||||
access: "same-access",
|
||||
refresh: "old-refresh",
|
||||
expires: Date.now() - 1000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
expect((store.profiles[CODEX_CLI_PROFILE_ID] as { refresh: string }).refresh).toBe(
|
||||
"new-refresh",
|
||||
);
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
import {
|
||||
CLAUDE_CLI_PROFILE_ID,
|
||||
CODEX_CLI_PROFILE_ID,
|
||||
ensureAuthProfileStore,
|
||||
} from "./auth-profiles.js";
|
||||
|
||||
describe("external CLI credential sync", () => {
|
||||
it("upgrades token to oauth when Claude Code CLI gets refreshToken", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-cli-upgrade-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
// Create Claude Code CLI credentials with refreshToken
|
||||
const claudeDir = path.join(tempHome, ".claude");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(claudeDir, ".credentials.json"),
|
||||
JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
accessToken: "new-oauth-access",
|
||||
refreshToken: "new-refresh-token",
|
||||
expiresAt: Date.now() + 60 * 60 * 1000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Create auth-profiles.json with existing token type credential
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {
|
||||
[CLAUDE_CLI_PROFILE_ID]: {
|
||||
type: "token",
|
||||
provider: "anthropic",
|
||||
token: "old-token",
|
||||
expires: Date.now() + 30 * 60 * 1000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
// Should upgrade from token to oauth
|
||||
const cliProfile = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
expect(cliProfile.type).toBe("oauth");
|
||||
expect((cliProfile as { access: string }).access).toBe("new-oauth-access");
|
||||
expect((cliProfile as { refresh: string }).refresh).toBe("new-refresh-token");
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
it("syncs Codex CLI credentials into openai-codex:codex-cli", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-sync-"));
|
||||
try {
|
||||
await withTempHome(
|
||||
async (tempHome) => {
|
||||
// Create Codex CLI credentials
|
||||
const codexDir = path.join(tempHome, ".codex");
|
||||
fs.mkdirSync(codexDir, { recursive: true });
|
||||
const codexCreds = {
|
||||
tokens: {
|
||||
access_token: "codex-access-token",
|
||||
refresh_token: "codex-refresh-token",
|
||||
},
|
||||
};
|
||||
const codexAuthPath = path.join(codexDir, "auth.json");
|
||||
fs.writeFileSync(codexAuthPath, JSON.stringify(codexCreds));
|
||||
|
||||
// Create empty auth-profiles.json
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
profiles: {},
|
||||
}),
|
||||
);
|
||||
|
||||
const store = ensureAuthProfileStore(agentDir);
|
||||
|
||||
expect(store.profiles[CODEX_CLI_PROFILE_ID]).toBeDefined();
|
||||
expect((store.profiles[CODEX_CLI_PROFILE_ID] as { access: string }).access).toBe(
|
||||
"codex-access-token",
|
||||
);
|
||||
},
|
||||
{ prefix: "clawdbot-home-" },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(agentDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import { ensureAuthProfileStore, markAuthProfileFailure } from "./auth-profiles.
|
||||
|
||||
describe("markAuthProfileFailure", () => {
|
||||
it("disables billing failures for ~5 hours by default", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-auth-"));
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
try {
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
@@ -42,7 +42,7 @@ describe("markAuthProfileFailure", () => {
|
||||
}
|
||||
});
|
||||
it("honors per-provider billing backoff overrides", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-auth-"));
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
try {
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
fs.writeFileSync(
|
||||
@@ -86,7 +86,7 @@ describe("markAuthProfileFailure", () => {
|
||||
}
|
||||
});
|
||||
it("resets backoff counters outside the failure window", async () => {
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-auth-"));
|
||||
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
try {
|
||||
const authPath = path.join(agentDir, "auth-profiles.json");
|
||||
const now = Date.now();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import type { AuthProfileStore } from "./types.js";
|
||||
|
||||
export function resolveAuthProfileDisplayLabel(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
profileId: string;
|
||||
}): string {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { formatCliCommand } from "../../cli/command-format.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import { normalizeProviderId } from "../model-selection.js";
|
||||
import { listProfilesForProvider } from "./profiles.js";
|
||||
import { suggestOAuthProfileIdForLegacyDefault } from "./repair.js";
|
||||
import type { AuthProfileStore } from "./types.js";
|
||||
|
||||
export function formatAuthDoctorHint(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
provider: string;
|
||||
profileId?: string;
|
||||
@@ -38,6 +38,6 @@ export function formatAuthDoctorHint(params: {
|
||||
}`,
|
||||
`- auth store oauth profiles: ${storeOauthProfiles || "(none)"}`,
|
||||
`- suggested profile: ${suggested}`,
|
||||
`Fix: run "${formatCliCommand("clawdbot doctor --yes")}"`,
|
||||
`Fix: run "${formatCliCommand("moltbot doctor --yes")}"`,
|
||||
].join("\n");
|
||||
}
|
||||
@@ -1,22 +1,11 @@
|
||||
import { readQwenCliCredentialsCached } from "../cli-credentials.js";
|
||||
import {
|
||||
readClaudeCliCredentialsCached,
|
||||
readCodexCliCredentialsCached,
|
||||
readQwenCliCredentialsCached,
|
||||
} from "../cli-credentials.js";
|
||||
import {
|
||||
CLAUDE_CLI_PROFILE_ID,
|
||||
CODEX_CLI_PROFILE_ID,
|
||||
EXTERNAL_CLI_NEAR_EXPIRY_MS,
|
||||
EXTERNAL_CLI_SYNC_TTL_MS,
|
||||
QWEN_CLI_PROFILE_ID,
|
||||
log,
|
||||
} from "./constants.js";
|
||||
import type {
|
||||
AuthProfileCredential,
|
||||
AuthProfileStore,
|
||||
OAuthCredential,
|
||||
TokenCredential,
|
||||
} from "./types.js";
|
||||
import type { AuthProfileCredential, AuthProfileStore, OAuthCredential } from "./types.js";
|
||||
|
||||
function shallowEqualOAuthCredentials(a: OAuthCredential | undefined, b: OAuthCredential): boolean {
|
||||
if (!a) return false;
|
||||
@@ -33,25 +22,10 @@ function shallowEqualOAuthCredentials(a: OAuthCredential | undefined, b: OAuthCr
|
||||
);
|
||||
}
|
||||
|
||||
function shallowEqualTokenCredentials(a: TokenCredential | undefined, b: TokenCredential): boolean {
|
||||
if (!a) return false;
|
||||
if (a.type !== "token") return false;
|
||||
return (
|
||||
a.provider === b.provider &&
|
||||
a.token === b.token &&
|
||||
a.expires === b.expires &&
|
||||
a.email === b.email
|
||||
);
|
||||
}
|
||||
|
||||
function isExternalProfileFresh(cred: AuthProfileCredential | undefined, now: number): boolean {
|
||||
if (!cred) return false;
|
||||
if (cred.type !== "oauth" && cred.type !== "token") return false;
|
||||
if (
|
||||
cred.provider !== "anthropic" &&
|
||||
cred.provider !== "openai-codex" &&
|
||||
cred.provider !== "qwen-portal"
|
||||
) {
|
||||
if (cred.provider !== "qwen-portal") {
|
||||
return false;
|
||||
}
|
||||
if (typeof cred.expires !== "number") return true;
|
||||
@@ -59,163 +33,14 @@ function isExternalProfileFresh(cred: AuthProfileCredential | undefined, now: nu
|
||||
}
|
||||
|
||||
/**
|
||||
* Find any existing openai-codex profile (other than codex-cli) that has the same
|
||||
* access and refresh tokens. This prevents creating a duplicate codex-cli profile
|
||||
* when the user has already set up a custom profile with the same credentials.
|
||||
*/
|
||||
export function findDuplicateCodexProfile(
|
||||
store: AuthProfileStore,
|
||||
creds: OAuthCredential,
|
||||
): string | undefined {
|
||||
for (const [profileId, profile] of Object.entries(store.profiles)) {
|
||||
if (profileId === CODEX_CLI_PROFILE_ID) continue;
|
||||
if (profile.type !== "oauth") continue;
|
||||
if (profile.provider !== "openai-codex") continue;
|
||||
if (profile.access === creds.access && profile.refresh === creds.refresh) {
|
||||
return profileId;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync OAuth credentials from external CLI tools (Claude Code CLI, Codex CLI) into the store.
|
||||
* This allows clawdbot to use the same credentials as these tools without requiring
|
||||
* separate authentication, and keeps credentials in sync when CLI tools refresh tokens.
|
||||
* Sync OAuth credentials from external CLI tools (Qwen Code CLI) into the store.
|
||||
*
|
||||
* Returns true if any credentials were updated.
|
||||
*/
|
||||
export function syncExternalCliCredentials(
|
||||
store: AuthProfileStore,
|
||||
options?: { allowKeychainPrompt?: boolean },
|
||||
): boolean {
|
||||
export function syncExternalCliCredentials(store: AuthProfileStore): boolean {
|
||||
let mutated = false;
|
||||
const now = Date.now();
|
||||
|
||||
// Sync from Claude Code CLI (supports both OAuth and Token credentials)
|
||||
const existingClaude = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
const shouldSyncClaude =
|
||||
!existingClaude ||
|
||||
existingClaude.provider !== "anthropic" ||
|
||||
existingClaude.type === "token" ||
|
||||
!isExternalProfileFresh(existingClaude, now);
|
||||
const claudeCreds = shouldSyncClaude
|
||||
? readClaudeCliCredentialsCached({
|
||||
allowKeychainPrompt: options?.allowKeychainPrompt,
|
||||
ttlMs: EXTERNAL_CLI_SYNC_TTL_MS,
|
||||
})
|
||||
: null;
|
||||
if (claudeCreds) {
|
||||
const existing = store.profiles[CLAUDE_CLI_PROFILE_ID];
|
||||
const claudeCredsExpires = claudeCreds.expires ?? 0;
|
||||
|
||||
// Determine if we should update based on credential comparison
|
||||
let shouldUpdate = false;
|
||||
let isEqual = false;
|
||||
|
||||
if (claudeCreds.type === "oauth") {
|
||||
const existingOAuth = existing?.type === "oauth" ? existing : undefined;
|
||||
isEqual = shallowEqualOAuthCredentials(existingOAuth, claudeCreds);
|
||||
// Update if: no existing profile, type changed to oauth, expired, or CLI has newer token
|
||||
shouldUpdate =
|
||||
!existingOAuth ||
|
||||
existingOAuth.provider !== "anthropic" ||
|
||||
existingOAuth.expires <= now ||
|
||||
(claudeCredsExpires > now && claudeCredsExpires > existingOAuth.expires);
|
||||
} else {
|
||||
const existingToken = existing?.type === "token" ? existing : undefined;
|
||||
isEqual = shallowEqualTokenCredentials(existingToken, claudeCreds);
|
||||
// Update if: no existing profile, expired, or CLI has newer token
|
||||
shouldUpdate =
|
||||
!existingToken ||
|
||||
existingToken.provider !== "anthropic" ||
|
||||
(existingToken.expires ?? 0) <= now ||
|
||||
(claudeCredsExpires > now && claudeCredsExpires > (existingToken.expires ?? 0));
|
||||
}
|
||||
|
||||
// Also update if credential type changed (token -> oauth upgrade)
|
||||
if (existing && existing.type !== claudeCreds.type) {
|
||||
// Prefer oauth over token (enables auto-refresh)
|
||||
if (claudeCreds.type === "oauth") {
|
||||
shouldUpdate = true;
|
||||
isEqual = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Avoid downgrading from oauth to token-only credentials.
|
||||
if (existing?.type === "oauth" && claudeCreds.type === "token") {
|
||||
shouldUpdate = false;
|
||||
}
|
||||
|
||||
if (shouldUpdate && !isEqual) {
|
||||
store.profiles[CLAUDE_CLI_PROFILE_ID] = claudeCreds;
|
||||
mutated = true;
|
||||
log.info("synced anthropic credentials from claude cli", {
|
||||
profileId: CLAUDE_CLI_PROFILE_ID,
|
||||
type: claudeCreds.type,
|
||||
expires:
|
||||
typeof claudeCreds.expires === "number"
|
||||
? new Date(claudeCreds.expires).toISOString()
|
||||
: "unknown",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sync from Codex CLI
|
||||
const existingCodex = store.profiles[CODEX_CLI_PROFILE_ID];
|
||||
const existingCodexOAuth = existingCodex?.type === "oauth" ? existingCodex : undefined;
|
||||
const duplicateExistingId = existingCodexOAuth
|
||||
? findDuplicateCodexProfile(store, existingCodexOAuth)
|
||||
: undefined;
|
||||
if (duplicateExistingId) {
|
||||
delete store.profiles[CODEX_CLI_PROFILE_ID];
|
||||
mutated = true;
|
||||
log.info("removed codex-cli profile: credentials already exist in another profile", {
|
||||
existingProfileId: duplicateExistingId,
|
||||
removedProfileId: CODEX_CLI_PROFILE_ID,
|
||||
});
|
||||
}
|
||||
const shouldSyncCodex =
|
||||
!existingCodex ||
|
||||
existingCodex.provider !== "openai-codex" ||
|
||||
!isExternalProfileFresh(existingCodex, now);
|
||||
const codexCreds =
|
||||
shouldSyncCodex || duplicateExistingId
|
||||
? readCodexCliCredentialsCached({ ttlMs: EXTERNAL_CLI_SYNC_TTL_MS })
|
||||
: null;
|
||||
if (codexCreds) {
|
||||
const duplicateProfileId = findDuplicateCodexProfile(store, codexCreds);
|
||||
if (duplicateProfileId) {
|
||||
if (store.profiles[CODEX_CLI_PROFILE_ID]) {
|
||||
delete store.profiles[CODEX_CLI_PROFILE_ID];
|
||||
mutated = true;
|
||||
log.info("removed codex-cli profile: credentials already exist in another profile", {
|
||||
existingProfileId: duplicateProfileId,
|
||||
removedProfileId: CODEX_CLI_PROFILE_ID,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const existing = store.profiles[CODEX_CLI_PROFILE_ID];
|
||||
const existingOAuth = existing?.type === "oauth" ? existing : undefined;
|
||||
|
||||
// Codex creds don't carry expiry; use file mtime heuristic for freshness.
|
||||
const shouldUpdate =
|
||||
!existingOAuth ||
|
||||
existingOAuth.provider !== "openai-codex" ||
|
||||
existingOAuth.expires <= now ||
|
||||
codexCreds.expires > existingOAuth.expires;
|
||||
|
||||
if (shouldUpdate && !shallowEqualOAuthCredentials(existingOAuth, codexCreds)) {
|
||||
store.profiles[CODEX_CLI_PROFILE_ID] = codexCreds;
|
||||
mutated = true;
|
||||
log.info("synced openai-codex credentials from codex cli", {
|
||||
profileId: CODEX_CLI_PROFILE_ID,
|
||||
expires: new Date(codexCreds.expires).toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sync from Qwen Code CLI
|
||||
const existingQwen = store.profiles[QWEN_CLI_PROFILE_ID];
|
||||
const shouldSyncQwen =
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { resolveApiKeyForProfile } from "./oauth.js";
|
||||
import { ensureAuthProfileStore } from "./store.js";
|
||||
import type { AuthProfileStore } from "./types.js";
|
||||
|
||||
describe("resolveApiKeyForProfile fallback to main agent", () => {
|
||||
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
|
||||
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
let tmpDir: string;
|
||||
let mainAgentDir: string;
|
||||
let secondaryAgentDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "oauth-fallback-test-"));
|
||||
mainAgentDir = path.join(tmpDir, "agents", "main", "agent");
|
||||
secondaryAgentDir = path.join(tmpDir, "agents", "kids", "agent");
|
||||
await fs.mkdir(mainAgentDir, { recursive: true });
|
||||
await fs.mkdir(secondaryAgentDir, { recursive: true });
|
||||
|
||||
// Set environment variables so resolveMoltbotAgentDir() returns mainAgentDir
|
||||
process.env.CLAWDBOT_STATE_DIR = tmpDir;
|
||||
process.env.CLAWDBOT_AGENT_DIR = mainAgentDir;
|
||||
process.env.PI_CODING_AGENT_DIR = mainAgentDir;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
|
||||
// Restore original environment
|
||||
if (previousStateDir === undefined) delete process.env.CLAWDBOT_STATE_DIR;
|
||||
else process.env.CLAWDBOT_STATE_DIR = previousStateDir;
|
||||
if (previousAgentDir === undefined) delete process.env.CLAWDBOT_AGENT_DIR;
|
||||
else process.env.CLAWDBOT_AGENT_DIR = previousAgentDir;
|
||||
if (previousPiAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
||||
else process.env.PI_CODING_AGENT_DIR = previousPiAgentDir;
|
||||
|
||||
await fs.rm(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("falls back to main agent credentials when secondary agent token is expired and refresh fails", async () => {
|
||||
const profileId = "anthropic:claude-cli";
|
||||
const now = Date.now();
|
||||
const expiredTime = now - 60 * 60 * 1000; // 1 hour ago
|
||||
const freshTime = now + 60 * 60 * 1000; // 1 hour from now
|
||||
|
||||
// Write expired credentials for secondary agent
|
||||
const secondaryStore: AuthProfileStore = {
|
||||
version: 1,
|
||||
profiles: {
|
||||
[profileId]: {
|
||||
type: "oauth",
|
||||
provider: "anthropic",
|
||||
access: "expired-access-token",
|
||||
refresh: "expired-refresh-token",
|
||||
expires: expiredTime,
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeFile(
|
||||
path.join(secondaryAgentDir, "auth-profiles.json"),
|
||||
JSON.stringify(secondaryStore),
|
||||
);
|
||||
|
||||
// Write fresh credentials for main agent
|
||||
const mainStore: AuthProfileStore = {
|
||||
version: 1,
|
||||
profiles: {
|
||||
[profileId]: {
|
||||
type: "oauth",
|
||||
provider: "anthropic",
|
||||
access: "fresh-access-token",
|
||||
refresh: "fresh-refresh-token",
|
||||
expires: freshTime,
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeFile(path.join(mainAgentDir, "auth-profiles.json"), JSON.stringify(mainStore));
|
||||
|
||||
// Mock fetch to simulate OAuth refresh failure
|
||||
const fetchSpy = vi.fn(async () => {
|
||||
return new Response(JSON.stringify({ error: "invalid_grant" }), {
|
||||
status: 400,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchSpy);
|
||||
|
||||
// Load the secondary agent's store (will merge with main agent's store)
|
||||
const loadedSecondaryStore = ensureAuthProfileStore(secondaryAgentDir);
|
||||
|
||||
// Call resolveApiKeyForProfile with the secondary agent's expired credentials
|
||||
// This should:
|
||||
// 1. Try to refresh the expired token (fails due to mocked fetch)
|
||||
// 2. Fall back to main agent's fresh credentials
|
||||
// 3. Copy those credentials to the secondary agent
|
||||
const result = await resolveApiKeyForProfile({
|
||||
store: loadedSecondaryStore,
|
||||
profileId,
|
||||
agentDir: secondaryAgentDir,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.apiKey).toBe("fresh-access-token");
|
||||
expect(result?.provider).toBe("anthropic");
|
||||
|
||||
// Verify the credentials were copied to the secondary agent
|
||||
const updatedSecondaryStore = JSON.parse(
|
||||
await fs.readFile(path.join(secondaryAgentDir, "auth-profiles.json"), "utf8"),
|
||||
) as AuthProfileStore;
|
||||
expect(updatedSecondaryStore.profiles[profileId]).toMatchObject({
|
||||
access: "fresh-access-token",
|
||||
expires: freshTime,
|
||||
});
|
||||
});
|
||||
|
||||
it("throws error when both secondary and main agent credentials are expired", async () => {
|
||||
const profileId = "anthropic:claude-cli";
|
||||
const now = Date.now();
|
||||
const expiredTime = now - 60 * 60 * 1000; // 1 hour ago
|
||||
|
||||
// Write expired credentials for both agents
|
||||
const expiredStore: AuthProfileStore = {
|
||||
version: 1,
|
||||
profiles: {
|
||||
[profileId]: {
|
||||
type: "oauth",
|
||||
provider: "anthropic",
|
||||
access: "expired-access-token",
|
||||
refresh: "expired-refresh-token",
|
||||
expires: expiredTime,
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeFile(
|
||||
path.join(secondaryAgentDir, "auth-profiles.json"),
|
||||
JSON.stringify(expiredStore),
|
||||
);
|
||||
await fs.writeFile(path.join(mainAgentDir, "auth-profiles.json"), JSON.stringify(expiredStore));
|
||||
|
||||
// Mock fetch to simulate OAuth refresh failure
|
||||
const fetchSpy = vi.fn(async () => {
|
||||
return new Response(JSON.stringify({ error: "invalid_grant" }), {
|
||||
status: 400,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchSpy);
|
||||
|
||||
const loadedSecondaryStore = ensureAuthProfileStore(secondaryAgentDir);
|
||||
|
||||
// Should throw because both agents have expired credentials
|
||||
await expect(
|
||||
resolveApiKeyForProfile({
|
||||
store: loadedSecondaryStore,
|
||||
profileId,
|
||||
agentDir: secondaryAgentDir,
|
||||
}),
|
||||
).rejects.toThrow(/OAuth token refresh failed/);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,10 @@
|
||||
import { getOAuthApiKey, type OAuthCredentials, type OAuthProvider } from "@mariozechner/pi-ai";
|
||||
import lockfile from "proper-lockfile";
|
||||
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import { refreshChutesTokens } from "../chutes-oauth.js";
|
||||
import { refreshQwenPortalCredentials } from "../../providers/qwen-portal-oauth.js";
|
||||
import { writeClaudeCliCredentials } from "../cli-credentials.js";
|
||||
import { AUTH_STORE_LOCK_OPTIONS, CLAUDE_CLI_PROFILE_ID } from "./constants.js";
|
||||
import { AUTH_STORE_LOCK_OPTIONS, log } from "./constants.js";
|
||||
import { formatAuthDoctorHint } from "./doctor.js";
|
||||
import { ensureAuthStoreFile, resolveAuthStorePath } from "./paths.js";
|
||||
import { suggestOAuthProfileIdForLegacyDefault } from "./repair.js";
|
||||
@@ -72,12 +71,6 @@ async function refreshOAuthTokenWithLock(params: {
|
||||
};
|
||||
saveAuthProfileStore(store, params.agentDir);
|
||||
|
||||
// Sync refreshed credentials back to Claude Code CLI if this is the claude-cli profile
|
||||
// This ensures Claude Code continues to work after ClawdBot refreshes the token
|
||||
if (params.profileId === CLAUDE_CLI_PROFILE_ID && cred.provider === "anthropic") {
|
||||
writeClaudeCliCredentials(result.newCredentials);
|
||||
}
|
||||
|
||||
return result;
|
||||
} finally {
|
||||
if (release) {
|
||||
@@ -91,7 +84,7 @@ async function refreshOAuthTokenWithLock(params: {
|
||||
}
|
||||
|
||||
async function tryResolveOAuthProfile(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
profileId: string;
|
||||
agentDir?: string;
|
||||
@@ -124,7 +117,7 @@ async function tryResolveOAuthProfile(params: {
|
||||
}
|
||||
|
||||
export async function resolveApiKeyForProfile(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
profileId: string;
|
||||
agentDir?: string;
|
||||
@@ -203,6 +196,32 @@ export async function resolveApiKeyForProfile(params: {
|
||||
// keep original error
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: if this is a secondary agent, try using the main agent's credentials
|
||||
if (params.agentDir) {
|
||||
try {
|
||||
const mainStore = ensureAuthProfileStore(undefined); // main agent (no agentDir)
|
||||
const mainCred = mainStore.profiles[profileId];
|
||||
if (mainCred?.type === "oauth" && Date.now() < mainCred.expires) {
|
||||
// Main agent has fresh credentials - copy them to this agent and use them
|
||||
refreshedStore.profiles[profileId] = { ...mainCred };
|
||||
saveAuthProfileStore(refreshedStore, params.agentDir);
|
||||
log.info("inherited fresh OAuth credentials from main agent", {
|
||||
profileId,
|
||||
agentDir: params.agentDir,
|
||||
expires: new Date(mainCred.expires).toISOString(),
|
||||
});
|
||||
return {
|
||||
apiKey: buildOAuthApiKey(mainCred.provider, mainCred),
|
||||
provider: mainCred.provider,
|
||||
email: mainCred.email,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// keep original error if main agent fallback also fails
|
||||
}
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const hint = formatAuthDoctorHint({
|
||||
cfg,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import { normalizeProviderId } from "../model-selection.js";
|
||||
import { listProfilesForProvider } from "./profiles.js";
|
||||
import type { AuthProfileStore } from "./types.js";
|
||||
@@ -16,7 +16,7 @@ function resolveProfileUnusableUntil(stats: {
|
||||
}
|
||||
|
||||
export function resolveAuthProfileOrder(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
provider: string;
|
||||
preferredProfile?: string;
|
||||
|
||||
@@ -3,17 +3,17 @@ import path from "node:path";
|
||||
|
||||
import { saveJsonFile } from "../../infra/json-file.js";
|
||||
import { resolveUserPath } from "../../utils.js";
|
||||
import { resolveClawdbotAgentDir } from "../agent-paths.js";
|
||||
import { resolveMoltbotAgentDir } from "../agent-paths.js";
|
||||
import { AUTH_PROFILE_FILENAME, AUTH_STORE_VERSION, LEGACY_AUTH_FILENAME } from "./constants.js";
|
||||
import type { AuthProfileStore } from "./types.js";
|
||||
|
||||
export function resolveAuthStorePath(agentDir?: string): string {
|
||||
const resolved = resolveUserPath(agentDir ?? resolveClawdbotAgentDir());
|
||||
const resolved = resolveUserPath(agentDir ?? resolveMoltbotAgentDir());
|
||||
return path.join(resolved, AUTH_PROFILE_FILENAME);
|
||||
}
|
||||
|
||||
export function resolveLegacyAuthStorePath(agentDir?: string): string {
|
||||
const resolved = resolveUserPath(agentDir ?? resolveClawdbotAgentDir());
|
||||
const resolved = resolveUserPath(agentDir ?? resolveMoltbotAgentDir());
|
||||
return path.join(resolved, LEGACY_AUTH_FILENAME);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import type { AuthProfileConfig } from "../../config/types.js";
|
||||
import { normalizeProviderId } from "../model-selection.js";
|
||||
import { listProfilesForProvider } from "./profiles.js";
|
||||
@@ -17,7 +17,7 @@ function isEmailLike(value: string): boolean {
|
||||
}
|
||||
|
||||
export function suggestOAuthProfileIdForLegacyDefault(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
provider: string;
|
||||
legacyProfileId: string;
|
||||
@@ -64,7 +64,7 @@ export function suggestOAuthProfileIdForLegacyDefault(params: {
|
||||
}
|
||||
|
||||
export function repairOAuthProfileIdMismatch(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
store: AuthProfileStore;
|
||||
provider: string;
|
||||
legacyProfileId?: string;
|
||||
@@ -123,7 +123,7 @@ export function repairOAuthProfileIdMismatch(params: {
|
||||
return { ...order, [resolvedKey]: deduped };
|
||||
})();
|
||||
|
||||
const nextCfg: ClawdbotConfig = {
|
||||
const nextCfg: MoltbotConfig = {
|
||||
...params.cfg,
|
||||
auth: {
|
||||
...params.cfg.auth,
|
||||
|
||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import type { SessionEntry } from "../../config/sessions.js";
|
||||
import { resolveSessionAuthProfileOverride } from "./session-override.js";
|
||||
|
||||
@@ -23,7 +23,7 @@ async function writeAuthStore(agentDir: string) {
|
||||
|
||||
describe("resolveSessionAuthProfileOverride", () => {
|
||||
it("keeps user override when provider alias differs", async () => {
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-auth-"));
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
process.env.CLAWDBOT_STATE_DIR = tmpDir;
|
||||
try {
|
||||
@@ -40,7 +40,7 @@ describe("resolveSessionAuthProfileOverride", () => {
|
||||
const sessionStore = { "agent:main:main": sessionEntry };
|
||||
|
||||
const resolved = await resolveSessionAuthProfileOverride({
|
||||
cfg: {} as ClawdbotConfig,
|
||||
cfg: {} as MoltbotConfig,
|
||||
provider: "z.ai",
|
||||
agentDir,
|
||||
sessionEntry,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import { updateSessionStore, type SessionEntry } from "../../config/sessions.js";
|
||||
import { normalizeProviderId } from "../model-selection.js";
|
||||
import {
|
||||
@@ -37,7 +37,7 @@ export async function clearSessionAuthProfileOverride(params: {
|
||||
}
|
||||
|
||||
export async function resolveSessionAuthProfileOverride(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
provider: string;
|
||||
agentDir: string;
|
||||
sessionEntry?: SessionEntry;
|
||||
|
||||
@@ -3,13 +3,8 @@ import type { OAuthCredentials } from "@mariozechner/pi-ai";
|
||||
import lockfile from "proper-lockfile";
|
||||
import { resolveOAuthPath } from "../../config/paths.js";
|
||||
import { loadJsonFile, saveJsonFile } from "../../infra/json-file.js";
|
||||
import {
|
||||
AUTH_STORE_LOCK_OPTIONS,
|
||||
AUTH_STORE_VERSION,
|
||||
CODEX_CLI_PROFILE_ID,
|
||||
log,
|
||||
} from "./constants.js";
|
||||
import { findDuplicateCodexProfile, syncExternalCliCredentials } from "./external-cli-sync.js";
|
||||
import { AUTH_STORE_LOCK_OPTIONS, AUTH_STORE_VERSION, log } from "./constants.js";
|
||||
import { syncExternalCliCredentials } from "./external-cli-sync.js";
|
||||
import { ensureAuthStoreFile, resolveAuthStorePath, resolveLegacyAuthStorePath } from "./paths.js";
|
||||
import type { AuthProfileCredential, AuthProfileStore, ProfileUsageStats } from "./types.js";
|
||||
|
||||
@@ -229,14 +224,14 @@ export function loadAuthProfileStore(): AuthProfileStore {
|
||||
|
||||
function loadAuthProfileStoreForAgent(
|
||||
agentDir?: string,
|
||||
options?: { allowKeychainPrompt?: boolean },
|
||||
_options?: { allowKeychainPrompt?: boolean },
|
||||
): AuthProfileStore {
|
||||
const authPath = resolveAuthStorePath(agentDir);
|
||||
const raw = loadJsonFile(authPath);
|
||||
const asStore = coerceAuthStore(raw);
|
||||
if (asStore) {
|
||||
// Sync from external CLI tools on every load
|
||||
const synced = syncExternalCliCredentials(asStore, options);
|
||||
const synced = syncExternalCliCredentials(asStore);
|
||||
if (synced) {
|
||||
saveJsonFile(authPath, asStore);
|
||||
}
|
||||
@@ -297,7 +292,7 @@ function loadAuthProfileStoreForAgent(
|
||||
}
|
||||
|
||||
const mergedOAuth = mergeOAuthFileIntoStore(store);
|
||||
const syncedCli = syncExternalCliCredentials(store, options);
|
||||
const syncedCli = syncExternalCliCredentials(store);
|
||||
const shouldWrite = legacy !== null || mergedOAuth || syncedCli;
|
||||
if (shouldWrite) {
|
||||
saveJsonFile(authPath, store);
|
||||
@@ -337,15 +332,6 @@ export function ensureAuthProfileStore(
|
||||
const mainStore = loadAuthProfileStoreForAgent(undefined, options);
|
||||
const merged = mergeAuthProfileStores(mainStore, store);
|
||||
|
||||
// Keep per-agent view clean even if the main store has codex-cli.
|
||||
const codexProfile = merged.profiles[CODEX_CLI_PROFILE_ID];
|
||||
if (codexProfile?.type === "oauth") {
|
||||
const duplicateId = findDuplicateCodexProfile(merged, codexProfile);
|
||||
if (duplicateId) {
|
||||
delete merged.profiles[CODEX_CLI_PROFILE_ID];
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { OAuthCredentials } from "@mariozechner/pi-ai";
|
||||
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
|
||||
export type ApiKeyCredential = {
|
||||
type: "api_key";
|
||||
@@ -12,7 +12,7 @@ export type ApiKeyCredential = {
|
||||
export type TokenCredential = {
|
||||
/**
|
||||
* Static bearer-style token (often OAuth access token / PAT).
|
||||
* Not refreshable by clawdbot (unlike `type: "oauth"`).
|
||||
* Not refreshable by moltbot (unlike `type: "oauth"`).
|
||||
*/
|
||||
type: "token";
|
||||
provider: string;
|
||||
@@ -65,7 +65,7 @@ export type AuthProfileStore = {
|
||||
};
|
||||
|
||||
export type AuthProfileIdRepairResult = {
|
||||
config: ClawdbotConfig;
|
||||
config: MoltbotConfig;
|
||||
changes: string[];
|
||||
migrated: boolean;
|
||||
fromProfileId?: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import { normalizeProviderId } from "../model-selection.js";
|
||||
import { saveAuthProfileStore, updateAuthProfileStoreWithLock } from "./store.js";
|
||||
import type { AuthProfileFailureReason, AuthProfileStore, ProfileUsageStats } from "./types.js";
|
||||
@@ -82,7 +82,7 @@ type ResolvedAuthCooldownConfig = {
|
||||
};
|
||||
|
||||
function resolveAuthCooldownConfig(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
providerId: string;
|
||||
}): ResolvedAuthCooldownConfig {
|
||||
const defaults = {
|
||||
@@ -192,7 +192,7 @@ export async function markAuthProfileFailure(params: {
|
||||
store: AuthProfileStore;
|
||||
profileId: string;
|
||||
reason: AuthProfileFailureReason;
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
agentDir?: string;
|
||||
}): Promise<void> {
|
||||
const { store, profileId, reason, agentDir, cfg } = params;
|
||||
|
||||
@@ -21,7 +21,7 @@ describe("exec approvals", () => {
|
||||
beforeEach(async () => {
|
||||
previousHome = process.env.HOME;
|
||||
previousUserProfile = process.env.USERPROFILE;
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-test-"));
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-test-"));
|
||||
process.env.HOME = tempDir;
|
||||
// Windows uses USERPROFILE for os.homedir()
|
||||
process.env.USERPROFILE = tempDir;
|
||||
@@ -80,7 +80,7 @@ describe("exec approvals", () => {
|
||||
|
||||
it("skips approval when node allowlist is satisfied", async () => {
|
||||
const { callGatewayTool } = await import("./tools/gateway.js");
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-test-bin-"));
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-test-bin-"));
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
await fs.mkdir(binDir, { recursive: true });
|
||||
const exeName = process.platform === "win32" ? "tool.cmd" : "tool";
|
||||
|
||||
@@ -60,11 +60,18 @@ export function buildDockerExecArgs(params: {
|
||||
for (const [key, value] of Object.entries(params.env)) {
|
||||
args.push("-e", `${key}=${value}`);
|
||||
}
|
||||
const hasCustomPath = typeof params.env.PATH === "string" && params.env.PATH.length > 0;
|
||||
if (hasCustomPath) {
|
||||
// Avoid interpolating PATH into the shell command; pass it via env instead.
|
||||
args.push("-e", `CLAWDBOT_PREPEND_PATH=${params.env.PATH}`);
|
||||
}
|
||||
// Login shell (-l) sources /etc/profile which resets PATH to a minimal set,
|
||||
// overriding both Docker ENV and -e PATH=... environment variables.
|
||||
// Prepend custom PATH after profile sourcing to ensure custom tools are accessible
|
||||
// while preserving system paths that /etc/profile may have added.
|
||||
const pathExport = params.env.PATH ? `export PATH="${params.env.PATH}:$PATH"; ` : "";
|
||||
const pathExport = hasCustomPath
|
||||
? 'export PATH="${CLAWDBOT_PREPEND_PATH}:$PATH"; unset CLAWDBOT_PREPEND_PATH; '
|
||||
: "";
|
||||
args.push(params.containerName, "sh", "-lc", `${pathExport}${params.command}`);
|
||||
return args;
|
||||
}
|
||||
|
||||
@@ -318,9 +318,30 @@ describe("buildDockerExecArgs", () => {
|
||||
});
|
||||
|
||||
const commandArg = args[args.length - 1];
|
||||
expect(commandArg).toContain('export PATH="/custom/bin:/usr/local/bin:/usr/bin:$PATH"');
|
||||
expect(args).toContain("CLAWDBOT_PREPEND_PATH=/custom/bin:/usr/local/bin:/usr/bin");
|
||||
expect(commandArg).toContain('export PATH="${CLAWDBOT_PREPEND_PATH}:$PATH"');
|
||||
expect(commandArg).toContain("echo hello");
|
||||
expect(commandArg).toBe('export PATH="/custom/bin:/usr/local/bin:/usr/bin:$PATH"; echo hello');
|
||||
expect(commandArg).toBe(
|
||||
'export PATH="${CLAWDBOT_PREPEND_PATH}:$PATH"; unset CLAWDBOT_PREPEND_PATH; echo hello',
|
||||
);
|
||||
});
|
||||
|
||||
it("does not interpolate PATH into the shell command", () => {
|
||||
const injectedPath = "$(touch /tmp/moltbot-path-injection)";
|
||||
const args = buildDockerExecArgs({
|
||||
containerName: "test-container",
|
||||
command: "echo hello",
|
||||
env: {
|
||||
PATH: injectedPath,
|
||||
HOME: "/home/user",
|
||||
},
|
||||
tty: false,
|
||||
});
|
||||
|
||||
const commandArg = args[args.length - 1];
|
||||
expect(args).toContain(`CLAWDBOT_PREPEND_PATH=${injectedPath}`);
|
||||
expect(commandArg).not.toContain(injectedPath);
|
||||
expect(commandArg).toContain("CLAWDBOT_PREPEND_PATH");
|
||||
});
|
||||
|
||||
it("does not add PATH export when PATH is not in env", () => {
|
||||
|
||||
@@ -28,7 +28,7 @@ describe("resolveBootstrapFilesForRun", () => {
|
||||
];
|
||||
});
|
||||
|
||||
const workspaceDir = await makeTempWorkspace("clawdbot-bootstrap-");
|
||||
const workspaceDir = await makeTempWorkspace("moltbot-bootstrap-");
|
||||
const files = await resolveBootstrapFilesForRun({ workspaceDir });
|
||||
|
||||
expect(files.some((file) => file.name === "EXTRA.md")).toBe(true);
|
||||
@@ -53,7 +53,7 @@ describe("resolveBootstrapContextForRun", () => {
|
||||
];
|
||||
});
|
||||
|
||||
const workspaceDir = await makeTempWorkspace("clawdbot-bootstrap-");
|
||||
const workspaceDir = await makeTempWorkspace("moltbot-bootstrap-");
|
||||
const result = await resolveBootstrapContextForRun({ workspaceDir });
|
||||
const extra = result.contextFiles.find((file) => file.path === "EXTRA.md");
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { applyBootstrapHookOverrides } from "./bootstrap-hooks.js";
|
||||
import {
|
||||
filterBootstrapFilesForSession,
|
||||
@@ -18,7 +18,7 @@ export function makeBootstrapWarn(params: {
|
||||
|
||||
export async function resolveBootstrapFilesForRun(params: {
|
||||
workspaceDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
sessionKey?: string;
|
||||
sessionId?: string;
|
||||
agentId?: string;
|
||||
@@ -40,7 +40,7 @@ export async function resolveBootstrapFilesForRun(params: {
|
||||
|
||||
export async function resolveBootstrapContextForRun(params: {
|
||||
workspaceDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
sessionKey?: string;
|
||||
sessionId?: string;
|
||||
agentId?: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { createInternalHookEvent, triggerInternalHook } from "../hooks/internal-hooks.js";
|
||||
import type { AgentBootstrapHookContext } from "../hooks/internal-hooks.js";
|
||||
import { resolveAgentIdFromSessionKey } from "../routing/session-key.js";
|
||||
@@ -7,7 +7,7 @@ import type { WorkspaceBootstrapFile } from "./workspace.js";
|
||||
export async function applyBootstrapHookOverrides(params: {
|
||||
files: WorkspaceBootstrapFile[];
|
||||
workspaceDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
sessionKey?: string;
|
||||
sessionId?: string;
|
||||
agentId?: string;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolveUserPath } from "../utils.js";
|
||||
import { createCacheTrace } from "./cache-trace.js";
|
||||
|
||||
describe("createCacheTrace", () => {
|
||||
it("returns null when diagnostics cache tracing is disabled", () => {
|
||||
const trace = createCacheTrace({
|
||||
cfg: {} as ClawdbotConfig,
|
||||
cfg: {} as MoltbotConfig,
|
||||
env: {},
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
import type { AgentMessage, StreamFn } from "@mariozechner/pi-agent-core";
|
||||
import type { Api, Model } from "@mariozechner/pi-ai";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolveStateDir } from "../config/paths.js";
|
||||
import { parseBooleanValue } from "../utils/boolean.js";
|
||||
import { resolveUserPath } from "../utils.js";
|
||||
@@ -52,7 +52,7 @@ export type CacheTrace = {
|
||||
};
|
||||
|
||||
type CacheTraceInit = {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
runId?: string;
|
||||
sessionId?: string;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import type { ChannelPlugin } from "../channels/plugins/types.js";
|
||||
import { setActivePluginRegistry } from "../plugins/runtime.js";
|
||||
import { createTestRegistry } from "../test-utils/channel-plugins.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
import { __testing, listAllChannelSupportedActions } from "./channel-tools.js";
|
||||
|
||||
describe("channel tools", () => {
|
||||
const errorSpy = vi.spyOn(defaultRuntime, "error").mockImplementation(() => undefined);
|
||||
|
||||
beforeEach(() => {
|
||||
const plugin: ChannelPlugin = {
|
||||
id: "test",
|
||||
meta: {
|
||||
id: "test",
|
||||
label: "Test",
|
||||
selectionLabel: "Test",
|
||||
docsPath: "/channels/test",
|
||||
blurb: "test plugin",
|
||||
},
|
||||
capabilities: { chatTypes: ["direct"] },
|
||||
config: {
|
||||
listAccountIds: () => [],
|
||||
resolveAccount: () => ({}),
|
||||
},
|
||||
actions: {
|
||||
listActions: () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
__testing.resetLoggedListActionErrors();
|
||||
errorSpy.mockClear();
|
||||
setActivePluginRegistry(createTestRegistry([{ pluginId: "test", source: "test", plugin }]));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setActivePluginRegistry(createTestRegistry([]));
|
||||
errorSpy.mockClear();
|
||||
});
|
||||
|
||||
it("skips crashing plugins and logs once", () => {
|
||||
const cfg = {} as MoltbotConfig;
|
||||
expect(listAllChannelSupportedActions({ cfg })).toEqual([]);
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(listAllChannelSupportedActions({ cfg })).toEqual([]);
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+48
-11
@@ -1,35 +1,40 @@
|
||||
import { getChannelDock } from "../channels/dock.js";
|
||||
import { getChannelPlugin, listChannelPlugins } from "../channels/plugins/index.js";
|
||||
import { normalizeAnyChannelId } from "../channels/registry.js";
|
||||
import type { ChannelAgentTool, ChannelMessageActionName } from "../channels/plugins/types.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type {
|
||||
ChannelAgentTool,
|
||||
ChannelMessageActionName,
|
||||
ChannelPlugin,
|
||||
} from "../channels/plugins/types.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
|
||||
/**
|
||||
* Get the list of supported message actions for a specific channel.
|
||||
* Returns an empty array if channel is not found or has no actions configured.
|
||||
*/
|
||||
export function listChannelSupportedActions(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
channel?: string;
|
||||
}): ChannelMessageActionName[] {
|
||||
if (!params.channel) return [];
|
||||
const plugin = getChannelPlugin(params.channel as Parameters<typeof getChannelPlugin>[0]);
|
||||
if (!plugin?.actions?.listActions) return [];
|
||||
const cfg = params.cfg ?? ({} as ClawdbotConfig);
|
||||
return plugin.actions.listActions({ cfg });
|
||||
const cfg = params.cfg ?? ({} as MoltbotConfig);
|
||||
return runPluginListActions(plugin, cfg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of all supported message actions across all configured channels.
|
||||
*/
|
||||
export function listAllChannelSupportedActions(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
}): ChannelMessageActionName[] {
|
||||
const actions = new Set<ChannelMessageActionName>();
|
||||
for (const plugin of listChannelPlugins()) {
|
||||
if (!plugin.actions?.listActions) continue;
|
||||
const cfg = params.cfg ?? ({} as ClawdbotConfig);
|
||||
const channelActions = plugin.actions.listActions({ cfg });
|
||||
const cfg = params.cfg ?? ({} as MoltbotConfig);
|
||||
const channelActions = runPluginListActions(plugin, cfg);
|
||||
for (const action of channelActions) {
|
||||
actions.add(action);
|
||||
}
|
||||
@@ -37,7 +42,7 @@ export function listAllChannelSupportedActions(params: {
|
||||
return Array.from(actions);
|
||||
}
|
||||
|
||||
export function listChannelAgentTools(params: { cfg?: ClawdbotConfig }): ChannelAgentTool[] {
|
||||
export function listChannelAgentTools(params: { cfg?: MoltbotConfig }): ChannelAgentTool[] {
|
||||
// Channel docking: aggregate channel-owned tools (login, etc.).
|
||||
const tools: ChannelAgentTool[] = [];
|
||||
for (const plugin of listChannelPlugins()) {
|
||||
@@ -50,7 +55,7 @@ export function listChannelAgentTools(params: { cfg?: ClawdbotConfig }): Channel
|
||||
}
|
||||
|
||||
export function resolveChannelMessageToolHints(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
channel?: string | null;
|
||||
accountId?: string | null;
|
||||
}): string[] {
|
||||
@@ -59,8 +64,40 @@ export function resolveChannelMessageToolHints(params: {
|
||||
const dock = getChannelDock(channelId);
|
||||
const resolve = dock?.agentPrompt?.messageToolHints;
|
||||
if (!resolve) return [];
|
||||
const cfg = params.cfg ?? ({} as ClawdbotConfig);
|
||||
const cfg = params.cfg ?? ({} as MoltbotConfig);
|
||||
return (resolve({ cfg, accountId: params.accountId }) ?? [])
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
const loggedListActionErrors = new Set<string>();
|
||||
|
||||
function runPluginListActions(
|
||||
plugin: ChannelPlugin,
|
||||
cfg: MoltbotConfig,
|
||||
): ChannelMessageActionName[] {
|
||||
if (!plugin.actions?.listActions) return [];
|
||||
try {
|
||||
const listed = plugin.actions.listActions({ cfg });
|
||||
return Array.isArray(listed) ? listed : [];
|
||||
} catch (err) {
|
||||
logListActionsError(plugin.id, err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function logListActionsError(pluginId: string, err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const key = `${pluginId}:${message}`;
|
||||
if (loggedListActionErrors.has(key)) return;
|
||||
loggedListActionErrors.add(key);
|
||||
const stack = err instanceof Error && err.stack ? err.stack : null;
|
||||
const details = stack ?? message;
|
||||
defaultRuntime.error?.(`[channel-tools] ${pluginId}.actions.listActions failed: ${details}`);
|
||||
}
|
||||
|
||||
export const __testing = {
|
||||
resetLoggedListActionErrors() {
|
||||
loggedListActionErrors.clear();
|
||||
},
|
||||
};
|
||||
@@ -45,7 +45,7 @@ describe("runClaudeCliAgent", () => {
|
||||
});
|
||||
|
||||
await runClaudeCliAgent({
|
||||
sessionId: "clawdbot-session",
|
||||
sessionId: "moltbot-session",
|
||||
sessionFile: "/tmp/session.jsonl",
|
||||
workspaceDir: "/tmp",
|
||||
prompt: "hi",
|
||||
@@ -61,7 +61,7 @@ describe("runClaudeCliAgent", () => {
|
||||
expect(argv).toContain("hi");
|
||||
});
|
||||
|
||||
it("uses provided --session-id when a claude session id is provided", async () => {
|
||||
it("uses --resume when a claude session id is provided", async () => {
|
||||
runCommandWithTimeoutMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({ message: "ok", session_id: "sid-2" }),
|
||||
stderr: "",
|
||||
@@ -71,7 +71,7 @@ describe("runClaudeCliAgent", () => {
|
||||
});
|
||||
|
||||
await runClaudeCliAgent({
|
||||
sessionId: "clawdbot-session",
|
||||
sessionId: "moltbot-session",
|
||||
sessionFile: "/tmp/session.jsonl",
|
||||
workspaceDir: "/tmp",
|
||||
prompt: "hi",
|
||||
@@ -83,7 +83,7 @@ describe("runClaudeCliAgent", () => {
|
||||
|
||||
expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(1);
|
||||
const argv = runCommandWithTimeoutMock.mock.calls[0]?.[0] as string[];
|
||||
expect(argv).toContain("--session-id");
|
||||
expect(argv).toContain("--resume");
|
||||
expect(argv).toContain("c9d7b831-1c31-4d22-80b9-1e50ca207d4b");
|
||||
expect(argv).toContain("hi");
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
|
||||
vi.mock("./tools/gateway.js", () => ({
|
||||
callGatewayTool: vi.fn(async (method: string) => {
|
||||
@@ -20,11 +20,13 @@ describe("gateway tool", () => {
|
||||
vi.useFakeTimers();
|
||||
const kill = vi.spyOn(process, "kill").mockImplementation(() => true);
|
||||
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-test-"));
|
||||
const previousProfile = process.env.CLAWDBOT_PROFILE;
|
||||
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-test-"));
|
||||
process.env.CLAWDBOT_STATE_DIR = stateDir;
|
||||
process.env.CLAWDBOT_PROFILE = "isolated";
|
||||
|
||||
try {
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
config: { commands: { restart: true } },
|
||||
}).find((candidate) => candidate.name === "gateway");
|
||||
expect(tool).toBeDefined();
|
||||
@@ -47,7 +49,9 @@ describe("gateway tool", () => {
|
||||
payload?: { kind?: string; doctorHint?: string | null };
|
||||
};
|
||||
expect(parsed.payload?.kind).toBe("restart");
|
||||
expect(parsed.payload?.doctorHint).toBe("Run: clawdbot doctor --non-interactive");
|
||||
expect(parsed.payload?.doctorHint).toBe(
|
||||
"Run: moltbot --profile isolated doctor --non-interactive",
|
||||
);
|
||||
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
await vi.runAllTimersAsync();
|
||||
@@ -60,12 +64,17 @@ describe("gateway tool", () => {
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = previousStateDir;
|
||||
}
|
||||
if (previousProfile === undefined) {
|
||||
delete process.env.CLAWDBOT_PROFILE;
|
||||
} else {
|
||||
process.env.CLAWDBOT_PROFILE = previousProfile;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("passes config.apply through gateway call", async () => {
|
||||
const { callGatewayTool } = await import("./tools/gateway.js");
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "agent:main:whatsapp:dm:+15555550123",
|
||||
}).find((candidate) => candidate.name === "gateway");
|
||||
expect(tool).toBeDefined();
|
||||
@@ -91,7 +100,7 @@ describe("gateway tool", () => {
|
||||
|
||||
it("passes config.patch through gateway call", async () => {
|
||||
const { callGatewayTool } = await import("./tools/gateway.js");
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "agent:main:whatsapp:dm:+15555550123",
|
||||
}).find((candidate) => candidate.name === "gateway");
|
||||
expect(tool).toBeDefined();
|
||||
@@ -117,7 +126,7 @@ describe("gateway tool", () => {
|
||||
|
||||
it("passes update.run through gateway call", async () => {
|
||||
const { callGatewayTool } = await import("./tools/gateway.js");
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "agent:main:whatsapp:dm:+15555550123",
|
||||
}).find((candidate) => candidate.name === "gateway");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
@@ -17,7 +17,7 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
|
||||
describe("agents_list", () => {
|
||||
beforeEach(() => {
|
||||
@@ -30,7 +30,7 @@ describe("agents_list", () => {
|
||||
});
|
||||
|
||||
it("defaults to the requester agent only", async () => {
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
}).find((candidate) => candidate.name === "agents_list");
|
||||
if (!tool) throw new Error("missing agents_list tool");
|
||||
@@ -67,7 +67,7 @@ describe("agents_list", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
}).find((candidate) => candidate.name === "agents_list");
|
||||
if (!tool) throw new Error("missing agents_list tool");
|
||||
@@ -107,7 +107,7 @@ describe("agents_list", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
}).find((candidate) => candidate.name === "agents_list");
|
||||
if (!tool) throw new Error("missing agents_list tool");
|
||||
@@ -142,7 +142,7 @@ describe("agents_list", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
}).find((candidate) => candidate.name === "agents_list");
|
||||
if (!tool) throw new Error("missing agents_list tool");
|
||||
|
||||
@@ -11,7 +11,7 @@ vi.mock("../media/image-ops.js", () => ({
|
||||
}));
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
|
||||
describe("nodes camera_snap", () => {
|
||||
beforeEach(() => {
|
||||
@@ -36,7 +36,7 @@ describe("nodes camera_snap", () => {
|
||||
throw new Error(`unexpected method: ${String(method)}`);
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "nodes");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "nodes");
|
||||
if (!tool) throw new Error("missing nodes tool");
|
||||
|
||||
const result = await tool.execute("call1", {
|
||||
@@ -72,7 +72,7 @@ describe("nodes camera_snap", () => {
|
||||
throw new Error(`unexpected method: ${String(method)}`);
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "nodes");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "nodes");
|
||||
if (!tool) throw new Error("missing nodes tool");
|
||||
|
||||
await tool.execute("call1", {
|
||||
@@ -113,7 +113,7 @@ describe("nodes run", () => {
|
||||
throw new Error(`unexpected method: ${String(method)}`);
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "nodes");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "nodes");
|
||||
if (!tool) throw new Error("missing nodes tool");
|
||||
|
||||
await tool.execute("call1", {
|
||||
|
||||
@@ -77,7 +77,7 @@ vi.mock("../infra/provider-usage.js", () => ({
|
||||
}));
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
|
||||
describe("session_status tool", () => {
|
||||
it("returns a status card for the current session", async () => {
|
||||
@@ -90,7 +90,7 @@ describe("session_status tool", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -99,7 +99,7 @@ describe("session_status tool", () => {
|
||||
const result = await tool.execute("call1", {});
|
||||
const details = result.details as { ok?: boolean; statusText?: string };
|
||||
expect(details.ok).toBe(true);
|
||||
expect(details.statusText).toContain("Clawdbot");
|
||||
expect(details.statusText).toContain("Moltbot");
|
||||
expect(details.statusText).toContain("🧠 Model:");
|
||||
expect(details.statusText).not.toContain("OAuth/token status");
|
||||
});
|
||||
@@ -111,7 +111,7 @@ describe("session_status tool", () => {
|
||||
main: { sessionId: "s1", updatedAt: 10 },
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -134,7 +134,7 @@ describe("session_status tool", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -156,7 +156,7 @@ describe("session_status tool", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -178,7 +178,7 @@ describe("session_status tool", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "agent:main:main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "agent:main:main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -218,7 +218,7 @@ describe("session_status tool", () => {
|
||||
},
|
||||
);
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "agent:support:main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "agent:support:main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -243,7 +243,7 @@ describe("session_status tool", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({ agentSessionKey: "main" }).find(
|
||||
const tool = createMoltbotTools({ agentSessionKey: "main" }).find(
|
||||
(candidate) => candidate.name === "session_status",
|
||||
);
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
@@ -21,7 +21,7 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
|
||||
const waitForCalls = async (getCount: () => number, count: number, timeoutMs = 2000) => {
|
||||
const start = Date.now();
|
||||
@@ -35,7 +35,7 @@ const waitForCalls = async (getCount: () => number, count: number, timeoutMs = 2
|
||||
|
||||
describe("sessions tools", () => {
|
||||
it("uses number (not integer) in tool schemas for Gemini compatibility", () => {
|
||||
const tools = createClawdbotTools();
|
||||
const tools = createMoltbotTools();
|
||||
const byName = (name: string) => {
|
||||
const tool = tools.find((candidate) => candidate.name === name);
|
||||
expect(tool).toBeDefined();
|
||||
@@ -118,7 +118,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "sessions_list");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "sessions_list");
|
||||
expect(tool).toBeDefined();
|
||||
if (!tool) throw new Error("missing sessions_list tool");
|
||||
|
||||
@@ -155,7 +155,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "sessions_history");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "sessions_history");
|
||||
expect(tool).toBeDefined();
|
||||
if (!tool) throw new Error("missing sessions_history tool");
|
||||
|
||||
@@ -191,7 +191,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "sessions_history");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "sessions_history");
|
||||
expect(tool).toBeDefined();
|
||||
if (!tool) throw new Error("missing sessions_history tool");
|
||||
|
||||
@@ -218,7 +218,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools().find((candidate) => candidate.name === "sessions_history");
|
||||
const tool = createMoltbotTools().find((candidate) => candidate.name === "sessions_history");
|
||||
expect(tool).toBeDefined();
|
||||
if (!tool) throw new Error("missing sessions_history tool");
|
||||
|
||||
@@ -290,7 +290,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: requesterKey,
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_send");
|
||||
@@ -390,7 +390,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_send");
|
||||
@@ -480,7 +480,7 @@ describe("sessions tools", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: requesterKey,
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_send");
|
||||
|
||||
+4
-4
@@ -22,10 +22,10 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
import { resetSubagentRegistryForTests } from "./subagent-registry.js";
|
||||
|
||||
describe("clawdbot-tools: subagents", () => {
|
||||
describe("moltbot-tools: subagents", () => {
|
||||
beforeEach(() => {
|
||||
configOverride = {
|
||||
session: {
|
||||
@@ -69,7 +69,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -120,7 +120,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
|
||||
+3
-3
@@ -22,10 +22,10 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
import { resetSubagentRegistryForTests } from "./subagent-registry.js";
|
||||
|
||||
describe("clawdbot-tools: subagents", () => {
|
||||
describe("moltbot-tools: subagents", () => {
|
||||
beforeEach(() => {
|
||||
configOverride = {
|
||||
session: {
|
||||
@@ -89,7 +89,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "discord:group:req",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
|
||||
+6
-6
@@ -22,10 +22,10 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
import { resetSubagentRegistryForTests } from "./subagent-registry.js";
|
||||
|
||||
describe("clawdbot-tools: subagents", () => {
|
||||
describe("moltbot-tools: subagents", () => {
|
||||
beforeEach(() => {
|
||||
configOverride = {
|
||||
session: {
|
||||
@@ -65,7 +65,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "discord:group:req",
|
||||
agentSurface: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -108,7 +108,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "discord:group:req",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -139,7 +139,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "discord:group:req",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -176,7 +176,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "agent:main:main",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
|
||||
+6
-6
@@ -23,10 +23,10 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
|
||||
import { emitAgentEvent } from "../infra/agent-events.js";
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
import { resetSubagentRegistryForTests } from "./subagent-registry.js";
|
||||
|
||||
describe("clawdbot-tools: subagents", () => {
|
||||
describe("moltbot-tools: subagents", () => {
|
||||
beforeEach(() => {
|
||||
configOverride = {
|
||||
session: {
|
||||
@@ -70,7 +70,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -107,7 +107,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -171,7 +171,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "discord:group:req",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -272,7 +272,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
agentAccountId: "kev",
|
||||
|
||||
+5
-5
@@ -22,10 +22,10 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
import { resetSubagentRegistryForTests } from "./subagent-registry.js";
|
||||
|
||||
describe("clawdbot-tools: subagents", () => {
|
||||
describe("moltbot-tools: subagents", () => {
|
||||
beforeEach(() => {
|
||||
configOverride = {
|
||||
session: {
|
||||
@@ -59,7 +59,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "agent:research:main",
|
||||
agentChannel: "discord",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -108,7 +108,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -143,7 +143,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
|
||||
+4
-4
@@ -23,10 +23,10 @@ vi.mock("../config/config.js", async (importOriginal) => {
|
||||
|
||||
import { emitAgentEvent } from "../infra/agent-events.js";
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import { createMoltbotTools } from "./moltbot-tools.js";
|
||||
import { resetSubagentRegistryForTests } from "./subagent-registry.js";
|
||||
|
||||
describe("clawdbot-tools: subagents", () => {
|
||||
describe("moltbot-tools: subagents", () => {
|
||||
beforeEach(() => {
|
||||
configOverride = {
|
||||
session: {
|
||||
@@ -95,7 +95,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
return {};
|
||||
});
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
@@ -155,7 +155,7 @@ describe("clawdbot-tools: subagents", () => {
|
||||
resetSubagentRegistryForTests();
|
||||
callGatewayMock.mockReset();
|
||||
|
||||
const tool = createClawdbotTools({
|
||||
const tool = createMoltbotTools({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "whatsapp",
|
||||
}).find((candidate) => candidate.name === "sessions_spawn");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import type { CliBackendConfig } from "../config/types.js";
|
||||
import { normalizeProviderId } from "./model-selection.js";
|
||||
|
||||
@@ -28,6 +28,14 @@ const CLAUDE_MODEL_ALIASES: Record<string, string> = {
|
||||
const DEFAULT_CLAUDE_BACKEND: CliBackendConfig = {
|
||||
command: "claude",
|
||||
args: ["-p", "--output-format", "json", "--dangerously-skip-permissions"],
|
||||
resumeArgs: [
|
||||
"-p",
|
||||
"--output-format",
|
||||
"json",
|
||||
"--dangerously-skip-permissions",
|
||||
"--resume",
|
||||
"{sessionId}",
|
||||
],
|
||||
output: "json",
|
||||
input: "arg",
|
||||
modelArg: "--model",
|
||||
@@ -95,7 +103,7 @@ function mergeBackendConfig(base: CliBackendConfig, override?: CliBackendConfig)
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCliBackendIds(cfg?: ClawdbotConfig): Set<string> {
|
||||
export function resolveCliBackendIds(cfg?: MoltbotConfig): Set<string> {
|
||||
const ids = new Set<string>([
|
||||
normalizeBackendKey("claude-cli"),
|
||||
normalizeBackendKey("codex-cli"),
|
||||
@@ -109,7 +117,7 @@ export function resolveCliBackendIds(cfg?: ClawdbotConfig): Set<string> {
|
||||
|
||||
export function resolveCliBackendConfig(
|
||||
provider: string,
|
||||
cfg?: ClawdbotConfig,
|
||||
cfg?: MoltbotConfig,
|
||||
): ResolvedCliBackend | null {
|
||||
const normalized = normalizeBackendKey(provider);
|
||||
const configured = cfg?.agents?.defaults?.cliBackends ?? {};
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("cli credentials", () => {
|
||||
});
|
||||
|
||||
it("falls back to the file store when the keychain update fails", async () => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-"));
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-"));
|
||||
const credPath = path.join(tempDir, ".claude", ".credentials.json");
|
||||
|
||||
fs.mkdirSync(path.dirname(credPath), { recursive: true, mode: 0o700 });
|
||||
@@ -182,7 +182,7 @@ describe("cli credentials", () => {
|
||||
});
|
||||
|
||||
it("reads Codex credentials from keychain when available", async () => {
|
||||
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-"));
|
||||
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-codex-"));
|
||||
process.env.CODEX_HOME = tempHome;
|
||||
|
||||
const accountHash = "cli|";
|
||||
@@ -211,7 +211,7 @@ describe("cli credentials", () => {
|
||||
});
|
||||
|
||||
it("falls back to Codex auth.json when keychain is unavailable", async () => {
|
||||
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-codex-"));
|
||||
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "moltbot-codex-"));
|
||||
process.env.CODEX_HOME = tempHome;
|
||||
execSyncMock.mockImplementation(() => {
|
||||
throw new Error("not found");
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import type { ImageContent } from "@mariozechner/pi-ai";
|
||||
import { resolveHeartbeatPrompt } from "../auto-reply/heartbeat.js";
|
||||
import type { ThinkLevel } from "../auto-reply/thinking.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { isTruthyEnvValue } from "../infra/env.js";
|
||||
import { shouldLogVerbose } from "../globals.js";
|
||||
import { createSubsystemLogger } from "../logging/subsystem.js";
|
||||
import { runCommandWithTimeout } from "../process/exec.js";
|
||||
import { resolveUserPath } from "../utils.js";
|
||||
import { resolveClawdbotDocsPath } from "./docs-path.js";
|
||||
import { resolveMoltbotDocsPath } from "./docs-path.js";
|
||||
import { resolveSessionAgentIds } from "./agent-scope.js";
|
||||
import { makeBootstrapWarn, resolveBootstrapContextForRun } from "./bootstrap-files.js";
|
||||
import { resolveCliBackendConfig } from "./cli-backends.js";
|
||||
@@ -37,7 +37,7 @@ export async function runCliAgent(params: {
|
||||
sessionKey?: string;
|
||||
sessionFile: string;
|
||||
workspaceDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
prompt: string;
|
||||
provider: string;
|
||||
model?: string;
|
||||
@@ -86,7 +86,7 @@ export async function runCliAgent(params: {
|
||||
sessionAgentId === defaultAgentId
|
||||
? resolveHeartbeatPrompt(params.config?.agents?.defaults?.heartbeat?.prompt)
|
||||
: undefined;
|
||||
const docsPath = await resolveClawdbotDocsPath({
|
||||
const docsPath = await resolveMoltbotDocsPath({
|
||||
workspaceDir,
|
||||
argv1: process.argv[1],
|
||||
cwd: process.cwd(),
|
||||
@@ -303,7 +303,7 @@ export async function runClaudeCliAgent(params: {
|
||||
sessionKey?: string;
|
||||
sessionFile: string;
|
||||
workspaceDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
prompt: string;
|
||||
provider?: string;
|
||||
model?: string;
|
||||
|
||||
@@ -6,7 +6,7 @@ import path from "node:path";
|
||||
import type { AgentTool } from "@mariozechner/pi-agent-core";
|
||||
import type { ImageContent } from "@mariozechner/pi-ai";
|
||||
import type { ThinkLevel } from "../../auto-reply/thinking.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import type { CliBackendConfig } from "../../config/types.js";
|
||||
import { runExec } from "../../process/exec.js";
|
||||
import type { EmbeddedContextFile } from "../pi-embedded-helpers.js";
|
||||
@@ -86,7 +86,7 @@ function tokenToRegex(token: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup suspended Clawdbot CLI processes that have accumulated.
|
||||
* Cleanup suspended Moltbot CLI processes that have accumulated.
|
||||
* Only cleans up if there are more than the threshold (default: 10).
|
||||
*/
|
||||
export async function cleanupSuspendedCliProcesses(
|
||||
@@ -148,7 +148,7 @@ export type CliOutput = {
|
||||
usage?: CliUsage;
|
||||
};
|
||||
|
||||
function buildModelAliasLines(cfg?: ClawdbotConfig) {
|
||||
function buildModelAliasLines(cfg?: MoltbotConfig) {
|
||||
const models = cfg?.agents?.defaults?.models ?? {};
|
||||
const entries: Array<{ alias: string; model: string }> = [];
|
||||
for (const [keyRaw, entryRaw] of Object.entries(models)) {
|
||||
@@ -165,7 +165,7 @@ function buildModelAliasLines(cfg?: ClawdbotConfig) {
|
||||
|
||||
export function buildSystemPrompt(params: {
|
||||
workspaceDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
defaultThinkLevel?: ThinkLevel;
|
||||
extraSystemPrompt?: string;
|
||||
ownerNumbers?: string[];
|
||||
@@ -187,7 +187,7 @@ export function buildSystemPrompt(params: {
|
||||
workspaceDir: params.workspaceDir,
|
||||
cwd: process.cwd(),
|
||||
runtime: {
|
||||
host: "clawdbot",
|
||||
host: "moltbot",
|
||||
os: `${os.type()} ${os.release()}`,
|
||||
arch: os.arch(),
|
||||
node: process.version,
|
||||
@@ -389,7 +389,7 @@ export function appendImagePathsToPrompt(prompt: string, paths: string[]): strin
|
||||
export async function writeCliImages(
|
||||
images: ImageContent[],
|
||||
): Promise<{ paths: string[]; cleanup: () => Promise<void> }> {
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-cli-images-"));
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-cli-images-"));
|
||||
const paths: string[] = [];
|
||||
for (let i = 0; i < images.length; i += 1) {
|
||||
const image = images[i];
|
||||
|
||||
@@ -103,5 +103,47 @@ describe("pruneHistoryForContextShare", () => {
|
||||
expect(pruned.droppedChunks).toBe(0);
|
||||
expect(pruned.messages.length).toBe(messages.length);
|
||||
expect(pruned.keptTokens).toBe(estimateMessagesTokens(messages));
|
||||
expect(pruned.droppedMessagesList).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns droppedMessagesList containing dropped messages", () => {
|
||||
const messages: AgentMessage[] = [
|
||||
makeMessage(1, 4000),
|
||||
makeMessage(2, 4000),
|
||||
makeMessage(3, 4000),
|
||||
makeMessage(4, 4000),
|
||||
];
|
||||
const maxContextTokens = 2000; // budget is 1000 tokens (50%)
|
||||
const pruned = pruneHistoryForContextShare({
|
||||
messages,
|
||||
maxContextTokens,
|
||||
maxHistoryShare: 0.5,
|
||||
parts: 2,
|
||||
});
|
||||
|
||||
expect(pruned.droppedChunks).toBeGreaterThan(0);
|
||||
expect(pruned.droppedMessagesList.length).toBe(pruned.droppedMessages);
|
||||
|
||||
// All messages accounted for: kept + dropped = original
|
||||
const allIds = [
|
||||
...pruned.droppedMessagesList.map((m) => m.timestamp),
|
||||
...pruned.messages.map((m) => m.timestamp),
|
||||
].sort((a, b) => a - b);
|
||||
const originalIds = messages.map((m) => m.timestamp).sort((a, b) => a - b);
|
||||
expect(allIds).toEqual(originalIds);
|
||||
});
|
||||
|
||||
it("returns empty droppedMessagesList when no pruning needed", () => {
|
||||
const messages: AgentMessage[] = [makeMessage(1, 100)];
|
||||
const pruned = pruneHistoryForContextShare({
|
||||
messages,
|
||||
maxContextTokens: 100_000,
|
||||
maxHistoryShare: 0.5,
|
||||
parts: 2,
|
||||
});
|
||||
|
||||
expect(pruned.droppedChunks).toBe(0);
|
||||
expect(pruned.droppedMessagesList).toEqual([]);
|
||||
expect(pruned.messages.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -301,6 +301,7 @@ export function pruneHistoryForContextShare(params: {
|
||||
parts?: number;
|
||||
}): {
|
||||
messages: AgentMessage[];
|
||||
droppedMessagesList: AgentMessage[];
|
||||
droppedChunks: number;
|
||||
droppedMessages: number;
|
||||
droppedTokens: number;
|
||||
@@ -310,6 +311,7 @@ export function pruneHistoryForContextShare(params: {
|
||||
const maxHistoryShare = params.maxHistoryShare ?? 0.5;
|
||||
const budgetTokens = Math.max(1, Math.floor(params.maxContextTokens * maxHistoryShare));
|
||||
let keptMessages = params.messages;
|
||||
const allDroppedMessages: AgentMessage[] = [];
|
||||
let droppedChunks = 0;
|
||||
let droppedMessages = 0;
|
||||
let droppedTokens = 0;
|
||||
@@ -323,11 +325,13 @@ export function pruneHistoryForContextShare(params: {
|
||||
droppedChunks += 1;
|
||||
droppedMessages += dropped.length;
|
||||
droppedTokens += estimateMessagesTokens(dropped);
|
||||
allDroppedMessages.push(...dropped);
|
||||
keptMessages = rest.flat();
|
||||
}
|
||||
|
||||
return {
|
||||
messages: keptMessages,
|
||||
droppedMessagesList: allDroppedMessages,
|
||||
droppedChunks,
|
||||
droppedMessages,
|
||||
droppedTokens,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import {
|
||||
CONTEXT_WINDOW_HARD_MIN_TOKENS,
|
||||
CONTEXT_WINDOW_WARN_BELOW_TOKENS,
|
||||
@@ -72,7 +72,7 @@ describe("context-window-guard", () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies ClawdbotConfig;
|
||||
} satisfies MoltbotConfig;
|
||||
|
||||
const info = resolveContextWindowInfo({
|
||||
cfg,
|
||||
@@ -89,7 +89,7 @@ describe("context-window-guard", () => {
|
||||
it("falls back to agents.defaults.contextTokens", () => {
|
||||
const cfg = {
|
||||
agents: { defaults: { contextTokens: 20_000 } },
|
||||
} satisfies ClawdbotConfig;
|
||||
} satisfies MoltbotConfig;
|
||||
const info = resolveContextWindowInfo({
|
||||
cfg,
|
||||
provider: "anthropic",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
export const CONTEXT_WINDOW_HARD_MIN_TOKENS = 16_000;
|
||||
export const CONTEXT_WINDOW_WARN_BELOW_TOKENS = 32_000;
|
||||
@@ -17,7 +17,7 @@ function normalizePositiveInt(value: unknown): number | null {
|
||||
}
|
||||
|
||||
export function resolveContextWindowInfo(params: {
|
||||
cfg: ClawdbotConfig | undefined;
|
||||
cfg: MoltbotConfig | undefined;
|
||||
provider: string;
|
||||
modelId: string;
|
||||
modelContextWindow?: number;
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
// the agent reports a model id. This includes custom models.json entries.
|
||||
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import { resolveClawdbotAgentDir } from "./agent-paths.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import { resolveMoltbotAgentDir } from "./agent-paths.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
|
||||
type ModelEntry = { id: string; contextWindow?: number };
|
||||
|
||||
@@ -12,8 +12,8 @@ const loadPromise = (async () => {
|
||||
try {
|
||||
const { discoverAuthStorage, discoverModels } = await import("@mariozechner/pi-coding-agent");
|
||||
const cfg = loadConfig();
|
||||
await ensureClawdbotModelsJson(cfg);
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
await ensureMoltbotModelsJson(cfg);
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
const authStorage = discoverAuthStorage(agentDir);
|
||||
const modelRegistry = discoverModels(authStorage, agentDir);
|
||||
const models = modelRegistry.getAll() as ModelEntry[];
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { resolveClawdbotPackageRoot } from "../infra/clawdbot-root.js";
|
||||
import { resolveMoltbotPackageRoot } from "../infra/moltbot-root.js";
|
||||
|
||||
export async function resolveClawdbotDocsPath(params: {
|
||||
export async function resolveMoltbotDocsPath(params: {
|
||||
workspaceDir?: string;
|
||||
argv1?: string;
|
||||
cwd?: string;
|
||||
@@ -15,7 +15,7 @@ export async function resolveClawdbotDocsPath(params: {
|
||||
if (fs.existsSync(workspaceDocs)) return workspaceDocs;
|
||||
}
|
||||
|
||||
const packageRoot = await resolveClawdbotPackageRoot({
|
||||
const packageRoot = await resolveMoltbotPackageRoot({
|
||||
cwd: params.cwd,
|
||||
argv1: params.argv1,
|
||||
moduleUrl: params.moduleUrl,
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolveAgentAvatar } from "./identity-avatar.js";
|
||||
|
||||
async function writeFile(filePath: string, contents = "avatar") {
|
||||
@@ -14,12 +14,12 @@ async function writeFile(filePath: string, contents = "avatar") {
|
||||
|
||||
describe("resolveAgentAvatar", () => {
|
||||
it("resolves local avatar from config when inside workspace", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-avatar-"));
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-avatar-"));
|
||||
const workspace = path.join(root, "work");
|
||||
const avatarPath = path.join(workspace, "avatars", "main.png");
|
||||
await writeFile(avatarPath);
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -41,13 +41,13 @@ describe("resolveAgentAvatar", () => {
|
||||
});
|
||||
|
||||
it("rejects avatars outside the workspace", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-avatar-"));
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-avatar-"));
|
||||
const workspace = path.join(root, "work");
|
||||
await fs.mkdir(workspace, { recursive: true });
|
||||
const outsidePath = path.join(root, "outside.png");
|
||||
await writeFile(outsidePath);
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
@@ -67,7 +67,7 @@ describe("resolveAgentAvatar", () => {
|
||||
});
|
||||
|
||||
it("falls back to IDENTITY.md when config has no avatar", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-avatar-"));
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-avatar-"));
|
||||
const workspace = path.join(root, "work");
|
||||
const avatarPath = path.join(workspace, "avatars", "fallback.png");
|
||||
await writeFile(avatarPath);
|
||||
@@ -78,7 +78,7 @@ describe("resolveAgentAvatar", () => {
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [{ id: "main", workspace }],
|
||||
},
|
||||
@@ -94,7 +94,7 @@ describe("resolveAgentAvatar", () => {
|
||||
});
|
||||
|
||||
it("accepts remote and data avatars", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
list: [
|
||||
{ id: "main", identity: { avatar: "https://example.com/avatar.png" } },
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolveUserPath } from "../utils.js";
|
||||
import { resolveAgentWorkspaceDir } from "./agent-scope.js";
|
||||
import { loadAgentIdentityFromWorkspace } from "./identity-file.js";
|
||||
@@ -20,7 +20,7 @@ function normalizeAvatarValue(value: string | undefined | null): string | null {
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function resolveAvatarSource(cfg: ClawdbotConfig, agentId: string): string | null {
|
||||
function resolveAvatarSource(cfg: MoltbotConfig, agentId: string): string | null {
|
||||
const fromConfig = normalizeAvatarValue(resolveAgentIdentity(cfg, agentId)?.avatar);
|
||||
if (fromConfig) return fromConfig;
|
||||
const workspace = resolveAgentWorkspaceDir(cfg, agentId);
|
||||
@@ -79,7 +79,7 @@ function resolveLocalAvatarPath(params: {
|
||||
return { ok: true, filePath: realPath };
|
||||
}
|
||||
|
||||
export function resolveAgentAvatar(cfg: ClawdbotConfig, agentId: string): AgentAvatarResolution {
|
||||
export function resolveAgentAvatar(cfg: MoltbotConfig, agentId: string): AgentAvatarResolution {
|
||||
const source = resolveAvatarSource(cfg, agentId);
|
||||
if (!source) {
|
||||
return { kind: "none", reason: "missing" };
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolveHumanDelayConfig } from "./identity.js";
|
||||
|
||||
describe("resolveHumanDelayConfig", () => {
|
||||
it("returns undefined when no humanDelay config is set", () => {
|
||||
const cfg: ClawdbotConfig = {};
|
||||
const cfg: MoltbotConfig = {};
|
||||
expect(resolveHumanDelayConfig(cfg, "main")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("merges defaults with per-agent overrides", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
defaults: {
|
||||
humanDelay: { mode: "natural", minMs: 800, maxMs: 1800 },
|
||||
|
||||
+10
-13
@@ -1,38 +1,35 @@
|
||||
import type { ClawdbotConfig, HumanDelayConfig, IdentityConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig, HumanDelayConfig, IdentityConfig } from "../config/config.js";
|
||||
import { resolveAgentConfig } from "./agent-scope.js";
|
||||
|
||||
const DEFAULT_ACK_REACTION = "👀";
|
||||
|
||||
export function resolveAgentIdentity(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
): IdentityConfig | undefined {
|
||||
return resolveAgentConfig(cfg, agentId)?.identity;
|
||||
}
|
||||
|
||||
export function resolveAckReaction(cfg: ClawdbotConfig, agentId: string): string {
|
||||
export function resolveAckReaction(cfg: MoltbotConfig, agentId: string): string {
|
||||
const configured = cfg.messages?.ackReaction;
|
||||
if (configured !== undefined) return configured.trim();
|
||||
const emoji = resolveAgentIdentity(cfg, agentId)?.emoji?.trim();
|
||||
return emoji || DEFAULT_ACK_REACTION;
|
||||
}
|
||||
|
||||
export function resolveIdentityNamePrefix(
|
||||
cfg: ClawdbotConfig,
|
||||
agentId: string,
|
||||
): string | undefined {
|
||||
export function resolveIdentityNamePrefix(cfg: MoltbotConfig, agentId: string): string | undefined {
|
||||
const name = resolveAgentIdentity(cfg, agentId)?.name?.trim();
|
||||
if (!name) return undefined;
|
||||
return `[${name}]`;
|
||||
}
|
||||
|
||||
/** Returns just the identity name (without brackets) for template context. */
|
||||
export function resolveIdentityName(cfg: ClawdbotConfig, agentId: string): string | undefined {
|
||||
export function resolveIdentityName(cfg: MoltbotConfig, agentId: string): string | undefined {
|
||||
return resolveAgentIdentity(cfg, agentId)?.name?.trim() || undefined;
|
||||
}
|
||||
|
||||
export function resolveMessagePrefix(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
opts?: { configured?: string; hasAllowFrom?: boolean; fallback?: string },
|
||||
): string {
|
||||
@@ -42,10 +39,10 @@ export function resolveMessagePrefix(
|
||||
const hasAllowFrom = opts?.hasAllowFrom === true;
|
||||
if (hasAllowFrom) return "";
|
||||
|
||||
return resolveIdentityNamePrefix(cfg, agentId) ?? opts?.fallback ?? "[clawdbot]";
|
||||
return resolveIdentityNamePrefix(cfg, agentId) ?? opts?.fallback ?? "[moltbot]";
|
||||
}
|
||||
|
||||
export function resolveResponsePrefix(cfg: ClawdbotConfig, agentId: string): string | undefined {
|
||||
export function resolveResponsePrefix(cfg: MoltbotConfig, agentId: string): string | undefined {
|
||||
const configured = cfg.messages?.responsePrefix;
|
||||
if (configured !== undefined) {
|
||||
if (configured === "auto") {
|
||||
@@ -57,7 +54,7 @@ export function resolveResponsePrefix(cfg: ClawdbotConfig, agentId: string): str
|
||||
}
|
||||
|
||||
export function resolveEffectiveMessagesConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
opts?: { hasAllowFrom?: boolean; fallbackMessagePrefix?: string },
|
||||
): { messagePrefix: string; responsePrefix?: string } {
|
||||
@@ -71,7 +68,7 @@ export function resolveEffectiveMessagesConfig(
|
||||
}
|
||||
|
||||
export function resolveHumanDelayConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
): HumanDelayConfig | undefined {
|
||||
const defaults = cfg.agents?.defaults?.humanDelay;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ClawdbotConfig, MemorySearchConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig, MemorySearchConfig } from "../config/config.js";
|
||||
import { resolveStateDir } from "../config/paths.js";
|
||||
import { clampInt, clampNumber, resolveUserPath } from "../utils.js";
|
||||
import { resolveAgentConfig } from "./agent-scope.js";
|
||||
@@ -119,9 +119,16 @@ function mergeConfig(
|
||||
const provider = overrides?.provider ?? defaults?.provider ?? "auto";
|
||||
const defaultRemote = defaults?.remote;
|
||||
const overrideRemote = overrides?.remote;
|
||||
const hasRemote = Boolean(defaultRemote || overrideRemote);
|
||||
const hasRemoteConfig = Boolean(
|
||||
overrideRemote?.baseUrl ||
|
||||
overrideRemote?.apiKey ||
|
||||
overrideRemote?.headers ||
|
||||
defaultRemote?.baseUrl ||
|
||||
defaultRemote?.apiKey ||
|
||||
defaultRemote?.headers,
|
||||
);
|
||||
const includeRemote =
|
||||
hasRemote || provider === "openai" || provider === "gemini" || provider === "auto";
|
||||
hasRemoteConfig || provider === "openai" || provider === "gemini" || provider === "auto";
|
||||
const batch = {
|
||||
enabled: overrideRemote?.batch?.enabled ?? defaultRemote?.batch?.enabled ?? true,
|
||||
wait: overrideRemote?.batch?.wait ?? defaultRemote?.batch?.wait ?? true,
|
||||
@@ -267,7 +274,7 @@ function mergeConfig(
|
||||
}
|
||||
|
||||
export function resolveMemorySearchConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
cfg: MoltbotConfig,
|
||||
agentId: string,
|
||||
): ResolvedMemorySearchConfig | null {
|
||||
const defaults = cfg.agents?.defaults?.memorySearch;
|
||||
|
||||
@@ -65,7 +65,7 @@ export async function minimaxUnderstandImage(params: {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"MM-API-Source": "Clawdbot",
|
||||
"MM-API-Source": "Moltbot",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
|
||||
@@ -16,7 +16,7 @@ describe("getApiKeyForModel", () => {
|
||||
const previousStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
|
||||
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-oauth-"));
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-oauth-"));
|
||||
|
||||
try {
|
||||
process.env.CLAWDBOT_STATE_DIR = tempDir;
|
||||
@@ -99,7 +99,7 @@ describe("getApiKeyForModel", () => {
|
||||
const previousAgentDir = process.env.CLAWDBOT_AGENT_DIR;
|
||||
const previousPiAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
const previousOpenAiKey = process.env.OPENAI_API_KEY;
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-auth-"));
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
|
||||
try {
|
||||
delete process.env.OPENAI_API_KEY;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { type Api, getEnvApiKey, type Model } from "@mariozechner/pi-ai";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import type { ModelProviderAuthMode, ModelProviderConfig } from "../config/types.js";
|
||||
import { getShellEnvAppliedKeys } from "../infra/shell-env.js";
|
||||
import { formatCliCommand } from "../cli/command-format.js";
|
||||
@@ -23,7 +23,7 @@ const AWS_SECRET_KEY_ENV = "AWS_SECRET_ACCESS_KEY";
|
||||
const AWS_PROFILE_ENV = "AWS_PROFILE";
|
||||
|
||||
function resolveProviderConfig(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
cfg: MoltbotConfig | undefined,
|
||||
provider: string,
|
||||
): ModelProviderConfig | undefined {
|
||||
const providers = cfg?.models?.providers ?? {};
|
||||
@@ -45,7 +45,7 @@ function resolveProviderConfig(
|
||||
}
|
||||
|
||||
export function getCustomProviderApiKey(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
cfg: MoltbotConfig | undefined,
|
||||
provider: string,
|
||||
): string | undefined {
|
||||
const entry = resolveProviderConfig(cfg, provider);
|
||||
@@ -54,7 +54,7 @@ export function getCustomProviderApiKey(
|
||||
}
|
||||
|
||||
function resolveProviderAuthOverride(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
cfg: MoltbotConfig | undefined,
|
||||
provider: string,
|
||||
): ModelProviderAuthMode | undefined {
|
||||
const entry = resolveProviderConfig(cfg, provider);
|
||||
@@ -128,7 +128,7 @@ export type ResolvedProviderAuth = {
|
||||
|
||||
export async function resolveApiKeyForProvider(params: {
|
||||
provider: string;
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
profileId?: string;
|
||||
preferredProfile?: string;
|
||||
store?: AuthProfileStore;
|
||||
@@ -221,7 +221,7 @@ export async function resolveApiKeyForProvider(params: {
|
||||
[
|
||||
`No API key found for provider "${provider}".`,
|
||||
`Auth store: ${authStorePath} (agentDir: ${resolvedAgentDir}).`,
|
||||
`Configure auth for this agent (${formatCliCommand("clawdbot agents add <id>")}) or copy auth-profiles.json from the main agentDir.`,
|
||||
`Configure auth for this agent (${formatCliCommand("moltbot agents add <id>")}) or copy auth-profiles.json from the main agentDir.`,
|
||||
].join(" "),
|
||||
);
|
||||
}
|
||||
@@ -293,7 +293,7 @@ export function resolveEnvApiKey(provider: string): EnvApiKeyResult | null {
|
||||
|
||||
export function resolveModelAuthMode(
|
||||
provider?: string,
|
||||
cfg?: ClawdbotConfig,
|
||||
cfg?: MoltbotConfig,
|
||||
store?: AuthProfileStore,
|
||||
): ModelAuthMode | undefined {
|
||||
const resolved = provider?.trim();
|
||||
@@ -335,7 +335,7 @@ export function resolveModelAuthMode(
|
||||
|
||||
export async function getApiKeyForModel(params: {
|
||||
model: Model<Api>;
|
||||
cfg?: ClawdbotConfig;
|
||||
cfg?: MoltbotConfig;
|
||||
profileId?: string;
|
||||
preferredProfile?: string;
|
||||
store?: AuthProfileStore;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import {
|
||||
__setModelCatalogImportForTest,
|
||||
loadModelCatalog,
|
||||
@@ -10,11 +10,11 @@ import {
|
||||
type PiSdkModule = typeof import("@mariozechner/pi-coding-agent");
|
||||
|
||||
vi.mock("./models-config.js", () => ({
|
||||
ensureClawdbotModelsJson: vi.fn().mockResolvedValue({ agentDir: "/tmp", wrote: false }),
|
||||
ensureMoltbotModelsJson: vi.fn().mockResolvedValue({ agentDir: "/tmp", wrote: false }),
|
||||
}));
|
||||
|
||||
vi.mock("./agent-paths.js", () => ({
|
||||
resolveClawdbotAgentDir: () => "/tmp/clawdbot",
|
||||
resolveMoltbotAgentDir: () => "/tmp/moltbot",
|
||||
}));
|
||||
|
||||
describe("loadModelCatalog", () => {
|
||||
@@ -43,7 +43,7 @@ describe("loadModelCatalog", () => {
|
||||
} as unknown as PiSdkModule;
|
||||
});
|
||||
|
||||
const cfg = {} as ClawdbotConfig;
|
||||
const cfg = {} as MoltbotConfig;
|
||||
const first = await loadModelCatalog({ config: cfg });
|
||||
expect(first).toEqual([]);
|
||||
|
||||
@@ -75,7 +75,7 @@ describe("loadModelCatalog", () => {
|
||||
}) as unknown as PiSdkModule,
|
||||
);
|
||||
|
||||
const result = await loadModelCatalog({ config: {} as ClawdbotConfig });
|
||||
const result = await loadModelCatalog({ config: {} as MoltbotConfig });
|
||||
expect(result).toEqual([{ id: "gpt-4.1", name: "GPT-4.1", provider: "openai" }]);
|
||||
expect(warnSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type ClawdbotConfig, loadConfig } from "../config/config.js";
|
||||
import { resolveClawdbotAgentDir } from "./agent-paths.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import { type MoltbotConfig, loadConfig } from "../config/config.js";
|
||||
import { resolveMoltbotAgentDir } from "./agent-paths.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
|
||||
export type ModelCatalogEntry = {
|
||||
id: string;
|
||||
@@ -39,7 +39,7 @@ export function __setModelCatalogImportForTest(loader?: () => Promise<PiSdkModul
|
||||
}
|
||||
|
||||
export async function loadModelCatalog(params?: {
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
useCache?: boolean;
|
||||
}): Promise<ModelCatalogEntry[]> {
|
||||
if (params?.useCache === false) {
|
||||
@@ -57,13 +57,13 @@ export async function loadModelCatalog(params?: {
|
||||
});
|
||||
try {
|
||||
const cfg = params?.config ?? loadConfig();
|
||||
await ensureClawdbotModelsJson(cfg);
|
||||
await ensureMoltbotModelsJson(cfg);
|
||||
// IMPORTANT: keep the dynamic import *inside* the try/catch.
|
||||
// If this fails once (e.g. during a pnpm install that temporarily swaps node_modules),
|
||||
// we must not poison the cache with a rejected promise (otherwise all channel handlers
|
||||
// will keep failing until restart).
|
||||
const piSdk = await importPiSdk();
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
const authStorage = piSdk.discoverAuthStorage(agentDir);
|
||||
const registry = piSdk.discoverModels(authStorage, agentDir) as
|
||||
| {
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import type { AuthProfileStore } from "./auth-profiles.js";
|
||||
import { saveAuthProfileStore } from "./auth-profiles.js";
|
||||
import { AUTH_STORE_VERSION } from "./auth-profiles/constants.js";
|
||||
import { runWithModelFallback } from "./model-fallback.js";
|
||||
|
||||
function makeCfg(overrides: Partial<ClawdbotConfig> = {}): ClawdbotConfig {
|
||||
function makeCfg(overrides: Partial<MoltbotConfig> = {}): MoltbotConfig {
|
||||
return {
|
||||
agents: {
|
||||
defaults: {
|
||||
@@ -14,7 +21,7 @@ function makeCfg(overrides: Partial<ClawdbotConfig> = {}): ClawdbotConfig {
|
||||
},
|
||||
},
|
||||
...overrides,
|
||||
} as ClawdbotConfig;
|
||||
} as MoltbotConfig;
|
||||
}
|
||||
|
||||
describe("runWithModelFallback", () => {
|
||||
@@ -101,7 +108,7 @@ describe("runWithModelFallback", () => {
|
||||
const cfg = makeCfg();
|
||||
const run = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('No credentials found for profile "anthropic:claude-cli".'))
|
||||
.mockRejectedValueOnce(new Error('No credentials found for profile "anthropic:default".'))
|
||||
.mockResolvedValueOnce("ok");
|
||||
|
||||
const result = await runWithModelFallback({
|
||||
@@ -117,6 +124,122 @@ describe("runWithModelFallback", () => {
|
||||
expect(run.mock.calls[1]?.[1]).toBe("claude-haiku-3-5");
|
||||
});
|
||||
|
||||
it("skips providers when all profiles are in cooldown", async () => {
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
const provider = `cooldown-test-${crypto.randomUUID()}`;
|
||||
const profileId = `${provider}:default`;
|
||||
|
||||
const store: AuthProfileStore = {
|
||||
version: AUTH_STORE_VERSION,
|
||||
profiles: {
|
||||
[profileId]: {
|
||||
type: "api_key",
|
||||
provider,
|
||||
key: "test-key",
|
||||
},
|
||||
},
|
||||
usageStats: {
|
||||
[profileId]: {
|
||||
cooldownUntil: Date.now() + 60_000,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
saveAuthProfileStore(store, tempDir);
|
||||
|
||||
const cfg = makeCfg({
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: `${provider}/m1`,
|
||||
fallbacks: ["fallback/ok-model"],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const run = vi.fn().mockImplementation(async (providerId, modelId) => {
|
||||
if (providerId === "fallback") return "ok";
|
||||
throw new Error(`unexpected provider: ${providerId}/${modelId}`);
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await runWithModelFallback({
|
||||
cfg,
|
||||
provider,
|
||||
model: "m1",
|
||||
agentDir: tempDir,
|
||||
run,
|
||||
});
|
||||
|
||||
expect(result.result).toBe("ok");
|
||||
expect(run.mock.calls).toEqual([["fallback", "ok-model"]]);
|
||||
expect(result.attempts[0]?.reason).toBe("rate_limit");
|
||||
} finally {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not skip when any profile is available", async () => {
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "moltbot-auth-"));
|
||||
const provider = `cooldown-mixed-${crypto.randomUUID()}`;
|
||||
const profileA = `${provider}:a`;
|
||||
const profileB = `${provider}:b`;
|
||||
|
||||
const store: AuthProfileStore = {
|
||||
version: AUTH_STORE_VERSION,
|
||||
profiles: {
|
||||
[profileA]: {
|
||||
type: "api_key",
|
||||
provider,
|
||||
key: "key-a",
|
||||
},
|
||||
[profileB]: {
|
||||
type: "api_key",
|
||||
provider,
|
||||
key: "key-b",
|
||||
},
|
||||
},
|
||||
usageStats: {
|
||||
[profileA]: {
|
||||
cooldownUntil: Date.now() + 60_000,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
saveAuthProfileStore(store, tempDir);
|
||||
|
||||
const cfg = makeCfg({
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: `${provider}/m1`,
|
||||
fallbacks: ["fallback/ok-model"],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const run = vi.fn().mockImplementation(async (providerId) => {
|
||||
if (providerId === provider) return "ok";
|
||||
return "unexpected";
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await runWithModelFallback({
|
||||
cfg,
|
||||
provider,
|
||||
model: "m1",
|
||||
agentDir: tempDir,
|
||||
run,
|
||||
});
|
||||
|
||||
expect(result.result).toBe("ok");
|
||||
expect(run.mock.calls).toEqual([[provider, "m1"]]);
|
||||
expect(result.attempts).toEqual([]);
|
||||
} finally {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not append configured primary when fallbacksOverride is set", async () => {
|
||||
const cfg = makeCfg({
|
||||
agents: {
|
||||
@@ -156,7 +279,7 @@ describe("runWithModelFallback", () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
} as ClawdbotConfig;
|
||||
} as MoltbotConfig;
|
||||
|
||||
const calls: Array<{ provider: string; model: string }> = [];
|
||||
|
||||
@@ -193,7 +316,7 @@ describe("runWithModelFallback", () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
} as ClawdbotConfig;
|
||||
} as MoltbotConfig;
|
||||
|
||||
const calls: Array<{ provider: string; model: string }> = [];
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "./defaults.js";
|
||||
import {
|
||||
coerceToFailoverError,
|
||||
@@ -14,6 +14,11 @@ import {
|
||||
resolveModelRefFromString,
|
||||
} from "./model-selection.js";
|
||||
import type { FailoverReason } from "./pi-embedded-helpers.js";
|
||||
import {
|
||||
ensureAuthProfileStore,
|
||||
isProfileInCooldown,
|
||||
resolveAuthProfileOrder,
|
||||
} from "./auth-profiles.js";
|
||||
|
||||
type ModelCandidate = {
|
||||
provider: string;
|
||||
@@ -43,7 +48,7 @@ function shouldRethrowAbort(err: unknown): boolean {
|
||||
}
|
||||
|
||||
function buildAllowedModelKeys(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
cfg: MoltbotConfig | undefined,
|
||||
defaultProvider: string,
|
||||
): Set<string> | null {
|
||||
const rawAllowlist = (() => {
|
||||
@@ -61,7 +66,7 @@ function buildAllowedModelKeys(
|
||||
}
|
||||
|
||||
function resolveImageFallbackCandidates(params: {
|
||||
cfg: ClawdbotConfig | undefined;
|
||||
cfg: MoltbotConfig | undefined;
|
||||
defaultProvider: string;
|
||||
modelOverride?: string;
|
||||
}): ModelCandidate[] {
|
||||
@@ -122,7 +127,7 @@ function resolveImageFallbackCandidates(params: {
|
||||
}
|
||||
|
||||
function resolveFallbackCandidates(params: {
|
||||
cfg: ClawdbotConfig | undefined;
|
||||
cfg: MoltbotConfig | undefined;
|
||||
provider: string;
|
||||
model: string;
|
||||
/** Optional explicit fallbacks list; when provided (even empty), replaces agents.defaults.model.fallbacks. */
|
||||
@@ -186,9 +191,10 @@ function resolveFallbackCandidates(params: {
|
||||
}
|
||||
|
||||
export async function runWithModelFallback<T>(params: {
|
||||
cfg: ClawdbotConfig | undefined;
|
||||
cfg: MoltbotConfig | undefined;
|
||||
provider: string;
|
||||
model: string;
|
||||
agentDir?: string;
|
||||
/** Optional explicit fallbacks list; when provided (even empty), replaces agents.defaults.model.fallbacks. */
|
||||
fallbacksOverride?: string[];
|
||||
run: (provider: string, model: string) => Promise<T>;
|
||||
@@ -211,11 +217,33 @@ export async function runWithModelFallback<T>(params: {
|
||||
model: params.model,
|
||||
fallbacksOverride: params.fallbacksOverride,
|
||||
});
|
||||
const authStore = params.cfg
|
||||
? ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false })
|
||||
: null;
|
||||
const attempts: FallbackAttempt[] = [];
|
||||
let lastError: unknown;
|
||||
|
||||
for (let i = 0; i < candidates.length; i += 1) {
|
||||
const candidate = candidates[i] as ModelCandidate;
|
||||
if (authStore) {
|
||||
const profileIds = resolveAuthProfileOrder({
|
||||
cfg: params.cfg,
|
||||
store: authStore,
|
||||
provider: candidate.provider,
|
||||
});
|
||||
const isAnyProfileAvailable = profileIds.some((id) => !isProfileInCooldown(authStore, id));
|
||||
|
||||
if (profileIds.length > 0 && !isAnyProfileAvailable) {
|
||||
// All profiles for this provider are in cooldown; skip without attempting
|
||||
attempts.push({
|
||||
provider: candidate.provider,
|
||||
model: candidate.model,
|
||||
error: `Provider ${candidate.provider} is in cooldown (all profiles unavailable)`,
|
||||
reason: "rate_limit",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const result = await params.run(candidate.provider, candidate.model);
|
||||
return {
|
||||
@@ -271,7 +299,7 @@ export async function runWithModelFallback<T>(params: {
|
||||
}
|
||||
|
||||
export async function runWithImageModelFallback<T>(params: {
|
||||
cfg: ClawdbotConfig | undefined;
|
||||
cfg: MoltbotConfig | undefined;
|
||||
modelOverride?: string;
|
||||
run: (provider: string, model: string) => Promise<T>;
|
||||
onError?: (attempt: {
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
normalizeProviderId,
|
||||
modelKey,
|
||||
} from "./model-selection.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
describe("model-selection", () => {
|
||||
describe("normalizeProviderId", () => {
|
||||
@@ -49,7 +49,7 @@ describe("model-selection", () => {
|
||||
|
||||
describe("buildModelAliasIndex", () => {
|
||||
it("should build alias index from config", () => {
|
||||
const cfg: Partial<ClawdbotConfig> = {
|
||||
const cfg: Partial<MoltbotConfig> = {
|
||||
agents: {
|
||||
defaults: {
|
||||
models: {
|
||||
@@ -61,7 +61,7 @@ describe("model-selection", () => {
|
||||
};
|
||||
|
||||
const index = buildModelAliasIndex({
|
||||
cfg: cfg as ClawdbotConfig,
|
||||
cfg: cfg as MoltbotConfig,
|
||||
defaultProvider: "anthropic",
|
||||
});
|
||||
|
||||
@@ -105,7 +105,7 @@ describe("model-selection", () => {
|
||||
describe("resolveConfiguredModelRef", () => {
|
||||
it("should fall back to anthropic and warn if provider is missing for non-alias", () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const cfg: Partial<ClawdbotConfig> = {
|
||||
const cfg: Partial<MoltbotConfig> = {
|
||||
agents: {
|
||||
defaults: {
|
||||
model: "claude-3-5-sonnet",
|
||||
@@ -114,7 +114,7 @@ describe("model-selection", () => {
|
||||
};
|
||||
|
||||
const result = resolveConfiguredModelRef({
|
||||
cfg: cfg as ClawdbotConfig,
|
||||
cfg: cfg as MoltbotConfig,
|
||||
defaultProvider: "google",
|
||||
defaultModel: "gemini-pro",
|
||||
});
|
||||
@@ -127,9 +127,9 @@ describe("model-selection", () => {
|
||||
});
|
||||
|
||||
it("should use default provider/model if config is empty", () => {
|
||||
const cfg: Partial<ClawdbotConfig> = {};
|
||||
const cfg: Partial<MoltbotConfig> = {};
|
||||
const result = resolveConfiguredModelRef({
|
||||
cfg: cfg as ClawdbotConfig,
|
||||
cfg: cfg as MoltbotConfig,
|
||||
defaultProvider: "openai",
|
||||
defaultModel: "gpt-4",
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import type { ModelCatalogEntry } from "./model-catalog.js";
|
||||
import { normalizeGoogleModelId } from "./models-config.providers.js";
|
||||
import { resolveAgentModelPrimary } from "./agent-scope.js";
|
||||
@@ -32,7 +32,7 @@ export function normalizeProviderId(provider: string): string {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function isCliProvider(provider: string, cfg?: ClawdbotConfig): boolean {
|
||||
export function isCliProvider(provider: string, cfg?: MoltbotConfig): boolean {
|
||||
const normalized = normalizeProviderId(provider);
|
||||
if (normalized === "claude-cli") return true;
|
||||
if (normalized === "codex-cli") return true;
|
||||
@@ -73,7 +73,7 @@ export function parseModelRef(raw: string, defaultProvider: string): ModelRef |
|
||||
}
|
||||
|
||||
export function buildModelAliasIndex(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
defaultProvider: string;
|
||||
}): ModelAliasIndex {
|
||||
const byAlias = new Map<string, { alias: string; ref: ModelRef }>();
|
||||
@@ -116,7 +116,7 @@ export function resolveModelRefFromString(params: {
|
||||
}
|
||||
|
||||
export function resolveConfiguredModelRef(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
defaultProvider: string;
|
||||
defaultModel: string;
|
||||
}): ModelRef {
|
||||
@@ -138,7 +138,7 @@ export function resolveConfiguredModelRef(params: {
|
||||
|
||||
// Default to anthropic if no provider is specified, but warn as this is deprecated.
|
||||
console.warn(
|
||||
`[clawdbot] Model "${trimmed}" specified without provider. Falling back to "anthropic/${trimmed}". Please use "anthropic/${trimmed}" in your config.`,
|
||||
`[moltbot] Model "${trimmed}" specified without provider. Falling back to "anthropic/${trimmed}". Please use "anthropic/${trimmed}" in your config.`,
|
||||
);
|
||||
return { provider: "anthropic", model: trimmed };
|
||||
}
|
||||
@@ -154,7 +154,7 @@ export function resolveConfiguredModelRef(params: {
|
||||
}
|
||||
|
||||
export function resolveDefaultModelForAgent(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
agentId?: string;
|
||||
}): ModelRef {
|
||||
const agentModelOverride = params.agentId
|
||||
@@ -186,7 +186,7 @@ export function resolveDefaultModelForAgent(params: {
|
||||
}
|
||||
|
||||
export function buildAllowedModelSet(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
catalog: ModelCatalogEntry[];
|
||||
defaultProvider: string;
|
||||
defaultModel?: string;
|
||||
@@ -262,7 +262,7 @@ export type ModelRefStatus = {
|
||||
};
|
||||
|
||||
export function getModelRefStatus(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
catalog: ModelCatalogEntry[];
|
||||
ref: ModelRef;
|
||||
defaultProvider: string;
|
||||
@@ -284,7 +284,7 @@ export function getModelRefStatus(params: {
|
||||
}
|
||||
|
||||
export function resolveAllowedModelRef(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
catalog: ModelCatalogEntry[];
|
||||
raw: string;
|
||||
defaultProvider: string;
|
||||
@@ -323,7 +323,7 @@ export function resolveAllowedModelRef(params: {
|
||||
}
|
||||
|
||||
export function resolveThinkingDefault(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
provider: string;
|
||||
model: string;
|
||||
catalog?: ModelCatalogEntry[];
|
||||
@@ -342,7 +342,7 @@ export function resolveThinkingDefault(params: {
|
||||
* Returns null if hooks.gmail.model is not set.
|
||||
*/
|
||||
export function resolveHooksGmailModel(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
cfg: MoltbotConfig;
|
||||
defaultProvider: string;
|
||||
}): ModelRef | null {
|
||||
const hooksModel = params.cfg.hooks?.gmail?.model;
|
||||
|
||||
@@ -2,13 +2,13 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
|
||||
return withTempHomeBase(fn, { prefix: "clawdbot-models-" });
|
||||
return withTempHomeBase(fn, { prefix: "moltbot-models-" });
|
||||
}
|
||||
|
||||
const _MODELS_CONFIG: ClawdbotConfig = {
|
||||
const _MODELS_CONFIG: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
"custom-proxy": {
|
||||
@@ -61,10 +61,10 @@ describe("models-config", () => {
|
||||
}),
|
||||
}));
|
||||
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
|
||||
const agentDir = path.join(home, "agent-default-base-url");
|
||||
await ensureClawdbotModelsJson({ models: { providers: {} } }, agentDir);
|
||||
await ensureMoltbotModelsJson({ models: { providers: {} } }, agentDir);
|
||||
|
||||
const raw = await fs.readFile(path.join(agentDir, "models.json"), "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
@@ -102,9 +102,9 @@ describe("models-config", () => {
|
||||
resolveCopilotApiToken,
|
||||
}));
|
||||
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
|
||||
await ensureClawdbotModelsJson({ models: { providers: {} } });
|
||||
await ensureMoltbotModelsJson({ models: { providers: {} } });
|
||||
|
||||
expect(resolveCopilotApiToken).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ githubToken: "copilot-token" }),
|
||||
|
||||
@@ -2,13 +2,13 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
|
||||
return withTempHomeBase(fn, { prefix: "clawdbot-models-" });
|
||||
return withTempHomeBase(fn, { prefix: "moltbot-models-" });
|
||||
}
|
||||
|
||||
const _MODELS_CONFIG: ClawdbotConfig = {
|
||||
const _MODELS_CONFIG: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
"custom-proxy": {
|
||||
@@ -56,12 +56,12 @@ describe("models-config", () => {
|
||||
resolveCopilotApiToken: vi.fn().mockRejectedValue(new Error("boom")),
|
||||
}));
|
||||
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
await ensureClawdbotModelsJson({ models: { providers: {} } });
|
||||
await ensureMoltbotModelsJson({ models: { providers: {} } });
|
||||
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
const raw = await fs.readFile(path.join(agentDir, "models.json"), "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<string, { baseUrl?: string }>;
|
||||
@@ -115,9 +115,9 @@ describe("models-config", () => {
|
||||
}),
|
||||
}));
|
||||
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
|
||||
await ensureClawdbotModelsJson({ models: { providers: {} } }, agentDir);
|
||||
await ensureMoltbotModelsJson({ models: { providers: {} } }, agentDir);
|
||||
|
||||
const raw = await fs.readFile(path.join(agentDir, "models.json"), "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
|
||||
@@ -2,13 +2,13 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
|
||||
return withTempHomeBase(fn, { prefix: "clawdbot-models-" });
|
||||
return withTempHomeBase(fn, { prefix: "moltbot-models-" });
|
||||
}
|
||||
|
||||
const MODELS_CONFIG: ClawdbotConfig = {
|
||||
const MODELS_CONFIG: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
"custom-proxy": {
|
||||
@@ -49,10 +49,10 @@ describe("models-config", () => {
|
||||
const prevKey = process.env.MINIMAX_API_KEY;
|
||||
process.env.MINIMAX_API_KEY = "sk-minimax-test";
|
||||
try {
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
minimax: {
|
||||
@@ -74,9 +74,9 @@ describe("models-config", () => {
|
||||
},
|
||||
};
|
||||
|
||||
await ensureClawdbotModelsJson(cfg);
|
||||
await ensureMoltbotModelsJson(cfg);
|
||||
|
||||
const modelPath = path.join(resolveClawdbotAgentDir(), "models.json");
|
||||
const modelPath = path.join(resolveMoltbotAgentDir(), "models.json");
|
||||
const raw = await fs.readFile(modelPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<string, { apiKey?: string; models?: Array<{ id: string }> }>;
|
||||
@@ -93,10 +93,10 @@ describe("models-config", () => {
|
||||
it("merges providers by default", async () => {
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
await fs.mkdir(agentDir, { recursive: true });
|
||||
await fs.writeFile(
|
||||
path.join(agentDir, "models.json"),
|
||||
@@ -128,7 +128,7 @@ describe("models-config", () => {
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await ensureClawdbotModelsJson(MODELS_CONFIG);
|
||||
await ensureMoltbotModelsJson(MODELS_CONFIG);
|
||||
|
||||
const raw = await fs.readFile(path.join(agentDir, "models.json"), "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
|
||||
@@ -2,13 +2,13 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
|
||||
return withTempHomeBase(fn, { prefix: "clawdbot-models-" });
|
||||
return withTempHomeBase(fn, { prefix: "moltbot-models-" });
|
||||
}
|
||||
|
||||
const _MODELS_CONFIG: ClawdbotConfig = {
|
||||
const _MODELS_CONFIG: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
"custom-proxy": {
|
||||
@@ -46,10 +46,10 @@ describe("models-config", () => {
|
||||
it("normalizes gemini 3 ids to preview for google providers", async () => {
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
google: {
|
||||
@@ -83,9 +83,9 @@ describe("models-config", () => {
|
||||
},
|
||||
};
|
||||
|
||||
await ensureClawdbotModelsJson(cfg);
|
||||
await ensureMoltbotModelsJson(cfg);
|
||||
|
||||
const modelPath = path.join(resolveClawdbotAgentDir(), "models.json");
|
||||
const modelPath = path.join(resolveMoltbotAgentDir(), "models.json");
|
||||
const raw = await fs.readFile(modelPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<string, { models: Array<{ id: string }> }>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import type { ModelDefinitionConfig } from "../config/types.models.js";
|
||||
import {
|
||||
DEFAULT_COPILOT_API_BASE_URL,
|
||||
@@ -14,10 +14,10 @@ import {
|
||||
} from "./synthetic-models.js";
|
||||
import { discoverVeniceModels, VENICE_BASE_URL } from "./venice-models.js";
|
||||
|
||||
type ModelsConfig = NonNullable<ClawdbotConfig["models"]>;
|
||||
type ModelsConfig = NonNullable<MoltbotConfig["models"]>;
|
||||
export type ProviderConfig = NonNullable<ModelsConfig["providers"]>[string];
|
||||
|
||||
const MINIMAX_API_BASE_URL = "https://api.minimax.io/anthropic";
|
||||
const MINIMAX_API_BASE_URL = "https://api.minimax.chat/v1";
|
||||
const MINIMAX_DEFAULT_MODEL_ID = "MiniMax-M2.1";
|
||||
const MINIMAX_DEFAULT_VISION_MODEL_ID = "MiniMax-VL-01";
|
||||
const MINIMAX_DEFAULT_CONTEXT_WINDOW = 200000;
|
||||
@@ -31,7 +31,7 @@ const MINIMAX_API_COST = {
|
||||
};
|
||||
|
||||
const MOONSHOT_BASE_URL = "https://api.moonshot.ai/v1";
|
||||
const MOONSHOT_DEFAULT_MODEL_ID = "kimi-k2-0905-preview";
|
||||
const MOONSHOT_DEFAULT_MODEL_ID = "kimi-k2.5";
|
||||
const MOONSHOT_DEFAULT_CONTEXT_WINDOW = 256000;
|
||||
const MOONSHOT_DEFAULT_MAX_TOKENS = 8192;
|
||||
const MOONSHOT_DEFAULT_COST = {
|
||||
@@ -244,7 +244,7 @@ export function normalizeProviders(params: {
|
||||
function buildMinimaxProvider(): ProviderConfig {
|
||||
return {
|
||||
baseUrl: MINIMAX_API_BASE_URL,
|
||||
api: "anthropic-messages",
|
||||
api: "openai-completions",
|
||||
models: [
|
||||
{
|
||||
id: MINIMAX_DEFAULT_MODEL_ID,
|
||||
@@ -275,7 +275,7 @@ function buildMoonshotProvider(): ProviderConfig {
|
||||
models: [
|
||||
{
|
||||
id: MOONSHOT_DEFAULT_MODEL_ID,
|
||||
name: "Kimi K2 0905 Preview",
|
||||
name: "Kimi K2.5",
|
||||
reasoning: false,
|
||||
input: ["text"],
|
||||
cost: MOONSHOT_DEFAULT_COST,
|
||||
@@ -459,15 +459,15 @@ export async function resolveImplicitCopilotProvider(params: {
|
||||
|
||||
// pi-coding-agent's ModelRegistry marks a model "available" only if its
|
||||
// `AuthStorage` has auth configured for that provider (via auth.json/env/etc).
|
||||
// Our Copilot auth lives in Clawdbot's auth-profiles store instead, so we also
|
||||
// Our Copilot auth lives in Moltbot's auth-profiles store instead, so we also
|
||||
// write a runtime-only auth.json entry for pi-coding-agent to pick up.
|
||||
//
|
||||
// This is safe because it's (1) within Clawdbot's agent dir, (2) contains the
|
||||
// This is safe because it's (1) within Moltbot's agent dir, (2) contains the
|
||||
// GitHub token (not the exchanged Copilot token), and (3) matches existing
|
||||
// patterns for OAuth-like providers in pi-coding-agent.
|
||||
// Note: we deliberately do not write pi-coding-agent's `auth.json` here.
|
||||
// Clawdbot uses its own auth store and exchanges tokens at runtime.
|
||||
// `models list` uses Clawdbot's auth heuristics for availability.
|
||||
// Moltbot uses its own auth store and exchanges tokens at runtime.
|
||||
// `models list` uses Moltbot's auth heuristics for availability.
|
||||
|
||||
// We intentionally do NOT define custom models for Copilot in models.json.
|
||||
// pi-coding-agent treats providers with models as replacements requiring apiKey.
|
||||
@@ -480,7 +480,7 @@ export async function resolveImplicitCopilotProvider(params: {
|
||||
|
||||
export async function resolveImplicitBedrockProvider(params: {
|
||||
agentDir: string;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}): Promise<ProviderConfig | null> {
|
||||
const env = params.env ?? process.env;
|
||||
|
||||
@@ -2,13 +2,13 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
|
||||
return withTempHomeBase(fn, { prefix: "clawdbot-models-" });
|
||||
return withTempHomeBase(fn, { prefix: "moltbot-models-" });
|
||||
}
|
||||
|
||||
const MODELS_CONFIG: ClawdbotConfig = {
|
||||
const MODELS_CONFIG: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
"custom-proxy": {
|
||||
@@ -64,10 +64,10 @@ describe("models-config", () => {
|
||||
|
||||
try {
|
||||
vi.resetModules();
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
|
||||
const agentDir = path.join(home, "agent-empty");
|
||||
const result = await ensureClawdbotModelsJson(
|
||||
const result = await ensureMoltbotModelsJson(
|
||||
{
|
||||
models: { providers: {} },
|
||||
},
|
||||
@@ -99,12 +99,12 @@ describe("models-config", () => {
|
||||
it("writes models.json for configured providers", async () => {
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
await ensureClawdbotModelsJson(MODELS_CONFIG);
|
||||
await ensureMoltbotModelsJson(MODELS_CONFIG);
|
||||
|
||||
const modelPath = path.join(resolveClawdbotAgentDir(), "models.json");
|
||||
const modelPath = path.join(resolveMoltbotAgentDir(), "models.json");
|
||||
const raw = await fs.readFile(modelPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<string, { baseUrl?: string }>;
|
||||
@@ -119,12 +119,12 @@ describe("models-config", () => {
|
||||
const prevKey = process.env.MINIMAX_API_KEY;
|
||||
process.env.MINIMAX_API_KEY = "sk-minimax-test";
|
||||
try {
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
await ensureClawdbotModelsJson({});
|
||||
await ensureMoltbotModelsJson({});
|
||||
|
||||
const modelPath = path.join(resolveClawdbotAgentDir(), "models.json");
|
||||
const modelPath = path.join(resolveMoltbotAgentDir(), "models.json");
|
||||
const raw = await fs.readFile(modelPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<
|
||||
@@ -136,7 +136,7 @@ describe("models-config", () => {
|
||||
}
|
||||
>;
|
||||
};
|
||||
expect(parsed.providers.minimax?.baseUrl).toBe("https://api.minimax.io/anthropic");
|
||||
expect(parsed.providers.minimax?.baseUrl).toBe("https://api.minimax.chat/v1");
|
||||
expect(parsed.providers.minimax?.apiKey).toBe("MINIMAX_API_KEY");
|
||||
const ids = parsed.providers.minimax?.models?.map((model) => model.id);
|
||||
expect(ids).toContain("MiniMax-M2.1");
|
||||
@@ -153,12 +153,12 @@ describe("models-config", () => {
|
||||
const prevKey = process.env.SYNTHETIC_API_KEY;
|
||||
process.env.SYNTHETIC_API_KEY = "sk-synthetic-test";
|
||||
try {
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
await ensureClawdbotModelsJson({});
|
||||
await ensureMoltbotModelsJson({});
|
||||
|
||||
const modelPath = path.join(resolveClawdbotAgentDir(), "models.json");
|
||||
const modelPath = path.join(resolveMoltbotAgentDir(), "models.json");
|
||||
const raw = await fs.readFile(modelPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { type ClawdbotConfig, loadConfig } from "../config/config.js";
|
||||
import { resolveClawdbotAgentDir } from "./agent-paths.js";
|
||||
import { type MoltbotConfig, loadConfig } from "../config/config.js";
|
||||
import { resolveMoltbotAgentDir } from "./agent-paths.js";
|
||||
import {
|
||||
normalizeProviders,
|
||||
type ProviderConfig,
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
resolveImplicitProviders,
|
||||
} from "./models-config.providers.js";
|
||||
|
||||
type ModelsConfig = NonNullable<ClawdbotConfig["models"]>;
|
||||
type ModelsConfig = NonNullable<MoltbotConfig["models"]>;
|
||||
|
||||
const DEFAULT_MODE: NonNullable<ModelsConfig["mode"]> = "merge";
|
||||
|
||||
@@ -72,12 +72,12 @@ async function readJson(pathname: string): Promise<unknown> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureClawdbotModelsJson(
|
||||
config?: ClawdbotConfig,
|
||||
export async function ensureMoltbotModelsJson(
|
||||
config?: MoltbotConfig,
|
||||
agentDirOverride?: string,
|
||||
): Promise<{ agentDir: string; wrote: boolean }> {
|
||||
const cfg = config ?? loadConfig();
|
||||
const agentDir = agentDirOverride?.trim() ? agentDirOverride.trim() : resolveClawdbotAgentDir();
|
||||
const agentDir = agentDirOverride?.trim() ? agentDirOverride.trim() : resolveMoltbotAgentDir();
|
||||
|
||||
const explicitProviders = (cfg.models?.providers ?? {}) as Record<string, ProviderConfig>;
|
||||
const implicitProviders = await resolveImplicitProviders({ agentDir });
|
||||
|
||||
@@ -2,13 +2,13 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
|
||||
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
|
||||
return withTempHomeBase(fn, { prefix: "clawdbot-models-" });
|
||||
return withTempHomeBase(fn, { prefix: "moltbot-models-" });
|
||||
}
|
||||
|
||||
const _MODELS_CONFIG: ClawdbotConfig = {
|
||||
const _MODELS_CONFIG: MoltbotConfig = {
|
||||
models: {
|
||||
providers: {
|
||||
"custom-proxy": {
|
||||
@@ -92,9 +92,9 @@ describe("models-config", () => {
|
||||
resolveCopilotApiToken,
|
||||
}));
|
||||
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
|
||||
await ensureClawdbotModelsJson({ models: { providers: {} } }, agentDir);
|
||||
await ensureMoltbotModelsJson({ models: { providers: {} } }, agentDir);
|
||||
|
||||
expect(resolveCopilotApiToken).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ githubToken: "alpha-token" }),
|
||||
@@ -127,10 +127,10 @@ describe("models-config", () => {
|
||||
}),
|
||||
}));
|
||||
|
||||
const { ensureClawdbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveClawdbotAgentDir } = await import("./agent-paths.js");
|
||||
const { ensureMoltbotModelsJson } = await import("./models-config.js");
|
||||
const { resolveMoltbotAgentDir } = await import("./agent-paths.js");
|
||||
|
||||
await ensureClawdbotModelsJson({
|
||||
await ensureMoltbotModelsJson({
|
||||
models: {
|
||||
providers: {
|
||||
"github-copilot": {
|
||||
@@ -142,7 +142,7 @@ describe("models-config", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
const raw = await fs.readFile(path.join(agentDir, "models.json"), "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
providers: Record<string, { baseUrl?: string }>;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Type } from "@sinclair/typebox";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import { isTruthyEnvValue } from "../infra/env.js";
|
||||
import { resolveClawdbotAgentDir } from "./agent-paths.js";
|
||||
import { resolveMoltbotAgentDir } from "./agent-paths.js";
|
||||
import {
|
||||
collectAnthropicApiKeys,
|
||||
isAnthropicBillingError,
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from "./live-auth-keys.js";
|
||||
import { isModernModelRef } from "./live-model-filter.js";
|
||||
import { getApiKeyForModel, requireApiKey } from "./model-auth.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
import { isRateLimitErrorMessage } from "./pi-embedded-helpers/errors.js";
|
||||
|
||||
const LIVE = isTruthyEnvValue(process.env.LIVE) || isTruthyEnvValue(process.env.CLAWDBOT_LIVE_TEST);
|
||||
@@ -151,7 +151,7 @@ describeLive("live models (profile keys)", () => {
|
||||
"completes across selected models",
|
||||
async () => {
|
||||
const cfg = loadConfig();
|
||||
await ensureClawdbotModelsJson(cfg);
|
||||
await ensureMoltbotModelsJson(cfg);
|
||||
if (!DIRECT_ENABLED) {
|
||||
logProgress(
|
||||
"[live-models] skipping (set CLAWDBOT_LIVE_MODELS=modern|all|<list>; all=modern)",
|
||||
@@ -164,7 +164,7 @@ describeLive("live models (profile keys)", () => {
|
||||
logProgress(`[live-models] anthropic keys loaded: ${anthropicKeys.length}`);
|
||||
}
|
||||
|
||||
const agentDir = resolveClawdbotAgentDir();
|
||||
const agentDir = resolveMoltbotAgentDir();
|
||||
const authStorage = discoverAuthStorage(agentDir);
|
||||
const modelRegistry = discoverModels(authStorage, agentDir);
|
||||
const models = modelRegistry.getAll() as Array<Model<Api>>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { resolvePluginTools } from "../plugins/tools.js";
|
||||
import type { GatewayMessageChannel } from "../utils/message-channel.js";
|
||||
import { resolveSessionAgentId } from "./agent-scope.js";
|
||||
@@ -19,12 +19,9 @@ import { createSessionsSpawnTool } from "./tools/sessions-spawn-tool.js";
|
||||
import { createWebFetchTool, createWebSearchTool } from "./tools/web-tools.js";
|
||||
import { createTtsTool } from "./tools/tts-tool.js";
|
||||
|
||||
export function createClawdbotTools(options?: {
|
||||
browserControlUrl?: string;
|
||||
export function createMoltbotTools(options?: {
|
||||
sandboxBrowserBridgeUrl?: string;
|
||||
allowHostBrowserControl?: boolean;
|
||||
allowedControlUrls?: string[];
|
||||
allowedControlHosts?: string[];
|
||||
allowedControlPorts?: number[];
|
||||
agentSessionKey?: string;
|
||||
agentChannel?: GatewayMessageChannel;
|
||||
agentAccountId?: string;
|
||||
@@ -42,7 +39,7 @@ export function createClawdbotTools(options?: {
|
||||
sandboxRoot?: string;
|
||||
workspaceDir?: string;
|
||||
sandboxed?: boolean;
|
||||
config?: ClawdbotConfig;
|
||||
config?: MoltbotConfig;
|
||||
pluginToolAllowlist?: string[];
|
||||
/** Current channel ID for auto-threading (Slack). */
|
||||
currentChannelId?: string;
|
||||
@@ -75,11 +72,8 @@ export function createClawdbotTools(options?: {
|
||||
});
|
||||
const tools: AnyAgentTool[] = [
|
||||
createBrowserTool({
|
||||
defaultControlUrl: options?.browserControlUrl,
|
||||
sandboxBridgeUrl: options?.sandboxBrowserBridgeUrl,
|
||||
allowHostControl: options?.allowHostBrowserControl,
|
||||
allowedControlUrls: options?.allowedControlUrls,
|
||||
allowedControlHosts: options?.allowedControlHosts,
|
||||
allowedControlPorts: options?.allowedControlPorts,
|
||||
}),
|
||||
createCanvasTool(),
|
||||
createNodesTool({
|
||||
@@ -31,6 +31,7 @@ describe("classifyFailoverReason", () => {
|
||||
"messages.84.content.1.image.source.base64.data: At least one of the image dimensions exceed max allowed size for many-image requests: 2000 pixels",
|
||||
),
|
||||
).toBeNull();
|
||||
expect(classifyFailoverReason("image exceeds 5 MB maximum")).toBeNull();
|
||||
});
|
||||
it("classifies OpenAI usage limit errors as rate_limit", () => {
|
||||
expect(classifyFailoverReason("You have hit your ChatGPT usage limit (plus plan)")).toBe(
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseImageSizeError } from "./pi-embedded-helpers.js";
|
||||
|
||||
describe("parseImageSizeError", () => {
|
||||
it("parses max MB values from error text", () => {
|
||||
expect(parseImageSizeError("image exceeds 5 MB maximum")?.maxMb).toBe(5);
|
||||
expect(parseImageSizeError("Image exceeds 5.5 MB limit")?.maxMb).toBe(5.5);
|
||||
});
|
||||
|
||||
it("returns null for unrelated errors", () => {
|
||||
expect(parseImageSizeError("context overflow")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ const _makeFile = (overrides: Partial<WorkspaceBootstrapFile>): WorkspaceBootstr
|
||||
describe("isAuthErrorMessage", () => {
|
||||
it("matches credential validation errors", () => {
|
||||
const samples = [
|
||||
'No credentials found for profile "anthropic:claude-cli".',
|
||||
'No credentials found for profile "anthropic:default".',
|
||||
"No API key found for profile openai.",
|
||||
];
|
||||
for (const sample of samples) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { DEFAULT_BOOTSTRAP_MAX_CHARS, resolveBootstrapMaxChars } from "./pi-embedded-helpers.js";
|
||||
import { DEFAULT_AGENTS_FILENAME } from "./workspace.js";
|
||||
|
||||
@@ -17,13 +17,13 @@ describe("resolveBootstrapMaxChars", () => {
|
||||
it("uses configured value when valid", () => {
|
||||
const cfg = {
|
||||
agents: { defaults: { bootstrapMaxChars: 12345 } },
|
||||
} as ClawdbotConfig;
|
||||
} as MoltbotConfig;
|
||||
expect(resolveBootstrapMaxChars(cfg)).toBe(12345);
|
||||
});
|
||||
it("falls back when invalid", () => {
|
||||
const cfg = {
|
||||
agents: { defaults: { bootstrapMaxChars: -1 } },
|
||||
} as ClawdbotConfig;
|
||||
} as MoltbotConfig;
|
||||
expect(resolveBootstrapMaxChars(cfg)).toBe(DEFAULT_BOOTSTRAP_MAX_CHARS);
|
||||
});
|
||||
});
|
||||
@@ -23,12 +23,14 @@ export {
|
||||
isFailoverAssistantError,
|
||||
isFailoverErrorMessage,
|
||||
isImageDimensionErrorMessage,
|
||||
isImageSizeError,
|
||||
isOverloadedErrorMessage,
|
||||
isRawApiErrorPayload,
|
||||
isRateLimitAssistantError,
|
||||
isRateLimitErrorMessage,
|
||||
isTimeoutErrorMessage,
|
||||
parseImageDimensionError,
|
||||
parseImageSizeError,
|
||||
} from "./pi-embedded-helpers/errors.js";
|
||||
export { isGoogleModelApi, sanitizeGoogleTurnOrdering } from "./pi-embedded-helpers/google.js";
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import path from "node:path";
|
||||
|
||||
import type { AgentMessage } from "@mariozechner/pi-agent-core";
|
||||
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import type { WorkspaceBootstrapFile } from "../workspace.js";
|
||||
import type { EmbeddedContextFile } from "./types.js";
|
||||
|
||||
@@ -80,7 +80,7 @@ type TrimBootstrapResult = {
|
||||
originalLength: number;
|
||||
};
|
||||
|
||||
export function resolveBootstrapMaxChars(cfg?: ClawdbotConfig): number {
|
||||
export function resolveBootstrapMaxChars(cfg?: MoltbotConfig): number {
|
||||
const raw = cfg?.agents?.defaults?.bootstrapMaxChars;
|
||||
if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) {
|
||||
return Math.floor(raw);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { AssistantMessage } from "@mariozechner/pi-ai";
|
||||
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { MoltbotConfig } from "../../config/config.js";
|
||||
import { formatSandboxToolPolicyBlockedMessage } from "../sandbox.js";
|
||||
import type { FailoverReason } from "./types.js";
|
||||
|
||||
@@ -252,7 +252,7 @@ export function formatRawAssistantErrorForUi(raw?: string): string {
|
||||
|
||||
export function formatAssistantErrorText(
|
||||
msg: AssistantMessage,
|
||||
opts?: { cfg?: ClawdbotConfig; sessionKey?: string },
|
||||
opts?: { cfg?: MoltbotConfig; sessionKey?: string },
|
||||
): string | undefined {
|
||||
// Also format errors if errorMessage is present, even if stopReason isn't "error"
|
||||
const raw = (msg.errorMessage ?? "").trim();
|
||||
@@ -401,6 +401,7 @@ const ERROR_PATTERNS = {
|
||||
const IMAGE_DIMENSION_ERROR_RE =
|
||||
/image dimensions exceed max allowed size for many-image requests:\s*(\d+)\s*pixels/i;
|
||||
const IMAGE_DIMENSION_PATH_RE = /messages\.(\d+)\.content\.(\d+)\.image/i;
|
||||
const IMAGE_SIZE_ERROR_RE = /image exceeds\s*(\d+(?:\.\d+)?)\s*mb/i;
|
||||
|
||||
function matchesErrorPatterns(raw: string, patterns: readonly ErrorPattern[]): boolean {
|
||||
if (!raw) return false;
|
||||
@@ -467,6 +468,25 @@ export function isImageDimensionErrorMessage(raw: string): boolean {
|
||||
return Boolean(parseImageDimensionError(raw));
|
||||
}
|
||||
|
||||
export function parseImageSizeError(raw: string): {
|
||||
maxMb?: number;
|
||||
raw: string;
|
||||
} | null {
|
||||
if (!raw) return null;
|
||||
const lower = raw.toLowerCase();
|
||||
if (!lower.includes("image exceeds") || !lower.includes("mb")) return null;
|
||||
const match = raw.match(IMAGE_SIZE_ERROR_RE);
|
||||
return {
|
||||
maxMb: match?.[1] ? Number.parseFloat(match[1]) : undefined,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export function isImageSizeError(errorMessage?: string): boolean {
|
||||
if (!errorMessage) return false;
|
||||
return Boolean(parseImageSizeError(errorMessage));
|
||||
}
|
||||
|
||||
export function isCloudCodeAssistFormatError(raw: string): boolean {
|
||||
return !isImageDimensionErrorMessage(raw) && matchesErrorPatterns(raw, ERROR_PATTERNS.format);
|
||||
}
|
||||
@@ -478,6 +498,7 @@ export function isAuthAssistantError(msg: AssistantMessage | undefined): boolean
|
||||
|
||||
export function classifyFailoverReason(raw: string): FailoverReason | null {
|
||||
if (isImageDimensionErrorMessage(raw)) return null;
|
||||
if (isImageSizeError(raw)) return null;
|
||||
if (isRateLimitErrorMessage(raw)) return "rate_limit";
|
||||
if (isOverloadedErrorMessage(raw)) return "rate_limit";
|
||||
if (isCloudCodeAssistFormatError(raw)) return "format";
|
||||
|
||||
@@ -51,7 +51,7 @@ function hasFollowingNonThinkingBlock(
|
||||
* OpenAI Responses API can reject transcripts that contain a standalone `reasoning` item id
|
||||
* without the required following item.
|
||||
*
|
||||
* Clawdbot persists provider-specific reasoning metadata in `thinkingSignature`; if that metadata
|
||||
* Moltbot persists provider-specific reasoning metadata in `thinkingSignature`; if that metadata
|
||||
* is incomplete, drop the block to keep history usable.
|
||||
*/
|
||||
export function downgradeOpenAIReasoningBlocks(messages: AgentMessage[]): AgentMessage[] {
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Model } from "@mariozechner/pi-ai";
|
||||
import { getModel, streamSimple } from "@mariozechner/pi-ai";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isTruthyEnvValue } from "../infra/env.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { applyExtraParamsToAgent } from "./pi-embedded-runner.js";
|
||||
|
||||
const OPENAI_KEY = process.env.OPENAI_API_KEY ?? "";
|
||||
@@ -14,7 +14,7 @@ describeLive("pi embedded extra params (live)", () => {
|
||||
it("applies config maxTokens to openai streamFn", async () => {
|
||||
const model = getModel("openai", "gpt-5.2") as Model<"openai-completions">;
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
const cfg: MoltbotConfig = {
|
||||
agents: {
|
||||
defaults: {
|
||||
models: {
|
||||
|
||||
@@ -2,8 +2,8 @@ import fs from "node:fs/promises";
|
||||
import type { AgentMessage } from "@mariozechner/pi-agent-core";
|
||||
import { SessionManager } from "@mariozechner/pi-coding-agent";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
import { applyGoogleTurnOrderingFix } from "./pi-embedded-runner.js";
|
||||
|
||||
vi.mock("@mariozechner/pi-ai", async () => {
|
||||
@@ -69,10 +69,10 @@ const _makeOpenAiConfig = (modelIds: string[]) =>
|
||||
},
|
||||
},
|
||||
},
|
||||
}) satisfies ClawdbotConfig;
|
||||
}) satisfies MoltbotConfig;
|
||||
|
||||
const _ensureModels = (cfg: ClawdbotConfig, agentDir: string) =>
|
||||
ensureClawdbotModelsJson(cfg, agentDir) as unknown;
|
||||
const _ensureModels = (cfg: MoltbotConfig, agentDir: string) =>
|
||||
ensureMoltbotModelsJson(cfg, agentDir) as unknown;
|
||||
|
||||
const _textFromContent = (content: unknown) => {
|
||||
if (typeof content === "string") return content;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
import { buildEmbeddedSandboxInfo } from "./pi-embedded-runner.js";
|
||||
import type { SandboxContext } from "./sandbox.js";
|
||||
|
||||
@@ -68,10 +68,10 @@ const _makeOpenAiConfig = (modelIds: string[]) =>
|
||||
},
|
||||
},
|
||||
},
|
||||
}) satisfies ClawdbotConfig;
|
||||
}) satisfies MoltbotConfig;
|
||||
|
||||
const _ensureModels = (cfg: ClawdbotConfig, agentDir: string) =>
|
||||
ensureClawdbotModelsJson(cfg, agentDir) as unknown;
|
||||
const _ensureModels = (cfg: MoltbotConfig, agentDir: string) =>
|
||||
ensureMoltbotModelsJson(cfg, agentDir) as unknown;
|
||||
|
||||
const _textFromContent = (content: unknown) => {
|
||||
if (typeof content === "string") return content;
|
||||
@@ -105,14 +105,14 @@ describe("buildEmbeddedSandboxInfo", () => {
|
||||
const sandbox = {
|
||||
enabled: true,
|
||||
sessionKey: "session:test",
|
||||
workspaceDir: "/tmp/clawdbot-sandbox",
|
||||
agentWorkspaceDir: "/tmp/clawdbot-workspace",
|
||||
workspaceDir: "/tmp/moltbot-sandbox",
|
||||
agentWorkspaceDir: "/tmp/moltbot-workspace",
|
||||
workspaceAccess: "none",
|
||||
containerName: "clawdbot-sbx-test",
|
||||
containerName: "moltbot-sbx-test",
|
||||
containerWorkdir: "/workspace",
|
||||
docker: {
|
||||
image: "clawdbot-sandbox:bookworm-slim",
|
||||
containerPrefix: "clawdbot-sbx-",
|
||||
image: "moltbot-sandbox:bookworm-slim",
|
||||
containerPrefix: "moltbot-sbx-",
|
||||
workdir: "/workspace",
|
||||
readOnlyRoot: true,
|
||||
tmpfs: ["/tmp"],
|
||||
@@ -127,18 +127,18 @@ describe("buildEmbeddedSandboxInfo", () => {
|
||||
},
|
||||
browserAllowHostControl: true,
|
||||
browser: {
|
||||
controlUrl: "http://localhost:9222",
|
||||
bridgeUrl: "http://localhost:9222",
|
||||
noVncUrl: "http://localhost:6080",
|
||||
containerName: "clawdbot-sbx-browser-test",
|
||||
containerName: "moltbot-sbx-browser-test",
|
||||
},
|
||||
} satisfies SandboxContext;
|
||||
|
||||
expect(buildEmbeddedSandboxInfo(sandbox)).toEqual({
|
||||
enabled: true,
|
||||
workspaceDir: "/tmp/clawdbot-sandbox",
|
||||
workspaceDir: "/tmp/moltbot-sandbox",
|
||||
workspaceAccess: "none",
|
||||
agentWorkspaceMount: undefined,
|
||||
browserControlUrl: "http://localhost:9222",
|
||||
browserBridgeUrl: "http://localhost:9222",
|
||||
browserNoVncUrl: "http://localhost:6080",
|
||||
hostBrowserAllowed: true,
|
||||
});
|
||||
@@ -147,14 +147,14 @@ describe("buildEmbeddedSandboxInfo", () => {
|
||||
const sandbox = {
|
||||
enabled: true,
|
||||
sessionKey: "session:test",
|
||||
workspaceDir: "/tmp/clawdbot-sandbox",
|
||||
agentWorkspaceDir: "/tmp/clawdbot-workspace",
|
||||
workspaceDir: "/tmp/moltbot-sandbox",
|
||||
agentWorkspaceDir: "/tmp/moltbot-workspace",
|
||||
workspaceAccess: "none",
|
||||
containerName: "clawdbot-sbx-test",
|
||||
containerName: "moltbot-sbx-test",
|
||||
containerWorkdir: "/workspace",
|
||||
docker: {
|
||||
image: "clawdbot-sandbox:bookworm-slim",
|
||||
containerPrefix: "clawdbot-sbx-",
|
||||
image: "moltbot-sandbox:bookworm-slim",
|
||||
containerPrefix: "moltbot-sbx-",
|
||||
workdir: "/workspace",
|
||||
readOnlyRoot: true,
|
||||
tmpfs: ["/tmp"],
|
||||
@@ -178,7 +178,7 @@ describe("buildEmbeddedSandboxInfo", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
enabled: true,
|
||||
workspaceDir: "/tmp/clawdbot-sandbox",
|
||||
workspaceDir: "/tmp/moltbot-sandbox",
|
||||
workspaceAccess: "none",
|
||||
agentWorkspaceMount: undefined,
|
||||
hostBrowserAllowed: false,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { ensureClawdbotModelsJson } from "./models-config.js";
|
||||
import type { MoltbotConfig } from "../config/config.js";
|
||||
import { ensureMoltbotModelsJson } from "./models-config.js";
|
||||
import { createSystemPromptOverride } from "./pi-embedded-runner.js";
|
||||
|
||||
vi.mock("@mariozechner/pi-ai", async () => {
|
||||
@@ -67,10 +67,10 @@ const _makeOpenAiConfig = (modelIds: string[]) =>
|
||||
},
|
||||
},
|
||||
},
|
||||
}) satisfies ClawdbotConfig;
|
||||
}) satisfies MoltbotConfig;
|
||||
|
||||
const _ensureModels = (cfg: ClawdbotConfig, agentDir: string) =>
|
||||
ensureClawdbotModelsJson(cfg, agentDir) as unknown;
|
||||
const _ensureModels = (cfg: MoltbotConfig, agentDir: string) =>
|
||||
ensureMoltbotModelsJson(cfg, agentDir) as unknown;
|
||||
|
||||
const _textFromContent = (content: unknown) => {
|
||||
if (typeof content === "string") return content;
|
||||
|
||||
Loaded 100 of 2406 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user