Skip to content

Commit c160772

Browse files
committed
feat: configure Code Mode per model with inherited defaults
1 parent 383a293 commit c160772

44 files changed

Lines changed: 730 additions & 144 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"core": 2361,
2+
"core": 2363,
33
"channel": 3675,
4-
"plugin": 4028
4+
"plugin": 4055
55
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
0d0b0cbefc90c4c06c189c1b2187341b91831fdaae35cdd4240ef45c734b21d2 config-baseline.json
2-
b0ded1a606c27b41dc14041b12ff32ebf44314032be6af31d38856bf6db10df6 config-baseline.core.json
1+
6dcaa827b84779a236de965f61361fdbff388e010bd9a50b8a21c12ea191da94 config-baseline.json
2+
6772fdc4d4cf4c5b0efce172a6286a96a9b97f6978bfac57367acf34a493510f config-baseline.core.json
33
b0cec3af0df6a2e436a66c3d00b5aadeeca13043a056963daf60dea9ee3c4765 config-baseline.channel.json
4-
30ea5089672338a910478e45a04d7ddb6bd3e62cb52b3f209d2372ddc0dbfc31 config-baseline.plugin.json
4+
ac1f364bf8ecb0d34cee215150e29bf350f1d1909778ecdde53cbe5b0fb22014 config-baseline.plugin.json

‎docs/gateway/config-agents.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ date context. Falls back to the host timezone.
427427
- `models`: configured aliases and per-model settings. Each entry can include `alias` (shortcut) and `params` (provider-specific, for example `temperature`, `maxTokens`, `cacheRetention`, `context1m`, `anthropicServerCompaction`, `anthropicCompactThreshold`, `responsesServerCompaction`, `responsesCompactThreshold`, OpenRouter `provider` routing, `chat_template_kwargs`, `extra_body`/`extraBody`). Adding entries does not restrict model overrides.
428428
- Use `provider/*` entries such as `"openai/*": {}` or `"vllm/*": {}` to show all discovered models for selected providers without manually listing every model id.
429429
- Add `agentRuntime` to a `provider/*` entry when every dynamically discovered model for that provider should use the same runtime. Exact `provider/model` runtime policy still wins over the wildcard.
430+
- Add `codeMode: true` or `codeMode: false` to an exact `provider/model` entry to override OpenClaw Code Mode activation. Omit it to inherit the global `tools.codeMode` default, including `"auto"`; agent-specific activation settings take precedence. This changes neither runtime selection nor Codex native Code Mode. The Control UI model editor offers **Default**, **On**, and **Off** alongside runtime settings. See [per-model Code Mode](/tools/code-mode#override-one-model) for precedence and an example.
430431
- Safe metadata edits: use `openclaw config set agents.defaults.models '<json>' --strict-json --merge` to add entries. `config set` refuses replacements that would remove existing entries unless you pass `--replace`.
431432
- `modelPolicy.allow`: explicit override allowlist. Accepts aliases, exact `provider/model` refs, and trailing prefix wildcards such as `openai/*` or `clawrouter/anthropic/*`. Omit it or use `[]` to allow any model. `agents.entries.*.modelPolicy.allow` replaces the default policy for that agent; an explicit empty list opts that agent into allow-any.
432433
- Provider-scoped configure/onboarding flows merge selected provider models into this map and preserve unrelated providers already configured.
@@ -1081,7 +1082,7 @@ for provider examples and precedence.
10811082
- `thinkingDefault`: optional per-agent default thinking level (`off | minimal | low | medium | high | xhigh | adaptive | max`). Overrides `agents.defaults.thinkingDefault` for this agent when no per-message or session override is set. The selected provider/model profile controls which values are valid; for Google Gemini, `adaptive` keeps provider-owned dynamic thinking (`thinkingLevel` omitted on Gemini 3/3.1, `thinkingBudget: -1` on Gemini 2.5).
10821083
- `reasoningDefault`: optional per-agent default reasoning visibility (`on | off | stream`). Overrides `agents.defaults.reasoningDefault` for this agent when no per-message or session reasoning override is set.
10831084
- `fastModeDefault`: optional per-agent default for fast mode (`"auto" | true | false`). Overrides `agents.defaults.fastModeDefault` for this agent when no per-message or session fast-mode override is set.
1084-
- `models`: optional per-agent model catalog/runtime overrides keyed by full `provider/model` ids. Use `models["provider/model"].agentRuntime` for per-agent runtime exceptions.
1085+
- `models`: optional per-agent model catalog/runtime overrides keyed by full `provider/model` ids. Use `models["provider/model"].agentRuntime` for per-agent runtime exceptions. `models["provider/model"].codeMode` accepts `true` or `false` and takes precedence over the agent's `tools.codeMode` activation, the shared model override, and the global default. Omit it to inherit; it does not affect Codex native Code Mode.
10851086
- `runtime`: optional per-agent runtime descriptor. Use `type: "acp"` with `runtime.acp` defaults (`agent`, `backend`, `mode`, `cwd`) when the agent should default to ACP harness sessions.
10861087
- `identity.avatar`: workspace-relative path, `http(s)` URL, or `data:` URI.
10871088
- Local workspace-relative `identity.avatar` image files are limited to 2 MB. `http(s)` URLs and `data:` URIs are not checked against the local file-size limit.

‎docs/tools/code-mode.md‎

Lines changed: 76 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ program that searches, describes, and calls the hidden tool catalog.
1919
OpenClaw Code Mode is off by default. To try it, open **Settings → Agents &
2020
Tools → Labs** and turn on **Code Mode**. The Labs switch writes the `"auto"`
2121
tier, which engages only for models marked as preferred Code Mode performers.
22+
This is the global default; agent and model overrides take precedence.
2223
</Note>
2324

2425
This page documents OpenClaw code mode, not Codex Code Mode. The two features
@@ -30,7 +31,7 @@ separate implementations:
3031
prefixed by a `// @exec: {...}` pragma line for execution options), executed
3132
in Codex's in-process V8 Code Mode runtime.
3233
- OpenClaw code mode runs in the generic OpenClaw agent runtime and is
33-
disabled unless `tools.codeMode.enabled` is `true` or `"auto"`. Its `exec`
34+
enabled through global, agent, or model activation settings. Its `exec`
3435
tool takes a JSON `{ code, language }` payload, executed in a QuickJS-WASI
3536
worker.
3637

@@ -119,7 +120,7 @@ To enable the same tier without the Control UI, set it in config:
119120
}
120121
```
121122

122-
To force code mode on for every tool-capable run, regardless of model:
123+
To default code mode on for every tool-capable run, regardless of model:
123124

124125
```json5
125126
{
@@ -131,8 +132,9 @@ To force code mode on for every tool-capable run, regardless of model:
131132

132133
Object form works too: `tools.codeMode.enabled` accepts the same `false`,
133134
`true`, and `"auto"` values. Code mode stays off when `tools.codeMode` is
134-
omitted, `false`, or an object without an explicit `enabled` value. Configuring
135-
limits or other Code Mode options does not enable it.
135+
omitted, `false`, or an object without an explicit `enabled` value, unless an
136+
agent or model override enables it. Configuring limits or other Code Mode
137+
options does not enable it.
136138

137139
See [Automatic per-model activation](#automatic-per-model-activation) for the
138140
exact semantics and the shipped model list.
@@ -162,6 +164,58 @@ Set explicit limits for tighter bounds:
162164
}
163165
```
164166

167+
### Override one model
168+
169+
Set `codeMode: true` or `codeMode: false` on an exact `provider/model` entry in
170+
`agents.defaults.models`. Omit `codeMode` to inherit the parent activation
171+
setting, including its `"auto"` behavior. The model field accepts only a
172+
boolean; `"auto"` belongs on the global or per-agent `tools.codeMode` setting.
173+
174+
```json5
175+
{
176+
tools: { codeMode: "auto" },
177+
agents: {
178+
defaults: {
179+
models: {
180+
"openai/gpt-5.6-luna": {
181+
agentRuntime: { id: "openclaw" },
182+
codeMode: true,
183+
},
184+
},
185+
},
186+
entries: {
187+
research: {
188+
models: {
189+
"openai/gpt-5.6-luna": { codeMode: false },
190+
},
191+
},
192+
},
193+
},
194+
}
195+
```
196+
197+
The example enables Code Mode for this model except on the `research` agent.
198+
Activation resolves from the first explicit setting in this order:
199+
200+
1. `agents.entries.<agent>.models["provider/model"].codeMode`.
201+
2. `agents.entries.<agent>.tools.codeMode.enabled` (or its boolean/`"auto"` shorthand).
202+
3. `agents.defaults.models["provider/model"].codeMode`.
203+
4. `tools.codeMode.enabled` (or its shorthand), defaulting to `false`.
204+
205+
In the Control UI, open **Settings → Agent Defaults**, show **Advanced**
206+
settings, and find **Models** under **Agent Defaults**. Each model has a
207+
**Code Mode** selector beside its runtime: **Default** removes the override,
208+
**On** saves `true`, and **Off** saves `false`. Use **Raw** config or the CLI
209+
for agent-specific model overrides; the **Agent List** form does not yet
210+
support its constrained map schema.
211+
212+
Overrides affect the selected model on future runs, including fallback models;
213+
they do not enable tools on a tool-free run or change runtime selection. The
214+
example separately selects `agentRuntime.id: "openclaw"` because OpenAI routes
215+
may otherwise use Codex. These settings do not control Codex native Code Mode.
216+
Model overrides change activation only; limits still come from the global and
217+
per-agent `tools.codeMode` options.
218+
165219
### What the model does
166220

167221
For a tool with a declared output such as
@@ -305,9 +359,9 @@ Provider-owned tools such as remote Python sandboxes are separate tools. See
305359

306360
## Configuration
307361

308-
`tools.codeMode.enabled` is the activation gate. It defaults to `false`,
309-
including when the Code Mode object configures other fields. Set `true` or
310-
`"auto"` explicitly to enable it.
362+
`tools.codeMode.enabled` sets the global activation default. It defaults to
363+
`false`, including when the Code Mode object configures other fields. Set
364+
`true` or `"auto"` explicitly, or use an [agent or model override](#override-one-model).
311365

312366
| Field | Default | Clamp |
313367
| --------------------- | ------------------------------ | ----------------------------------------------- |
@@ -333,13 +387,14 @@ an engaged run never silently falls back to broad direct tool exposure.
333387

334388
`tools.codeMode.enabled` accepts three values:
335389

336-
- `false` (default): code mode is off for every run.
337-
- `true`: code mode engages for every tool-capable run, regardless of model.
390+
- `false` (default): code mode is off unless an agent or model override enables it.
391+
- `true`: code mode engages for tool-capable runs unless an override disables it.
338392
- `"auto"`: code mode engages only when the run's model is flagged as a
339393
preferred code-mode performer in its provider catalog.
340394

341-
`false` and `true` behave exactly as before the `"auto"` tier existed; `"auto"`
342-
is an explicit per-model opt-in.
395+
These values supply the default when no agent or model override takes
396+
precedence. `"auto"` uses catalog capability; an explicit per-model boolean
397+
bypasses that capability preference.
343398

344399
### The `compat.codeMode` catalog flag
345400

@@ -413,10 +468,9 @@ sometimes regressed, which is why `"auto"` leaves them on direct tools.
413468

414469
Use `"auto"` when agents switch between models: strong models get the compact
415470
surface, weaker or local ones keep the exposure they handle best. Use `true`
416-
when you have verified a specific unflagged model performs well with code
417-
mode; global force-on is most predictable for single-model deployments. For
418-
open-weight or uncached serving where every prompt token is billed or
419-
recomputed, prefer enabling per model (via `"auto"` or a per-agent override)
471+
on an exact model entry when you have verified an unflagged model performs well
472+
with code mode. For open-weight or uncached serving where every prompt token is billed or
473+
recomputed, prefer enabling per model (via `"auto"` or an explicit model override)
420474
rather than globally, since the token savings depend on the model actually
421475
using the program surface well.
422476

@@ -430,8 +484,9 @@ final model request is assembled:
430484
2. Build the effective OpenClaw tool list, adding eligible plugin, MCP, and
431485
client tools.
432486
3. Apply allow/deny policy.
433-
4. If `tools.codeMode.enabled` is `false`, or is `"auto"` and the run's model
434-
is not catalog-preferred, continue with normal tool exposure.
487+
4. Resolve activation using the [agent and model precedence](#override-one-model).
488+
If it is `false`, or `"auto"` and the run's model is not catalog-preferred,
489+
continue with normal tool exposure.
435490
5. If enabled and tools are active for the run, retain required direct-only
436491
tools and register every catalog-eligible effective tool in the code-mode
437492
catalog.
@@ -1238,9 +1293,11 @@ does not use a `node:vm` child as the sandbox.
12381293

12391294
Code mode coverage should prove:
12401295

1241-
- disabled config leaves existing tool exposure unchanged
1296+
- disabled config without an enabling override leaves existing tool exposure unchanged
12421297
- omitted `enabled`, including object config that sets other fields, stays
1243-
disabled
1298+
disabled unless an agent or model override enables it
1299+
- per-model `true`, `false`, and unset values preserve activation precedence,
1300+
fallback-model selection, and limits from the enclosing options
12441301
- enabled config exposes `exec`, `wait`, and only required direct-only tools to
12451302
the model when tools are active for the run
12461303
- raw no-tool runs, `disableTools`, and empty allowlists do not trigger

‎extensions/copilot/src/tool-bridge.test.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -661,18 +661,35 @@ describe("createCopilotToolBridge", () => {
661661
expect(hiddenExecute).not.toHaveBeenCalled();
662662
});
663663

664-
it("reports code mode as disengaged when the config leaves it off", async () => {
665-
const result = await createCopilotToolBridge({
666-
attemptParams: {
667-
config: { tools: { codeMode: false } },
668-
runId: "run-no-code-mode",
669-
sessionKey: "agent:agent-1:main",
670-
} as never,
671-
createOpenClawCodingTools: vi.fn(async () => [makeTool({ name: "read" })]),
672-
});
673-
674-
expect(result.codeModeEngaged).toBe(false);
675-
});
664+
it.each([
665+
{ configured: false, override: undefined },
666+
{ configured: true, override: false },
667+
])(
668+
"keeps the direct surface when configured=$configured, invocation=$override",
669+
async ({ configured, override }) => {
670+
const result = await createCopilotToolBridge({
671+
attemptParams: {
672+
config: {
673+
tools: { codeMode: configured, toolSearch: false },
674+
agents: {
675+
entries: { "agent-1": {} },
676+
defaults: { models: { "github-copilot/gpt-4o": { codeMode: configured } } },
677+
},
678+
},
679+
codeModeOverride: override,
680+
runId: "run-no-code-mode",
681+
sessionKey: "agent:agent-1:main",
682+
},
683+
createOpenClawCodingTools: vi.fn(async () => [makeTool({ name: "read" })]),
684+
});
685+
try {
686+
expect(result.codeModeEngaged).toBe(false);
687+
expect(result.promptToolPolicy.apply().tools.map((tool) => tool.name)).toEqual(["read"]);
688+
} finally {
689+
result.cleanup?.();
690+
}
691+
},
692+
);
676693

677694
it("keeps code-mode controls visible when a narrow allowlist is active", async () => {
678695
const createOpenClawCodingTools = vi.fn(async () => [

‎extensions/copilot/src/tool-bridge.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ export async function createCopilotToolBridge(
199199
abortSignal: input.abortSignal,
200200
agentId: input.agentId,
201201
config: attemptParams.config,
202+
codeModeOverride: attemptParams.codeModeOverride,
202203
disableTools: attemptParams.disableTools,
203204
executeTool: (toolParams) => executeCatalogTool(input, toolParams),
204205
forceMessageTool: shouldForceCopilotMessageTool(attemptParams),

‎src/agents/code-mode-execution.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import {
2323
boundOutputToLimit,
2424
enforceSnapshotPayloadLimits,
2525
prepareSource,
26-
resolveCodeModeConfig,
2726
toToolSearchConfig,
2827
type CodeModeConfig,
2928
type CodeModeLanguage,
@@ -65,6 +64,7 @@ import { ToolInputError } from "./tools/common.js";
6564
export async function runCodeModeExec(params: {
6665
toolCallId: string;
6766
ctx: ToolSearchToolContext;
67+
config: CodeModeConfig;
6868
code: string;
6969
assistantTurnId?: string;
7070
language?: CodeModeLanguage;
@@ -74,15 +74,7 @@ export async function runCodeModeExec(params: {
7474
onRuntime?: (runtime: ToolSearchRuntime) => void;
7575
}) {
7676
removeExpiredRuns();
77-
const config = resolveCodeModeConfig(
78-
params.ctx.runtimeConfig ?? params.ctx.config,
79-
params.ctx.agentId,
80-
);
81-
// The exec/wait tools only exist when the run gate engaged code mode, so
82-
// "auto" counts as enabled here; only a hard `false` rejects execution.
83-
if (config.enabled === false) {
84-
throw new ToolInputError("code mode is disabled.");
85-
}
77+
const { config } = params;
8678
const runtime = new ToolSearchRuntime(params.ctx, toToolSearchConfig(config), {
8779
prepareInput: true,
8880
validateInput: true,

‎src/agents/code-mode-runtime.ts‎

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import { isRecord } from "@openclaw/normalization-core/record-coerce";
22
import { readNonBlankString } from "@openclaw/normalization-core/string-coerce";
33
import { uniqueValues } from "@openclaw/normalization-core/string-normalization";
44
import { parse, tokenizer } from "acorn";
5+
import { normalizeAgentModelRefForConfig } from "../config/model-input.js";
56
import type { OpenClawConfig } from "../config/types.openclaw.js";
67
import { formatErrorMessage } from "../infra/errors.js";
8+
import { modelKey } from "../shared/model-key.js";
79
import { clampNumber } from "../utils.js";
810
import { resolveAgentConfig } from "./agent-scope-config.js";
911
import { boundCodeModeResult } from "./code-mode-json.js";
@@ -41,7 +43,7 @@ export type CodeModeLanguage = "javascript" | "typescript";
4143

4244
/** Resolved Code Mode runtime limits and visible language options. */
4345
export type CodeModeConfig = {
44-
/** Master switch tier: true/false, or "auto" (engage per model catalog flag). */
46+
/** Effective activation policy; "auto" follows the model catalog flag. */
4547
enabled: boolean | "auto";
4648
runtime: "quickjs-wasi";
4749
mode: "only";
@@ -111,14 +113,29 @@ function normalizeCodeModeRawConfig(value: unknown): Record<string, unknown> | u
111113
return isRecord(codeMode) ? codeMode : undefined;
112114
}
113115

114-
function readCodeModeRawConfig(config?: OpenClawConfig, agentId?: string): Record<string, unknown> {
116+
function readCodeModeRawConfig(
117+
config?: OpenClawConfig,
118+
agentId?: string,
119+
model?: { provider: string; modelId: string },
120+
): Record<string, unknown> {
115121
const tools = isRecord(config?.tools) ? config.tools : undefined;
116122
const globalRaw = normalizeCodeModeRawConfig(tools?.codeMode) ?? {};
117-
const agentRaw =
118-
config && agentId
119-
? normalizeCodeModeRawConfig(resolveAgentConfig(config, agentId)?.tools?.codeMode)
120-
: undefined;
121-
return agentRaw ? { ...globalRaw, ...agentRaw } : globalRaw;
123+
const agent = config && agentId ? resolveAgentConfig(config, agentId) : undefined;
124+
const agentRaw = normalizeCodeModeRawConfig(agent?.tools?.codeMode);
125+
const key = model
126+
? normalizeAgentModelRefForConfig(modelKey(model.provider, model.modelId))
127+
: undefined;
128+
// An options-only agent object inherits activation; it must not hide a model
129+
// override. Explicit false at either scope remains an authored choice.
130+
return {
131+
...globalRaw,
132+
...agentRaw,
133+
enabled:
134+
(key ? agent?.models?.[key]?.codeMode : undefined) ??
135+
agentRaw?.enabled ??
136+
(key ? config?.agents?.defaults?.models?.[key]?.codeMode : undefined) ??
137+
globalRaw.enabled,
138+
};
122139
}
123140

124141
function readEnabled(value: unknown): boolean | "auto" {
@@ -142,8 +159,12 @@ function readLanguages(value: unknown): CodeModeLanguage[] {
142159
}
143160

144161
/** Resolves Code Mode runtime limits and language support from config. */
145-
export function resolveCodeModeConfig(config?: OpenClawConfig, agentId?: string): CodeModeConfig {
146-
const raw = readCodeModeRawConfig(config, agentId);
162+
export function resolveCodeModeConfig(
163+
config?: OpenClawConfig,
164+
agentId?: string,
165+
model?: { provider: string; modelId: string },
166+
): CodeModeConfig {
167+
const raw = readCodeModeRawConfig(config, agentId, model);
147168
const maxSearchLimit = clampNumber(
148169
readPositiveInteger(raw.maxSearchLimit, DEFAULT_MAX_SEARCH_LIMIT),
149170
1,
@@ -190,7 +211,7 @@ export function resolveCodeModeConfig(config?: OpenClawConfig, agentId?: string)
190211
}
191212

192213
/**
193-
* Resolves the master switch against one model's catalog capability flag.
214+
* Resolves the effective activation policy against one model's catalog flag.
194215
* `true`/`false` are absolute; `"auto"` engages only for models whose catalog
195216
* compat declares `codeMode: "preferred"`. This gates the model-facing tool
196217
* surface only; runs that route to a provider-native harness (for example the

0 commit comments

Comments
 (0)