Skip to content

chat: custom trajectory compaction model - #316114

Merged
Bhavya U (bhavyaus) merged 2 commits into
microsoft:mainfrom
gryan11:ryangabriel/custom_trajectory_compaction_model
Jun 9, 2026
Merged

Bhavya U (bhavyaus) merged 2 commits into
microsoft:mainfrom
gryan11:ryangabriel/custom_trajectory_compaction_model

Conversation

@gryan11

@gryan11 Gabriel Ryan (gryan11) commented May 12, 2026 •

Copy link
Copy Markdown
Member

chat: route conversation-history compaction to the trajectory-compaction CAPI model (usePrismCompaction)

Adds a flag-gated route for conversation-history compaction so we can run summarisation against a dedicated, lighter model instead of the main agent endpoint.

What changes

When chat.conversationCompaction.usePrismCompaction is enabled and the active agent model matches chat.conversationCompaction.prismModelFilter, both the foreground (/compact) and background auto-compaction paths resolve their endpoint to the trajectory-compaction model via the standard CAPI endpoint provider (regular chat completions ΓÇö not a separate proxy). When the flag is off, behavior is byte-identical to upstream (the off-flag execution path is physically the original code).

Settings

  • chat.conversationCompaction.usePrismCompaction (ExperimentBased boolean, default false) ΓÇö master enable flag
  • chat.conversationCompaction.model (ExperimentBased string, default '') ΓÇö when set, overrides the default trajectory-compaction family
  • chat.conversationCompaction.prismModelFilter (ExperimentBased string, default 'claude-haiku-4.5,claude-sonnet-4.5,claude-sonnet-4.6,gemini-2.5-pro,gemini-3-flash,gemini-3.5-flash') ΓÇö comma-separated, case-insensitive substring filter against the agent model id and family; empty string = no filter

All three settings are registered in package.json (tagged experimental + onExp) and have localized descriptions in package.nls.json.

Routing (decidePrismRouting)

Single source of truth shared by the foreground entry point (ConversationHistorySummarizer.getSummary) and the background dispatcher in AgentIntentInvocation. Decision order:

  1. usePrismCompaction flag off → main agent
  2. Agent model not in prismModelFilter → main agent
  3. Otherwise → prism

The dispatchers then physically branch on the decision: prism requests go through _getSummaryPrism / _startPrismBackgroundSummarization, and off-flag requests go through the unmodified _getSummary / _startBackgroundSummarization paths.

Safety nets on the prism path

  • Post-render pruning detection ΓÇö a prompt-tsx tracer counts removedCount during render; if any node was pruned to fit the compaction endpoint, throw PruningOccurredError and fall back to the agent endpoint so the summary sees the full conversation.
  • Prompt-too-long fallback ΓÇö BudgetExceededError and server-side context_length_exceeded thrown from _getSummaryPrism also fall back to the agent endpoint.
  • Length truncation handled inline ΓÇö ChatFetchResponseType.Length on the prism path uses response.truncatedValue as a partial summary (warn-logged) instead of throwing; only the prism path tolerates this, so off-flag callers continue to fail closed.
  • Cancellation skipped in telemetry ΓÇö token-driven cancellation in the prism background path (/compact, session dispose, endpoint switch) re-throws without error log or failure telemetry.
  • Cache-parity gates skipped ΓÇö the prism background branch hardcodes cacheWarm=true and skips _lastModelCapabilities since the prism endpoint shares no prompt-cache prefix with the main agent loop.

Endpoint provider

endpointProvider.getChatEndpoint(family) used to only recognize the utility aliases (copilot-utility, copilot-utility-small); it now falls through to getChatModelFromCapiFamily for arbitrary CAPI families so trajectory-compaction (or any other CAPI-registered family) resolves by name.

Diff scope

File Notes
extension/prompts/node/agent/compactionEndpoint.ts (new) resolveCompactionEndpoint, buildCompactionToolOpts, formatCompactionFailureError, renderCompactionMessages, DEFAULT_COMPACTION_MODEL = 'trajectory-compaction'
extension/prompts/node/agent/summarizedConversationHistory.tsx Adds decidePrismRouting, matchesPrismFilter, PruningOccurredError, _getSummaryPrism, _renderSummarizationPromptWithTracer, _isPromptTooLongError. Off-flag path (_getSummary, _renderSummarizationPrompt, handleSummarizationResponse) is unchanged from pre-PR.
extension/intents/node/agentIntent.ts Background dispatcher branches on decidePrismRouting: routes to new _startPrismBackgroundSummarization (re-renders against compaction endpoint, handles Length + cancellation, telemetry uses compactionEndpoint.model on both success and failure) when prism is on; original _startBackgroundSummarization is restored byte-for-byte to its pre-PR form.
extension/prompt/vscode-node/endpointProviderImpl.ts getChatEndpoint resolves arbitrary CAPI families, not just utility aliases
extension/prompts/node/agent/backgroundSummarizer.ts Extracts shouldKickOffBackgroundSummarization + BackgroundSummarizationThresholds, adds endpointId to the constructor, widens the work-callback return type to … | undefined
platform/configuration/common/configurationService.ts 3 new ConfigKey entries
package.json + package.nls.json Schema + localized descriptions for the 3 settings
extension/prompts/node/agent/test/compactionEndpoint.spec.ts (new) Unit tests for resolveCompactionEndpoint (default, prism-flag-on routing, fallback on resolve failure)

Evaluations

Evaluations on MS-Bench summarization bench show using the trajectory compaction model is equivalent or slightly beneficial compared to main agent model trajectory compaction with lower cost. See detailed results and analysis here: Trajectory Compaction Model Proposal

Tests

  • All unit tests in compactionEndpoint.spec.ts (3), summarization.spec.tsx (34), agentPrompt.spec.tsx (11), and backgroundSummarizer.spec.ts (23) pass. Net additions from this PR: 3 cases — the new compactionEndpoint.spec.ts (resolveCompactionEndpoint: default / on-flag / fallback). Other spec files are unchanged from upstream main.
  • Off-flag execution path is the physically-original code, so existing summarisation behavior is preserved

Extended dev unit tests for the internal helpers, smoke scripts, and a local-testing doc live on the companion ryangabriel/custom_trajectory_compaction_model-dev branch for manual end-to-end verification.

Manual verification

Set in user settings:

{
  "github.copilot.chat.conversationCompaction.usePrismCompaction": true
}

Reload window, trigger /compact or let auto-compaction run on a long session. The chat debug log entry's model field should read trajectory-compaction for sessions where the agent model matches prismModelFilter.

To narrow which agent models route through prism, override the filter:

{
  "github.copilot.chat.conversationCompaction.prismModelFilter": "claude-sonnet-4.6"
}

Commits (squash-merge recommended)

Initial:

  • 1324b357667 route trajectory compaction through CAPI (model: trajectory-compaction)
  • 8a32669d44f allow BackgroundSummarizer work callback to resolve undefined
  • 86970cfdbb5 replace images with text placeholders only when crossing to compaction endpoint
  • c2c56e9c0ec trim PR diff per senior-engineer review (rename useAgenticProxy ΓåÆ usePrismCompaction; move renderCompactionMessages into compactionEndpoint.ts; extract background cross-endpoint branch into a helper)
  • 02c4e792ebd trim non-essential tests, smoke scripts, and docs (dev-only)
  • dfb91afab6a address PR review (branch prism path, register settings)

Routing, gating, and safety nets:

  • 7c428495db4 resolve arbitrary CAPI family in endpointProvider
  • 82b7859e93a capacity-gated prism fallback + length/cancellation handling
  • dd4c4397d2c opt prism in per agent model via configurable filter
  • f7e3e032209 default prism filter to specific CAPI model IDs
  • 32b9385b7e8 add gemini-3-flash and gemini-3.5-flash to default prism filter
  • 2a2d4f758ba apply prism model filter to background path too
  • 1dc332e83c9 unify prism routing across foreground/background and add debug logs
  • 073c7593f95 simplify capacity rule in decidePrismRouting
  • 922542445fc keep off-flag execution path byte-identical to pre-prism
  • 2bc83bae9de handle Length response on prism foreground path

Follow-up review feedback:

  • 3c403138122 address Bhavya review (restore stream: false on off-flag foreground; attribute prism failure telemetry to compactionEndpoint.model)
  • 008f730b6e4 drop currentContextTokens prop, rely on post-render pruning check
  • ce0c803abae clean if/else split between prism and production paths in agentIntent.ts dispatcher
  • 66a3cf98f63 minimize PR diff + clean prism/production split in summarizedConversationHistory.tsx
  • b0c472e937d trim verbose comments to minimize PR diff
  • 11c9811784e label prism vs production branches in dispatchers
  • ab2a4872467 drop stream:false from prism foreground request
  • c16cf33e63b trim added test cases to minimum needed coverage
  • 0a9e6f8751a restore appendTranscriptHintToSummary suite (was preexisting on main)
  • 8f39af6fb34 revert BackgroundSummarizer.start callback signature widening (use CancellationError on empty render)
  • c31b1997c76 restore shouldKickOffBackgroundSummarization test suite (was preexisting on main)

Copilot AI review requested due to automatic review settings May 12, 2026 20:50

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.

Pull request overview

This PR adds experiment-gated support for routing conversation-history (trajectory) compaction to a dedicated model/endpoint (optionally via the Copilot agentic proxy), shared across both foreground and background compaction paths, and fixes proxy endpoint cloning to preserve proxy routing.

Changes:

  • Introduces ExP settings to choose whether compaction uses the agentic proxy and (optionally) a dedicated compaction model.
  • Adds a shared resolveCompactionEndpoint() helper and updates both foreground (summarizedConversationHistory.tsx) and background (agentIntent.ts) compaction call sites to use it and report the effective model in telemetry.
  • Fixes ProxyAgenticEndpoint.cloneWithTokenOverride() to return a ProxyAgenticEndpoint (preserving proxy routing) and supports a max-prompt-token override.
Show a summary per file
File Description
extensions/copilot/src/platform/endpoint/node/proxyAgenticEndpoint.ts Preserve agentic-proxy routing when cloning endpoints with a prompt-token override.
extensions/copilot/src/platform/configuration/common/configurationService.ts Adds ExP config keys for compaction endpoint/model selection.
extensions/copilot/src/extension/prompts/node/agent/summarizedConversationHistory.tsx Foreground compaction resolves and uses the dedicated compaction endpoint; telemetry records actual model used.
extensions/copilot/src/extension/prompts/node/agent/compactionEndpoint.ts New helper to resolve the compaction endpoint (proxy vs provider vs fallback).
extensions/copilot/src/extension/prompt/node/searchSubagentToolCallingLoop.ts Updates ProxyAgenticEndpoint instantiation for the new constructor signature.
extensions/copilot/src/extension/prompt/node/executionSubagentToolCallingLoop.ts Updates ProxyAgenticEndpoint instantiation for the new constructor signature.
extensions/copilot/src/extension/intents/node/editCodeIntent.ts Makes endpointProvider protected for use by subclasses.
extensions/copilot/src/extension/intents/node/agentIntent.ts Background compaction resolves and uses the compaction endpoint; tool schemas/capabilities are adjusted based on endpoint choice.

Copilot's findings

  • Files reviewed: 8/8 changed files
  • Comments generated: 2

@bhavyaus

Copy link
Copy Markdown
Collaborator

A couple of design suggestions to shrink the blast radius of this change. The core concern: the off-flag path now runs through the same modified shared helpers, so it's no longer guaranteed to be byte-identical to today. I'd suggest inverting the structure so the flag-off path is physically the original code.

1. Branch instead of intertwine. These are two different algorithms — fork-and-append for cache parity vs. re-render-self-contained — so splitting them keeps the existing path untouched and avoids any unintended changes to it:

if (prismEnabled) {
    this._startPrismBackgroundSummarization(...);  // re-render against compaction endpoint
} else {
    this._startBackgroundSummarization(...);       // unchanged — exactly today's code
}

2. Skip the warm-cache wait on the prism path. The cacheWarm gate (shouldKickOffBackgroundSummarization) exists only to preserve prompt-cache prefix parity with the main agent endpoint — hence it waits for a completed tool-call round to fire at ~0.80, otherwise holding out for the 0.90 cold-cache emergency. Routing to a different compaction endpoint shares no prefix, so that rationale evaporates: we should kick off as soon as the budget threshold is crossed (cacheWarm: prismEnabled ? true : cacheWarm). Waiting for a tool round here only delays compaction with zero cache benefit. The _lastModelCapabilities block can be skipped too — it's also cache-parity machinery.

3. Add a user-visible opt-out. usePrismCompaction is a TeamInternal experiment flag today. Since it changes which model summarizes the conversation, users who manage summarization closely (custom thresholds, /compact discipline) will be surprised by it. I'd promote it to a documented, user-settable config — at minimum respecting an explicit false so the experiment can't override an opted-out user.

@gryan11
Gabriel Ryan (gryan11) force-pushed the ryangabriel/custom_trajectory_compaction_model branch 2 times, most recently from eac2d9d to dfb91af Compare May 28, 2026 17:02
@bhavyaus

Copy link
Copy Markdown
Collaborator

Flag-off regression: foreground /compact now streams where it didn't before.

On main, the foreground summarization request explicitly sets stream: false (summarizedConversationHistory.tsx:757). After the refactor into the shared _executeSummarizationRequest, requestOptions only carries { temperature: 0, ...toolOpts } and stream is gone.

That matters because messagesApi.ts:232 defaults a missing stream to true:

stream: options.requestOptions?.stream ?? true,

So with the flag off, Anthropic / Messages-API compaction requests now stream where they previously didn't. This breaks the "flag-off is byte-identical to upstream" guarantee we agreed on for the non-forked foreground path.

Can we restore stream: false in _executeSummarizationRequest (or pass it through per-path) so the disabled path stays identical to upstream?

@bhavyaus

Copy link
Copy Markdown
Collaborator

Prism background failure telemetry attributes the wrong model.

In _startPrismBackgroundSummarization, the success path logs model: compactionEndpoint.model (~line 1254), but the catch / failure path logs model: this.endpoint.model, which is the main agent model (~line 1290). That means trajectory-compaction failures get charged to the main model, so success vs. failure telemetry for the new route isn't comparable.

Should be compactionEndpoint.model in the failure path too.

@gryan11

Copy link
Copy Markdown
Member Author

All three addressed:

  1. Branch instead of intertwine (dfb91afab6a, ce0c803abae, 66a3cf98f63) — dispatcher now does if (routingDecision.usePrism) { this._startPrismBackgroundSummarization(...) } else { this._startBackgroundSummarization(...) }. _startBackgroundSummarization is restored byte-for-byte to its pre-PR form; the prism path is a separate method that re-renders against the compaction endpoint.

  2. Skip the warm-cache wait on the prism path — the prism branch hardcodes const cacheWarm = true with a comment explaining the cache-prefix rationale doesn't apply, and the _lastModelCapabilities cache-parity block runs only on the production branch.

  3. User-visible opt-out — all three settings are registered in package.json (chat.conversationCompaction.{usePrismCompaction, model, prismModelFilter}) with experimental + onExp tags, so an explicit user value wins over the experiment.

@gryan11

Copy link
Copy Markdown
Member Author

Fixed in 3c403138122. _getSummary (off-flag / production path) sets stream: false again, restoring byte-identical behavior to upstream. The prism path in _getSummaryPrism intentionally omits it (commented inline). Verified by 922542445fc, which keeps the off-flag execution path identical to pre-prism.

@gryan11

Copy link
Copy Markdown
Member Author

Fixed in 3c403138122. compactionEndpoint is hoisted above the try so the catch block in _startPrismBackgroundSummarization logs model: compactionEndpoint?.model ?? this.endpoint.model. The fallback to this.endpoint.model only triggers if resolveCompactionEndpoint itself threw (i.e. no compaction model was picked), which is the correct attribution in that case. The success path already used compactionEndpoint.model, so prism success vs. failure telemetry is now comparable.

@bhavyaus
Bhavya U (bhavyaus) force-pushed the ryangabriel/custom_trajectory_compaction_model branch from c31b199 to 07f3f67 Compare June 7, 2026 19:31
Bhavya U (bhavyaus) pushed a commit to gryan11/vscode that referenced this pull request Jun 7, 2026
…oft#316114)

Route conversation-history compaction (foreground /compact and background auto-compaction) to the dedicated trajectory-compaction CAPI model when chat.conversationCompaction.usePrismCompaction is enabled and the agent model matches chat.conversationCompaction.prismModelFilter. When the flag is off, behavior is unchanged from upstream.

Squashed rebase of PR microsoft#316114 onto main. Conflicts resolved by unioning additive changes: combined main's isCAPIEndpoint import with the PR's APIUsage import in agentIntent.ts, and kept both main's longToolCallCachePreservation.* and the PR's conversationCompaction.* nls keys. main's microsoft#320273 background-summarization anchor-round fix is preserved (backgroundSummarizer.ts unchanged).
…oft#316114)

Route conversation-history compaction (foreground /compact and background auto-compaction) to the dedicated trajectory-compaction CAPI model when chat.conversationCompaction.usePrismCompaction is enabled and the agent model matches chat.conversationCompaction.prismModelFilter. When the flag is off, behavior is unchanged from upstream.

Squashed rebase of PR microsoft#316114 onto main. Conflicts resolved by unioning additive changes: combined main's isCAPIEndpoint import with the PR's APIUsage import in agentIntent.ts, and kept both main's longToolCallCachePreservation.* and the PR's conversationCompaction.* nls keys. main's microsoft#320273 background-summarization anchor-round fix is preserved (backgroundSummarizer.ts unchanged).
@bhavyaus
Bhavya U (bhavyaus) force-pushed the ryangabriel/custom_trajectory_compaction_model branch from 07f3f67 to ae3c849 Compare June 7, 2026 20:10
roblourens
roblourens previously approved these changes Jun 7, 2026
@bhavyaus

Copy link
Copy Markdown
Collaborator

Michael Lively (@Yoyokrazy) pinging here - need help adding Gabe

Resolved conflicts:
- extensions/copilot/src/extension/intents/node/agentIntent.ts: combined main's raceTimeout import with the PR's CancellationError import; dropped stale backgroundTodoProcessor import (renamed/moved on main to backgroundTodoAgent/backgroundTodoAgentProcessor) since BackgroundTodoDecision/BackgroundTodoProcessor/IBackgroundTodoExecutionContext were no longer referenced.
- extensions/copilot/src/extension/prompt/vscode-node/endpointProviderImpl.ts: kept the PR's extended JSDoc describing the trajectory-compaction CAPI family fallthrough.

Co-authored-by: Copilot <[email protected]>
@bhavyaus
Bhavya U (bhavyaus) merged commit 43d80e3 into microsoft:main Jun 9, 2026
25 checks passed
@vs-code-engineering vs-code-engineering Bot added this to the 1.125.0 milestone Jun 9, 2026
@vs-code-engineering vs-code-engineering Bot locked and limited conversation to collaborators Jul 24, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants