@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
163 lines • 7.12 kB
JavaScript
import { estimateTokens, findCutPoint } from "../../../compaction/compaction.js";
import { buildSessionContext } from "../../../session-manager.js";
export const RESUME_SLICE_SCHEMA = "senpi.compaction.resume-slice.v1";
export const RESUME_SLICE_ORIGIN = "resume-admission";
const PREVIEW_ENTRY_ID = "__senpi_resume_slice_preview__";
const MIN_KEEP_TOKENS = 1_024;
const MAX_CARRIED_SUMMARY_CHARS = 8_000;
const TRUNCATION_NOTE = "\n[Earlier checkpoint truncated]";
const CHECKPOINT_MARKER = [
"[Resume recovery checkpoint]",
"The restored conversation was larger than this model's context window, so older context was reduced without any provider request.",
"The complete transcript is still recorded in the session file. Continue from the retained messages and treat omitted details as unknown.",
].join("\n");
export function resumeSliceNotice(plan) {
return `Restored context of ${plan.tokensBefore} tokens exceeded this model's window, so older context was reduced to ${plan.tokensAfter} tokens before the first prompt. The full transcript is preserved in the session file.`;
}
function fixedOverheadTokens(projection) {
return (projection.systemPromptTokens +
projection.activeToolSchemaTokens +
projection.outputReserveTokens +
projection.compactionReserveTokens +
projection.speculationLeadTokens +
projection.safetyMarginTokens);
}
function latestCompaction(entries) {
for (let index = entries.length - 1; index >= 0; index--) {
const entry = entries[index];
if (entry?.type === "compaction")
return entry;
}
return undefined;
}
function resolveBoundaryStart(entries) {
const previous = latestCompaction(entries);
if (!previous)
return 0;
const keptIndex = entries.findIndex((entry) => entry.id === previous.firstKeptEntryId);
if (keptIndex >= 0)
return keptIndex;
return entries.indexOf(previous) + 1;
}
function buildSliceSummary(entries) {
const carried = latestCompaction(entries)?.summary?.trim();
if (!carried)
return CHECKPOINT_MARKER;
const bounded = carried.length <= MAX_CARRIED_SUMMARY_CHARS
? carried
: `${carried.slice(0, MAX_CARRIED_SUMMARY_CHARS - TRUNCATION_NOTE.length)}${TRUNCATION_NOTE}`;
return `${CHECKPOINT_MARKER}\n\nEarlier checkpoint:\n${bounded}`;
}
/**
* Live context tokens at `tokenScale` reported tokens per estimated token
* (senpi#3447). A compaction or branch summary is written fresh and its estimate
* is about right, so only the other messages take the reported ratio.
*/
export function chargeContextTokens(messages, tokenScale) {
const { summaryTokens, otherTokens } = contextTokenParts(messages);
return Math.ceil(summaryTokens + otherTokens * tokenScale);
}
export function contextTokenParts(messages) {
let summaryTokens = 0;
let otherTokens = 0;
for (const message of messages) {
const tokens = estimateTokens(message);
if (message.role === "compactionSummary" || message.role === "branchSummary")
summaryTokens += tokens;
else
otherTokens += tokens;
}
return { summaryTokens, otherTokens };
}
function measureSlicedContext(entries, firstKeptEntryId, summary, tokensBefore, tokenScale) {
const preview = {
type: "compaction",
id: PREVIEW_ENTRY_ID,
parentId: entries.at(-1)?.id ?? null,
timestamp: new Date(0).toISOString(),
summary,
firstKeptEntryId,
tokensBefore,
fromHook: false,
};
return chargeContextTokens(buildSessionContext([...entries, preview], PREVIEW_ENTRY_ID).messages, tokenScale);
}
/**
* Choose the smallest deterministic context reduction that lets an over-window
* restored session carry an ordinary request. `findCutPoint` owns boundary
* safety, so a retained tool result always keeps its originating tool call.
*/
export function planResumeSlice({ entries, projection, tokenScale = 1, }) {
const overhead = fixedOverheadTokens(projection);
const keepBudget = projection.contextWindow - overhead;
if (keepBudget < MIN_KEEP_TOKENS)
return undefined;
const toEstimate = (tokens) => Math.floor(tokens / tokenScale);
const entryList = [...entries];
const boundaryStart = resolveBoundaryStart(entryList);
const summary = buildSliceSummary(entryList);
let measuredCutIndex = -1;
const planAt = (firstKeptIndex) => {
const firstKeptEntryId = entryList[firstKeptIndex]?.id;
if (!firstKeptEntryId)
return undefined;
const tokensAfter = measureSlicedContext(entryList, firstKeptEntryId, summary, projection.liveContextTokens, tokenScale);
if (tokensAfter + overhead > projection.contextWindow)
return undefined;
return {
firstKeptEntryId,
summary,
tokensBefore: projection.liveContextTokens,
tokensAfter,
droppedEntries: Math.max(0, firstKeptIndex - boundaryStart),
};
};
const minTarget = Math.max(1, toEstimate(MIN_KEEP_TOKENS));
for (let target = toEstimate(keepBudget); target >= minTarget; target = Math.floor(target / 2)) {
const cut = findCutPoint(entryList, boundaryStart, entryList.length, target);
if (cut.firstKeptEntryIndex === measuredCutIndex)
continue;
measuredCutIndex = cut.firstKeptEntryIndex;
const plan = planAt(cut.firstKeptEntryIndex);
if (plan)
return plan;
}
return planAtEarliestFittingUserTurn(entryList, boundaryStart, planAt);
}
/**
* `findCutPoint` keeps the entry that crosses its budget, so a single oldest turn
* larger than the whole budget is never dropped by the halving above. A cut at a
* user turn is always boundary-safe, and the kept context only shrinks as the cut
* moves later, so the earliest fitting user turn is found by binary search
* (senpi#3447). A cut must keep a completed assistant reply: reducing the
* conversation to only the request that just failed is no repair (#1873).
*/
function planAtEarliestFittingUserTurn(entries, boundaryStart, planAt) {
const lastCompletedReply = entries.findLastIndex((entry) => entry.type === "message" &&
entry.message.role === "assistant" &&
entry.message.stopReason !== "error" &&
entry.message.stopReason !== "aborted");
const userTurns = [];
for (let index = boundaryStart + 1; index < lastCompletedReply; index++) {
const entry = entries[index];
if (entry?.type === "message" && entry.message.role === "user")
userTurns.push(index);
}
let low = 0;
let high = userTurns.length - 1;
let best;
while (low <= high) {
const middle = Math.floor((low + high) / 2);
const index = userTurns[middle];
const plan = index === undefined ? undefined : planAt(index);
if (plan) {
best = plan;
high = middle - 1;
}
else {
low = middle + 1;
}
}
return best;
}
//# sourceMappingURL=resume-slice.js.map