@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
481 lines • 24.8 kB
JavaScript
import { stripTurnRetrySuppressionPrefix } from "@earendil-works/pi-ai";
import { estimateTokens } from "../../../compaction/index.js";
import { StreamDurationBudgetError, StreamIdleTimeoutError, SummarizationTotalBudgetError, } from "../../../compaction/stream-watchdog.js";
import { CredentialFailoverError, TURN_RETRY_SUPPRESSION_PREFIX } from "../../../credential-pool/failover.js";
import { filterContextExcludedMessages } from "../../../messages.js";
import { buildSessionContext, getSessionContextEntryId, } from "../../../session-manager.js";
import { markFailedTurnFragments } from "./fallback-failed-turn-normalization.js";
import { withoutOpaqueSignatures } from "./opaque-signatures.js";
import { SummarizationOverflowExhaustedError } from "./overflow-retry.js";
import { resolveEffectiveReserveTokens } from "./policy.js";
import { isSafeBoundedValue } from "./retained-message-projection.js";
import { hasUnsafeRetainedContent } from "./retained-message-safety.js";
import { SummaryGenerationError, SummaryRequestError } from "./speculative.js";
import { capUtf8Bytes } from "./task-intent.js";
// A budget rejection reached a replay-safe, atomic candidate. Invalid cut points
// must not outvote that actionable constraint just because a tool batch is wide.
const REJECTION_REASON_PRIORITY = {
"missing-preparation-boundary": 0,
"context-reconstruction-failed": 1,
"atomic-tool-chain-cut": 2,
"unsafe-retained-content": 3,
"retained-token-budget-exceeded": 4,
};
export class UnsafeRetainedSuffixError extends Error {
constructor(diagnostics) {
super(formatRequiredCompactionFallbackRejection(diagnostics, true));
this.name = "UnsafeRetainedSuffixError";
this.diagnostics = diagnostics;
}
}
export function formatRequiredCompactionFallbackRejection(diagnostics, automaticPaused = false) {
const candidates = diagnostics.candidateRejections ?? [];
const rejectionCounts = new Map();
for (const candidate of candidates) {
rejectionCounts.set(candidate.rejectionReason, (rejectionCounts.get(candidate.rejectionReason) ?? 0) + 1);
}
const reason = [...rejectionCounts].sort((left, right) => REJECTION_REASON_PRIORITY[right[0]] - REJECTION_REASON_PRIORITY[left[0]])[0]?.[0] ??
diagnostics.rejectionReason ??
"context-reconstruction-failed";
const bestCandidate = candidates
.filter((candidate) => candidate.estimatedTokens !== undefined && Number.isFinite(candidate.estimatedTokens))
.reduce((best, candidate) => !best || (candidate.estimatedTokens ?? Infinity) < (best.estimatedTokens ?? Infinity) ? candidate : best, undefined);
const formatCandidate = (candidate) => candidate
? {
...candidate,
firstKeptEntryId: capUtf8Bytes(candidate.firstKeptEntryId, 128),
...(candidate.unsafeEntryId ? { unsafeEntryId: capUtf8Bytes(candidate.unsafeEntryId, 128) } : {}),
...(candidate.unsafeMessageRole
? { unsafeMessageRole: capUtf8Bytes(candidate.unsafeMessageRole, 32) }
: {}),
}
: undefined;
const recovery = {
"retained-token-budget-exceeded": "The retained turn exceeds the usable context. Use set_model to select a larger-context model, then compact (or /model and /compact).",
"atomic-tool-chain-cut": "The retained tool calls and results do not form complete pairs. Finish the pending tool operation, then use compact to retry explicitly.",
"unsafe-retained-content": "The retained message cannot be replayed safely. Inspect the identified entry with get_messages; use compact after correcting the context or selecting a larger-context model.",
"missing-preparation-boundary": "The prepared boundary is absent from the branch. Reload the session and run /compact.",
"context-reconstruction-failed": "The retained context could not be reconstructed. Reload the session and run /compact.",
};
const diagnostic = {
rejectionReason: reason,
contextWindow: diagnostics.contextWindow,
reserveTokens: diagnostics.reserveTokens,
budgetTokens: diagnostics.budgetTokens,
budgetExceeded: diagnostics.budgetExceeded ?? false,
candidatesChecked: diagnostics.candidatesChecked ?? 0,
rejectionCounts: Object.fromEntries(rejectionCounts),
firstCandidate: formatCandidate(candidates[0]),
bestCandidate: formatCandidate(bestCandidate),
candidate: formatCandidate(candidates.find((candidate) => candidate.rejectionReason === reason)),
};
const pause = automaticPaused
? " Automatic compaction is paused for this unchanged transcript and model/settings."
: "";
return `deterministic compaction fallback could not retain a safe suffix\n${JSON.stringify(diagnostic)}\n${recovery[reason]}${pause} The original transcript has not been changed.`;
}
const NON_VISIBLE_USER_TEXT = /[\p{White_Space}\p{Default_Ignorable_Code_Point}]/gu;
function isRecord(value) {
return typeof value === "object" && value !== null;
}
function hasMeaningfulUserText(entry) {
if (entry.type !== "message" || typeof entry.message !== "object" || entry.message === null)
return false;
if (entry.message.role !== "user")
return false;
const content = entry.message.content;
const hasVisibleText = (text) => typeof text === "string" && text.normalize("NFKC").replace(NON_VISIBLE_USER_TEXT, "").length > 0;
if (typeof content === "string")
return hasVisibleText(content);
if (!Array.isArray(content))
return false;
return content.some((block) => isRecord(block) && block.type === "text" && hasVisibleText(block.text));
}
/**
* A provider or credential fault that ended the summary stream with no usable
* summary and no cheaper recovery left.
*
* Credential rotation rethrows EVERY terminal outcome as `CredentialFailoverError`,
* and once any event past `start` reached the caller it prepends the
* `senpi:no-turn-retry:` marker so the session layer never replays a partially
* delivered turn. That marker also disables session retry and model fallback, so
* before #1741 such an error left required compaction with no recovery at all:
* it applied no summary, authorized no fallback, and repeated identically on the
* next prompt because the context stayed above the threshold. Single-key
* providers have no rotation wrapper and surface the same outage as a
* non-transient `SummaryRequestError`, so the authorization keys on the outcome
* ("the summary stream is dead") rather than on the marker alone.
*
* Deliberately NOT authorized: user aborts (they resolve `undefined` upstream),
* policy refusals (reducing context would not make the model comply), missing
* credentials (a configuration fault with an actionable message), and ordinary
* bugs - destructive context reduction must never be a bug's recovery path.
*/
function isTerminalSummarizationProviderFailure(error) {
if (error instanceof CredentialFailoverError)
return true;
if (error instanceof Error && error.message.startsWith(TURN_RETRY_SUPPRESSION_PREFIX))
return true;
return error instanceof SummaryRequestError && !error.transient && !error.refused && error.failureKind === undefined;
}
export function classifyRequiredCompactionFallbackFailure(error) {
if (error instanceof UnsafeRetainedSuffixError)
return "unsafe-retained-content";
if (error instanceof StreamDurationBudgetError ||
error instanceof StreamIdleTimeoutError ||
error instanceof SummarizationTotalBudgetError) {
return "summarization-timeout";
}
if (error instanceof SummaryRequestError && error.transient && error.failureKind === "upstream-stream-truncated") {
return "upstream-stream-truncated";
}
if (error instanceof SummarizationOverflowExhaustedError) {
return "summarization-overflow-exhausted";
}
if (error instanceof SummaryGenerationError && error.kind === "empty-summary") {
return "summarization-empty-summary";
}
if (isTerminalSummarizationProviderFailure(error)) {
return "summarization-provider-failure";
}
return undefined;
}
export { stripTurnRetrySuppressionPrefix };
const FALLBACK_FAILURE_CAUSE = {
"unsafe-retained-content": "no replay-safe retained suffix fits the context",
"summarization-timeout": "the summary stream ran out of its time budget",
"summarization-provider-failure": "the provider ended the summary stream with an error",
"upstream-stream-truncated": "the provider truncated the summary stream",
"summarization-overflow-exhausted": "the summary input stayed over the provider's context limit",
"summarization-empty-summary": "the provider returned no summary text",
};
/**
* What the user is told when a required compaction recovered through the
* deterministic checkpoint. States the outcome plainly and never carries the
* internal retry-suppression marker.
*/
export function formatRequiredCompactionFallbackNotice(failureKind, cause) {
const detail = cause instanceof Error ? stripTurnRetrySuppressionPrefix(cause.message).trim() : "";
return [
`Compaction could not complete a provider summary: ${FALLBACK_FAILURE_CAUSE[failureKind]}.`,
"A deterministic checkpoint was applied and older transcript detail was dropped, so it is safe to continue.",
detail ? `Provider reported: ${capUtf8Bytes(detail, 512)}.` : "",
"Run /compact on a different model for a richer summary.",
]
.filter((part) => part.length > 0)
.join(" ");
}
export function createRequiredCompactionFallback(preparation, contextWindow, failureKind, metadata, branchEntries = [], diagnostics) {
const reserveTokens = resolveEffectiveReserveTokens(contextWindow, preparation.settings);
const budget = contextWindow - reserveTokens;
const preparedBoundaryIndex = branchEntries.findIndex((entry) => entry.id === preparation.firstKeptEntryId);
if (!preparation.firstKeptEntryId || preparedBoundaryIndex === -1) {
if (diagnostics) {
Object.assign(diagnostics, {
rejectionReason: "missing-preparation-boundary",
contextWindow,
reserveTokens,
budgetTokens: budget,
});
}
return undefined;
}
const marker = [
"[Deterministic compaction recovery checkpoint]",
"Generated summarization did not complete, so older context was reduced without another provider request.",
"Continue from the retained messages after this checkpoint. Treat omitted transcript details as unknown.",
].join("\n");
const taskIntent = metadata.taskIntent?.trim();
const fixedText = taskIntent ? `${marker}\n\nTask intent:\n${taskIntent}` : marker;
const maxSummaryBytes = Math.max(1_024, Math.floor(contextWindow * 0.4));
const previousSummary = preparation.previousSummary?.trim();
let summary = metadata.summary ?? fixedText;
if (previousSummary && metadata.summary === undefined) {
const availableBytes = Math.max(0, maxSummaryBytes - Buffer.byteLength(`${fixedText}\n\nPrevious checkpoint:\n`));
const truncationMarker = "\n[Older checkpoint truncated]";
const boundedPrevious = Buffer.byteLength(previousSummary) <= availableBytes
? previousSummary
: `${capUtf8Bytes(previousSummary, Math.max(0, availableBytes - Buffer.byteLength(truncationMarker)))}${truncationMarker}`;
summary = `${fixedText}\n\nPrevious checkpoint:\n${boundedPrevious}`;
}
const baseDetails = {
schema: "senpi.compaction.deterministic-fallback.v1",
origin: "required-compaction-recovery",
failureKind,
retainedMessagePolicy: "omit-unsafe-v1",
...(taskIntent ? { taskIntent } : {}),
};
let candidateCount = 0;
let sawUnsafeRetainedContent = false;
let sawRetainedBudgetExceeded = false;
const checkedEntryIds = new Set();
const syntheticCompaction = {
type: "compaction",
id: "__senpi_deterministic_fallback_preview__",
parentId: branchEntries.at(-1)?.id ?? null,
timestamp: new Date(0).toISOString(),
summary,
firstKeptEntryId: branchEntries[0]?.id ?? preparation.firstKeptEntryId,
tokensBefore: preparation.tokensBefore,
details: { ...baseDetails, retainedSuffix: "prepared" },
fromHook: true,
};
let projectedMessages;
try {
projectedMessages = filterContextExcludedMessages(buildSessionContext([...branchEntries, syntheticCompaction]).messages);
}
catch {
if (diagnostics) {
Object.assign(diagnostics, {
rejectionReason: "context-reconstruction-failed",
contextWindow,
reserveTokens,
budgetTokens: budget,
});
}
return undefined;
}
// Evaluate the candidate the provider would actually receive: `convertToLlm`
// drops failed/aborted assistant turns (and their orphaned tool results) before
// every request, so their dangling toolCall blocks are neither incomplete calls
// nor retained tokens here. Raw session history stays untouched - this mask is
// local to the fallback projection (code-yeongyu/oh-my-openagent#7921).
const droppedByFailedTurnNormalization = markFailedTurnFragments(projectedMessages);
const messageIndexesByEntryId = new Map();
for (const [index, message] of projectedMessages.entries()) {
const entryId = getSessionContextEntryId(message);
if (entryId !== undefined)
messageIndexesByEntryId.set(entryId, index);
}
const summaryIndex = messageIndexesByEntryId.get(syntheticCompaction.id);
const unsafeSuffix = new Array(projectedMessages.length + 1).fill(false);
const unsafeIndexSuffix = new Int32Array(projectedMessages.length + 1).fill(-1);
const tokenSuffix = new Array(projectedMessages.length + 1).fill(0);
const toolCalls = new Map();
const toolResults = new Map();
for (let index = projectedMessages.length - 1; index >= 0; index--) {
const message = projectedMessages[index];
tokenSuffix[index] = tokenSuffix[index + 1];
unsafeIndexSuffix[index] = unsafeIndexSuffix[index + 1];
if (droppedByFailedTurnNormalization[index]) {
unsafeSuffix[index] = unsafeSuffix[index + 1];
continue;
}
let messageUnsafe = false;
let serialized;
try {
messageUnsafe = hasUnsafeRetainedContent([message]);
const bounded = isSafeBoundedValue(message);
messageUnsafe ||= !bounded;
let imageTokens = 0;
if (!messageUnsafe && message.role === "toolResult") {
const content = message.content.map((block) => {
if (block.type !== "image")
return block;
imageTokens += estimateTokens({ ...message, content: [block] });
return { ...block, data: "" };
});
serialized = JSON.stringify({ ...message, content });
}
else {
serialized = bounded ? JSON.stringify(message, withoutOpaqueSignatures) : undefined;
}
// Apply the shared weighted chars/4 estimator to the envelope too.
// Storage bytes are not tokens; opaque text and image costs still count.
tokenSuffix[index] +=
serialized === undefined
? Number.POSITIVE_INFINITY
: Math.max(estimateTokens(message), estimateTokens({ role: "user", content: serialized, timestamp: 0 }) + imageTokens);
}
catch {
messageUnsafe = true;
tokenSuffix[index] = Number.POSITIVE_INFINITY;
}
unsafeSuffix[index] = unsafeSuffix[index + 1] || messageUnsafe;
if (messageUnsafe)
unsafeIndexSuffix[index] = index;
if (typeof message !== "object" || message === null)
continue;
if (message.role === "toolResult" && typeof message.toolCallId === "string") {
const indexes = toolResults.get(message.toolCallId) ?? [];
indexes.push(index);
toolResults.set(message.toolCallId, indexes);
}
else if (message.role === "assistant" && Array.isArray(message.content)) {
for (const block of message.content) {
if (!isRecord(block) || block.type !== "toolCall" || typeof block.id !== "string")
continue;
const call = toolCalls.get(block.id) ?? { indexes: [], newestIncomplete: block.incomplete === true };
call.indexes.push(index);
toolCalls.set(block.id, call);
}
}
}
const invalidToolChainDiff = new Int32Array(projectedMessages.length + 2);
const markInvalidRange = (start, endExclusive) => {
const boundedStart = Math.max(0, start);
const boundedEnd = Math.min(projectedMessages.length + 1, endExclusive);
if (boundedStart >= boundedEnd)
return;
invalidToolChainDiff[boundedStart]++;
invalidToolChainDiff[boundedEnd]--;
};
for (const [id, call] of toolCalls) {
const results = toolResults.get(id) ?? [];
if (results.length === 0) {
markInvalidRange(0, Math.max(call.indexes[0] ?? -1, results[0] ?? -1) + 1);
continue;
}
const callIndex = call.indexes[0];
const resultIndex = results[0];
// Indexes are newest-first. Older duplicate IDs matter only while retained;
// dropping an entire historical pair leaves the newest pair valid.
markInvalidRange(0, Math.max(call.indexes[1] ?? -1, results[1] ?? -1) + 1);
if (call.newestIncomplete || callIndex >= resultIndex) {
markInvalidRange(0, Math.max(callIndex, resultIndex) + 1);
}
else {
markInvalidRange(callIndex + 1, resultIndex + 1);
}
}
for (const [id, results] of toolResults) {
if (toolCalls.has(id))
continue;
markInvalidRange(0, results[0] + 1);
}
const toolChainValidAt = new Array(projectedMessages.length + 1).fill(true);
let invalidToolChainCount = 0;
for (let index = 0; index < toolChainValidAt.length; index++) {
invalidToolChainCount += invalidToolChainDiff[index];
toolChainValidAt[index] = invalidToolChainCount === 0;
}
const projectCandidate = (firstKeptEntryId, retainedSuffix) => {
if (checkedEntryIds.has(firstKeptEntryId))
return undefined;
checkedEntryIds.add(firstKeptEntryId);
candidateCount++;
const details = { ...baseDetails, retainedSuffix };
const reject = (rejectionReason, detail = {}) => {
if (diagnostics) {
if (!diagnostics.rejectionReason ||
REJECTION_REASON_PRIORITY[rejectionReason] > REJECTION_REASON_PRIORITY[diagnostics.rejectionReason]) {
diagnostics.rejectionReason = rejectionReason;
}
diagnostics.contextWindow = contextWindow;
diagnostics.reserveTokens = reserveTokens;
diagnostics.budgetTokens = budget;
diagnostics.candidateRejections ??= [];
diagnostics.candidateRejections.push({ firstKeptEntryId, rejectionReason, ...detail });
}
return undefined;
};
const result = {
summary,
firstKeptEntryId,
tokensBefore: preparation.tokensBefore,
details,
};
const startIndex = messageIndexesByEntryId.get(firstKeptEntryId);
if (startIndex === undefined)
return reject("context-reconstruction-failed");
const retainedStart = Math.min(startIndex, projectedMessages.length);
if (unsafeSuffix[retainedStart]) {
sawUnsafeRetainedContent = true;
const unsafeMessageIndex = unsafeIndexSuffix[retainedStart];
const unsafeMessage = projectedMessages[unsafeMessageIndex];
return reject("unsafe-retained-content", {
unsafeMessageIndex,
unsafeEntryId: getSessionContextEntryId(unsafeMessage),
unsafeMessageRole: unsafeMessage.role,
});
}
if (!toolChainValidAt[retainedStart])
return reject("atomic-tool-chain-cut");
// The hard-limit valve reserves the scaled budget, so accepting against the raw
// configured reserve would admit a context that valve immediately compacts again.
const summaryTokens = summaryIndex === undefined
? Number.POSITIVE_INFINITY
: Math.max(estimateTokens(projectedMessages[summaryIndex]), estimateTokens({
role: "user",
content: JSON.stringify(projectedMessages[summaryIndex]),
timestamp: 0,
}));
const retainedTokens = (tokenSuffix[retainedStart] ?? Number.POSITIVE_INFINITY) + summaryTokens;
if (retainedTokens > budget) {
sawRetainedBudgetExceeded = true;
if (diagnostics)
diagnostics.budgetExceeded = true;
return reject("retained-token-budget-exceeded", { estimatedTokens: retainedTokens });
}
return { ...result, estimatedTokensAfter: retainedTokens };
};
// 1. Try prepared boundary
const prepared = projectCandidate(preparation.firstKeptEntryId, "prepared");
if (prepared) {
if (diagnostics)
diagnostics.candidatesChecked = candidateCount;
return prepared;
}
// 2. If prepared boundary cut an atomic signed chain or was rejected, walk backward
// to the actual chain boundary. The chain length is determined by the session.
for (let index = preparedBoundaryIndex - 1; index >= 0; index--) {
const entry = branchEntries[index];
if (entry.type === "compaction")
break;
// Only consider message turn starts or assistant call starts
const earlier = projectCandidate(entry.id, "earlier-safe-boundary");
if (earlier) {
if (diagnostics)
diagnostics.candidatesChecked = candidateCount;
return earlier;
}
}
// 3. Try latest meaningful user turn
for (let index = branchEntries.length - 1; index > preparedBoundaryIndex; index--) {
const entry = branchEntries[index];
if (!hasMeaningfulUserText(entry))
continue;
const latestUser = projectCandidate(entry.id, "latest-user-turn");
if (latestUser) {
if (diagnostics)
diagnostics.candidatesChecked = candidateCount;
return latestUser;
}
// A steering user message can occur inside a tool chain. Keep that request
// and walk back to its declaring assistant instead of orphaning the result.
for (let earlierIndex = index - 1; earlierIndex > preparedBoundaryIndex; earlierIndex--) {
const earlierEntry = branchEntries[earlierIndex];
if (earlierEntry.type === "compaction")
break;
const earlier = projectCandidate(earlierEntry.id, "earlier-safe-boundary");
if (earlier) {
if (diagnostics)
diagnostics.candidatesChecked = candidateCount;
return earlier;
}
}
break;
}
// A split turn can contain an unsafe or over-budget persisted tool payload
// after the prepared boundary and no later user message. Advance to the
// earliest safe suffix rather than retaining that payload forever. `projectCandidate`
// still rejects orphaned tool results, incomplete call chains, unsafe
// content, and over-budget suffixes.
if (sawUnsafeRetainedContent || sawRetainedBudgetExceeded) {
for (let index = preparedBoundaryIndex + 1; index < branchEntries.length; index++) {
const entry = branchEntries[index];
if (entry.type === "compaction")
continue;
const laterSafe = projectCandidate(entry.id, "later-safe-boundary");
if (laterSafe) {
if (diagnostics)
diagnostics.candidatesChecked = candidateCount;
return laterSafe;
}
}
}
if (diagnostics)
diagnostics.candidatesChecked = candidateCount;
return undefined;
}
//# sourceMappingURL=deterministic-fallback.js.map