Repository navigation
Expand file tree
/
Copy pathcompaction-execution.ts
More file actions
316 lines (293 loc) · 10.3 KB
/
Copy pathcompaction-execution.ts
File metadata and controls
316 lines (293 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
import { isContextOverflow, type RetryCallbacks, type RetryPolicy } from "@earendil-works/pi-ai";
import type { AssistantMessage, Model, Usage } from "@earendil-works/pi-ai/compat";
import {
allowOverflowRetry,
boundSummarizationInput,
SummarizationOverflowExhaustedError,
shrinkSummarizationInputForOverflowRetry,
} from "../extensions/builtin/compaction/overflow-retry.ts";
import { convertToLlm } from "../messages.ts";
import { combineUsage } from "../usage-totals.ts";
import {
buildSummarizationContext,
type CacheFriendlySummaryOptions,
type CompactionDetails,
type CompactionPreparation,
type CompactionResult,
cacheFriendlyContextFits,
completeSummarization,
createSummarizationOptions,
generateSummaryWithUsage,
getSummarizationFailure,
type SummarizationStreamFn,
} from "./compaction.ts";
import {
computeFileLists,
contentTextForSummary,
formatFileOperations,
SUMMARIZATION_SYSTEM_PROMPT,
serializeConversation,
} from "./utils.ts";
const TURN_PREFIX_SUMMARIZATION_PROMPT = `The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
## Original Request
[What did the user ask for?]
## Progress So Far
- [Key decisions and work completed in these messages]
## Context Needed to Continue
- [Information from these messages needed to understand the later work]
Only summarize information explicitly present above. Do not infer or recreate later messages.`;
const SOURCE_CONTEXT_TURN_PREFIX_SUMMARIZATION_PROMPT = `The messages above are context from an ongoing conversation whose final turn is still in progress. Later messages of that turn are stored separately and do not need to be reconstructed.
The conversation may also contain complete earlier turns for background. Summarize only the final, incomplete turn. It begins with the last user-role request before this instruction. Do not summarize earlier turns except for details needed to understand the final turn.
Create a concise checkpoint of that request and the progress shown so far. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
## Original Request
[What did the user ask for?]
## Progress So Far
- [Key decisions and work completed in these messages]
## Context Needed to Continue
- [Information from these messages needed to understand the later work]
Only summarize information explicitly present above. Do not infer or recreate later messages.`;
/**
* Generate summaries for compaction using prepared data.
* Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
*
* @param preparation - Pre-calculated preparation from prepareCompaction()
* @param customInstructions - Optional custom focus for the summary
* @param cacheFriendly - Active provider contexts and request settings for cache-friendly summarization
*/
export async function compact(
preparation: CompactionPreparation,
model: Model<any>,
apiKey: string | undefined,
headers?: Record<string, string>,
customInstructions?: string,
signal?: AbortSignal,
extraBody?: Record<string, unknown>,
thinkingLevel?: ThinkingLevel,
streamFn?: StreamFn,
env?: Record<string, string>,
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>,
retry?: RetryPolicy,
callbacks?: RetryCallbacks,
sessionId?: string,
cacheFriendly?: CacheFriendlySummaryOptions,
): Promise<CompactionResult> {
const {
firstKeptEntryId,
messagesToSummarize,
turnPrefixMessages,
isSplitTurn,
tokensBefore,
previousSummary,
fileOps,
settings,
} = preparation;
// Generate summaries and merge into one
let summary: string;
let summaryUsage: Usage;
if (isSplitTurn && turnPrefixMessages.length > 0) {
let historyText = previousSummary ?? "No prior history.";
let historyUsage: Usage | undefined;
if (messagesToSummarize.length > 0) {
const historyResult = await generateSummaryWithUsage(
messagesToSummarize,
model,
settings.reserveTokens,
apiKey,
headers,
signal,
customInstructions,
previousSummary,
extraBody,
thinkingLevel,
streamFn,
env,
transformContext,
retry,
callbacks,
sessionId,
{
sourceContext: cacheFriendly?.sourceContext,
requestOptions: cacheFriendly?.requestOptions,
},
settings.summarizationMaxDurationMs,
);
historyText = historyResult.text;
historyUsage = historyResult.usage;
}
const turnPrefixResult = await generateTurnPrefixSummary(
turnPrefixMessages,
model,
settings.reserveTokens,
apiKey,
headers,
env,
signal,
extraBody,
thinkingLevel,
streamFn,
transformContext,
retry,
callbacks,
sessionId,
{
sourceContext: cacheFriendly?.turnPrefixSourceContext,
requestOptions: cacheFriendly?.requestOptions,
},
settings.summarizationMaxDurationMs,
);
// Merge into single summary
summary = `${historyText}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult.text}`;
summaryUsage = historyUsage ? combineUsage(historyUsage, turnPrefixResult.usage) : turnPrefixResult.usage;
} else {
// Just generate history summary
const result = await generateSummaryWithUsage(
messagesToSummarize,
model,
settings.reserveTokens,
apiKey,
headers,
signal,
customInstructions,
previousSummary,
extraBody,
thinkingLevel,
streamFn,
env,
transformContext,
retry,
callbacks,
sessionId,
{
sourceContext: cacheFriendly?.sourceContext,
requestOptions: cacheFriendly?.requestOptions,
},
settings.summarizationMaxDurationMs,
);
summary = result.text;
summaryUsage = result.usage;
}
// Compute file lists and append to summary
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
summary += formatFileOperations(readFiles, modifiedFiles);
if (!firstKeptEntryId) {
throw new Error("First kept entry has no UUID - session may need migration");
}
return {
summary,
firstKeptEntryId,
tokensBefore,
usage: summaryUsage,
details: { readFiles, modifiedFiles } satisfies CompactionDetails,
};
}
/**
* Generate a summary for a turn prefix (when splitting a turn).
*/
async function generateTurnPrefixSummary(
messages: AgentMessage[],
model: Model<any>,
reserveTokens: number,
apiKey: string | undefined,
headers?: Record<string, string>,
env?: Record<string, string>,
signal?: AbortSignal,
extraBody?: Record<string, unknown>,
thinkingLevel?: ThinkingLevel,
streamFn?: SummarizationStreamFn,
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>,
retry?: RetryPolicy,
callbacks?: RetryCallbacks,
sessionId?: string,
cacheFriendly?: Pick<CacheFriendlySummaryOptions, "sourceContext" | "requestOptions">,
summarizationMaxDurationMs?: number,
): Promise<{ text: string; usage: Usage }> {
const maxTokens = Math.min(
Math.floor(0.5 * reserveTokens),
model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,
);
let sourceContext = cacheFriendly?.sourceContext;
if (
sourceContext &&
!cacheFriendlyContextFits(
model,
buildSummarizationContext(SOURCE_CONTEXT_TURN_PREFIX_SUMMARIZATION_PROMPT, sourceContext),
maxTokens,
)
) {
sourceContext = undefined;
}
let turnMessages: AgentMessage[] = [];
// The standalone request is bounded to the window with the same rule as the history summary (senpi#4079): a
// turn close to the window by itself must not make its prefix summary overflow it, or the compaction never
// succeeds. Inside the turn the request is kept and its oldest tool steps go first.
const boundsTurn = !sourceContext && model.contextWindow > 0;
const promptTokens = Math.ceil(
`${SUMMARIZATION_SYSTEM_PROMPT}# Conversation\n\n\n# Instructions\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`.length /
4,
);
let summarizedMessages: AgentMessage[] = [];
if (!sourceContext) {
turnMessages = transformContext ? await transformContext(messages, signal) : messages;
summarizedMessages = turnMessages;
const serializedFits =
Math.ceil(serializeConversation(convertToLlm(turnMessages)).length / 4) + promptTokens + maxTokens <=
model.contextWindow;
if (boundsTurn && !serializedFits) {
summarizedMessages = boundSummarizationInput(turnMessages, model.contextWindow, promptTokens);
}
}
const overflowStartedAt = Date.now();
let overflowAttempts = 0;
let response: AssistantMessage;
while (true) {
let promptText: string;
if (sourceContext) {
promptText = SOURCE_CONTEXT_TURN_PREFIX_SUMMARIZATION_PROMPT;
} else {
const conversationText = serializeConversation(convertToLlm(summarizedMessages));
const omitted = turnMessages.length - summarizedMessages.length;
const omittedNote = omitted > 0 ? `<omitted-history messages="${omitted}" />\n` : "";
promptText = `# Conversation\n${omittedNote}${conversationText}\n\n# Instructions\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
}
response = await completeSummarization(
model,
buildSummarizationContext(promptText, sourceContext),
createSummarizationOptions(
model,
maxTokens,
apiKey,
headers,
env,
signal,
thinkingLevel,
extraBody,
sessionId,
sourceContext ? cacheFriendly?.requestOptions : undefined,
sourceContext ? "short" : undefined,
),
streamFn,
retry,
callbacks,
summarizationMaxDurationMs,
);
if (!boundsTurn || !isContextOverflow(response, model.contextWindow)) break;
overflowAttempts += 1;
const elapsedMs = Date.now() - overflowStartedAt;
const shrunk = allowOverflowRetry(overflowAttempts, elapsedMs)
? shrinkSummarizationInputForOverflowRetry(summarizedMessages, model.contextWindow, promptTokens)
: undefined;
if (shrunk === undefined) throw new SummarizationOverflowExhaustedError(overflowAttempts, elapsedMs);
summarizedMessages = shrunk;
}
const failure = getSummarizationFailure(response, "Turn prefix summarization");
if (failure) throw new Error(failure);
if (response.content.some((block) => block.type === "toolCall")) {
throw new Error("Turn prefix summarization attempted to call a tool");
}
return {
text: contentTextForSummary(response.content),
usage: response.usage,
};
}