UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

99 lines (98 loc) • 3.52 kB
import { entryRendersIntoContext } from "../../internal/harness.js"; export class SessionReadFileStates { seats = new Map(); restored = new Map(); static CAP = 1024; noteRestored(sessionId, absPaths) { if (absPaths.length === 0) return; const batch = this.restored.get(sessionId) ?? new Set(); for (const p of absPaths) batch.add(p); this.restored.delete(sessionId); this.restored.set(sessionId, batch); while (this.restored.size > SessionReadFileStates.CAP) { const oldest = this.restored.keys().next().value; if (oldest === undefined) break; this.restored.delete(oldest); } } pendingRestored(sessionId) { return [...(this.restored.get(sessionId) ?? [])]; } settleRestored(sessionId, checked) { const batch = this.restored.get(sessionId); if (batch === undefined) return; for (const p of checked) batch.delete(p); if (batch.size === 0) this.restored.delete(sessionId); } get(sessionId) { const seat = this.seats.get(sessionId); if (seat !== undefined) { this.seats.delete(sessionId); this.seats.set(sessionId, seat); } return seat; } adopt(sessionId, state, anchorLeafId, seen) { this.seats.delete(sessionId); this.seats.set(sessionId, { state, anchorLeafId, ...(seen !== undefined ? { seen } : {}) }); while (this.seats.size > SessionReadFileStates.CAP) { const oldest = this.seats.keys().next().value; if (oldest === undefined) break; this.seats.delete(oldest); } } reanchor(sessionId, state, anchorLeafId) { const seat = this.seats.get(sessionId); if (seat !== undefined && seat.state === state) seat.anchorLeafId = anchorLeafId; } } export async function sessionSeatAnchorHolds(getEntry, anchorLeafId, currentLeafId) { if (anchorLeafId === null) return false; let id = currentLeafId; for (let steps = 0; id !== null && steps < 100_000; steps++) { if (id === anchorLeafId) return true; const entry = await getEntry(id); if (entry === null || entry === undefined || entryRendersIntoContext(entry)) return false; id = entry.parentId; } return false; } export async function readSeatLeaf(session) { try { return (await session.getStorage().getLeafId()) ?? null; } catch { return undefined; } } export function sessionLogWhole(session) { try { const storage = session.getStorage(); return (storage.getReplayLoss?.()?.dropped ?? 0) === 0 && (storage.getFloorId?.() ?? null) === null; } catch { return false; } } export async function legReadCarrier(input) { if (input.resuming) return { from: "checkpoint" }; if (input.spec.sessionId === undefined) return { from: "none" }; const row = input.spec.resumeAt === undefined ? input.seats?.get(input.sessionId) : undefined; if (row === undefined) return { from: "transcript" }; const leaf = await input.leaf(); return leaf !== undefined && (await sessionSeatAnchorHolds(input.getEntry, row.anchorLeafId, leaf)) ? { from: "seat", state: row.state, ...(row.seen !== undefined ? { seen: row.seen } : {}) } : { from: "transcript" }; }