Repository navigation
Studio: run the local tool loop against every capable external provider - #8665
Conversation
Studio's tools execute on the Studio host, not on the model, but only one external provider could use them: the gate was a hardcoded provider_type == "openai_codex" in routes/inference.py and again in research_runs.py. Point Studio at your own llama.cpp, vLLM, Ollama or OpenRouter and Search, Code, MCP, Docs and Deep Research all greyed out. Generalise the capability instead of adding a second implementation: - providers.py declares studio_tools per provider type and provider_runs_local_tools() replaces the hardcoded comparison. Hidden entries now reach /registry flagged rather than filtered out, which is why the UI could never learn the self-hosted presets are capable. - The loop moves to core/inference/studio_tool_loop.py behind a Transport protocol. CodexTransport keeps the app-server call; OAICompatTransport wraps ExternalProviderClient.stream_chat_completion, the one function every provider re-yields through. - Self-hosted models often write a call as text instead of emitting structured tool_calls, so the loop feeds content through StreamToolCallHealer, the same bounded buffer the client-tool passthrough uses. Only a partial-signal window is ever withheld and an unparseable block flushes verbatim, so a turn that never terminates renders its text instead of nothing. - Deep Research accepts any capable saved connection. Research hops keep tool_choice "none" and enabled_tools [], so a prompt-injected page in the evidence set still cannot reach python. - response_format now reaches OpenAI-compatible providers at all; JSON mode was silently dropped for every one of them. Anthropic is deliberately excluded: _stream_anthropic never forwards a caller's function-tool schemas, so the loop would advertise a catalog the model never sees. It needs schema plus tool_use/tool_result translation. The local, GGUF, safetensors and MLX paths are untouched -- every hunk in routes/inference.py is inside _proxy_to_external_provider. Codex behaviour is unchanged, and the healer is only constructed when a tool catalog is actually selected. Fixes #7282. Fixes #7761. Also fixes a live bug: chat-runtime-store disarmed Deep Research for any external model id including openai_codex, which the backend and the menu both permit, so Codex users had to re-enable it after every model switch.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b0f8396782
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for provider_type, info in PROVIDER_REGISTRY.items(): | ||
| if info.get("hidden"): | ||
| continue | ||
| result.append( |
There was a problem hiding this comment.
Honor the hidden flag when exposing registry entries
Including all registry rows makes custom, vllm, ollama, and llama_cpp appear twice in the connection picker: once through CUSTOM_PROVIDER_PRESETS and again through the registry group. The frontend currently filters only the hardcoded HIDDEN_PROVIDER_TYPES = new Set(["qwen"]) and never checks the newly returned entry.hidden, contrary to this function's comment, so the UI must consume that flag before these rows are exposed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Stale against head. list_available_providers already skips hidden entries unless include_hidden=true (providers.py), the route defaults it to false (routes/providers.py), and the dialog filters them client-side too: setRegistry(registryRows.filter((entry) => !entry.hidden)) in chat-providers-dialog.tsx. No duplicate rows in any client/server skew.
| if decision == "deny": | ||
| decision_slot = None | ||
| result = TOOL_REJECTED_MESSAGE |
There was a problem hiding this comment.
Bound retries after a denied forced tool call
With a forced tool_choice, denying a call leaves both remaining and executed_any unchanged, so the next turn still advertises the forced choice and the model must request another tool; repeated denials can therefore produce an unbounded sequence of approval prompts despite max_calls. Count handled attempts separately or relax the forced choice after a denial so rejecting an unsafe call can terminate normally.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not unbounded. A turn where every call is denied leaves turn_executed_real_tool false, so it counts as fruitless and the loop breaks at _MAX_FRUITLESS_TURNS = 2; max_provider_turns caps the asking a second time. Repeated denials stop after 2 prompts, verified by running the loop against an always-deny approval slot.
The first cut generalised the Codex loop, which never had to deal with a model that writes a call as text, repeats one, or stalls. Everything the llama.cpp and safetensors loops learned about that is now shared here, taken from the work in #8630: - ToolLoopController owns dedup, one-shot withdrawal and the force-final-answer transition, so a repeated call cannot spend the budget twice. - stream_tool_execution streams live stdout with heartbeats, so a long python or terminal call cannot idle the stream out. - The approval card is flushed on its own write before the stream blocks, so Allow and Deny paint immediately in the desktop app. - A stalled model that says what it will do gets one nudge to do it. - Usage is summed and reported once instead of a burst of partial counts. - append_assistant_turn merges a continued partial, and replayed content is stripped of markup since the call replays structurally. Fixes found by testing the above: - An intermediate turn's [DONE] was relayed, so a spec-compliant client stopped before the tool cards and the final answer. - A structured call was dropped unless finish_reason was exactly tool_calls. Ollama and several proxies close with stop, or omit it. A truncated turn (finish_reason length) still never executes. - Argument fragments without an index started a phantom call and ran the real one with empty arguments. - Two distinct calls at one index merged into unparseable JSON. - max_tool_calls_per_message capped what was advertised, not what ran: a provider that called anyway was executed. It is a safety limit, so it now gates execution, per call rather than per turn. - Provider turns are bounded, not just executions. A model asking for tools that can never run cannot trade turns forever. - Call ids are unique for the whole run, so a provider that restarts its numbering cannot put two results under one id. - An empty tool_calls list no longer counts as grammar mode working and disables healing for the rest of the turn. - A call with no id is given one instead of being silently dropped. - The provider stream is closed from this frame rather than left to the async-generator finalisation hook. - Content parts reach the replayed assistant message, not just the client. Compatibility: /api/providers/registry hides the backend-only entries again by default and takes include_hidden=true, so a browser holding a pre-capability bundle sees exactly the list it saw before instead of rendering the self-hosted presets as duplicate options. Also fixes the frontend build: thread.tsx used providerModelSupportsStudioTools without importing it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad16cb87f6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not decision.should_execute: | ||
| completion = controller.record_noop(decision) | ||
| noop_messages.append(completion.model_message()) | ||
| continue |
There was a problem hiding this comment.
Close provisional cards for skipped structured calls
When the provider repeats a previously successful structured call, prepare_call classifies it as a duplicate after its delta.tool_calls has already been forwarded and the frontend has created a provisional tool card. This branch emits neither tool_start nor tool_end and only adds a nudge to the provider conversation, leaving that user-visible card without a result and appearing unfinished after the response completes. Suppress the forwarded no-op call or emit a terminal event for it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar. The premise is right that a duplicate structured call gets neither tool_start nor tool_end, but the outcome is a rendered card without a Result section, not a wrong tool, a lost call, wrong args or a crash. The model still gets the duplicate nudge through record_noop, which is exactly what the local loops do, and the part is dropped on outbound replay.
There was a problem hiding this comment.
Confirmed, fixed in c8c54c4. The loop relays the provider's own tool_calls delta, so the client paints a card for every announced call, and a skipped one emitted nothing terminal and kept spinning for the rest of the answer. It now gets a tool_end of its own, the same way the budget-exhausted branch already did. One wrinkle worth noting: a repeated call is exactly the one the loop renames for the replayed history, so both events are keyed on the id the provider streamed or they would land on no card at all.
There was a problem hiding this comment.
Correct. Fixed in b1e6d04: a call the loop announces but never runs now emits a paired tool_start and tool_end. One deliberate exception, a call naming a tool this install never offered gets neither event, because painting a card for it advertises a tool the user switched off.
| gen = stream_with_studio_tools( | ||
| OAICompatTransport( | ||
| client, | ||
| model = model, | ||
| continue_final_message = _continue_final_message(payload), |
There was a problem hiding this comment.
Replay Responses reasoning items across local tool turns
When the selected provider is OpenAI and a GPT-5/o3 reasoning response emits a function call, this newly enabled loop starts a fresh /responses request for the tool result. _stream_openai_responses translates the function call into delta.tool_calls, but the loop does not retain the accompanying reasoning output item; the next request therefore rebuilds only function_call and function_call_output items and also lacks previous_response_id. Responses reasoning tool flows require the returned reasoning items to accompany the function output, so the first post-tool request can be rejected or lose the reasoning state. Preserve those output items in the replay or continue from the response ID.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable. _stream_openai_responses never sets store, so the API default store: true applies, and the follow-up input is a well-formed function_call plus function_call_output pair that references no rs_* id. The 404 "Item with id not found" failure mode requires store: false. What remains is the documented few-percent benefit of passing reasoning items back, which is an enhancement and identical on the pre-existing non-loop Responses path.
There was a problem hiding this comment.
Not taking this one. The loop rebuilds each call with responses_function_call, which emits type, call_id, name and arguments and no server-side item id, so the Responses pairing check that raises "function_call was provided without its required reasoning item" does not apply to it: that check keys off the fc_ item id linking back to its rs_ item. No reasoning item is sent either, so the mirror-image error cannot fire. OpenAI documents replaying reasoning items as a recommendation for quality and token efficiency, and states that unrelated reasoning items are ignored. So nothing is rejected and no call is lost here; carrying them would be a quality improvement, and it is not new to this PR since the same translation already served the client-tool passthrough on /responses.
There was a problem hiding this comment.
Correct. Fixed in bd0dc7d. The reasoning items were already captured but only the image-generation card read them. They are replayed now, re-sanitized because the recorded copy carries a status the API rejects on an input item, buffered so a trailing reasoning item is never emitted, and carrying encrypted_content for orgs whose ids resolve to nothing.
There was a problem hiding this comment.
Following up on my earlier note: the reasoning items are now replayed after all, in bd0dc7d. The analysis in that note still stands, that the request we build carries no server-side item id so the pairing check never rejects it, but replaying them is worth having for reasoning continuity and token efficiency across tool rounds, so switching this to agreed.
| # One provider call per possible execution, plus headroom for the no-op, | ||
| # nudge and final-answer passes that legitimately execute nothing. | ||
| max_provider_turns = (25 if unlimited else max(1, remaining)) + 2 * MAX_ACT_REPROMPTS + 4 |
There was a problem hiding this comment.
Preserve unlimited tool runs past the fixed turn cap
When max_tool_calls_per_message is set to the documented unlimited sentinel (9999 or higher), unlimited disables the execution budget but this expression still caps the run at roughly 33 provider turns. A legitimate long-running agent that continues making distinct successful calls reaches that cap and exits the loop silently without obtaining a final answer, despite the caller explicitly requesting no call limit. Keep a separate high safety bound for pathological no-op turns without imposing the 25-turn branch on successful unlimited runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 19096da. The bound now follows the local loops (max(1, min(remaining, 9999)) plus the reprompt headroom) instead of a fixed 25 for the unlimited sentinel; reproduced the old truncation at 35 turns with no final answer. A run that executes nothing is still stopped by the fruitless-turn bound, which I confirmed still fires after 3 turns on a model repeating one call.
There was a problem hiding this comment.
Agreed, fixed in 19096da. Both local loops run an unlimited request for as many turns as the model asks for, so swapping in a fixed 25 here stopped a productive run at turn 35 with no final answer. The sentinel now keeps its own bound, and a run that executes nothing is still ended by the fruitless-turn guard, which is the case the cap existed for.
There was a problem hiding this comment.
Not accurate, and the arithmetic is checkable. The cap is max(1, remaining) + 2 * MAX_ACT_REPROMPTS + 4 with MAX_ACT_REPROMPTS = 3, so the unlimited sentinel gives 9999 + 10 = 10009 provider turns, not 33. The figure of roughly 33 corresponds to the default budget of 25, which is a different input.
The sentinel deliberately keeps its own budget rather than dropping to a smaller fixed number, because both local loops run Max for as many turns as the model asks for, and a lower bound here would cut a productive run short with no final answer. Runaway no-op turns are already bounded separately by fruitless_turns, which ends a run after two consecutive turns that execute nothing.
…h the external loop Forward response_format into the native Gemini and OpenAI Responses request shapes so a deep research planning hop still gets JSON mode; Gemini takes a generationConfig responseMimeType and only on a tool-free turn, Responses takes text.format. Keep an explicit max_tool_calls_per_message of 0 meaning disabled instead of falling back to 25, refuse a non-scalar providerType with a 400 rather than a registry TypeError, recompute continue_final_message per turn so a post-tool request no longer resumes a role=tool message, replay each call's Gemini thought signature on the assistant turn, restore round_id on every tool card, and let a verified internal workflow key resolve the run's saved connection.
|
I built this branch and drove it in a browser against a mock llama.cpp-style OpenAI-compatible server, then ran the same flow against Branch under test The feature worksRegistering a
Same flow on Other checks that passed:
Blocking: three tests fail on this branch and pass on mainThe same two files on
The last two are on the pre-existing Codex path, which the description says does not move and that For context on the noise floor: the whole
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 30c3076dbb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| except (RuntimeError, GeneratorExit): | ||
| pass | ||
|
|
||
| calls = turn.calls(used_call_ids) if turn.finish_reason != "length" else [] |
There was a problem hiding this comment.
Terminate truncated provisional tool cards
When a provider streams any delta.tool_calls fragments and then finishes with finish_reason="length", those fragments have already been forwarded and the frontend has opened a provisional tool card. Replacing the accumulated calls with an empty list then exits without emitting tool_end, so the truncated card remains visibly running after the response completes. Keep refusing to execute the truncated call, but emit a terminal failure event for each provisional call.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar, same as the duplicate-call sibling. No tool_end is emitted, but assistant-ui derives a resultless tool part's status from the message status, which flips to complete when the stream returns, so the card stops spinning at end of stream. Nothing dangling is replayed either: the outbound history drops a resultless tool part and the truncated call never reaches assistant_tool_calls.
There was a problem hiding this comment.
Fixed in 46fddfb. A truncated turn's fragments were already relayed, so the client had a card for the call, and refusing to run it left that card open for the rest of the response. It is now closed through the same unrun-call helper the budget and skipped paths use. Structured calls only: one recovered from text was never streamed, and the released markup span is what reports that case.
| # Route the hop to whichever saved connection the run was created with. | ||
| # The route's _sanitize_config already refused anything but an enabled | ||
| # saved connection of a studio-tools-capable provider type. | ||
| if inference.get("providerType"): |
There was a problem hiding this comment.
Apply provider output floors to research hops
Widening these hops to every capable provider also admits Kimi, but Deep Research still hard-caps planning and decision calls at 4096 and 2048 tokens respectively, while the frontend's provider contract explicitly requires at least 16000 output tokens for Kimi thinking models. When thinking remains enabled on the decision and audit hops, Kimi can truncate before completing the required JSON, causing plan parsing or the run itself to fail even though ordinary Kimi chat applies the 16000-token floor. Resolve each research hop's output budget against the selected provider's minimum before sending it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable. Thinking is hardcoded False on the planning, decision and audit hops (and enable_thinking is False also forces reasoning_effort none), which the Kimi translation sends as thinking: {"type": "disabled"}. The 16000 figure is a chat-composer floor with no backend counterpart, and Moonshot's own guidance scopes it to thinking mode; kimi-k2-thinking is not in the registry allowlist, so the only selectable Kimi models run these hops with thinking off.
There was a problem hiding this comment.
Not taking this one. The premise that thinking stays on for these hops does not hold: planning, decision and the synthesis audit all pass enable_thinking = False, which becomes reasoning_effort none and, on Kimi, thinking type disabled. Moonshot's max_tokens 16000 guidance exists so reasoning_content plus content fit one budget, so with thinking off it does not apply, and 2048 is ample for the small JSON action object these hops emit. kimi-k2-thinking, the only always-on model, is not selectable either: the registry allowlist is kimi-k2.5 or kimi-k2.6 and manual model ids are refused for this provider. The one hop that does honour the user's thinking preference is synthesis, which already budgets 16384 and has a length recovery pass. The caps themselves are also unchanged by this PR.
…osted images Race the provider read against the cancel flag in OAICompatTransport, so Stop and a model load close the upstream instead of waiting for the next chunk; stream_chat_completion takes no cancel_event and the cancel routes only set the flag, so nothing else could reach the socket. Replay a call that overflowed the tool budget in the assistant message that carries its result, since a role=tool message with no matching tool_call is rejected outright by a strict server. Let the unlimited sentinel keep the local loops' bound rather than a fixed 25-turn headroom that truncated a long run. Forward the provider-hosted tools the loop has no local equivalent for, so the Images toggle still works on a turn that also enables a Studio tool.
The external loop relays the provider's own tool_calls delta, so the client paints a card for every call the model announces. A call the controller then declines to run (a repeat of one that already succeeded, a disabled tool, a second render_html) emitted no terminal event, so that card kept spinning for the rest of the answer and settled as a tool that ran and returned nothing. Emit a tool_end for it, the same way the budget-exhausted branch already does, and key both on the id the provider streamed: a repeated call is exactly the one the loop renames for the replayed history, so the renamed id belongs to no card.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c8c54c4e66
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| name = decision.tool_name | ||
| arguments = decision.arguments | ||
| call_id = decision.tool_call_id |
There was a problem hiding this comment.
Reuse the streamed ID for execution events
When an external provider restarts tool-call IDs on each follow-up turn (for example, repeatedly emitting call_0), _Turn.calls renames the replay ID and preserves the original as stream_id, but this branch uses the renamed decision.tool_call_id for tool_start, output, denial, and tool_end events. The already-forwarded delta.tool_calls opened a provisional frontend card under the original ID, so the execution events create a second card while the provisional one remains unfinished. Use stream_id for client-facing events while retaining the renamed ID only for provider-history replay.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The cards are deliberately kept distinct. The rename exists so two results in one message cannot collide under a single id, and that is pinned by test_duplicate_ids_across_turns_stay_distinct_in_the_cards. What is left is a provisional card without a Result section, the same family as the two earlier card items: assistant-ui derives a resultless part's status from the message status, which completes when the stream returns, and the outbound history drops the part.
… saved provider row Authorize the saved-connection path on the Deep Research workflow key alone rather than on any internally minted key: a data-recipe job also holds one and can read provider ids, so the broader check would have let it spend an unrelated saved credential. The workflow name is set by Studio at mint time and read back from the stored key row. Validate the research connection's capability on the saved provider type and persist it, instead of comparing it to the client's UI label. A legacy custom connection still stored as backend type openai reports custom, vllm or ollama in the UI, so the equality check refused a connection the chat route drives.
…al tool loop Review of the external-provider tool loop turned up several things that were either wrong before this branch or introduced by it. Each one is pinned by a test that fails without the fix. A provider endpoint could forge Studio's own tool cards. The loop writes its tool_start / tool_end frames onto the same SSE stream it relays provider chunks on, and the client tells them apart by shape, so an endpoint could paint a completed python card, sourced local, for code that never ran. base_url is user-configurable, so this needed a boundary: provider lines are stripped of Studio's control vocabulary at every relay site. The pre-change bundle asks for provider-hosted tools as enable_tools plus enabled_tools ["web_search", "code_execution"], which the widened gate captured, dropping hosted code_execution and silently swapping hosted search for local. Providers that run builtins themselves now declare hosted_tools in the registry, and a request naming only those stays on the hosted passthrough. The Code pill keeps a connection's own sandbox rather than relocating execution to this machine as a side effect of an update. A truncated turn discarded a healed tool call, and because promotion strips the markup from the relayed text, the user lost the call and the text describing it. The healer now records the promoted span so a discarded call releases what the model actually wrote. A budget-exhausted call appended a role=tool message with no matching assistant tool_calls entry, which OpenAI, DeepSeek and strict vLLM reject as invalid history, and closed a UI card that was never opened. Durable research compared the saved row's provider type against the type the client sent. Self-hosted connections are stored as openai and surfaced as llama_cpp, vllm, ollama or custom, so that check rejected exactly the connections the path exists to serve. It validates the saved row now. The saved-credential exception is scoped to the Deep Research workflow key rather than to any internally minted key, so a data-recipe subprocess key cannot spend a saved cloud credential. Pill state keyed on hosted builtins, so a self-hosted connection dropped the user's saved Search and Code preference on every reload and sent enable_tools: false while the composer left the pills clickable. The schema guard asserted an exact column set, so it failed on any unrelated column main added later. It now asserts what this change actually owns: the pre-existing columns stay readable and the capability is not persisted.
|
Thanks for building it and driving it in a browser with a control worktree. That is the most useful kind of report to get, and most of it landed. Everything below is now on the branch as of b1e6d04. Fixed The truncated-turn case was the best catch. Promotion is destructive, so once the healer lifts a call out of the text the markup is already gone, and discarding the call on The orphan The pill reset was exactly as you described. On the Code pill moving execution to the host, I took the conservative branch. Already fixed before your report The three failing tests and the One I do not think is real
On the credit paragraph Fair, and I will fix the wording. Per-connection framing from #8630 and the |
…, keep the resolved model id Three follow-ups from the same review pass. OpenAI's Responses API requires reasoning items to be passed back alongside the function call and its output; omitting them costs accuracy and the prompt-cache hit, and a reasoning item with nothing after it is rejected outright. Studio already captured those items but only the image-generation card read them, so a local tool call dropped them. They are replayed now, re-sanitized because the recorded copy carries a status the API refuses on input, buffered so a trailing reasoning item is never emitted, and carrying encrypted_content for orgs whose ids resolve to nothing. Capability sync only ever wrote rows the registry returned, so a provider that disappeared after a backend rollback kept studio_tools true in localStorage forever. Persisted capabilities are pruned to what the backend still reports. Clearing is the safe direction: an unknown capability reads as null, which every caller treats as not capable. The summed usage chunk reported the model the request asked for. OpenRouter and similar resolve a routing alias to a concrete model and name it on every chunk, which is the more specific answer, so that id wins.
…op draining a cancelled tool Streamed tool-call names arrive two ways and the loop handled only one at a time. llama-server re-sends the whole name as it grows, so appending produced webweb_search; OpenAI sends fragments that continue it, so assigning produced _search. Either way the name misses the enabled-tool check and the call silently never runs. A fragment that already starts with what we have is the name resent, anything else continues it. Usage hanging off a chunk that also carries a choice was relayed intact and then counted again in the summed chunk the loop emits at the end, so a client that adds up chunks double-counted the turn. The chunk cannot be withheld wholesale without losing its content, so only the usage block is dropped. A tool that does not watch the cancel event kept being asked for heartbeats after a Stop, holding the answer open. The consumer stops requesting them and lets the existing drain join the worker under its own bounded timeout.
|
@codex review |
A turn that streams tool_call fragments and then stops at finish_reason "length" has already put a card on the client, and the loop is right to refuse a call whose arguments are cut off mid-write. It left that card open for the rest of the response though, so it read as a tool that ran and returned nothing. Close it through the same unrun-call helper the budget and skipped paths use. Structured calls only: a call the healer recovered from text was never streamed, and the released markup span is what tells the user about that one. Also make the leaked-approval-slot assertion order independent. state .tool_approvals._pending is process global, and a sibling module that drives the route through the confirm gate leaves an entry behind, so asserting the whole registry is empty made that test pass or fail on collection order. Compare against the slots the test did not open instead.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0e2a2586f9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| selection.modelId, | ||
| ) === true; | ||
| const canSearch = supportsBuiltinWebSearch || supportsStudioToolsHere; | ||
| const canRunCode = supportsBuiltinCodeExecution || supportsStudioToolsHere; |
There was a problem hiding this comment.
Disable Code when no execution backend is usable
For a Studio-tools-capable provider whose selected model lacks its hosted code tool—for example OpenAI o3 or gpt-5.4—this expression still enables and restores the Code pill because the provider-level Studio capability is true. Downstream, selectCodeToolNames deliberately returns neither hosted nor local tools when the provider type owns a sandbox but the model cannot use it, so a Code-only send becomes enable_tools: false and silently answers without executing code. Derive this UI capability from the actual hosted/local placement rather than the general Studio-tools flag.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is the documented rule, not a gap. code-tool-placement.ts states it deliberately: a connection with its own sandbox keeps it, and a model on such a connection that cannot use it runs nothing, exactly as before the loop existed, rather than relocating execution onto the user's machine. Those are two different trust boundaries, so a persisted true must not change meaning underneath the user. Greying the pill for that combination is an affordance refinement on top of a deliberate decision, not a correctness bug.
There was a problem hiding this comment.
Confirmed, fixed in 57f91a7. The pill was keyed on the general Studio-tools flag, so a model on a sandbox-owning provider that cannot use that sandbox lit it and restored a stored preference, while selectCodeToolNames deliberately runs nothing there rather than relocating the work onto the user's machine. The pill is now read out of that placement rule itself, so what the composer offers and what the request carries cannot disagree, with a test that walks the whole placement matrix to keep it that way.
|
@codex review |
The pill was enabled from the general Studio-tools flag, so a model on a sandbox-owning provider that cannot use that sandbox, an OpenAI o3 for instance, lit it and restored a stored preference. The placement rule deliberately runs nothing there rather than relocating the work onto the user's machine, so a Code-only send became enable_tools: false and answered without executing anything. Read the pill out of the placement rule itself, which makes it impossible for what the composer offers and what the request carries to disagree.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 57f91a7768
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| except (RuntimeError, GeneratorExit): | ||
| pass | ||
|
|
||
| truncated = turn.finish_reason == "length" |
There was a problem hiding this comment.
Refuse tool calls from content-filtered turns
When an external provider streams a structured call and then terminates the candidate with finish_reason="content_filter"—for example, the native Gemini translator maps safety and blocklist stops to this value—this check treats the turn as complete rather than discarded, so turn.calls(...) proceeds and Studio may execute the blocked call locally. This can run Search automatically or reach Code under the configured permission mode despite the provider explicitly refusing the turn; refusal/content-filter finish reasons should terminate any announced calls without executing them, just as the length path does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 8cffa4c. length and content_filter are both refused now. stop deliberately stays executable: llama.cpp and vLLM routinely end a good tool call with it, and refusing those would disable tool calling on the self-hosted servers this path exists for.
| yield _SSE_KEEPALIVE | ||
| else: | ||
| yield _sse(event) | ||
| result = outcome.get("result", "") |
There was a problem hiding this comment.
Mark interrupted tool runs as cancelled
When /inference/cancel or a disconnect sets cancel_event while a tool that has not yet returned is running, the loop breaks at the cancellation check with no value in outcome, so this fallback turns the interruption into an empty successful result. record_result then records success and emits a normal tool_end, even though the worker may have been abandoned and may still be performing side effects; use an explicit cancellation result/state instead of treating the missing outcome as success.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and worse than described because a recent change made the path more reachable: the drain loop now breaks as soon as cancel_event is set, so outcome is empty and result defaulted to the empty string. record_result then reported a successful call with no output. Fixed in 1312925 with an explicit cancellation result that says the tool may already have done part of its work.
| assistant_message: dict[str, Any] = { | ||
| "role": "assistant", | ||
| # Markup never replays: the call is carried structurally below. | ||
| "content": strip_tool_markup( | ||
| "".join(turn.text), final = True, enabled_tool_names = allowed_tool_names |
There was a problem hiding this comment.
Replay hosted outputs across local tool turns
When a capable provider emits both a hosted-tool result and a Studio function call in the same turn—for example, Gemini returns codeExecutionResult plus a local web_search call, or OpenAI generates an image before requesting a local tool—the hosted result reaches the client only as a synthetic _toolEvent. This reconstructed assistant history retains text, reasoning, and local tool_calls but not those hosted output items, so the follow-up provider request loses data the model just produced and can synthesize an incorrect or incomplete final answer. Capture and replay the hosted native items, or continue the provider response by ID, before sending the local tool result.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. A hosted result produced in the same turn as a local call reaches the client as a synthetic _toolEvent but is not in the assistant history the loop replays, so the follow-up request loses what the model just produced. Not fixed here: capturing the native items per provider, or continuing by response id, is a larger change than the rest of this round and I would rather do it deliberately than late. Tracking as a follow-up.
…ted reasoning tool_choice "none" was advertised outbound but never enforced on the way back, so a provider that emitted a call anyway had it executed. Deep Research sets "none" precisely so the scraped third-party text its hops carry cannot reach python or terminal, which makes this the one place the instruction has to be a rule rather than a hint. A call arriving under "none" is now refused. A turn ending in content_filter was treated as executable. Like length, it means the model never finished saying what it wanted, so the arguments collected so far can be half written. Both are refused now. "stop" deliberately stays executable: llama.cpp and vLLM routinely end a perfectly good tool call with it, and refusing those would disable tool calling on the self-hosted servers this path is for. A pre-existing test asserted the reasoning replay sanitizer strips encrypted_content. It should not: a zero-data-retention org has store=false forced on it, so the item id resolves to nothing server side and the encrypted blob is the only thing carrying the model's reasoning state into the next request. The assertion was an exact dict match whose stated subject was the status field, so it now checks that and leaves the rest alone.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8cffa4cef5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # local implementation of those names either, so reading such a request as | ||
| # "local" would drop them just the same, only after also replacing the | ||
| # provider's search with ours. | ||
| return all(isinstance(name, str) and name in HOSTED_TOOL_NAMES for name in enabled) |
There was a problem hiding this comment.
Distinguish current local Search requests from legacy hosted ones
When Search is the only enabled tool on OpenAI, Gemini, Kimi, or OpenRouter, the current frontend sends enable_tools: true with enabled_tools: ["web_search"] (chat-adapter.ts:5061-5067), which this predicate classifies as a legacy hosted-tool request and routes around the Studio loop. The provider therefore executes and bills its hosted search even though the new adapter describes web_search as Studio-run and the connection dialog tells users that Search runs locally (chat-providers-dialog.tsx:1291-1294). Add an explicit discriminator for new local-tool requests rather than inferring legacy intent solely from the tool names.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it is the sharpest thing raised on this PR. The two requests are byte-identical, so the predicate cannot tell them apart, and I chose hosted because that is what the pre-change bundle meant and preserving it was the priority. The cost is exactly what you describe: the connections dialog says Search runs locally, and on OpenAI, Gemini, Kimi and OpenRouter it does not. An explicit discriminator on the new studio-tools request is the right fix, since it also lets an old cached bundle keep hosted search while a current one gets local. Tracking as a follow-up rather than changing the wire format late in this PR, and the disclosure wording should be corrected with it.
| "supports_streaming": True, | ||
| "supports_vision": True, | ||
| "supports_tool_calling": True, | ||
| "studio_tools": True, |
There was a problem hiding this comment.
Exclude Gemini image models from Studio-tool capability
When a Gemini image model such as gemini-2.5-flash-image is selected with MCP or document/RAG tools, this provider-wide capability enables the Studio loop and exposes those controls, but _stream_gemini sets text_tools_allowed = not is_image_model_strict and consequently emits no functionDeclarations for these models (external_provider.py:3801-3802,3972). The model never receives the selected local tools, so the request silently completes without using MCP or Docs; publish per-model studio_tools: false entries for the image models or support their function declarations before advertising the capability.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. _stream_gemini sets text_tools_allowed false for image models, so the catalog never reaches them while the provider-wide flag lit up the MCP and Docs pills. Fixed in 1312925: the backend gate is model-aware and leaves those models on the plain proxy. The pills are still driven by the provider-level capability in the frontend, so that half is a follow-up.
| try: | ||
| parsed = json.loads(arguments or "{}") | ||
| except (TypeError, ValueError, json.JSONDecodeError): |
There was a problem hiding this comment.
Handle recursively nested tool arguments
When an external or self-hosted model emits a syntactically valid but deeply nested JSON value in function.arguments, json.loads raises RecursionError, which is not covered by this exception handler. This escapes the tool loop after the provider's tool-call delta has already been relayed, producing a stream-level server error instead of safely rejecting the malformed call; catch RecursionError here and treat the arguments as invalid/raw input like the other decoding failures.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. Confirmed that json.loads raises RecursionError on deeply nested input and that RecursionError is not a ValueError, so it escaped the existing handler after the delta had already been relayed. Fixed in 1312925 by treating it as unparseable input.
…p Gemini image models A tool interrupted by Stop or a disconnect fell through to an empty result, which record_result then reported as a successful call with no output. The transcript claimed the tool ran and produced nothing, when it was abandoned partway and its side effects may already have happened. Cancellation now says so. Deeply nested but syntactically valid JSON in function.arguments raises RecursionError, which is not a ValueError, so it escaped the loop after the provider's tool-call delta had already been relayed and surfaced as a stream-level server error. It is treated as unparseable input like any other decoding failure. Gemini's image models drop the function catalog inside the native translator (text_tools_allowed is false for them), so the provider-wide capability flag was advertising a loop those models cannot participate in: the MCP and Docs pills lit up and the turn completed as though nothing had been selected. The gate is model-aware now and leaves them on the plain proxy.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The squash merge of #8665 kept only two trailers, so the four PRs that work was built out of are not attributed anywhere in main's history. Recording them here. #8626 (@khalidejaz) contributed the registry capability and the hidden-entry exposure, down to the provider_runs_local_tools() name. #8630 (@mahiatlinux) contributed the loop internals: the user-turn append, the tool-stream advance and drain, usage merging, the approval flush delay, the budget-exhausted nudge and the streamed tool-name fix, plus a number of its test cases. They also built the merged branch and drove it in a browser against a control worktree, which found several real defects before release, including a truncated turn discarding a healed call together with the text describing it. #7805 (@Etherll) contributed the hosted-provider reach. #7330 (@Souravrajvi0) is the original OpenAI-compatible framing the work started from. Two things were deliberately not taken, and the difference is worth recording: the per-connection framing from #8630 and the studio_tool_execution column from #7805. #8665 shipped a static disclosure instead while widening the capability from four self-hosted types to thirteen. Co-authored-by: Malik Khalid Ejaz <[email protected]> Co-authored-by: Maheswar Kumar <[email protected]> Co-authored-by: Etherl <[email protected]> Co-authored-by: Souravrajvi0 <[email protected]>
) The squash merge of #8665 kept only two trailers, so the four PRs that work was built out of are not attributed anywhere in main's history. Recording them here. #8626 (@khalidejaz) contributed the registry capability and the hidden-entry exposure, down to the provider_runs_local_tools() name. #8630 (@mahiatlinux) contributed the loop internals: the user-turn append, the tool-stream advance and drain, usage merging, the approval flush delay, the budget-exhausted nudge and the streamed tool-name fix, plus a number of its test cases. They also built the merged branch and drove it in a browser against a control worktree, which found several real defects before release, including a truncated turn discarding a healed call together with the text describing it. #7805 (@Etherll) contributed the hosted-provider reach. #7330 (@Souravrajvi0) is the original OpenAI-compatible framing the work started from. Two things were deliberately not taken, and the difference is worth recording: the per-connection framing from #8630 and the studio_tool_execution column from #7805. #8665 shipped a static disclosure instead while widening the capability from four self-hosted types to thirteen. Co-authored-by: Malik Khalid Ejaz <[email protected]> Co-authored-by: Maheswar Kumar <[email protected]> Co-authored-by: Etherl <[email protected]> Co-authored-by: Souravrajvi0 <[email protected]>
What changed
Studio's tools run on the Studio host, not on the model. Despite that, every external connection except one was a pure proxy: point Studio at your own llama.cpp, vLLM or Ollama server, or at OpenRouter, and Search, Code, MCP, Docs and Deep Research all greyed out.
The gate was not architectural. It was a hardcoded provider type, in three places:
openai_codexalready had a working Studio-owned tool loop over a network stream Studio does not control. This generalises that capability instead of adding a second implementation of it.providers.pydeclaresstudio_toolsper provider type, andprovider_runs_local_tools()replaces the hardcoded comparison. Hidden registry entries now reach/api/providers/registryflagged withhiddenrather than being filtered out, which is why the UI could never learn that the self-hosted presets are capable.core/inference/studio_tool_loop.pybehind aTransportprotocol.CodexTransportkeeps the app-server call and its conversation-affinity ids;OAICompatTransportwrapsExternalProviderClient.stream_chat_completion, which is the one function every provider re-yields through (the Anthropic, Gemini, Responses and Kimi sub-streams are each translated to OpenAI chunk shape and re-yielded there).delta.tool_calls, so the loop feeds content throughStreamToolCallHealer, the same bounded buffer the client-tool passthrough already uses. Only a trailing partial-signal window is ever withheld, and a block that cannot become a declared call flushes verbatim.tool_choice: "none"andenabled_tools: [], so a prompt-injected page in the evidence set still cannot steer a hop intopython.response_formatnow reaches OpenAI-compatible providers at all. It was silently dropped for every one of them, so JSON mode did nothing and Deep Research planning hops would have come back unparseable on any non-Codex provider.Why reuse the healer rather than write another buffer
A turn where the model opens a
<tool_call>envelope and never closes it has to render its text, not nothing.StreamToolCallHealeralready solves this properly:_partial_signal_suffixwithholds only the longest suffix that could still become a signal,_closed_signal_spanis the false-alarm escape, and_MAX_HOLD_CHARSis a backstop rather than the mechanism. No cap on user-controlled content is invented here, and there is no third streaming marker buffer to drift out of sync withtool_call_parser.pyandtool_healing.py.Anthropic is deliberately excluded
_stream_anthropiconly appends Anthropic's own hosted builtins and never forwards a caller's function-tool schemas, so the loop would advertise a catalog the model never sees. Enabling it needs OpenAI to Anthropic schema translation plustool_use/tool_resultmessage replay, which is separate work. Anthropic keeps its hostedweb_search,web_fetchandcode_executionin the meantime.Everything else is enabled: OpenAI, Gemini, OpenRouter, DeepSeek, Kimi, Qwen, Mistral, HuggingFace, and the four self-hosted presets (llama.cpp, vLLM, Ollama, custom).
Also fixes a live bug
chat-runtime-store.tsdisarmed Deep Research for anyexternal::model id, includingopenai_codex, which both the backend and the menu permit. Codex users had Deep Research silently switched off on every model switch and had to re-enable it by hand. It now gates on the capability rather than on the id prefix.Nothing on the existing paths moves
Every hunk in
routes/inference.pyis inside_proxy_to_external_provider, so the local GGUF, safetensors and MLX router is untouched.CodexTransportsetsheals_text_tool_calls = False, so the Codex path allocates no healer and behaves exactly as before. The healer is only constructed when a tool catalog is actually selected, so an external chat with no tools enabled is unchanged too.Measured on a 4,000 chunk synthetic stream:
The 10 us on the new path is roughly 0.05% of a typical inter-token gap, and applies only to a path that did not previously exist.
Verification
Backend, from
studio/backend: 2448 passed, 42 skipped. Frontend:tsc --noEmitclean, 2023 of 2023 tests passed.New coverage in
tests/test_studio_tool_loop.py(15 cases), including the ones that motivated this shape:<tool_call>envelope the model never closes releases its text as prose and terminates, rather than rendering an empty answerwebthenweb_searchintowebweb_searchand the call silently never runscall:NAME{...}and a fencedterminal[ARGS]{...}example are not promotedpermission_mode="auto"prompts on high risk onlyEnd to end against real hardware:
llama-server(CUDA) servingunsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XLwith--jinja, registered in Studio as allama_cppconnection.pythontool executed on the Studio host, result contained42,provenance.source = "local""Find latest Github issues in Unsloth github repo and devise fixes for each"drove five chainedweb_searchcalls (a listing search, a site-scoped search, then fetches of/issues, issue [Bug] Unsloth Studio: Claude Code fails with 401 despite following docs and having a valid key #8663 and issue [Bug] Docs: obsolete/missing linkstudio#model-arena#8652), returned real page content, hit the tool-call budget with the documented continue-anyway message, and synthesised per-issue fixesconfirm_tool_callsis now accepted for a capable provider, and a non-streaming request is still refused rather than silently proxied without confirmation supportKnown gap
An empty
<tool_call></tool_call>envelope emitted after a tool result leaks into the visible answer. The healer flushes closed-but-unparseable markup verbatim by design so it can never swallow real content, while the local path strips it throughStreamingMarkupStripper. Making the two consistent means touching shared display logic, where getting it wrong swallows user content, so it is left for a follow-up rather than rushed in here.Canvas (
render_html) and image generation are out of scope. Canvas is local-only even for Codex with no stated reason, and image generation is provider-hosted with no local fallback to widen. Both want their own change.Credit
This builds on four contributor PRs, and it is worth being precise about what was
taken and what was not.
Taken close to verbatim: the registry capability and the hidden-entry exposure from
#8626 (@khalidejaz), down to the
provider_runs_local_tools()name. Exposing thehidden entries behind an
include_hiddenopt-in is the one change on top, so acached pre-change bundle cannot render the self-hosted presets twice.
Taken in substance: the loop internals from #8630 (@mahiatlinux), including
_append_user_turn,_advance_tool_stream/_drain_step_task,_merge_usage/_usage_chunk_line, the approval flush delay, the budget-exhausted nudge and thestreamed tool-name fix, plus a number of its test cases.
Not taken, and the difference matters: #8630's per-connection framing, meaning the
enableLocalToolsfield, its persistence and the notice dialog, and #7805's(@Etherll)
studio_tool_executioncolumn and checkbox. This PR uses a staticdisclosure in the connections panel instead, while widening the capability from four
self-hosted types to thirteen. That is a real design difference rather than a
simplification of the same idea, and reviewers should weigh it as one.
#7330 (@Souravrajvi0) is the original OpenAI-compatible framing this line of work
started from.
Thanks to all four, and to @khalidejaz for the real-hardware vLLM report that pinned
down the non-terminating turn, and to @mahiatlinux for building this branch and
driving it in a browser against a control worktree.
Fixes #7282
Fixes #7761