zapagent 1.14.10 → 1.14.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/App.tsx +10 -4
- package/src/agent/buildAgentRuntime.ts +3 -0
- package/src/agent/cacheMemoryAudit.ts +56 -1
- package/src/agent/wireRunHandlers.ts +17 -10
- package/src/commands/dispatcher.ts +14 -10
- package/src/commands/status.ts +10 -0
- package/src/config.ts +10 -17
- package/src/context-budget.ts +3 -10
- package/src/headless/runHeadless.ts +3 -0
- package/src/hooks/useAgentRunner.ts +3 -92
- package/src/provider-catalog.ts +34 -3
- package/src/provider-metadata.ts +20 -9
- package/src/ui/dialog-connect.tsx +19 -10
- package/src/ui/dialog-context-window.tsx +42 -0
- package/src/ui/dialog-model-metadata.tsx +57 -0
- package/src/ui/dialog-model.tsx +30 -7
- package/src/ui/provider-directory.tsx +5 -5
- package/zapsdk/agent/events.ts +4 -0
- package/zapsdk/agent/loop.ts +153 -34
- package/zapsdk/agent/subagent-assembly.ts +3 -0
- package/zapsdk/builtin-tools/subagent.ts +6 -0
- package/zapsdk/context/autocompact.ts +17 -460
- package/zapsdk/context/compact-budget.ts +30 -0
- package/zapsdk/context/compact-summary.ts +336 -0
- package/zapsdk/context/compact.ts +290 -0
- package/zapsdk/context/microcompact.ts +1 -1
- package/zapsdk/context/prune.ts +106 -0
- package/zapsdk/context/reactive-compact.ts +44 -11
- package/zapsdk/context/request-cache.ts +76 -0
- package/zapsdk/core/llm.ts +3 -0
- package/zapsdk/core/provider-request.ts +11 -1
- package/zapsdk/core/providers/anthropic.ts +4 -2
- package/zapsdk/core/providers/openai-compatible.ts +4 -2
- package/zapsdk/core/providers/openai-responses.ts +2 -2
- package/zapsdk/index.ts +3 -0
- package/zapsdk/memory/conversation.ts +81 -92
|
@@ -1,475 +1,32 @@
|
|
|
1
1
|
import type { LLMProvider, LLMCallOptions } from "../core/llm.js";
|
|
2
|
-
import { assertProviderRequestAllowed } from "../core/provider-deadline.js";
|
|
3
2
|
import type { Message } from "../core/types.js";
|
|
4
|
-
import { createSystemMessage, createUserMessage } from "../core/types.js";
|
|
5
|
-
import { redactJsonSecrets, redactTextSecrets } from "../utils/redact.js";
|
|
6
|
-
import { countCodePoints, sliceHeadCodePoints, sliceTailCodePoints, splitLogicalLines } from "../utils/logical-lines.js";
|
|
7
3
|
import { TokenCounter } from "./token-counter.js";
|
|
4
|
+
import { executeCompact, type CompactOptions, type CompactResult } from "./compact.js";
|
|
5
|
+
import type { AutoCompactOptions } from "./compact-summary.js";
|
|
6
|
+
export * from "./compact-summary.js";
|
|
8
7
|
|
|
9
|
-
/**
|
|
10
|
-
* Structured compaction prompt — required sections plus `<analysis>` scratchpad.
|
|
11
|
-
*
|
|
12
|
-
* A single-sentence "summarize this" prompt produces vague prose that loses
|
|
13
|
-
* the information the next turn actually needs: what the task is, what was
|
|
14
|
-
* tried, which files changed, what's pending. This template (ported from
|
|
15
|
-
* Claude Code's `getCompactPrompt`, trimmed for zap's scope) forces the
|
|
16
|
-
* summarizer to enumerate the operationally useful facts.
|
|
17
|
-
*
|
|
18
|
-
* Sections intentionally overlap (tasks / current-work / files-changed)
|
|
19
|
-
* because each foregrounds a different axis — an LLM reading the summary
|
|
20
|
-
* to resume work should find whichever angle it's looking for without
|
|
21
|
-
* having to re-derive.
|
|
22
|
-
*/
|
|
23
|
-
export const STRUCTURED_COMPACT_PROMPT = `You are compacting a coding-agent conversation for context-window reasons. The next turn of the agent will resume from your summary alone, so DON'T omit actionable detail. Produce your summary using the exact sections below. Keep each section tight — facts, no filler.
|
|
24
|
-
|
|
25
|
-
<analysis>
|
|
26
|
-
Briefly reason about what the user's overall goal was, what progress was made, and what remains. This scratchpad lets you plan the summary; users never see it.
|
|
27
|
-
</analysis>
|
|
28
|
-
|
|
29
|
-
# Primary Request and Intent
|
|
30
|
-
The user's actual requests, goals, and intent — in their own framing, not paraphrased into agent-speak. If the user changed direction mid-session, note each intent with its trigger turn.
|
|
31
|
-
|
|
32
|
-
# All user messages (verbatim)
|
|
33
|
-
Every non-tool-result user message, preserved verbatim when short. For long user messages, keep opening + closing intact and elide only the middle. Critically: preserve any shorthand or labels the user introduces (e.g. "P1", "the auth bug", "option A", file/path references) EXACTLY as written — future turns refer back to these by nickname. If a prior agent response defined such a label (e.g. "P1 = items 4-7: ScrollBox, Textarea, Select, truecolor"), include that label→value mapping right after the user message that first used it.
|
|
34
|
-
|
|
35
|
-
# Current task status
|
|
36
|
-
What is the agent working on right now? What was the last concrete step? Is a tool call in flight or a decision pending?
|
|
37
|
-
|
|
38
|
-
# Files read / modified
|
|
39
|
-
Bulleted list. For each: path + a ≤ 120-char description of what was inspected or changed. Include exact paths, not paraphrases.
|
|
40
|
-
|
|
41
|
-
# Commands run
|
|
42
|
-
Bulleted list of non-trivial shell / bash invocations and their outcome (success / what it revealed / what failed).
|
|
43
|
-
|
|
44
|
-
# Key facts discovered
|
|
45
|
-
Findings from web searches, file inspection, test output, etc. Bullet list.
|
|
46
|
-
|
|
47
|
-
# Decisions made
|
|
48
|
-
Choices that the agent or user committed to that future-you needs to honor. E.g. "use jsdiff not myers", "write to docs/specs/…, not docs/".
|
|
49
|
-
|
|
50
|
-
# Errors encountered and their resolution
|
|
51
|
-
Any error messages + what fixed them (or that they're still blocking). Include user feedback on attempted fixes — that's where the best corrections come from.
|
|
52
|
-
|
|
53
|
-
# Code changes summary
|
|
54
|
-
If files were edited or written, describe the change semantically (not diff-verbatim). One bullet per file.
|
|
55
|
-
|
|
56
|
-
# Next steps
|
|
57
|
-
What the agent was about to do when compaction happened. Bullet list, imperative form. If possible, include a direct quote from the most recent user message to anchor the next step to the user's actual framing.
|
|
58
|
-
|
|
59
|
-
Output the summary as plain markdown with these section headers. Do not wrap in \`\`\` fences. Do not prefix with "Summary:" or similar.`;
|
|
60
|
-
|
|
61
|
-
export const REPAIR_COMPACT_SUMMARY_PROMPT = `You are repairing a failed coding-agent compact summary. Rewrite the prior summary so it follows the exact required section contract. Use the original compact input as the source of truth. Preserve actionable details and user wording where possible. If a required section has no evidence, write "_(none captured)_" instead of leaving it empty.
|
|
62
|
-
|
|
63
|
-
Required sections, in this exact order:
|
|
64
|
-
# Primary Request and Intent
|
|
65
|
-
# All user messages (verbatim)
|
|
66
|
-
# Current task status
|
|
67
|
-
# Files read / modified
|
|
68
|
-
# Commands run
|
|
69
|
-
# Key facts discovered
|
|
70
|
-
# Decisions made
|
|
71
|
-
# Errors encountered and their resolution
|
|
72
|
-
# Code changes summary
|
|
73
|
-
# Next steps
|
|
74
|
-
|
|
75
|
-
Output only the repaired markdown summary. Do not wrap it in code fences.`;
|
|
76
|
-
|
|
77
|
-
export interface AutoCompactOptions {
|
|
78
|
-
/**
|
|
79
|
-
* Rough character-count threshold for triggering compaction.
|
|
80
|
-
* 1 token ≈ 4 chars, so the default 320_000 chars ≈ 80k tokens.
|
|
81
|
-
*/
|
|
82
|
-
charThreshold?: number;
|
|
83
|
-
/** Number of most-recent messages to keep verbatim after compaction (default: 10) */
|
|
84
|
-
keepRecent?: number;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** Head + tail preview for long strings. Prior code took only `slice(0, N)`,
|
|
88
|
-
* which drops the tail of tool_results where error/exit-code/summary live.
|
|
89
|
-
* Keeping both ends preserves the decisive information at both boundaries. */
|
|
90
|
-
export function headTailPreview(content: string, maxChars: number): string {
|
|
91
|
-
const limit = Number.isFinite(maxChars) ? Math.max(0, Math.floor(maxChars)) : 0;
|
|
92
|
-
const totalChars = countCodePoints(content);
|
|
93
|
-
if (totalChars <= limit) return content;
|
|
94
|
-
const half = Math.max(0, Math.floor(limit / 2) - 30);
|
|
95
|
-
const head = sliceHeadCodePoints(content, half);
|
|
96
|
-
const tail = sliceTailCodePoints(content, half);
|
|
97
|
-
const elidedChars = Math.max(0, totalChars - countCodePoints(head) - countCodePoints(tail));
|
|
98
|
-
return (
|
|
99
|
-
head +
|
|
100
|
-
`\n…[${elidedChars} chars elided]…\n` +
|
|
101
|
-
tail
|
|
102
|
-
);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** Role-aware preview used when feeding a conversation to the compaction
|
|
106
|
-
* summarizer.
|
|
107
|
-
*
|
|
108
|
-
* tool_result content is dense with noise (file bodies, search hits) and
|
|
109
|
-
* the decisive signal lives at the boundaries — command name/args at the
|
|
110
|
-
* head, exit code / error / summary at the tail. Aggressive 2000-char
|
|
111
|
-
* head+tail is fine.
|
|
112
|
-
*
|
|
113
|
-
* assistant / user narratives are the opposite: structured lists,
|
|
114
|
-
* numbered plans, and user-introduced shorthand typically live in the
|
|
115
|
-
* middle of longer turns. Truncating to 2000 chars silently drops those
|
|
116
|
-
* definitions, which breaks later references (e.g. user says "fix P1"
|
|
117
|
-
* after the agent defined P0-P3 mid-turn). Give narrative messages a
|
|
118
|
-
* larger budget — they're rarer than tool_result so the total input
|
|
119
|
-
* stays manageable even at 3× the cap. */
|
|
120
|
-
export function previewMessageForCompact(
|
|
121
|
-
role: string,
|
|
122
|
-
content: string,
|
|
123
|
-
): string {
|
|
124
|
-
const cap = role === "tool_result" ? 2000 : 6000;
|
|
125
|
-
return headTailPreview(redactTextSecrets(content), cap);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function previewHistoryMessage(message: Message): string {
|
|
129
|
-
const parts = [`[${message.role}]: ${previewMessageForCompact(message.role, message.content)}`];
|
|
130
|
-
if (message.role === "assistant" && message.toolCalls?.length) {
|
|
131
|
-
// Tool-only turns often have no prose. Preserve the invocation evidence
|
|
132
|
-
// alongside its results, without copying opaque provider replay fields.
|
|
133
|
-
let calls: string;
|
|
134
|
-
try {
|
|
135
|
-
calls = JSON.stringify(message.toolCalls.map(({ id, name, arguments: args }) => ({
|
|
136
|
-
id, name, arguments: args,
|
|
137
|
-
})), redactJsonSecrets);
|
|
138
|
-
} catch {
|
|
139
|
-
calls = JSON.stringify(message.toolCalls.map(({ id, name }) => ({
|
|
140
|
-
id, name, arguments: "[unserializable arguments]",
|
|
141
|
-
})));
|
|
142
|
-
}
|
|
143
|
-
parts.push(`[tool_calls]: ${previewMessageForCompact("assistant", calls)}`);
|
|
144
|
-
}
|
|
145
|
-
if (message.role === "tool_result" && message.toolCallId) {
|
|
146
|
-
parts.unshift(`[tool_result reference]: ${previewMessageForCompact("tool_result", JSON.stringify({ id: message.toolCallId }))}`);
|
|
147
|
-
}
|
|
148
|
-
return parts.join("\n");
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** Remove the prompt's private scratchpad from a compaction response before
|
|
152
|
-
* it enters persistent conversation history. The compact prompt explicitly
|
|
153
|
-
* tells the summarizer that `<analysis>` is for planning and users never see
|
|
154
|
-
* it; persisting it would leak low-quality reasoning into future turns. */
|
|
155
|
-
export function sanitizeCompactSummary(text: string): string {
|
|
156
|
-
return redactTextSecrets(text)
|
|
157
|
-
.replace(/<analysis\b[^>]*>[\s\S]*?(?:<\/analysis>|$)/gi, "")
|
|
158
|
-
.replace(/<\/analysis>/gi, "")
|
|
159
|
-
.trim();
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
export const REQUIRED_COMPACT_SUMMARY_HEADINGS = [
|
|
163
|
-
"Primary Request and Intent",
|
|
164
|
-
"All user messages (verbatim)",
|
|
165
|
-
"Current task status",
|
|
166
|
-
"Files read / modified",
|
|
167
|
-
"Commands run",
|
|
168
|
-
"Key facts discovered",
|
|
169
|
-
"Decisions made",
|
|
170
|
-
"Errors encountered and their resolution",
|
|
171
|
-
"Code changes summary",
|
|
172
|
-
"Next steps",
|
|
173
|
-
] as const;
|
|
174
|
-
|
|
175
|
-
const COMPACT_HEADING_ALIASES = new Map<string, string>(
|
|
176
|
-
[
|
|
177
|
-
["主要请求和意图", "Primary Request and Intent"],
|
|
178
|
-
["主要请求与意图", "Primary Request and Intent"],
|
|
179
|
-
["请求和意图", "Primary Request and Intent"],
|
|
180
|
-
["请求与意图", "Primary Request and Intent"],
|
|
181
|
-
["所有用户消息", "All user messages (verbatim)"],
|
|
182
|
-
["所有用户消息(原文)", "All user messages (verbatim)"],
|
|
183
|
-
["所有用户消息(原文)", "All user messages (verbatim)"],
|
|
184
|
-
["用户消息", "All user messages (verbatim)"],
|
|
185
|
-
["用户消息(原文)", "All user messages (verbatim)"],
|
|
186
|
-
["用户消息(原文)", "All user messages (verbatim)"],
|
|
187
|
-
["user messages", "All user messages (verbatim)"],
|
|
188
|
-
["user messages verbatim", "All user messages (verbatim)"],
|
|
189
|
-
["当前任务状态", "Current task status"],
|
|
190
|
-
["当前状态", "Current task status"],
|
|
191
|
-
["任务状态", "Current task status"],
|
|
192
|
-
["读取 / 修改的文件", "Files read / modified"],
|
|
193
|
-
["读取/修改的文件", "Files read / modified"],
|
|
194
|
-
["已读 / 修改文件", "Files read / modified"],
|
|
195
|
-
["已读/修改文件", "Files read / modified"],
|
|
196
|
-
["文件读写", "Files read / modified"],
|
|
197
|
-
["文件读取和修改", "Files read / modified"],
|
|
198
|
-
["文件读取与修改", "Files read / modified"],
|
|
199
|
-
["运行的命令", "Commands run"],
|
|
200
|
-
["执行的命令", "Commands run"],
|
|
201
|
-
["命令", "Commands run"],
|
|
202
|
-
["发现的关键事实", "Key facts discovered"],
|
|
203
|
-
["关键事实", "Key facts discovered"],
|
|
204
|
-
["关键发现", "Key facts discovered"],
|
|
205
|
-
["已做决定", "Decisions made"],
|
|
206
|
-
["做出的决定", "Decisions made"],
|
|
207
|
-
["决策", "Decisions made"],
|
|
208
|
-
["决定", "Decisions made"],
|
|
209
|
-
["遇到的错误及解决", "Errors encountered and their resolution"],
|
|
210
|
-
["遇到的错误和解决", "Errors encountered and their resolution"],
|
|
211
|
-
["错误及解决", "Errors encountered and their resolution"],
|
|
212
|
-
["错误和解决", "Errors encountered and their resolution"],
|
|
213
|
-
["错误及其解决", "Errors encountered and their resolution"],
|
|
214
|
-
["errors encountered and resolution", "Errors encountered and their resolution"],
|
|
215
|
-
["代码变更摘要", "Code changes summary"],
|
|
216
|
-
["代码修改摘要", "Code changes summary"],
|
|
217
|
-
["代码更改摘要", "Code changes summary"],
|
|
218
|
-
["变更摘要", "Code changes summary"],
|
|
219
|
-
["下一步", "Next steps"],
|
|
220
|
-
["后续步骤", "Next steps"],
|
|
221
|
-
["接下来的步骤", "Next steps"],
|
|
222
|
-
].map(([alias, canonical]) => [normalizeHeadingText(alias), normalizeHeadingText(canonical)]),
|
|
223
|
-
);
|
|
224
|
-
|
|
225
|
-
export interface CompactSummaryQuality {
|
|
226
|
-
ok: boolean;
|
|
227
|
-
missingHeadings: string[];
|
|
228
|
-
emptyHeadings: string[];
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/** Validate that a model followed the structured compaction contract. A short
|
|
232
|
-
* prose summary is worse than no compact: it frees tokens by discarding the
|
|
233
|
-
* exact operational anchors the next turn needs. */
|
|
234
|
-
export function validateCompactSummary(summary: string): CompactSummaryQuality {
|
|
235
|
-
const sections = new Map<string, string[]>();
|
|
236
|
-
let currentHeading: string | null = null;
|
|
237
|
-
for (const line of splitLogicalLines(summary)) {
|
|
238
|
-
const match = line.match(/^#{1,3}\s+(.+?)\s*$/);
|
|
239
|
-
if (match) {
|
|
240
|
-
const heading = normalizeCompactHeadingTitle(match[1]);
|
|
241
|
-
if (!sections.has(heading)) sections.set(heading, []);
|
|
242
|
-
currentHeading = heading;
|
|
243
|
-
continue;
|
|
244
|
-
}
|
|
245
|
-
if (currentHeading) sections.get(currentHeading)?.push(line);
|
|
246
|
-
}
|
|
247
|
-
const missingHeadings = REQUIRED_COMPACT_SUMMARY_HEADINGS
|
|
248
|
-
.filter((heading) => !sections.has(normalizeCompactHeadingTitle(heading)));
|
|
249
|
-
const emptyHeadings = REQUIRED_COMPACT_SUMMARY_HEADINGS
|
|
250
|
-
.filter((heading) => {
|
|
251
|
-
if (missingHeadings.includes(heading)) return false;
|
|
252
|
-
const body = sections.get(normalizeCompactHeadingTitle(heading)) ?? [];
|
|
253
|
-
return body.join("\n").trim().length === 0;
|
|
254
|
-
});
|
|
255
|
-
return {
|
|
256
|
-
ok: missingHeadings.length === 0 && emptyHeadings.length === 0,
|
|
257
|
-
missingHeadings,
|
|
258
|
-
emptyHeadings,
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
export function isUsableCompactSummary(summary: string): boolean {
|
|
263
|
-
return summary.trim().length > 0 && validateCompactSummary(summary).ok;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
export function compactSummaryFailureReason(summary: string): string | null {
|
|
267
|
-
if (!summary.trim()) return "summarizer returned an empty compact summary";
|
|
268
|
-
const quality = validateCompactSummary(summary);
|
|
269
|
-
if (quality.ok) return null;
|
|
270
|
-
const parts: string[] = [];
|
|
271
|
-
if (quality.missingHeadings.length > 0) {
|
|
272
|
-
parts.push(`missing required sections: ${formatHeadingList(quality.missingHeadings)}`);
|
|
273
|
-
}
|
|
274
|
-
if (quality.emptyHeadings.length > 0) {
|
|
275
|
-
parts.push(`empty required sections: ${formatHeadingList(quality.emptyHeadings)}`);
|
|
276
|
-
}
|
|
277
|
-
return `summarizer returned an unusable compact summary (${parts.join("; ")})`;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
function formatHeadingList(headings: string[]): string {
|
|
281
|
-
return headings.slice(0, 3).join(", ") + (headings.length > 3 ? `, +${headings.length - 3} more` : "");
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
export function normalizeCompactHeadingTitle(value: string): string {
|
|
285
|
-
const normalized = normalizeHeadingText(value);
|
|
286
|
-
return COMPACT_HEADING_ALIASES.get(normalized) ?? normalized;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function normalizeHeadingText(value: string): string {
|
|
290
|
-
return value
|
|
291
|
-
.trim()
|
|
292
|
-
.replace(/[::]\s*$/u, "")
|
|
293
|
-
.trim()
|
|
294
|
-
.replace(/^\*{1,3}(.+?)\*{1,3}$/u, "$1")
|
|
295
|
-
.replace(/^_{1,3}(.+?)_{1,3}$/u, "$1")
|
|
296
|
-
.replace(/[::]\s*$/u, "")
|
|
297
|
-
.trim()
|
|
298
|
-
.replace(/\s*\/\s*/g, " / ")
|
|
299
|
-
.replace(/\s+/g, " ")
|
|
300
|
-
.toLowerCase();
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function leadingSystemMessageCount(messages: Message[]): number {
|
|
304
|
-
let count = 0;
|
|
305
|
-
while (messages[count]?.role === "system") count++;
|
|
306
|
-
return count;
|
|
307
|
-
}
|
|
308
|
-
|
|
8
|
+
/** Compatibility wrapper. Budgeted hosts share the same planner as /compact. */
|
|
309
9
|
export class AutoCompact {
|
|
310
|
-
private charThreshold: number;
|
|
311
|
-
private keepRecent: number;
|
|
312
10
|
private readonly counter = new TokenCounter();
|
|
313
|
-
|
|
314
|
-
constructor(options: AutoCompactOptions = {}) {
|
|
315
|
-
this.charThreshold = options.charThreshold ?? 320_000;
|
|
316
|
-
this.keepRecent = options.keepRecent ?? 10;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/** Total character count across all messages */
|
|
11
|
+
constructor(private readonly options: AutoCompactOptions = {}) {}
|
|
320
12
|
totalChars(messages: Message[]): number {
|
|
321
13
|
return messages.reduce((sum, message) => sum + this.counter.countMessageChars(message), 0);
|
|
322
14
|
}
|
|
323
|
-
|
|
324
15
|
shouldCompact(messages: Message[]): boolean {
|
|
325
|
-
return this.totalChars(messages) > this.charThreshold;
|
|
16
|
+
return this.totalChars(messages) > (this.options.charThreshold ?? 320_000);
|
|
326
17
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
* Compact by LLM summarization.
|
|
330
|
-
* Keeps leading system messages + last keepRecent messages verbatim.
|
|
331
|
-
* The tail boundary is adjusted to never start on a tool_result message —
|
|
332
|
-
* doing so would orphan its tool_use (in the compacted middle) and cause API errors.
|
|
333
|
-
* Summarizes everything in between via an LLM call.
|
|
334
|
-
* If summarization fails or violates the structured-summary contract, leaves
|
|
335
|
-
* messages unchanged and returns an empty summary so callers can surface a
|
|
336
|
-
* failed compaction instead of persisting a low-information placeholder.
|
|
337
|
-
*/
|
|
338
|
-
async compact(
|
|
339
|
-
messages: Message[],
|
|
340
|
-
provider: LLMProvider,
|
|
341
|
-
options: Pick<LLMCallOptions, "signal" | "deadline"> = {},
|
|
342
|
-
): Promise<{ messages: Message[]; summary: string; failureReason?: string }> {
|
|
343
|
-
const systemLen = leadingSystemMessageCount(messages);
|
|
344
|
-
const systemMsgs = messages.slice(0, systemLen);
|
|
345
|
-
|
|
346
|
-
// Tail boundary picked by TWO bounds — whichever is more aggressive:
|
|
347
|
-
// 1. Count-based: keep at most keepRecent messages (legacy behaviour).
|
|
348
|
-
// 2. Char-based: keep messages whose combined content fits in half
|
|
349
|
-
// the charThreshold. Catches the "few but huge messages" case
|
|
350
|
-
// (e.g. user inlined a 1600-line file via @-ref). Without the
|
|
351
|
-
// char bound, 10 × 16k-token messages = 160k total but each fits
|
|
352
|
-
// under keepRecent=10, so middle is empty and compact no-ops.
|
|
353
|
-
const countTail = Math.max(systemLen, messages.length - this.keepRecent);
|
|
354
|
-
const tailBudget = Math.floor(this.charThreshold / 2);
|
|
355
|
-
let charTail = messages.length;
|
|
356
|
-
let charsSoFar = 0;
|
|
357
|
-
while (charTail > systemLen + 1) {
|
|
358
|
-
const m = messages[charTail - 1];
|
|
359
|
-
const len = m ? this.counter.countMessageChars(m) : 0;
|
|
360
|
-
if (charsSoFar + len > tailBudget && charTail < messages.length) break;
|
|
361
|
-
charsSoFar += len;
|
|
362
|
-
charTail--;
|
|
363
|
-
}
|
|
364
|
-
let tailStart = Math.max(countTail, charTail);
|
|
365
|
-
// Safety net: even after both bounds, if the conversation is non-
|
|
366
|
-
// trivially long but middle would still be empty, force AT LEAST one
|
|
367
|
-
// non-system message into the summary. Otherwise we'd just no-op and
|
|
368
|
-
// the autocompact trigger keeps firing on every subsequent step.
|
|
369
|
-
if (tailStart === systemLen && messages.length - systemLen > 1) {
|
|
370
|
-
tailStart = systemLen + 1;
|
|
371
|
-
}
|
|
372
|
-
// Find a safe tail boundary: never start on a tool_result, because its
|
|
373
|
-
// matching tool_use would be in the compacted portion, causing an API error.
|
|
374
|
-
while (tailStart > systemLen && messages[tailStart]?.role === "tool_result") {
|
|
375
|
-
tailStart--;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
const tail = messages.slice(tailStart);
|
|
379
|
-
const middle = messages.slice(systemLen, tailStart);
|
|
380
|
-
|
|
381
|
-
if (middle.length === 0) {
|
|
382
|
-
// Genuinely nothing to compact — system-only message or single non-
|
|
383
|
-
// system turn that can't be safely split. Return an explicit "no-op"
|
|
384
|
-
// sentinel so the caller can surface useful UI ("compact had no
|
|
385
|
-
// effect, free space manually") instead of pretending it worked.
|
|
386
|
-
return { messages, summary: "" };
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
const historyText = middle.map(previewHistoryMessage).join("\n\n");
|
|
390
|
-
|
|
391
|
-
let summary = "";
|
|
18
|
+
async compact(messages: Message[], provider: LLMProvider,
|
|
19
|
+
callOptions: Pick<LLMCallOptions, "signal" | "deadline"> = {}, options: CompactOptions = {}): Promise<CompactResult> {
|
|
392
20
|
try {
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
summary = sanitizeCompactSummary(response.text);
|
|
403
|
-
} catch (err) {
|
|
404
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
405
|
-
return { messages, summary: "", failureReason: `summarizer failed: ${message}` };
|
|
21
|
+
return await executeCompact(messages, provider, { ...options,
|
|
22
|
+
legacyKeepRecent: this.options.keepRecent ?? 10,
|
|
23
|
+
legacyCharThreshold: this.options.charThreshold ?? 320_000,
|
|
24
|
+
...callOptions,
|
|
25
|
+
});
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (callOptions.signal?.aborted && options.contextWindow !== undefined) throw error;
|
|
28
|
+
return { messages, summary: "", status: "failed",
|
|
29
|
+
failureReason: `summarizer failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
406
30
|
}
|
|
407
|
-
|
|
408
|
-
const failureReason = compactSummaryFailureReason(summary);
|
|
409
|
-
if (failureReason) {
|
|
410
|
-
const repaired = await repairCompactSummary(provider, historyText, summary, failureReason, options);
|
|
411
|
-
if (!repaired.ok) {
|
|
412
|
-
return { messages, summary: "", failureReason: repaired.failureReason };
|
|
413
|
-
}
|
|
414
|
-
summary = repaired.summary;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
const summaryMsg = createUserMessage(
|
|
418
|
-
`[Context compacted — ${middle.length} earlier messages summarized]\n${summary}`
|
|
419
|
-
);
|
|
420
|
-
|
|
421
|
-
return {
|
|
422
|
-
messages: [...systemMsgs, summaryMsg, ...tail],
|
|
423
|
-
summary,
|
|
424
|
-
};
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
async function repairCompactSummary(
|
|
429
|
-
provider: LLMProvider,
|
|
430
|
-
historyText: string,
|
|
431
|
-
invalidSummary: string,
|
|
432
|
-
failureReason: string,
|
|
433
|
-
options: Pick<LLMCallOptions, "signal" | "deadline">,
|
|
434
|
-
): Promise<
|
|
435
|
-
| { ok: true; summary: string }
|
|
436
|
-
| { ok: false; failureReason: string }
|
|
437
|
-
> {
|
|
438
|
-
let summary = "";
|
|
439
|
-
try {
|
|
440
|
-
assertProviderRequestAllowed(options);
|
|
441
|
-
const response = await provider.call(
|
|
442
|
-
[
|
|
443
|
-
createSystemMessage(REPAIR_COMPACT_SUMMARY_PROMPT),
|
|
444
|
-
createUserMessage([
|
|
445
|
-
"The previous compact summary failed validation:",
|
|
446
|
-
failureReason,
|
|
447
|
-
"",
|
|
448
|
-
"Original compact input:",
|
|
449
|
-
historyText,
|
|
450
|
-
"",
|
|
451
|
-
"Previous invalid summary:",
|
|
452
|
-
invalidSummary || "_(empty)_",
|
|
453
|
-
].join("\n")),
|
|
454
|
-
],
|
|
455
|
-
[],
|
|
456
|
-
options,
|
|
457
|
-
);
|
|
458
|
-
summary = sanitizeCompactSummary(response.text);
|
|
459
|
-
} catch (err) {
|
|
460
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
461
|
-
return {
|
|
462
|
-
ok: false,
|
|
463
|
-
failureReason: `${failureReason}; repair attempt failed: ${message}`,
|
|
464
|
-
};
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
const repairedFailure = compactSummaryFailureReason(summary);
|
|
468
|
-
if (repairedFailure) {
|
|
469
|
-
return {
|
|
470
|
-
ok: false,
|
|
471
|
-
failureReason: `${failureReason}; repair attempt still invalid: ${repairedFailure}`,
|
|
472
|
-
};
|
|
473
31
|
}
|
|
474
|
-
return { ok: true, summary };
|
|
475
32
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { CONTEXT_INPUT_SAFETY_MARGIN_TOKENS } from "../agent/context-limits.js";
|
|
2
|
+
|
|
3
|
+
export function deriveCompactionThresholds(contextWindow: number) {
|
|
4
|
+
const window = Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : 128000;
|
|
5
|
+
const reserveForOutput = Math.min(8192, Math.max(1024, Math.floor(window * 0.10)));
|
|
6
|
+
return { triggerAt: Math.floor((window - reserveForOutput) * 0.8),
|
|
7
|
+
keepFloorTokens: Math.floor((window - reserveForOutput) * 0.4), reserveForOutput };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface CompactLimits {
|
|
11
|
+
contextWindow?: number;
|
|
12
|
+
inputTokenLimit?: number;
|
|
13
|
+
reservedOutputTokens?: number;
|
|
14
|
+
outputTokenCeiling?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Undefined means legacy SDK mode, never an invented 128K context. */
|
|
18
|
+
export function compactBudget(limits: CompactLimits) {
|
|
19
|
+
const value = limits.contextWindow;
|
|
20
|
+
if (value === undefined || !Number.isFinite(value) || value <= 0) return undefined;
|
|
21
|
+
const window = Math.floor(value);
|
|
22
|
+
const reserved = limits.reservedOutputTokens !== undefined && Number.isFinite(limits.reservedOutputTokens)
|
|
23
|
+
? Math.max(0, Math.floor(limits.reservedOutputTokens)) : deriveCompactionThresholds(window).reserveForOutput;
|
|
24
|
+
const inputLimit = limits.inputTokenLimit !== undefined && Number.isFinite(limits.inputTokenLimit)
|
|
25
|
+
? Math.max(0, Math.floor(limits.inputTokenLimit)) : Infinity;
|
|
26
|
+
const effectiveInputLimit = Math.max(1, Math.floor(Math.min(window - reserved,
|
|
27
|
+
inputLimit) - CONTEXT_INPUT_SAFETY_MARGIN_TOKENS));
|
|
28
|
+
return { effectiveInputLimit, compactAt: Math.max(1, Math.floor(effectiveInputLimit * 0.8)),
|
|
29
|
+
keepFloorTokens: Math.max(1, Math.floor(effectiveInputLimit * 0.4)), reservedOutputTokens: reserved };
|
|
30
|
+
}
|