UNPKG

@code-yeongyu/senpi

Version:

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

364 lines • 20.8 kB
import { hasCredentialHeaders, isContextOverflow, isRetryableAssistantError, isRetryableErrorMessage, retryTransientCall, } from "@earendil-works/pi-ai"; import { DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, prepareCompaction, } from "../../../compaction/index.js"; import { createSummarizationDeadline, StreamDurationBudgetError, StreamIdleTimeoutError, SummarizationTotalBudgetError, summarizationMaxDurationMs, summarizationTotalBudgetMs, } from "../../../compaction/stream-watchdog.js"; import { createWarmAnchorSnapshot, isWarmSummaryAnchorValid, } from "../../../compaction/warm-anchor.js"; import { CredentialFailoverError, TURN_RETRY_SUPPRESSION_PREFIX } from "../../../credential-pool/failover.js"; import { convertToLlm } from "../../../messages.js"; import { pruneToolResults } from "./emergency-prune.js"; import { allowOverflowRetry, boundSummarizationInput, SUMMARIZATION_INPUT_BUDGET_RATIO, SummarizationOverflowExhaustedError, shrinkSummarizationInputForOverflowRetry, } from "./overflow-retry.js"; import { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from "./policy.js"; import { buildPrompt } from "./prompts.js"; import { estimateSummaryRequestTokens, generateSummaryMessage, getSummaryText, hasSummarizationReasoningOverride, isAssistantMessage, } from "./speculative-summary.js"; import { allowSummarizationRetry, DEFAULT_SUMMARIZATION_RETRY_POLICY } from "./summarization-retry.js"; import { extractTaskIntent, resolveInheritedTaskIntent } from "./task-intent.js"; export { createEmergencyPruneLatch, hardLimitEmergencyPrune, truncateContextMessages, } from "./emergency-prune.js"; import { computeStructuralYield } from "./yield.js"; const DEFAULT_CONTEXT_WINDOW = 200_000; // Hysteresis: the emergency prune engages at EMERGENCY_CONTEXT_TARGET_RATIO but only // releases once the context falls below this lower ratio. A single threshold makes a // session parked near the limit alternate between the pruned and un-pruned history on // consecutive requests; because pruning rewrites old tool results, every alternation // invalidates the provider prompt-cache prefix and re-bills the whole conversation. const SUMMARY_SCHEMA = "senpi.compaction.summary.v1"; function approxTokens(text) { return Math.ceil(text.length / 4); } export class SummaryRequestError extends Error { constructor(message, transient, failureKind, refused = false) { super(message); this.name = "SummaryRequestError"; this.transient = transient; this.failureKind = failureKind; this.refused = refused; } } const UPSTREAM_STREAM_TRUNCATED_PATTERN = /(?:^|[^A-Za-z0-9_])upstream_stream_truncated(?:[^A-Za-z0-9_]|$)/; /** * Only failures with no cheaper recovery earn another billed request. * * Every class that `classifyRequiredCompactionFallbackFailure` recognizes * (watchdog timeouts, the compaction-wide total budget, terminal provider and * credential failures, `upstream-stream-truncated`, overflow exhaustion, * empty-summary generation failures) already * has a deterministic zero-LLM recovery, and context overflow is answered by * shrinking the input in the surrounding loop - replaying those would pay for a * summarization the fallback can rebuild for free. The classes checked here are * mirrored from that classifier rather than imported, because * `deterministic-fallback.ts` imports this module. */ export function isRetryableSummaryAttempt(error) { if (error instanceof StreamDurationBudgetError || error instanceof StreamIdleTimeoutError) return false; if (error instanceof SummarizationTotalBudgetError) return false; if (error instanceof SummarizationOverflowExhaustedError) return false; if (error instanceof SummaryGenerationError) return false; // Mirrors the `summarization-provider-failure` class: credential rotation has // already spent every slot it may spend, and the marker means output was // committed, so another billed attempt buys nothing the fallback cannot // rebuild for free. Message text alone must not re-authorize it - the wrapped // provider detail can read as transient (#1741). if (error instanceof CredentialFailoverError) return false; if (error instanceof Error && error.message.startsWith(TURN_RETRY_SUPPRESSION_PREFIX)) return false; if (error instanceof SummaryRequestError) return error.failureKind === undefined && error.transient; if (error instanceof Error) return isRetryableErrorMessage(error.message); return false; } function isRefusalStop(response) { return response.stopDetails?.type === "refusal" || response.stopDetails?.type === "sensitive"; } function summaryRequestFailureKind(response) { if (isRefusalStop(response)) return undefined; return UPSTREAM_STREAM_TRUNCATED_PATTERN.test(response.errorMessage ?? "") ? "upstream-stream-truncated" : undefined; } export class SummaryGenerationError extends Error { constructor(kind, message) { super(message); this.name = "SummaryGenerationError"; this.kind = kind; } } /** * Output budget for one summarization request. Adaptive-thinking models emit * reasoning tokens before the summary text, so the legacy flat 8192 cap could * be consumed entirely by thinking, ending the stream with zero text blocks. * Grant generous headroom, clamped to what the model can actually emit and to * half the context window: providers that enforce input + output <= window * would otherwise reject the request for models advertising contextWindow == * maxTokens (every summarization request also carries conversation input). */ export function getPromptVariant(options) { if (options.reason === "branch") return "branch"; if (options.preparation.previousSummary) return "update"; if (options.preparation.isSplitTurn) return "turn_prefix"; return "default"; } export function createSpeculativeCompactionSnapshot(context, options) { const model = context.model; if (!model) return undefined; const expectedRevision = context.getMessageRevision(); const branchEntries = context.sessionManager.getBranch(); const contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW; const settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS; const thresholdRatio = computeEffectiveThreshold(contextWindow); const preparation = prepareCompaction(branchEntries, { ...settings, keepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio), }); if (!preparation) return undefined; return { ...options, expectedRevision, model, contextWindow, preparation, branchEntries, promptVariant: getPromptVariant({ reason: "extension", preparation }), systemPrompt: context.getSystemPrompt?.(), systemPromptStablePrefix: context.getSystemPromptStablePrefix?.(), }; } /** * Generate a compaction summary for the snapshot. Resolves `undefined` only * when the request was aborted (caller signal or an aborted stream); every * other failure throws — {@link SummaryGenerationError} for diagnosable * generation failures, the raw provider error otherwise. Abort is checked * before and after credential resolution so a cancelled request never * misreports as an auth failure. */ export async function runExtensionCompaction(context, snapshot, signal, onProgress) { if (signal?.aborted) return undefined; // A provider is authenticated for summarization by a resolved key, a credential // request header, or ambient request-time auth. The ambient marker comes from the // same provider resolution normal turns use; an unconfigured keyed provider still // has none of these and is rejected before a request. const authenticated = (resolved) => resolved?.ok === true && Boolean(resolved.apiKey || hasCredentialHeaders(resolved.headers) || resolved.ambient); const session = { sessionId: context.sessionManager.getSessionId() }; let selectedModel = context.getCompactionModel?.() ?? snapshot.model; let auth = await context.modelRegistry?.getApiKeyAndHeaders(selectedModel, session); if (signal?.aborted) return undefined; // A configured summary model whose credentials could not be confirmed earlier (#830) must not // disable compaction: without credentials at request time, summarize on the session model. if (selectedModel !== snapshot.model && !authenticated(auth)) { selectedModel = snapshot.model; auth = await context.modelRegistry?.getApiKeyAndHeaders(selectedModel, session); if (signal?.aborted) return undefined; } const selectedSnapshot = selectedModel === snapshot.model ? snapshot : { ...snapshot, model: selectedModel, contextWindow: selectedModel.contextWindow }; if (!auth?.ok || !authenticated(auth)) { const detail = auth && !auth.ok ? auth.error : `no credentials resolved for provider "${selectedModel.provider}"`; throw new SummaryGenerationError("auth", `summarization credentials unavailable: ${detail}`); } const requestSnapshot = auth.baseUrl ? { ...selectedSnapshot, model: { ...selectedModel, baseUrl: auth.baseUrl } } : selectedSnapshot; const prompt = buildPrompt({ variant: requestSnapshot.promptVariant, previousSummary: requestSnapshot.preparation.previousSummary, taskIntent: resolveInheritedTaskIntent(requestSnapshot.branchEntries ?? []), customInstructions: requestSnapshot.customInstructions, }); const promptTokens = approxTokens(prompt.user); const sourceMessages = [ ...requestSnapshot.preparation.messagesToSummarize, ...requestSnapshot.preparation.turnPrefixMessages, ]; let messages = boundSummarizationInput(pruneToolResults(sourceMessages, requestSnapshot.contextWindow, SUMMARIZATION_INPUT_BUDGET_RATIO), requestSnapshot.contextWindow, promptTokens); // One deadline for the whole compaction. The per-attempt budget scales with the // input and every retry re-arms it, so without this a large session could hold // the turn for attempt-budget x attempts with no bound the user can predict. const deadline = createSummarizationDeadline(summarizationTotalBudgetMs(requestSnapshot.preparation.settings.summarizationMaxDurationMs)); const overflowRetryStartMs = Date.now(); let overflowAttempts = 0; const summarizationToolsOffered = (requestSnapshot.tools?.length ?? 0) > 0; const reasoningOverrideOffered = hasSummarizationReasoningOverride(requestSnapshot.model); let toolUseRetrySpent = false; let reasoningOverrideRetrySpent = false; while (true) { if (signal?.aborted) return undefined; let response; const currentMessages = messages; const retryStartedMs = Date.now(); // Only the routes that block the user's turn retry here. The speculative // warm-up owns its own bounded retry (`idle-retry.ts`) with idle/breaker // guards re-evaluated between attempts, and a failed warm job must stay // inheritable so the next blocking route degrades on it instead of paying // for a second request. const retryEligible = snapshot.origin === "core-route" || snapshot.origin === "blocking"; // The attempt budget and the retry gate share one input-size-scaled number, // so a large session gets both a proportional attempt deadline and room to // retry transient failures without the 120s-era retry budget disqualifying // every slow attempt (#1068). const attemptBudgetMs = summarizationMaxDurationMs(estimateSummaryRequestTokens(requestSnapshot, messages, prompt, sourceMessages), snapshot.preparation.settings.summarizationMaxDurationMs); try { // The provider `error` stop is raised INSIDE the retried producer so a // transient summarization failure spends the shared retry budget. The // surrounding loop keeps overflow shrinking and abort handling, which // must never be answered by replaying the same request. response = await retryTransientCall(async () => { const attempt = await generateSummaryMessage({ context, forbidToolCalls: toolUseRetrySpent, // Re-clamped per attempt, not per loop turn: a retry that starts // near the deadline gets only what is left, and none starts past it. maxDurationMs: deadline.attemptBudgetMs(attemptBudgetMs), messages: currentMessages, onProgress, prompt, signal, snapshot: requestSnapshot, auth: { apiKey: auth.apiKey, headers: auth.headers, extraBody: auth.extraBody, }, ...(reasoningOverrideRetrySpent ? { omitReasoningOptions: true } : {}), }); if (attempt && isAssistantMessage(attempt) && attempt.stopReason === "error" && !isContextOverflow(attempt, requestSnapshot.contextWindow)) { const failureKind = summaryRequestFailureKind(attempt); throw new SummaryRequestError(attempt.errorMessage || "Compaction summary request failed", failureKind !== undefined || isRetryableAssistantError(attempt), failureKind, isRefusalStop(attempt)); } return attempt; }, (error) => retryEligible && deadline.remainingMs() > 0 && allowSummarizationRetry(Date.now() - retryStartedMs, attemptBudgetMs) && isRetryableSummaryAttempt(error), DEFAULT_SUMMARIZATION_RETRY_POLICY, signal); } catch (error) { if (signal?.aborted) return undefined; throw error; } if (!response) return undefined; if (isAssistantMessage(response) && isContextOverflow(response, requestSnapshot.contextWindow)) { overflowAttempts++; const elapsedMs = Date.now() - overflowRetryStartMs; const retryMessages = allowOverflowRetry(overflowAttempts, elapsedMs) ? shrinkSummarizationInputForOverflowRetry(messages, requestSnapshot.contextWindow, promptTokens) : undefined; if (!retryMessages) { throw new SummarizationOverflowExhaustedError(overflowAttempts, elapsedMs); } messages = retryMessages; continue; } if (isAssistantMessage(response) && response.stopReason === "aborted") { // A partial summary from an aborted stream must never be applied. return undefined; } if (isAssistantMessage(response) && response.stopReason === "error") { // Surface the real provider failure instead of silently degrading // into a generic "Compaction cancelled". Preserve the structured // truncation class here so downstream recovery never trusts arbitrary // thrown error text as authorization for destructive context reduction. const failureKind = summaryRequestFailureKind(response); throw new SummaryRequestError(response.errorMessage || "Compaction summary request failed", failureKind !== undefined || isRetryableAssistantError(response), failureKind, isRefusalStop(response)); } const summary = getSummaryText(response); if (!summary) { const stopReason = isAssistantMessage(response) ? response.stopReason : "unknown"; // A summarizer can hijack the forwarded agent tools and answer with a // bare tool call (observed on chatgpt-subscription gpt-5.6-sol, 2026-08-31), // which used to surface as a terminal empty-summary failure. Spend one // retry with tool calling forbidden; the tools stay in the request // because Anthropic rejects tool_use history without the tools param. if (stopReason === "toolUse" && summarizationToolsOffered && !toolUseRetrySpent) { toolUseRetrySpent = true; continue; } // Some OpenAI-completions relays complete with a normal stop but zero // text when the summarization prompt pins an explicit reasoning effort // (GLM-5.3-flash behind a custom relay, 2026-09-17: HTTP 200 carrying // only the role prelude). Spend one retry without the reasoning // override, but only when the first attempt carried one: a model with // no override would just replay the identical prompt. On Anthropic the // override is `thinkingEnabled: false`, so the retry runs with the // provider's default thinking, clamped by the compaction deadline. // Persistent emptiness still throws and the deterministic fallback // owns recovery. if (stopReason === "stop" && reasoningOverrideOffered && !reasoningOverrideRetrySpent) { reasoningOverrideRetrySpent = true; continue; } throw new SummaryGenerationError("empty-summary", `summarization response contained no text (stopReason: ${stopReason})`); } // Informational only: the core rejects an applied compaction that would // still overflow (_wouldCompactionOverflow). Rejecting here based on the // size of the *discarded* input made large sessions uncompactable. const tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary); const parsedSummary = extractTaskIntent(summary); const taskIntent = parsedSummary.taskIntent ?? resolveInheritedTaskIntent(snapshot.branchEntries ?? []); return { summary: parsedSummary.summaryText, firstKeptEntryId: snapshot.preparation.firstKeptEntryId, tokensBefore: snapshot.preparation.tokensBefore, details: { schema: SUMMARY_SCHEMA, promptVariant: snapshot.promptVariant, tokenEstimate, structuralYield: computeStructuralYield({ previousSummary: snapshot.preparation.previousSummary ?? "", messagesToSummarize: snapshot.preparation.messagesToSummarize, turnPrefixMessages: snapshot.preparation.turnPrefixMessages, summary: parsedSummary.summaryText, tokensBefore: snapshot.preparation.tokensBefore, }), ...(snapshot.origin ? { origin: snapshot.origin } : {}), ...(taskIntent ? { taskIntent } : {}), }, }; } } export async function applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction, signal) { const provider = context.model?.provider; if ((provider === "cursor" || provider === "cursor-cli-oauth") && context.isIdle && !context.isIdle()) { return { applied: false, reason: "rejected" }; } if (!snapshot || !compaction) return { applied: false, reason: "unavailable" }; if (snapshot.generation !== getCurrentGeneration()) { return { applied: false, reason: "stale" }; } const revisionUnchanged = snapshot.expectedRevision === context.getMessageRevision(); const warmAnchor = createWarmAnchorSnapshot(snapshot.preparation.firstKeptEntryId, snapshot.branchEntries ?? []); if (!revisionUnchanged && (!warmAnchor || !isWarmSummaryAnchorValid(warmAnchor, context.sessionManager.getBranch()))) { return { applied: false, reason: "stale" }; } return await context.applyCompaction(compaction, { reason: "extension", ...(revisionUnchanged || !warmAnchor ? { expectedRevision: snapshot.expectedRevision } : { expectedWarmAnchor: warmAnchor }), signal, }); } export async function applySpeculativeCompaction(context, snapshot, getCurrentGeneration, generate) { if (!snapshot) return { applied: false, reason: "unavailable" }; const compaction = await generate(); return await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction); } //# sourceMappingURL=speculative.js.map