Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/* __GDPR__FRAGMENT__
"SummarizedConversationHistoryData" : {
"summarizationId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "An ID to join all attempts of this summarization task." },
"outcome": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The success state or failure reason of the summarization." },
"detailedOutcome": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "A more detailed error message." },
"model": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The model ID used for the summarization." },
"requestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The request ID from the summarization call." },
"chatRequestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The chat request ID that this summarization ran during." },
"promptTypes": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Role and character count of each prompt message in order, as a proxy for cache hit rate (e.g. system:1234,user:567)." },
"numRounds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The number of tool call rounds before this summarization was triggered." },
"numRoundsSinceLastSummarization": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The number of tool call rounds since the last summarization." },
"turnIndex": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The index of the current turn." },
"curTurnRoundIndex": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The index of the current round within the current turn." },
"lastUsedTool": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The name of the last tool used before summarization." },
"isDuringToolCalling": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Whether this summarization was triggered during a tool calling loop." },
"conversationId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Id for the current chat conversation." },
"hasWorkingNotebook": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Whether the conversation summary includes a working notebook." },
"mode": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The mode of the conversation summary." },
"summarizationMode": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The mode of the conversation summary." },
"duration": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The duration of the summarization attempt in ms." },
"promptTokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "comment": "Number of prompt tokens, server side counted", "isMeasurement": true },
"promptCacheTokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "comment": "Number of prompt tokens hitting cache as reported by server", "isMeasurement": true },
"responseTokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "comment": "Number of generated tokens", "isMeasurement": true }
}
*/
export
interface
ConversationHistorySummarizationPromptProps
extends
SummarizedAgentHistoryProps
{
readonly
?
:
boolean
;
}
const
SummaryPrompt
=
<>
Your task is to create a comprehensive, detailed summary of the entire conversation that captures all essential information needed to seamlessly continue the work without any loss of context. This summary will be used to compact the conversation while preserving critical technical details, decisions, and progress.
<br/>
## Recent Context Analysis<br />
Pay special attention to the most recent agent commands and tool executions that led to this summarization being triggered. Include:
<br/>
- **Last Agent Commands**: What specific actions/tools were just executed<br />
- **Tool Results**: Key outcomes from recent tool calls (truncate if very long, but preserve essential information)
<br/>
- **Immediate State**: What was the system doing right before summarization<br />
- **Triggering Context**: What caused the token budget to be exceeded<br />
## Analysis Process<br />
Before providing your final summary, wrap your analysis in `<analysis>` tags to organize your thoughts systematically:
<br/>
1. **Chronological Review**: Go through the conversation chronologically, identifying key phases and transitions<br />
2. **Intent Mapping**: Extract all explicit and implicit user requests, goals, and expectations<br />
3. **Technical Inventory**: Catalog all technical concepts, tools, frameworks, and architectural decisions<br />
4. **Code Archaeology**: Document all files, functions, and code patterns that were discussed or modified<br />
5. **Progress Assessment**: Evaluate what has been completed vs. what remains pending<br />
6. **Context Validation**: Ensure all critical information for continuation is captured<br />
7. **Recent Commands Analysis**: Document the specific agent commands and tool results from the most recent operations<br />
## Summary Structure<br />
Your summary must include these sections in order, following the exact format below:
<br/>
<Tagname='analysis'>
[Chronological Review: Walk through conversation phases: initial request → exploration → implementation → debugging → current state]
<br/>
[Intent Mapping: List each explicit user request with message context]
<br/>
[Technical Inventory: Catalog all technologies, patterns, and decisions mentioned]
<br/>
[Code Archaeology: Document every file, function, and code change discussed]
<br/>
[Progress Assessment: What's done vs. pending with specific status]
<br/>
[Context Validation: Verify all continuation context is captured]
<br/>
[Recent Commands Analysis: Last agent commands executed, tool results (truncated if long), immediate pre-summarization state]
<br/>
</Tag>
<br />
<Tagname='summary'>
1. Conversation Overview:
<br/>
- Primary Objectives: [All explicit user requests and overarching goals with exact quotes]
<br/>
- Session Context: [High-level narrative of conversation flow and key phases]
<br/>
- User Intent Evolution: [How user's needs or direction changed throughout conversation]
<br/>
2. Technical Foundation:
<br/>
- [Core Technology 1]: [Version/details and purpose]
<br/>
- [Framework/Library 2]: [Configuration and usage context]
<br/>
- [Architectural Pattern 3]: [Implementation approach and reasoning]
<br/>
- [Environment Detail 4]: [Setup specifics and constraints]
<br/>
3. Codebase Status:
<br/>
- [File Name 1]:
<br/>
- Purpose: [Why this file is important to the project]
<br/>
- Current State: [Summary of recent changes or modifications]
<br/>
- Key Code Segments: [Important functions/classes with brief explanations]
<br/>
- Dependencies: [How this relates to other components]
<br/>
- [File Name 2]:
<br/>
- Purpose: [Role in the project]
<br/>
- Current State: [Modification status]
<br/>
- Key Code Segments: [Critical code blocks]
<br/>
- [Additional files as needed]
<br/>
4. Problem Resolution:
<br/>
- Issues Encountered: [Technical problems, bugs, or challenges faced]
<br/>
- Solutions Implemented: [How problems were resolved and reasoning]
<br/>
- Debugging Context: [Ongoing troubleshooting efforts or known issues]
<br/>
- Lessons Learned: [Important insights or patterns discovered]
<br/>
5. Progress Tracking:
<br/>
- Completed Tasks: [What has been successfully implemented with status indicators]
<br/>
- Partially Complete Work: [Tasks in progress with current completion status]
<br/>
- Validated Outcomes: [Features or code confirmed working through testing]
<br/>
6. Active Work State:
<br/>
- Current Focus: [Precisely what was being worked on in most recent messages]
<br/>
- Recent Context: [Detailed description of last few conversation exchanges]
<br/>
- Working Code: [Code snippets being modified or discussed recently]
<br/>
- Immediate Context: [Specific problem or feature being addressed before summary]
<br/>
7. Recent Operations:
<br/>
- Last Agent Commands: [Specific tools/actions executed just before summarization with exact command names]
<br/>
- Tool Results Summary: [Key outcomes from recent tool executions - truncate long results but keep essential info]
<br/>
- Pre-Summary State: [What the agent was actively doing when token budget was exceeded]
<br/>
- Operation Context: [Why these specific commands were executed and their relationship to user goals]
<br/>
8. Continuation Plan:
<br/>
- [Pending Task 1]: [Details and specific next steps with verbatim quotes]
<br/>
- [Pending Task 2]: [Requirements and continuation context]
<br/>
- [Priority Information]: [Which tasks are most urgent or logically sequential]
<br/>
- [Next Action]: [Immediate next step with direct quotes from recent messages]
<br/>
</Tag>
<br />
## Quality Guidelines<br />
- **Precision**: Include exact filenames, function names, variable names, and technical terms<br />
- **Completeness**: Capture all context needed to continue without re-reading the full conversation<br />
- **Clarity**: Write for someone who needs to pick up exactly where the conversation left off<br />
- **Verbatim Accuracy**: Use direct quotes for task specifications and recent work context<br />
- **Technical Depth**: Include enough detail for complex technical decisions and code patterns<br />
- **Logical Flow**: Present information in a way that builds understanding progressively<br />
This summary should serve as a comprehensive handoff document that enables seamless continuation of all active work streams while preserving the full technical and contextual richness of the original conversation.
<br/>
</>
;
/**
* Prompt used to summarize conversation history when the context window is exceeded.
*/
Summarize the conversation history so far, paying special attention to the most recent agent commands and tool results that triggered this summarization. Structure your summary using the enhanced format provided in the system message.
<br/>
{
&&
<>
<br/>
IMPORTANT: Do NOT call any tools. Your only task is to generate a text summary of the conversation. Do not attempt to execute any actions or make any tool calls.
<br/>
</>
}
Focus particularly on:
<br/>
- The specific agent commands/tools that were just executed<br />
- The results returned from these recent tool calls (truncate if very long but preserve key information)
<br/>
- What the agent was actively working on when the token budget was exceeded<br />
- How these recent operations connect to the overall user goals<br />
Include all important tool calls and their results as part of the appropriate sections, with special emphasis on the most recent operations.
</UserMessage>
</>
)
;
}
}
class
WorkingNotebookSummary
extends
PromptElement<NotebookSummaryProps>
{
async
render
(
:
void
,
:
PromptSizing
)
{
return
(
<UserMessage>
This is the current state of the notebook that you have been working on:
// Reverse the tool call rounds so they are in chronological order
.
reverse
(
)
;
.
push
(
<ChatToolCallsflexGrow={1}promptContext={this.props.promptContext}toolCallRounds={toolCallRounds}toolCallResults={toolCallResults}isHistorical={!(toolCallResultInNextTurn && i ===this.props.promptContext.history.length-1)}truncateAt={this.props.maxToolResultLength}/>
)
;
.
push
(
...
.
reverse
(
)
)
;
if
(
)
{
// All preceding turns are covered by the summary and shouldn't be included verbatim
/** Optional hard cap on summary tokens; effective budget = min(prompt sizing tokenBudget, this value) */
readonly
?
:
number
;
/** Optional custom instructions to include in the summarization prompt */
readonly
?
:
string
;
/** Skip Full mode and go straight to Simple mode for foreground budget-exceeded recovery. */
readonly
?
:
boolean
;
/**
* Forwarded to the latest user message when the customizations-index has
* drifted from its frozen snapshot. See {@link AgentUserMessageProps.customizationsIndexUpdate}.
*/
readonly
?
:
{
:
string
;
:
readonly
ChatLanguageModelToolReference
[
]
|
undefined
}
;
}
/**
* Renders conversation history with tool calls and summaries, triggering summarization while rendering if necessary.
*/
export
class
SummarizedConversationHistory
extends
PromptElement<SummarizedAgentHistoryProps>
{
constructor
(
:
SummarizedAgentHistoryProps
,
IInstantiationService
private
readonly
:
IInstantiationService
,
ISessionTranscriptService
private
readonly
:
ISessionTranscriptService
,
)
{
super
(
)
;
}
async
render
(
:
void
,
:
PromptSizing
,
:
Progress
<
ChatResponsePart
>
|
undefined
,
:
CancellationToken
|
undefined
)
{
const
=
{
...
this
.
props
.
promptContext
}
;
let
:
SummarizedConversationHistoryMetadata
|
undefined
;
const
=
this
.
props
.
promptContext
.
conversation
?.
;
if
(
)
{
// Lazily start the transcript session now (before summarization) so it
// captures the full pre-compaction conversation. startSession is
// idempotent — if hooks already started it, this is a no-op.
/**
* Lazily starts a transcript session with the full conversation history.
* This is called just before summarization so that the transcript file
* contains the complete pre-compaction conversation. If a session was
* already started (e.g. by hooks), this is a no-op.
*/
private
async
ensureTranscriptSession
(
)
:
Promise
<
void
>
{
const
=
this
.
props
.
promptContext
.
conversation
?.
;
if
(
!
)
{
return
;
}
// Short-circuit if session already exists — avoids rebuilding
// the full IHistoricalTurn[] array on every render.
if
(
this
.
sessionTranscriptService
.
getTranscriptPath
(
)
)
{
return
;
}
// Build IHistoricalTurn[] from the prompt context's Turn[] history
const
:
IHistoricalTurn
[
]
=
this
.
props
.
promptContext
.
history
.
map
(
=>
(
{
:
.
request
.
message
,
:
.
startTime
,
:
.
rounds
.
map
(
=>
(
{
:
.
response
,
:
.
toolCalls
.
map
(
=>
(
{
:
.
name
,
:
.
arguments
,
:
.
id
,
}
)
)
,
:
.
thinking
?
(
Array
.
isArray
(
.
thinking
.
text
)
?
.
thinking
.
text
.
join
(
''
)
:
.
thinking
.
text
)
:
undefined
,
:
.
timestamp
,
}
)
)
,
}
)
)
;
await
this
.
sessionTranscriptService
.
startSession
(
,
undefined
,
.
length
>
0
?
:
undefined
)
;
}
private
addSummaryToHistory
(
:
string
,
:
string
,
?
:
ThinkingData
)
:
void
{
const
=
this
.
props
.
promptContext
.
toolCallRounds
?.
find
(
=>
.
id
===
)
;
if
(
)
{
.
summary
=
;
// Only ever overwrite: clearing would drop a signed block the round is still replayed with.
if
(
)
{
.
thinking
=
;
}
return
;
}
// Adding summaries to rounds in previous turns will only be persisted during the current session.
// For the next turn, need to restore them from metadata (see normalizeSummariesOnRounds).
for
(
const
of
[
...
this
.
props
.
promptContext
.
history
]
.
reverse
(
)
)
{
const
=
.
rounds
.
find
(
=>
.
id
===
)
;
if
(
)
{
.
summary
=
;
if
(
)
{
.
thinking
=
;
}
break
;
}
}
}
}
/**
* Only Anthropic's manual thinking mode (`type: "enabled"`) requires an assistant message to open
* with a thinking block. Adaptive thinking accepts history as-is, so carrying a signed block onto
* a round that never produced one is a pointless edit of a message the API returned.
*/
function
requiresLeadingThinkingBlock
(
:
IChatEndpoint
)
:
boolean
{
return
isAnthropicFamily
(
)
&&
!
.
supportsAdaptiveThinking
;
}
enum
SummaryMode
{
Simple
=
'simple'
,
Full
=
'full'
}
interface
SummarizationResult
{
:
FetchSuccess
<
string
>
;
?
:
readonly
ChatResultPromptTokenDetail
[
]
;
?
:
string
;
?
:
string
;
?
:
number
;
?
:
number
;
?
:
number
;
}
class
ConversationHistorySummarizer
{
private
readonly
=
generateUuid
(
)
;
constructor
(
private
readonly
:
SummarizedAgentHistoryProps
,
private
readonly
:
PromptSizing
,
private
readonly
:
Progress
<
ChatResponsePart
>
|
undefined
,
private
readonly
:
CancellationToken
|
undefined
,
ITelemetryService
private
readonly
:
ITelemetryService
,
ILogService
private
readonly
:
ILogService
,
IInstantiationService
private
readonly
:
IInstantiationService
,
IConfigurationService
private
readonly
:
IConfigurationService
,
IChatHookService
private
readonly
:
IChatHookService
,
ISessionTranscriptService
private
readonly
:
ISessionTranscriptService
,
)
{
}
async
summarizeHistory
(
)
:
Promise
<
{
:
string
;
:
string
;
?
:
ThinkingData
;
?
:
APIUsage
;
?
:
readonly
ChatResultPromptTokenDetail
[
]
;
?
:
string
;
?
:
string
;
?
:
number
;
?
:
number
;
?
:
number
}
|
undefined
>
{
// Execute pre-compact hook before summarization to allow hooks to archive transcripts or perform cleanup
await
this
.
executePreCompactHook
(
)
;
// Just a function for test to create props and call this
const
=
this
.
instantiationService
.
createInstance
(
SummarizedConversationHistoryPropsBuilder
)
.
getProps
(
this
.
props
)
;
if
(
!
)
{
this
.
logService
.
info
(
'[ConversationHistorySummarizer] no prior content to summarize, skipping'
)
;
return
undefined
;
}
const
=
this
.
getSummaryWithFallback
(
)
;
this
.
progress
?.
report
(
new
ChatResponseProgressPart2
(
.
t
(
'Compacting conversation...'
)
,
async
(
)
=>
{
try
{
await
;
}
catch
{
return
.
t
(
'Could not compact conversation'
)
;
}
return
.
t
(
'Compacted conversation'
)
;
}
)
)
;
const
=
await
;
const
{
,
}
=
computeSummarizationRoundCounts
(
this
.
props
.
promptContext
.
history
,
this
.
props
.
promptContext
.
toolCallRounds
)
;
return
{
:
this
.
appendTranscriptHint
(
.
result
.
value
)
,
:
.
summarizedToolCallRoundId
,
:
.
summarizedThinking
,
:
.
result
.
usage
,
:
.
promptTokenDetails
,
:
.
model
,
:
.
summarizationMode
,
,
,
:
.
durationMs
,
}
;
}
/**
* Strips the `<analysis>` scratchpad and `<summary>` wrapper from a compaction
* response. Falls back to the raw text when the model omits the tags.
*/
private
unwrapSummary
(
:
string
)
:
string
{
const
=
extractSummary
(
)
;
if
(
===
undefined
)
{
this
.
logService
.
debug
(
'[ConversationHistorySummarizer] no <summary> tags in compaction response, using raw response text'
)
;
return
;
}
return
;
}
private
appendTranscriptHint
(
:
string
)
:
string
{
const
=
this
.
props
.
promptContext
.
conversation
?.
;
if
(
!
)
{
return
;
}
return
appendTranscriptHintToSummary
(
,
,
this
.
sessionTranscriptService
)
;
}
private
async
getSummaryWithFallback
(
:
ISummarizedConversationHistoryInfo
)
:
Promise
<
SummarizationResult
>
{
const
=
this
.
configurationService
.
getConfig
<
string
|
undefined
>
(
ConfigKey
.
Advanced
.
AgentHistorySummarizationMode
)
;
if
(
this
.
props
.
forceSimpleSummary
&&
!==
SummaryMode
.
Full
)
{
// Foreground budget-exceeded recovery — go straight to Simple.
/**
* Executes the PreCompact hook before summarization starts.
* This gives hook scripts a chance to archive the transcript or perform cleanup
* before the conversation is compacted.
*/
/**
* Send telemetry for conversation summarization.
* @param outcome High-level result of the summarization (for example, 'success', 'too_large', or the ChatFetchResponseType value)
* @param requestId Unique identifier of the underlying chat request used for summarization
* @param model Identifier of the language model used to generate the summary
* @param mode Summarization mode indicating how the conversation was summarized
* @param elapsedTime Total time in milliseconds taken for the summarization request
* @param usage Token usage information for the summarization request, if available
* @param detailedOutcome Optional detailed reason for non-success outcomes (for example, error or cancellation reason)
* @param promptTypes Optional pre-computed promptTypes string for the summarization request
*/
private
sendSummarizationTelemetry
(
:
string
,
:
string
,
:
string
,
:
SummaryMode
,
:
number
,
:
APIUsage
|
undefined
,
?
:
string
,
?
:
string
)
:
void
{
const
{
,
}
=
computeSummarizationRoundCounts
(
this
.
props
.
promptContext
.
history
,
this
.
props
.
promptContext
.
toolCallRounds
)
;
const
=
this
.
props
.
promptContext
.
history
.
length
;
const
=
this
.
props
.
promptContext
.
toolCallRounds
?.
??
0
;
const
=
this
.
props
.
promptContext
.
toolCallRounds
?.
at
(
-
1
)
?.
?.
at
(
-
1
)
?.
??
this
.
props
.
promptContext
.
history
?.
at
(
-
1
)
?.
.
at
(
-
1
)
?.
?.
at
(
-
1
)
?.
??
'none'
;
const
=
!
!
this
.
props
.
promptContext
.
toolCallRounds
?.
?
1
:
0
;
const
=
this
.
props
.
promptContext
.
conversation
?.
;
const
=
this
.
props
.
workingNotebook
?
1
:
0
;
/* __GDPR__
"summarizedConversationHistory" : {
"owner": "roblourens",
"comment": "Tracks when summarization happens and what the outcome was",
"${include}": [ "${SummarizedConversationHistoryData}" ]
}
*/
this
.
telemetryService
.
sendMSFTTelemetryEvent
(
'summarizedConversationHistory'
,
{
:
this
.
summarizationId
,
,
,
,
:
this
.
props
.
promptContext
.
conversation
?.
getLatestTurn
(
)
.
id
,
,
,
,
,
:
,
// Try to unstick GDPR
,
}
,
{
,
,
,
,
,
,
:
,
:
?.
,
:
?.
?.
,
:
?.
,
}
)
;
}
}
export
function
stripCacheBreakpoints
(
:
ChatMessage
[
]
)
:
void
{
.
forEach
(
=>
{
.
content
=
.
content
.
filter
(
=>
{
return
.
type
!==
Raw
.
ChatCompletionContentPartKind
.
CacheBreakpoint
;
}
)
;
}
)
;
}
export
function
replaceImageContentWithPlaceholders
(
:
ChatMessage
[
]
)
:
void
{
.
forEach
(
=>
{
.
content
=
.
content
.
map
(
=>
{
if
(
.
type
===
Raw
.
ChatCompletionContentPartKind
.
Image
)
{
return
{
:
Raw
.
ChatCompletionContentPartKind
.
Text
,
:
'[Image was attached]'
}
;
}
return
;
}
)
;
}
)
;
}
/**
* Bake a stable transcript pointer into a freshly-produced summary text.
*
* Shared by both the full/simple summarization path
* ({@link ConversationHistorySummarizer}) and the background summarization
* path in `agentIntent.ts`. The hint is appended exactly once, at summary
* creation time, so the resulting string is frozen from then on and replayed
* verbatim — preserving Anthropic prompt cache hits across subsequent renders.
*
* Returns the input unchanged when there is no transcript on disk for the
* session.
*/
export
function
appendTranscriptHintToSummary
(
:
string
,
:
string
,
:
ISessionTranscriptService
)
:
string
{
const
=
.
getTranscriptPath
(
)
;
if
(
!
)
{
return
;
}
const
=
.
fsPath
;
const
=
.
getLineCount
(
)
;
let
=
;
+=
`\nIf you need specific details from before compaction (such as exact code snippets, error messages, tool results, or content you previously generated), use the ${ToolName.ReadFile} tool to look up the full uncompacted conversation transcript at: "${transcriptPath}"`
;
if
(
!==
undefined
)
{
+=
`\nAt the time this summary was created, the transcript had ${lineCount} lines.`
/**
* Strip custom client-side tool search (tool_search) tool_use and tool_result
* messages from the conversation. The summarization call uses ChatLocation.Other
* but createMessagesRequestBody still converts tool_search results to
* tool_reference blocks (customToolSearchEnabled isn't gated by location).
* Without tool search enabled in the request, Anthropic rejects tool_reference
* content blocks with: "Input tag 'tool_reference' found using 'type' does not
* match any of the expected tags".
*/
export
function
stripToolSearchMessages
(
:
ChatMessage
[
]
)
:
ChatMessage
[
]
{
const
=
new
Set<string>
(
)
;
for
(
const
of
)
{
if
(
.
role
===
Raw
.
ChatRole
.
Assistant
&&
.
toolCalls
)
{
for
(
const
of
.
toolCalls
)
{
if
(
.
function
.
name
===
CUSTOM_TOOL_SEARCH_NAME
)
{
.
add
(
.
id
)
;
}
}
}
}
if
(
.
size
===
0
)
{
return
;
}
return
.
map
(
=>
{
if
(
.
role
===
Raw
.
ChatRole
.
Assistant
&&
.
toolCalls
)
{
const
=
.
toolCalls
.
filter
(
=>
!
.
has
(
.
id
)
)
;
if
(
.
length
!==
.
toolCalls
.
length
)
{
return
{
...
,
:
.
length
>
0
?
:
undefined
}
;
}
}
else
if
(
.
role
===
Raw
.
ChatRole
.
Tool
&&
.
toolCallId
&&
.
has
(
.
toolCallId
)
)
{
return
undefined
;
}
return
;
}
)
.
filter
(
(
)
:
is
ChatMessage
=>
!==
undefined
)
;
}
export
interface
ISummarizedConversationHistoryInfo
{
readonly
:
SummarizedAgentHistoryProps
;
readonly
:
string
;
readonly
?
:
ThinkingData
;
}
/**
* Exported for test
*/
export
class
SummarizedConversationHistoryPropsBuilder
{
constructor
(
IPromptPathRepresentationService
private
readonly
:
IPromptPathRepresentationService
,
IWorkspaceService
private
readonly
:
IWorkspaceService
,
)
{
}
getProps
(
:
SummarizedAgentHistoryProps
)
:
ISummarizedConversationHistoryInfo
|
undefined
{
let
=
.
promptContext
.
toolCallRounds
;
let
=
.
promptContext
.
isContinuation
;
let
=
''
;
if
(
&&
.
length
>
1
)
{
// If there are multiple tool call rounds, exclude the last one, because it must have put us over the limit.
// Summarize from the previous round in this turn.
=
.
slice
(
0
,
-
1
)
;
=
.
at
(
-
1
)
!
.
id
;
}
else
if
(
.
promptContext
.
history
.
length
>
0
)
{
// If there is only one tool call round, then summarize from the last round of the last turn.
// Or if there are no tool call rounds, then the new user message put us over the limit. (or the last assistant message?)
// This flag excludes the last user message from the summary.
=
true
;
=
[
]
;
=
.
promptContext
.
history
.
at
(
-
1
)
!
.
rounds
.
at
(
-
1
)
!
.
id
;
}
else
{
return
undefined
;
}
const
=
requiresLeadingThinkingBlock
(
.
endpoint
)
?
this
.
findLastThinking
(
)
:
undefined
;
const
=
{
...
.
promptContext
,
,
,
}
;
return
{
:
{
...
,
:
this
.
getWorkingNotebook
(
)
,
}
,
,
}
;
}
private
findLastThinking
(
:
SummarizedAgentHistoryProps
)
:
ThinkingData
|
undefined
{
if
(
.
promptContext
.
toolCallRounds
)
{
for
(
let
=
.
promptContext
.
toolCallRounds
.
length
-
1
;
>=
0
;
--
)
{
const
=
.
promptContext
.
toolCallRounds
[
]
;
if
(
.
thinking
)
{
return
.
thinking
;
}
}
}
return
undefined
;
}
private
getWorkingNotebook
(
:
SummarizedAgentHistoryProps
)
:
NotebookDocument
|
undefined
{
const
=
.
promptContext
.
toolCallRounds
&&
[
...
.
promptContext
.
toolCallRounds
]
.
reverse
(
)
.
find
(
=>
.
toolCalls
.
some
(
=>
.
name
===
ToolName
.
RunNotebookCell
)
)
;
const
=
?.
.
find
(
=>
.
name
===
ToolName
.
RunNotebookCell
)
;
if
(
&&
.
arguments
)
{
try
{
const
=
JSON
.
parse
(
.
arguments
)
;
if
(
typeof
.
filePath
===
'string'
)
{
const
=
this
.
_promptPathRepresentationService
.
resolveFilePath
(
.
filePath
)
;
if
(
!
)
{
return
undefined
;
}
return
this
.
_workspaceService
.
notebookDocuments
.
find
(
=>
.
uri
.
toString
(
)
===
.
toString
(
)
)
;
}
}
catch
(
)
{
// Ignore parsing errors
}
}
return
undefined
;
}
}
interface
SummaryMessageProps
extends
BasePromptElementProps
{
readonly
:
string
;
readonly
:
IChatEndpoint
;
}
class
SummaryMessageElement
extends
PromptElement<SummaryMessageProps>
{
async
render
(
:
void
,
:
PromptSizing
)
{
return
<UserMessage>
<Tagname='conversation-summary'>
{
this
.
props
.
summaryText
}
</Tag>
{
this
.
props
.
endpoint
.
family
===
'gpt-4.1'
&&
<Tagname='reminderInstructions'>
<DefaultOpenAIKeepGoingReminder/>
</Tag>
}
</UserMessage>
;
}
}
export
interface
SummarizationUserMessageProps
extends
BasePromptElementProps
{
readonly
:
IChatEndpoint
;
}
/**
* User message appended to the agent prompt when background summarization is
* triggered. Instructs the model to output ONLY a summary wrapped in
* `<summary>` tags, with no tool calls. The summary is extracted from the
* response and stored on the round for the next iteration.
*/
export
class
SummarizationUserMessage
extends
PromptElement<SummarizationUserMessageProps>
{
async
render
(
:
void
,
:
PromptSizing
)
{
const
=
this
.
props
.
endpoint
.
model
.
startsWith
(
'claude-opus'
)
;
return
<UserMessagepriority={1000}>
The conversation has grown too large for the context window and must be compacted now.
<br/>
<br/>
{
SummaryPrompt
}
<br/>
<br/>
IMPORTANT: Output your summary wrapped in
{
'<summary>'
}
and
{
'</summary>'
}
tags. Do NOT call any tools. Your ONLY task right now is to produce a comprehensive summary of the conversation so far.
<br/>
{
&&
<>
<br/>
IMPORTANT: Do NOT call any tools. Your only task is to generate a text summary of the conversation. Do not attempt to execute any actions or make any tool calls.
<br/>
</>
}
</UserMessage>
;
}
}
/**
* Extracts a summary from the model's response text.
*
* Parsing strategy (multi-level fallback):
* 1. Clean `<summary>...</summary>` tags → extracts content between them
* 2. `<summary>` found but no closing tag → takes everything after `<summary>`
* 3. No tags found → returns undefined (caller falls back to separate-call summarization)
*
* @returns The extracted summary text, or `undefined` if no summary could be found.
*/
export
function
extractSummary
(
:
string
)
:
string
|
undefined
{
// 1. Try clean <summary>...</summary> extraction
const
=
'<summary>'
;
const
=
'</summary>'
;
const
=
.
indexOf
(
)
;
if
(
!==
-
1
)
{
const
=
+
.
length
;
const
=
.
indexOf
(
,
)
;
if
(
!==
-
1
)
{
// Clean extraction
return
.
substring
(
,
)
.
trim
(
)
;
}
// 2. Open tag but no closing tag — take everything after <summary>