Skip to content

agentHost: stream BYOK model output as it is produced - #341851

Merged
Vritant Bhardwaj (vritant24) merged 6 commits into
microsoft:mainfrom
NeoMetric:agents/fix-byok-models-streaming-issue
Nov 12, 2026
Merged

Vritant Bhardwaj (vritant24) merged 6 commits into
microsoft:mainfrom
NeoMetric:agents/fix-byok-models-streaming-issue

Conversation

@NeoMetric

@NeoMetric Midhun C N (NeoMetric) commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Description

BYOK model responses were buffered until completion, so streamed output appeared all at once. This change forwards model deltas over the agent-host bridge and emits Responses SSE frames as they arrive, while retaining the complete result as the authoritative response.

It also preserves provider state across continuations and reports errors before or after streaming begins. The safe HTTP response and error lifecycle is:

  • A failure before any visible output still answers with its JSON status (502 for a provider error, a non-retryable 422 for an empty reply to a user message), so retries and messages behave as they did before.
  • A failure discovered after visible output already reached the client closes the response as a normal completion instead of response.failed, so the runtime does not retry the turn and resend text the user already has.
  • That interruption is made visible in the message: a fixed note, _Response interrupted: the model stopped before finishing. Try again._, is appended to the answer (opening a message item when the open item is a reasoning or tool-call item). The provider's own error is not included, since it is not meant for display and is already logged by the agent host.

Related to #340983 (incremental streaming; cancellation is a separate issue).

How to test

In a dev build:

  1. Configure a BYOK model and ask for a long response. Text should appear incrementally rather than all at once.
  2. Ask it to use a tool and confirm the continuation completes, and that a second question keeps the provider state (no "unknown response id" errors).
  3. Point the model at an endpoint that fails before producing anything. The turn should fail with the descriptive error and show no partial text.
  4. Produce an empty reply to a user message. The turn should fail with the context-window/token-limit message without retrying.
  5. Interrupt the provider after the first tokens arrive (drop the connection mid-response). The partial answer should appear exactly once, no retry should resend it, and the message must end with _Response interrupted: the model stopped before finishing. Try again._. The provider's error text must not appear in the message.

Verification

On Windows, on the current branch head:

  • node build/next/index.ts transpile — passed (client sources compile on the rebased base).
  • ESLint over the changed TypeScript files — passed.
  • BYOK unit tests (byokResponsesTranslation.test.ts, byokLmProxyService.test.ts, byokLmBridgeRegistry.test.ts) — 65 passed.
  • BYOK Responses provider integration tests (copilotByokResponses.integrationTest.ts) — 5 passed, including streamed output followed by a provider failure, and the streamed tool-call continuation.
  • Manual check in a dev build: streamed output appears as it is produced, and a tool call continuation completes.

pnpm run build-fast, pnpm run typecheck-client and pnpm run valid-layers-check passed earlier in this PR; they were not re-run for the last patch because the local dependency install is behind the lockfile's Copilot SDK pin, so the client was transpiled directly and the focused tests above were run instead.

Copilot AI balanced review requested due to automatic review settings October 15, 2026 19:24

@NeoMetric Midhun C N (NeoMetric) left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@microsoft-github-policy-service agree

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved defects affect SSE sequencing, continuation IDs, encrypted reasoning state, and empty-response handling.

4 open findings
What changed in this PR

Streams BYOK model output incrementally from the renderer through the agent host’s Responses proxy, while preserving the final completion result.

Changes:

  • Adds request-tagged delta events across the IPC bridge.
  • Introduces incremental SSE emission, deferred headers, and wire response-ID mapping.
  • Expands streaming tests and updates bridge mocks.
File Description
src/​vs/​workbench/​contrib/​chat/​test/​browser/​agentSessions/​agentHostByokLmHandler.test.ts Tests delta ordering and opt-in streaming.
src/​vs/​workbench/​contrib/​chat/​browser/​agentSessions/​agentHost/​agentHostByokLmHandler.ts Publishes model output deltas.
src/​vs/​platform/​agentHost/​test/​node/​providerIntegration/​copilotOtel.integrationTest.ts Updates bridge mock.
src/​vs/​platform/​agentHost/​test/​node/​providerIntegration/​copilotManagedPermissions.integrationTest.ts Updates bridge mock.
src/​vs/​platform/​agentHost/​test/​node/​providerIntegration/​copilotByokSelectionIds.integrationTest.ts Updates bridge mock.
src/​vs/​platform/​agentHost/​test/​node/​providerIntegration/​copilotByokResponses.integrationTest.ts Exercises streamed responses with the SDK.
src/​vs/​platform/​agentHost/​test/​node/​copilotSessionLauncher.test.ts Updates bridge mocks.
src/​vs/​platform/​agentHost/​test/​node/​copilotAgent.test.ts Updates bridge mocks.
src/​vs/​platform/​agentHost/​test/​node/​byokResponsesTranslation.test.ts Tests incremental SSE translation.
src/​vs/​platform/​agentHost/​test/​node/​byokLmProxyService.test.ts Tests streaming, failures, and continuation mapping.
src/​vs/​platform/​agentHost/​test/​node/​byokLmBridgeRegistry.test.ts Updates bridge mock.
src/​vs/​platform/​agentHost/​test/​node/​agentHostUtilityModelService.test.ts Updates bridge mock.
src/​vs/​platform/​agentHost/​test/​node/​agentHostClientByokLmChannel.test.ts Tests delta forwarding.
src/​vs/​platform/​agentHost/​node/​copilot/​byokResponsesTranslation.ts Adds incremental SSE emitter.
src/​vs/​platform/​agentHost/​node/​copilot/​byokLmProxyService.ts Relays deltas and manages response lifecycle.
src/​vs/​platform/​agentHost/​common/​agentHostClientByokLmChannel.ts Exposes delta events over IPC.
src/​vs/​platform/​agentHost/​common/​agentHostByokLm.ts Defines streaming request and delta contracts.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@NeoMetric Midhun C N (NeoMetric) left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@microsoft-github-policy-service agree

@NeoMetric
Midhun C N (NeoMetric) force-pushed the agents/fix-byok-models-streaming-issue branch from 11ad0d2 to bbb2ae8 Compare October 18, 2026 05:36
@NeoMetric

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

@NeoMetric
Midhun C N (NeoMetric) force-pushed the agents/fix-byok-models-streaming-issue branch 6 times, most recently from 298dd3e to c78132c Compare November 3, 2026 04:34

@NeoMetric Midhun C N (NeoMetric) left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Requesting reviews

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Note

This review, including the inline comments, was written by an AI agent (GitHub Copilot) on behalf of Vritant Bhardwaj (@vritant24), based on building the branch and testing it in Code OSS.

Thanks for this, the streaming works well end to end. I built the branch and ran it in Code OSS (Agents window, local agent host) against a mock OpenAI-compatible BYOK provider that sends one word every 150 ms.

Scenario Result
Long reply ✅ Text renders incrementally (37 → 253 chars over ~6 s) instead of all at the end
Tool call ✅ Streamed text, tool runs, continuation resolves, final answer streams
Empty reply to a user message ✅ Single request, descriptive 422, no retries
Stop partway through ✅ UI stops immediately (renderer keeps generating, see note below)
Provider connection drops partway through ❌ Partial text is duplicated 6 times (inline comment)
Unit tests from the description, plus copilotAgent.test.ts, on macOS ✅ 1303 passing, 1 pending

The mid-stream failure is the one blocking issue for me. The other inline comments are smaller.

Follow-up, not for this PR: Stop doesn't cancel the model call in the renderer. channel.call('chat', request) passes no cancellation token and AgentHostClientByokLmChannel.call uses CancellationToken.None. In my test the model kept generating for about 2 s after Stop, and every delta still crossed IPC before the proxy discarded it. Now that output streams, Stop is common mid-answer, so it would be worth wiring the request's AbortController through as a cancellation token.

@NeoMetric
Midhun C N (NeoMetric) force-pushed the agents/fix-byok-models-streaming-issue branch from c78132c to 5f8e2a8 Compare November 4, 2026 05:29
@NeoMetric

Copy link
Copy Markdown
Contributor Author

Vritant Bhardwaj (@vritant24) Pushed fixes for all 4 comments, replied on each thread — could you approve the workflow run when you get a chance? Thanks!

@NeoMetric
Midhun C N (NeoMetric) force-pushed the agents/fix-byok-models-streaming-issue branch from bfee534 to 43e39e0 Compare November 6, 2026 05:22
BYOK completions were buffered: the proxy awaited the whole renderer call
before writing a single OpenAI Responses SSE frame, so a reply appeared all
at once however the provider streamed it.

The bridge keeps `chat()` as the authoritative round trip and adds a
one-way delta stream on the same channel, tagged with a request id the
proxy mints. The renderer publishes each part just before folding it into
the result, so replaying the deltas reproduces the output the caller
receives, and the proxy writes frames as they arrive.

Headers are committed on the first delta instead of up front, so a request
that produces no output keeps the JSON status it always had, including the
422 for an empty reply to a user message, and a failure after output was
written is reported as `response.failed`. The proxy also advertises its own
response id and maps a client echo of it back to the provider state id,
which keeps tool continuations explicit.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Pre-generate response skeleton frames when creating the SSE emitter so
  wire sequence numbers begin at 0 and are strictly increasing.
- Stage invisible initial frames (whitespace or metadata-only reasoning)
  until visible output arrives, preserving the 422 JSON error on empty
  replies to user messages.
- Retain a bounded, scoped wire-to-provider response ID mapping for all
  stateful responses independently of the one-shot tool-recovery cache,
  allowing echoed previous_response_id to resolve to provider state IDs.
- Update reasoning encryptedContent on each delta carrying defined state
  so output_item.done reflects the latest folded state.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The visible-delta path committed the stream and then wrote the frames directly, bypassing the abort/ended guard in write(). A delta that arrived after the client disconnected was therefore still written to a response that was already closed. Route every delta through write(), which commits first and then writes, so staged frames and the visible-delta path share one guarded write.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…vider

Address review comments on the BYOK streaming rebase:

- byokResponsesTranslation.ts: add isMintedResponseId() to recognize
  response ids this proxy minted itself (resp_byok_* prefix), as opposed
  to ids a provider issued.
- byokLmProxyService.ts: when a client echoes a previous_response_id that
  is a minted id with no known mapping (e.g. evicted from the capped
  continuation map, or left over from before a rebind), drop it instead
  of forwarding it to the provider, which would hand the provider an id
  it never issued.
- agentHostByokLm.ts: fix doc comment on encryptedContent - later values
  replace earlier ones, not just the first occurrence.
- byokLmProxyService.test.ts: add a regression test for the
  dropped-unmapped-minted-id behavior.
- copilotByokResponses.integrationTest.ts: add streamDeltas coverage to
  the tool-continuation integration test; remove a leftover diagnostic
  scaffold test (no assertions, stray console.log) that was failing the
  integration runner's no-console-output check.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ot a retryable failure

Fixes a review comment the previous commits on this branch missed: once a BYOK Responses stream has committed visible output, a later provider failure (connection drop, bridge error, thrown exception) sent that failure in-stream as 'response.failed'. The bundled runtime retries a 'response.failed' turn from scratch, resending the request, and each retry re-streams the already-shown text: a partial answer could be repeated 6 times before the retries were exhausted.

'response.completed' is closed with whatever reached the client instead: a runtime only retries when the stream does not end in 'response.completed', regardless of the error.code/type on a 'response.failed' frame (tried 'server_error' and 'invalid_request_error') or of using the spec-correct 'response.incomplete' terminal status (also retried). The failure is now only logged server-side in byokLmProxyService.ts, not surfaced in-stream; a client that already has partial output sees it once, with no error banner, instead of either losing it or seeing it duplicated.

Also fixes the integration test harness: withSdkSession never set 'streaming: true' on client.createSession(...), so the bundled SDK never requested a streamed response from the proxy -- every existing streamDeltas-based test in this file was passing via the non-streaming JSON fallback (whose final 'assistant.message'/'assistant.reasoning' events fire regardless of streaming) without ever exercising the SSE path the tests intended to cover. Production code (copilotSessionLauncher.ts) already sets 'streaming: true'; only the test harness was missing it.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@NeoMetric
Midhun C N (NeoMetric) force-pushed the agents/fix-byok-models-streaming-issue branch from 43e39e0 to 1b58906 Compare November 9, 2026 16:49
@NeoMetric

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest main, so a fresh review would be great whenever someone has a moment.

@vritant24

Vritant Bhardwaj (vritant24) commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Note

This comment was written by an AI agent (GitHub Copilot) on behalf of Vritant Bhardwaj (@vritant24).

Midhun C N (@NeoMetric) thanks for the rebase. One request from the review is still open: this follow-up. Its thread was marked resolved, but the change isn't in the branch yet. The Nov 6 and Nov 9 force pushes were rebases only; git range-diff shows all five commits unchanged since bfee534f9b.

The fix for the duplicated text works. However, when the provider fails after output has started, the response now just stops, and nothing tells the user it's incomplete. Could you:

  • In fail() in byokResponsesTranslation.ts, push one more text delta before closing the open item and emitting response.completed:
    \n\n_Response interrupted: the model stopped before finishing. Try again._
    
    Keep the text fixed and generic, without the provider's error message (it's already logged). If the open item isn't a message (for example, a reasoning item), open a message item for the note, the same way push() does for a text delta.
  • Update the integration test to assert that the final message ends with this note, still with exactly one call and no duplicated text.
A provider failure discovered after visible output was already streamed
closes the response as a completion, so the runtime does not retry and
resend the partial text. That left the answer silently truncated, with
the failure only in the agent host log.

Append a fixed note to the message before closing the response, opening
a message item when the open item is not one (for example a reasoning
item). The provider's error stays server-side. Cover it in the emitter
unit tests, the proxy test, and the SDK integration test.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@vritant24
Vritant Bhardwaj (vritant24) merged commit da14cdc into microsoft:main Nov 12, 2026
93 of 96 checks passed
@vs-code-engineering vs-code-engineering Bot added this to the 1.147.0 milestone Nov 12, 2026

@Caffeine19 UnnecTrycat (Caffeine19) 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.

Really thanks🤗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

7 participants