You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(core): retry forced tool use rejected by Claude thinking - #2510
agent.act and exploring agent.assert retry with automatic tool choice when a gateway returns Anthropic's HTTP 400 error Thinking may not be enabled when tool_choice forces tool use. The retry keeps manual extended thinking enabled and ignores 5xx retry chains that quote the refusal.
The remembered auto mode has two scopes. A refusal that names the model (Claude Fable 5.1, Muse Spark) covers every later step on that model. Any other refusal or downgrade covers only later steps whose providerOptions match exactly, and a step with no providerOptions is a scope of its own.
Why
The forced-choice fallback missed Anthropic's manual-thinking wording, so the step failed with MODEL_PROVIDER_FAILED even though Claude could continue under auto.
Remembering that refusal on the bare model object would force sibling agents sharing the same model constant into auto even when their providerOptions leave thinking off. The same holds when thinking is a setting of the model itself (AI SDK defaultSettingsMiddleware): the agent that inherits it sends no options, and a sibling whose options turn thinking off must keep forced tool calls. A refusal that names the model is not about options, so scoping it per option set would cost one rejected request per agent where main costs one per model.
Adaptive thinking has a separate behavior. On models that accept a forced tool call, Claude can start its response with that call and skip thinking. A successful response takes no error-driven retry. Anthropic's tool-choice documentation
How it works
FORCED_CHOICE_PATTERNS adds Anthropic's manual-thinking HTTP 400 sentence (tool-choice.ts:21). MODEL_WIDE_PATTERNS lists the refusals that name the model (tool-choice.ts:33).
forcedToolChoiceRefusal, which replaces isForcedToolChoiceRejected, walks the full cause and lastError chain up to depth 8. It returns undefined if any wrapped error carries a non-4xx HTTP status, so a statusless AI_RetryError wrapping an HTTP 502 never triggers the auto fallback. Otherwise it returns 'model' for a model-wide match and 'options' for any other match (tool-choice.ts:103).
rememberAutoToolChoice and prefersAutoToolChoice keep a WeakMap per model instance. It holds a model-wide flag and a set of providerOptions keys, with '' for no options (tool-choice.ts:136). A key is the JSON form of the options with sorted keys, so toJSON applies. Options with no JSON form, such as a bigint an executor passes directly, get no key: the step still retries with auto, and nothing is remembered (tool-choice.ts:174).
LoopRun reads the memory at construction (tool-loop.ts:311). freeToolChoiceRetry records the refusal's scope, and 'options' for a prose reply under a forced choice (tool-loop.ts:656). noticeToolChoiceDowngrade records 'options', because the AI SDK's Anthropic provider downgrades both for models that reject forced use and for manual thinking, and its warning does not say which (tool-loop.ts:673).
Verified
Ran it locally: yes
The built CLI, with a scripted anthropic.messages model, ran on main (7c1b2b258) and on this branch (d00f974b). The model throws the Anthropic 400 errors. The table lists the tool choice of each request.
shared-model.e2e.ts: thinking comes from defaultSettingsMiddleware. The default agent sends no options, and lean sends thinking: { type: 'disabled' } with maxModelCalls: 1.
fable.e2e.ts: the model refuses every forced choice with Fable 5.1's message. Agents low (effort: 'low'), high (effort: 'high'), and default (no options) run in that order.
✓ |verify| tests-verify-2510/shared-model.e2e.ts (2 tests) 331ms ai 240 tokens
✓ |verify| tests-verify-2510b/fable.e2e.ts (3 tests) 519ms ai 360 tokens
Main
This PR
Inherited manual thinking + forced tool choice
required, MODEL_PROVIDER_FAILED
required, then auto with thinking intact, passes
Sibling that turns thinking off (maxModelCalls: 1)
Skipped after step 1 failed
tool:complete_step, passes
Fable-style refusal across three option sets
required, then auto ×3: one rejected request
required, then auto ×3: one rejected request
One more run covers options whose own field is a bigint and whose toJSON writes it as text, such as a 64-bit request id. Config resolution accepts them. The model answers the manual-thinking 400, and the test runs two agent.act steps. On 2e10b94b, the first step failed after one required call with ACTION_FAILED: Do not know how to serialize a BigInt. On d00f974b the calls are required, auto, auto, and the test passes.
Unit tests in packages/e2e/tests/unit/tool-loop-tool-choice.test.ts cover the following:
required and tool:complete_step retries with providerOptions kept
shared-model isolation with explicit options and with model-level thinking
one rejection across option sets for a model-wide refusal
the forcedToolChoiceRefusal scope across gateway wrappers, 502 AI_RetryError chains, and unrelated thinking 400s
the options scope of a downgrade warning and of a prose reply under a forced choice. Each test fails when its path remembers the whole model.
scope keys from the JSON form of providerOptions (toJSON applied), and options with no JSON form, which are retried but not remembered
On 84f333309 the model-level thinking test and the model-wide test fail. Live gateway behavior is still unverified: no model key was available.
Summary by CodeRabbit
Bug Fixes
Agent turns now retry with automatic tool choice when a model rejects forced tool use, including Claude’s manual extended-thinking restriction, while retaining thinking settings.
Automatic tool choice applies to the affected model or matching provider options, allowing unrelated configurations to continue using forced tool calls.
Documentation
Clarified which models reject forced tool calls and how fallback behavior applies to later steps.
Refusal detection and preference scope packages/core/src/agent/model/tool-choice.ts
The detector recognizes Anthropic’s manual-thinking error and checks wrapped errors. Automatic tool-choice preferences use a model-wide scope or a canonicalized provider-options scope.
Tool-loop preference and retry packages/core/src/agent/tool-loop.ts
The tool loop uses the model and effective provider options to select the initial mode. It records an automatic preference after a forced choice is rejected, skipped, or downgraded.
Retry validation and documentation packages/e2e/tests/helpers/fake-loop-model.ts, packages/e2e/tests/unit/tool-loop-tool-choice.test.ts, docs/models.mdx, .changeset/anthropic-thinking-tool-choice.md
The fake model records provider options. Tests cover retries, provider-option scopes, and refusal classification. The documentation describes retained thinking settings and later steps that use auto; the changeset declares a patch release.
Possibly related issues
e2e-inc/e2e#2383: This PR retries forced tool choices that conflict with Claude manual thinking. It does not suppress the SDK downgrade warning described in the issue.
Suggested reviewers:kdy1, nathanwalker
Change: Bug fix
Merge Risk: Minimal · up to d00f9
The change retries forced tool use with automatic tool choice when Claude rejects it under manual thinking, and it remembers that choice per model or per set of provider options. No actionable merge-blocking risk was identified.
Security architecture risk: Low · up to d00f9
The fallback keeps the same permitted actions and usually limits its effect to requests with matching settings. The new memory has no size limit for a long-lived shared configuration, and unusually complex settings can interrupt recovery.
Retained concerns
Trivial · reliability · observed: The old cache kept one membership bit per model instance. The new cache keeps the complete canonical JSON for every distinct option scope learned on that instance, with no size limit or eviction. A long-lived instance reused with changing configurations can accumulate request-option data after the originating steps finish. The weak key limits retention to the model object's lifetime, not the lifetime of each configuration.
Trivial · reliability · inferred: Only the first serialization is guarded. If deeply nested options serialize successfully but exhaust the stack during recursive sorting, key generation can abort loop construction or escape the refusal handler before the automatic-choice retry. Capability memory can therefore turn a recoverable refusal into a step failure instead of skipping memoization.
Security review details
Security Blast Radius
inferred — Preference changes can affect later callers in the same process that reuse the identical model object. A model-wide refusal affects all option sets on that object, as qualifying refusals did on the base; other updates affect only callers whose canonical option keys match. This identity boundary is not a tenant boundary.
Trust Boundaries and Controls
observed — Provider or gateway error text can influence request mode through a bounded error-chain scan. A numeric non-4xx status on the traversed chain vetoes classification, but a matching record need not supply a status. The resulting preference governs tool selection mode, not which tools may be offered.
Resilience and Maintainability Implications
observed — The cache can be updated by a warning on a successful provider turn or before a retry has completed. There is no outcome-based rollback; the state records an observed compatibility signal, not proof that the step succeeded.
Hardening Proposals
proposed — Bound the number and size of remembered option scopes, avoid retaining raw option values where practical, and make all key-generation failures skip memoization without blocking the current step's fallback.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
For d00f974b0642, the pull request's head, measured merged into its base.
🔴 1 case costs more.
Repeatability: two builds of the head agree in every case, 10 trials each.
Base 7c1b2b2589cc, head c765091acbb1.
A direction is reported only when the trial ranges of base and head do not overlap and the change is at least 0.5%.
Case
Mode
Base
Head
Change
Direction
Base spread
Head spread
mobile/project-snapshot
jitless
141,055,527
143,440,495
+1.691%
🔴 higher (ranges do not overlap)
0.047%
0.113%
3 unchanged cases
Case
Mode
Base
Head
Change
Direction
Base spread
Head spread
redact/screen-text
jitless
789,701
789,683
-0.002%
⚪ same (ranges overlap, change under 0.5%)
0.035%
0.028%
redact/fragments
jitless
467,945,363
467,944,034
0%
⚪ same (ranges overlap, change under 0.5%)
0.030%
0.013%
locate/catalog
jitless
51,699,329
51,699,826
+0.001%
⚪ same (ranges overlap, change under 0.5%)
0.017%
0.014%
How this is measured
Instructions per iteration: the difference between a run of N and of 3N iterations, divided by 2N, so startup, loading, warmup, and compilation cancel. 5 trial(s) per case and checkout. Lower is better.
Machine: linux x64, AMD EPYC, Node v26.13.1, valgrind-3.22.0, ASLR off.
act completes Apple Pay Billing Address (skipped: the CI simulator's Apple Pay sheet skips the billing-address step, so the scenario cannot be completed there)
control inventory › a label query resolves a labeled text field
17.2s
🟢
control inventory › a labeled field answers name, display value, value reads, fill, and clear
16.7s
🟢
control inventory › a placeholder query and attribute reads find the field
5.3s
🟢
control inventory › getAttribute reads the label, resource id, and class an Appium suite asks for
5.5s
🟢
control inventory › a secure field takes a fill and denies value reads
7.9s
🟢
control inventory › press sends a character and Enter through the soft keyboard
9.2s
🟢
control inventory › a field autofocuses on mount and focus() moves the focus
10.5s
🟢
control inventory › toBeFocused follows the focus
8.1s
🟢
control inventory › a switch checks, unchecks, and reports its state
8.8s
🟢
control inventory › checkbox and radio roles answer getByRole, and a checkbox toggles by tap
8.5s
🟢
control inventory › checkbox and radio roles check, uncheck, and report their state
9.8s
🟢
control inventory › a radio group reports the checked option
8.1s
🟢
control inventory › buttons report disabled, enabled, and a state that arrives later
8.0s
🟢
control inventory › a display: none element is absent rather than hidden, its visible twin attached
7.3s
🟢
control inventory › a header answers its accessible name
5.2s
🟢
control inventory › a tab row answers count, all, texts, filters, positions, and switching
7.0s
🟢
control inventory › a list answers counts, list-form text, reads, and boxes in order
6.9s
⏭️
control inventory › a row contains its texts (skipped: React Native flattens a plain View out of the accessibility tree on both platforms: XCTest and the Android helper report a View with a testID as a leaf beside its children, so filter({ has }) and a query scoped to it match nothing; only Sc…)
🟢
control inventory › a long press lands as one
8.5s
🟢
control inventory › tap({ count: 3 }) lands three presses
8.2s
🟢
control inventory › pointer verbs land at the point asked for
9.3s
🟢
control inventory › an ambiguous locator fails at once
5.7s
🟢
control inventory › screenshot, restart, and clearState reopen the app on its home list
12.4s
🟢
refusals › verbs a device never declares are refused before the engine
2ms
🟢
refusals › keys the soft keyboard cannot send are refused by the engine
203ms
🟢
refusals › a missing locator fails as not found once its timeout passes
1.1s
🟢
tests/device-fixture.e2e.ts · 15 passed
2m 20s
🟢
device fixture › setAppearance flips the color scheme the app reads
19.6s
🟢
device fixture › setOrientation rotates the window and viewport dimensions
8.7s
🟢
device fixture › the clipboard reads back what was written
5.8s
🟢
device fixture › home leaves the app, openApp brings it back where it was
8.2s
🟢
device fixture › closeApp then openApp relaunches on the home list
9.3s
🟢
device fixture › closeApp leaves the next commands on the same device
14.2s
🟢
device fixture › foregroundApp after closeApp reports the closed session as APP_NOT_OPEN
5.8s
🟢
device fixture › openLink opens the scenario a deep link names
13.8s
🟢
device fixture › isAppInstalled finds the app under test and no app that is absent
6.5s
🟢
device fixture › uninstallApp removes the app until installApp puts it back
10.4s
🟢
device fixture › device.back pops the scenario
5.9s
🟢
device fixture › unstable_raw reaches the test session through the raw driver
4.7s
🟢
device fixture › setLocation and clearLocation change what the app reads
9.9s
🟢
device fixture › enrollBiometrics and setBiometrics answer a biometric prompt
11.5s
🟢
device fixture › pressButton is refused on an iOS simulator
5.5s
🟢
tests/device.e2e.ts · 7 passed
1m 22s
🟢
permissions all grants the microphone without a system dialog
12.6s
🟢
sequential onboarding echoes the exact values
25.4s
🟢
isKeyboardShown follows the keyboard up and through a dismissal
7.8s
🟢
a control under the keyboard reads hidden and refuses a tap until the keyboard is dismissed
10.0s
🟢
a shake is sent without an error and leaves the screen readable
5.3s
🟢
onboarding rejects a malformed email before advancing
9.5s
🟢
dismissing the keyboard over choice controls leaves them as they were
11.0s
🟢
tests/flows-lists.e2e.ts · 7 passed
4m 9s
🟢
infinite scroll reaches the target item
35.2s
🟢
product catalog adds exactly two of the right variant
10.3s
🟢
gestures: long-press, then swipe left
8.7s
🟢
sticky chrome: accept below the fold, then continue
12.5s
🟢
async states: load, pull to refresh, claim through the toast
12.2s
🟢
huge virtualized list reaches row 512
2m 37s
🟢
web view coupon form applies the code shown on the page
12.6s
🟢
tests/flows.e2e.ts · 7 passed
1m 9s
🟢
text inputs unlock the submit button
12.2s
🟢
filled text inputs report their values
10.5s
🟢
modal flow confirms through the native alert
9.7s
🟢
bottom tabs act inside the last tab
7.4s
🟢
error recovery retries, then confirms the delete
9.5s
🟢
choice controls place the exact order
7.7s
🟢
debounced search selects the target once results arrive
11.5s
🟢
tests/login-form.e2e.ts · 3 passed
43.7s
🟢
login form › rejects a malformed email
12.4s
🟢
login form › rejects an unknown account
12.6s
🟢
login form › signs in and logs out
18.7s
🟢
tests/scroll-to.e2e.ts · 2 passed
2m 51s
🟢
screen.scrollTo reaches the last row of the list and comes back to the first
control inventory › a label query resolves a labeled text field
16.8s
🟢
control inventory › a labeled field answers name, display value, value reads, fill, and clear
10.8s
🟢
control inventory › a placeholder query and attribute reads find the field
4.8s
🟢
control inventory › getAttribute reads the label, resource id, and class an Appium suite asks for
4.3s
🟢
control inventory › a secure field takes a fill and denies value reads
6.2s
🟢
control inventory › press sends a character and Enter through the soft keyboard
7.4s
🟢
control inventory › a field autofocuses on mount and focus() moves the focus
6.4s
🟢
control inventory › toBeFocused follows the focus
6.2s
🟢
control inventory › a switch checks, unchecks, and reports its state
6.5s
🟢
control inventory › checkbox and radio roles answer getByRole, and a checkbox toggles by tap
6.6s
🟢
control inventory › checkbox and radio roles check, uncheck, and report their state
7.0s
🟢
control inventory › a tab role answers getByRole
3.3s
🟢
control inventory › a radio group reports the checked option
6.3s
🟢
control inventory › buttons report disabled, enabled, and a state that arrives later
6.5s
🟢
control inventory › a display: none element is absent rather than hidden, its visible twin attached
4.8s
🟢
control inventory › a header answers its accessible name
3.3s
🟢
control inventory › a tab row answers count, all, texts, filters, positions, and switching
4.9s
🟢
control inventory › a list answers counts, list-form text, reads, and boxes in order
4.9s
⏭️
control inventory › a row contains its texts (skipped: React Native flattens a plain View out of the accessibility tree on both platforms: XCTest and the Android helper report a View with a testID as a leaf beside its children, so filter({ has }) and a query scoped to it match nothing; only Sc…)
🟢
control inventory › a long press lands as one
6.7s
🟢
control inventory › a double tap lands inside the 300 ms window
6.1s
🟢
control inventory › tap({ count: 3 }) lands three presses
5.6s
🟢
control inventory › an ambiguous locator fails at once
4.8s
🟢
control inventory › screenshot, restart, and clearState reopen the app on its home list
5.9s
🟢
refusals › verbs a device never declares are refused before the engine
2ms
🟢
refusals › keys the soft keyboard cannot send are refused by the engine
1.3s
🟢
refusals › a missing locator fails as not found once its timeout passes
1.1s
🟢
tests/device-fixture.e2e.ts · 14 passed
1m 26s
🟢
device fixture › setOrientation rotates the window and viewport dimensions
4.4s
🟢
device fixture › home leaves the app, openApp brings it back where it was
3.8s
🟢
device fixture › foregroundApp sees the home screen after home()
3.0s
🟢
device fixture › closeApp then openApp relaunches on the home list
5.2s
🟢
device fixture › closeApp leaves the next commands on the same device
5.5s
🟢
device fixture › foregroundApp after closeApp reports the closed session as APP_NOT_OPEN
3.9s
🟢
device fixture › openLink opens the scenario a deep link names
4.1s
🟢
device fixture › isAppInstalled finds the app under test and no app that is absent
3.5s
🟢
device fixture › uninstallApp removes the app until installApp puts it back
6.1s
🟢
device fixture › device.back pops the scenario
4.0s
🟢
device fixture › unstable_raw reaches the test session through the raw driver
2.9s
🟢
device fixture › setNetwork and setAirplaneMode change what the app sees
14.8s
🟢
device fixture › setLocation and clearLocation change what the app reads
17.4s
🟢
device fixture › pressButton shows the volume panel on Android
7.3s
🟢
tests/device.e2e.ts · 8 passed
51.1s
🟢
permission prompt › allowing the system dialog enables the microphone
5.3s
🟢
permission prompt › a denied prompt recovers once the permission is granted outside
10.7s
🟢
permissions all grants the microphone without a system dialog
5.9s
🟢
sequential onboarding echoes the exact values
9.2s
🟢
a shake is sent without an error and leaves the screen readable
4.3s
🟢
a lock and an unlock both complete and leave the app readable
4.4s
🟢
onboarding rejects a malformed email before advancing
5.1s
🟢
dismissing the keyboard over choice controls leaves them as they were
6.1s
🟢
tests/flows-lists.e2e.ts · 7 passed
3m 2s
🟢
infinite scroll reaches the target item
27.4s
🟢
product catalog adds exactly two of the right variant
8.1s
🟢
gestures: long-press, then swipe left
7.3s
🟢
gestures: double-tap completes the flow
9.1s
🟢
sticky chrome: accept below the fold, then continue
10.2s
🟢
async states: load, pull to refresh, claim through the toast
11.4s
🟢
huge virtualized list reaches row 512
1m 49s
🟢
tests/flows.e2e.ts · 7 passed
46.2s
🟢
text inputs unlock the submit button
5.6s
🟢
filled text inputs report their values
5.1s
🟢
modal flow confirms through the native alert
8.4s
🟢
bottom tabs act inside the last tab
6.1s
🟢
error recovery retries, then confirms the delete
8.0s
🟢
choice controls place the exact order
5.3s
🟢
debounced search selects the target once results arrive
7.8s
🟢
tests/login-form.e2e.ts · 3 passed
25.2s
🟢
login form › rejects a malformed email
6.6s
🟢
login form › rejects an unknown account
6.6s
🟢
login form › signs in and logs out
12.1s
🟢
tests/scroll-to.e2e.ts · 2 passed
1m 5s
🟢
screen.scrollTo reaches the last row of the list and comes back to the first
39.9s
🟢
locator.scrollTo scrolls the list it names
24.9s
🟢
tests/smoke.e2e.ts · 1 passed
4.5s
🟢
home lists the scenarios and opens one
4.5s
Tested by e2e 0.25.0 · 10m 9s · android-emulator · run artifacts
github-actionsBot
added
size:L
Up to 499 changed lines, not counting tests, fixtures, translated docs, or the lockfile
and removed
Ready for Human Review
Green, conflict-free, every thread handled. Waiting on a maintainer.
size:S
Up to 29 changed lines, not counting tests, fixtures, translated docs, or the lockfile
labels
Nov 29, 2026
The reason will be displayed to describe this comment to others. Learn more.
Automated review (AI triage pass), not yet read by a maintainer.
Reviewed 84f333309. Adds Anthropic's manual-thinking refusal to the existing forced-tool-choice fallback, stops a 5xx retry chain that quotes the refusal from triggering it, and scopes the remembered auto mode per model + providerOptions. Correct, well-contained, tests fail when the fix is reverted.
Not a heuristic in the policy sense: Anthropic documents that forced tool_choice is incompatible with manual extended thinking, and the 400 body carries no structured code beyond invalid_request_error, so the message match is the same signal main already uses for Fable 5.1 / DeepSeek / Muse Spark (tool-choice.ts:21). Detection is tight: exact sentence, 4xx only, and any non-4xx status anywhere in the cause/lastError chain vetoes the match (tool-choice.ts:99).
Verified locally: targeted suite passes (24/24). Mutation checks, each rebuilt core and re-ran the file:
drop the new pattern: 4 new tests fail
remember auto globally (ignore options): the shared-model scoping test fails
old early return true on first match: the 502 AI_RetryError test fails
only check status on the matched node (break instead of return false): same test fails
Nits
tool-choice.ts:143-146 - the catch returns '*', which would widen a scoped refusal to every agent on the model, the exact leak this PR removes. providerOptions is JSON by type (it goes over HTTP), so the branch is dead; drop the try/catch instead of keeping a fallback that points the wrong way.
A model that rejects forced choice outright (Fable 5.1) now pays one extra 400 per distinct providerOptions set instead of one per model. Negligible, but the docs line "Later steps on that model with the same provider options start with auto" (models.mdx:175) reads as if steps without options are also scoped, while a refusal with no options applies to all ('*', tool-choice.ts:127). Fine as is for users; mention only if touching it again.
For the maintainer
Error-driven vs proactive: the loop could start in auto when providerOptions.anthropic.thinking.type === 'enabled' and skip the first 400. The PR keeps the generic error-driven path, which also covers gateway/Bedrock/Vertex option shapes. Reasonable; say if you want the proactive shortcut too.
CI: runner tests and mobile jobs still pending at review time; everything finished so far is green.
[claude-fable-5-2] responding on behalf of michal-e2e
Answers to the review of 84f3333 and to the retained concerns in the CodeRabbit summary. Nothing is pushed for them.
Nit 1, the catch in providerOptionsScope. Half right. The fallback does widen: a key that cannot be serialized is remembered as '*'. The branch is not dead, though: ProviderOptions values are unknown (types.ts:1941). A 10n in agents.<name>.providerOptions stops the run at config load, but the providerOptions of createToolLoopExecutor are not part of the config digest. In two runs of the built CLI at this head against a local stand-in for the Anthropic API, a 10n under a key the Anthropic provider does not read made the next request of a sibling agent on the same model object carry auto; with 10 in its place it carried tool:complete_step. Dropping the try/catch trades the widening for a TypeError: by reading, rememberAutoToolChoice would throw in the retry path, and prefersAutoToolChoice in the LoopRun constructor once a scope is remembered for the model. The author decides between keeping the fallback, dropping it, and remembering nothing when the key cannot be built.
Nit 2, docs/models.mdx:175. Correct, and left as written, as the review suggests. The sentence is read again if the scope code changes.
Proactive auto under enabled thinking. Not added: the pull request keeps the error-driven path. One fact for the maintainer's call: @ai-sdk/anthropic 4.0.111 already sends auto in place of a forced choice under manual thinking and warns, and the loop handles that warning, so the shortcut would save the first 400 only where the provider does not downgrade the choice itself, as on the gateway path.
CI. Finished since the review: on 84f3333, 45 checks pass and 3 are skipped, the four required gates among the passes.
CodeRabbit, a refusal with no local options. True as described, and it is the stated rule (tool-choice.ts:113-120): a refusal with no providerOptions is remembered for the whole model object. In the same runs, an agent with no options that got the manual-thinking 400 from the stand-in passed after the retry, and the next request of a sibling with thinking: { type: 'disabled' } on that model object carried auto. This needs thinking switched on outside e2e's options. The author decides whether a refusal with no options keeps the wildcard.
CodeRabbit, keys with no bound. True as described: one string per distinct option set that was refused or downgraded, per live model object. The options are set per agent entry or per executor, so the set grows with the config, not with the steps. No bound is added here; the author decides whether one is wanted.
CodeRabbit, the hardening proposal. Its three parts are the three points above (serialization failure, the wildcard for omitted options, the bound); each is with the author as stated there.
A forced-tool-choice refusal under no providerOptions was remembered as
'*', which matched every option set on the model. When thinking comes from
the model itself (AI SDK defaultSettingsMiddleware), an agent that sends
explicit options turning it off then also started in auto, and with a
one-call budget its prose reply failed the step with STEP_NO_CONCLUSION.
Absent options now get their own scope key, so only steps with the same
options (or none) start in auto. The try/catch around the key is gone:
providerOptions are JSON values by type, and its fallback widened the
scope to the whole model.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Scoping the remembered auto mode by providerOptions made a model that never
takes a forced choice (Claude Fable 5.1, Muse Spark) refuse once per option
set: three agents with different options cost three rejected requests where
main cost one.
forcedToolChoiceRefusal (replacing isForcedToolChoiceRejected) now says what
a refusal depends on. A message that names the model ("not supported for
this model", "only auto is supported") is remembered for the whole model;
the manual-thinking refusal, the other patterns, and provider downgrades
stay scoped to the step's providerOptions, since the AI SDK's Anthropic
provider downgrades for manual thinking too and its warning does not say
which cause applied. The loop's JSDoc and docs/models.mdx describe the two
scopes instead of a per-model memory.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
Architecture findings (1)
Advisory architecture findings (1)
Trivial — The patch removes the named export isForcedToolChoiceRejected from a module exposed by the package’s ./lib/* mapping. A consumer that imports that symbol through the mapped path can fail during module loading after the upgrade. No downstream consumer was confirmed.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: defaults
Review profile: CHILL
Plan: Advanced
Run ID: d4a41d1d-642f-4df7-aa25-7907b1ad3619
Commits
Reviewing files that changed from the base of the PR and between 84f3333 and 2e10b94.
Files skipped from review as they are similar to previous changes: 1
docs/models.mdx
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
…ions
The scope key canonicalized providerOptions by walking their own fields,
which dropped a value's toJSON. An option whose own field is a bigint but
whose JSON form is text (a 64-bit id) passes config resolution, then made
JSON.stringify throw while the loop recorded a forced-choice refusal, so
the step failed with ACTION_FAILED instead of retrying with auto. Two
settings told apart only by toJSON also shared one key.
The key now comes from the options' JSON form, with keys sorted. Options
with no JSON form (a bigint or a cycle an executor passes directly) get no
key: the refusal is still retried, just not remembered.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The downgrade warning and a prose reply under a forced choice now remember
auto only for the step's providerOptions, but no test told that apart from
remembering it for the whole model: both paths passed with 'model' too.
Each new test runs a thinking agent and a lean agent on one model and
fails when its path widens the scope.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
Architecture findings (2)
Advisory architecture findings (2)
Trivial — The old cache kept one membership bit per model instance. The new cache keeps the complete canonical JSON for every distinct option scope learned on that instance, with no size limit or eviction. A long-lived instance reused with changing configurations can accumulate request-option data after the originating steps finish. The weak key limits retention to the model object's lifetime, not the lifetime of each configuration.
Trivial — Only the first serialization is guarded. If deeply nested options serialize successfully but exhaust the stack during recursive sorting, key generation can abort loop construction or escape the refusal handler before the automatic-choice retry. Capability memory can therefore turn a recoverable refusal into a step failure instead of skipping memoization.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: defaults
Review profile: CHILL
Plan: Advanced
Run ID: bccb3b09-e67a-4361-91fe-2b2faeb2b06f
Commits
Reviewing files that changed from the base of the PR and between 2e10b94 and d00f974.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Note
This text was drafted with AI and posted after human approval.
Harness: T3 Code
AI agents: coordinator: Claude Opus 5.5 (claude-opus-5-5), reviewer: GPT-6.2 Astra (gpt-6.2-astra), reviewer: GPT-6.2 Sol (gpt-6.2-sol), reviewer: Claude Opus 5.5 (claude-opus-5-5), reviewer: Claude Sonnet 5.5 (claude-sonnet-5-5)
Verdict: Approve
This review approves the pull request. The P3 items are optional and do not block the merge.
Live check on Vercel AI Gateway (gateway('anthropic/claude-sonnet-4.5'), manual thinking, built CLI on the testbed): the gateway does not return the HTTP 400. It downgrades the forced choice to auto itself and sends a toolChoice warning, on gateway(), /v1/messages, and /v1/chat/completions alike. So the new 400 retry path was not reached live; only the downgrade path was. On that path, three agents shared one model (thinking enabled, thinking disabled, no options). On main, the second and third agents were sent auto. On this branch they kept required, and the thinking agent's next step started with auto. The test passed on both.
Retry agent turns with automatic tool choice when Anthropic rejects forced tool use with manual extended thinking, keeping that fallback scoped to the model's provider options.
The reason will be displayed to describe this comment to others. Learn more.
P3 · Non-blocking · The changeset does not say that downgrade and prose-reply memory is now per providerOptions
Optional. This does not block the merge.
Before this change, a provider downgrade (noticeToolChoiceDowngrade, packages/core/src/agent/tool-loop.ts:673) or a prose reply under a forced choice (tool-loop.ts:649-650) put the whole model in auto. Now each distinct providerOptions set learns it again.
Trigger: several agents share one model that always downgrades forced choice, for example Claude Sonnet 5.5 through @ai-sdk/anthropic, with different providerOptions. A scripted run with agents default (no options) and low ({ anthropic: { effort: 'low' } }), steps default, low, default, gave these tool choices:
main: required, auto, auto, auto
this branch: required, auto, required, auto, auto
The extra call is a billed turn when the model answers in prose. A DeepSeek-style options refusal also costs one more rejected request per option set.
docs/models.mdx describes the trade-off. The release note reads as if only the new manual-thinking refusal is scoped, so users who share one model across agents get no notice of the added turn.
The reason will be displayed to describe this comment to others. Learn more.
P3 · Non-blocking · The per-model option set grows without a bound in a long-lived process
Optional. This does not block the merge.
rememberAutoToolChoice adds the full canonical JSON of every refused or downgraded providerOptions set to a Set that lives as long as the model object (AUTO_TOOL_CHOICE, line 136). No path removes an entry, and line 165 still adds option keys after memory.model is true.
Trigger: a long-lived host (openHost, e2e mcp, createAgent) reuses one model constant while it varies a per-session option such as gateway.user. A probe with 100 distinct gateway.user values and a downgrading provider kept one marker on main and 100 serialized option strings on this branch. The memory grows with the number of distinct option sets, not with the number of steps, so the impact is small.
The reason will be displayed to describe this comment to others. Learn more.
Automated review (AI triage pass), not yet read by a maintainer.
Reviewed d00f974b0. Since 84f333309 the refusal memory splits in two: a refusal that names the model (Fable 5.1, Muse Spark) puts the whole model in auto, while every other refusal, a downgrade warning, and a prose reply apply only to the same providerOptions. The key is now canonical JSON with toJSON applied. Correct, and the tests fail when the change is reverted.
Earlier nits:
The catch that returned '*' is fixed. Options with no JSON form are now not remembered (tool-choice.ts:157-158, tool-choice.ts:173-181), so a refusal can no longer spread to sibling agents.
The docs wording is fixed. models.mdx:175-179 now covers both cases and matches the code.
The delta is sound. MODEL_WIDE_PATTERNS (tool-choice.ts:33-36) match only messages that name the model. A downgrade warning does not say why the provider sent auto, so recording it per options (tool-loop.ts:673) is the safe choice: if the model was the cause, it costs one warned call per options set, not a failure.
Verified locally: the targeted suite passes (31/31). Mutation checks, each with core rebuilt:
Treat every refusal as options: 3 tests fail, including "remembers a refusal that names the model for agents with other providerOptions".
Remember the downgrade for the whole model: "remembers a downgrade only for the providerOptions it came with" fails.
CI is green.
Nits
The changeset (.changeset/anthropic-thinking-tool-choice.md) does not say that DeepSeek V4 refusals, downgrades, and prose replies are now remembered per providerOptions, not per model. This matches kdy1's P3; it is optional.
For the maintainer
DeepSeek V4 refuses a forced choice because it thinks by default, and that refusal now counts as options. Each distinct options set on a shared DeepSeek model pays one extra 400 before it falls back. In return, an agent that turns thinking off keeps forced calls. Fine as long as that trade is intended.
kdy1 approved d00f974b0 with two P3s: the changeset wording (nit 1 above) and the unbounded per-model options set. That set holds one entry per distinct refused options set and lives only as long as the model object, so it is fine as is.
* docs(pt): bring nine guide pages back in line with English
Picks up the English changes the pt guides missed: the experimental
warnings on the Electron and desktop engines (e2e-inc#2540, e2e-inc#2541), driving a
Mac app with @e2e-dev/core (e2e-inc#2499), expect(electron) and waitForURL
(e2e-inc#2439), the ffmpeg download (e2e-inc#2502), the desktop placeholder lines
(e2e-inc#2529), forced tool use under extended thinking (e2e-inc#2510), and e2e-inc#2448's
new descriptions and links. Adds three glossary rows.
* docs(pt): pick up e2e-inc#2470, e2e-inc#2504, e2e-inc#2509, and e2e-inc#2547 in the guides
* docs(pt): pick up e2e-inc#2555 in electron
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
e2e teamOpened by the e2e teamReady for Human ReviewGreen, conflict-free, every thread handled. Waiting on a maintainer.size:LUp to 499 changed lines, not counting tests, fixtures, translated docs, or the lockfile
3 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
agent.actand exploringagent.assertretry with automatic tool choice when a gateway returns Anthropic's HTTP 400 errorThinking may not be enabled when tool_choice forces tool use.The retry keeps manual extended thinking enabled and ignores 5xx retry chains that quote the refusal.The remembered
automode has two scopes. A refusal that names the model (Claude Fable 5.1, Muse Spark) covers every later step on that model. Any other refusal or downgrade covers only later steps whoseproviderOptionsmatch exactly, and a step with noproviderOptionsis a scope of its own.Why
The forced-choice fallback missed Anthropic's manual-thinking wording, so the step failed with
MODEL_PROVIDER_FAILEDeven though Claude could continue underauto.Remembering that refusal on the bare model object would force sibling agents sharing the same model constant into
autoeven when theirproviderOptionsleave thinking off. The same holds when thinking is a setting of the model itself (AI SDKdefaultSettingsMiddleware): the agent that inherits it sends no options, and a sibling whose options turn thinking off must keep forced tool calls. A refusal that names the model is not about options, so scoping it per option set would cost one rejected request per agent where main costs one per model.Adaptive thinking has a separate behavior. On models that accept a forced tool call, Claude can start its response with that call and skip thinking. A successful response takes no error-driven retry. Anthropic's tool-choice documentation
How it works
FORCED_CHOICE_PATTERNSadds Anthropic's manual-thinking HTTP 400 sentence (tool-choice.ts:21).MODEL_WIDE_PATTERNSlists the refusals that name the model (tool-choice.ts:33).forcedToolChoiceRefusal, which replacesisForcedToolChoiceRejected, walks the fullcauseandlastErrorchain up to depth 8. It returnsundefinedif any wrapped error carries a non-4xx HTTP status, so a statuslessAI_RetryErrorwrapping an HTTP 502 never triggers theautofallback. Otherwise it returns'model'for a model-wide match and'options'for any other match (tool-choice.ts:103).rememberAutoToolChoiceandprefersAutoToolChoicekeep aWeakMapper model instance. It holds a model-wide flag and a set ofproviderOptionskeys, with''for no options (tool-choice.ts:136). A key is the JSON form of the options with sorted keys, sotoJSONapplies. Options with no JSON form, such as abigintan executor passes directly, get no key: the step still retries withauto, and nothing is remembered (tool-choice.ts:174).LoopRunreads the memory at construction (tool-loop.ts:311).freeToolChoiceRetryrecords the refusal's scope, and'options'for a prose reply under a forced choice (tool-loop.ts:656).noticeToolChoiceDowngraderecords'options', because the AI SDK's Anthropic provider downgrades both for models that reject forced use and for manual thinking, and its warning does not say which (tool-loop.ts:673).Verified
Ran it locally: yes
The built CLI, with a scripted
anthropic.messagesmodel, ran on main (7c1b2b258) and on this branch (d00f974b). The model throws the Anthropic 400 errors. The table lists the tool choice of each request.shared-model.e2e.ts: thinking comes fromdefaultSettingsMiddleware. Thedefaultagent sends no options, andleansendsthinking: { type: 'disabled' }withmaxModelCalls: 1.fable.e2e.ts: the model refuses every forced choice with Fable 5.1's message. Agentslow(effort: 'low'),high(effort: 'high'), anddefault(no options) run in that order.required,MODEL_PROVIDER_FAILEDrequired, thenautowith thinking intact, passesmaxModelCalls: 1)tool:complete_step, passesrequired, thenauto×3: one rejected requestrequired, thenauto×3: one rejected requestOne more run covers options whose own field is a
bigintand whosetoJSONwrites it as text, such as a 64-bit request id. Config resolution accepts them. The model answers the manual-thinking 400, and the test runs twoagent.actsteps. On2e10b94b, the first step failed after onerequiredcall withACTION_FAILED: Do not know how to serialize a BigInt. Ond00f974bthe calls arerequired,auto,auto, and the test passes.Unit tests in
packages/e2e/tests/unit/tool-loop-tool-choice.test.tscover the following:requiredandtool:complete_stepretries withproviderOptionskeptforcedToolChoiceRefusalscope across gateway wrappers, 502AI_RetryErrorchains, and unrelated thinking 400sproviderOptions(toJSONapplied), and options with no JSON form, which are retried but not rememberedOn
84f333309the model-level thinking test and the model-wide test fail. Live gateway behavior is still unverified: no model key was available.Summary by CodeRabbit
Bug Fixes
Documentation