UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

535 lines (534 loc) • 25.3 kB
import { closeSync, existsSync, fstatSync, statSync } from "node:fs"; import { openSync, readFileSync, readdirSync, rmSync, utimesSync } from "./descriptor-seat.js"; import { join, resolve as resolvePath } from "node:path"; import { BaseSessionStorage, storageBuiltWithJudge, StoredSession, SessionError, assertForkTarget, compareOccupants, forkRowCells, forkTargetTaken, frozenRow, getEntriesToFork, importRowCells, incarnationCell, leafIdAfterEntry, ownerCell, placementCellToWrite, readIncarnationCell, readOwnerCell, readPlacementCell, readRowExpectation, recordedOwnerCells, recordedOwnerName, replayLossText, resolveLeafId, rowExpectationMissed, sessionHeadOf, sessionLogMarkOf, heldRowCells, heldRowMatches, readSessionRepoRowCells, uuidv7, validateEntriesForImport, } from "../../internal/harness.js"; import { readUnreadableDeleteId, rowUnreadableNow } from "../../core/session.js"; import { canonicalStoreKey, AppendLog, atomicWriteFile, ensureDir, firstJsonlRecord, lastJsonlRecord, readJsonlRecords, sanitizePathComponent, writeThenLink } from "./fs-atomic.js"; import { guardCorruptSink } from "./corrupt-read-sink.js"; import { assertAdoptionBootGate } from "./adoption/marker.js"; import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js"; import { joinHolderJudge, readHolderJudge } from "../../core/checkpoint-generation.js"; import { thrownText } from "../../core/thrown-value.js"; import { HolderLatch } from "../../core/holder-latch.js"; import { HANDED_SESSION_VIEW } from "./holder-verbs.js"; const SUFFIX = ".jsonl"; const PLACEMENT_READ_FACE = "SessionRepo.placementOf"; export function sessionsDirOf(root) { return join(root, "sessions"); } function sessionPathIn(dir, id) { return join(dir, `${sanitizePathComponent(id)}${SUFFIX}`); } function requireMetaHeader(id, first, skipped = () => "") { if (first === undefined || first.kind !== "meta") { throw new SessionError("corrupt_session", `Session ${id} is unreadable: its log has no meta header${skipped()}`, undefined, "no_header"); } return first; } function atFirstRecordIn(dir, sessionId, read) { let fd; try { fd = openSync(sessionPathIn(dir, sessionId), "r"); } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } try { const { size, mtimeMs } = fstatSync(fd); return read(fd, size, firstJsonlRecord(fd, size, SESSION_LINE_JUDGE), mtimeMs); } finally { closeSync(fd); } } export function readRowPlacement(sessionsDir, sessionId) { const id = readUnreadableDeleteId(PLACEMENT_READ_FACE, sessionId); return atFirstRecordIn(sessionsDir, id, (_fd, _size, first) => readPlacementCell(requireMetaHeader(id, first).placement, id)); } const SESSION_LINE_JUDGE = { accepts: (r) => { const line = r; if (line.kind === "meta") return true; if (line.kind !== "entry" || line.entry === null || typeof line.entry !== "object" || Array.isArray(line.entry)) return false; const entry = line.entry; return typeof entry.id === "string" && (entry.type !== "leaf" || entry.targetId === null || typeof entry.targetId === "string"); }, what: "a session line is neither a meta header nor an entry record with a string id (and, for a leaf, a string or null target)", }; const sharedSessionStorages = new Map(); const sessionStorageFinalizer = new FinalizationRegistry(({ canonical, log }) => { log.close(); if (sharedSessionStorages.get(canonical)?.deref() === undefined) sharedSessionStorages.delete(canonical); }); const LINK_UNSUPPORTED = new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS"]); function linkNewRow(path, content, sessionId, taken) { try { writeThenLink(path, content); } catch (err) { const { code, syscall } = err; if (code === "EEXIST" && syscall === "link") throw taken(); const unsupported = syscall === "link" && typeof code === "string" && LINK_UNSUPPORTED.has(code); throw new SessionError("storage", `session ${sessionId} could not be laid down: ${thrownText(err)} — nothing was written${unsupported ? " (a new row is linked into place whole, never written by a replacing rename, so the sessions directory must be on a file system that can make hard links)" : ""}`, err instanceof Error ? err : undefined); } } function evictSharedSessionStorage(canonical) { const live = sharedSessionStorages.get(canonical)?.deref(); sharedSessionStorages.delete(canonical); if (live !== undefined) { sessionStorageFinalizer.unregister(live); live.closeLog(); } } class FileSessionStorage extends BaseSessionStorage { log; canonicalPath; holders = new Set(); occupant; constructor(log, meta, entries, canonicalPath, replayLoss, holderIsCurrent) { super(meta, entries, undefined, { ...(replayLoss !== undefined ? { replayLoss } : {}), ...(holderIsCurrent !== undefined ? { holderIsCurrent } : {}) }); this.log = log; this.canonicalPath = canonicalPath; this.occupant = { incarnation: meta.incarnation }; } getResidence() { return Object.freeze(storageBuiltWithJudge(this) ? { durability: "durable", fence: Object.freeze({ holder: "writes" }) } : { durability: "durable" }); } addHolder(holder) { this.holders.add(holder); } removeHolder(holder) { this.holders.delete(holder); return this.holders.size === 0; } closeLog() { this.log.close(); } adoptRecordedRow(log, metadata) { const previous = this.log; this.log = log; previous.close(); this.adoptRecordedOwner(metadata); } isViewOf(row) { return compareOccupants(this.occupant, row) === "same" && this.log.isFileAtPath(); } persistSync(entry) { this.log.append({ kind: "entry", entry }, true); } async appendEntry(entry, opts) { this.assertExpectedLeaf(opts, "appendEntry"); this.persistSync(entry); this.recordEntry(entry); } async setLeafId(leafId, opts) { this.assertExpectedLeaf(opts, "setLeafId"); const entry = this.createLeafEntry(leafId); this.persistSync(entry); this.recordEntry(entry); } } void HANDED_SESSION_VIEW; const FILE_SESSION_REPO_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, rowCells: 0, holderIsCurrent: 0 }); const authorityJudges = new WeakMap(); export class FileSessionRepo { dir; tmpDir; onCorruptRead; joined = new Map(); latch = new HolderLatch(this); views = new WeakMap(); rowCells; holderIsCurrent; transcriptDirectory; constructor(root, options) { const opts = receiveOptions(options, "FileSessionRepo", FILE_SESSION_REPO_OPTION_KEYS); this.rowCells = readSessionRepoRowCells("FileSessionRepo options", opts.rowCells); this.holderIsCurrent = readHolderJudge("FileSessionRepo.holderIsCurrent", opts.holderIsCurrent); if (this.holderIsCurrent !== undefined) this.fence = Object.freeze({ holder: "writes" }); const at = resolvePath(root); assertAdoptionBootGate(at, "FileSessionRepo"); this.dir = sessionsDirOf(at); this.transcriptDirectory = this.dir; this.tmpDir = join(at, "tmp"); ensureDir(this.dir); ensureDir(this.tmpDir); this.onCorruptRead = guardCorruptSink(opts?.onCorruptRead); } disclose(path, reason, sessionId) { this.onCorruptRead?.({ kind: "file", path, reason, ...(sessionId !== undefined ? { sessionId } : {}) }); } pathFor(id) { return sessionPathIn(this.dir, id); } read(id) { const path = this.pathFor(id); if (!existsSync(path)) { throw new SessionError("not_found", `Session not found: ${id}`); } let tally; const lines = readJsonlRecords(path, (info) => { if (info.kind === "replay") tally = info; this.onCorruptRead?.({ ...info, sessionId: id }); }, SESSION_LINE_JUDGE); const loss = tally !== undefined ? { dropped: tally.dropped, total: tally.total } : undefined; const meta = this.headerOf(id, path, lines[0], () => ` (${replayLossText(loss ?? { dropped: 0, total: lines.length })})`); const entries = []; for (const line of lines) if (line.kind === "entry") entries.push(line.entry); return { meta, entries, ...(loss !== undefined ? { loss } : {}) }; } headerOf(id, path, first, skipped = () => "") { const head = this.metaLineOf(id, first, skipped); return { ...this.cellsOf(id, path, head), owner: readOwnerCell(head.owner, id) }; } cellsOf(id, path, head) { const said = (key) => (detail) => this.disclose(path, `session header ${key}: ${detail}`, id); const incarnation = readIncarnationCell(head.incarnation, said("incarnation")); const forkedFromIncarnation = readIncarnationCell(head.forkedFromIncarnation, said("forkedFromIncarnation")); return { id, createdAt: head.createdAt, ...(head.forkedFrom !== undefined ? { forkedFrom: head.forkedFrom } : {}), ...(head.placement !== undefined ? { placement: head.placement } : {}), ...(incarnation !== undefined ? { incarnation } : {}), ...(forkedFromIncarnation !== undefined ? { forkedFromIncarnation } : {}), }; } metaLineOf(id, first, skipped = () => "") { const { placement: raw, ...cells } = heldRowCells(this.rowCells, requireMetaHeader(id, first, skipped)); const placement = readPlacementCell(raw, id); return { ...cells, ...(placement !== undefined ? { placement } : {}) }; } async headOf(sessionId) { return this.headNow(sessionId); } headNow(sessionId) { return this.atRow(sessionId, (fd, size, meta) => { const last = lastJsonlRecord(fd, size, (r) => r.kind === "entry", SESSION_LINE_JUDGE); return sessionHeadOf(meta, last === undefined ? null : leafIdAfterEntry(last.entry)); }); } async readRow(sessionId) { return this.rowNow(sessionId); } rowNow(sessionId) { let read; try { read = this.read(sessionId); } catch (err) { if (err instanceof SessionError && err.code === "not_found") return undefined; throw err; } const { meta, entries } = read; return { metadata: meta, head: sessionHeadOf(meta, resolveLeafId(entries)), entries }; } rowOf(sessionId) { const path = this.pathFor(sessionId); return this.atFirstRecord(sessionId, (_fd, _size, first, mtimeMs) => { const head = this.metaLineOf(sessionId, first); const cells = this.cellsOf(sessionId, path, head); const lastActiveAt = Math.trunc(mtimeMs); let owner; try { owner = readOwnerCell(head.owner, sessionId); } catch (err) { if (head.placement === undefined || !(err instanceof SessionError)) throw err; return { id: sessionId, placement: head.placement, lastActiveAt, ownerFault: thrownText(err) }; } return { ...cells, owner, lastActiveAt }; }); } atRow(sessionId, read) { const path = this.pathFor(sessionId); return this.atFirstRecord(sessionId, (fd, size, first, mtimeMs) => read(fd, size, this.headerOf(sessionId, path, first), mtimeMs)); } atFirstRecord(sessionId, read) { return atFirstRecordIn(this.dir, sessionId, read); } refuseRowAfterDispose(id) { if (!this.latch.closed) return; throw Object.assign(new Error(`session ${id}: this session repo was disposed, so it neither hands out nor changes a row — the views it held were released with it; open the data root again to go on`), { code: "log_closed" }); } assertJudgeJoins(id) { const live = sharedSessionStorages.get(canonicalStoreKey(this.pathFor(id)))?.deref(); if (live !== undefined) joinHolderJudge(authorityJudges, live, this.holderIsCurrent, "session", `FileSessionRepo: session ${id}`); } handedOut(storage, id) { return new StoredSession(this.viewOf(storage, id)); } viewOf(storage, id) { const known = this.views.get(storage); if (known !== undefined) return known; const latch = this.latch; const view = Object.create(null); for (const [name, kind] of Object.entries(HANDED_SESSION_VIEW)) { const member = Reflect.get(storage, name); if (typeof member === "function") { const call = (args) => Reflect.apply(member, storage, args); view[name] = kind === "read" ? (...args) => call(args) : kind === "view" ? (...args) => !latch.closed && call(args) : (...args) => latch.closed ? Promise.reject(Object.assign(new Error(`session ${id}: ${name}: this log was closed for the repo that handed the session out (it, or the backend that built it, was disposed) — refusing to write; open the data root again to go on`), { code: "log_closed" })) : call(args); } } this.views.set(storage, view); return view; } storage(meta, entries, loss) { const { id } = meta; const canonical = canonicalStoreKey(this.pathFor(id)); const live = sharedSessionStorages.get(canonical)?.deref(); this.assertJudgeJoins(id); if (live !== undefined && live.isViewOf(meta)) { live.addHolder(this); this.joined.set(canonical, new WeakRef(live)); return live; } if (live !== undefined) evictSharedSessionStorage(canonical); const log = new AppendLog(this.pathFor(id)); const created = new FileSessionStorage(log, frozenRow({ ...meta, ...(meta.placement !== undefined ? { placement: { ...meta.placement } } : {}) }), entries, canonical, loss, this.holderIsCurrent); joinHolderJudge(authorityJudges, created, this.holderIsCurrent, "session", `FileSessionRepo: session ${id}`); sharedSessionStorages.set(canonical, new WeakRef(created)); created.addHolder(this); this.joined.set(canonical, new WeakRef(created)); sessionStorageFinalizer.register(created, { canonical, log }, created); return created; } async dispose() { this.latch.close(); for (const [canonical, ref] of this.joined) { const mine = ref.deref(); if (mine === undefined) continue; if (sharedSessionStorages.get(canonical)?.deref() !== mine) continue; if (mine.removeHolder(this)) evictSharedSessionStorage(canonical); } this.joined.clear(); } async create(options = {}) { this.latch.refuse("FileSessionRepo.create"); const id = options.id ?? uuidv7(); const createdAt = new Date().toISOString(); const path = this.pathFor(id); if (!existsSync(path)) { const owner = ownerCell(options.owner ?? null); const placement = placementCellToWrite(options.placement, id, Date.now()); const meta = heldRowCells(this.rowCells, { id, createdAt, ...(placement !== undefined ? { placement } : {}), ...incarnationCell(undefined), ...owner }); this.assertJudgeJoins(id); linkNewRow(path, `${JSON.stringify({ kind: "meta", ...meta })}\n`, id, () => new SessionError("conflict", `session ${id} was created by another writer between this create's existence check and its write — refusing to replace or attach to that row`)); return this.handedOut(this.storage(meta, []), id); } const { meta, entries, loss } = this.read(id); return this.handedOut(this.storage({ ...meta, createdAt: meta.createdAt || createdAt }, entries, loss), id); } async open(metadata) { const { meta, entries, loss } = this.read(metadata.id); this.refuseRowAfterDispose(metadata.id); return this.handedOut(this.storage(meta, entries, loss), metadata.id); } async touch(sessionId) { this.latch.refuse("FileSessionRepo.touch"); const now = new Date(); try { utimesSync(this.pathFor(sessionId), now, now); } catch (err) { if (err.code === "ENOENT") return; if (typeof sessionId !== "string") throw err; throw new SessionError("storage", `session ${sessionId}'s activity could not be recorded: ${thrownText(err)}`, err instanceof Error ? err : undefined); } } async list() { return this.rows("the listing") .filter((row) => row.placement === undefined) .sort((a, b) => a.createdAt.localeCompare(b.createdAt)); } rows(listing) { let names; try { names = readdirSync(this.dir); } catch (err) { if (err.code !== "ENOENT") { this.disclose(this.dir, `session directory unreadable (${err.code ?? "unknown"}) — ${listing} degraded to empty`); } return []; } const out = []; for (const name of names) { if (!name.endsWith(SUFFIX)) continue; const id = name.slice(0, -SUFFIX.length); let row; try { row = this.rowOf(id); } catch (err) { this.disclose(this.pathFor(id), `session log unreadable (${thrownText(err)}) — skipped from ${listing}`, id); continue; } if (row === undefined) continue; if ("ownerFault" in row) this.disclose(this.pathFor(id), `session log is a placed row whose owner cell is unreadable (${row.ownerFault}) — the placed listing lists it, the host listing never does`, id); out.push(row); } return out; } async listPlaced(kind, opts) { const now = Date.now(); const out = []; for (const row of this.rows("the placed listing")) { const placement = row.placement; if (placement === undefined || placement.kind !== kind) continue; if (opts?.scope !== undefined && placement.scope !== opts.scope) continue; if (opts?.olderThanMs !== undefined && now - row.lastActiveAt <= opts.olderThanMs) continue; out.push(placement.scope !== undefined && placement.handle !== undefined ? { sessionId: row.id, placedAt: placement.placedAt, scope: placement.scope, handle: placement.handle } : { sessionId: row.id, placedAt: placement.placedAt, tupleIncomplete: true }); } return out; } async placementOf(sessionId) { return readRowPlacement(this.dir, sessionId); } async delete(metadata, expect) { this.latch.refuse("FileSessionRepo.delete"); if (expect !== undefined && !heldRowMatches(this.rowCells, expect, this.headNow(metadata.id), () => sessionLogMarkOf(this.read(metadata.id).entries))) throw rowExpectationMissed(metadata.id, "delete"); this.removeRow(metadata.id); } async deleteUnreadable(sessionId) { this.latch.refuse("FileSessionRepo.deleteUnreadable"); const id = readUnreadableDeleteId("SessionRepo.deleteUnreadable", sessionId); if (!rowUnreadableNow(() => this.headNow(id))) return false; this.removeRow(id); return true; } removeRow(id) { evictSharedSessionStorage(canonicalStoreKey(this.pathFor(id))); try { rmSync(this.pathFor(id), { force: true }); } catch (err) { throw new SessionError("storage", `session ${id} could not be deleted: ${thrownText(err)}`, err instanceof Error ? err : undefined); } } async fork(sourceMetadata, options = {}) { this.latch.refuse("FileSessionRepo.fork"); assertForkTarget(sourceMetadata.id, options.id); const source = await this.open(sourceMetadata); const forked = await getEntriesToFork(source.getStorage(), options); const id = options.id ?? uuidv7(); const createdAt = new Date().toISOString(); const path = this.pathFor(id); const placement = placementCellToWrite(options.placement, id, Date.now()); const meta = heldRowCells(this.rowCells, { id, createdAt, ...(placement !== undefined ? { placement } : {}), ...forkRowCells(await source.getMetadata(), options.owner) }); const lines = [JSON.stringify({ kind: "meta", ...meta })]; for (const entry of forked) { lines.push(JSON.stringify({ kind: "entry", entry })); } this.assertJudgeJoins(id); linkNewRow(path, `${lines.join("\n")}\n`, id, () => forkTargetTaken(id)); return this.handedOut(this.storage(meta, [...forked]), id); } async exportEntries(sessionId) { return this.read(sessionId).entries; } async importEntries(sessionId, owner, entries, options) { this.latch.refuse("FileSessionRepo.importEntries"); const validated = validateEntriesForImport(entries, options); const prior = this.rowNow(sessionId); if (!heldRowMatches(this.rowCells, options?.expect, prior?.metadata, () => sessionLogMarkOf(prior.entries))) throw rowExpectationMissed(sessionId, "import"); const meta = heldRowCells(this.rowCells, importRowCells(sessionId, owner, prior?.metadata, new Date().toISOString())); this.assertJudgeJoins(sessionId); evictSharedSessionStorage(canonicalStoreKey(this.pathFor(sessionId))); const lines = [JSON.stringify({ kind: "meta", ...meta })]; for (const entry of validated) { lines.push(JSON.stringify({ kind: "entry", entry })); } atomicWriteFile(this.tmpDir, this.pathFor(sessionId), `${lines.join("\n")}\n`); return sessionHeadOf(meta, resolveLeafId(validated)); } async recordOwner(sessionId, owner, expect) { this.latch.refuse("FileSessionRepo.recordOwner"); const name = recordedOwnerName(owner); const prior = this.rowNow(sessionId); if (prior === undefined) return void readRowExpectation(expect); const claimed = recordedOwnerCells(sessionId, name, prior.metadata, expect, () => heldRowMatches(this.rowCells, expect, prior.metadata, () => sessionLogMarkOf(prior.entries))); if (claimed === undefined) return prior.head; this.assertJudgeJoins(sessionId); const meta = heldRowCells(this.rowCells, claimed); const path = this.pathFor(sessionId); const canonical = canonicalStoreKey(path); const live = sharedSessionStorages.get(canonical)?.deref(); const keep = live !== undefined && live.isViewOf(prior.metadata) ? live : undefined; if (live !== undefined && keep === undefined) evictSharedSessionStorage(canonical); const held = readFileSync(path); const headerEnd = held.indexOf(0x0a); const header = (() => { try { return JSON.parse((headerEnd < 0 ? held : held.subarray(0, headerEnd)).toString("utf8")); } catch { return undefined; } })(); if (header?.kind !== "meta") throw new SessionError("storage", `session ${sessionId}'s log does not open with its header line — its owner is not recorded`); const body = headerEnd < 0 ? Buffer.alloc(0) : held.subarray(headerEnd + 1); const { atimeMs, mtimeMs } = statSync(path); atomicWriteFile(this.tmpDir, path, Buffer.concat([Buffer.from(`${JSON.stringify({ kind: "meta", ...meta })}\n`, "utf8"), body])); try { utimesSync(path, atimeMs / 1000, mtimeMs / 1000); } catch { } if (keep !== undefined) { let log; try { log = new AppendLog(path); } catch (err) { evictSharedSessionStorage(canonical); throw new SessionError("storage", `session ${sessionId}'s owner was recorded, but its open sessions could not be bound to the rewritten log: ${thrownText(err)}`, err instanceof Error ? err : undefined); } sessionStorageFinalizer.unregister(keep); keep.adoptRecordedRow(log, frozenRow({ ...meta, ...(meta.placement !== undefined ? { placement: { ...meta.placement } } : {}) })); sessionStorageFinalizer.register(keep, { canonical, log }, keep); } return sessionHeadOf(meta, prior.head.leafId); } }