UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

123 lines (122 loc) • 6.01 kB
import { SessionError } from "../harness/types.js"; import { validateEntriesForImport } from "./import-validate.js"; import { InMemorySessionStorage } from "./memory-storage.js"; import { resolveLeafId } from "./storage-base.js"; import { assertForkTarget, createSessionId, createTimestamp, forkRowCells, forkTargetTaken, frozenRow, getEntriesToFork, headOfSession, importRowCells, incarnationCell, ownerCell, readRowExpectation, recordedOwnerCells, recordedOwnerName, rowExpectationMissed, sessionHeadOf, toSession } from "./repo-utils.js"; import { heldRowCells, heldRowMatches, readSessionRepoRowCells } from "./row-cells.js"; import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js"; import { readHolderJudge } from "../../core/checkpoint-generation.js"; const IN_MEMORY_SESSION_REPO_OPTION_KEYS = optionKeys()({ rowCells: 0, holderIsCurrent: 0 }); export class InMemorySessionRepo { rows = new Map(); touched = new Map(); rowCells; holderIsCurrent; constructor(options) { const opts = receiveOptions(options, "InMemorySessionRepo", IN_MEMORY_SESSION_REPO_OPTION_KEYS); this.rowCells = readSessionRepoRowCells("InMemorySessionRepo options", opts.rowCells); this.holderIsCurrent = readHolderJudge("InMemorySessionRepo.holderIsCurrent", opts.holderIsCurrent); if (this.holderIsCurrent !== undefined) this.fence = Object.freeze({ holder: "writes" }); } async create(options = {}) { if (options.id !== undefined) { const existing = this.rows.get(options.id); if (existing) return existing.session; } const metadata = { id: options.id ?? createSessionId(), createdAt: createTimestamp(), ...incarnationCell(undefined), ...ownerCell(options.owner ?? null), }; return this.lay(metadata, []).session; } async open(metadata) { const row = this.rows.get(metadata.id); if (!row) { throw new SessionError("not_found", `Session not found: ${metadata.id}`); } return row.session; } async headOf(sessionId) { const row = this.rows.get(sessionId); return row === undefined ? undefined : headOfSession(row.session); } async placementOf(sessionId) { return this.rows.get(sessionId)?.metadata.placement; } async readRow(sessionId) { const row = this.rows.get(sessionId); if (row === undefined) return undefined; const entries = await row.storage.getEntries(); return { metadata: row.metadata, head: sessionHeadOf(row.metadata, resolveLeafId(entries)), entries }; } async list() { return [...this.rows.entries()].map(([id, row]) => { const touched = this.touched.get(id); return touched !== undefined ? { ...row.metadata, lastActiveAt: touched } : row.metadata; }); } async touch(sessionId) { if (this.rows.has(sessionId)) this.touched.set(sessionId, Date.now()); } async delete(metadata, expect) { const row = this.rows.get(metadata.id); if (!heldRowMatches(this.rowCells, expect, row?.metadata, () => row.storage.logMarkNow())) throw rowExpectationMissed(metadata.id, "delete"); this.rows.delete(metadata.id); this.touched.delete(metadata.id); } async fork(sourceMetadata, options) { assertForkTarget(sourceMetadata.id, options.id); const source = await this.open(sourceMetadata); const forkedEntries = await getEntriesToFork(source.getStorage(), options); const metadata = { id: options.id ?? createSessionId(), createdAt: createTimestamp(), ...forkRowCells(await source.getMetadata(), options.owner), }; if (this.rows.has(metadata.id)) throw forkTargetTaken(metadata.id); return this.lay(metadata, forkedEntries).session; } async exportEntries(sessionId) { const row = await this.readRow(sessionId); if (row === undefined) throw new SessionError("not_found", `Session not found: ${sessionId}`); return row.entries; } async importEntries(sessionId, owner, entries, options) { ownerCell(owner === undefined ? null : owner); const validated = validateEntriesForImport(entries, options); const prior = this.rows.get(sessionId); if (!heldRowMatches(this.rowCells, options?.expect, prior?.metadata, () => prior.storage.logMarkNow())) throw rowExpectationMissed(sessionId, "import"); const { metadata } = this.lay(importRowCells(sessionId, owner, prior?.metadata, createTimestamp()), validated); return sessionHeadOf(metadata, resolveLeafId(validated)); } async recordOwner(sessionId, owner, expect) { const name = recordedOwnerName(owner); const row = this.rows.get(sessionId); if (row === undefined) return void readRowExpectation(expect); const claimed = recordedOwnerCells(sessionId, name, row.metadata, expect, () => heldRowMatches(this.rowCells, expect, row.metadata, () => row.storage.logMarkNow())); if (claimed === undefined) return sessionHeadOf(row.metadata, row.storage.leafNow()); const metadata = frozenRow(heldRowCells(this.rowCells, claimed)); row.storage.recordOwnerCell(metadata); this.rows.set(sessionId, { ...row, metadata }); return sessionHeadOf(metadata, row.storage.leafNow()); } lay(given, entries) { const metadata = frozenRow(heldRowCells(this.rowCells, given)); const storage = new InMemorySessionStorage({ metadata, entries, ...(this.holderIsCurrent !== undefined ? { holderIsCurrent: this.holderIsCurrent } : {}) }); const row = { session: toSession(storage), storage, metadata }; this.rows.set(metadata.id, row); return row; } }