@sema-agent/core
Version:
Stateless, task-oriented AI agent core
40 lines (39 loc) • 1.91 kB
JavaScript
import { CONTEXT_TRIM_NOTICE, roomShortfallOf } from "../context-guard.js";
import { messageRole } from "../message-utils.js";
import { isPersonsWordsRow } from "../user-row-origin.js";
import { createMessagesOmittedSeat } from "./messages-omitted-seat.js";
function rowKeyOf(row) {
if (row === undefined)
return "";
const own = row;
return messageRole(row) === "compactionSummary" && typeof own.entryId === "string" ? `compactionSummary#${own.entryId}` : `${messageRole(row)}:${String(own.timestamp)}`;
}
export function createTrimStretch(ids) {
const announce = createMessagesOmittedSeat(ids);
let start;
let head;
return {
begin(view) {
const key = rowKeyOf(view[0]);
if (head !== undefined && key !== head) {
start = undefined;
announce(0);
}
head = key;
},
notBefore: () => start,
handedOn(v) {
const chose = v.sentSize !== undefined ? v.framed.reduce((n, m) => n + (m.content === CONTEXT_TRIM_NOTICE ? 0 : v.sentSize(m)), 0) : 0;
const room = v.sizing !== undefined ? roomShortfallOf(chose, v.lineTokens, v.sizing) : undefined;
const short = room !== undefined && (v.omitted > 0 || v.sizing.scale * (v.sizing.fixedTokens + chose) - 1e-6 > v.windowTokens) ? room : undefined;
const kept = new Set(v.kept);
const yours = v.working.filter((m) => !kept.has(m) && isPersonsWordsRow(m) && m.engineMinted !== true).length;
const first = v.working.findIndex((m) => kept.has(m) && !v.held.has(m) && messageRole(m) !== "compactionSummary");
const from = v.omitted > 0 ? (first === -1 ? v.working.length : first) : undefined;
return () => {
start = from;
announce(v.omitted, short, yours, v.compaction);
};
},
};
}