@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
156 lines (145 loc) • 9.54 kB
JavaScript
import { isContextOverflow } from "@earendil-works/pi-ai";
import { allowOverflowRetry, boundSummarizationInput, SummarizationOverflowExhaustedError, shrinkSummarizationInputForOverflowRetry, } from "../extensions/builtin/compaction/overflow-retry.js";
import { convertToLlm } from "../messages.js";
import { combineUsage } from "../usage-totals.js";
import { buildSummarizationContext, cacheFriendlyContextFits, completeSummarization, createSummarizationOptions, generateSummaryWithUsage, getSummarizationFailure, } from "./compaction.js";
import { computeFileLists, contentTextForSummary, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
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, model, apiKey, headers, customInstructions, signal, extraBody, thinkingLevel, streamFn, env, transformContext, retry, callbacks, sessionId, cacheFriendly) {
const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, } = preparation;
// Generate summaries and merge into one
let summary;
let summaryUsage;
if (isSplitTurn && turnPrefixMessages.length > 0) {
let historyText = previousSummary ?? "No prior history.";
let historyUsage;
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 },
};
}
/**
* Generate a summary for a turn prefix (when splitting a turn).
*/
async function generateTurnPrefixSummary(messages, model, reserveTokens, apiKey, headers, env, signal, extraBody, thinkingLevel, streamFn, transformContext, retry, callbacks, sessionId, cacheFriendly, summarizationMaxDurationMs) {
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 = [];
// 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 = [];
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;
while (true) {
let promptText;
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,
};
}
//# sourceMappingURL=compaction-execution.js.map