Skip to content

Copilot Chat: expose the chat session id to language model request middleware - #337203

Closed
Niels Kootstra (nkootstra) wants to merge 10 commits into
microsoft:mainfrom
nkootstra:feat/copilot-request-middleware-session
Closed

Niels Kootstra (nkootstra) wants to merge 10 commits into
microsoft:mainfrom
nkootstra:feat/copilot-request-middleware-session

Conversation

@nkootstra

@nkootstra Niels Kootstra (nkootstra) commented Sep 22, 2026 •

Copy link
Copy Markdown

Stacked on #337130 and depends on it. Only the last two commits, copilot: expose the chat session id to language model request middleware and copilot: only trust the conversation id from the chat participant, belong to this PR; the rest is the base PR.

Summary

  • The request middleware context from Copilot Chat: let extensions contribute request headers to BYOK language model requests #337130 now carries 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.
  • sessionId is undefined for requests that are not made from a chat session, such as an extension calling vscode.lm directly.
  • To make the id available to the provider, the proposed chatProvider API gains ProvideLanguageModelChatResponseOptions.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. With customendpoint the 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.

copilot.registerLanguageModelRequestMiddleware({
	selector: { vendors: ['customendpoint'] },
	provideRequestHeaders: async ({ sessionId }) =>
		sessionId ? { 'x-litellm-session-id': sessionId } : {},
});
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.ts authenticates 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.ts passes the conversation id to the provider inside modelOptions._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). AgentHostByokLmHandler copies it onto ILanguageModelChatRequestOptions.sessionId, and extHostLanguageModels.ts forwards it to the provider as ProvideLanguageModelChatResponseOptions.sessionId. AbstractOpenAICompatibleLMProvider.applyRequestMiddleware puts it in the middleware context, taking the option from core first and the participant path's _conversationId as fallback. The fallback is only used when the request was initiated by the Copilot Chat extension itself (requestInitiator equals IEnvService.extensionId) and the value is a string, because modelOptions is caller-controlled on vscode.lm requests. LanguageModelRequestContext.sessionId is documented in the Copilot extension API together with the LiteLLM example above.

Behavior and constraints

  • The id is the chat session id that core already uses for the session, not a new identifier. It is stable for the lifetime of a chat and differs between chats and between windows.
  • The id is only exposed to middleware; it is not added to any request by default.
  • Requests from vscode.lm callers outside a chat carry undefined. Another extension cannot attribute its request to a chat session by putting _conversationId in its model options: the fallback ignores it for every initiator other than Copilot Chat.

Validation

  • Unit tests: the proxy test asserts the authenticated session id reaches the bridge request, and the agent host handler test asserts it reaches the language model request options. The custom endpoint provider test asserts the id reaches the middleware context, and a new test covers the fallback: the core option wins, _conversationId is 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.
  • vitest for src/extension/byok and src/extension/api, tsc --noEmit for the Copilot extension, npm run typecheck-client at the repo root, scripts/test.sh --grep "ByokLmProxyService|AgentHostByokLmHandler", eslint on changed files and npm run hygiene pass.

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.

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.

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 High severity · 1 Medium severity

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.
@nkootstra
Niels Kootstra (nkootstra) force-pushed the feat/copilot-request-middleware-session branch from 3c18ff7 to 797ccbe Compare September 22, 2026 05:39
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.

3 participants