Skip to content

Studio: run the local tool loop against every capable external provider - #8665

Merged
danielhanchen merged 20 commits into
mainfrom
feat/studio-tools-all-external-providers
Aug 13, 2026
Merged

danielhanchen merged 20 commits into
mainfrom
feat/studio-tools-all-external-providers

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

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:

routes/inference.py:11340   provider_type == "openai_codex" and _explicit_studio_tool_loop_requested(payload)
routes/inference.py:11449   -> stream_codex_with_studio_tools
research_runs.py:207        provider_type != "openai_codex" -> 400

openai_codex already 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.py declares studio_tools per provider type, and provider_runs_local_tools() replaces the hardcoded comparison. Hidden registry entries now reach /api/providers/registry flagged with hidden rather than being filtered out, which is why the UI could never learn that 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 and its conversation-affinity ids; OAICompatTransport wraps ExternalProviderClient.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).
  • Self-hosted models frequently write a tool call as text instead of emitting structured delta.tool_calls, so the loop feeds content through StreamToolCallHealer, 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.
  • Deep Research accepts any capable saved connection. The research hops keep tool_choice: "none" and enabled_tools: [], so a prompt-injected page in the evidence set still cannot steer a hop into python.
  • response_format now 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. StreamToolCallHealer already solves this properly: _partial_signal_suffix withholds only the longest suffix that could still become a signal, _closed_signal_span is the false-alarm escape, and _MAX_HOLD_CHARS is 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 with tool_call_parser.py and tool_healing.py.

Anthropic is deliberately excluded

_stream_anthropic only 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 plus tool_use / tool_result message replay, which is separate work. Anthropic keeps its hosted web_search, web_fetch and code_execution in 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.ts disarmed Deep Research for any external:: model id, including openai_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.py is inside _proxy_to_external_provider, so the local GGUF, safetensors and MLX router is untouched. CodexTransport sets heals_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:

path per chunk
Codex style, healing off 2.35 us
external, no tools selected 2.29 us
external, tools selected (healing on) 12.38 us

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 --noEmit clean, 2023 of 2023 tests passed.

New coverage in tests/test_studio_tool_loop.py (15 cases), including the ones that motivated this shape:

  • a <tool_call> envelope the model never closes releases its text as prose and terminates, rather than rendering an empty answer
  • a partial marker split across a delta boundary is not broken
  • streamed tool-name fragments are last-wins, not concatenated: llama-server re-sends the whole name as it grows, so appending turns web then web_search into webweb_search and the call silently never runs
  • markerless call:NAME{...} and a fenced terminal[ARGS]{...} example are not promoted
  • an undeclared name in text markup stays data
  • a denied or duplicate call does not spend a budget iteration
  • permission_mode="auto" prompts on high risk only

End to end against real hardware: llama-server (CUDA) serving unsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL with --jinja, registered in Studio as a llama_cpp connection.

Known 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 through StreamingMarkupStripper. 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 the
hidden entries behind an include_hidden opt-in is the one change on top, so a
cached 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 the
streamed tool-name fix, plus a number of its test cases.

Not taken, and the difference matters: #8630's per-connection framing, meaning the
enableLocalTools field, its persistence and the notice dialog, and #7805's
(@Etherll) studio_tool_execution column and checkbox. This PR uses a static
disclosure 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

shimmyshimmer and others added 2 commits August 13, 2026 10:21
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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines 589 to 590
for provider_type, info in PROVIDER_REGISTRY.items():
if info.get("hidden"):
continue
result.append(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +424 to +426
if decision == "deny":
decision_slot = None
result = TOOL_REJECTED_MESSAGE

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

shimmyshimmer and others added 3 commits August 13, 2026 11:14
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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +666 to +669
if not decision.should_execute:
completion = controller.record_noop(decision)
noop_messages.append(completion.model_message())
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +11789 to +11793
gen = stream_with_studio_tools(
OAICompatTransport(
client,
model = model,
continue_final_message = _continue_final_message(payload),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +489 to +491
# 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@mahiatlinux

Copy link
Copy Markdown
Contributor

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 origin/main in a second worktree as a control. Everything below ran locally; nothing is taken from the description. No GPU here, so training, CUDA, Triton and quantisation checks were skipped.

Branch under test ec531ecdc, baseline origin/main at 5e184f50c.

The feature works

Registering a llama_cpp connection and asking for the python tool:

  • the request carries tools=python,terminal, tool_choice=auto
  • the model wrote the call as text, split across six stream deltas (Let me compute that.\n<tool / _call> / {"name": "pyt / hon", ... / </tool_ / call>), and the healer stitched it
  • python executed on the Studio host, output 42
  • the result was replayed as a tool message with a matching tool_calls entry, and the model answered from it
  • the mock server logged exactly two turns

Same flow on origin/main: Search and Code render disabled, the Deep Research menu item is aria-disabled="true", and the outbound request carries no tool catalog at all. The before and after is real.

Other checks that passed:

  • terminal with rm -rf stops on "Waiting for approval" and does not run
  • <tool_call>{"name": "rm_rf_root", ...}</tool_call> for an undeclared name stays as text, no promotion
  • an unterminated <tool_call> envelope releases its prose and terminates rather than rendering nothing
  • live GET /api/providers/registry returns supports_studio_tools=false for anthropic only, and the four hidden self-hosted presets appear only under include_hidden=true, so the default response is unchanged for a cached bundle
  • frontend tsc --noEmit clean, npm test 2023/2023
  • the documented empty <tool_call></tool_call> leak reproduces exactly as described

Blocking: three tests fail on this branch and pass on main

$ pytest tests/test_studio_tool_loop.py tests/test_external_tool_edge_cases.py \
         tests/test_external_tools_compat.py tests/test_external_provider_usage_chunk.py \
         tests/test_openai_codex_subscription.py -q

FAILED tests/test_external_provider_usage_chunk.py::test_custom_provider_registry_is_hidden
FAILED tests/test_openai_codex_subscription.py::test_codex_studio_tool_loop_executes_and_continues
FAILED tests/test_openai_codex_subscription.py::test_codex_tool_budget_resolves_parallel_overflow_without_executing_it
3 failed, 149 passed

The same two files on origin/main, same interpreter and command: 58 passed.

  1. tests/test_external_provider_usage_chunk.py:204 raises StopIteration. next(p for p in list_available_providers() if p["provider_type"] == "custom") runs against a function whose default is now include_hidden = False, and custom is hidden, so the generator is empty. The assertions meant to lock in hidden and supports_studio_tools never execute.
  2. test_codex_studio_tool_loop_executes_and_continues asserts False.
  3. test_codex_tool_budget_resolves_parallel_overflow_without_executing_it raises KeyError: 'tool_call_id'.

The last two are on the pre-existing Codex path, which the description says does not move and that CodexTransport leaves behaving exactly as before. They also mean the reported "2448 passed, 42 skipped" is not reproducible on the branch as committed.

For context on the noise floor: the whole studio/backend/tests tree (torch-only files excluded) is 109 failed / 21,853 passed here versus 107 failed / 22,292 passed on main, and those baseline failures are all diffusion, video and precision tests that need a GPU.

finish_reason: "length" deletes a promoted call and its text

core/inference/studio_tool_loop.py:616

calls = turn.calls(...) if turn.finish_reason != "length" else []

A truncated turn discards every call, including ones the healer already promoted. Promotion is destructive: feed() removed the <tool_call>...</tool_call> span from the text events, so the text was never relayed either. The user loses both.

Reproduced in the browser with the same tool call as the working case, only ending the turn with finish_reason: "length". The rendered answer is Let me compute that. follow-up answer 42 with no tool card, no execution, and the tool-call markup gone. A small GGUF on llama-server with a modest max_tokens hits this.

max_tool_calls_per_message: 0 becomes 25

routes/inference.py:11807

max_calls = payload.max_tool_calls_per_message or 25,
timeout   = payload.tool_call_timeout or 300,

0 is an explicit value here, not unset. The field is ge = 0 and documented "0 = disabled", and the settings slider has min={0} and renders 0 as "Off" with "0 disables tool use". Every sibling call site in the same file guards correctly: Codex at :11527, GGUF at :12990, safetensors at :14392.

So the slider at Off with Search or Code on runs up to 25 local python or terminal calls against any external connection, while the same slider at 0 against a local GGUF correctly runs none. test_zero_budget_withdraws_the_catalog passes max_calls=0 straight into the loop, so it cannot catch the route-level coercion.

Budget exhaustion appends an orphan role=tool message

core/inference/studio_tool_loop.py:644

The budget branch appends {"role": "tool", "tool_call_id": call["id"], ...} and then continues, before assistant_tool_calls.append(decision.as_assistant_tool_call()) at line 670. The assistant message built at :825 therefore declares no matching tool_calls entry, and the next turn replays a tool result with no call to answer it. OpenAI, DeepSeek and a strict vLLM return 400 on that shape, and the exception is caught at :11864, so the user gets an error instead of the answer already paid for.

The same branch yields tool_end before tool_start at :694 is ever reached, which closes a UI card that was never drawn and breaks the len(tool_end) == len(tool_start) invariant test_disallowed_call_still_gets_a_tool_result_message asserts.

This is what test_codex_tool_budget_resolves_parallel_overflow_without_executing_it now raises KeyError: 'tool_call_id' on. #7330 sliced the round's calls to the remaining budget before building the list, which is the one-line fix.

The Search and Code pills reset to off every session

features/chat/chat-page.tsx:2216 and :2246 (duplicated at :2759, :2799)

Both external-selection handlers still derive pill state from hosted builtins:

const nextToolsEnabled = supportsBuiltinWebSearch ? (storedToolsEnabled ?? searchOnByDefault) : false;
codeToolsEnabled: supportsBuiltinCodeExecution ? (storedCodeToolsEnabled ?? false) : false,

providerSupportsBuiltinWebSearch returns false for llama_cpp, vllm, ollama, custom, deepseek, mistral, qwen and huggingface, so the stored preference is discarded even though supportsTools is now true and the composer leaves the pills clickable.

Reproduced: turn Search and Code on for a llama.cpp connection, reload, both come back off and enable_tools: false goes out. #7805 updated both defaults to (supportsBuiltinWebSearch || supportsStudioTools).

The Code pill moves execution from a cloud sandbox to the host with no signal

features/chat/api/chat-adapter.ts:5034

Before this change only openai_codex carried studio_tools, so codeToolsEnabled fell through to the hosted branch and sent code_execution, run in OpenAI's or Gemini's sandbox. Now supportsStudioToolsForThisTurn is true for openai and gemini, the Studio branch wins, and it sends ["python", "terminal"] to run locally.

codeToolsEnabled persists across the upgrade, permission_mode defaults to "auto" where only is_high_risk_tool_call prompts, and the only disclosure is a paragraph inside the Connections edit panel that the owner of an existing connection never reopens. Nothing in the composer or the stream says execution moved.

The same branch emits only search_knowledge_base, web_search, python and terminal; image_generation and web_fetch live only in the hosted branch at :5113, and the backend sends enabled_tools = None at routes/inference.py:11794. I did not reproduce the image-generation loss, which needs a real key, but the branch selection is unconditional.

Related, routes/inference.py:11736: mcp_allowed = bool(payload.mcp_enabled) has no and _cli_policy is not False, unlike the local paths at :12878 and :14331, so unsloth run --disable-tools no longer holds for the thirteen provider types this opens up.

On the credit paragraph

Two of the four attributions hold and are understated. #8626 gets "registry capability + hidden-entry exposure", which is exact down to the shared symbol name provider_runs_local_tools(), and making the hidden exposure opt-in via include_hidden is a genuine improvement on it. #8630's loop internals are carried over near-verbatim, comments included: _append_user_turn, _advance_tool_stream / _drain_step_task, _merge_usage / _usage_chunk_line, the 50 ms approval flush, _BUDGET_EXHAUSTED_NUDGE and the name-assignment fix.

Two do not:

"Hosted-provider reach" from #7805 is taken for the OpenAI-compatible family and native Gemini only. The Anthropic exclusion is stated clearly in its own section, so the gap is between that section and the credit line rather than a concealment, but #7805's function-tool translation and tool_use / tool_result replay are discarded rather than carried.

One more verification claim to re-check: "a non-streaming request is still refused rather than silently proxied without confirmation support" holds only when confirm_tool_calls is explicitly set. With stream: false and enable_tools: true, studio_tool_loop is false at :11354 and the request falls through to the plain proxy at :11817 with enabled_tools that the self-hosted family has no mapping for, so it returns 200 with no tools attached.

Suggested before merge

  1. Fix the three failing tests and re-run the number in the description.
  2. max_calls = payload.max_tool_calls_per_message if payload.max_tool_calls_per_message is not None else 25, matching the three sibling call sites. Same shape for tool_call_timeout.
  3. Build assistant_tool_calls before the budget branch, or slice the round's calls to the remaining budget, so no orphan role=tool message can be replayed, and move tool_start above the budget check.
  4. Keep promoted calls on a finish_reason: "length" turn, or put the consumed markup back into the visible text.
  5. Widen the pill defaults in chat-page.tsx to supportsBuiltinWebSearch || supportsStudioTools.
  6. Gate mcp_allowed on the CLI tool policy.
  7. Decide the consent question deliberately. Carrying Studio: Add opt-in tool execution for external providers #7805's per-connection column, or defaulting codeToolsEnabled off once on upgrade, would both close it.

The architecture is right and better than any of the four it supersedes: one loop behind a transport protocol, reusing StreamToolCallHealer and ToolLoopController rather than a fourth accumulator, with openai_codex_tool_loop.py shrinking by 345 lines to reuse it. The last-wins tool-name fragment handling alone fixes a real webweb_search class of bug. The list above is what stands between it and merging.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1158 to +1161
# 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"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

pre-commit-ci Bot and others added 3 commits August 13, 2026 12:44
…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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

shimmyshimmer and others added 2 commits August 13, 2026 13:06
… 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

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 finish_reason: "length" lost both. The healer now records the promoted span and a discarded call releases exactly what the model wrote, rather than a reconstruction from the parsed call. Structured calls release nothing extra, since nothing was stripped for them.

The orphan role=tool message is real and I want to be clear that you were right and an earlier review of mine was wrong. I had it measured as harmless. The shape that reaches the wire is parallel calls overflowing the budget, where one call runs and the next overflows, so the nudge turn still goes out. Printing the follow-up payload before and after shows declared=['c1'] ORPHANS=['c2'] becoming declared=['c1','c2'] ORPHANS=[]. I did not take the slicing approach from #7330, because slicing deletes the refused calls before the model is ever told they were refused, and the loop deliberately answers them so it stops asking. Pairing the result with its call fixes the invalid history without changing what the model is told. The tool_end without a tool_start is fixed too, with the exception that a call naming a tool this install never offered gets no card at all rather than a paired one, since painting a card advertises a tool the user switched off.

The pill reset was exactly as you described. chat-page.tsx was untouched by the branch, and both duplicated blocks derived pill state from the hosted builtins, so providerSupportsBuiltinWebSearch being false for llama_cpp, vllm, ollama and custom discarded the stored preference and sent enable_tools: false while the composer left the pills clickable. Both now key on supportsBuiltinWebSearch || supportsStudioTools.

On the Code pill moving execution to the host, I took the conservative branch. code_execution and python/terminal are two trust boundaries rather than two spellings of one feature, and a persisted toggle should not change which machine runs model-authored code as a side effect of an update. A connection with its own sandbox keeps it, and Studio's local tools are for connections that have none. image_generation and web_fetch are no longer dropped either.

Already fixed before your report

The three failing tests and the max_tool_calls_per_message or 25 coercion. You tested ec531ec and both landed after it. The budget catch was correct: all four sites now use the explicit is not None form, so a documented 0 stays 0.

One I do not think is real

mcp_allowed = bool(payload.mcp_enabled) without the CLI policy check. The external loop is gated on _explicit_studio_tool_loop_requested, which returns False when the policy is False, so unsloth run --disable-tools still holds and mcp_allowed is never reached. Happy to be shown otherwise if you have a repro.

On the credit paragraph

Fair, and I will fix the wording. Per-connection framing from #8630 and the studio_tool_execution column from #7805 were genuinely not taken, and the body should say what was harvested rather than implying the framing came with it. The capability surface going from four self-hosted types to thirteen without a per-connection opt-in is a real difference from your PR and should be stated plainly rather than glossed.

…, 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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", "")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1032 to +1036
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +156 to +158
try:
parsed = json.loads(arguments or "{}")
except (TypeError, ValueError, json.JSONDecodeError):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen
danielhanchen merged commit 0e158a8 into main Aug 13, 2026
46 of 58 checks passed
@danielhanchen
danielhanchen deleted the feat/studio-tools-all-external-providers branch August 13, 2026 14:37
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 1312925f57

ℹ️ 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".

danielhanchen added a commit that referenced this pull request Aug 14, 2026
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]>
danielhanchen added a commit that referenced this pull request Aug 14, 2026
)

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Add toolcalling etc for external API calls [Bug] Remote Models not able to do Tool Calling

3 participants