From e0478493a2a7b3c4cf2d9577fa4a8efc6aed9cdc Mon Sep 17 00:00:00 2001
From: Toshii <94262432+0xToshii@users.noreply.github.com>
Date: Wed, 13 Aug 2025 13:59:00 -0700
Subject: [PATCH] auto compact - context management (#5520)
* base
* working state reduction & summarization flow wo duplicate calls
* stop injecting into user message
* focus on latest message
* edge case for cancelled stream post summarization tool call
* fix merge
---
proto/cline/ui.proto | 1 +
src/core/assistant-message/index.ts | 1 +
.../context-management/ContextManager.ts | 76 +++++--------------
src/core/prompts/contextManagement.ts | 75 ++++++++++++++++++
src/core/task/TaskState.ts | 3 +
src/core/task/ToolExecutor.ts | 60 +++++++++++++++
src/core/task/index.ts | 68 ++++++++++++++++-
src/shared/ExtensionMessage.ts | 2 +
src/shared/proto-conversions/cline-message.ts | 2 +
webview-ui/src/components/chat/ChatRow.tsx | 75 ++++++++++++++++++
10 files changed, 303 insertions(+), 60 deletions(-)
create mode 100644 src/core/prompts/contextManagement.ts
diff --git a/proto/cline/ui.proto b/proto/cline/ui.proto
index f73ddb43..f40a6b3d 100644
--- a/proto/cline/ui.proto
+++ b/proto/cline/ui.proto
@@ -41,6 +41,7 @@ enum ClineAsk {
NEW_TASK = 13;
CONDENSE = 14;
REPORT_BUG = 15;
+ SUMMARIZE_TASK = 16;
}
// Enum for ClineSay types
diff --git a/src/core/assistant-message/index.ts b/src/core/assistant-message/index.ts
index 4165b343..4b425cf3 100644
--- a/src/core/assistant-message/index.ts
+++ b/src/core/assistant-message/index.ts
@@ -25,6 +25,7 @@ export const toolUseNames = [
"attempt_completion",
"new_task",
"condense",
+ "summarize_task",
"report_bug",
"new_rule",
"web_fetch",
diff --git a/src/core/context/context-management/ContextManager.ts b/src/core/context/context-management/ContextManager.ts
index 83fde4dd..68592d02 100644
--- a/src/core/context/context-management/ContextManager.ts
+++ b/src/core/context/context-management/ContextManager.ts
@@ -106,7 +106,24 @@ export class ContextManager {
}
/**
- * primary entry point for getting up to date context & truncating when required
+ * Determine whether we should compact context window, based on token counts
+ */
+ shouldCompactContextWindow(clineMessages: ClineMessage[], api: ApiHandler, previousApiReqIndex: number): boolean {
+ if (previousApiReqIndex >= 0) {
+ const previousRequest = clineMessages[previousApiReqIndex]
+ if (previousRequest && previousRequest.text) {
+ const { tokensIn, tokensOut, cacheWrites, cacheReads }: ClineApiReqInfo = JSON.parse(previousRequest.text)
+ const totalTokens = (tokensIn || 0) + (tokensOut || 0) + (cacheWrites || 0) + (cacheReads || 0)
+
+ const { maxAllowedSize } = getContextWindowInfo(api)
+ return totalTokens >= maxAllowedSize
+ }
+ }
+ return false
+ }
+
+ /**
+ * primary entry point for getting up to date context
*/
async getNewContextMessagesAndMetadata(
apiConversationHistory: Anthropic.Messages.MessageParam[],
@@ -118,63 +135,6 @@ export class ContextManager {
) {
let updatedConversationHistoryDeletedRange = false
- // If the previous API request's total token usage is close to the context window, truncate the conversation history to free up space for the new request
- if (previousApiReqIndex >= 0) {
- const previousRequest = clineMessages[previousApiReqIndex]
- if (previousRequest && previousRequest.text) {
- const timestamp = previousRequest.ts
- const { tokensIn, tokensOut, cacheWrites, cacheReads }: ClineApiReqInfo = JSON.parse(previousRequest.text)
- const totalTokens = (tokensIn || 0) + (tokensOut || 0) + (cacheWrites || 0) + (cacheReads || 0)
- const { maxAllowedSize } = getContextWindowInfo(api)
-
- // This is the most reliable way to know when we're close to hitting the context window.
- if (totalTokens >= maxAllowedSize) {
- // Since the user may switch between models with different context windows, truncating half may not be enough (ie if switching from claude 200k to deepseek 64k, half truncation will only remove 100k tokens, but we need to remove much more)
- // So if totalTokens/2 is greater than maxAllowedSize, we truncate 3/4 instead of 1/2
- const keep = totalTokens / 2 > maxAllowedSize ? "quarter" : "half"
-
- // we later check how many chars we trim to determine if we should still truncate history
- let [anyContextUpdates, uniqueFileReadIndices] = this.applyContextOptimizations(
- apiConversationHistory,
- conversationHistoryDeletedRange ? conversationHistoryDeletedRange[1] + 1 : 2,
- timestamp,
- )
-
- let needToTruncate = true
- if (anyContextUpdates) {
- // determine whether we've saved enough chars to not truncate
- const charactersSavedPercentage = this.calculateContextOptimizationMetrics(
- apiConversationHistory,
- conversationHistoryDeletedRange,
- uniqueFileReadIndices,
- )
- if (charactersSavedPercentage >= 0.3) {
- needToTruncate = false
- }
- }
-
- if (needToTruncate) {
- // go ahead with truncation
- anyContextUpdates = this.applyStandardContextTruncationNoticeChange(timestamp) || anyContextUpdates
-
- // NOTE: it's okay that we overwriteConversationHistory in resume task since we're only ever removing the last user message and not anything in the middle which would affect this range
- conversationHistoryDeletedRange = this.getNextTruncationRange(
- apiConversationHistory,
- conversationHistoryDeletedRange,
- keep,
- )
-
- updatedConversationHistoryDeletedRange = true
- }
-
- // if we alter the context history, save the updated version to disk
- if (anyContextUpdates) {
- await this.saveContextHistory(taskDirectory)
- }
- }
- }
- }
-
const truncatedConversationHistory = this.getAndAlterTruncatedMessages(
apiConversationHistory,
conversationHistoryDeletedRange,
diff --git a/src/core/prompts/contextManagement.ts b/src/core/prompts/contextManagement.ts
new file mode 100644
index 00000000..e6e113a8
--- /dev/null
+++ b/src/core/prompts/contextManagement.ts
@@ -0,0 +1,75 @@
+export const summarizeTask = () =>
+ `
+The current conversation is rapidly running out of context. Now, your urgent task is to create a comprehensive detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
+This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context. You MUST ONLY respond to this message by using the summarize_task tool call.
+
+Before providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
+1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
+ - The user's explicit requests and intents
+ - Your approach to addressing the user's requests
+ - Key decisions, technical concepts and code patterns
+ - Specific details like file names, full code snippets, function signatures, file edits, etc
+2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
+
+Your summary should include the following sections:
+1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
+2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
+3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
+4. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
+5. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
+6. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
+7. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests without confirming with the user first.
+ If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
+8. You should pay special attention to the most recent user message, as it indicates the user's most recent intent, if applicable.
+
+Usage:
+
+Your detailed summary
+
+
+Here's an example of how your output should be structured:
+
+
+
+[Your thought process, ensuring all points are covered thoroughly and accurately]
+
+
+
+1. Primary Request and Intent:
+ [Detailed description]
+2. Key Technical Concepts:
+ - [Concept 1]
+ - [Concept 2]
+ - [...]
+3. Files and Code Sections:
+ - [File Name 1]
+ - [Summary of why this file is important]
+ - [Summary of the changes made to this file, if any]
+ - [Important Code Snippet]
+ - [File Name 2]
+ - [Important Code Snippet]
+ - [...]
+4. Problem Solving:
+ [Description of solved problems and ongoing troubleshooting]
+5. Pending Tasks:
+ - [Task 1]
+ - [Task 2]
+ - [...]
+6. Current Work:
+ [Precise description of current work]
+7. Optional Next Step:
+ [Optional Next step to take]
+
+
+
+
+\n
+`
+
+export const continuationPrompt = (summaryText: string) => `
+This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:
+${summaryText}.
+
+Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on. Pay special attention to the most recent user message when responding rather than the initial task message, if applicable.
+If the most recent user's message starts with "/newtask", "/smol", "/compact", "/newrule", or "/reportbug", you should indicate to the user that they will need to run this command again.
+`
diff --git a/src/core/task/TaskState.ts b/src/core/task/TaskState.ts
index 15d31cd5..300b0c9d 100644
--- a/src/core/task/TaskState.ts
+++ b/src/core/task/TaskState.ts
@@ -52,4 +52,7 @@ export class TaskState {
abort: boolean = false
didFinishAbortingStream = false
abandoned = false
+
+ // Auto-context summarization
+ currentlySummarizing: boolean = false
}
diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts
index eeddea53..c800b57b 100644
--- a/src/core/task/ToolExecutor.ts
+++ b/src/core/task/ToolExecutor.ts
@@ -54,6 +54,7 @@ import { MessageStateHandler } from "./message-state"
import { AutoApprove } from "./tools/autoApprove"
import { showNotificationForApprovalIfAutoApprovalEnabled } from "./utils"
import { Mode } from "@shared/storage/types"
+import { continuationPrompt } from "../prompts/contextManagement"
export class ToolExecutor {
private autoApprover: AutoApprove
@@ -202,6 +203,8 @@ export class ToolExecutor {
return `[${block.name} for creating a new task]`
case "condense":
return `[${block.name}]`
+ case "summarize_task":
+ return `[${block.name}]`
case "report_bug":
return `[${block.name}]`
case "new_rule":
@@ -1645,6 +1648,63 @@ export class ToolExecutor {
break
}
}
+ case "summarize_task": {
+ const context: string | undefined = block.params.context
+ try {
+ if (block.partial) {
+ // Show streaming summary generation in tool UI
+ const partialMessage = JSON.stringify({
+ tool: "summarizeTask",
+ content: this.removeClosingTag(block, "context", context),
+ } satisfies ClineSayTool)
+
+ await this.say("tool", partialMessage, undefined, undefined, block.partial)
+ break
+ } else {
+ if (!context) {
+ this.taskState.consecutiveMistakeCount++
+ this.pushToolResult(await this.sayAndCreateMissingParamError("summarize_task", "context"), block)
+ await this.saveCheckpoint()
+ break
+ }
+ this.taskState.consecutiveMistakeCount = 0
+
+ // Show completed summary in tool UI
+ const completeMessage = JSON.stringify({
+ tool: "summarizeTask",
+ content: context,
+ } satisfies ClineSayTool)
+
+ await this.say("tool", completeMessage, undefined, undefined, false)
+
+ // Use the continuationPrompt to format the tool result
+ this.pushToolResult(formatResponse.toolResult(continuationPrompt(context)), block)
+
+ const apiConversationHistory = this.messageStateHandler.getApiConversationHistory()
+ const keepStrategy = "none"
+
+ // clear the context history at this point in time. note that this will not include the assistant message
+ // for summarizing, which we will need to delete later
+ this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
+ apiConversationHistory,
+ this.taskState.conversationHistoryDeletedRange,
+ keepStrategy,
+ )
+ await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
+ await this.contextManager.triggerApplyStandardContextTruncationNoticeChange(
+ Date.now(),
+ await ensureTaskDirectoryExists(this.context, this.taskId),
+ )
+ }
+ await this.saveCheckpoint()
+ this.taskState.currentlySummarizing = true
+ break
+ } catch (error) {
+ await this.handleError("summarizing context window", error, block)
+ await this.saveCheckpoint()
+ break
+ }
+ }
case "condense": {
const context: string | undefined = block.params.context
try {
diff --git a/src/core/task/index.ts b/src/core/task/index.ts
index 3f7f8bfa..26ac1160 100644
--- a/src/core/task/index.ts
+++ b/src/core/task/index.ts
@@ -80,6 +80,7 @@ import { showChangedFilesDiff } from "./multifile-diff"
import { TaskState } from "./TaskState"
import { ToolExecutor } from "./ToolExecutor"
import { updateApiReqMsg } from "./utils"
+import { summarizeTask } from "@core/prompts/contextManagement"
export type ToolResponse = string | Array
type UserContent = Array
@@ -2084,7 +2085,63 @@ export class Task {
// No explicit UI message here, error message will be in ExtensionState.
}
- const [parsedUserContent, environmentDetails, clinerulesError] = await this.loadContext(userContent, includeFileDetails)
+ // when we initially trigger the context cleanup, we will be increasing the context window size, so we need some state `currentlySummarizing`
+ // to store whether we have already started the context summarization flow, so we don't attempt to summarize again. additionally, immediately
+ // post summarizing we need to increment the conversationHistoryDeletedRange to mask out the summarization-trigger user & assistant response messaages
+ let shouldCompact = false
+ if (this.taskState.currentlySummarizing) {
+ this.taskState.currentlySummarizing = false
+
+ if (this.taskState.conversationHistoryDeletedRange) {
+ const [start, end] = this.taskState.conversationHistoryDeletedRange
+ const apiHistory = this.messageStateHandler.getApiConversationHistory()
+
+ // we want to increment the deleted range to remove the pre-summarization tool call output, with additional safety check
+ const safeEnd = Math.min(end + 2, apiHistory.length - 1)
+ if (end + 2 <= safeEnd) {
+ this.taskState.conversationHistoryDeletedRange = [start, end + 2]
+ await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
+ }
+ }
+ } else {
+ shouldCompact = this.contextManager.shouldCompactContextWindow(
+ this.messageStateHandler.getClineMessages(),
+ this.api,
+ previousApiReqIndex,
+ )
+
+ // There is an edge case where the summarize_task tool call completes but the user cancels the next request before it finishes
+ // this will result in this.taskState.currentlySummarizing being false, and we also failed to update the context window token
+ // estimate, which require a full new message to be completed along with gathering the latest usage block. A proxy for whether
+ // we just summarized would be to check the number of in-range messages, which itself has some extreme edge case (e.g. what if
+ // first+second user messages take up entire context-window, but in this case there's already an issue). TODO: Examine other
+ // approaches such as storing this.taskState.currentlySummarizing on disk in the clineMessages. This was intentionally not done
+ // for now to prevent additional disk from needing to be used.
+ // The worse case scenario is effectively cline summarizing a summary, which is bad UX, but doesn't break other logic.
+ if (shouldCompact && this.taskState.conversationHistoryDeletedRange) {
+ const apiHistory = this.messageStateHandler.getApiConversationHistory()
+ const activeMessageCount = apiHistory.length - this.taskState.conversationHistoryDeletedRange[1] - 1
+
+ // IMPORTANT - we didn't append this next user message yet so the last message in this array is an assistant message
+ // that's why we are comparing to an even number of messages (0, 2) rather than odd (1, 3)
+ if (activeMessageCount <= 2) {
+ shouldCompact = false
+ }
+ }
+ }
+
+ let parsedUserContent: UserContent
+ let environmentDetails: string
+ let clinerulesError: boolean
+
+ // when summarizing the context window, we do not want to inject updated to the context
+ if (shouldCompact) {
+ parsedUserContent = userContent
+ environmentDetails = ""
+ clinerulesError = false
+ } else {
+ ;[parsedUserContent, environmentDetails, clinerulesError] = await this.loadContext(userContent, includeFileDetails)
+ }
// error handling if the user uses the /newrule command & their .clinerules is a file, for file read operations didnt work properly
if (clinerulesError === true) {
@@ -2096,7 +2153,14 @@ export class Task {
userContent = parsedUserContent
// add environment details as its own text block, separate from tool results
- userContent.push({ type: "text", text: environmentDetails })
+ // do not add environment details to the message which we are compacting the context window
+ if (!shouldCompact) {
+ userContent.push({ type: "text", text: environmentDetails })
+ }
+
+ if (shouldCompact) {
+ userContent.push({ type: "text", text: summarizeTask() })
+ }
await this.messageStateHandler.addToApiConversationHistory({
role: "user",
diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts
index 60ff81ee..675f53c7 100644
--- a/src/shared/ExtensionMessage.ts
+++ b/src/shared/ExtensionMessage.ts
@@ -99,6 +99,7 @@ export type ClineAsk =
| "use_mcp_server"
| "new_task"
| "condense"
+ | "summarize_task"
| "report_bug"
export type ClineSay =
@@ -140,6 +141,7 @@ export interface ClineSayTool {
| "listCodeDefinitionNames"
| "searchFiles"
| "webFetch"
+ | "summarizeTask"
path?: string
diff?: string
content?: string
diff --git a/src/shared/proto-conversions/cline-message.ts b/src/shared/proto-conversions/cline-message.ts
index 12dd457d..eb8fed11 100644
--- a/src/shared/proto-conversions/cline-message.ts
+++ b/src/shared/proto-conversions/cline-message.ts
@@ -24,6 +24,7 @@ function convertClineAskToProtoEnum(ask: AppClineAsk | undefined): ClineAsk | un
use_mcp_server: ClineAsk.USE_MCP_SERVER,
new_task: ClineAsk.NEW_TASK,
condense: ClineAsk.CONDENSE,
+ summarize_task: ClineAsk.SUMMARIZE_TASK,
report_bug: ClineAsk.REPORT_BUG,
}
@@ -57,6 +58,7 @@ function convertProtoEnumToClineAsk(ask: ClineAsk): AppClineAsk | undefined {
[ClineAsk.USE_MCP_SERVER]: "use_mcp_server",
[ClineAsk.NEW_TASK]: "new_task",
[ClineAsk.CONDENSE]: "condense",
+ [ClineAsk.SUMMARIZE_TASK]: "summarize_task",
[ClineAsk.REPORT_BUG]: "report_bug",
}
diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx
index cff914c9..4a77432a 100644
--- a/webview-ui/src/components/chat/ChatRow.tsx
+++ b/webview-ui/src/components/chat/ChatRow.tsx
@@ -598,6 +598,81 @@ export const ChatRowContent = memo(
/>
>
)
+ case "summarizeTask":
+ return (
+ <>
+
+ {toolIcon("book")}
+ Cline is condensing the conversation:
+