@sema-agent/core
Version:
Stateless, task-oriented AI agent core
72 lines (71 loc) • 2.99 kB
JavaScript
import { calculateContextTokens } from "../../internal/harness.js";
import { measureContext, unevaluableWindowOf } from "../auto-compaction.js";
export const CONTEXT_ROOM_SHARE = 0.7;
function parentOf(messages, toolCallId) {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m === undefined || m.role !== "assistant" || !Array.isArray(m.content))
continue;
const calls = m.content.filter((part) => part.type === "toolCall");
if (calls.some((c) => c.id === toolCallId))
return { message: m, key: calls[0].id };
}
return undefined;
}
function billedOf(message) {
const u = message.usage;
if (u === undefined || u.input + (u.cacheRead ?? 0) + (u.cacheWrite ?? 0) <= 0)
return 0;
return calculateContextTokens(u);
}
export function createContextRoomSeat(input) {
let ledger;
return {
async open(toolCallId) {
if (toolCallId === undefined || toolCallId === "")
return undefined;
const messages = await input.messages();
const parent = parentOf(messages, toolCallId);
if (parent === undefined)
return undefined;
const model = input.model();
const overlay = input.contextOverlay();
const overhead = input.overheadTokens();
const measure = measureContext({
messages,
model,
...(overlay !== undefined ? { contextOverlay: overlay } : {}),
settings: input.settings(),
...(overhead !== undefined ? { overheadTokens: overhead } : {}),
});
if (measure.contextUsage === undefined) {
const u = unevaluableWindowOf(measure, model);
if (u !== undefined)
input.onNoWindow?.(u);
return undefined;
}
const compactAt = measure.contextUsage.compactAtTokens;
const held = Math.max(billedOf(parent.message), measure.tokens);
const landed = new Set();
for (const m of messages)
if (m.role === "toolResult")
landed.add(m.toolCallId);
if (ledger === undefined || ledger.key !== parent.key)
ledger = { key: parent.key, claims: new Map() };
const book = ledger;
return {
room() {
let pending = 0;
for (const [id, tokens] of book.claims)
if (!landed.has(id))
pending += tokens;
return Math.max(0, Math.floor((compactAt - (held + pending)) * CONTEXT_ROOM_SHARE));
},
claim(tokens) {
book.claims.set(toolCallId, (book.claims.get(toolCallId) ?? 0) + tokens);
},
charsPerToken: measure.charsPerToken,
};
},
};
}