@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
211 lines • 11.5 kB
JavaScript
import { dropFailedAssistantTurns, sanitizeAnthropicToolPairs as sanitizeAnthropicPayload, } from "@earendil-works/pi-ai";
import { stream } from "@earendil-works/pi-ai/compat";
import { estimateContextTokens, estimateTokens } from "../../../compaction/compaction.js";
import { consumeStreamWithIdleTimeout, DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS, summarizationMaxDurationMs, } from "../../../compaction/stream-watchdog.js";
import { convertToLlm } from "../../../messages.js";
import { getSessionContextEntryId } from "../../../session-manager.js";
import { repairOrphanedToolResults } from "./repair-tool-pairs.js";
import { normalizeSummarizationTurnOrder } from "./summarization-turn-order.js";
const SUMMARY_TOKEN_HEADROOM = 32_768;
const SUMMARY_CONTEXT_WINDOW_RESERVE_RATIO = 0.5;
function summaryMaxTokens(model, contextWindow) {
const headroom = model.maxTokens > 0 ? Math.min(SUMMARY_TOKEN_HEADROOM, model.maxTokens) : SUMMARY_TOKEN_HEADROOM;
if (contextWindow > 0) {
return Math.min(headroom, Math.floor(contextWindow * SUMMARY_CONTEXT_WINDOW_RESERVE_RATIO));
}
return headroom;
}
/**
* Reasoning override for summarization requests. Compaction must be fast: a
* summarization request that inherits the provider's default reasoning mode
* burns its latency (and output budget) on invisible thinking before emitting
* the summary. Disable or minimize reasoning per wire family; adapters ignore
* options their provider does not support. Mirrors how ChatGPT Subscription keeps its
* compaction turn cheap.
*/
function summarizationReasoningOptions(model) {
if (!model.reasoning)
return {};
if (model.api === "anthropic-messages")
return { thinkingEnabled: false };
const reasoningEffort = ["low", "medium", "high"].find((level) => model.thinkingLevelMap?.[level] !== null);
if (!reasoningEffort)
return {};
switch (model.api) {
case "openai-responses":
case "openai-codex-responses":
case "azure-openai-responses":
return { reasoningEffort, reasoningSummary: null };
case "openai-completions":
return { reasoningEffort };
default:
return {};
}
}
/**
* Whether `summarizationReasoningOptions` pins anything for this model. The
* empty-stop retry drops that pin, so it is only worth a request when there is
* one to drop; otherwise the retry would replay the identical prompt.
*/
export function hasSummarizationReasoningOverride(model) {
return Object.keys(summarizationReasoningOptions(model)).length > 0;
}
/**
* Estimated input of the request {@link generateSummaryMessage} sends for `messages`, which sizes its
* wall-clock budget. The request carries the agent's system prompt, its tool schemas and the transcript as
* native messages with their replayed reasoning, so the transcript's own chars/4 estimate sees only part of
* it: on large OpenAI sessions it measured a third of the provider-reported context, which kept the
* size-adaptive budget on its 120s floor. The last provider-reported usage inside the transcript already
* counts that whole prefix (system prompt, tools and opaque reasoning included); what follows it is
* estimated, plus the schemas of tools a later tool result activated (`addedToolNames`), which that usage
* never billed. `sourceMessages` is the transcript before pruning, input bounding or an overflow shrink cut
* it: the usage measured that transcript, so the estimated size of what was cut before it is subtracted.
* Without usage, or when the usage predates the branch's latest compaction or context edit (a message kept
* through an earlier compaction), the request is estimated whole, system prompt and tools included.
*/
export function estimateSummaryRequestTokens(snapshot, messages, prompt, sourceMessages = messages) {
const instruction = { role: "user", content: [{ type: "text", text: prompt.user }], timestamp: 0 };
const request = [...messages, instruction];
const estimate = estimateContextTokens(request);
const usageIndex = estimate.lastUsageIndex;
const usageMessage = usageIndex === null ? undefined : request[usageIndex];
const sourceUsageIndex = usageMessage ? sourceMessages.indexOf(usageMessage) : -1;
if (usageIndex !== null &&
usageMessage &&
sourceUsageIndex >= 0 &&
isUsageCurrent(usageMessage, snapshot.branchEntries)) {
const cutTokens = sumEstimatedTokens(sourceMessages.slice(0, sourceUsageIndex + 1)) -
sumEstimatedTokens(request.slice(0, usageIndex + 1));
return (Math.max(0, estimate.usageTokens - Math.max(0, cutTokens)) +
estimate.trailingTokens +
estimateActivatedToolsTokens(snapshot.tools, request.slice(usageIndex + 1)));
}
const systemPrompt = snapshot.systemPrompt ?? prompt.system;
const tools = snapshot.tools && snapshot.tools.length > 0 ? JSON.stringify(snapshot.tools) : "";
return sumEstimatedTokens(dropFailedAssistantTurns(request)) + Math.ceil((systemPrompt.length + tools.length) / 4);
}
/**
* Usage captured before the branch's latest compaction or context edit measured a context that no longer
* exists (the same provenance rule as the session's pre-prompt estimate). Without branch entries there is
* nothing that could have invalidated it.
*/
function isUsageCurrent(usageMessage, branchEntries) {
if (!branchEntries)
return true;
const usageEntryId = getSessionContextEntryId(usageMessage);
for (let i = branchEntries.length - 1; i >= 0; i--) {
const entry = branchEntries[i];
if (usageEntryId !== undefined && entry.id === usageEntryId)
return true;
if (entry.type === "compaction" || entry.type === "context_edit")
return false;
}
return true;
}
function sumEstimatedTokens(messages) {
return messages.reduce((total, message) => total + estimateTokens(message), 0);
}
/** Schemas of tools first activated by a tool result after the usage (`addedToolNames`), as pi-ai counts them. */
function estimateActivatedToolsTokens(tools, afterUsage) {
const added = new Set(afterUsage.flatMap((message) => (message.role === "toolResult" ? (message.addedToolNames ?? []) : [])));
const activated = added.size > 0 ? (tools ?? []).filter((tool) => added.has(tool.name)) : [];
return activated.length > 0 ? Math.ceil(JSON.stringify(activated).length / 4) : 0;
}
export function getSummaryText(message) {
const content = Array.isArray(message.content)
? message.content
: [{ type: "text", text: message.content }];
return content
.filter((content) => content.type === "text")
.map((content) => content.text)
.join("\n")
.trim();
}
export function isAssistantMessage(message) {
return message.role === "assistant" && "stopReason" in message;
}
/**
* Providers registered through `pi.registerProvider()` (anthropic-subscription, Kiro, any
* extension provider) exist only in Senpi's ModelRuntime, never in compat's builtin
* api-registry, which rejects their api id outright. Dispatch through the runtime
* whenever it is reachable and keep compat for contexts constructed without a registry.
*/
function summarizationStream(context, model, requestContext, options) {
const runtime = context.modelRegistry?.modelRuntime;
const scoped = { ...options, cwd: context.cwd };
return runtime ? runtime.stream(model, requestContext, scoped) : stream(model, requestContext, scoped);
}
export async function generateSummaryMessage(options) {
// Send the conversation as native LLM messages with the summarization
// instruction as a trailing user message, mirroring normal agent traffic.
// A single serialized `<conversation>` text dump of a large session is
// deterministically refused by Anthropic's anti-distillation classifier
// ("reverse engineering or duplicating model outputs"), while the same
// content as native blocks with the agent's system prompt and tools passes.
// Request-local controller: the idle watchdog must be able to tear down a
// stalled summarization request without aborting the caller's own signal.
const requestController = new AbortController();
const onCallerAbort = () => requestController.abort(options.signal?.reason);
if (options.signal) {
if (options.signal.aborted)
onCallerAbort();
else
options.signal.addEventListener("abort", onCallerAbort, { once: true });
}
try {
const requestMessages = [
...options.messages,
{
role: "user",
content: [{ type: "text", text: options.prompt.user }],
timestamp: Date.now(),
},
];
const maxDurationMs = options.maxDurationMs ??
summarizationMaxDurationMs(estimateSummaryRequestTokens(options.snapshot, options.messages, options.prompt));
const providerRequest = await options.context.prepareProviderRequest?.(requestMessages);
const requestContext = {
systemPrompt: options.snapshot.systemPrompt ?? options.prompt.system,
...(options.snapshot.systemPrompt !== undefined && options.snapshot.systemPromptStablePrefix !== undefined
? { systemPromptStablePrefix: options.snapshot.systemPromptStablePrefix }
: {}),
messages: repairOrphanedToolResults(normalizeSummarizationTurnOrder(convertToLlm(providerRequest?.messages ?? requestMessages))),
...(options.snapshot.tools && options.snapshot.tools.length > 0 ? { tools: options.snapshot.tools } : {}),
};
const headers = providerRequest
? await providerRequest.transformHeaders(options.auth.headers ?? {})
: options.auth.headers;
const responseStream = summarizationStream(options.context, options.snapshot.model, requestContext, {
apiKey: options.auth.apiKey,
headers,
extraBody: options.auth.extraBody,
onPayload: async (payload, model) => {
const sanitized = model.api === "anthropic-messages" ? sanitizeAnthropicPayload(payload) : payload;
return providerRequest ? await providerRequest.transformPayload(sanitized) : sanitized;
},
maxTokens: summaryMaxTokens(options.snapshot.model, options.snapshot.contextWindow),
signal: requestController.signal,
...(options.omitReasoningOptions ? {} : summarizationReasoningOptions(options.snapshot.model)),
...(options.forbidToolCalls ? { toolChoice: "none" } : {}),
});
// Settlement rides inside the watchdog: a provider whose iterator ends
// without a terminal event used to park here with every timer cleared.
return await consumeStreamWithIdleTimeout(responseStream, {
idleTimeoutMs: DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,
maxDurationMs,
abort: () => requestController.abort(),
signal: options.signal,
onEvent: (event) => {
if (event.type === "text_delta" && event.delta) {
options.onProgress?.(event.delta);
}
},
settle: async () => await responseStream.result(),
});
}
finally {
if (options.signal)
options.signal.removeEventListener("abort", onCallerAbort);
}
}
//# sourceMappingURL=speculative-summary.js.map