Skip to content

Commit ef3ac6a

Browse files
authored
fix: guard Anthropic Messages max tokens (#66664)
* Docs: add Anthropic max_tokens investigation memo Regeneration-Prompt: | Investigate the reported OpenClaw cron isolated-agent failure where an Anthropic Haiku run returned "max_tokens: must be greater than or equal to 1". Do not implement a fix yet. Inspect the cron isolated-agent execution path, the embedded runner, extra param plumbing, Anthropic transport code, and any model-selection or token-budget logic that could synthesize maxTokens = 0. Produce a concise maintainer memo with concrete file references, explain why cron itself is not the component setting maxTokens, identify the most likely root cause, describe the smallest repro shape, and recommend the cleanest fix. * openclaw-e82: guard Anthropic Messages maxTokens Regeneration-Prompt: | Fix the Anthropic Messages path so OpenClaw never sends max_tokens <= 0 to Anthropic. Match the positive-number guard already used by the Anthropic Vertex transport, but keep the change scoped: validate token limits in src/agents/anthropic-transport-stream.ts where transport options are resolved and where the final payload is assembled, fall back to the model limit when a runtime override is zero, fail locally when no positive token budget exists, and drop non-positive maxTokens from src/agents/pi-embedded-runner/extra-params.ts so hidden config params do not leak through. Add focused regression coverage for both the transport and extra-param forwarding path, and remove the earlier investigation memo from the branch so the PR diff only contains the fix. * fix: scope Anthropic max token guard * fix: document Anthropic max token guard * fix: floor Anthropic max token overrides
1 parent 9b25c8f commit ef3ac6a

4 files changed

Lines changed: 208 additions & 4 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ Docs: https://docs.openclaw.ai
3131
- Auto-reply/billing: classify pure billing cooldown fallback summaries from structured fallback reasons so users see billing guidance instead of the generic failure reply. (#66363) Thanks @Rohan5commit.
3232
- Agents/fallback: preserve the original prompt body on model fallback retries with session history so the retrying model keeps the active task instead of only seeing a generic continue message. (#66029) Thanks @WuKongAI-CMU.
3333
- Reply/secrets: resolve active reply channel/account SecretRefs before reply-run message-action discovery so channel token SecretRefs (for example Discord) do not degrade into discovery-time unresolved-secret failures. (#66796) Thanks @joshavant.
34+
- Agents/Anthropic: ignore non-positive Anthropic Messages token overrides and fail locally when no positive token budget remains, so invalid `max_tokens` values no longer reach the provider API. (#66664) thanks @jalehman
3435

3536
## 2026.4.14
3637

‎src/agents/anthropic-transport-stream.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,141 @@ describe("anthropic transport stream", () => {
111111
);
112112
});
113113

114+
it("ignores non-positive runtime maxTokens overrides and falls back to the model limit", async () => {
115+
const model = attachModelProviderRequestTransport(
116+
{
117+
id: "claude-sonnet-4-6",
118+
name: "Claude Sonnet 4.6",
119+
api: "anthropic-messages",
120+
provider: "anthropic",
121+
baseUrl: "https://api.anthropic.com",
122+
reasoning: true,
123+
input: ["text"],
124+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
125+
contextWindow: 200000,
126+
maxTokens: 8192,
127+
} satisfies Model<"anthropic-messages">,
128+
{
129+
proxy: {
130+
mode: "env-proxy",
131+
},
132+
},
133+
);
134+
const streamFn = createAnthropicMessagesTransportStreamFn();
135+
136+
const stream = await Promise.resolve(
137+
streamFn(
138+
model,
139+
{
140+
messages: [{ role: "user", content: "hello" }],
141+
} as Parameters<typeof streamFn>[1],
142+
{
143+
apiKey: "sk-ant-api",
144+
maxTokens: 0,
145+
} as Parameters<typeof streamFn>[2],
146+
),
147+
);
148+
await stream.result();
149+
150+
expect(anthropicMessagesStreamMock).toHaveBeenCalledWith(
151+
expect.objectContaining({
152+
model: "claude-sonnet-4-6",
153+
max_tokens: 8192,
154+
stream: true,
155+
}),
156+
undefined,
157+
);
158+
});
159+
160+
it("ignores fractional runtime maxTokens overrides that floor to zero", async () => {
161+
const model = attachModelProviderRequestTransport(
162+
{
163+
id: "claude-sonnet-4-6",
164+
name: "Claude Sonnet 4.6",
165+
api: "anthropic-messages",
166+
provider: "anthropic",
167+
baseUrl: "https://api.anthropic.com",
168+
reasoning: true,
169+
input: ["text"],
170+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
171+
contextWindow: 200000,
172+
maxTokens: 8192,
173+
} satisfies Model<"anthropic-messages">,
174+
{
175+
proxy: {
176+
mode: "env-proxy",
177+
},
178+
},
179+
);
180+
const streamFn = createAnthropicMessagesTransportStreamFn();
181+
182+
const stream = await Promise.resolve(
183+
streamFn(
184+
model,
185+
{
186+
messages: [{ role: "user", content: "hello" }],
187+
} as Parameters<typeof streamFn>[1],
188+
{
189+
apiKey: "sk-ant-api",
190+
maxTokens: 0.5,
191+
} as Parameters<typeof streamFn>[2],
192+
),
193+
);
194+
await stream.result();
195+
196+
expect(anthropicMessagesStreamMock).toHaveBeenCalledWith(
197+
expect.objectContaining({
198+
model: "claude-sonnet-4-6",
199+
max_tokens: 8192,
200+
stream: true,
201+
}),
202+
undefined,
203+
);
204+
});
205+
206+
it("fails locally when Anthropic maxTokens is non-positive after resolution", async () => {
207+
const model = attachModelProviderRequestTransport(
208+
{
209+
id: "claude-haiku-4-5",
210+
name: "Claude Haiku 4.5",
211+
api: "anthropic-messages",
212+
provider: "anthropic",
213+
baseUrl: "https://api.anthropic.com",
214+
reasoning: false,
215+
input: ["text"],
216+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
217+
contextWindow: 32000,
218+
maxTokens: 0,
219+
} satisfies Model<"anthropic-messages">,
220+
{
221+
proxy: {
222+
mode: "env-proxy",
223+
},
224+
},
225+
);
226+
const streamFn = createAnthropicMessagesTransportStreamFn();
227+
228+
const stream = await Promise.resolve(
229+
streamFn(
230+
model,
231+
{
232+
messages: [{ role: "user", content: "hello" }],
233+
} as Parameters<typeof streamFn>[1],
234+
{
235+
apiKey: "sk-ant-api",
236+
} as Parameters<typeof streamFn>[2],
237+
),
238+
);
239+
240+
const result = await stream.result();
241+
242+
expect(result.stopReason).toBe("error");
243+
expect(result.errorMessage).toContain(
244+
"Anthropic Messages transport requires a positive maxTokens value",
245+
);
246+
expect(anthropicMessagesStreamMock).not.toHaveBeenCalled();
247+
});
248+
114249
it("preserves Anthropic OAuth identity and tool-name remapping with transport overrides", async () => {
115250
anthropicMessagesStreamMock.mockReturnValueOnce(
116251
(async function* () {

‎src/agents/anthropic-transport-stream.ts‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,26 @@ function clampReasoningLevel(level: ThinkingLevel): "minimal" | "low" | "medium"
128128
return level === "xhigh" ? "high" : level;
129129
}
130130

131+
function resolvePositiveAnthropicMaxTokens(value: unknown): number | undefined {
132+
if (typeof value !== "number" || !Number.isFinite(value)) {
133+
return undefined;
134+
}
135+
const floored = Math.floor(value);
136+
return floored > 0 ? floored : undefined;
137+
}
138+
139+
function resolveAnthropicMessagesMaxTokens(params: {
140+
modelMaxTokens: number | undefined;
141+
requestedMaxTokens: number | undefined;
142+
}): number | undefined {
143+
const requested = resolvePositiveAnthropicMaxTokens(params.requestedMaxTokens);
144+
if (requested !== undefined) {
145+
return requested;
146+
}
147+
const modelMax = resolvePositiveAnthropicMaxTokens(params.modelMaxTokens);
148+
return modelMax !== undefined ? Math.min(modelMax, 32_000) : undefined;
149+
}
150+
131151
function adjustMaxTokensForThinking(params: {
132152
baseMaxTokens: number;
133153
modelMaxTokens: number;
@@ -479,18 +499,26 @@ function buildAnthropicParams(
479499
isOAuthToken: boolean,
480500
options: AnthropicTransportOptions | undefined,
481501
) {
502+
const maxTokens = resolveAnthropicMessagesMaxTokens({
503+
modelMaxTokens: model.maxTokens,
504+
requestedMaxTokens: options?.maxTokens,
505+
});
506+
if (maxTokens === undefined) {
507+
throw new Error(
508+
`Anthropic Messages transport requires a positive maxTokens value for ${model.provider}/${model.id}`,
509+
);
510+
}
482511
const payloadPolicy = resolveAnthropicPayloadPolicy({
483512
provider: model.provider,
484513
api: model.api,
485514
baseUrl: model.baseUrl,
486515
cacheRetention: options?.cacheRetention,
487516
enableCacheControl: true,
488517
});
489-
const defaultMaxTokens = Math.min(model.maxTokens, 32_000);
490518
const params: Record<string, unknown> = {
491519
model: model.id,
492520
messages: convertAnthropicMessages(context.messages, model, isOAuthToken),
493-
max_tokens: options?.maxTokens || defaultMaxTokens,
521+
max_tokens: maxTokens,
494522
stream: true,
495523
};
496524
if (isOAuthToken) {
@@ -555,7 +583,17 @@ function resolveAnthropicTransportOptions(
555583
options: AnthropicTransportOptions | undefined,
556584
apiKey: string,
557585
): AnthropicTransportOptions {
558-
const baseMaxTokens = options?.maxTokens || Math.min(model.maxTokens, 32_000);
586+
const baseMaxTokens = resolveAnthropicMessagesMaxTokens({
587+
modelMaxTokens: model.maxTokens,
588+
requestedMaxTokens: options?.maxTokens,
589+
});
590+
if (baseMaxTokens === undefined) {
591+
throw new Error(
592+
`Anthropic Messages transport requires a positive maxTokens value for ${model.provider}/${model.id}`,
593+
);
594+
}
595+
const reasoningModelMaxTokens =
596+
resolvePositiveAnthropicMaxTokens(model.maxTokens) ?? baseMaxTokens;
559597
const resolved: AnthropicTransportOptions = {
560598
temperature: options?.temperature,
561599
maxTokens: baseMaxTokens,
@@ -583,7 +621,7 @@ function resolveAnthropicTransportOptions(
583621
}
584622
const adjusted = adjustMaxTokensForThinking({
585623
baseMaxTokens,
586-
modelMaxTokens: model.maxTokens,
624+
modelMaxTokens: reasoningModelMaxTokens,
587625
reasoningLevel: options.reasoning,
588626
customBudgets: options.thinkingBudgets,
589627
});

‎src/agents/pi-embedded-runner-extraparams.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1317,6 +1317,36 @@ describe("applyExtraParamsToAgent", () => {
13171317
expect(calls[0]?.transport).toBe("websocket");
13181318
});
13191319

1320+
it("preserves maxTokens: 0 in shared extra params for providers that forward it", () => {
1321+
const { calls, agent } = createOptionsCaptureAgent();
1322+
const cfg = {
1323+
agents: {
1324+
defaults: {
1325+
models: {
1326+
"openai/gpt-5": {
1327+
params: {
1328+
maxTokens: 0,
1329+
},
1330+
},
1331+
},
1332+
},
1333+
},
1334+
};
1335+
1336+
applyExtraParamsToAgent(agent, cfg, "openai", "gpt-5");
1337+
1338+
const model = {
1339+
api: "openai-responses",
1340+
provider: "openai",
1341+
id: "gpt-5",
1342+
} as Model<"openai-responses">;
1343+
const context: Context = { messages: [] };
1344+
void agent.streamFn?.(model, context, {});
1345+
1346+
expect(calls).toHaveLength(1);
1347+
expect(calls[0]?.maxTokens).toBe(0);
1348+
});
1349+
13201350
it("defaults Codex transport to auto (WebSocket-first)", () => {
13211351
const { calls, agent } = createOptionsCaptureAgent();
13221352

0 commit comments

Comments
 (0)