From 54faddb3ff6d3af6eaffa76c4fa36ea65dc17139 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Tue, 19 Aug 2025 09:51:16 -0700 Subject: [PATCH] truncate first user message (#5668) --- .../context-management/ContextManager.ts | 50 +++++++++++++------ src/core/prompts/responses.ts | 13 ++++- src/core/task/ToolExecutor.ts | 2 + src/core/task/index.ts | 5 +- 4 files changed, 53 insertions(+), 17 deletions(-) diff --git a/src/core/context/context-management/ContextManager.ts b/src/core/context/context-management/ContextManager.ts index f516e6bd..a848bd64 100644 --- a/src/core/context/context-management/ContextManager.ts +++ b/src/core/context/context-management/ContextManager.ts @@ -399,14 +399,14 @@ export class ContextManager { * Public function for triggering potentially setting the truncation message * If the truncation message already exists, does nothing, otherwise adds the message */ - async triggerApplyStandardContextTruncationNoticeChange(timestamp: number, taskDirectory: string) { - /* - const assistantUpdated = this.applyStandardContextTruncationNoticeChange(timestamp) - const userUpdated = this.applyFirstUserMessageReplacement(timestamp) - if (assistantUpdated || userUpdated) - */ - const updated = this.applyStandardContextTruncationNoticeChange(timestamp) - if (updated) { + async triggerApplyStandardContextTruncationNoticeChange( + timestamp: number, + taskDirectory: string, + apiConversationHistory: Anthropic.Messages.MessageParam[], + ) { + const assistantUpdated = this.applyStandardContextTruncationNoticeChange(timestamp) + const userUpdated = this.applyFirstUserMessageReplacement(timestamp, apiConversationHistory) + if (assistantUpdated || userUpdated) { await this.saveContextHistory(taskDirectory) } } @@ -428,13 +428,35 @@ export class ContextManager { /** * Replace the first user message when context window is compacted */ - private applyFirstUserMessageReplacement(timestamp: number): boolean { + private applyFirstUserMessageReplacement( + timestamp: number, + apiConversationHistory: Anthropic.Messages.MessageParam[], + ): boolean { if (!this.contextHistoryUpdates.has(0)) { - // first user message always at index 0 - const innerMap = new Map() - innerMap.set(0, [[timestamp, "text", [formatResponse.contextTruncationFirstUserMessage()], []]]) - this.contextHistoryUpdates.set(0, [0, innerMap]) // same EditType as first assistant truncation notice - return true + try { + // choosing to be extra careful here, but likely not required + let firstUserMessage = "" + + const message = apiConversationHistory[0] + if (Array.isArray(message.content)) { + const block = message.content[0] + if (block && block.type === "text") { + firstUserMessage = block.text + } + } + + if (firstUserMessage) { + const processedFirstUserMessage = formatResponse.processFirstUserMessageForTruncation(firstUserMessage) + + const innerMap = new Map() + innerMap.set(0, [[timestamp, "text", [processedFirstUserMessage], []]]) + this.contextHistoryUpdates.set(0, [0, innerMap]) // same EditType as first assistant truncation notice + + return true + } + } catch (error) { + console.error("applyFirstUserMessageReplacement:", error) + } } return false } diff --git a/src/core/prompts/responses.ts b/src/core/prompts/responses.ts index 07d68d30..b812aa35 100644 --- a/src/core/prompts/responses.ts +++ b/src/core/prompts/responses.ts @@ -9,9 +9,18 @@ export const formatResponse = { `[[NOTE] This file read has been removed to save space in the context window. Refer to the latest file read for the most up to date version of this file.]`, contextTruncationNotice: () => - `[NOTE] Some previous conversation history with the user has been removed to maintain optimal context window length. The initial user task and the most recent exchanges have been retained for continuity, while intermediate conversation history has been removed. Please keep this in mind as you continue assisting the user.`, + `[NOTE] Some previous conversation history with the user has been removed to maintain optimal context window length. The initial user task has been retained for continuity, while intermediate conversation history has been removed. Please keep this in mind as you continue assisting the user.`, - contextTruncationFirstUserMessage: () => `It's time to build!`, + processFirstUserMessageForTruncation: (originalContent: string) => { + const MAX_CHARS = 400_000 + + if (originalContent.length <= MAX_CHARS) { + return originalContent + } + + const truncated = originalContent.substring(0, MAX_CHARS) + return truncated + "\n\n[[NOTE] This message was truncated past this point to preserve context window space.]" + }, condense: () => `The user has accepted the condensed conversation summary you generated. This summary covers important details of the historical conversation with the user which has been truncated.\nIt's crucial that you respond by ONLY asking the user what you should work on next. You should NOT take any initiative or make any assumptions about continuing with work. For example you should NOT suggest file changes or attempt to read any files.\nWhen asking the user what you should work on next, you can reference information in the summary which was just generated. However, you should NOT reference information outside of what's contained in the summary for this response. Keep this response CONCISE.`, diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 9e929971..54038706 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -1724,6 +1724,7 @@ export class ToolExecutor { await this.contextManager.triggerApplyStandardContextTruncationNoticeChange( Date.now(), await ensureTaskDirectoryExists(this.context, this.taskId), + apiConversationHistory, ) } await this.saveCheckpoint() @@ -1812,6 +1813,7 @@ export class ToolExecutor { await this.contextManager.triggerApplyStandardContextTruncationNoticeChange( Date.now(), await ensureTaskDirectoryExists(this.context, this.taskId), + apiConversationHistory, ) } await this.saveCheckpoint() diff --git a/src/core/task/index.ts b/src/core/task/index.ts index c26d54f3..361b11cd 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -1622,8 +1622,10 @@ export class Task { } private async handleContextWindowExceededError(): Promise { + const apiConversationHistory = this.messageStateHandler.getApiConversationHistory() + this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange( - this.messageStateHandler.getApiConversationHistory(), + apiConversationHistory, this.taskState.conversationHistoryDeletedRange, "quarter", // Force aggressive truncation ) @@ -1631,6 +1633,7 @@ export class Task { await this.contextManager.triggerApplyStandardContextTruncationNoticeChange( Date.now(), await ensureTaskDirectoryExists(this.getContext(), this.taskId), + apiConversationHistory, ) this.taskState.didAutomaticallyRetryFailedApiRequest = true