UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

169 lines • 10.6 kB
/** * Context compaction for long sessions. * * Pure functions for compaction logic. The session manager handles I/O, * and after compaction the session is reloaded. */ import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core"; import { type RetryCallbacks, type RetryPolicy } from "@earendil-works/pi-ai"; import type { AssistantMessage, Context, Model, SimpleStreamOptions, TranscriptContext, Usage } from "@earendil-works/pi-ai/compat"; import { type SessionEntry, type SessionProjection } from "../session-manager.ts"; import type { CompactionSettings as BaseCompactionSettings } from "./compaction-settings.ts"; export type CompactionSettings = BaseCompactionSettings & { /** Optional "provider/model" override for the compaction summarization model. */ model?: string; }; export { DEFAULT_COMPACTION_SETTINGS } from "./compaction-settings.ts"; import { type FileOperations } from "./utils.ts"; export type SummarizationStreamFn = StreamFn; type SummarizationOptions = SimpleStreamOptions & { readonly env?: Record<string, string>; }; /** Details stored in CompactionEntry.details for file tracking */ export interface CompactionDetails { readFiles: string[]; modifiedFiles: string[]; } /** Result from compact() - SessionManager adds uuid/parentUuid when saving */ export interface CompactionResult<T = unknown> { summary: string; firstKeptEntryId: string; tokensBefore: number; estimatedTokensAfter?: number; /** Usage from the LLM call(s) that generated this summary, if available */ usage?: Usage; /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */ details?: T; } /** Active provider contexts and request settings used to preserve cacheable compaction prefixes. */ export interface CacheFriendlySummaryOptions { /** Exact provider context prefix containing the history to summarize. */ sourceContext?: Context; /** Exact provider context prefix containing a split turn's prefix. */ turnPrefixSourceContext?: Context; /** Provider request settings copied from the active agent request path. */ requestOptions?: Pick<SimpleStreamOptions, "sessionId" | "onPayload" | "onResponse" | "transport" | "thinkingBudgets" | "maxRetryDelayMs">; } /** * Calculate total context tokens from usage. * Prefer request context over cumulative billing; unknown context is estimated from messages. */ export declare function calculateContextTokens(usage: Usage): number; /** * Threshold numerator. Prefer the larger of billed usage and the local * transcript estimate, unless billed usage is implausibly larger than the * estimate (Cursor cacheRead spikes of several million vs ~150k local). */ export declare function resolveThresholdContextTokens(usageTokens: number, estimateTokens: number): number; /** * Find the last valid assistant message usage from session entries. */ export declare function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined; export interface ContextUsageEstimate { tokens: number; usageTokens: number; trailingTokens: number; lastUsageIndex: number | null; } /** * Estimate context tokens from messages, using the last assistant usage when available. * If there are messages after the last usage, estimate their tokens with estimateTokens. */ export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate; /** Estimate projected context without trusting usage captured before a later edit or compaction. */ export declare function estimateProjectedContextTokens(projection: SessionProjection, branchEntries: SessionEntry[]): ContextUsageEstimate; /** * Check if compaction should trigger based on context usage. */ export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean; /** * Estimate token count for a message using chars/4 heuristic. * This is conservative (overestimates tokens). * * Cached per message object (senpi#2525): a message whose JSON is unchanged returns the memoized * value instead of re-scanning every content block. Reuse is validated by the message's JSON text, * never by identity alone, so any in-place change (including the resident store's token/text swaps) * re-estimates. */ export declare function estimateTokens(message: AgentMessage): number; /** * Find the context-visible user-role message that starts the turn containing the given entry index. * Returns -1 if no turn start found before the index. */ export declare function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number; export interface CutPointResult { /** Index of first entry to keep */ firstKeptEntryIndex: number; /** Index of user message that starts the turn being split, or -1 if not splitting */ turnStartIndex: number; /** Whether this cut splits a turn (cut point is not a user message) */ isSplitTurn: boolean; } /** * Find the cut point in session entries that keeps approximately `keepRecentTokens`. * * Algorithm: Walk backwards from newest, accumulating estimated message sizes. * Stop when we've accumulated >= keepRecentTokens. Cut at that point. * * Can cut at user OR assistant messages (never tool results). When cutting at an * assistant message with tool calls, its tool results come after and will be kept. * * Returns CutPointResult with: * - firstKeptEntryIndex: the entry index to start keeping from * - turnStartIndex: if cutting mid-turn, the user message that started that turn * - isSplitTurn: whether we're cutting in the middle of a turn * * Only considers entries between `startIndex` and `endIndex` (exclusive). */ export declare function findCutPoint(entries: SessionEntry[], startIndex: number, endIndex: number, keepRecentTokens: number): CutPointResult; export declare function getSummarizationFailure(response: AssistantMessage, label: string): string | undefined; export declare function createSummarizationOptions(model: Model<any>, maxTokens: number, apiKey: string | undefined, headers: Record<string, string> | undefined, env: Record<string, string> | undefined, signal: AbortSignal | undefined, thinkingLevel: ThinkingLevel | undefined, extraBody?: Record<string, unknown>, sessionId?: string, requestOptions?: CacheFriendlySummaryOptions["requestOptions"], cacheRetention?: SimpleStreamOptions["cacheRetention"]): SummarizationOptions; /** * Shared choke point for every compaction/branch-summary summarization call. Wraps the * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g. * `terminated`, socket close) honor the configured retry policy instead of failing * the whole compaction on the first attempt. Deterministic errors and aborts return * immediately (see {@link retryAssistantCall}). */ export declare function completeSummarization(model: Model<any>, context: TranscriptContext, options: SimpleStreamOptions, streamFn?: SummarizationStreamFn, retry?: RetryPolicy, callbacks?: RetryCallbacks, summarizationMaxDurationMsOverride?: number): Promise<AssistantMessage>; /** * Generate a summary of the conversation using the LLM. * If previousSummary is provided, uses the update prompt to merge. */ export declare function generateSummary(currentMessages: AgentMessage[], model: Model<any>, reserveTokens: number, apiKey: string | undefined, headers?: Record<string, string>, signal?: AbortSignal, customInstructions?: string, previousSummary?: string, 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?: Pick<CacheFriendlySummaryOptions, "sourceContext" | "requestOptions">, summarizationMaxDurationMs?: number): Promise<string>; /** Build a standalone summary request or append its instruction to an existing provider context. */ export declare function buildSummarizationContext(promptText: string, sourceContext?: Context): TranscriptContext; /** Whether the source context leaves room for the requested summary output and provider safety margin. */ export declare function cacheFriendlyContextFits(model: Model<any>, context: TranscriptContext, maxTokens: number): boolean; /** Generate or update a conversation summary and return its provider usage. */ export declare function generateSummaryWithUsage(currentMessages: AgentMessage[], model: Model<any>, reserveTokens: number, apiKey: string | undefined, headers?: Record<string, string>, signal?: AbortSignal, customInstructions?: string, previousSummary?: string, 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?: Pick<CacheFriendlySummaryOptions, "sourceContext" | "requestOptions">, summarizationMaxDurationMs?: number): Promise<{ text: string; usage: Usage; }>; export interface CompactionPreparation { /** UUID of first entry to keep */ firstKeptEntryId: string; /** Messages that will be summarized and discarded */ messagesToSummarize: AgentMessage[]; /** * Active-context prefix for the history summary. * Includes the previous compaction summary before messages retained by that compaction. */ sourceMessages?: AgentMessage[]; /** Messages that will be turned into turn prefix summary (if splitting) */ turnPrefixMessages: AgentMessage[]; /** Active-context prefix through the split-turn prefix, or empty when not splitting. */ turnPrefixSourceMessages?: AgentMessage[]; /** Whether this is a split turn (cut point in middle of turn) */ isSplitTurn: boolean; tokensBefore: number; /** Summary from previous compaction, for iterative update */ previousSummary?: string; /** File operations extracted from messagesToSummarize */ fileOps: FileOperations; /** Compaction settions from settings.jsonl */ settings: CompactionSettings; } export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings, forceProgress?: boolean, allowSummaryOnly?: boolean): CompactionPreparation | undefined; export { compact } from "./compaction-execution.ts"; //# sourceMappingURL=compaction.d.ts.map