Skip to content

Copilot Chat: let extensions contribute request headers to BYOK language model requests - #337130

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

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

Conversation

@nkootstra

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

Copy link
Copy Markdown

Summary

  • Adds 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, the signed-in user, the chat session, the work item.
  • Applies to every OpenAI-compatible BYOK provider (openai, azure including Entra auth, ollama, openrouter, xai, customoai, customendpoint); Anthropic and Gemini are out of scope.
  • Middleware may set what requestHeaders may set for that provider, through the same sanitiser. On customendpoint that includes Authorization and api-key, which replace the configured credential; other providers keep their own.
  • Middleware can be scoped to a provider group. The request context carries the resolved request URL and the name of the provider group the model was configured in, and the selector accepts providerGroups. To make the group name available, the proposed chatProvider API now passes it to provideLanguageModelChatInformation as PrepareLanguageModelChatModelOptions.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.json cannot provide. The first is a credential that is not a static key: a bearer token from SSO or vscode.authentication that 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.

const copilot = vscode.extensions.getExtension('github.copilot-chat')!.exports.getAPI(2);
copilot.registerLanguageModelRequestMiddleware({
	selector: { vendors: ['customendpoint'] },
	provideRequestHeaders: async ({ modelId }) => {
		const session = await vscode.authentication.getSession('my-sso', ['llm-gateway'], { silent: true });
		return {
			Authorization: `Bearer ${session?.accessToken}`,
			'x-litellm-end-user': session?.account.id ?? 'anonymous',
			'x-litellm-tags': `model:${modelId},ticket:${tracker.activeTicket()}`,
		};
	},
});

Why scope to a provider group

One vendor such as customendpoint can 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. With providerGroups an 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 verify context.url.

for (const group of ['Acme Premium', 'Acme Budget']) {
	copilot.registerLanguageModelRequestMiddleware({
		selector: { vendors: ['customendpoint'], providerGroups: [group] },
		provideRequestHeaders: async ({ url }) => {
			if (new URL(url).origin !== 'https://gateway.example.com') {
				return {};
			}
			return { Authorization: `Bearer ${await getToken(group)}` };
		},
	});
}
Technical context for AI-assisted review

Intent and previous behavior

OpenAIEndpoint read requestHeaders from 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, so X-Shared and x-shared could both be sent. CustomEndpointOAIEndpoint already let configuration override Authorization and api-key and suppressed its default credential when it did.

Core passed the provider group name to the main thread as options.group, but extHostLanguageModels.ts dropped it before calling the provider, so an extension could not learn which group a model belongs to.

Implementation

byok/common/requestHeaders.ts holds the reserved names, the proxy-*/sec-* prefix check and a case-insensitive merge, used by the endpoint.

byok/common/languageModelRequestMiddleware.ts is a registry service. provideRequestHeaders snapshots 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 on vendors, modelIds and providerGroups.

OpenAIEndpoint.applyRequestHeaders sanitises 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. cloneWithTokenOverride carries the headers to the clone. CustomEndpointOAIEndpoint treats a credential header from middleware like one from configuration and suppresses its default credential. AbstractOpenAICompatibleLMProvider.applyRequestMiddleware runs 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.provideLanguageModelChatInformation reads group from the options and stores it as providerGroup on every model it returns. src/vscode-dts/vscode.proposed.chatProvider.d.ts declares PrepareLanguageModelChatModelOptions.group, and extHostLanguageModels.ts forwards it.

CopilotExtensionApi.version is now 2.

Behavior and constraints

  • Header names middleware may set are the ones requestHeaders may 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.
  • Middleware headers override same-named configuration headers, compared case-insensitively.
  • Middleware values are never ${apiKey}-interpolated, so the configured key is not exposed to other extensions. Middleware cannot change the request URL.
  • The context carries url (the fully resolved request URL) and providerGroup (the group name, or undefined for models requested without a group). A request without a group never matches a selector with providerGroups.
  • Model ids are not unique across groups; modelIds alone 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.
  • Registrations are logged at info level with their selector; contributed header names at debug level.
  • Open question: should registration be restricted to an allow-list of extension ids, or is installed-and-trusted plus logging sufficient?
  • Follow-up: Copilot Chat: expose the chat session id to language model request middleware #337203 (stacked on this PR) adds the chat session id to the middleware context, so a gateway can group requests per chat.

Validation

  • Unit tests for the registry (selector matching including provider groups and the no-group case, ordered case-insensitive merge, concurrency, dispose in flight for both headers and errors, continue and fail, timeout, cancellation), for the custom endpoint (middleware overrides configured headers, replaces the credential and suppresses the default one, survives the token-override clone, receives the resolved URL and group name, and keeps a credential scoped to its group when two groups share a URL with different keys) and for the base endpoint (middleware credential dropped).
  • Manual: dev build with a throwaway extension registering middleware for customendpoint against a local request-capturing OpenAI-compatible endpoint, exercised both through vscode.lm and from the chat view. The middleware Authorization replaced 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-Id and Host from 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 three customendpoint groups 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.
  • vitest for src/extension/byok and src/extension/api, npm run typecheck-client at the repo root, eslint on changed files, and npm run hygiene pass.
  • The Azure Entra path is covered by a provider-level test that stubs vscode.authentication.getSession and 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.

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
Copilot AI balanced review requested due to automatic review settings September 21, 2026 19:45
@nkootstra

Copy link
Copy Markdown
Author

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

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

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.
@nkootstra
Niels Kootstra (nkootstra) marked this pull request as ready for review September 22, 2026 05:47
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