UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

137 lines (136 loc) • 6.58 kB
import { createHash } from "node:crypto"; import { mintSystemReminder } from "../reminder-mint.js"; import { appendAdmittedRow } from "../row-admission.js"; import { thrownText } from "../thrown-value.js"; import { DATE_ANCHOR_CUSTOM_TYPE } from "../leg-close-records.js"; import { flushOwedAnnouncedSnapshot } from "./announce-once-ledger.js"; export { DATE_ANCHOR_CUSTOM_TYPE }; const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; const DIGEST = /^[0-9a-z:]{1,80}$/; const SHA256 = /^[0-9a-f]{64}$/; const MAX_HEAD_BLOCKS = 64; export const MEMORY_TAIL_MAX_CHARS = 1024 * 1024; function normalizeMemoryTail(v) { if (typeof v !== "object" || v === null) return undefined; const { mount, digest } = v; return typeof mount === "string" && DIGEST.test(mount) && typeof digest === "string" && SHA256.test(digest) ? { mount, digest } : undefined; } function normalizeHead(v) { if (typeof v !== "object" || v === null) return undefined; const { blocks, tools } = v; if (typeof tools !== "string" || !DIGEST.test(tools) || typeof blocks !== "object" || blocks === null || Array.isArray(blocks)) return undefined; const entries = Object.entries(blocks); if (entries.length > MAX_HEAD_BLOCKS || !entries.every(([id, d]) => id.length <= 200 && typeof d === "string" && DIGEST.test(d))) return undefined; return { blocks: Object.fromEntries(entries), tools }; } function normalizeAnchor(v) { if (typeof v !== "object" || v === null) return undefined; const { prefixDate, announcedDate, segment, head, memory } = v; if (segment !== null && (typeof segment !== "string" || segment.length > 200)) return undefined; const date = typeof prefixDate === "string" && ISO_DATE.test(prefixDate) && typeof announcedDate === "string" && ISO_DATE.test(announcedDate) ? { prefixDate, announcedDate } : undefined; const headRead = normalizeHead(head); const memoryRead = normalizeMemoryTail(memory); if (date === undefined && headRead === undefined && memoryRead === undefined) return undefined; return { ...(date !== undefined ? { date } : {}), ...(headRead !== undefined ? { head: headRead } : {}), ...(memoryRead !== undefined ? { memory: memoryRead } : {}), segment }; } export function conversationSegmentOf(branch) { for (let i = branch.length - 1; i >= 0; i--) if (branch[i].type === "compaction") return branch[i].id; return null; } export async function restateToldSeat(prepared, seat, told) { if (prepared.batchHaltRef.current !== undefined) return; if (!told.carried) { try { await appendAdmittedRow(prepared.admitRows, prepared.session, { role: "user", content: [{ type: "text", text: mintSystemReminder(told.body, prepared.reminderMark) }], timestamp: Date.now(), engineMinted: true }); } catch (err) { try { prepared.postureFrameRef.report?.(new Error(`${told.what} could not be restated after compaction (the next leg tells the model again): ${thrownText(err)}`)); } catch { } return; } } seat.segment = await prepared.session.getBranch().then(conversationSegmentOf, () => undefined); if (told.carried || seat.segment === undefined) return; told.record(told.value, seat.segment); prepared.frameReceipts.listingSnapshotOwed = true; await flushOwedAnnouncedSnapshot(prepared); } export async function readDateAnchor(session) { let branch; try { branch = await session.getBranch(); } catch { return undefined; } let date; let head; let memory; for (let i = branch.length - 1; i >= 0 && branch[i].type !== "compaction" && (date === undefined || head === undefined || memory === undefined); i--) { const e = branch[i]; if (e.type !== "custom" || e.customType !== DATE_ANCHOR_CUSTOM_TYPE) continue; const entry = normalizeAnchor(e.data); if (entry === undefined) continue; if (date === undefined && entry.date !== undefined) date = entry; if (head === undefined && entry.head !== undefined) head = entry; if (memory === undefined && entry.memory !== undefined) memory = entry; } const segment = conversationSegmentOf(branch); let lastHead; for (let i = branch.length - 1; i >= 0 && lastHead === undefined; i--) { const e = branch[i]; if (e.type === "custom" && e.customType === DATE_ANCHOR_CUSTOM_TYPE) lastHead = normalizeAnchor(e.data)?.head; } return { current: date !== undefined && date.segment === segment ? date.date : undefined, segment, ...(head !== undefined && head.segment === segment ? { head: head.head } : {}), ...(memory !== undefined && memory.segment === segment ? { memory: memory.memory } : {}), ...(lastHead !== undefined ? { lastHead } : {}), }; } export function prefixHeadBlocksOf(blocks) { const out = {}; for (const b of blocks) { const key = out[b.id] === undefined ? b.id : `${b.id}#${Object.keys(out).length}`; out[key] = createHash("sha256").update(b.text, "utf8").digest("hex").slice(0, 16); } return out; } export function headSegmentsChanged(anchored, now) { const before = Object.keys(anchored.blocks); const after = Object.keys(now.blocks); const moved = [...new Set([...before, ...after])].filter((id) => anchored.blocks[id] !== now.blocks[id] || before.indexOf(id) !== after.indexOf(id)).sort(); return anchored.tools === now.tools ? moved : [...moved, "tools"]; } export function owedDateAnchor(session, read, date, head, memory) { if (read === undefined) return undefined; const dateOwed = date !== undefined && read.current?.announcedDate !== date.announcedDate; const headOwed = head !== undefined && (read.head === undefined || headSegmentsChanged(read.head, head).length > 0); if (!dateOwed && !headOwed && memory === undefined) return undefined; const pair = date !== undefined ? { prefixDate: date.legDate, announcedDate: date.announcedDate } : read.current; const data = { ...(pair !== undefined ? pair : {}), segment: read.segment, ...(head !== undefined ? { head } : read.head !== undefined ? { head: read.head } : {}), ...(memory !== undefined ? { memory } : {}) }; return () => session.appendCustomEntry(DATE_ANCHOR_CUSTOM_TYPE, data).then(() => undefined, () => undefined); }