UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

90 lines (89 loc) • 3.19 kB
import { createHash } from "node:crypto"; import { erasureStatusOf } from "./file-backend.js"; export const INDEX_COPIES_MAX_BYTES = 16 * 1024 * 1024; export const INDEX_COPY_OVERHEAD_BYTES = 256; const COPIES = new Map(); let heldBytes = 0; export function indexCopyDigest(copy) { const planes = Object.entries(copy.planes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); return createHash("sha256").update(JSON.stringify([planes, copy.marked]), "utf8").digest("hex"); } function drop(name) { const held = COPIES.get(name); if (held === undefined) return; COPIES.delete(name); heldBytes -= held.bytes; } export function keepIndexCopy(key, copy, planes) { const digest = indexCopyDigest(copy); const name = `${key}:${digest}`; drop(name); const current = planes.length > 0 && planes.every((p) => { const read = typeof p.storeState === "object" && p.storeState !== null ? READ_UNDER.get(p.storeState) : undefined; return read !== undefined && read[0] === p.memoryDir && read[1] === storeOf(p.memoryDir).drops; }); if (!current) return digest; const stores = planes.map((p) => p.memoryDir); const bytes = INDEX_COPY_OVERHEAD_BYTES + Buffer.byteLength(name, "utf8") + stores.reduce((n, s) => n + Buffer.byteLength(s, "utf8"), 0) + Object.values(copy.planes).reduce((n, text) => n + Buffer.byteLength(text ?? "", "utf8"), 0); if (bytes > INDEX_COPIES_MAX_BYTES) return digest; COPIES.set(name, { copy, stores: [...stores], bytes }); heldBytes += bytes; while (heldBytes > INDEX_COPIES_MAX_BYTES) { const oldest = COPIES.keys().next().value; if (oldest === undefined) break; drop(oldest); } return digest; } export function indexCopyOf(key, digest) { const name = `${key}:${digest}`; const held = COPIES.get(name); if (held === undefined) return undefined; COPIES.delete(name); COPIES.set(name, held); return held.copy; } const STORES = new Map(); const READ_UNDER = new WeakMap(); function storeOf(store) { let s = STORES.get(store); if (s === undefined) STORES.set(store, (s = { erasures: 0, drops: 0 })); return s; } export function dropIndexCopiesOf(store) { storeOf(store).drops += 1; for (const [name, held] of [...COPIES]) if (held.stores.includes(store)) drop(name); } export async function readAdmittedStoreState(store, read) { const at = storeOf(store); const drops = at.drops; const floor = at.erasures; const state = await read(); if (state.erasures < at.erasures) { dropIndexCopiesOf(store); return state.erasures < floor ? "lowered" : "overtaken"; } at.erasures = state.erasures; READ_UNDER.set(state, [store, drops]); return state; } export function indexCopiesAnswered(att, counted) { if (counted) return att; try { const out = { ...att, residuals: { ...att.residuals, carriers: { ...att.residuals.carriers, indexLine: { unverified: true } } } }; out.status = erasureStatusOf(out); return out; } catch { return undefined; } }