Repository navigation
[Fix] Reasoning with tool use fails on OpenAI Compatible endpoints that require the Responses API - #2498
Conversation
…ible provider
Reasoning models such as GPT-6.1 Terra on Azure OpenAI reject
reasoning_effort combined with function tools on /chat/completions and
require /v1/responses. The OpenAI Compatible provider only spoke Chat
Completions, so reasoning could not be combined with tool use on those
endpoints.
Add an openAiUseResponsesApi setting. When enabled, createMessage posts
to {baseUrl}/responses with the provider's custom base URL, custom
model/deployment ID, and custom headers. The resolved reasoning_effort
is translated to the Responses reasoning.effort shape, tools use the
flattened Responses function shape, and the shared Responses input and
stream transforms (also used by the xAI provider) handle conversion.
Chat Completions stays the default, so existing setups are unchanged.
|
Important Review skippedBot user detected. To trigger a single review, invoke the
|
| Check name | Status | Explanation |
|---|---|---|
| Security Boundaries | Summary: No changed path in PR #2498 leaks secrets or PII, trusts unvalidated input in a way that executes it, or bypasses approval or allowlist controls. The PR's own commits (05e80b1..`9ac392d… |
|
| Persistence Integrity | Result: PASS. I found no changed persistence path in this PR that can lose or corrupt state through an un-awaited operation, a non-atomic write, missing rollback, or an unpropagated persisted defa… | |
| Lifecycle Resource Cleanup | Check: Lifecycle resource cleanup. Result: no changed lifecycle path found that leaks a resource or duplicates work. Scope reviewed: the PR's own commits, 05e80b1^..9ac392d (the branch also contains u… |
Full details: Security Boundaries
-
Explanation
Summary: No changed path in PR
#2498leaks secrets or PII, trusts unvalidated input in a way that executes it, or bypasses approval or allowlist controls. The PR's own commits (05e80b1..9ac392d, base75a93a9) were reviewed directly. Evidence checked: - Function allowlists:buildResponsesRequestinsrc/api/providers/utils/openai-compatible-responses.ts(lines 120-143) keepsallowed_toolsrestriction mode and flattens only function references. A missing or non-string name throws. The mapping runs beforebridgeExternalAbortSignalregisters any listener. The Chat Completions path forwardstool_choiceunchanged, so the Responses path does not weaken the restriction. - Extra Body precedence: The Responses path returns{ ...extraBody, ...requestBody }. The Chat path uses{ ...this.extraBody, ...requestOptions }. Both keep Zoo-managed fields in control. - Endpoint and credentials:responsesReasoningScope(src/api/transform/responses-api-reasoning.tslines 35-37) stores only a SHA-256 digest of the base URL. No plaintext URL, key, or header is persisted. The PR adds no logging of keys or request bodies insrcorpackages. - Stored reasoning replay:readResponsesReasoningItemchecks item type, id, encrypted content, and summary shape.readReplayableResponsesReasoningrequires matching format, provider, and endpoint. Items are replayed only to the same endpoint. - Azure URL handling: Headers and API key reuse the existing client options. The Azure v1 URL path only rewrites the path of the user's configured base URL. It adds no new host. - Error handling:assertResponsesApiSuccessturns failed, incomplete, and cancelled responses into errors. This avoids reporting partial output as success. Minor observation (not a failure): The endpoint digest hashes the full base URL, including any userinfo or query. The digest is one-way. It is not a plaintext leak, so it does not meet the check's failure condition. The check was judged on code evidence from the local checkout. No changed path matches a failure condition.
Full details: Persistence Integrity
-
Explanation
Result: PASS. I found no changed persistence path in this PR that can lose or corrupt state through an un-awaited operation, a non-atomic write, missing rollback, or an unpropagated persisted default. Scope. The local
origin/mainis behind, so a plain three-dot diff pulls in 11 unrelated upstream commits. I scoped the review to the PR's seven commits,75a93a9..9ac392d(05e80b1 through 9ac392d). Those touch the OpenAI Responses path, the Chat Completions format filter, the provider settings schema, and the settings UI. The shared task core (src/core/task/*) is unchanged. Changed persistence paths checked: 1. Encrypted reasoning capture (src/api/providers/openai.ts).this.responsesReasoningis reset at the start of each request. It is assigned only after the stream loop or the non-stream response completes successfully. An early generator close, a failed or incomplete response, or a premature EOF leaves it empty, so partial reasoning is never published. 2. Write ordering.getReasoningDetails()is read insideaddToApiConversationHistory, which Task.ts awaits at line 5135 after the stream loop ends. The save uses the existing history hooks, and their write path is unchanged. 3. Replay and ownership (responses-api-reasoning.ts,responses-api-input.ts). Tagged items replay only whenformat,provider, and the endpoint hash match. Untagged items are omitted on this path, as the description states. This is a deliberate scope choice, not a silent loss on an existing path. 4. Chat Completions filter (openai-format.ts). The filter dropstype: "reasoning"entries fromreasoning_details. I checked the other providers' writers. OpenRouter storesreasoning.text,reasoning.summary, andreasoning.encrypted, and no other writer storestype: "reasoning"there, so their data is not dropped. 5. Persisted settingopenAiUseResponsesApi. It is declared in the sameopenAiSchemaasopenAiStrictToolSchemas, and a profile round-trip test covers it. Consumers read it by truthiness. The webview uses?? false, and the dedicated Kimi Code, Moonshot, MiMo, and DeepSeek handlers set it tofalse. The default is therefore propagated consistently. Residual notes (not failing criteria): - An explicit emptyoutputinresponse.completedclears items captured from earlier events. This follows the completed snapshot as the authoritative output and is documented in the PR. - Thereasoningtext block is skipped whenreasoning_detailsis present. This affects display or summary text, not encrypted state, which is stored in the details. Evidence is from direct code reads and diffs; no build or test execution was used.
Full details: Lifecycle Resource Cleanup
-
Explanation
Check: Lifecycle resource cleanup. Result: no changed lifecycle path found that leaks a resource or duplicates work. Scope reviewed: the PR's own commits, 05e80b1^..9ac392d (the branch also contains unrelated commits from main). I grepped every added non-test source line for listener, timer, watcher, dispose, abort, and close primitives. Only two lifecycle sites were added: the bridge and its release in src/api/providers/openai.ts. Evidence: 1. Listener bridge. handleResponsesApiMessage (openai.ts) builds the request first. It calls bridgeExternalAbortSignal(metadata?.abortSignal) only after construction, directly before the try. It releases the listener in finally. The comment on the bridge states this ordering is intentional. 2. Bridge semantics. src/api/providers/utils/abort-signal.ts registers one anonymous-retained listener with a named callback. dispose() calls removeEventListener. An already-aborted signal does not register a listener. 3. Early generator exit. Consumer return() runs the finally, which removes the listener. For the streaming path, yield* forwards return into processResponsesApiStream's for-await. The OpenAI SDK 5.23.2 iterator (src/node_modules/openai/core/streaming.js) calls controller.abort() in its finally when not done. The HTTP connection therefore closes on early break. 4. Cancellation. A mid-stream external abort ends the stream without a completed event. The code then throws, and isRequestAborted(error, abortSignal) normalizes it to an AbortError. No retry or re-issue path exists in the PR, so no duplicate work follows. 5. Non-stream and completePrompt paths. These pass the signal directly to the SDK and register no listener. The timeout is passed only when usable. 6. Reasoning state. this.responsesReasoning is reset at the start of each task request and set only after success, so a failed or closed request does not publish partial state. This is state handling, not a resource. 7. Azure client. The constructor assigns one new OpenAI client. The Azure AI Inference guard throws before any client is created, so nothing is left allocated. Limitations: I did not execute the test suites, per the sandbox rules. The verdict relies on source reading and the SDK source in the sandbox.
Full details: Regression Evidence
-
Explanation
Summary: Most changed behavior has focused tests at the unit layer. One stated negative behavior does not. The PR states that single completions "do not overwrite task reasoning state." No test checks this. Scope checked: The PR-specific commits are
05e80b1through9ac392d. I diffed from parent75a93a9becauseorigin/mainhas moved past the PR base. Covered (adequate evidence): - Terminal stream failures (response.failed,incomplete,cancelled,error,response.error, andcompletedwith a failed status) are rejected. Tests are inresponses-api-stream.spec.ts(≈L458–475) andresponses-api-contract.spec.ts(≈L38–42). - Token-limit classification (OutputTokenLimitError) is tested for both message and completion entry points (openai.spec.ts≈L2491). - Premature EOF without a completion event is rejected and does not publish partial reasoning (openai.spec.ts≈L2775). - Abort and timeout forwarding, and listener release on completion, failure, and early exit, are tested (≈L2305–2369). - The Kimi Code, Moonshot, MiMo, and DeepSeek stale-flag isolation is tested (≈L2505). - Azure v1 routing, dated versions, and the AI Inference rejection are tested (≈L2711–2761). - Reasoning round-trip, ownership, endpoint change, and clearing on failure, close, or construction error are tested (≈L2521–2678). - Malformed function references are rejected (openai-compatible-responses.spec.ts≈L146). - The settings UI has Vitest coverage (OpenAICompatible.spec.tsx,SettingsView.spec.tsx). The visible toggle also has committed Playwright visual baselines for the Azure and Extra Body stories (OpenAICompatible.visual.tsx; five PNGs changed). Gap (FAIL basis): - Changed behavior:completePromptnow has a Responses path (openai.ts≈L501–545). Prompt enhancement and condensation call it. The PR says these calls "do not overwrite task reasoning state." - The only writes tothis.responsesReasoningare inhandleResponsesApiMessage(lines 360, 401, 425).completePromptdoes not write it. That is correct today. - No test inopenai.spec.tschecks the invariant. Reasoning assertions (getReasoningDetails) appear only in the task and clearing paths (≈L2543–2789). The single-completion routing test (≈L2433–2520) does not assert reasoning state. - Plausible regression: a single completion in the middle of a task wipes or replaces captured encrypted reasoning. The next tool-call turn then loses its replay chain. This is a real failure mode, so the omission is not a theoretical branch. Note on the check: The PR's manual mutation claims do not name this invariant. The TLA+ models do not test the ResponsescompletePromptpath against the real handler.Resolution
Add a focused unit test in
src/api/providers/__tests__/openai.spec.ts, in theOpenAiHandler Responses APIblock: 1. ConfigureopenAiUseResponsesApi: true. 2. RuncreateMessagewith a mockedresponse.completedwhoseoutputincludes a reasoning item. AssertgetReasoningDetails()returns that item. 3. CallcompletePrompt("prompt")with a mocked Responses result. The result may include a different reasoning item, or none. 4. AssertgetReasoningDetails()still returns the item from step 2, unchanged. 5. Optionally add a case where thecompletePromptcall fails. Assert the task reasoning is still unchanged. Run the test with the existing Vitest command foropenai.spec.ts. Confirm that a mutation makingcompletePromptassignthis.responsesReasoningfails the new test.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
|
1 issue outstanding. See session
Reviewed fbf1f23 |
Review statusThis PR was opened by an automated account. A human maintainer must verify the change intent, provenance, and validation before merging. Current step: Required CI passed. Waiting for automated review of the latest commit. If automated review does not start, a maintainer must restart it. Review-state labels are managed by this workflow; do not edit them manually. |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Changed-code mutation testingReport for PR head
Details: mutants, guidance, and reproductionChanged-code mutation testing
Focused tests
Reproduce locallyFrom a full checkout containing both commits: Mutation reports
The workflow uploads generated reports in the Advisory findings
|
| // Omit temperature unless the | ||
| // model supports it and the user set a custom value, so the server's own | ||
| // default applies. | ||
| if (modelInfo.supportsTemperature !== false && options.modelTemperature != null) { |
There was a problem hiding this comment.
Can we preserve the o-series temperature omission to avoid rejecting existing profiles?
There was a problem hiding this comment.
Fixed in fbf1f233d. The Responses request builder now omits temperature for o-series model IDs (o1/o3/o4), mirroring the Chat Completions handleO3FamilyMessage behavior. An existing o-series profile with a custom temperature is no longer rejected when the Responses API toggle is enabled. Regression tests cover o1, o3, and o4-mini with a configured temperature; the non-o-series inclusion table still passes.
There was a problem hiding this comment.
Confirmed in 8fcc532d62. Temperature policy now runs once after the Extra Body merge: o1/o3/o4 requests omit temperature regardless of the configured value or Extra Body. The 108-case property table covers zero/unset values, model capability, and ordinary-model precedence. The SDD Temperature invariant now includes the o-series and Extra Body inputs; its sabotage checks and corresponding code mutations fail as expected.
| typeof message.content === "string" | ||
| ? message.content | ||
| : message.content.map((part) => { | ||
| if (part.type === "tool_use") return { ...part, id: sanitizeIdentifierSurrogates(part.id) } |
There was a problem hiding this comment.
Would normalizing both history ID fields to the Responses length limit prevent failures after switching from Gemini?
There was a problem hiding this comment.
Fixed in fbf1f233d. Both history ID fields (tool_use.id and tool_result.tool_use_id) now pass through the existing deterministic truncateOpenAiCallId normalization (64-char Responses limit with hash suffix) after surrogate encoding. History recorded through providers with longer IDs (e.g. Gemini) no longer fails after switching to the Responses path, and because the transform is identical on both fields, call/result pairs keep matching. A regression test feeds a 100+ char ID through both fields and asserts the emitted function_call/function_call_output call_ids are within the limit and equal.
There was a problem hiding this comment.
Confirmed in 8fcc532d62. Both tool_use.id and tool_result.tool_use_id now use the same normalizeHistoryCallId helper: encode surrogate identifiers, then truncate to the 64-character limit. The 28-case property table checks short IDs, the length boundary, longer IDs, surrogate expansion, matching call/result IDs, and unchanged history. Added SDD boundedness, pairing, and short-ID preservation rules; bypassing either field's normalizer fails the model check and real-code assertions.
… on Responses requests Review feedback on #2498: - Omit temperature for o1/o3/o4 model IDs on the Responses path, matching the Chat Completions o-series handling, so existing o-series profiles with a custom temperature are not rejected when the toggle is enabled. - Normalize both history ID fields (tool_use.id, tool_result.tool_use_id) to the Responses call_id length limit with the existing deterministic truncation, so history recorded through providers with longer IDs (e.g. Gemini) no longer fails after switching, while call/result pairs keep matching.
| // the Responses API toggle is enabled. | ||
| const modelId = options.openAiModelId ?? "" | ||
| const isOSeriesModel = modelId.includes("o1") || modelId.includes("o3") || modelId.includes("o4") | ||
| if (!isOSeriesModel && modelInfo.supportsTemperature !== false && options.modelTemperature != null) { |
There was a problem hiding this comment.
This still allows temperature for o-series models when it comes from Extra Body. With openAiExtraBody: {"temperature":0.4}, the guard leaves requestBody.temperature absent, so the final { ...extraBody, ...requestBody } preserves the unsupported value. The Chat Completions o-series path owns temperature: undefined and therefore suppresses that collision. Please explicitly remove/override Extra Body's temperature for o-series Responses requests too, and cover that combination.
There was a problem hiding this comment.
Fixed in 8dc519673. After the final { ...extraBody, ...requestBody } merge, the builder now explicitly deletes temperature for o-series models, so an openAiExtraBody: {"temperature": 0.4} value can no longer survive the spread — the same net effect as the Chat Completions path's temperature: undefined ownership. A new regression case in openai-compatible-responses.spec.ts covers o1/o3/o4-mini with extraBody: { temperature: 0.4 } (asserting the final request has no temperature property) plus a non-o-series model confirming Extra Body temperature is still preserved where supported.
There was a problem hiding this comment.
Addressed and simplified in 8fcc532d62. The builder resolves temperature after merging Extra Body and explicitly deletes it for o-series models. Ordinary models retain configured-temperature precedence and Extra Body fallback. The property table covers both sources together. Validation: 698 focused tests, type checking, and ESLint pass with unchanged suppression counts. All 37 Responses TLC configurations produce their expected pass/invariant-failure results, and all four real-code mutation replays fail assertions. Review findings and replay evidence are recorded in the SDD files.
The Responses request guard leaves requestBody.temperature absent for o1/o3/o4 models, so an openAiExtraBody temperature survived the final spread and reached models that reject the parameter outright. The Chat Completions o-series path owns temperature: undefined and suppresses that collision. Mirror it by explicitly deleting the merged temperature for o-series models, and cover the combination in the request-builder spec.
One conflict: src/core/webview/__tests__/ClineProvider.spec.ts. Resolved by hand as a union, not by taking a side. The branch adds the provider-settings test helpers (StalledProfile, stallProviderSettingsProfile, persistedViewStateClaim) and main adds the mention-segment helpers (noUserSegments, expectMixedPayload) at the same spot after afterAll(); both blocks are kept, each helper is declared once and used, and main's joinSegments / MentionSegment imports are present. Line-level proof, because a green run cannot prove the upstream side survived: Zoo-Code-Org#2498 changed only two lines in this file (the test.each title gaining "and Responses", and openAiUseResponsesApi: enableReasoningEffort,) and no test fails when they are dropped, since the assertion is a toMatchObject over that object. Both are in the resolved file, at lines 4166 and 4173. Every one of main's 97 added lines (base d112b7f) is present; every one of the branch's 2031 added lines is present. The 4 lines the resolved file lacks against main are the axios mock this branch rewrote (present in the base, absent from the branch blob); the 9 lines it lacks against the branch are lines main itself rewrote or deleted (present in the base, absent from the main blob, so they are not lost assertions). Measured on win32, node v25.9.0, vitest 4.1.12, core lane, this spec alone: 424 tests passed (420 at the pre-merge head), Duration 9.76 s, exit 1 from EnvironmentTeardownError unhandled rejections raised by worker teardown - the pre-merge head run gives the same exit 1 with 8 of the same rejections and 420 passed, and a forks-pool run of the merged file gives 424 passed with 9, so the count is a teardown race in this environment and not a test failure. prettier --check exit 0; eslint --max-warnings=0 exit 0 with the recorded 195 suppressions for this file unchanged. node_modules in this worktree is a junction composite (store from a scratch donor, every @Roo-code link re-pointed into this worktree) because a plain junction to a donor 39 commits behind main resolves @roo-code/types to stale sources and the spec then dies at import in src/shared/mentionSegments.ts.
One conflict: src/core/webview/__tests__/ClineProvider.spec.ts, resolved as a union of the two helper blocks that both landed after afterAll(): this branch's stalled-profile helpers (StalledProfile typed from ProviderSettingsManager["getProfile"], stallProviderSettingsProfile with the spyOn form and its one-call guard, persistedViewStateClaim) and main's mention-segment helpers (noUserSegments, expectMixedPayload). No line of either block was edited; the only hand-written content is the closing brace of persistedViewStateClaim, the blank line between the blocks, and the removal of the three conflict markers. Read, not assumed: main's 97 added lines in this file (base d112b7f) are all present, this branch's additions are all present, and Zoo-Code-Org#2498's two lines - the test.each title gaining "and Responses" and openAiUseResponsesApi: enableReasoningEffort, - sit at lines 4166 and 4173 of the resolved file. They are the lines a take-ours would have deleted silently, because the assertion over that configuration is a toMatchObject.
Related GitHub Issue
Fixes #2040
Closes #1579
#2040 reports the same Azure/OpenAI-compatible error when reasoning and function tools require
/responses. #1579 requests Responses API support through a per-profile opt-in setting.Description
Some OpenAI-compatible endpoints require
/responsesto combine reasoning with function tools. This adds an opt-in Use Responses API setting for both task messages and single completions such as prompt enhancement and condensation. Chat Completions remains the default. Custom deployment names, headers, reasoning effort, and function tools are retained.A pure
buildResponsesRequest()prepares the request from explicit inputs. It honors streaming, temperature capability, output limits, strict schemas, and Extra Body precedence. Zero and omitted values follow the existing Chat Completions policy. Function allowlists retain their restriction mode and use the flattened Responses shape; malformed function references are rejected before listener registration.Failed, incomplete, cancelled, and error responses now raise an error instead of appearing successful. Premature stream EOF without a completion event is also rejected. Output-token truncation retains
OutputTokenLimitError. Cancellation signals and valid timeout overrides reach the SDK, and external bridge listeners are released on completion, failure, and early generator exit.Completion and its optional output snapshot now use one observer callback. Item events remain the fallback when a gateway omits the snapshot; an explicit empty snapshot clears captured items. The endpoint fingerprint is computed once per history read, and a redundant Azure guard was removed.
Encrypted reasoning items are captured only for successful task responses. The completed output snapshot sets their order. The existing history hooks persist them with a provider tag and a fingerprint of the effective SDK endpoint; URL credentials and query secrets are not stored in that metadata. Responses replay requires matching ownership after serialization or reload. Raw Responses items are excluded from Chat Completions, while other providers' reasoning formats retain their existing handling. Older untagged items are omitted on the OpenAI-compatible path because their source cannot be verified. A new request clears prior reasoning; failure and early close cannot publish partial reasoning. Single completions do not overwrite task reasoning state.
Dedicated Kimi Code, Moonshot, MiMo, and DeepSeek handlers explicitly ignore a stale Responses opt-in from another profile.
For Azure, explicit
/openai/v1URLs are preserved and use the standard OpenAI client, including modernservices.ai.azure.com/openai/v1endpoints. An older Azure OpenAI root defaults to/openai/v1when Responses is enabled and no dated version was selected. Explicit dated versions remain available for legacy Azure endpoints. The older Azure AI Inference route rejects this combination with an instruction to use/openai/v1.The SDD artifacts follow
docs/architecture/tla/AGENTS.md. Three models separate request routing/cleanup, request-option rules, and protocol/reasoning history. Their headers record the review ratchet, input domains, findings, costs, and manual gate results. Models check abstractions; they do not prove the implementation correct.Test Procedure
o1/o3/o4routing precedence, SDK cancellation and timeout options, terminal failures, missing/null/empty completion snapshots, token-limit classification, zero/default/omitted options, strict schemas, filtered tools, function allowlists, and malformed restrictions.a60cdbcec4; the fresh result for this refactor is pending CI.anysuppressions were removed; no suppression count increased.docs/architecture/tla/ResponsesReviewReplays.mdmaps each sabotage configuration to its test; ownership has separate Responses and Chat Completions mutations. These are manual checks, not an automated model-to-code correspondence proof or a CI gate.src/. To repeat TLC, run each.cfgagainst its matching*MC.tlamodule fromdocs/architecture/tla, using-metadiroutside the repository. Fixed configs must pass; sabotage configs must exit with invariant failure 12.All 17 non-English locales include the setting text. Five committed visual baselines came from pinned CI container artifact
14438633679; their webview comparisons passed in run 44544690027. This review round does not change the UI layout.Pre-Submission Checklist
Visual Snapshots
Committed baselines cover the Azure guidance story and the Extra Body story in dark, light, high-contrast, and high-contrast-light themes.
Videos (interaction / animation only)
Not applicable.
Documentation Updates
docs/architecture/tla/.Additional Notes
maxis not rejected globally;nonedoes not request encrypted reasoning. See OpenAI reasoning guidance.strict: nullandparameters: nullwhen unspecified, with explicit regression coverage. See OpenAI function calling.allowed_tools.Get in Touch
Discord: taltas1