Skip to content

Commit 93d5cd1

Browse files
authored
fix: honor configured xhigh thinking compat (#74273)
* fix: honor configured xhigh thinking compat * test: update agent command model selection mock
1 parent 6cea276 commit 93d5cd1

19 files changed

Lines changed: 392 additions & 38 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Docs: https://docs.openclaw.ai
2424
- Browser/gateway: ignore Playwright dialog-close races from `Page.handleJavaScriptDialog` so browser automation no longer crashes the Gateway when a dialog disappears before Playwright accepts it. (#40067) Thanks @randyjtw.
2525
- Cron/Gateway: defer missed isolated agent-turn catch-up out of the channel startup window, so overdue cron work cannot starve Discord or Telegram while providers connect after a restart. Thanks @vincentkoc.
2626
- Heartbeat/cron: defer heartbeat turns while cron work is active or queued, add opt-in `heartbeat.skipWhenBusy` for subagent/nested lane pressure, and retry busy skips without advancing the schedule so local Ollama hosts do not run heartbeat and cron prompts concurrently. Fixes #50773. Thanks @scottgl9.
27+
- Agents/thinking: honor configured model `compat.supportedReasoningEfforts` entries that include `xhigh`, so custom OpenAI-compatible provider refs expose and validate `/think xhigh` consistently across command menus, Gateway sessions, agent CLI, and `llm-task`. Carries forward #48904. Thanks @Milchstrassse and @wufunc.
2728
- Plugins/runtime-deps: prune stale `openclaw-unknown-*` bundled runtime dependency roots during Gateway startup while keeping recent or locked roots, so old staging debris cannot keep growing across restarts. Thanks @vincentkoc.
2829
- Ollama: compose caller abort signals with guarded-fetch timeouts for native `/api/chat` streams, so `/stop` and early cancellation still interrupt local Ollama requests that also carry provider timeout budgets. Refs #74133. Thanks @obviyus.
2930
- Doctor/TTS: migrate legacy `messages.tts.enabled`, agent TTS, channel TTS, and voice-call plugin TTS toggles to `auto` mode during `openclaw doctor --fix`, matching the documented TTS config contract. Thanks @vincentkoc.

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,7 @@ Time format in system prompt. Default: `auto` (OS preference).
375375
- `params` merge precedence (config): `agents.defaults.params` (global base) is overridden by `agents.defaults.models["provider/model"].params` (per-model), then `agents.list[].params` (matching agent id) overrides by key. See [Prompt Caching](/reference/prompt-caching) for details.
376376
- `params.extra_body`/`params.extraBody`: advanced pass-through JSON merged into `api: "openai-completions"` request bodies for OpenAI-compatible proxies. If it collides with generated request keys, the extra body wins; non-native completions routes still strip OpenAI-only `store` afterward.
377377
- `params.chat_template_kwargs`: vLLM/OpenAI-compatible chat-template arguments merged into top-level `api: "openai-completions"` request bodies. For `vllm/nemotron-3-*` with thinking off, the bundled vLLM plugin automatically sends `enable_thinking: false` and `force_nonempty_content: true`; explicit `chat_template_kwargs` override generated defaults, and `extra_body.chat_template_kwargs` still has final precedence. For vLLM Qwen thinking controls, set `params.qwenThinkingFormat` to `"chat-template"` or `"top-level"` on that model entry.
378+
- `compat.supportedReasoningEfforts`: per-model OpenAI-compatible reasoning effort list. Include `"xhigh"` for custom endpoints that truly accept it; OpenClaw then exposes `/think xhigh` in command menus, Gateway session rows, session patch validation, agent CLI validation, and `llm-task` validation for that configured provider/model. Use `compat.reasoningEffortMap` when the backend wants a provider-specific value for a canonical level.
378379
- `params.preserveThinking`: Z.AI-only opt-in for preserved thinking. When enabled and thinking is on, OpenClaw sends `thinking.clear_thinking: false` and replays prior `reasoning_content`; see [Z.AI thinking and preserved thinking](/providers/zai#thinking-and-preserved-thinking).
379380
- `agentRuntime`: default low-level agent runtime policy. Omitted id defaults to OpenClaw Pi. Use `id: "pi"` to force the built-in PI harness, `id: "auto"` to let registered plugin harnesses claim supported models, a registered harness id such as `id: "codex"`, or a supported CLI backend alias such as `id: "claude-cli"`. Set `fallback: "none"` to disable automatic PI fallback. Explicit plugin runtimes such as `codex` fail closed by default unless you set `fallback: "pi"` in the same override scope. Keep model refs canonical as `provider/model`; select Codex, Claude CLI, Gemini CLI, and other execution backends through runtime config instead of legacy runtime provider prefixes. See [Agent runtimes](/concepts/agent-runtimes) for how this differs from provider/model selection.
380381
- Config writers that mutate these fields (for example `/models set`, `/models set-image`, and fallback add/remove commands) save canonical object form and preserve existing fallback lists when possible.

‎docs/gateway/local-models.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,40 @@ Compatibility notes for stricter OpenAI-compatible backends:
245245
openclaw config set agents.defaults.models '{"local/my-local-model":{"params":{"extra_body":{"tool_choice":"required"}}}}' --strict-json --merge
246246
```
247247

248+
- If a custom OpenAI-compatible model accepts OpenAI reasoning efforts beyond
249+
the built-in profile, declare them on the model compat block. Adding `"xhigh"`
250+
here makes `/think xhigh`, session pickers, Gateway validation, and `llm-task`
251+
validation expose the level for that configured provider/model ref:
252+
253+
```json5
254+
{
255+
models: {
256+
providers: {
257+
local: {
258+
baseUrl: "http://127.0.0.1:8000/v1",
259+
apiKey: "sk-local",
260+
api: "openai-responses",
261+
models: [
262+
{
263+
id: "gpt-5.4",
264+
name: "GPT 5.4 via local proxy",
265+
reasoning: true,
266+
input: ["text"],
267+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
268+
contextWindow: 196608,
269+
maxTokens: 8192,
270+
compat: {
271+
supportedReasoningEfforts: ["low", "medium", "high", "xhigh"],
272+
reasoningEffortMap: { xhigh: "xhigh" },
273+
},
274+
},
275+
],
276+
},
277+
},
278+
},
279+
}
280+
```
281+
248282
- Some smaller or stricter local backends are unstable with OpenClaw's full
249283
agent-runtime prompt shape, especially when tool schemas are included. First
250284
verify the provider path with the lean local probe:

‎docs/tools/thinking.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ title: "Thinking levels"
2828
- Anthropic Claude Opus 4.7 also exposes `/think max`; it maps to the same provider-owned max effort path.
2929
- Ollama thinking-capable models expose `/think low|medium|high|max`; `max` maps to native `think: "high"` because Ollama's native API accepts `low`, `medium`, and `high` effort strings.
3030
- OpenAI GPT models map `/think` through model-specific Responses API effort support. `/think off` sends `reasoning.effort: "none"` only when the target model supports it; otherwise OpenClaw omits the disabled reasoning payload instead of sending an unsupported value.
31+
- Custom OpenAI-compatible catalog entries can opt into `/think xhigh` by setting `models.providers.<provider>.models[].compat.supportedReasoningEfforts` to include `"xhigh"`. This uses the same compat metadata that maps outbound OpenAI reasoning effort payloads, so menus, session validation, agent CLI, and `llm-task` agree with transport behavior.
3132
- Stale configured OpenRouter Hunter Alpha refs skip proxy reasoning injection because that retired route could return final answer text through reasoning fields.
3233
- Google Gemini maps `/think adaptive` to Gemini's provider-owned dynamic thinking. Gemini 3 requests omit a fixed `thinkingLevel`, while Gemini 2.5 requests send `thinkingBudget: -1`; fixed levels still map to the closest Gemini `thinkingLevel` or budget for that model family.
3334
- MiniMax (`minimax/*`) on the Anthropic-compatible streaming path defaults to `thinking: { type: "disabled" }` unless you explicitly set thinking in model params or request params. This avoids leaked `reasoning_content` deltas from MiniMax's non-native Anthropic stream format.
@@ -126,5 +127,6 @@ Malformed local-model reasoning tags are handled conservatively. Closed `<think>
126127
- Provider plugins that proxy Claude models should reuse `resolveClaudeThinkingProfile(modelId)` from `openclaw/plugin-sdk/provider-model-shared` so direct Anthropic and proxy catalogs stay aligned.
127128
- Each profile level has a stored canonical `id` (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `adaptive`, or `max`) and may include a display `label`. Binary providers use `{ id: "low", label: "on" }`.
128129
- Tool plugins that need to validate an explicit thinking override should use `api.runtime.agent.resolveThinkingPolicy({ provider, model })` plus `api.runtime.agent.normalizeThinkingLevel(...)`; they should not keep their own provider/model level lists.
130+
- Tool plugins with access to configured custom model metadata can pass `catalog` into `resolveThinkingPolicy` so `compat.supportedReasoningEfforts` opt-ins are reflected in plugin-side validation.
129131
- Published legacy hooks (`supportsXHighThinking`, `isBinaryThinking`, and `resolveDefaultThinkingLevel`) remain as compatibility adapters, but new custom level sets should use `resolveThinkingProfile`.
130132
- Gateway rows/defaults expose `thinkingLevels`, `thinkingOptions`, and `thinkingDefault` so ACP/chat clients render the same profile ids and labels that runtime validation uses.

‎src/agents/agent-command.live-model-switch.test.ts‎

Lines changed: 119 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@ import { INTERNAL_RUNTIME_CONTEXT_BEGIN, INTERNAL_RUNTIME_CONTEXT_END } from "./
33
import { LiveSessionModelSwitchError } from "./live-model-switch-error.js";
44

55
const state = vi.hoisted(() => ({
6+
defaultRuntimeConfig: {
7+
agents: {
8+
defaults: {
9+
models: {
10+
"anthropic/claude": {},
11+
"openai/claude": {},
12+
"openai/gpt-5.4": {},
13+
},
14+
},
15+
},
16+
},
17+
runtimeConfigMock: undefined as unknown,
618
acpResolveSessionMock: vi.fn((..._args: unknown[]): unknown => null),
719
acpRunTurnMock: vi.fn((..._args: unknown[]): unknown => undefined),
820
buildAcpResultMock: vi.fn(),
@@ -22,6 +34,8 @@ const state = vi.hoisted(() => ({
2234
trajectoryRecordEventMock: vi.fn(),
2335
trajectoryFlushMock: vi.fn(async () => undefined),
2436
clearSessionAuthProfileOverrideMock: vi.fn(),
37+
isThinkingLevelSupportedMock: vi.fn((_args: unknown) => true),
38+
resolveThinkingDefaultMock: vi.fn((_args: unknown) => "low"),
2539
authProfileStoreMock: { profiles: {} } as { profiles: Record<string, unknown> },
2640
sessionEntryMock: undefined as unknown,
2741
sessionStoreMock: undefined as unknown,
@@ -109,7 +123,7 @@ vi.mock("../auto-reply/thinking.js", () => ({
109123
formatXHighModelHint: () => "model-x",
110124
normalizeThinkLevel: (v?: string) => v || undefined,
111125
normalizeVerboseLevel: (v?: string) => v || undefined,
112-
isThinkingLevelSupported: () => true,
126+
isThinkingLevelSupported: (args: unknown) => state.isThinkingLevelSupportedMock(args),
113127
resolveSupportedThinkingLevel: ({ level }: { level?: string }) => level,
114128
supportsXHighThinking: () => false,
115129
}));
@@ -134,39 +148,18 @@ vi.mock("../cli/deps.js", () => ({
134148
}));
135149

136150
vi.mock("../config/io.js", () => ({
137-
getRuntimeConfig: () => ({
138-
agents: {
139-
defaults: {
140-
models: {
141-
"anthropic/claude": {},
142-
"openai/claude": {},
143-
"openai/gpt-5.4": {},
144-
},
145-
},
146-
},
147-
}),
151+
getRuntimeConfig: () => state.runtimeConfigMock ?? state.defaultRuntimeConfig,
148152
readConfigFileSnapshotForWrite: async () => ({
149153
snapshot: { valid: false },
150154
}),
151155
}));
152156

153157
vi.mock("./agent-runtime-config.js", () => {
154-
const cfg = {
155-
agents: {
156-
defaults: {
157-
models: {
158-
"anthropic/claude": {},
159-
"openai/claude": {},
160-
"openai/gpt-5.4": {},
161-
},
162-
},
163-
},
164-
};
165158
return {
166159
resolveAgentRuntimeConfig: async () => ({
167-
loadedRaw: cfg,
168-
sourceConfig: cfg,
169-
cfg,
160+
loadedRaw: state.runtimeConfigMock ?? state.defaultRuntimeConfig,
161+
sourceConfig: state.runtimeConfigMock ?? state.defaultRuntimeConfig,
162+
cfg: state.runtimeConfigMock ?? state.defaultRuntimeConfig,
170163
}),
171164
};
172165
});
@@ -311,12 +304,50 @@ vi.mock("./model-selection.js", () => ({
311304
allowedCatalog: [],
312305
allowAny: false,
313306
}),
307+
buildConfiguredModelCatalog: ({ cfg }: { cfg?: unknown }) => {
308+
const providers = (cfg as { models?: { providers?: Record<string, { models?: unknown[] }> } })
309+
?.models?.providers;
310+
if (!providers) {
311+
return [];
312+
}
313+
return Object.entries(providers).flatMap(([provider, entry]) =>
314+
Array.isArray(entry?.models)
315+
? entry.models
316+
.filter(
317+
(model): model is Record<string, unknown> => !!model && typeof model === "object",
318+
)
319+
.map((model) => {
320+
const id = typeof model.id === "string" ? model.id : "";
321+
return {
322+
provider,
323+
id,
324+
name: typeof model.name === "string" ? model.name : id,
325+
reasoning: typeof model.reasoning === "boolean" ? model.reasoning : undefined,
326+
compat: model.compat,
327+
};
328+
})
329+
.filter((model) => model.id)
330+
: [],
331+
);
332+
},
314333
modelKey: (p: string, m: string) => `${p}/${m}`,
315334
normalizeModelRef: (p: string, m: string) => ({ provider: p, model: m }),
316335
parseModelRef: (m: string, p: string) => ({ provider: p, model: m }),
317-
resolveConfiguredModelRef: () => ({ provider: "anthropic", model: "claude" }),
318-
resolveDefaultModelForAgent: () => ({ provider: "anthropic", model: "claude" }),
319-
resolveThinkingDefault: () => "low",
336+
resolveConfiguredModelRef: ({ cfg }: { cfg?: unknown }) => {
337+
const raw = (cfg as { agents?: { defaults?: { model?: string | { primary?: string } } } })
338+
?.agents?.defaults?.model;
339+
const primary = typeof raw === "string" ? raw : raw?.primary;
340+
const [provider, ...modelParts] = (primary ?? "anthropic/claude").split("/");
341+
return { provider, model: modelParts.join("/") || "claude" };
342+
},
343+
resolveDefaultModelForAgent: ({ cfg }: { cfg?: unknown }) => {
344+
const raw = (cfg as { agents?: { defaults?: { model?: string | { primary?: string } } } })
345+
?.agents?.defaults?.model;
346+
const primary = typeof raw === "string" ? raw : raw?.primary;
347+
const [provider, ...modelParts] = (primary ?? "anthropic/claude").split("/");
348+
return { provider, model: modelParts.join("/") || "claude" };
349+
},
350+
resolveThinkingDefault: (args: unknown) => state.resolveThinkingDefaultMock(args),
320351
}));
321352

322353
vi.mock("./provider-auth-aliases.js", () => ({
@@ -446,6 +477,9 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
446477
state.resolveAcpAgentPolicyErrorMock.mockReturnValue(null);
447478
state.resolveAcpDispatchPolicyErrorMock.mockReturnValue(null);
448479
state.resolveAcpExplicitTurnPolicyErrorMock.mockReturnValue(null);
480+
state.runtimeConfigMock = undefined;
481+
state.isThinkingLevelSupportedMock.mockReturnValue(true);
482+
state.resolveThinkingDefaultMock.mockReturnValue("low");
449483
state.acpRunTurnMock.mockImplementation(async (params: unknown) => {
450484
const onEvent = (params as { onEvent?: (event: unknown) => void }).onEvent;
451485
onEvent?.({ type: "text_delta", stream: "output", text: "done" });
@@ -506,6 +540,62 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
506540
expect(lifecycleEndCalls.length).toBeGreaterThanOrEqual(1);
507541
});
508542

543+
it("validates explicit thinking against configured model compat without an allowlist", async () => {
544+
state.runtimeConfigMock = {
545+
agents: {
546+
defaults: {
547+
model: { primary: "gmn/gpt-5.4" },
548+
},
549+
},
550+
models: {
551+
providers: {
552+
gmn: {
553+
models: [
554+
{
555+
id: "gpt-5.4",
556+
name: "GPT 5.4 via GMN",
557+
reasoning: true,
558+
compat: { supportedReasoningEfforts: ["low", "medium", "high", "xhigh"] },
559+
},
560+
],
561+
},
562+
},
563+
},
564+
};
565+
state.runWithModelFallbackMock.mockImplementation(async (params: FallbackRunnerParams) => {
566+
const result = await params.run(params.provider, params.model);
567+
return {
568+
result,
569+
provider: params.provider,
570+
model: params.model,
571+
attempts: [],
572+
};
573+
});
574+
state.runAgentAttemptMock.mockResolvedValue(makeSuccessResult("gmn", "gpt-5.4"));
575+
576+
await agentCommand({
577+
message: "hello",
578+
to: "+1234567890",
579+
senderIsOwner: true,
580+
thinking: "xhigh",
581+
});
582+
583+
expect(state.isThinkingLevelSupportedMock).toHaveBeenCalledWith(
584+
expect.objectContaining({
585+
provider: "gmn",
586+
model: "gpt-5.4",
587+
level: "xhigh",
588+
catalog: [
589+
expect.objectContaining({
590+
provider: "gmn",
591+
id: "gpt-5.4",
592+
compat: { supportedReasoningEfforts: ["low", "medium", "high", "xhigh"] },
593+
}),
594+
],
595+
}),
596+
);
597+
});
598+
509599
it("records fallback steps to the session trajectory runtime", async () => {
510600
state.runWithModelFallbackMock.mockImplementation(async (params: FallbackRunnerParams) => {
511601
await params.onFallbackStep?.({

‎src/agents/agent-command.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import { loadModelCatalog } from "./model-catalog.js";
5454
import { runWithModelFallback } from "./model-fallback.js";
5555
import {
5656
buildAllowedModelSet,
57+
buildConfiguredModelCatalog,
5758
modelKey,
5859
normalizeModelRef,
5960
parseModelRef,
@@ -298,7 +299,13 @@ async function prepareAgentCommandExecution(
298299
defaultProvider: DEFAULT_PROVIDER,
299300
defaultModel: DEFAULT_MODEL,
300301
});
301-
const thinkingLevelsHint = formatThinkingLevels(configuredModel.provider, configuredModel.model);
302+
const configuredThinkingCatalog = buildConfiguredModelCatalog({ cfg });
303+
const thinkingLevelsHint = formatThinkingLevels(
304+
configuredModel.provider,
305+
configuredModel.model,
306+
", ",
307+
configuredThinkingCatalog.length > 0 ? configuredThinkingCatalog : undefined,
308+
);
302309

303310
const thinkOverride = normalizeThinkLevel(opts.thinking);
304311
const thinkOnce = normalizeThinkLevel(opts.thinkingOnce);
@@ -388,6 +395,7 @@ async function prepareAgentCommandExecution(
388395
body,
389396
transcriptBody,
390397
cfg,
398+
configuredThinkingCatalog,
391399
normalizedSpawned,
392400
agentCfg,
393401
thinkOverride,
@@ -424,6 +432,7 @@ async function agentCommandInternal(
424432
body,
425433
transcriptBody,
426434
cfg,
435+
configuredThinkingCatalog,
427436
normalizedSpawned,
428437
agentCfg,
429438
thinkOverride,
@@ -818,17 +827,18 @@ async function agentCommandInternal(
818827
}
819828
}
820829

830+
const catalogForThinking =
831+
modelCatalog ??
832+
(allowedModelCatalog.length > 0 ? allowedModelCatalog : configuredThinkingCatalog);
833+
const thinkingCatalog = catalogForThinking.length > 0 ? catalogForThinking : undefined;
821834
if (!resolvedThinkLevel) {
822-
const catalogForThinking = modelCatalog ?? allowedModelCatalog;
823835
resolvedThinkLevel = resolveThinkingDefault({
824836
cfg,
825837
provider,
826838
model,
827-
catalog: catalogForThinking.length > 0 ? catalogForThinking : undefined,
839+
catalog: thinkingCatalog,
828840
});
829841
}
830-
const catalogForThinking = modelCatalog ?? allowedModelCatalog;
831-
const thinkingCatalog = catalogForThinking.length > 0 ? catalogForThinking : undefined;
832842
if (
833843
!isThinkingLevelSupported({
834844
provider,

‎src/agents/model-catalog.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ type DiscoveredModel = {
3030
contextWindow?: number;
3131
reasoning?: boolean;
3232
input?: ModelInputType[];
33+
compat?: ModelCatalogEntry["compat"];
3334
};
3435

3536
type PiSdkModule = typeof import("./pi-model-discovery-runtime.js");
@@ -187,7 +188,8 @@ export async function loadModelCatalog(params?: {
187188
: undefined;
188189
const reasoning = typeof entry?.reasoning === "boolean" ? entry.reasoning : undefined;
189190
const input = Array.isArray(entry?.input) ? entry.input : undefined;
190-
models.push({ id, name, provider, contextWindow, reasoning, input });
191+
const compat = entry?.compat && typeof entry.compat === "object" ? entry.compat : undefined;
192+
models.push({ id, name, provider, contextWindow, reasoning, input, compat });
191193
}
192194
const supplemental = await augmentModelCatalogWithProviderPlugins({
193195
config: cfg,

0 commit comments

Comments
 (0)