Repository navigation
Copilot Chat: let extensions contribute request headers to BYOK language model requests - #337130
Closed
Niels Kootstra (nkootstra) wants to merge 9 commits into
Closed
Niels Kootstra (nkootstra) wants to merge 9 commits into
Niels Kootstra (nkootstra) wants to merge 9 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
Author
|
@microsoft-github-policy-service agree |
Contributor
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Disposal can still propagate failures, rejected credentials can leak into logs, and the Entra integration lacks regression coverage.
Get a fresh assessment by requesting another Copilot review.
Review effort: Balanced
Findings: 1
Open (3)
What changed in this PR
Adds API v2 support for extension-contributed, request-scoped headers across OpenAI-compatible BYOK providers.
Changes:
- Adds middleware registration, selection, timeout, cancellation, and ordered header merging.
- Applies sanitized headers across BYOK providers, including custom credential overrides.
- Adds service wiring and focused tests.
| File | Description |
|---|---|
extension/test/node/services.ts |
Registers middleware in tests. |
extension/extension/vscode/services.ts |
Registers the runtime service. |
byok/vscode-node/xAIProvider.ts |
Injects middleware support. |
byok/vscode-node/test/openRouterProvider.spec.ts |
Updates provider setup. |
byok/vscode-node/test/ollamaProvider.spec.ts |
Updates provider setup. |
byok/vscode-node/test/languageModelRequestMiddleware.spec.ts |
Tests registry behavior. |
byok/vscode-node/test/customEndpointProvider.spec.ts |
Tests header and credential overrides. |
byok/vscode-node/openRouterProvider.ts |
Injects middleware support. |
byok/vscode-node/openAIProvider.ts |
Injects middleware support. |
byok/vscode-node/ollamaProvider.ts |
Injects middleware support. |
byok/vscode-node/customOAIProvider.ts |
Propagates middleware dependency. |
byok/vscode-node/customEndpointProvider.ts |
Merges headers and credentials. |
byok/vscode-node/azureProvider.ts |
Covers the Entra request path. |
byok/vscode-node/abstractLanguageModelChatProvider.ts |
Applies middleware per request. |
byok/node/test/openAIEndpoint.spec.ts |
Tests protected credentials. |
byok/node/openAIEndpoint.ts |
Sanitizes and applies middleware headers. |
byok/common/requestHeaders.ts |
Adds shared header utilities. |
byok/common/languageModelRequestMiddleware.ts |
Implements the middleware registry. |
api/vscode/extensionApi.ts |
Exposes API version 2. |
api/vscode/api.d.ts |
Defines the public middleware API. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
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.
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.
Niels Kootstra (nkootstra)
marked this pull request as ready for review
September 22, 2026 05:47
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.



Summary
registerLanguageModelRequestMiddlewareto the Copilot Chat extension API (getAPI(2)), so an extension can attach headers to each BYOK language model request: a short-lived credential, the signed-in user, the chat session, the work item.openai,azureincluding Entra auth,ollama,openrouter,xai,customoai,customendpoint); Anthropic and Gemini are out of scope.requestHeadersmay set for that provider, through the same sanitiser. Oncustomendpointthat includesAuthorizationandapi-key, which replace the configured credential; other providers keep their own.providerGroups. To make the group name available, the proposedchatProviderAPI now passes it toprovideLanguageModelChatInformationasPrepareLanguageModelChatModelOptions.group(one d.ts field, one extension host line). That part needs API owner sign-off and can be reshaped independently of the rest.Related: #316794, #329469
Why an API and not a config value
Organisations that route BYOK models through a gateway (LiteLLM, Portkey, APIM, an internal proxy) need two things per request that
chatLanguageModels.jsoncannot provide. The first is a credential that is not a static key: a bearer token from SSO orvscode.authenticationthat rotates and belongs to the user, or a per-provider secret an internal extension manages so nobody pastes keys into settings. The second is context for attribution and cost tagging: which user, which chat session, which ticket. Template variables (#329469) could cover a workspace name or a session id, but not a token from an auth provider or the ticket a developer selected a minute ago. With this API the organisation ships one small extension that knows those values; users only configure the model.Why scope to a provider group
One vendor such as
customendpointcan back several user-configured provider groups: different gateways, or the same gateway with different keys that unlock different model lists. Model ids are not unique across groups. A middleware registered for a vendor alone would send its credential to every group of that vendor, and without the group name in the context the author cannot tell them apart. WithproviderGroupsan extension registers once per group. The group name is chosen by the user and can be renamed or reused for a different service, so it is routing, not the security check: the docs require middleware that returns a credential to also verifycontext.url.Technical context for AI-assisted review
Intent and previous behavior
OpenAIEndpointreadrequestHeadersfrom the model configuration once at construction and sanitised them against a private reserved-header list. Nothing outside the configuration file could influence request headers, and header merging was case-sensitive, soX-Sharedandx-sharedcould both be sent.CustomEndpointOAIEndpointalready let configuration overrideAuthorizationandapi-keyand suppressed its default credential when it did.Core passed the provider group name to the main thread as
options.group, butextHostLanguageModels.tsdropped it before calling the provider, so an extension could not learn which group a model belongs to.Implementation
byok/common/requestHeaders.tsholds the reserved names, theproxy-*/sec-*prefix check and a case-insensitive merge, used by the endpoint.byok/common/languageModelRequestMiddleware.tsis a registry service.provideRequestHeaderssnapshots the matching registrations, invokes them concurrently, and merges results in registration order. Each invocation is bounded by a 10 s timeout and by the request's cancellation token. A registration disposed while in flight has its result discarded. The registry does not filter header names. The selector matches onvendors,modelIdsandproviderGroups.OpenAIEndpoint.applyRequestHeaderssanitises middleware headers with the same rules as configuration headers, under a separate 20-header budget and with warnings attributed to the middleware rather than the model configuration.cloneWithTokenOverridecarries the headers to the clone.CustomEndpointOAIEndpointtreats a credential header from middleware like one from configuration and suppresses its default credential.AbstractOpenAICompatibleLMProvider.applyRequestMiddlewareruns the registry for a request with the endpoint's resolved URL and the model's group name, and is also called from the Azure Entra path, which builds its own endpoint.AbstractLanguageModelChatProvider.provideLanguageModelChatInformationreadsgroupfrom the options and stores it asproviderGroupon every model it returns.src/vscode-dts/vscode.proposed.chatProvider.d.tsdeclaresPrepareLanguageModelChatModelOptions.group, andextHostLanguageModels.tsforwards it.CopilotExtensionApi.versionis now 2.Behavior and constraints
requestHeadersmay set for the provider. Transport-owned and forbidden headers (Content-Type,X-Request-Id,Host,Cookie,Proxy-*,Sec-*, ...) are dropped and logged at warn level for both sources.${apiKey}-interpolated, so the configured key is not exposed to other extensions. Middleware cannot change the request URL.url(the fully resolved request URL) andproviderGroup(the group name, orundefinedfor models requested without a group). A request without a group never matches a selector withproviderGroups.modelIdsalone cannot separate two groups on the same gateway.errorBehavior: 'continue'(default) drops a failing or timed-out middleware's headers and logs;'fail'fails the request. Cancellation errors always propagate.Validation
customendpointagainst a local request-capturing OpenAI-compatible endpoint, exercised both throughvscode.lmand from the chat view. The middlewareAuthorizationreplaced the configured key on both requests, the context headers arrived, a middleware header overrode the same-named configured header while an unrelated configured header was kept,Content-Type,X-Request-IdandHostfrom the middleware were dropped with a warning in the Copilot log, and a middleware with a non-matching selector was not invoked. A second manual run configured threecustomendpointgroups at the same URL with different keys, registered one middleware per group for the first two with its own bearer token, and sent one request per model: the endpoint received each group's own middleware token for the first two and the configured key for the third, and each middleware was invoked only for its own group with the resolved URL and group name in the context.vitestforsrc/extension/byokandsrc/extension/api,npm run typecheck-clientat the repo root,eslinton changed files, andnpm run hygienepass.vscode.authentication.getSessionand checks that middleware scoped to the group receives the resolved Azure URL and the group name, and that its headers reach the endpoint while the Entra token stays the credential.