Repository navigation
agentHost: serve BYOK provider groups to agent hosts as model sources - #349506
Logan Ramos (lramos15) wants to merge 14 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved direct-routing flaws can send credentials to unintended endpoints and leave live sessions using withdrawn or stale routes.
5 open issues
What changed in this PR
This PR adds opt-in direct Custom Endpoint BYOK calls from the local agent host’s Copilot runtime, reducing dependence on the window-side bridge while retaining fallback for unsupported configurations.
Changes:
- Shares endpoint URL and authentication rules between core and the Copilot extension.
- Adds credential delivery, runtime provider registration, and model-ID translation for direct routing.
- Adds unit and integration coverage for routing, credentials, history restoration, and key persistence.
| File | Description |
|---|---|
| src/vs/workbench/contrib/chat/test/common/languageModels.ts | Updates the null service for credential resolution. |
| src/vs/workbench/contrib/chat/test/browser/chatManagement/chatModelsViewModel.test.ts | Updates the language-model service mock. |
| src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostByokLmHandler.test.ts | Tests direct discovery and credential gating. |
| src/vs/workbench/contrib/chat/common/languageModels.ts | Adds internal provider-group key resolution. |
| src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.ts | Advertises direct endpoints and serves credentials. |
| src/vs/platform/agentHost/test/node/providerIntegration/README.md | Documents direct-endpoint integration coverage. |
| src/vs/platform/agentHost/test/node/providerIntegration/copilotByokDirect.integrationTest.ts | Exercises four wire formats and checks key persistence. |
| src/vs/platform/agentHost/test/node/mapSessionEvents.test.ts | Tests restored direct-model identities. |
| src/vs/platform/agentHost/test/node/copilotSessionLauncher.test.ts | Tests provider synthesis, ID translation, and key withdrawal. |
| src/vs/platform/agentHost/test/node/byokLmBridgeRegistry.test.ts | Tests publication after credential or capability changes. |
| src/vs/platform/agentHost/test/node/agentHostClientByokLmChannel.test.ts | Tests separate credential requests. |
| src/vs/platform/agentHost/test/common/byokCustomEndpoint.test.ts | Tests endpoint mapping and bridge fallbacks. |
| src/vs/platform/agentHost/node/copilot/mapSessionEvents.ts | Translates runtime model IDs during replay. |
| src/vs/platform/agentHost/node/copilot/copilotSessionLauncher.ts | Builds direct providers and translates launch selections. |
| src/vs/platform/agentHost/node/copilot/copilotByokModelIds.ts | Defines stable provider names and ID conversions. |
| src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts | Applies ID translation and tracks live routing configuration. |
| src/vs/platform/agentHost/node/copilot/copilotAgent.ts | Syncs live sessions when BYOK models are withdrawn. |
| src/vs/platform/agentHost/node/byokLmBridgeRegistry.ts | Detects direct-route and capability changes. |
| src/vs/platform/agentHost/common/customEndpointUrl.ts | Centralizes URL and authentication rules. |
| src/vs/platform/agentHost/common/byokCustomEndpoint.ts | Maps compatible settings to runtime endpoints. |
| src/vs/platform/agentHost/common/agentService.ts | Declares the direct-routing setting ID. |
| src/vs/platform/agentHost/common/agentHostStarter.config.contribution.ts | Registers the default-off experimental setting. |
| src/vs/platform/agentHost/common/agentHostClientByokLmChannel.ts | Adds credential delivery over local IPC. |
| src/vs/platform/agentHost/common/agentHostByokLm.ts | Defines direct-endpoint and credential contracts. |
| extensions/copilot/src/util/vs/platform/agentHost/common/customEndpointUrl.ts | Vendors the shared endpoint rules. |
| extensions/copilot/src/extension/byok/vscode-node/test/customEndpointProvider.spec.ts | Adapts tests to the shared URL helper. |
| extensions/copilot/src/extension/byok/vscode-node/customEndpointProvider.ts | Uses shared URL and authentication helpers. |
| extensions/copilot/script/setup/copySources.ts | Includes the shared helper in source copying. |
Review effort: Balanced
98df516 to
a584811
Compare
…untime Behind the experimental `chat.agentHost.byokModels.customEndpointDirect.enabled` setting, the local agent host registers Custom Endpoint BYOK models with the Copilot runtime as real providers (the model's endpoint and the provider group's API key) instead of routing every request back through the window's bridge. - Share the Custom Endpoint URL rules between core and the Copilot extension (`customEndpointUrl.ts`, vendored by `copySources.ts`) and map each model to an `openai` (Chat Completions or Responses), `azure` or `anthropic` runtime endpoint that sends the same request and auth header as the extension. Models the runtime cannot reach the same way keep using the bridge. - The window serves each group's key over a separate `credential` call on the existing BYOK channel, behind the BYOK policy and the setting; model lists never carry keys. The agent host sets it as the provider's static `apiKey`, re-syncs on key changes, and drops it from live sessions once the window stops reporting the model. - Each direct model has its own runtime provider; the agent host translates its runtime selection id to and from the picker's `vendor/[group/]id`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…irect routing Addresses review feedback on direct Custom Endpoint BYOK routing: - A direct provider the window no longer reports (BYOK disabled by policy, the group removed or changed, the setting turned off) is pointed at the BYOK bridge under the same provider name, with or without a key. The session keeps its selection, and each request gets the bridge's per-request checks. If the proxy cannot start, the provider and its models are withdrawn. - Credential requests carry the snapshot's `credentialVersion`; the window refuses a version whose key has since been replaced, so a new key never reaches the endpoint of an older snapshot. - Groups with a discovery `url`, and models with `modelOptions`, stay on the bridge, since the extension's requests for them differ from the runtime's. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Replace the private direct-routing path (a credential call on the local BYOK channel plus agent/runtime model id translation) with the Agent Host Protocol model source registry, so local and remote agent hosts share one path. - Sync the protocol types to the pre-release microsoft/agent-host-protocol#627 (on #543), and narrow `authenticate` targets that are not MCP servers. - Host: a model source registry validates `root/modelSourceRegistrationSet` and `Removed`, reports status with `root/modelSourceStateChanged`, holds credentials delivered with a `modelSource` target in memory, fences them with a nonce, and removes a departed client's `contributingClient` sources. - Copilot agent: reads the `code.visualstudio.com/custom-endpoint@1` format, publishes each source's models with `modelSourceId`, and registers them on live sessions as host-owned providers that replace earlier ones on sync. Model ids are the runtime selection ids, bound to the registration, endpoint, and upstream model. - Window: registers eligible Custom Endpoint groups with every connected host that reads the format, and answers key requests; the bridge stops listing those models. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…g back Moves BYOK model sources to a VS Code-owned `byok-endpoints@1` definition format that carries each model's resolved endpoint, with strict host-side validation, and maps Custom Endpoint, Custom OpenAI Compatible, Azure (with a key), xAI, OpenRouter and Ollama groups through a core vendor table. Models whose requests the runtime would send differently stay on the bridge. Adopts the registry from agent-host-protocol#627 at e06ed620: contributor sets, model-source auth reasons, credential IDs and origins, leases, the grace period, and resumable `modelSourceUnavailable` errors. - Registers only the selected model's provider on a session, and never runs a turn on another model after its source is withdrawn or its key revoked. - Marks a key rejected on the endpoint's 401 instead of asking for GitHub sign-in. - Asks before using a remote agent host, sends it only public https endpoints, and never registers over relays. - Namespaces registration IDs per installation and profile, and lets a window withdraw only its own contribution unless every window agrees. - Honors `chat.byokUtilityModelDefault` for these models, and hides bridged copies only while the local host serves them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
9f9842f to
665267c
Compare
| if (url.endsWith('/v1')) { | ||
| url = url.slice(0, -3); | ||
| } | ||
| if (url.includes('models.ai.azure.com') || url.includes('inference.ml.azure.com')) { |
| if (url.endsWith('/v1')) { | ||
| url = url.slice(0, -3); | ||
| } | ||
| if (url.includes('models.ai.azure.com') || url.includes('inference.ml.azure.com')) { |
| if (url.includes('models.ai.azure.com') || url.includes('inference.ml.azure.com')) { | ||
| return `${url}/v1/chat/completions`; | ||
| } | ||
| if (url.includes('openai.azure.com')) { |
…27 at a03a5a1b Syncs the protocol to the registry as revised in review: model sources are `RootState.modelSources`, their definitions travel only on `root/modelSourceSet` with a client-chosen `nonce`, the host tracks contributing clients privately from each action's origin, and a key's ID is `authenticate`'s `accountId`. - Host: keeps definitions and contributors privately, treats a `Set` with the same provider, format and nonce as a re-registration that keeps the key, rejects one that repeats the nonce with a different definition, and publishes `accountId`. - Window: derives source IDs from the provider group and the nonce from a hash of the definition, so windows and devices share one source; registers it again on connect and reconnect; leaves another client's definition and key alone unless the user changed the group here; adds back a source another client removed only after reconnecting; and removes a source only when the user removes the group, or when policy turns the feature off on the local host. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…nt left When the last contributing client of a contributingClient-retained model source disconnects, the host now drains the source instead of removing it immediately: its models leave the catalog and new work fails as modelSourceUnavailable, but sessions with a running turn on it keep the provider until the turn ends. The source is removed once idle, and a re-registration cancels the drain. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…urces Register the OpenAI, Anthropic and Gemini vendors' provider groups as model sources, so the runtime calls their APIs directly with its own request settings instead of matching the extension's per-vendor behavior: - OpenAI models with a reasoning effort use Responses, the others Chat Completions, since the runtime always asks Responses for encrypted reasoning. - Anthropic models use Messages at the Anthropic API. - Gemini models use the runtime's experimental Google provider, the Interactions API with x-goog-api-key. Sessions on a model source's Responses model ask for no reasoning summary, as VS Code's BYOK providers never do, and restore the default when they leave it. A session launched on a model source's model gets tool search that defers tools past the 128 an OpenAI-compatible API accepts. The integration test adds a Gemini turn, checks Responses requests carry no reasoning summary, and checks the tool limit. A skipped test documents that the bundled runtime doesn't redact provider keys from tool results. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…27 at a4a01c06 Sync the protocol from microsoft/agent-host-protocol#627 at a4a01c06, which implements #622 after its second review round: - The definition is part of the model source: root/modelSourceSet carries only the source, and the reducer keeps the definition in root state. - Credential nonces, credentialOrigins, the capability's gracePeriod and principalPolicy are gone, and formats are { format } objects. The host no longer issues nonces: a later delivery replaces the key it holds, and a lease only lapses for the key it was delivered with. The window checks the host's copy of the definition before sending a key: every endpoint the key reaches must be one its own copy sends it to, whatever the nonce. It checks again after reading the key, since the source may have changed meanwhile. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A 401 on a model source's endpoint now carries the start time of the turn that got it, and the host drops the credential only if it accepted that credential before the turn started. A key delivered meanwhile is kept instead of being reported as rejected. The window no longer backs off and retries a failed key delivery on a timer. It delivers again on the next state change, such as a reconnect, a host report, or a replaced key. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Drop the skipped tool-output redaction test, which can't pass until the runtime redacts provider keys from tool results and is tracked as a runtime ask, and the mapping assertions the real-runtime integration test already checks on the wire. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Vritant Bhardwaj (vritant24)
left a comment
There was a problem hiding this comment.
Read at 6f67c7f. I traced these by reading; I did not run the code or read the tests in full, so a test may already cover some of them.
P1 is behavior a user can hit, worth settling before this leaves draft. P2 is a simplification or a maintainability point, and is your call.
P1
- A second window on a remote host can stop counting as a contributor after a group changes.
- A group with more than 256 direct-callable models is declined whole.
- Updating a group clears the key and can end turns running on its other models. Is that intended?
P2
4. The remote BYOK warning is hidden from the setting alone.
5. The Azure URL rule is a second copy of the extension's.
6. ConnectionModelSourceRegistrar could sync as one queued pass.
7. canSendKey could compare a recomputed nonce.
8. _reasoningSummaryOmitted may not need three states.
9. IModelSourceEntry repeats what is in root state.
10. Two 30-second disconnect timers.
Minor, no inline comment: the client-dispatchable action union is edited in 12 signatures across 6 files. A named type would make the next addition a one-line change.
| return resolveCustomEndpointRuntimeEndpoint({ ...settings, url, apiType: undefined, requestHeaders: undefined }); | ||
| } | ||
|
|
||
| function resolveAzureUrl(modelId: string, url: string): string | undefined { |
There was a problem hiding this comment.
[P2] Second copy of the extension's resolveAzureUrl
This restates resolveAzureUrl in extensions/copilot/src/extension/byok/vscode-node/azureProvider.ts, including the host matching and the pinned api-version. Direct calls match the extension's only while the two agree, and nothing ties them together.
customEndpointUrl.ts already solves this for Custom Endpoint with one import-free module that copySources.ts copies. The Azure resolver could move there and be called from both sides.
There was a problem hiding this comment.
Agent-assisted reply.
Agreed that it's a second copy. The two already differ: the direct path leaves /messages URLs on the bridge, and the extension throws on hosts this returns undefined for. I didn't share it in this PR because the plan is to move the built-in BYOK providers' URL rules into core. At that point this copy becomes the only one. Code scanning's substring alerts here are about classifying the URL; the key goes to the URL the user configured either way.
| private readonly _known = new Map<string, IDesiredModelSource>(); | ||
| /** Sources this window registered, or registered again, since it connected or last reconnected. */ | ||
| private readonly _contributed = new Set<string>(); | ||
| /** Sources another client removed after this window registered them. Not added back until a reconnect or a local change. */ | ||
| private readonly _removedElsewhere = new Set<string>(); | ||
| /** The nonce of each source the host declined; not registered again until it changes. */ | ||
| private readonly _rejected = new Map<string, string>(); | ||
| /** Sources this window dispatched whose echo hasn't arrived. */ | ||
| private readonly _inFlight = new Set<string>(); | ||
| /** Removals this window dispatched whose echo hasn't arrived. */ | ||
| private readonly _removing = new Set<string>(); | ||
| /** The delivery of each source's key in progress, until it is sent or given up. */ | ||
| private readonly _delivering = new Map<string, object>(); |
There was a problem hiding this comment.
[P2] Simplification: one queued async sync pass per connection
Of these seven collections, _inFlight, _removing and _delivering exist because _sync is re-entered while dispatches and key reads are pending. If each connection ran its sync through a Sequencer or Throttler and awaited dispatchConfirmed and authenticate inside the pass, those three and the isCurrent() guards could go. That leaves the ones the protocol requires: _known, _contributed, _removedElsewhere and _rejected.
Removal would need to become a confirmed dispatch too. I haven't tried this.
There was a problem hiding this comment.
Agent-assisted reply.
I'd rather not do this here. A serial pass would make one host's slow authenticate delay every other source's registration on that connection. It would still need the post-await checks for peer updates and disposal. I removed the delivery backoff earlier, which dropped _deliveryFailures and the pending timers, so _inFlight, _removing and _delivering are what's left.
| const HOST_REPORTED_FIELDS = ['state', 'credentialResource', 'accountId'] as const; | ||
|
|
||
| /** What the host knows about a model source beyond root state. Never published: it holds the credential. */ | ||
| interface IModelSourceEntry { |
There was a problem hiding this comment.
[P2] Simplification: keep only the private parts here
provider, format, nonce, definition, state, credentialResource and accountId are also in root state, which the registry already reads through _findModelSource. Keeping only what must stay private (contributors, credential, credentialSince, listed, lease, drain) would remove the second copy and the chance of the two disagreeing.
There was a problem hiding this comment.
Agent-assisted reply.
Most of these have to stay. _apply runs after the reducer has already applied the action, so root state no longer has the previous provider, format, nonce and definition. The entry keeps them to tell a re-registration from an update, and to reject a repeated nonce with a different definition. state, credentialResource and accountId are what the registry reports, not values it reads back. definition is a shared reference, not a copy.
- A window that contributed a source registers it again after another client updates it, so it keeps counting as a contributor. - A definition holds up to 512 models, and the window leaves any more on the bridge instead of the host declining the whole group. OpenRouter lists more than 256 tool-capable models. - The host declines a definition its agent can't read rather than storing it in root state for every client. - Before sending a key, the window compares the host's definition with its own through its nonce, and checks again after reading the key that the host still needs it. - Resuming a turn selects its model source's model again first, as sending does, and fails as unavailable while it can't. - The session's reasoning summary state is a boolean, and one timer drops a disconnected client's managed settings and model sources. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…27 at 6a80f578 Sync the protocol from microsoft/agent-host-protocol#627 at 6a80f578, which targets main now that #543 and #622 are merged: - ModelSourceInfo and AgentInfo.modelSources are gone: root state lists every model source, so the host stops publishing a catalog per agent. - format, definition and nonce are optional on ModelSource. The host rejects a client registration without any of them, and a model counts as the user's own when its root source has a definition. - A request that selects a model whose registered source can't serve it fails with AhpErrorCodes.ModelSourceUnavailable (-32013). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The remote BYOK warning was hidden whenever the direct endpoints setting was on, even when the session's host serves none of the window's models: a relayed connection, a host the user didn't allow, one whose agent lacks the format, or endpoints it can't reach. The registrar now publishes, per connection authority, whether the host serves the window's sources or is still setting them up, and the warning hides only for the session's own host. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Resolve conflicts in copilotAgent.ts and its tests: keep both sides' imports, and in handleAuthenticationToken keep this branch's early return for non-MCP authenticate targets ahead of main's hasGitHubToReturnTo Entra change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>


Registers BYOK provider groups with local and remote agent hosts as Agent Host Protocol model sources. The Copilot runtime then calls each provider's endpoint directly with the group's API key, instead of sending every request back to the window through the BYOK bridge. It's off by default, behind the experimental setting
chat.agentHost.byokModels.directEndpoints.enabled.Important
Builds on the AHP model source registry in microsoft/agent-host-protocol#627, which implements microsoft/agent-host-protocol#622 on top of microsoft/agent-host-protocol#543 (both merged). The protocol files are synced from the registry PR's head
6a80f578withAHP_PROTOCOL_REF=6a80f578 scripts/sync-agent-host-protocol.ts. Re-sync from the AHP release before merging.How it works
Window (
AgentHostModelSourceRegistrar)chatLanguageModels.jsonas a model source, with every connected host whose agent reads the format. The source ID comes from the group's configuration key, so every window and device with the group registers the same source.code.visualstudio.com/byok-endpoints@1, which lists each model's resolved endpoint, API, and limits. Itsnonceis a hash of the definition.authenticateonly when the host asks for one, and only if every endpoint the key reaches in the host's copy of the definition is one the window's own copy sends it to, whatever thenonce. It never caches or replays keys, and doesn't resend a key the host rejected or a client revoked until the user replaces it.Host (
AgentHostModelSourceRegistry)Setwith the same provider, format, andnoncere-registers the source and keeps its key, and one that repeats thenoncewith a different definition is rejected.credentialResource, andaccountId, and therequired,expired,rejected, andrevokedreasons. A later delivery replaces the key the host holds.expiresInlease lapses. Relay and scoped clients can't register sources or deliver keys.contributingClientsource's last window leaves, the host waits out its 30-second grace period. Then new turns on it fail, and running turns finish before the source is removed.Copilot agent
apiKey. A session registers only its selected model's provider, so it never holds another source's key.modelSourceUnavailableerror, and a request that selects the model fails withModelSourceUnavailable(-32013). It never falls back to another model, and resuming selects the model again first.chat.byokUtilityModelDefault. Automations are ready only while the model's key is present.Vendors
anthropic/models, because the runtime sendsx-api-keywhere the extension sends a bearer tokenthinkingthinking, and settings the runtime can't apply, such as custom headers,modelOptions, andstreaming: false/messagesURLsStill on the bridge
thinking, because ofinclude.anthropic/models: the extension sends their key as a bearer token, and the runtime's Anthropic provider usesx-api-key. A bearer option in our definition format would fix this without runtime changes.modelOptions,streaming: false, keyless Azure, and third-partyvscode.lmproviders.Keyless Azure and non-secret headers could also move later without runtime changes.
Accepted differences
generateContent.Runtime asks
include: ["reasoning.encrypted_content"]out of Responses requests for models without reasoningtool.execution_complete, and inevents.jsonl. The bridge leaks it the same way.Moving the built-in BYOK providers' discovery and configuration from the Copilot extension into core is left for a separate PR.
Validation
Run locally against Copilot SDK 2.0.1 (runtime 1.0.114), because the package feed doesn't serve the SDK build
mainpins yet. CI covers the pinned runtime.pnpm run typecheck-client,pnpm run oxlinton the changed files, andpnpm run valid-layers-check: passed../scripts/test.shoversrc/vs/platform/agentHost/testandsrc/vs/workbench/contrib/chat/test/browser/agentSessions: 22,816 passing, 0 failing../scripts/test-integration.sh --run src/vs/platform/agentHost/test/node/providerIntegration/copilotByokDirect.integrationTest.ts: 2 passing.Not run: an end-to-end turn against a real provider in a running window, or the Azure cross-platform pipeline.