UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

173 lines (172 loc) • 8.56 kB
import { SessionError, StreamingImportValidator, importRowCells, ownerCell, rowExpectationMissed, sessionLogMarkOf, sessionRowMatches, uuidv7 } from "../internal/harness.js"; import { optionKeys, receiptRefusal, receiveMembers } from "./own-property-receipt.js"; import { readRowExpectationMember } from "./runner/session-verb-doors.js"; import { callerKey } from "./caller-text.js"; import { thrownText } from "./thrown-value.js"; const EXPORT_WORDS = { subject: "SessionLogExportOptions", unit: "member", moment: "at SessionLogTransfer.exportStream" }; const BEGIN_WORDS = { subject: "SessionLogTransfer.beginReplace options", unit: "member", moment: "at SessionLogTransfer.beginReplace" }; const COMMIT_WORDS = { subject: "SessionLogCommit", unit: "member", moment: "at SessionLogReplace.commit" }; const EXPORT_KEYS = optionKeys()({ afterSeq: 0, batchSize: 0 }); const BEGIN_KEYS = optionKeys()({ preserveActorAssertions: 0 }); const COMMIT_KEYS = optionKeys()({ owner: 0, decide: 0, expect: 0 }); async function logOrNull(seat, sessionId) { return (await seat.readRow(sessionId))?.entries ?? null; } function committedHead(sessionId, answer) { if (typeof answer === "object" && answer !== null) { const { owner, incarnation, leafId } = answer; if ((owner === null || typeof owner === "string") && (incarnation === undefined || typeof incarnation === "string") && (leafId === null || typeof leafId === "string")) return { owner, incarnation, leafId }; } throw new SessionError("storage", `the repo's importEntries wrote session ${sessionId}'s log but answered no head (got ${answer === null ? "null" : typeof answer}) — a repo behind SessionStore.logTransfer answers the head its write committed; read the row again`); } function readRecord(raw, words, keys) { if (typeof raw !== "object" || raw === null) throw receiptRefusal(`${words.subject} must be an object, got ${raw === null ? "null" : typeof raw}`); return receiveMembers(raw, words, keys, (_, [stray]) => receiptRefusal(`${words.subject} carries ${callerKey(stray)} — not a member this face reads (its members are ${keys.map((k) => JSON.stringify(k)).join(", ")})`)); } function isIntegerFrom(value, floor) { return typeof value === "number" && Number.isSafeInteger(value) && value >= floor; } function readExportOptions(raw) { if (raw === undefined) return { afterSeq: -1 }; const got = readRecord(raw, EXPORT_WORDS, EXPORT_KEYS); const afterSeq = got["afterSeq"]; if (afterSeq !== undefined && !isIntegerFrom(afterSeq, -1)) throw receiptRefusal("SessionLogExportOptions.afterSeq must be an integer ≥ -1 when present"); if (got["batchSize"] !== undefined && !isIntegerFrom(got["batchSize"], 1)) throw receiptRefusal("SessionLogExportOptions.batchSize must be an integer ≥ 1 when present"); return { afterSeq: isIntegerFrom(afterSeq, -1) ? afterSeq : -1 }; } function readBeginOptions(raw) { if (raw === undefined) return {}; const preserveActorAssertions = readRecord(raw, BEGIN_WORDS, BEGIN_KEYS)["preserveActorAssertions"]; if (preserveActorAssertions === undefined) return {}; if (typeof preserveActorAssertions !== "boolean") throw receiptRefusal("beginReplace options.preserveActorAssertions must be a boolean when present"); return { preserveActorAssertions }; } function badCommit(what) { throw receiptRefusal(`SessionLogCommit.${what}`); } function readCommit(raw) { const got = readRecord(raw, COMMIT_WORDS, COMMIT_KEYS); const { owner, decide } = got; try { ownerCell(owner); } catch (err) { throw receiptRefusal(`SessionLogCommit.owner: ${thrownText(err)}`); } if (typeof decide !== "function") throw receiptRefusal(`SessionLogCommit.decide must be a function, got ${typeof decide}`); const expect = readRowExpectationMember(Object.hasOwn(got, "expect") ? got["expect"] : undefined, badCommit); return { owner: owner, decide: decide, expect }; } function detachedCopy(entry) { try { return structuredClone(entry); } catch (err) { throw new SessionError("invalid_session", `a staged entry is not plain data: ${thrownText(err)}`); } } function pick(log, ids, side) { const byId = new Map(log.map((e) => [e.id, e])); return ids.map((id) => { const entry = byId.get(id); if (entry === undefined) throw new SessionError("not_found", `the ${side} log holds no entry ${id}`); return entry; }); } export function repoLogTransfer(seat) { return { async listEntryIds(sessionId) { const log = await logOrNull(seat, sessionId); return log === null ? null : log.map((e) => e.id); }, async exportStream(sessionId, opts) { const { afterSeq } = readExportOptions(opts); const log = await logOrNull(seat, sessionId); if (log === null) return null; const tail = log.slice(afterSeq + 1); return (async function* () { yield* tail; })(); }, beginReplace(sessionId, opts) { return stagedReplace(seat, sessionId, readBeginOptions(opts)); }, }; } function stagedReplace(seat, sessionId, gate) { const validator = new StreamingImportValidator(gate); let staged = []; let ended; const refuseEnded = () => { if (ended !== undefined) throw new SessionError("invalid_session", `the staging of session ${sessionId} has ended (${ended}) — it takes nothing more`); }; return { stagingId: `${sessionId}#stg-${uuidv7()}`, async append(entries) { refuseEnded(); try { if (!Array.isArray(entries)) throw receiptRefusal(`SessionLogReplace.append takes an array of entries, got ${entries === null ? "null" : typeof entries}`); for (const entry of entries) { const copy = detachedCopy(entry); validator.step(copy); staged.push(copy); } } catch (err) { ended = "a batch was refused"; staged = []; throw err; } }, async commit(input) { refuseEnded(); ended = "committed"; const entries = staged; staged = []; const { owner, decide, expect: judged } = readCommit(input); validator.finish(); const stagedIds = entries.map((e) => e.id); return seat.holding(sessionId, async () => { const row = await seat.readRow(sessionId); if (row !== undefined) importRowCells(sessionId, owner, row.metadata, row.metadata.createdAt); if (!sessionRowMatches(judged, row?.head, () => sessionLogMarkOf(row?.entries ?? []))) throw rowExpectationMissed(sessionId, "commit"); const current = row === undefined ? null : row.entries; const view = { current: current === null ? null : current.map((e) => e.id), staged: stagedIds, read: async (side, ids) => structuredClone(side === "current" ? pick(current ?? [], ids, "current") : pick(entries, ids, "staged")), }; const verdict = await decide(view); if (verdict !== "replace" && verdict !== "keep") throw receiptRefusal(`SessionLogCommit.decide must answer "replace" or "keep", got ${typeof verdict === "string" ? `"${verdict}"` : typeof verdict}`); if (verdict === "keep") { if (row === undefined) throw new SessionError("invalid_session", `decide answered "keep" for session ${sessionId}, which has no row — there is no log to keep`); return { outcome: "kept", head: row.head }; } const expect = row === undefined ? { row: null } : { row: row.head, log: sessionLogMarkOf(row.entries) }; const answer = await seat.importEntries(sessionId, owner ?? undefined, entries, { ...gate, expect }); return { outcome: "replaced", head: committedHead(sessionId, answer) }; }); }, async abort() { ended ??= "aborted"; staged = []; }, }; }