Repository navigation
Copilot Chat: expose the chat session id to language model request middleware - #337203
Closed
Niels Kootstra (nkootstra) wants to merge 10 commits into
Closed
Niels Kootstra (nkootstra) wants to merge 10 commits into
Niels Kootstra (nkootstra) wants to merge 10 commits into
Conversation
Move the reserved header list and the forbidden prefix check out of OpenAIEndpoint into byok/common/requestHeaders.ts so a second header source can reuse them, and merge custom headers case-insensitively so a configured `X-Shared` and `x-shared` are not both sent. Sanitiser warnings now name their source instead of always blaming the model configuration.
Add registerLanguageModelRequestMiddleware to the Copilot Chat extension API (getAPI(2)) so an extension can attach headers to each BYOK language model request: a short-lived credential from an auth provider, the signed-in user, the chat session, or the work item, for gateways that need more than a static key in chatLanguageModels.json.
A registry invokes matching middleware concurrently with a timeout and the request's cancellation token, merges results in registration order, and every OpenAI-compatible provider applies them through the same sanitiser as `requestHeaders`. On customendpoint that lets middleware supply Authorization or api-key and suppresses the default credential, as configuration already can; other providers keep their own credential. Middleware values are never `${apiKey}`-interpolated.
Related: microsoft#316794, microsoft#329469
Do not log rejected header values, which may be credentials. Discard the error of a middleware registration disposed while in flight, matching the documented contract. Cover the Azure Entra ID request path with a provider-level middleware test, sharing the capturing chat fetcher between the BYOK provider specs.
Contributor
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The shared mutable middleware context permits cross-extension URL tampering, and the session fallback violates the documented non-chat contract.
Get a fresh assessment by requesting another Copilot review.
Review effort: Balanced
Findings: 1
Open (2)
What changed in this PR
Exposes chat session IDs to BYOK request middleware for per-chat request correlation.
Changes:
- Propagates session IDs through Agent Host, language-model APIs, and providers.
- Adds request middleware registration and safe header merging.
- Adds coverage for middleware, providers, credentials, and session propagation.
| File | Description |
|---|---|
src/vscode-dts/vscode.proposed.chatProvider.d.ts |
Adds provider group and session options. |
src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostByokLmHandler.test.ts |
Tests handler session forwarding. |
src/vs/workbench/contrib/chat/common/languageModels.ts |
Adds session ID to request options. |
src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.ts |
Forwards Agent Host session IDs. |
src/vs/workbench/api/common/extHostLanguageModels.ts |
Forwards group and session metadata. |
src/vs/platform/agentHost/test/node/byokLmProxyService.test.ts |
Tests proxy session extraction. |
src/vs/platform/agentHost/node/copilot/byokLmProxyService.ts |
Adds authenticated session to bridge requests. |
src/vs/platform/agentHost/common/agentHostByokLm.ts |
Extends bridge request contract. |
extensions/copilot/src/extension/test/node/services.ts |
Registers middleware in tests. |
extensions/copilot/src/extension/extension/vscode/services.ts |
Registers the middleware service. |
extensions/copilot/src/extension/byok/vscode-node/xAIProvider.ts |
Injects middleware into xAI. |
extensions/copilot/src/extension/byok/vscode-node/test/openRouterProvider.spec.ts |
Updates OpenRouter test setup. |
extensions/copilot/src/extension/byok/vscode-node/test/ollamaProvider.spec.ts |
Updates Ollama test setup. |
extensions/copilot/src/extension/byok/vscode-node/test/languageModelRequestMiddleware.spec.ts |
Tests registry behavior. |
extensions/copilot/src/extension/byok/vscode-node/test/customEndpointProvider.spec.ts |
Tests headers and session fallback. |
extensions/copilot/src/extension/byok/vscode-node/test/capturingChatMLFetcher.ts |
Adds request-capturing test helper. |
extensions/copilot/src/extension/byok/vscode-node/test/azureProvider.spec.ts |
Tests Azure Entra middleware behavior. |
extensions/copilot/src/extension/byok/vscode-node/openRouterProvider.ts |
Integrates OpenRouter middleware. |
extensions/copilot/src/extension/byok/vscode-node/openAIProvider.ts |
Integrates OpenAI middleware. |
extensions/copilot/src/extension/byok/vscode-node/ollamaProvider.ts |
Integrates Ollama middleware. |
extensions/copilot/src/extension/byok/vscode-node/customOAIProvider.ts |
Integrates custom OpenAI middleware. |
extensions/copilot/src/extension/byok/vscode-node/customEndpointProvider.ts |
Applies middleware credentials and headers. |
extensions/copilot/src/extension/byok/vscode-node/azureProvider.ts |
Applies middleware on Entra requests. |
extensions/copilot/src/extension/byok/vscode-node/abstractLanguageModelChatProvider.ts |
Builds middleware request context. |
extensions/copilot/src/extension/byok/node/test/openAIEndpoint.spec.ts |
Tests reserved credential handling. |
extensions/copilot/src/extension/byok/node/openAIEndpoint.ts |
Sanitizes and applies middleware headers. |
extensions/copilot/src/extension/byok/common/requestHeaders.ts |
Adds shared header utilities. |
extensions/copilot/src/extension/byok/common/languageModelRequestMiddleware.ts |
Implements middleware registry. |
extensions/copilot/src/extension/api/vscode/extensionApi.ts |
Exposes middleware registration API. |
extensions/copilot/src/extension/api/vscode/api.d.ts |
Documents the public API. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
The registry passed one context object to every matching middleware, so a registration could change the URL another one validates before it returns a credential. Each invocation now receives its own frozen copy.
Middleware could not tell which chat a request belongs to, so gateways such as LiteLLM could not group requests per chat session. The session identity already existed on both chat paths but never reached the provider: the agent host proxy authenticates each request with the session id in its bearer, and the Copilot participant passes the conversation id through the model options. The proxy now sets the session id on the bridge request, the agent host handler copies it onto the language model request options, and the extension host forwards it to the provider as `sessionId` on `ProvideLanguageModelChatResponseOptions`. The BYOK providers put it in the middleware context, falling back to the participant's conversation id, and the API documents it with a LiteLLM example.
The session id fallback read `_conversationId` from the request's model options. Those are caller-controlled on `vscode.lm` requests, so any extension could make middleware attribute its request to a chat session it does not own, and a non-string value would have been passed through. Only use the fallback when the request was initiated by this extension, whose chat participant is the one setting the option, and only when the value is a string. Requests from core carry the session id in the request options and are unaffected.
Niels Kootstra (nkootstra)
force-pushed
the
feat/copilot-request-middleware-session
branch
from
September 22, 2026 05:39
3c18ff7 to
797ccbe
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Stacked on #337130 and depends on it. Only the last two commits,
copilot: expose the chat session id to language model request middlewareandcopilot: only trust the conversation id from the chat participant, belong to this PR; the rest is the base PR.Summary
sessionId, the chat session a request belongs to, so an extension can tag every request of one chat with the same id and let a gateway group them. A new chat gets a new id, and separate VS Code windows have separate sessions.sessionIdisundefinedfor requests that are not made from a chat session, such as an extension callingvscode.lmdirectly.chatProviderAPI gainsProvideLanguageModelChatResponseOptions.sessionId(one d.ts field), and core forwards it along the chat path. That part needs API owner sign-off and can be reshaped independently of the rest.Why
Gateways such as LiteLLM attach requests to a session through a request header (
x-litellm-session-id), which is what makes per-chat grouping and cost views work. Withcustomendpointthe extension does not control the network request, so the only way to send such a header is through the middleware, and the middleware had no way to tell which chat a request came from. It could tell the vendor, model, URL and provider group apart, but two chats on the same model looked identical.Technical context for AI-assisted review
Previous behavior
The session identity existed on both chat paths but never reached the provider. On the agent host path, the loopback proxy in
byokLmProxyService.tsauthenticates every request with a bearer of the form<nonce>.<sessionId>and then discarded the session id after the check. On the Copilot participant path,extChatEndpoint.tspasses the conversation id to the provider insidemodelOptions._conversationId, which the BYOK providers did not read for the middleware context.Implementation
The proxy sets the authenticated session id on the bridge request (
IByokLmChatRequest.sessionId).AgentHostByokLmHandlercopies it ontoILanguageModelChatRequestOptions.sessionId, andextHostLanguageModels.tsforwards it to the provider asProvideLanguageModelChatResponseOptions.sessionId.AbstractOpenAICompatibleLMProvider.applyRequestMiddlewareputs it in the middleware context, taking the option from core first and the participant path's_conversationIdas fallback. The fallback is only used when the request was initiated by the Copilot Chat extension itself (requestInitiatorequalsIEnvService.extensionId) and the value is a string, becausemodelOptionsis caller-controlled onvscode.lmrequests.LanguageModelRequestContext.sessionIdis documented in the Copilot extension API together with the LiteLLM example above.Behavior and constraints
vscode.lmcallers outside a chat carryundefined. Another extension cannot attribute its request to a chat session by putting_conversationIdin its model options: the fallback ignores it for every initiator other than Copilot Chat.Validation
_conversationIdis used for requests initiated by this extension, and it is ignored for other initiators, for non-string values and when absent. The Azure Entra test and the registry fixture include the field.vitestforsrc/extension/byokandsrc/extension/api,tsc --noEmitfor the Copilot extension,npm run typecheck-clientat the repo root,scripts/test.sh --grep "ByokLmProxyService|AgentHostByokLmHandler",eslinton changed files andnpm run hygienepass.