Skip to content

Commit 204dd20

Browse files
authored
Merge pull request #385 from lessweb/improve-compact-robustness
fix(core): improve context compaction robustness
2 parents ca79ab5 + e27b3f0 commit 204dd20

11 files changed

Lines changed: 1227 additions & 348 deletions

File tree

‎docs/configuration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两
2828
| -------------------- | --------- | ------------------------------------------------------------------- |
2929
| `env` | object | 环境变量分组(见下方子字段表) |
3030
| `contextWindow` | number/string | 上下文窗口上限,可使用精确 token 数或 `128K`、`1M` 等格式 |
31-
| `autoCompactWindow` | number/string | 自动压缩阈值,默认取最终上下文窗口的 50% |
31+
| `autoCompactWindow` | number/string | 自动压缩阈值,默认取上下文窗口的 80% |
3232
| `model` | string | 模型名称。优先级高于 `env.MODEL` |
3333
| `thinkingEnabled` | boolean | 是否启用思考模式(DeepSeek V4 系列默认启用) |
3434
| `reasoningEffort` | string | 推理强度,可选 `"low"`、`"high"` 或 `"max"`(默认 `"max"`) |

‎docs/configuration_en.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ The following are all the top-level fields supported in `settings.json`, along w
2828
| ------------------ | ------- | --------------------------------------------------------------------------- |
2929
| `env` | object | Group of environment variables (see sub-field table below) |
3030
| `contextWindow` | number/string | Context-window limit as an exact token count or `128K`/`1M` value |
31-
| `autoCompactWindow` | number/string | Auto-compaction threshold; defaults to 50% of the final context window |
31+
| `autoCompactWindow` | number/string | Auto-compaction threshold; defaults to 80% of the context window |
3232
| `model` | string | Model name. Takes precedence over `env.MODEL` |
3333
| `thinkingEnabled` | boolean | Whether to enable thinking mode (enabled by default for DeepSeek V4 series)|
3434
| `reasoningEffort` | string | Reasoning intensity: `"low"`, `"high"`, or `"max"` (default `"max"`) |
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions";
2+
import type { SessionMessage } from "../session";
3+
4+
export type CompactBudget = {
5+
output: number;
6+
input: number;
7+
threshold: number;
8+
retain: number;
9+
};
10+
11+
export function compactBudget(window: number, configuredThreshold = Math.floor(window * 0.8)): CompactBudget {
12+
const output = Math.max(1, Math.min(65536, Math.floor(window / 8)));
13+
const input = window - output;
14+
const threshold = Math.min(configuredThreshold, input - output);
15+
if (threshold <= 0) throw new Error("The context window leaves no room for conversation input.");
16+
return { output, input, threshold, retain: Math.min(Math.floor(input * 0.16), Math.floor(threshold * 0.8)) };
17+
}
18+
19+
/** An estimate, not a tokenizer. Never charge binary image encodings as text. */
20+
export function estimateRequestTokens(messages: readonly ChatCompletionMessageParam[], tools: unknown = []): number {
21+
return messages.reduce((sum, message) => sum + 4 + estimateValue(message), estimateValue(tools));
22+
}
23+
24+
function estimateValue(value: unknown): number {
25+
if (typeof value === "string") {
26+
let tokens = 0;
27+
for (const char of value) tokens += /[\u3400-\u9fff\uf900-\ufaff]/u.test(char) ? 0.6 : 0.3;
28+
return Math.ceil(tokens);
29+
}
30+
if (Array.isArray(value)) return value.reduce((sum, item) => sum + estimateValue(item), 0);
31+
if (value && typeof value === "object") {
32+
const record = value as Record<string, unknown>;
33+
if (record.type === "image_url" || record.type === "file") {
34+
// Unknown model/image geometry: allow a conservative multi-tile visual budget.
35+
// Files here are uploaded images; their short file IDs do not reflect their cost.
36+
return (record.image_url as { detail?: string } | undefined)?.detail === "low" ? 85 : 4096;
37+
}
38+
return Object.entries(record).reduce((sum, [key, item]) => sum + estimateValue(key) + estimateValue(item), 0);
39+
}
40+
return value == null ? 0 : 1;
41+
}
42+
43+
export function isFixedContext(message: SessionMessage): boolean {
44+
return Boolean(message.meta?.skillCatalog) || (message.role === "system" && !message.meta?.isSummary);
45+
}
46+
47+
/** Eligible prefixes, longest first, with tool calls/results kept on the same side. */
48+
export function compactPrefixes(
49+
messages: SessionMessage[],
50+
prices: number[],
51+
retain: number
52+
): {
53+
history: SessionMessage[];
54+
ends: number[];
55+
} {
56+
const history = messages.filter((message) => !isFixedContext(message));
57+
if (history.length < 2) return { history, ends: [] };
58+
const priceById = new Map(messages.map((message, index) => [message.id, prices[index] ?? 0]));
59+
let keepFrom = history.length - 1;
60+
let tail = priceById.get(history[keepFrom].id) ?? 0;
61+
while (keepFrom > 0 && tail < retain) tail += priceById.get(history[--keepFrom].id) ?? 0;
62+
63+
const calls = new Map<string, number[]>();
64+
const edges: Array<[number, number]> = [];
65+
const pending = new Set<number>();
66+
const orphanResults = new Set<number>();
67+
history.forEach((message, index) => {
68+
// Once the conversation resumes, missing earlier results are replayed as interrupted.
69+
if (message.role === "user" || message.role === "assistant") pending.clear();
70+
const params = message.messageParams as { tool_calls?: Array<{ id?: string }>; tool_call_id?: string } | null;
71+
if (message.role === "assistant") {
72+
for (const call of params?.tool_calls ?? []) {
73+
if (!call.id) continue;
74+
calls.set(call.id, [...(calls.get(call.id) ?? []), index]);
75+
pending.add(index);
76+
}
77+
}
78+
if (message.role === "tool") {
79+
const candidates = calls.get(params?.tool_call_id ?? "");
80+
const from = candidates?.at(-1);
81+
if (from === undefined) orphanResults.add(index);
82+
else edges.push([from, index]);
83+
}
84+
});
85+
// Without a later conversation message, the trailing batch needs all of its results.
86+
for (const index of pending) {
87+
const params = history[index].messageParams as { tool_calls: Array<{ id?: string }> };
88+
if (
89+
params.tool_calls.every((call) =>
90+
history
91+
.slice(index + 1)
92+
.some(
93+
(message) =>
94+
message.role === "tool" &&
95+
(message.messageParams as { tool_call_id?: string } | null)?.tool_call_id === call.id
96+
)
97+
)
98+
)
99+
pending.delete(index);
100+
}
101+
const lastSummary = history.reduce((last, message, index) => (message.meta?.isSummary ? index : last), -1);
102+
const ends: number[] = [];
103+
for (let end = keepFrom; end > 0; end--) {
104+
if (end <= lastSummary || edges.some(([from, to]) => from < end && to >= end)) continue;
105+
if ([...pending, ...orphanResults].some((index) => index < end)) continue;
106+
ends.push(end);
107+
}
108+
return { history, ends };
109+
}
110+
111+
function errorRecord(error: unknown): Record<string, unknown> {
112+
return error && typeof error === "object" ? (error as Record<string, unknown>) : {};
113+
}
114+
115+
export function isContextOverflow(error: unknown): boolean {
116+
const outer = errorRecord(error);
117+
const inner = errorRecord(outer.error);
118+
const code = String(inner.code ?? outer.code ?? "");
119+
const message = String(inner.message ?? outer.message ?? "");
120+
if (outer.status != null && outer.status !== 400 && outer.status !== 413 && outer.status !== 422) return false;
121+
return (
122+
/^(context_length_exceeded|context_window_exceeded|max_context_length|CONTEXT_OVERFLOW)$/i.test(code) ||
123+
/(?:maximum context length|context (?:window|length).{0,40}(?:exceed|too (?:long|large))|(?:exceed|too many).{0,40}(?:context|input tokens))/i.test(
124+
message
125+
)
126+
);
127+
}
128+
129+
/** Only explicit image capacity failures authorize lossy image projection. */
130+
export function imageOffloadCount(error: unknown): number {
131+
const outer = errorRecord(error);
132+
const inner = errorRecord(outer.error);
133+
if (outer.status != null && outer.status !== 400 && outer.status !== 413 && outer.status !== 422) return 0;
134+
const code = String(inner.code ?? outer.code ?? "");
135+
const message = String(inner.message ?? outer.message ?? "");
136+
if (
137+
!/^(IMAGE_OFFLOAD_REQUIRED|too_many_images|image_limit_exceeded|image_token_limit_exceeded)$/i.test(code) &&
138+
!/(?:too many images|images?.{0,80}(?:exceed.{0,40}(?:limit|budget)|(?:token|count|number).{0,30}(?:limit|exceed)))/i.test(
139+
message
140+
)
141+
)
142+
return 0;
143+
const count = inner.offloadImages ?? outer.offloadImages;
144+
return typeof count === "number" && Number.isInteger(count) && count > 0 ? count : 1;
145+
}

‎packages/core/src/prompt.ts‎

Lines changed: 56 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -5,91 +5,59 @@ import * as path from "path";
55
import ejs from "ejs";
66
import matter from "gray-matter";
77
import { fileURLToPath } from "url";
8-
import type { SessionMessage } from "./session";
98
import { findGitBashPath, resolveShellPath } from "./common/shell-utils";
109
import { supportsMultimodal, type MultimodalMode } from "./common/model-capabilities";
1110

12-
const COMPACT_PROMPT_BASE = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
13-
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.
14-
15-
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
16-
17-
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
18-
- The user's explicit requests and intents
19-
- Your approach to addressing the user's requests
20-
- Key decisions, technical concepts and code patterns
21-
- Specific details like:
22-
- file names
23-
- full code snippets
24-
- function signatures
25-
- file edits
26-
- Errors that you ran into and how you fixed them
27-
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
28-
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
29-
30-
Your summary should include the following sections:
31-
32-
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
33-
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
34-
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.
35-
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
36-
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
37-
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
38-
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
39-
7. 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.
40-
8. 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 most recent 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 or really old requests that were already completed without confirming with the user first.
41-
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.
42-
43-
Here's an example of how your output should be structured:
44-
45-
<example>
46-
<analysis>
47-
[Your thought process, ensuring all points are covered thoroughly and accurately]
48-
</analysis>
49-
50-
<summary>
51-
1. Primary Request and Intent:
52-
[Detailed description]
53-
54-
2. Key Technical Concepts:
55-
- [Concept 1]
56-
- [Concept 2]
57-
- [...]
58-
59-
3. Files and Code Sections:
60-
- [File Name 1]
61-
- [Summary of why this file is important]
62-
- [Summary of the changes made to this file, if any]
63-
- [Important Code Snippet]
64-
- [File Name 2]
65-
- [Important Code Snippet]
66-
- [...]
67-
68-
4. Errors and fixes:
69-
- [Detailed description of error 1]:
70-
- [How you fixed the error]
71-
- [User feedback on the error if any]
72-
- [...]
73-
74-
5. Problem Solving:
75-
[Description of solved problems and ongoing troubleshooting]
76-
77-
6. All user messages:
78-
- [Detailed non tool use user message]
79-
- [...]
80-
81-
7. Pending Tasks:
82-
- [Task 1]
83-
- [Task 2]
84-
- [...]
85-
86-
8. Current Work:
87-
[Precise description of current work]
88-
89-
9. Optional Next Step:
90-
[Optional Next step to take]
91-
92-
</summary>`;
11+
const SUMMARY_OPEN_TAG = "<compacted-summary>";
12+
const SUMMARY_CLOSE_TAG = "</compacted-summary>";
13+
14+
/**
15+
* The summarization directive, delivered as the FINAL user message after the
16+
* replayed conversation rather than as a distinct summarizer system prompt.
17+
* Keeping the conversation's own system prompt, tools, and message prefix in
18+
* front of it makes the auxiliary call a genuine prefix of the last routed
19+
* request, so the provider's KV cache is reused instead of invalidated.
20+
*/
21+
export const COMPACTION_INSTRUCTION = [
22+
"You are now acting as a compaction engine for this AI coding assistant. Condense the conversation ABOVE into a structured checkpoint that lets another model resume the work with no loss of essential context.",
23+
"",
24+
'Output EXACTLY the Markdown structure below: keep every section, in order. Use terse bullets, not prose paragraphs. Write "(none)" for an empty section — never drop a section.',
25+
"",
26+
"## Primary Request and Intent",
27+
"- [the user's original and evolving goals; quote verbatim where the exact wording matters]",
28+
"",
29+
"## Key Technical Concepts",
30+
"- [technologies, frameworks, patterns, and conventions in play]",
31+
"",
32+
"## Files and Code",
33+
"- [exact path: why it matters, key changes or snippets]",
34+
"",
35+
"## Errors and Fixes",
36+
"- [error: how it was resolved, plus any related user feedback]",
37+
"",
38+
"## Pending Jobs",
39+
"- [explicitly requested work not yet completed]",
40+
"",
41+
"## Current Work",
42+
"- [precisely what was in progress at this checkpoint]",
43+
"",
44+
"## Next Step",
45+
'- [the single next action, directly in line with the most recent request, or "(none)"]',
46+
"",
47+
"## Critical Context",
48+
"- [decisions and their rationale, constraints, user preferences, open questions, data needed to continue]",
49+
"",
50+
"Rules:",
51+
"- Write concise English engineering prose. Preserve exact file paths, commands, error strings, identifiers, numeric values, function signatures, and syntax fragments.",
52+
"- Capture user feedback and explicit instructions faithfully, especially corrections.",
53+
"- Do NOT mention this summarization request or that the context was compacted.",
54+
"- Output only the checkpoint text: do not call any tool or take any other action.",
55+
`- If the conversation already contains a ${SUMMARY_OPEN_TAG} block, it is a PRIOR checkpoint. Do not copy it forward verbatim: preserve still-true facts, drop stale ones, and merge newer information into a single consolidated summary under the same structure.`,
56+
].join("\n");
57+
58+
/** Framing that makes the replacement user message established context. */
59+
export const CHECKPOINT_PREAMBLE =
60+
"This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.";
9361

9462
const SYSTEM_PROMPT_BASE = `You are a helpful software engineer assistant.`;
9563

@@ -293,20 +261,12 @@ export function getSystemPrompt(_projectRoot: string, options: PromptToolOptions
293261
return toolDocs ? `${SYSTEM_PROMPT_BASE}\n\n# Available Tools\n\n${toolDocs}` : SYSTEM_PROMPT_BASE;
294262
}
295263

296-
export function getCompactPrompt(sessionMessages: SessionMessage[]): string {
297-
const jsonl = sessionMessages
298-
.map((message) =>
299-
JSON.stringify({
300-
id: message.id,
301-
role: message.role,
302-
content: message.content,
303-
contentParams: message.contentParams,
304-
messageParams: message.messageParams,
305-
createTime: message.createTime,
306-
})
307-
)
308-
.join("\n");
309-
return `${COMPACT_PROMPT_BASE}\n\nconversation below:\n\n\`\`\`jsonl\n${jsonl}\n\`\`\``;
264+
export function getCompactPrompt(): string {
265+
return COMPACTION_INSTRUCTION;
266+
}
267+
268+
export function frameCompactSummary(summary: string): string {
269+
return `${CHECKPOINT_PREAMBLE}\n\n${SUMMARY_OPEN_TAG}\n${summary}\n${SUMMARY_CLOSE_TAG}`;
310270
}
311271

312272
export function getRuntimeContext(projectRoot: string, model?: string, addWorkingDirs: string[] = []): string {

0 commit comments

Comments
 (0)